blob: 0336959d3da286d7c574c1fda557c93e07fc575b [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 Storchaka520b7ae2018-02-22 23:33:30 +020084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
93
Antoine Pitrou86a36b52011-11-25 18:56:07 +010094enum {
95 COMPILER_SCOPE_MODULE,
96 COMPILER_SCOPE_CLASS,
97 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040098 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040099 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100 COMPILER_SCOPE_COMPREHENSION,
101};
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103/* The following items change on entry and exit of code blocks.
104 They must be saved and restored when returning to a block.
105*/
106struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400110 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100111 int u_scope_type;
112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 /* The following fields are dicts that map objects to
114 the index of them in co_XXX. The index is used as
115 the argument for opcodes that refer to those collections.
116 */
117 PyObject *u_consts; /* all constants */
118 PyObject *u_names; /* all names */
119 PyObject *u_varnames; /* local variables */
120 PyObject *u_cellvars; /* cell variables */
121 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Victor Stinnerf8e32212013-11-19 23:56:34 +0100125 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100126 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 /* Pointer to the most recently allocated block. By following b_list
129 members, you can reach all early allocated blocks. */
130 basicblock *u_blocks;
131 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int u_nfblocks;
134 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int u_firstlineno; /* the first lineno of the block */
137 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000138 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 int u_lineno_set; /* boolean to indicate whether instr
140 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141};
142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000148
149Note that we don't track recursion levels during compilation - the
150task of detecting and rejecting excessive levels of nesting is
151handled by the symbol analysis pass.
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153*/
154
155struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200156 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 struct symtable *c_st;
158 PyFutureFeatures *c_future; /* pointer to module's __future__ */
159 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Georg Brandl8334fd92010-12-04 10:26:46 +0000161 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 int c_interactive; /* true if in interactive mode */
163 int c_nestlevel;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -0700164 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
165 if this value is different from zero.
166 This can be used to temporarily visit
167 nodes without emitting bytecode to
168 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
INADA Naokic2e16072018-11-26 21:23:22 +0900170 PyObject *c_const_cache; /* Python dict holding all constants,
171 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 struct compiler_unit *u; /* compiler state for current block */
173 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
174 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175};
176
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100177static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static void compiler_free(struct compiler *);
179static basicblock *compiler_new_block(struct compiler *);
180static int compiler_next_instr(struct compiler *, basicblock *);
181static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100182static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200185static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
187
188static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
189static int compiler_visit_stmt(struct compiler *, stmt_ty);
190static int compiler_visit_keyword(struct compiler *, keyword_ty);
191static int compiler_visit_expr(struct compiler *, expr_ty);
192static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700193static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200198static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500200static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400201static int compiler_async_with(struct compiler *, stmt_ty, int);
202static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100203static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400205 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500206static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400207static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000208
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700209static int compiler_sync_comprehension_generator(
210 struct compiler *c,
211 asdl_seq *generators, int gen_index,
212 expr_ty elt, expr_ty val, int type);
213
214static int compiler_async_comprehension_generator(
215 struct compiler *c,
216 asdl_seq *generators, int gen_index,
217 expr_ty elt, expr_ty val, int type);
218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000219static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000220static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400222#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000225_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /* Name mangling: __private becomes _classname__private.
228 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyObject *result;
230 size_t nlen, plen, ipriv;
231 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200233 PyUnicode_READ_CHAR(ident, 0) != '_' ||
234 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 Py_INCREF(ident);
236 return ident;
237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238 nlen = PyUnicode_GET_LENGTH(ident);
239 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 The only time a name with a dot can occur is when
243 we are compiling an import statement that has a
244 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 TODO(jhylton): Decide whether we want to support
247 mangling of the module name, e.g. __M.X.
248 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
250 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
251 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_INCREF(ident);
253 return ident; /* Don't mangle __whatever__ */
254 }
255 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 ipriv = 0;
257 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
258 ipriv++;
259 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 Py_INCREF(ident);
261 return ident; /* Don't mangle if class is just underscores */
262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000264
Antoine Pitrou55bff892013-04-06 21:21:04 +0200265 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
266 PyErr_SetString(PyExc_OverflowError,
267 "private identifier too large to be mangled");
268 return NULL;
269 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
272 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
273 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
274
275 result = PyUnicode_New(1 + nlen + plen, maxchar);
276 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200278 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
279 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200280 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
284 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
285 Py_DECREF(result);
286 return NULL;
287 }
Victor Stinner8f825062012-04-27 13:55:39 +0200288 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200289 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000290}
291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292static int
293compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296
INADA Naokic2e16072018-11-26 21:23:22 +0900297 c->c_const_cache = PyDict_New();
298 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900300 }
301
302 c->c_stack = PyList_New(0);
303 if (!c->c_stack) {
304 Py_CLEAR(c->c_const_cache);
305 return 0;
306 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309}
310
311PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200312PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
313 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 struct compiler c;
316 PyCodeObject *co = NULL;
Miss Islington (bot)92e836c2019-06-12 17:36:03 -0700317 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200319 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (!__doc__) {
322 __doc__ = PyUnicode_InternFromString("__doc__");
323 if (!__doc__)
324 return NULL;
325 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000326 if (!__annotations__) {
327 __annotations__ = PyUnicode_InternFromString("__annotations__");
328 if (!__annotations__)
329 return NULL;
330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (!compiler_init(&c))
332 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200333 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 c.c_filename = filename;
335 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (c.c_future == NULL)
338 goto finally;
339 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 flags = &local_flags;
341 }
342 merged = c.c_future->ff_features | flags->cf_flags;
343 c.c_future->ff_features = merged;
344 flags->cf_flags = merged;
345 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200346 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 c.c_nestlevel = 0;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -0700348 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200350 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900351 goto finally;
352 }
353
Victor Stinner14e461d2013-08-26 22:28:21 +0200354 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (c.c_st == NULL) {
356 if (!PyErr_Occurred())
357 PyErr_SetString(PyExc_SystemError, "no symtable");
358 goto finally;
359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Thomas Wouters1175c432006-02-27 22:49:54 +0000363 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 compiler_free(&c);
365 assert(co || PyErr_Occurred());
366 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367}
368
369PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200370PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
371 int optimize, PyArena *arena)
372{
373 PyObject *filename;
374 PyCodeObject *co;
375 filename = PyUnicode_DecodeFSDefault(filename_str);
376 if (filename == NULL)
377 return NULL;
378 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
379 Py_DECREF(filename);
380 return co;
381
382}
383
384PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385PyNode_Compile(struct _node *n, const char *filename)
386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 PyCodeObject *co = NULL;
388 mod_ty mod;
389 PyArena *arena = PyArena_New();
390 if (!arena)
391 return NULL;
392 mod = PyAST_FromNode(n, NULL, filename, arena);
393 if (mod)
394 co = PyAST_Compile(mod, filename, NULL, arena);
395 PyArena_Free(arena);
396 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000397}
398
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000399static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (c->c_st)
403 PySymtable_Free(c->c_st);
404 if (c->c_future)
405 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200406 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900407 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000409}
410
Guido van Rossum79f25d91997-04-29 20:08:16 +0000411static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_ssize_t i, n;
415 PyObject *v, *k;
416 PyObject *dict = PyDict_New();
417 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 n = PyList_Size(list);
420 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100421 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (!v) {
423 Py_DECREF(dict);
424 return NULL;
425 }
426 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300427 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 Py_DECREF(v);
429 Py_DECREF(dict);
430 return NULL;
431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_DECREF(v);
433 }
434 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435}
436
437/* Return new dict containing names from src that match scope(s).
438
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000439src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000441values are integers, starting at offset and increasing by one for
442each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443*/
444
445static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100446dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700448 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500450 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 assert(offset >= 0);
453 if (dest == NULL)
454 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455
Meador Inge2ca63152012-07-18 14:20:11 -0500456 /* Sort the keys so that we have a deterministic order on the indexes
457 saved in the returned dictionary. These indexes are used as indexes
458 into the free and cell var storage. Therefore if they aren't
459 deterministic, then the generated bytecode is not deterministic.
460 */
461 sorted_keys = PyDict_Keys(src);
462 if (sorted_keys == NULL)
463 return NULL;
464 if (PyList_Sort(sorted_keys) != 0) {
465 Py_DECREF(sorted_keys);
466 return NULL;
467 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500468 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500469
470 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* XXX this should probably be a macro in symtable.h */
472 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500473 k = PyList_GET_ITEM(sorted_keys, key_i);
474 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(PyLong_Check(v));
476 vi = PyLong_AS_LONG(v);
477 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300480 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500482 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_DECREF(dest);
484 return NULL;
485 }
486 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300487 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_DECREF(item);
490 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return NULL;
492 }
493 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 }
Meador Inge2ca63152012-07-18 14:20:11 -0500496 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000498}
499
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500static void
501compiler_unit_check(struct compiler_unit *u)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 basicblock *block;
504 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700505 assert((uintptr_t)block != 0xcbcbcbcbU);
506 assert((uintptr_t)block != 0xfbfbfbfbU);
507 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (block->b_instr != NULL) {
509 assert(block->b_ialloc > 0);
510 assert(block->b_iused > 0);
511 assert(block->b_ialloc >= block->b_iused);
512 }
513 else {
514 assert (block->b_iused == 0);
515 assert (block->b_ialloc == 0);
516 }
517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static void
521compiler_unit_free(struct compiler_unit *u)
522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 compiler_unit_check(u);
526 b = u->u_blocks;
527 while (b != NULL) {
528 if (b->b_instr)
529 PyObject_Free((void *)b->b_instr);
530 next = b->b_list;
531 PyObject_Free((void *)b);
532 b = next;
533 }
534 Py_CLEAR(u->u_ste);
535 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400536 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 Py_CLEAR(u->u_consts);
538 Py_CLEAR(u->u_names);
539 Py_CLEAR(u->u_varnames);
540 Py_CLEAR(u->u_freevars);
541 Py_CLEAR(u->u_cellvars);
542 Py_CLEAR(u->u_private);
543 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544}
545
546static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100547compiler_enter_scope(struct compiler *c, identifier name,
548 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100551 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
554 struct compiler_unit));
555 if (!u) {
556 PyErr_NoMemory();
557 return 0;
558 }
559 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100560 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100562 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 u->u_kwonlyargcount = 0;
564 u->u_ste = PySymtable_Lookup(c->c_st, key);
565 if (!u->u_ste) {
566 compiler_unit_free(u);
567 return 0;
568 }
569 Py_INCREF(name);
570 u->u_name = name;
571 u->u_varnames = list2dict(u->u_ste->ste_varnames);
572 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
573 if (!u->u_varnames || !u->u_cellvars) {
574 compiler_unit_free(u);
575 return 0;
576 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500577 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000578 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 int res;
582 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200583 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 name = _PyUnicode_FromId(&PyId___class__);
585 if (!name) {
586 compiler_unit_free(u);
587 return 0;
588 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300589 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500590 if (res < 0) {
591 compiler_unit_free(u);
592 return 0;
593 }
594 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200597 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (!u->u_freevars) {
599 compiler_unit_free(u);
600 return 0;
601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 u->u_blocks = NULL;
604 u->u_nfblocks = 0;
605 u->u_firstlineno = lineno;
606 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000607 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 u->u_lineno_set = 0;
609 u->u_consts = PyDict_New();
610 if (!u->u_consts) {
611 compiler_unit_free(u);
612 return 0;
613 }
614 u->u_names = PyDict_New();
615 if (!u->u_names) {
616 compiler_unit_free(u);
617 return 0;
618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Push the old compiler_unit on the stack. */
623 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400624 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
626 Py_XDECREF(capsule);
627 compiler_unit_free(u);
628 return 0;
629 }
630 Py_DECREF(capsule);
631 u->u_private = c->u->u_private;
632 Py_XINCREF(u->u_private);
633 }
634 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100637
638 block = compiler_new_block(c);
639 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100641 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400643 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
644 if (!compiler_set_qualname(c))
645 return 0;
646 }
647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000651static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652compiler_exit_scope(struct compiler *c)
653{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100654 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel--;
658 compiler_unit_free(c->u);
659 /* Restore c->u to the parent unit. */
660 n = PyList_GET_SIZE(c->c_stack) - 1;
661 if (n >= 0) {
662 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400663 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 assert(c->u);
665 /* we are deleting from a list so this really shouldn't fail */
666 if (PySequence_DelItem(c->c_stack, n) < 0)
667 Py_FatalError("compiler_exit_scope()");
668 compiler_unit_check(c->u);
669 }
670 else
671 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673}
674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675static int
676compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100678 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679 _Py_static_string(dot_locals, ".<locals>");
680 Py_ssize_t stack_size;
681 struct compiler_unit *u = c->u;
682 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100683
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100685 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400686 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 if (stack_size > 1) {
688 int scope, force_global = 0;
689 struct compiler_unit *parent;
690 PyObject *mangled, *capsule;
691
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400692 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400693 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 assert(parent);
695
Yury Selivanov75445082015-05-11 22:57:16 -0400696 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
697 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
698 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 assert(u->u_name);
700 mangled = _Py_Mangle(parent->u_private, u->u_name);
701 if (!mangled)
702 return 0;
703 scope = PyST_GetScope(parent->u_ste, mangled);
704 Py_DECREF(mangled);
705 assert(scope != GLOBAL_IMPLICIT);
706 if (scope == GLOBAL_EXPLICIT)
707 force_global = 1;
708 }
709
710 if (!force_global) {
711 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400712 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400713 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
714 dot_locals_str = _PyUnicode_FromId(&dot_locals);
715 if (dot_locals_str == NULL)
716 return 0;
717 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
718 if (base == NULL)
719 return 0;
720 }
721 else {
722 Py_INCREF(parent->u_qualname);
723 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400724 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100725 }
726 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400728 if (base != NULL) {
729 dot_str = _PyUnicode_FromId(&dot);
730 if (dot_str == NULL) {
731 Py_DECREF(base);
732 return 0;
733 }
734 name = PyUnicode_Concat(base, dot_str);
735 Py_DECREF(base);
736 if (name == NULL)
737 return 0;
738 PyUnicode_Append(&name, u->u_name);
739 if (name == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(u->u_name);
744 name = u->u_name;
745 }
746 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100747
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400748 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100749}
750
Eric V. Smith235a6f02015-09-19 14:51:32 -0400751
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752/* Allocate a new block and return a pointer to it.
753 Returns NULL on error.
754*/
755
756static basicblock *
757compiler_new_block(struct compiler *c)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 basicblock *b;
760 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 u = c->u;
763 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
764 if (b == NULL) {
765 PyErr_NoMemory();
766 return NULL;
767 }
768 memset((void *)b, 0, sizeof(basicblock));
769 /* Extend the singly linked list of blocks with new block. */
770 b->b_list = u->u_blocks;
771 u->u_blocks = b;
772 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773}
774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776compiler_next_block(struct compiler *c)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 basicblock *block = compiler_new_block(c);
779 if (block == NULL)
780 return NULL;
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786static basicblock *
787compiler_use_next_block(struct compiler *c, basicblock *block)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(block != NULL);
790 c->u->u_curblock->b_next = block;
791 c->u->u_curblock = block;
792 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
795/* Returns the offset of the next instruction in the current block's
796 b_instr array. Resizes the b_instr as necessary.
797 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000798*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799
800static int
801compiler_next_instr(struct compiler *c, basicblock *b)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 assert(b != NULL);
804 if (b->b_instr == NULL) {
805 b->b_instr = (struct instr *)PyObject_Malloc(
806 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
807 if (b->b_instr == NULL) {
808 PyErr_NoMemory();
809 return -1;
810 }
811 b->b_ialloc = DEFAULT_BLOCK_SIZE;
812 memset((char *)b->b_instr, 0,
813 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
814 }
815 else if (b->b_iused == b->b_ialloc) {
816 struct instr *tmp;
817 size_t oldsize, newsize;
818 oldsize = b->b_ialloc * sizeof(struct instr);
819 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000820
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700821 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 PyErr_NoMemory();
823 return -1;
824 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (newsize == 0) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 b->b_ialloc <<= 1;
831 tmp = (struct instr *)PyObject_Realloc(
832 (void *)b->b_instr, newsize);
833 if (tmp == NULL) {
834 PyErr_NoMemory();
835 return -1;
836 }
837 b->b_instr = tmp;
838 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
839 }
840 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841}
842
Christian Heimes2202f872008-02-06 14:31:34 +0000843/* Set the i_lineno member of the instruction at offset off if the
844 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 already been set. If it has been set, the call has no effect.
846
Christian Heimes2202f872008-02-06 14:31:34 +0000847 The line number is reset in the following cases:
848 - when entering a new scope
849 - on each statement
850 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200851 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000852 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000853*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855static void
856compiler_set_lineno(struct compiler *c, int off)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 basicblock *b;
859 if (c->u->u_lineno_set)
860 return;
861 c->u->u_lineno_set = 1;
862 b = c->u->u_curblock;
863 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864}
865
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200866/* Return the stack effect of opcode with argument oparg.
867
868 Some opcodes have different stack effect when jump to the target and
869 when not jump. The 'jump' parameter specifies the case:
870
871 * 0 -- when not jump
872 * 1 -- when jump
873 * -1 -- maximal
874 */
875/* XXX Make the stack effect of WITH_CLEANUP_START and
876 WITH_CLEANUP_FINISH deterministic. */
877static int
878stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300881 case NOP:
882 case EXTENDED_ARG:
883 return 0;
884
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200885 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case POP_TOP:
887 return -1;
888 case ROT_TWO:
889 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200890 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return 0;
892 case DUP_TOP:
893 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000894 case DUP_TOP_TWO:
895 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200897 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case UNARY_POSITIVE:
899 case UNARY_NEGATIVE:
900 case UNARY_NOT:
901 case UNARY_INVERT:
902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case SET_ADD:
905 case LIST_APPEND:
906 return -1;
907 case MAP_ADD:
908 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000909
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200910 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case BINARY_POWER:
912 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400913 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_MODULO:
915 case BINARY_ADD:
916 case BINARY_SUBTRACT:
917 case BINARY_SUBSCR:
918 case BINARY_FLOOR_DIVIDE:
919 case BINARY_TRUE_DIVIDE:
920 return -1;
921 case INPLACE_FLOOR_DIVIDE:
922 case INPLACE_TRUE_DIVIDE:
923 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case INPLACE_ADD:
926 case INPLACE_SUBTRACT:
927 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400928 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case INPLACE_MODULO:
930 return -1;
931 case STORE_SUBSCR:
932 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case DELETE_SUBSCR:
934 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case BINARY_LSHIFT:
937 case BINARY_RSHIFT:
938 case BINARY_AND:
939 case BINARY_XOR:
940 case BINARY_OR:
941 return -1;
942 case INPLACE_POWER:
943 return -1;
944 case GET_ITER:
945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case PRINT_EXPR:
948 return -1;
949 case LOAD_BUILD_CLASS:
950 return 1;
951 case INPLACE_LSHIFT:
952 case INPLACE_RSHIFT:
953 case INPLACE_AND:
954 case INPLACE_XOR:
955 case INPLACE_OR:
956 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200959 /* 1 in the normal flow.
960 * Restore the stack position and push 6 values before jumping to
961 * the handler if an exception be raised. */
962 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400963 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200964 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400965 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200966 /* Pop a variable number of values pushed by WITH_CLEANUP_START
967 * + __exit__ or __aexit__. */
968 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case RETURN_VALUE:
970 return -1;
971 case IMPORT_STAR:
972 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700973 case SETUP_ANNOTATIONS:
974 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case YIELD_VALUE:
976 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500977 case YIELD_FROM:
978 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case POP_BLOCK:
980 return 0;
981 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200982 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200984 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200985 /* Pop 6 values when an exception was raised. */
986 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case STORE_NAME:
989 return -1;
990 case DELETE_NAME:
991 return 0;
992 case UNPACK_SEQUENCE:
993 return oparg-1;
994 case UNPACK_EX:
995 return (oparg&0xFF) + (oparg>>8);
996 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200997 /* -1 at end of iterator, 1 if continue iterating. */
998 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case STORE_ATTR:
1001 return -2;
1002 case DELETE_ATTR:
1003 return -1;
1004 case STORE_GLOBAL:
1005 return -1;
1006 case DELETE_GLOBAL:
1007 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case LOAD_CONST:
1009 return 1;
1010 case LOAD_NAME:
1011 return 1;
1012 case BUILD_TUPLE:
1013 case BUILD_LIST:
1014 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001015 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001017 case BUILD_LIST_UNPACK:
1018 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001019 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001020 case BUILD_SET_UNPACK:
1021 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001022 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001023 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001025 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001026 case BUILD_CONST_KEY_MAP:
1027 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case LOAD_ATTR:
1029 return 0;
1030 case COMPARE_OP:
1031 return -1;
1032 case IMPORT_NAME:
1033 return -1;
1034 case IMPORT_FROM:
1035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001037 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case JUMP_ABSOLUTE:
1040 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001042 case JUMP_IF_TRUE_OR_POP:
1043 case JUMP_IF_FALSE_OR_POP:
1044 return jump ? 0 : -1;
1045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case POP_JUMP_IF_FALSE:
1047 case POP_JUMP_IF_TRUE:
1048 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case LOAD_GLOBAL:
1051 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001053 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001055 /* 0 in the normal flow.
1056 * Restore the stack position and push 6 values before jumping to
1057 * the handler if an exception be raised. */
1058 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001059 case BEGIN_FINALLY:
1060 /* Actually pushes 1 value, but count 6 for balancing with
1061 * END_FINALLY and POP_FINALLY.
1062 * This is the main reason of using this opcode instead of
1063 * "LOAD_CONST None". */
1064 return 6;
1065 case CALL_FINALLY:
1066 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case LOAD_FAST:
1069 return 1;
1070 case STORE_FAST:
1071 return -1;
1072 case DELETE_FAST:
1073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case RAISE_VARARGS:
1076 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001077
1078 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001080 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001081 case CALL_METHOD:
1082 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001084 return -oparg-1;
1085 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001086 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001087 case MAKE_FUNCTION:
1088 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1089 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 case BUILD_SLICE:
1091 if (oparg == 3)
1092 return -2;
1093 else
1094 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case LOAD_CLOSURE:
1098 return 1;
1099 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001100 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return 1;
1102 case STORE_DEREF:
1103 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001104 case DELETE_DEREF:
1105 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001106
1107 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case GET_AWAITABLE:
1109 return 0;
1110 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001111 /* 0 in the normal flow.
1112 * Restore the stack position to the position before the result
1113 * of __aenter__ and push 6 values before jumping to the handler
1114 * if an exception be raised. */
1115 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001116 case BEFORE_ASYNC_WITH:
1117 return 1;
1118 case GET_AITER:
1119 return 0;
1120 case GET_ANEXT:
1121 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001122 case GET_YIELD_FROM_ITER:
1123 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001124 case END_ASYNC_FOR:
1125 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001126 case FORMAT_VALUE:
1127 /* If there's a fmt_spec on the stack, we go from 2->1,
1128 else 1->1. */
1129 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001130 case LOAD_METHOD:
1131 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001133 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 }
Larry Hastings3a907972013-11-23 14:49:22 -08001135 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136}
1137
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001138int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001139PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1140{
1141 return stack_effect(opcode, oparg, jump);
1142}
1143
1144int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001145PyCompile_OpcodeStackEffect(int opcode, int oparg)
1146{
1147 return stack_effect(opcode, oparg, -1);
1148}
1149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150/* Add an opcode with no argument.
1151 Returns 0 on failure, 1 on success.
1152*/
1153
1154static int
1155compiler_addop(struct compiler *c, int opcode)
1156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 basicblock *b;
1158 struct instr *i;
1159 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001160 assert(!HAS_ARG(opcode));
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001161 if (c->c_do_not_emit_bytecode) {
1162 return 1;
1163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 off = compiler_next_instr(c, c->u->u_curblock);
1165 if (off < 0)
1166 return 0;
1167 b = c->u->u_curblock;
1168 i = &b->b_instr[off];
1169 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001170 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (opcode == RETURN_VALUE)
1172 b->b_return = 1;
1173 compiler_set_lineno(c, off);
1174 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175}
1176
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1179{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001180 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001183 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001185 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001187 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001188 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001189 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return -1;
1192 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001193 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_DECREF(v);
1195 return -1;
1196 }
1197 Py_DECREF(v);
1198 }
1199 else
1200 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001201 return arg;
1202}
1203
INADA Naokic2e16072018-11-26 21:23:22 +09001204// Merge const *o* recursively and return constant key object.
1205static PyObject*
1206merge_consts_recursive(struct compiler *c, PyObject *o)
1207{
1208 // None and Ellipsis are singleton, and key is the singleton.
1209 // No need to merge object and key.
1210 if (o == Py_None || o == Py_Ellipsis) {
1211 Py_INCREF(o);
1212 return o;
1213 }
1214
1215 PyObject *key = _PyCode_ConstantKey(o);
1216 if (key == NULL) {
1217 return NULL;
1218 }
1219
1220 // t is borrowed reference
1221 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1222 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001223 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001224 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001225 Py_DECREF(key);
1226 return t;
1227 }
1228
INADA Naokif7e4d362018-11-29 00:58:46 +09001229 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001230 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001232 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 Py_ssize_t len = PyTuple_GET_SIZE(o);
1234 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001235 PyObject *item = PyTuple_GET_ITEM(o, i);
1236 PyObject *u = merge_consts_recursive(c, item);
1237 if (u == NULL) {
1238 Py_DECREF(key);
1239 return NULL;
1240 }
1241
1242 // See _PyCode_ConstantKey()
1243 PyObject *v; // borrowed
1244 if (PyTuple_CheckExact(u)) {
1245 v = PyTuple_GET_ITEM(u, 1);
1246 }
1247 else {
1248 v = u;
1249 }
1250 if (v != item) {
1251 Py_INCREF(v);
1252 PyTuple_SET_ITEM(o, i, v);
1253 Py_DECREF(item);
1254 }
1255
1256 Py_DECREF(u);
1257 }
1258 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001259 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001260 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001261 // constant keys.
1262 // See _PyCode_ConstantKey() for detail.
1263 assert(PyTuple_CheckExact(key));
1264 assert(PyTuple_GET_SIZE(key) == 2);
1265
1266 Py_ssize_t len = PySet_GET_SIZE(o);
1267 if (len == 0) { // empty frozenset should not be re-created.
1268 return key;
1269 }
1270 PyObject *tuple = PyTuple_New(len);
1271 if (tuple == NULL) {
1272 Py_DECREF(key);
1273 return NULL;
1274 }
1275 Py_ssize_t i = 0, pos = 0;
1276 PyObject *item;
1277 Py_hash_t hash;
1278 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1279 PyObject *k = merge_consts_recursive(c, item);
1280 if (k == NULL) {
1281 Py_DECREF(tuple);
1282 Py_DECREF(key);
1283 return NULL;
1284 }
1285 PyObject *u;
1286 if (PyTuple_CheckExact(k)) {
1287 u = PyTuple_GET_ITEM(k, 1);
1288 Py_INCREF(u);
1289 Py_DECREF(k);
1290 }
1291 else {
1292 u = k;
1293 }
1294 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1295 i++;
1296 }
1297
1298 // Instead of rewriting o, we create new frozenset and embed in the
1299 // key tuple. Caller should get merged frozenset from the key tuple.
1300 PyObject *new = PyFrozenSet_New(tuple);
1301 Py_DECREF(tuple);
1302 if (new == NULL) {
1303 Py_DECREF(key);
1304 return NULL;
1305 }
1306 assert(PyTuple_GET_ITEM(key, 1) == o);
1307 Py_DECREF(o);
1308 PyTuple_SET_ITEM(key, 1, new);
1309 }
INADA Naokic2e16072018-11-26 21:23:22 +09001310
1311 return key;
1312}
1313
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001314static Py_ssize_t
1315compiler_add_const(struct compiler *c, PyObject *o)
1316{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001317 if (c->c_do_not_emit_bytecode) {
1318 return 0;
1319 }
1320
INADA Naokic2e16072018-11-26 21:23:22 +09001321 PyObject *key = merge_consts_recursive(c, o);
1322 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001323 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001324 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325
INADA Naokic2e16072018-11-26 21:23:22 +09001326 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1327 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329}
1330
1331static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001332compiler_addop_load_const(struct compiler *c, PyObject *o)
1333{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001334 if (c->c_do_not_emit_bytecode) {
1335 return 1;
1336 }
1337
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001338 Py_ssize_t arg = compiler_add_const(c, o);
1339 if (arg < 0)
1340 return 0;
1341 return compiler_addop_i(c, LOAD_CONST, arg);
1342}
1343
1344static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347{
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001348 if (c->c_do_not_emit_bytecode) {
1349 return 1;
1350 }
1351
Victor Stinnerad9a0662013-11-19 22:23:20 +01001352 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 return compiler_addop_i(c, opcode, arg);
1356}
1357
1358static int
1359compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001362 Py_ssize_t arg;
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001363
1364 if (c->c_do_not_emit_bytecode) {
1365 return 1;
1366 }
1367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1369 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001370 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371 arg = compiler_add_o(c, dict, mangled);
1372 Py_DECREF(mangled);
1373 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375 return compiler_addop_i(c, opcode, arg);
1376}
1377
1378/* Add an opcode with an integer argument.
1379 Returns 0 on failure, 1 on success.
1380*/
1381
1382static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001383compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 struct instr *i;
1386 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001387
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001388 if (c->c_do_not_emit_bytecode) {
1389 return 1;
1390 }
1391
Victor Stinner2ad474b2016-03-01 23:34:47 +01001392 /* oparg value is unsigned, but a signed C int is usually used to store
1393 it in the C code (like Python/ceval.c).
1394
1395 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1396
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001397 The argument of a concrete bytecode instruction is limited to 8-bit.
1398 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1399 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001400 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 off = compiler_next_instr(c, c->u->u_curblock);
1403 if (off < 0)
1404 return 0;
1405 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001406 i->i_opcode = opcode;
1407 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 compiler_set_lineno(c, off);
1409 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410}
1411
1412static int
1413compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 struct instr *i;
1416 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001418 if (c->c_do_not_emit_bytecode) {
1419 return 1;
1420 }
1421
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001422 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 assert(b != NULL);
1424 off = compiler_next_instr(c, c->u->u_curblock);
1425 if (off < 0)
1426 return 0;
1427 i = &c->u->u_curblock->b_instr[off];
1428 i->i_opcode = opcode;
1429 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (absolute)
1431 i->i_jabs = 1;
1432 else
1433 i->i_jrel = 1;
1434 compiler_set_lineno(c, off);
1435 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436}
1437
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001438/* NEXT_BLOCK() creates an implicit jump from the current block
1439 to the new block.
1440
1441 The returns inside this macro make it impossible to decref objects
1442 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (compiler_next_block((C)) == NULL) \
1446 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447}
1448
1449#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (!compiler_addop((C), (OP))) \
1451 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452}
1453
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001454#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (!compiler_addop((C), (OP))) { \
1456 compiler_exit_scope(c); \
1457 return 0; \
1458 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001459}
1460
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001461#define ADDOP_LOAD_CONST(C, O) { \
1462 if (!compiler_addop_load_const((C), (O))) \
1463 return 0; \
1464}
1465
1466/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1467#define ADDOP_LOAD_CONST_NEW(C, O) { \
1468 PyObject *__new_const = (O); \
1469 if (__new_const == NULL) { \
1470 return 0; \
1471 } \
1472 if (!compiler_addop_load_const((C), __new_const)) { \
1473 Py_DECREF(__new_const); \
1474 return 0; \
1475 } \
1476 Py_DECREF(__new_const); \
1477}
1478
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1481 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482}
1483
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001484/* Same as ADDOP_O, but steals a reference. */
1485#define ADDOP_N(C, OP, O, TYPE) { \
1486 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1487 Py_DECREF((O)); \
1488 return 0; \
1489 } \
1490 Py_DECREF((O)); \
1491}
1492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1495 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (!compiler_addop_i((C), (OP), (O))) \
1500 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
1503#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (!compiler_addop_j((C), (OP), (O), 1)) \
1505 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506}
1507
1508#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!compiler_addop_j((C), (OP), (O), 0)) \
1510 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511}
1512
1513/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1514 the ASDL name to synthesize the name of the C type and the visit function.
1515*/
1516
1517#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (!compiler_visit_ ## TYPE((C), (V))) \
1519 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001522#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!compiler_visit_ ## TYPE((C), (V))) { \
1524 compiler_exit_scope(c); \
1525 return 0; \
1526 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001527}
1528
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (!compiler_visit_slice((C), (V), (CTX))) \
1531 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532}
1533
1534#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 int _i; \
1536 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1537 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1538 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1539 if (!compiler_visit_ ## TYPE((C), elt)) \
1540 return 0; \
1541 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542}
1543
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001544#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 int _i; \
1546 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1547 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1548 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1549 if (!compiler_visit_ ## TYPE((C), elt)) { \
1550 compiler_exit_scope(c); \
1551 return 0; \
1552 } \
1553 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001554}
1555
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07001556/* These macros allows to check only for errors and not emmit bytecode
1557 * while visiting nodes.
1558*/
1559
1560#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1561 c->c_do_not_emit_bytecode++;
1562
1563#define END_DO_NOT_EMIT_BYTECODE \
1564 c->c_do_not_emit_bytecode--; \
1565}
1566
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001567/* Search if variable annotations are present statically in a block. */
1568
1569static int
1570find_ann(asdl_seq *stmts)
1571{
1572 int i, j, res = 0;
1573 stmt_ty st;
1574
1575 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1576 st = (stmt_ty)asdl_seq_GET(stmts, i);
1577 switch (st->kind) {
1578 case AnnAssign_kind:
1579 return 1;
1580 case For_kind:
1581 res = find_ann(st->v.For.body) ||
1582 find_ann(st->v.For.orelse);
1583 break;
1584 case AsyncFor_kind:
1585 res = find_ann(st->v.AsyncFor.body) ||
1586 find_ann(st->v.AsyncFor.orelse);
1587 break;
1588 case While_kind:
1589 res = find_ann(st->v.While.body) ||
1590 find_ann(st->v.While.orelse);
1591 break;
1592 case If_kind:
1593 res = find_ann(st->v.If.body) ||
1594 find_ann(st->v.If.orelse);
1595 break;
1596 case With_kind:
1597 res = find_ann(st->v.With.body);
1598 break;
1599 case AsyncWith_kind:
1600 res = find_ann(st->v.AsyncWith.body);
1601 break;
1602 case Try_kind:
1603 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1604 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1605 st->v.Try.handlers, j);
1606 if (find_ann(handler->v.ExceptHandler.body)) {
1607 return 1;
1608 }
1609 }
1610 res = find_ann(st->v.Try.body) ||
1611 find_ann(st->v.Try.finalbody) ||
1612 find_ann(st->v.Try.orelse);
1613 break;
1614 default:
1615 res = 0;
1616 }
1617 if (res) {
1618 break;
1619 }
1620 }
1621 return res;
1622}
1623
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001624/*
1625 * Frame block handling functions
1626 */
1627
1628static int
1629compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1630 basicblock *exit)
1631{
1632 struct fblockinfo *f;
1633 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1634 PyErr_SetString(PyExc_SyntaxError,
1635 "too many statically nested blocks");
1636 return 0;
1637 }
1638 f = &c->u->u_fblock[c->u->u_nfblocks++];
1639 f->fb_type = t;
1640 f->fb_block = b;
1641 f->fb_exit = exit;
1642 return 1;
1643}
1644
1645static void
1646compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1647{
1648 struct compiler_unit *u = c->u;
1649 assert(u->u_nfblocks > 0);
1650 u->u_nfblocks--;
1651 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1652 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1653}
1654
1655/* Unwind a frame block. If preserve_tos is true, the TOS before
1656 * popping the blocks will be restored afterwards.
1657 */
1658static int
1659compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1660 int preserve_tos)
1661{
1662 switch (info->fb_type) {
1663 case WHILE_LOOP:
1664 return 1;
1665
1666 case FINALLY_END:
1667 ADDOP_I(c, POP_FINALLY, preserve_tos);
1668 return 1;
1669
1670 case FOR_LOOP:
1671 /* Pop the iterator */
1672 if (preserve_tos) {
1673 ADDOP(c, ROT_TWO);
1674 }
1675 ADDOP(c, POP_TOP);
1676 return 1;
1677
1678 case EXCEPT:
1679 ADDOP(c, POP_BLOCK);
1680 return 1;
1681
1682 case FINALLY_TRY:
1683 ADDOP(c, POP_BLOCK);
1684 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1685 return 1;
1686
1687 case WITH:
1688 case ASYNC_WITH:
1689 ADDOP(c, POP_BLOCK);
1690 if (preserve_tos) {
1691 ADDOP(c, ROT_TWO);
1692 }
1693 ADDOP(c, BEGIN_FINALLY);
1694 ADDOP(c, WITH_CLEANUP_START);
1695 if (info->fb_type == ASYNC_WITH) {
1696 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001697 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001698 ADDOP(c, YIELD_FROM);
1699 }
1700 ADDOP(c, WITH_CLEANUP_FINISH);
1701 ADDOP_I(c, POP_FINALLY, 0);
1702 return 1;
1703
1704 case HANDLER_CLEANUP:
1705 if (preserve_tos) {
1706 ADDOP(c, ROT_FOUR);
1707 }
1708 if (info->fb_exit) {
1709 ADDOP(c, POP_BLOCK);
1710 ADDOP(c, POP_EXCEPT);
1711 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1712 }
1713 else {
1714 ADDOP(c, POP_EXCEPT);
1715 }
1716 return 1;
1717 }
1718 Py_UNREACHABLE();
1719}
1720
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001721/* Compile a sequence of statements, checking for a docstring
1722 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723
1724static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001725compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001727 int i = 0;
1728 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001729 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001730
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001731 /* Set current line number to the line number of first statement.
1732 This way line number for SETUP_ANNOTATIONS will always
1733 coincide with the line number of first "real" statement in module.
1734 If body is empy, then lineno will be set later in assemble. */
1735 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1736 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001737 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001738 c->u->u_lineno = st->lineno;
1739 }
1740 /* Every annotated class and module should have __annotations__. */
1741 if (find_ann(stmts)) {
1742 ADDOP(c, SETUP_ANNOTATIONS);
1743 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001744 if (!asdl_seq_LEN(stmts))
1745 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001746 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001747 if (c->c_optimize < 2) {
1748 docstring = _PyAST_GetDocString(stmts);
1749 if (docstring) {
1750 i = 1;
1751 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1752 assert(st->kind == Expr_kind);
1753 VISIT(c, expr, st->v.Expr.value);
1754 if (!compiler_nameop(c, __doc__, Store))
1755 return 0;
1756 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001758 for (; i < asdl_seq_LEN(stmts); i++)
1759 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761}
1762
1763static PyCodeObject *
1764compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyCodeObject *co;
1767 int addNone = 1;
1768 static PyObject *module;
1769 if (!module) {
1770 module = PyUnicode_InternFromString("<module>");
1771 if (!module)
1772 return NULL;
1773 }
1774 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001775 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 return NULL;
1777 switch (mod->kind) {
1778 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001779 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 compiler_exit_scope(c);
1781 return 0;
1782 }
1783 break;
1784 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001785 if (find_ann(mod->v.Interactive.body)) {
1786 ADDOP(c, SETUP_ANNOTATIONS);
1787 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 c->c_interactive = 1;
1789 VISIT_SEQ_IN_SCOPE(c, stmt,
1790 mod->v.Interactive.body);
1791 break;
1792 case Expression_kind:
1793 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1794 addNone = 0;
1795 break;
1796 case Suite_kind:
1797 PyErr_SetString(PyExc_SystemError,
1798 "suite should not be possible");
1799 return 0;
1800 default:
1801 PyErr_Format(PyExc_SystemError,
1802 "module kind %d should not be possible",
1803 mod->kind);
1804 return 0;
1805 }
1806 co = assemble(c, addNone);
1807 compiler_exit_scope(c);
1808 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001809}
1810
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811/* The test for LOCAL must come before the test for FREE in order to
1812 handle classes where name is both local and free. The local var is
1813 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001814*/
1815
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816static int
1817get_ref_type(struct compiler *c, PyObject *name)
1818{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001819 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001820 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001821 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001822 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001823 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (scope == 0) {
1825 char buf[350];
1826 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001827 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001829 PyUnicode_AsUTF8(name),
1830 PyUnicode_AsUTF8(c->u->u_name),
1831 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1832 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1833 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1834 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 );
1836 Py_FatalError(buf);
1837 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840}
1841
1842static int
1843compiler_lookup_arg(PyObject *dict, PyObject *name)
1844{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001845 PyObject *v;
1846 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001848 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001849 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
1852static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001853compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001855 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001856 if (qualname == NULL)
1857 qualname = co->co_name;
1858
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001859 if (free) {
1860 for (i = 0; i < free; ++i) {
1861 /* Bypass com_addop_varname because it will generate
1862 LOAD_DEREF but LOAD_CLOSURE is needed.
1863 */
1864 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1865 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001867 /* Special case: If a class contains a method with a
1868 free variable that has the same name as a method,
1869 the name will be considered free *and* local in the
1870 class. It should be handled by the closure, as
1871 well as by the normal name loookup logic.
1872 */
1873 reftype = get_ref_type(c, name);
1874 if (reftype == CELL)
1875 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1876 else /* (reftype == FREE) */
1877 arg = compiler_lookup_arg(c->u->u_freevars, name);
1878 if (arg == -1) {
1879 fprintf(stderr,
1880 "lookup %s in %s %d %d\n"
1881 "freevars of %s: %s\n",
1882 PyUnicode_AsUTF8(PyObject_Repr(name)),
1883 PyUnicode_AsUTF8(c->u->u_name),
1884 reftype, arg,
1885 PyUnicode_AsUTF8(co->co_name),
1886 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1887 Py_FatalError("compiler_make_closure()");
1888 }
1889 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001891 flags |= 0x08;
1892 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001894 ADDOP_LOAD_CONST(c, (PyObject*)co);
1895 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001896 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898}
1899
1900static int
1901compiler_decorators(struct compiler *c, asdl_seq* decos)
1902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (!decos)
1906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1909 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1910 }
1911 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912}
1913
1914static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001915compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001917{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001918 /* Push a dict of keyword-only default values.
1919
1920 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1921 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922 int i;
1923 PyObject *keys = NULL;
1924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1926 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1927 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1928 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001929 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001930 if (!mangled) {
1931 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001933 if (keys == NULL) {
1934 keys = PyList_New(1);
1935 if (keys == NULL) {
1936 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001937 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001938 }
1939 PyList_SET_ITEM(keys, 0, mangled);
1940 }
1941 else {
1942 int res = PyList_Append(keys, mangled);
1943 Py_DECREF(mangled);
1944 if (res == -1) {
1945 goto error;
1946 }
1947 }
1948 if (!compiler_visit_expr(c, default_)) {
1949 goto error;
1950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
1952 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 if (keys != NULL) {
1954 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1955 PyObject *keys_tuple = PyList_AsTuple(keys);
1956 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001957 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001958 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001959 assert(default_count > 0);
1960 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001961 }
1962 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001963 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001964 }
1965
1966error:
1967 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001968 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001969}
1970
1971static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001972compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1973{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001974 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001975 return 1;
1976}
1977
1978static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001979compiler_visit_argannotation(struct compiler *c, identifier id,
1980 expr_ty annotation, PyObject *names)
1981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001983 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001984 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1985 VISIT(c, annexpr, annotation)
1986 }
1987 else {
1988 VISIT(c, expr, annotation);
1989 }
Victor Stinner065efc32014-02-18 22:07:56 +01001990 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001991 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001992 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001993 if (PyList_Append(names, mangled) < 0) {
1994 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001995 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001996 }
1997 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001999 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002000}
2001
2002static int
2003compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2004 PyObject *names)
2005{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002006 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 for (i = 0; i < asdl_seq_LEN(args); i++) {
2008 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002009 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 c,
2011 arg->arg,
2012 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002013 names))
2014 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002016 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002017}
2018
2019static int
2020compiler_visit_annotations(struct compiler *c, arguments_ty args,
2021 expr_ty returns)
2022{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002023 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002024 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002025
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002026 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 */
2028 static identifier return_str;
2029 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002030 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 names = PyList_New(0);
2032 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002033 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002034
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002035 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002037 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2038 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002039 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002040 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002041 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002043 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002045 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002046 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002047 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (!return_str) {
2051 return_str = PyUnicode_InternFromString("return");
2052 if (!return_str)
2053 goto error;
2054 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002055 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 goto error;
2057 }
2058
2059 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002061 PyObject *keytuple = PyList_AsTuple(names);
2062 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002063 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002064 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002065 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002067 else {
2068 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002069 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002070 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002071
2072error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002074 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002075}
2076
2077static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002078compiler_visit_defaults(struct compiler *c, arguments_ty args)
2079{
2080 VISIT_SEQ(c, expr, args->defaults);
2081 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2082 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083}
2084
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002085static Py_ssize_t
2086compiler_default_arguments(struct compiler *c, arguments_ty args)
2087{
2088 Py_ssize_t funcflags = 0;
2089 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002090 if (!compiler_visit_defaults(c, args))
2091 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002092 funcflags |= 0x01;
2093 }
2094 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002095 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002096 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002097 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002098 return -1;
2099 }
2100 else if (res > 0) {
2101 funcflags |= 0x02;
2102 }
2103 }
2104 return funcflags;
2105}
2106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107static int
Yury Selivanov75445082015-05-11 22:57:16 -04002108compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002111 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002112 arguments_ty args;
2113 expr_ty returns;
2114 identifier name;
2115 asdl_seq* decos;
2116 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002117 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002118 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002119 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002120 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
Yury Selivanov75445082015-05-11 22:57:16 -04002122 if (is_async) {
2123 assert(s->kind == AsyncFunctionDef_kind);
2124
2125 args = s->v.AsyncFunctionDef.args;
2126 returns = s->v.AsyncFunctionDef.returns;
2127 decos = s->v.AsyncFunctionDef.decorator_list;
2128 name = s->v.AsyncFunctionDef.name;
2129 body = s->v.AsyncFunctionDef.body;
2130
2131 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2132 } else {
2133 assert(s->kind == FunctionDef_kind);
2134
2135 args = s->v.FunctionDef.args;
2136 returns = s->v.FunctionDef.returns;
2137 decos = s->v.FunctionDef.decorator_list;
2138 name = s->v.FunctionDef.name;
2139 body = s->v.FunctionDef.body;
2140
2141 scope_type = COMPILER_SCOPE_FUNCTION;
2142 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (!compiler_decorators(c, decos))
2145 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002146
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002147 firstlineno = s->lineno;
2148 if (asdl_seq_LEN(decos)) {
2149 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2150 }
2151
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002152 funcflags = compiler_default_arguments(c, args);
2153 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002155 }
2156
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002157 annotations = compiler_visit_annotations(c, args, returns);
2158 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002159 return 0;
2160 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002161 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002162 funcflags |= 0x04;
2163 }
2164
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002165 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002166 return 0;
2167 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168
INADA Naokicb41b272017-02-23 00:31:59 +09002169 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002170 if (c->c_optimize < 2) {
2171 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002172 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002173 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 compiler_exit_scope(c);
2175 return 0;
2176 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002179 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002181 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002183 qualname = c->u->u_qualname;
2184 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002186 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002187 Py_XDECREF(qualname);
2188 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002192 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002193 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* decorators */
2197 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2198 ADDOP_I(c, CALL_FUNCTION, 1);
2199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200
Yury Selivanov75445082015-05-11 22:57:16 -04002201 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202}
2203
2204static int
2205compiler_class(struct compiler *c, stmt_ty s)
2206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 PyCodeObject *co;
2208 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002209 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (!compiler_decorators(c, decos))
2213 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002214
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002215 firstlineno = s->lineno;
2216 if (asdl_seq_LEN(decos)) {
2217 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2218 }
2219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* ultimately generate code for:
2221 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2222 where:
2223 <func> is a function/closure created from the class body;
2224 it has a single argument (__locals__) where the dict
2225 (or MutableSequence) representing the locals is passed
2226 <name> is the class name
2227 <bases> is the positional arguments and *varargs argument
2228 <keywords> is the keyword arguments and **kwds argument
2229 This borrows from compiler_call.
2230 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002233 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002234 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return 0;
2236 /* this block represents what we do in the new scope */
2237 {
2238 /* use the class name for name mangling */
2239 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002240 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* load (global) __name__ ... */
2242 str = PyUnicode_InternFromString("__name__");
2243 if (!str || !compiler_nameop(c, str, Load)) {
2244 Py_XDECREF(str);
2245 compiler_exit_scope(c);
2246 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 Py_DECREF(str);
2249 /* ... and store it as __module__ */
2250 str = PyUnicode_InternFromString("__module__");
2251 if (!str || !compiler_nameop(c, str, Store)) {
2252 Py_XDECREF(str);
2253 compiler_exit_scope(c);
2254 return 0;
2255 }
2256 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002257 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002258 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002259 str = PyUnicode_InternFromString("__qualname__");
2260 if (!str || !compiler_nameop(c, str, Store)) {
2261 Py_XDECREF(str);
2262 compiler_exit_scope(c);
2263 return 0;
2264 }
2265 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002267 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 compiler_exit_scope(c);
2269 return 0;
2270 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002271 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002272 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002273 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002274 str = PyUnicode_InternFromString("__class__");
2275 if (str == NULL) {
2276 compiler_exit_scope(c);
2277 return 0;
2278 }
2279 i = compiler_lookup_arg(c->u->u_cellvars, str);
2280 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002281 if (i < 0) {
2282 compiler_exit_scope(c);
2283 return 0;
2284 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002285 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002288 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002289 str = PyUnicode_InternFromString("__classcell__");
2290 if (!str || !compiler_nameop(c, str, Store)) {
2291 Py_XDECREF(str);
2292 compiler_exit_scope(c);
2293 return 0;
2294 }
2295 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002297 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002298 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002299 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002300 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002301 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002302 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* create the code object */
2304 co = assemble(c, 1);
2305 }
2306 /* leave the new scope */
2307 compiler_exit_scope(c);
2308 if (co == NULL)
2309 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* 2. load the 'build_class' function */
2312 ADDOP(c, LOAD_BUILD_CLASS);
2313
2314 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002315 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 Py_DECREF(co);
2317
2318 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002319 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320
2321 /* 5. generate the rest of the code for the call */
2322 if (!compiler_call_helper(c, 2,
2323 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002324 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 return 0;
2326
2327 /* 6. apply decorators */
2328 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2329 ADDOP_I(c, CALL_FUNCTION, 1);
2330 }
2331
2332 /* 7. store into <name> */
2333 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2334 return 0;
2335 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336}
2337
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002338/* Return 0 if the expression is a constant value except named singletons.
2339 Return 1 otherwise. */
2340static int
2341check_is_arg(expr_ty e)
2342{
2343 if (e->kind != Constant_kind) {
2344 return 1;
2345 }
2346 PyObject *value = e->v.Constant.value;
2347 return (value == Py_None
2348 || value == Py_False
2349 || value == Py_True
2350 || value == Py_Ellipsis);
2351}
2352
2353/* Check operands of identity chacks ("is" and "is not").
2354 Emit a warning if any operand is a constant except named singletons.
2355 Return 0 on error.
2356 */
2357static int
2358check_compare(struct compiler *c, expr_ty e)
2359{
2360 Py_ssize_t i, n;
2361 int left = check_is_arg(e->v.Compare.left);
2362 n = asdl_seq_LEN(e->v.Compare.ops);
2363 for (i = 0; i < n; i++) {
2364 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2365 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2366 if (op == Is || op == IsNot) {
2367 if (!right || !left) {
2368 const char *msg = (op == Is)
2369 ? "\"is\" with a literal. Did you mean \"==\"?"
2370 : "\"is not\" with a literal. Did you mean \"!=\"?";
2371 return compiler_warn(c, msg);
2372 }
2373 }
2374 left = right;
2375 }
2376 return 1;
2377}
2378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002380cmpop(cmpop_ty op)
2381{
2382 switch (op) {
2383 case Eq:
2384 return PyCmp_EQ;
2385 case NotEq:
2386 return PyCmp_NE;
2387 case Lt:
2388 return PyCmp_LT;
2389 case LtE:
2390 return PyCmp_LE;
2391 case Gt:
2392 return PyCmp_GT;
2393 case GtE:
2394 return PyCmp_GE;
2395 case Is:
2396 return PyCmp_IS;
2397 case IsNot:
2398 return PyCmp_IS_NOT;
2399 case In:
2400 return PyCmp_IN;
2401 case NotIn:
2402 return PyCmp_NOT_IN;
2403 default:
2404 return PyCmp_BAD;
2405 }
2406}
2407
2408static int
2409compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2410{
2411 switch (e->kind) {
2412 case UnaryOp_kind:
2413 if (e->v.UnaryOp.op == Not)
2414 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2415 /* fallback to general implementation */
2416 break;
2417 case BoolOp_kind: {
2418 asdl_seq *s = e->v.BoolOp.values;
2419 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2420 assert(n >= 0);
2421 int cond2 = e->v.BoolOp.op == Or;
2422 basicblock *next2 = next;
2423 if (!cond2 != !cond) {
2424 next2 = compiler_new_block(c);
2425 if (next2 == NULL)
2426 return 0;
2427 }
2428 for (i = 0; i < n; ++i) {
2429 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2430 return 0;
2431 }
2432 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2433 return 0;
2434 if (next2 != next)
2435 compiler_use_next_block(c, next2);
2436 return 1;
2437 }
2438 case IfExp_kind: {
2439 basicblock *end, *next2;
2440 end = compiler_new_block(c);
2441 if (end == NULL)
2442 return 0;
2443 next2 = compiler_new_block(c);
2444 if (next2 == NULL)
2445 return 0;
2446 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2447 return 0;
2448 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2449 return 0;
2450 ADDOP_JREL(c, JUMP_FORWARD, end);
2451 compiler_use_next_block(c, next2);
2452 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2453 return 0;
2454 compiler_use_next_block(c, end);
2455 return 1;
2456 }
2457 case Compare_kind: {
2458 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2459 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002460 if (!check_compare(c, e)) {
2461 return 0;
2462 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463 basicblock *cleanup = compiler_new_block(c);
2464 if (cleanup == NULL)
2465 return 0;
2466 VISIT(c, expr, e->v.Compare.left);
2467 for (i = 0; i < n; i++) {
2468 VISIT(c, expr,
2469 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2470 ADDOP(c, DUP_TOP);
2471 ADDOP(c, ROT_THREE);
2472 ADDOP_I(c, COMPARE_OP,
2473 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2474 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2475 NEXT_BLOCK(c);
2476 }
2477 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2478 ADDOP_I(c, COMPARE_OP,
2479 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2480 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2481 basicblock *end = compiler_new_block(c);
2482 if (end == NULL)
2483 return 0;
2484 ADDOP_JREL(c, JUMP_FORWARD, end);
2485 compiler_use_next_block(c, cleanup);
2486 ADDOP(c, POP_TOP);
2487 if (!cond) {
2488 ADDOP_JREL(c, JUMP_FORWARD, next);
2489 }
2490 compiler_use_next_block(c, end);
2491 return 1;
2492 }
2493 /* fallback to general implementation */
2494 break;
2495 }
2496 default:
2497 /* fallback to general implementation */
2498 break;
2499 }
2500
2501 /* general implementation */
2502 VISIT(c, expr, e);
2503 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2504 return 1;
2505}
2506
2507static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002508compiler_ifexp(struct compiler *c, expr_ty e)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 basicblock *end, *next;
2511
2512 assert(e->kind == IfExp_kind);
2513 end = compiler_new_block(c);
2514 if (end == NULL)
2515 return 0;
2516 next = compiler_new_block(c);
2517 if (next == NULL)
2518 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002519 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2520 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 VISIT(c, expr, e->v.IfExp.body);
2522 ADDOP_JREL(c, JUMP_FORWARD, end);
2523 compiler_use_next_block(c, next);
2524 VISIT(c, expr, e->v.IfExp.orelse);
2525 compiler_use_next_block(c, end);
2526 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002527}
2528
2529static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530compiler_lambda(struct compiler *c, expr_ty e)
2531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002533 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002535 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 arguments_ty args = e->v.Lambda.args;
2537 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (!name) {
2540 name = PyUnicode_InternFromString("<lambda>");
2541 if (!name)
2542 return 0;
2543 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002545 funcflags = compiler_default_arguments(c, args);
2546 if (funcflags == -1) {
2547 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002549
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002550 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002551 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* Make None the first constant, so the lambda can't have a
2555 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002556 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002560 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2562 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2563 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002564 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 }
2566 else {
2567 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002568 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002570 qualname = c->u->u_qualname;
2571 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002573 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002576 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002577 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 Py_DECREF(co);
2579
2580 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581}
2582
2583static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584compiler_if(struct compiler *c, stmt_ty s)
2585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 basicblock *end, *next;
2587 int constant;
2588 assert(s->kind == If_kind);
2589 end = compiler_new_block(c);
2590 if (end == NULL)
2591 return 0;
2592
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002593 constant = expr_constant(s->v.If.test);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002594 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 * constant = 1: "if 1", "if 2", ...
2596 * constant = -1: rest */
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002597 if (constant == 0) {
2598 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 VISIT_SEQ(c, stmt, s->v.If.body);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002600 END_DO_NOT_EMIT_BYTECODE
2601 if (s->v.If.orelse) {
2602 VISIT_SEQ(c, stmt, s->v.If.orelse);
2603 }
2604 } else if (constant == 1) {
2605 VISIT_SEQ(c, stmt, s->v.If.body);
2606 if (s->v.If.orelse) {
2607 BEGIN_DO_NOT_EMIT_BYTECODE
2608 VISIT_SEQ(c, stmt, s->v.If.orelse);
2609 END_DO_NOT_EMIT_BYTECODE
2610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002612 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 next = compiler_new_block(c);
2614 if (next == NULL)
2615 return 0;
2616 }
2617 else
2618 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002619 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2620 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002622 if (asdl_seq_LEN(s->v.If.orelse)) {
2623 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 compiler_use_next_block(c, next);
2625 VISIT_SEQ(c, stmt, s->v.If.orelse);
2626 }
2627 }
2628 compiler_use_next_block(c, end);
2629 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630}
2631
2632static int
2633compiler_for(struct compiler *c, stmt_ty s)
2634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 start = compiler_new_block(c);
2638 cleanup = compiler_new_block(c);
2639 end = compiler_new_block(c);
2640 if (start == NULL || end == NULL || cleanup == NULL)
2641 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002642
2643 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 VISIT(c, expr, s->v.For.iter);
2647 ADDOP(c, GET_ITER);
2648 compiler_use_next_block(c, start);
2649 ADDOP_JREL(c, FOR_ITER, cleanup);
2650 VISIT(c, expr, s->v.For.target);
2651 VISIT_SEQ(c, stmt, s->v.For.body);
2652 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2653 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002654
2655 compiler_pop_fblock(c, FOR_LOOP, start);
2656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 VISIT_SEQ(c, stmt, s->v.For.orelse);
2658 compiler_use_next_block(c, end);
2659 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660}
2661
Yury Selivanov75445082015-05-11 22:57:16 -04002662
2663static int
2664compiler_async_for(struct compiler *c, stmt_ty s)
2665{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002666 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002667 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2668 c->u->u_ste->ste_coroutine = 1;
2669 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002670 return compiler_error(c, "'async for' outside async function");
2671 }
2672
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002673 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002674 except = compiler_new_block(c);
2675 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002676
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002677 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002678 return 0;
2679
2680 VISIT(c, expr, s->v.AsyncFor.iter);
2681 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002682
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002683 compiler_use_next_block(c, start);
2684 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2685 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002686
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002687 /* SETUP_FINALLY to guard the __anext__ call */
2688 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002689 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002690 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002691 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002692 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002693
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002694 /* Success block for __anext__ */
2695 VISIT(c, expr, s->v.AsyncFor.target);
2696 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2697 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2698
2699 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002700
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002701 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002702 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002703 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002704
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002705 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002706 VISIT_SEQ(c, stmt, s->v.For.orelse);
2707
2708 compiler_use_next_block(c, end);
2709
2710 return 1;
2711}
2712
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713static int
2714compiler_while(struct compiler *c, stmt_ty s)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002717 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 if (constant == 0) {
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002720 BEGIN_DO_NOT_EMIT_BYTECODE
2721 VISIT_SEQ(c, stmt, s->v.While.body);
2722 END_DO_NOT_EMIT_BYTECODE
2723 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 VISIT_SEQ(c, stmt, s->v.While.orelse);
Miss Islington (bot)9ea738e2019-07-29 07:47:30 -07002725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 return 1;
2727 }
2728 loop = compiler_new_block(c);
2729 end = compiler_new_block(c);
2730 if (constant == -1) {
2731 anchor = compiler_new_block(c);
2732 if (anchor == NULL)
2733 return 0;
2734 }
2735 if (loop == NULL || end == NULL)
2736 return 0;
2737 if (s->v.While.orelse) {
2738 orelse = compiler_new_block(c);
2739 if (orelse == NULL)
2740 return 0;
2741 }
2742 else
2743 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002746 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 return 0;
2748 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002749 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2750 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 }
2752 VISIT_SEQ(c, stmt, s->v.While.body);
2753 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 /* XXX should the two POP instructions be in a separate block
2756 if there is no else clause ?
2757 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002759 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002761 compiler_pop_fblock(c, WHILE_LOOP, loop);
2762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 if (orelse != NULL) /* what if orelse is just pass? */
2764 VISIT_SEQ(c, stmt, s->v.While.orelse);
2765 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768}
2769
2770static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002771compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002773 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002774 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002775 if (c->u->u_ste->ste_type != FunctionBlock)
2776 return compiler_error(c, "'return' outside function");
2777 if (s->v.Return.value != NULL &&
2778 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2779 {
2780 return compiler_error(
2781 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002783 if (preserve_tos) {
2784 VISIT(c, expr, s->v.Return.value);
2785 }
2786 for (int depth = c->u->u_nfblocks; depth--;) {
2787 struct fblockinfo *info = &c->u->u_fblock[depth];
2788
2789 if (!compiler_unwind_fblock(c, info, preserve_tos))
2790 return 0;
2791 }
2792 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002793 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002794 }
2795 else if (!preserve_tos) {
2796 VISIT(c, expr, s->v.Return.value);
2797 }
2798 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801}
2802
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803static int
2804compiler_break(struct compiler *c)
2805{
2806 for (int depth = c->u->u_nfblocks; depth--;) {
2807 struct fblockinfo *info = &c->u->u_fblock[depth];
2808
2809 if (!compiler_unwind_fblock(c, info, 0))
2810 return 0;
2811 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2812 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2813 return 1;
2814 }
2815 }
2816 return compiler_error(c, "'break' outside loop");
2817}
2818
2819static int
2820compiler_continue(struct compiler *c)
2821{
2822 for (int depth = c->u->u_nfblocks; depth--;) {
2823 struct fblockinfo *info = &c->u->u_fblock[depth];
2824
2825 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2826 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2827 return 1;
2828 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002829 if (!compiler_unwind_fblock(c, info, 0))
2830 return 0;
2831 }
2832 return compiler_error(c, "'continue' not properly in loop");
2833}
2834
2835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837
2838 SETUP_FINALLY L
2839 <code for body>
2840 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002841 BEGIN_FINALLY
2842 L:
2843 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 END_FINALLY
2845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 The special instructions use the block stack. Each block
2847 stack entry contains the instruction that created it (here
2848 SETUP_FINALLY), the level of the value stack at the time the
2849 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 Pushes the current value stack level and the label
2853 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002855 Pops en entry from the block stack.
2856 BEGIN_FINALLY
2857 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2860 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002863 when a SETUP_FINALLY entry is found, the raised and the caught
2864 exceptions are pushed onto the value stack (and the exception
2865 condition is cleared), and the interpreter jumps to the label
2866 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867*/
2868
2869static int
2870compiler_try_finally(struct compiler *c, stmt_ty s)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 body = compiler_new_block(c);
2875 end = compiler_new_block(c);
2876 if (body == NULL || end == NULL)
2877 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 ADDOP_JREL(c, SETUP_FINALLY, end);
2881 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002882 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002884 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2885 if (!compiler_try_except(c, s))
2886 return 0;
2887 }
2888 else {
2889 VISIT_SEQ(c, stmt, s->v.Try.body);
2890 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002895 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002897 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002899 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 ADDOP(c, END_FINALLY);
2901 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903}
2904
2905/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002906 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907 (The contents of the value stack is shown in [], with the top
2908 at the right; 'tb' is trace-back info, 'val' the exception's
2909 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910
2911 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002912 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 [] <code for S>
2914 [] POP_BLOCK
2915 [] JUMP_FORWARD L0
2916
2917 [tb, val, exc] L1: DUP )
2918 [tb, val, exc, exc] <evaluate E1> )
2919 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2920 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2921 [tb, val, exc] POP
2922 [tb, val] <assign to V1> (or POP if no V1)
2923 [tb] POP
2924 [] <code for S1>
2925 JUMP_FORWARD L0
2926
2927 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 .............................etc.......................
2929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2931
2932 [] L0: <next statement>
2933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 Of course, parts are not generated if Vi or Ei is not present.
2935*/
2936static int
2937compiler_try_except(struct compiler *c, stmt_ty s)
2938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002940 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 body = compiler_new_block(c);
2943 except = compiler_new_block(c);
2944 orelse = compiler_new_block(c);
2945 end = compiler_new_block(c);
2946 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2947 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002948 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002950 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002952 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 ADDOP(c, POP_BLOCK);
2954 compiler_pop_fblock(c, EXCEPT, body);
2955 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002956 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 compiler_use_next_block(c, except);
2958 for (i = 0; i < n; i++) {
2959 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002960 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 if (!handler->v.ExceptHandler.type && i < n-1)
2962 return compiler_error(c, "default 'except:' must be last");
2963 c->u->u_lineno_set = 0;
2964 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002965 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 except = compiler_new_block(c);
2967 if (except == NULL)
2968 return 0;
2969 if (handler->v.ExceptHandler.type) {
2970 ADDOP(c, DUP_TOP);
2971 VISIT(c, expr, handler->v.ExceptHandler.type);
2972 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2973 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2974 }
2975 ADDOP(c, POP_TOP);
2976 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002977 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002978
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002979 cleanup_end = compiler_new_block(c);
2980 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002981 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002982 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002983 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002984
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002985 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2986 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002988 /*
2989 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002990 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002991 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002992 try:
2993 # body
2994 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10002995 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002996 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002997 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002999 /* second try: */
3000 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3001 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003002 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003003 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003005 /* second # body */
3006 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
3007 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003008 ADDOP(c, BEGIN_FINALLY);
3009 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003011 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003012 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003013 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003014 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003016 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003017 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003018 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003019 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003021 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02003022 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003023 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 }
3025 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003026 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003028 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003029 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003030 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031
Guido van Rossumb940e112007-01-10 16:19:56 +00003032 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003033 ADDOP(c, POP_TOP);
3034 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003035 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003036 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003038 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003039 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 }
3041 ADDOP_JREL(c, JUMP_FORWARD, end);
3042 compiler_use_next_block(c, except);
3043 }
3044 ADDOP(c, END_FINALLY);
3045 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003046 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 compiler_use_next_block(c, end);
3048 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049}
3050
3051static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003052compiler_try(struct compiler *c, stmt_ty s) {
3053 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3054 return compiler_try_finally(c, s);
3055 else
3056 return compiler_try_except(c, s);
3057}
3058
3059
3060static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061compiler_import_as(struct compiler *c, identifier name, identifier asname)
3062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 /* The IMPORT_NAME opcode was already generated. This function
3064 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003067 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003069 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3070 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003071 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003072 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003075 while (1) {
3076 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003078 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003079 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003080 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003081 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003083 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003084 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003085 if (dot == -1) {
3086 break;
3087 }
3088 ADDOP(c, ROT_TWO);
3089 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003091 if (!compiler_nameop(c, asname, Store)) {
3092 return 0;
3093 }
3094 ADDOP(c, POP_TOP);
3095 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 }
3097 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003098}
3099
3100static int
3101compiler_import(struct compiler *c, stmt_ty s)
3102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 /* The Import node stores a module name like a.b.c as a single
3104 string. This is convenient for all cases except
3105 import a.b.c as d
3106 where we need to parse that string to extract the individual
3107 module names.
3108 XXX Perhaps change the representation to make this case simpler?
3109 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003110 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 for (i = 0; i < n; i++) {
3113 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3114 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003116 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3117 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 if (alias->asname) {
3121 r = compiler_import_as(c, alias->name, alias->asname);
3122 if (!r)
3123 return r;
3124 }
3125 else {
3126 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003127 Py_ssize_t dot = PyUnicode_FindChar(
3128 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003129 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003130 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003131 if (tmp == NULL)
3132 return 0;
3133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003135 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 Py_DECREF(tmp);
3137 }
3138 if (!r)
3139 return r;
3140 }
3141 }
3142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143}
3144
3145static int
3146compiler_from_import(struct compiler *c, stmt_ty s)
3147{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003148 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003149 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 if (!empty_string) {
3153 empty_string = PyUnicode_FromString("");
3154 if (!empty_string)
3155 return 0;
3156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003158 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003159
3160 names = PyTuple_New(n);
3161 if (!names)
3162 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* build up the names */
3165 for (i = 0; i < n; i++) {
3166 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3167 Py_INCREF(alias->name);
3168 PyTuple_SET_ITEM(names, i, alias->name);
3169 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003172 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 Py_DECREF(names);
3174 return compiler_error(c, "from __future__ imports must occur "
3175 "at the beginning of the file");
3176 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003177 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 if (s->v.ImportFrom.module) {
3180 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3181 }
3182 else {
3183 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3184 }
3185 for (i = 0; i < n; i++) {
3186 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3187 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003189 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 assert(n == 1);
3191 ADDOP(c, IMPORT_STAR);
3192 return 1;
3193 }
3194
3195 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3196 store_name = alias->name;
3197 if (alias->asname)
3198 store_name = alias->asname;
3199
3200 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 return 0;
3202 }
3203 }
3204 /* remove imported module */
3205 ADDOP(c, POP_TOP);
3206 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207}
3208
3209static int
3210compiler_assert(struct compiler *c, stmt_ty s)
3211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 static PyObject *assertion_error = NULL;
3213 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214
Georg Brandl8334fd92010-12-04 10:26:46 +00003215 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 return 1;
3217 if (assertion_error == NULL) {
3218 assertion_error = PyUnicode_InternFromString("AssertionError");
3219 if (assertion_error == NULL)
3220 return 0;
3221 }
3222 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003223 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3224 {
3225 if (!compiler_warn(c, "assertion is always true, "
3226 "perhaps remove parentheses?"))
3227 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003228 return 0;
3229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 end = compiler_new_block(c);
3232 if (end == NULL)
3233 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003234 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3235 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3237 if (s->v.Assert.msg) {
3238 VISIT(c, expr, s->v.Assert.msg);
3239 ADDOP_I(c, CALL_FUNCTION, 1);
3240 }
3241 ADDOP_I(c, RAISE_VARARGS, 1);
3242 compiler_use_next_block(c, end);
3243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244}
3245
3246static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003247compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3248{
3249 if (c->c_interactive && c->c_nestlevel <= 1) {
3250 VISIT(c, expr, value);
3251 ADDOP(c, PRINT_EXPR);
3252 return 1;
3253 }
3254
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003255 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003256 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003257 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003258 }
3259
3260 VISIT(c, expr, value);
3261 ADDOP(c, POP_TOP);
3262 return 1;
3263}
3264
3265static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266compiler_visit_stmt(struct compiler *c, stmt_ty s)
3267{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003268 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 /* Always assign a lineno to the next instruction for a stmt. */
3271 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003272 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 switch (s->kind) {
3276 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003277 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 case ClassDef_kind:
3279 return compiler_class(c, s);
3280 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003281 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 case Delete_kind:
3283 VISIT_SEQ(c, expr, s->v.Delete.targets)
3284 break;
3285 case Assign_kind:
3286 n = asdl_seq_LEN(s->v.Assign.targets);
3287 VISIT(c, expr, s->v.Assign.value);
3288 for (i = 0; i < n; i++) {
3289 if (i < n - 1)
3290 ADDOP(c, DUP_TOP);
3291 VISIT(c, expr,
3292 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3293 }
3294 break;
3295 case AugAssign_kind:
3296 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003297 case AnnAssign_kind:
3298 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 case For_kind:
3300 return compiler_for(c, s);
3301 case While_kind:
3302 return compiler_while(c, s);
3303 case If_kind:
3304 return compiler_if(c, s);
3305 case Raise_kind:
3306 n = 0;
3307 if (s->v.Raise.exc) {
3308 VISIT(c, expr, s->v.Raise.exc);
3309 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003310 if (s->v.Raise.cause) {
3311 VISIT(c, expr, s->v.Raise.cause);
3312 n++;
3313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003315 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003317 case Try_kind:
3318 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 case Assert_kind:
3320 return compiler_assert(c, s);
3321 case Import_kind:
3322 return compiler_import(c, s);
3323 case ImportFrom_kind:
3324 return compiler_from_import(c, s);
3325 case Global_kind:
3326 case Nonlocal_kind:
3327 break;
3328 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003329 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 case Pass_kind:
3331 break;
3332 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003333 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 case Continue_kind:
3335 return compiler_continue(c);
3336 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003337 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003338 case AsyncFunctionDef_kind:
3339 return compiler_function(c, s, 1);
3340 case AsyncWith_kind:
3341 return compiler_async_with(c, s, 0);
3342 case AsyncFor_kind:
3343 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 }
Yury Selivanov75445082015-05-11 22:57:16 -04003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347}
3348
3349static int
3350unaryop(unaryop_ty op)
3351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 switch (op) {
3353 case Invert:
3354 return UNARY_INVERT;
3355 case Not:
3356 return UNARY_NOT;
3357 case UAdd:
3358 return UNARY_POSITIVE;
3359 case USub:
3360 return UNARY_NEGATIVE;
3361 default:
3362 PyErr_Format(PyExc_SystemError,
3363 "unary op %d should not be possible", op);
3364 return 0;
3365 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366}
3367
3368static int
3369binop(struct compiler *c, operator_ty op)
3370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 switch (op) {
3372 case Add:
3373 return BINARY_ADD;
3374 case Sub:
3375 return BINARY_SUBTRACT;
3376 case Mult:
3377 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003378 case MatMult:
3379 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 case Div:
3381 return BINARY_TRUE_DIVIDE;
3382 case Mod:
3383 return BINARY_MODULO;
3384 case Pow:
3385 return BINARY_POWER;
3386 case LShift:
3387 return BINARY_LSHIFT;
3388 case RShift:
3389 return BINARY_RSHIFT;
3390 case BitOr:
3391 return BINARY_OR;
3392 case BitXor:
3393 return BINARY_XOR;
3394 case BitAnd:
3395 return BINARY_AND;
3396 case FloorDiv:
3397 return BINARY_FLOOR_DIVIDE;
3398 default:
3399 PyErr_Format(PyExc_SystemError,
3400 "binary op %d should not be possible", op);
3401 return 0;
3402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403}
3404
3405static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003406inplace_binop(struct compiler *c, operator_ty op)
3407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 switch (op) {
3409 case Add:
3410 return INPLACE_ADD;
3411 case Sub:
3412 return INPLACE_SUBTRACT;
3413 case Mult:
3414 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003415 case MatMult:
3416 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 case Div:
3418 return INPLACE_TRUE_DIVIDE;
3419 case Mod:
3420 return INPLACE_MODULO;
3421 case Pow:
3422 return INPLACE_POWER;
3423 case LShift:
3424 return INPLACE_LSHIFT;
3425 case RShift:
3426 return INPLACE_RSHIFT;
3427 case BitOr:
3428 return INPLACE_OR;
3429 case BitXor:
3430 return INPLACE_XOR;
3431 case BitAnd:
3432 return INPLACE_AND;
3433 case FloorDiv:
3434 return INPLACE_FLOOR_DIVIDE;
3435 default:
3436 PyErr_Format(PyExc_SystemError,
3437 "inplace binary op %d should not be possible", op);
3438 return 0;
3439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440}
3441
3442static int
3443compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3444{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003445 int op, scope;
3446 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 PyObject *dict = c->u->u_names;
3450 PyObject *mangled;
3451 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003453 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3454 !_PyUnicode_EqualToASCIIString(name, "True") &&
3455 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003456
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003457 mangled = _Py_Mangle(c->u->u_private, name);
3458 if (!mangled)
3459 return 0;
3460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 op = 0;
3462 optype = OP_NAME;
3463 scope = PyST_GetScope(c->u->u_ste, mangled);
3464 switch (scope) {
3465 case FREE:
3466 dict = c->u->u_freevars;
3467 optype = OP_DEREF;
3468 break;
3469 case CELL:
3470 dict = c->u->u_cellvars;
3471 optype = OP_DEREF;
3472 break;
3473 case LOCAL:
3474 if (c->u->u_ste->ste_type == FunctionBlock)
3475 optype = OP_FAST;
3476 break;
3477 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003478 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 optype = OP_GLOBAL;
3480 break;
3481 case GLOBAL_EXPLICIT:
3482 optype = OP_GLOBAL;
3483 break;
3484 default:
3485 /* scope can be 0 */
3486 break;
3487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003490 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 switch (optype) {
3493 case OP_DEREF:
3494 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003495 case Load:
3496 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3497 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003498 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003499 op = STORE_DEREF;
3500 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 case AugLoad:
3502 case AugStore:
3503 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003504 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 case Param:
3506 default:
3507 PyErr_SetString(PyExc_SystemError,
3508 "param invalid for deref variable");
3509 return 0;
3510 }
3511 break;
3512 case OP_FAST:
3513 switch (ctx) {
3514 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003515 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003516 op = STORE_FAST;
3517 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 case Del: op = DELETE_FAST; break;
3519 case AugLoad:
3520 case AugStore:
3521 break;
3522 case Param:
3523 default:
3524 PyErr_SetString(PyExc_SystemError,
3525 "param invalid for local variable");
3526 return 0;
3527 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003528 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 return 1;
3530 case OP_GLOBAL:
3531 switch (ctx) {
3532 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003533 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003534 op = STORE_GLOBAL;
3535 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 case Del: op = DELETE_GLOBAL; break;
3537 case AugLoad:
3538 case AugStore:
3539 break;
3540 case Param:
3541 default:
3542 PyErr_SetString(PyExc_SystemError,
3543 "param invalid for global variable");
3544 return 0;
3545 }
3546 break;
3547 case OP_NAME:
3548 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003549 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003550 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003551 op = STORE_NAME;
3552 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 case Del: op = DELETE_NAME; break;
3554 case AugLoad:
3555 case AugStore:
3556 break;
3557 case Param:
3558 default:
3559 PyErr_SetString(PyExc_SystemError,
3560 "param invalid for name variable");
3561 return 0;
3562 }
3563 break;
3564 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 assert(op);
3567 arg = compiler_add_o(c, dict, mangled);
3568 Py_DECREF(mangled);
3569 if (arg < 0)
3570 return 0;
3571 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572}
3573
3574static int
3575compiler_boolop(struct compiler *c, expr_ty e)
3576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003578 int jumpi;
3579 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 assert(e->kind == BoolOp_kind);
3583 if (e->v.BoolOp.op == And)
3584 jumpi = JUMP_IF_FALSE_OR_POP;
3585 else
3586 jumpi = JUMP_IF_TRUE_OR_POP;
3587 end = compiler_new_block(c);
3588 if (end == NULL)
3589 return 0;
3590 s = e->v.BoolOp.values;
3591 n = asdl_seq_LEN(s) - 1;
3592 assert(n >= 0);
3593 for (i = 0; i < n; ++i) {
3594 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3595 ADDOP_JABS(c, jumpi, end);
3596 }
3597 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3598 compiler_use_next_block(c, end);
3599 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600}
3601
3602static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003603starunpack_helper(struct compiler *c, asdl_seq *elts,
3604 int single_op, int inner_op, int outer_op)
3605{
3606 Py_ssize_t n = asdl_seq_LEN(elts);
3607 Py_ssize_t i, nsubitems = 0, nseen = 0;
3608 for (i = 0; i < n; i++) {
3609 expr_ty elt = asdl_seq_GET(elts, i);
3610 if (elt->kind == Starred_kind) {
3611 if (nseen) {
3612 ADDOP_I(c, inner_op, nseen);
3613 nseen = 0;
3614 nsubitems++;
3615 }
3616 VISIT(c, expr, elt->v.Starred.value);
3617 nsubitems++;
3618 }
3619 else {
3620 VISIT(c, expr, elt);
3621 nseen++;
3622 }
3623 }
3624 if (nsubitems) {
3625 if (nseen) {
3626 ADDOP_I(c, inner_op, nseen);
3627 nsubitems++;
3628 }
3629 ADDOP_I(c, outer_op, nsubitems);
3630 }
3631 else
3632 ADDOP_I(c, single_op, nseen);
3633 return 1;
3634}
3635
3636static int
3637assignment_helper(struct compiler *c, asdl_seq *elts)
3638{
3639 Py_ssize_t n = asdl_seq_LEN(elts);
3640 Py_ssize_t i;
3641 int seen_star = 0;
3642 for (i = 0; i < n; i++) {
3643 expr_ty elt = asdl_seq_GET(elts, i);
3644 if (elt->kind == Starred_kind && !seen_star) {
3645 if ((i >= (1 << 8)) ||
3646 (n-i-1 >= (INT_MAX >> 8)))
3647 return compiler_error(c,
3648 "too many expressions in "
3649 "star-unpacking assignment");
3650 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3651 seen_star = 1;
3652 asdl_seq_SET(elts, i, elt->v.Starred.value);
3653 }
3654 else if (elt->kind == Starred_kind) {
3655 return compiler_error(c,
3656 "two starred expressions in assignment");
3657 }
3658 }
3659 if (!seen_star) {
3660 ADDOP_I(c, UNPACK_SEQUENCE, n);
3661 }
3662 VISIT_SEQ(c, expr, elts);
3663 return 1;
3664}
3665
3666static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667compiler_list(struct compiler *c, expr_ty e)
3668{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003669 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003670 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003671 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003673 else if (e->v.List.ctx == Load) {
3674 return starunpack_helper(c, elts,
3675 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003677 else
3678 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680}
3681
3682static int
3683compiler_tuple(struct compiler *c, expr_ty e)
3684{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003685 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003686 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687 return assignment_helper(c, elts);
3688 }
3689 else if (e->v.Tuple.ctx == Load) {
3690 return starunpack_helper(c, elts,
3691 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3692 }
3693 else
3694 VISIT_SEQ(c, expr, elts);
3695 return 1;
3696}
3697
3698static int
3699compiler_set(struct compiler *c, expr_ty e)
3700{
3701 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3702 BUILD_SET, BUILD_SET_UNPACK);
3703}
3704
3705static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003706are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3707{
3708 Py_ssize_t i;
3709 for (i = begin; i < end; i++) {
3710 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003711 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003712 return 0;
3713 }
3714 return 1;
3715}
3716
3717static int
3718compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3719{
3720 Py_ssize_t i, n = end - begin;
3721 PyObject *keys, *key;
3722 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3723 for (i = begin; i < end; i++) {
3724 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3725 }
3726 keys = PyTuple_New(n);
3727 if (keys == NULL) {
3728 return 0;
3729 }
3730 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003731 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003732 Py_INCREF(key);
3733 PyTuple_SET_ITEM(keys, i - begin, key);
3734 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003735 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003736 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3737 }
3738 else {
3739 for (i = begin; i < end; i++) {
3740 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3741 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3742 }
3743 ADDOP_I(c, BUILD_MAP, n);
3744 }
3745 return 1;
3746}
3747
3748static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749compiler_dict(struct compiler *c, expr_ty e)
3750{
Victor Stinner976bb402016-03-23 11:36:19 +01003751 Py_ssize_t i, n, elements;
3752 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 int is_unpacking = 0;
3754 n = asdl_seq_LEN(e->v.Dict.values);
3755 containers = 0;
3756 elements = 0;
3757 for (i = 0; i < n; i++) {
3758 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3759 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003760 if (!compiler_subdict(c, e, i - elements, i))
3761 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 containers++;
3763 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 if (is_unpacking) {
3766 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3767 containers++;
3768 }
3769 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003770 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 }
3772 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003774 if (!compiler_subdict(c, e, n - elements, n))
3775 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003776 containers++;
3777 }
3778 /* If there is more than one dict, they need to be merged into a new
3779 * dict. If there is one dict and it's an unpacking, then it needs
3780 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003781 if (containers > 1 || is_unpacking) {
3782 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 }
3784 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785}
3786
3787static int
3788compiler_compare(struct compiler *c, expr_ty e)
3789{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003790 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003792 if (!check_compare(c, e)) {
3793 return 0;
3794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003796 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3797 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3798 if (n == 0) {
3799 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3800 ADDOP_I(c, COMPARE_OP,
3801 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3802 }
3803 else {
3804 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 if (cleanup == NULL)
3806 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003807 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 VISIT(c, expr,
3809 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003810 ADDOP(c, DUP_TOP);
3811 ADDOP(c, ROT_THREE);
3812 ADDOP_I(c, COMPARE_OP,
3813 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3814 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3815 NEXT_BLOCK(c);
3816 }
3817 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3818 ADDOP_I(c, COMPARE_OP,
3819 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 basicblock *end = compiler_new_block(c);
3821 if (end == NULL)
3822 return 0;
3823 ADDOP_JREL(c, JUMP_FORWARD, end);
3824 compiler_use_next_block(c, cleanup);
3825 ADDOP(c, ROT_TWO);
3826 ADDOP(c, POP_TOP);
3827 compiler_use_next_block(c, end);
3828 }
3829 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830}
3831
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003832static PyTypeObject *
3833infer_type(expr_ty e)
3834{
3835 switch (e->kind) {
3836 case Tuple_kind:
3837 return &PyTuple_Type;
3838 case List_kind:
3839 case ListComp_kind:
3840 return &PyList_Type;
3841 case Dict_kind:
3842 case DictComp_kind:
3843 return &PyDict_Type;
3844 case Set_kind:
3845 case SetComp_kind:
3846 return &PySet_Type;
3847 case GeneratorExp_kind:
3848 return &PyGen_Type;
3849 case Lambda_kind:
3850 return &PyFunction_Type;
3851 case JoinedStr_kind:
3852 case FormattedValue_kind:
3853 return &PyUnicode_Type;
3854 case Constant_kind:
3855 return e->v.Constant.value->ob_type;
3856 default:
3857 return NULL;
3858 }
3859}
3860
3861static int
3862check_caller(struct compiler *c, expr_ty e)
3863{
3864 switch (e->kind) {
3865 case Constant_kind:
3866 case Tuple_kind:
3867 case List_kind:
3868 case ListComp_kind:
3869 case Dict_kind:
3870 case DictComp_kind:
3871 case Set_kind:
3872 case SetComp_kind:
3873 case GeneratorExp_kind:
3874 case JoinedStr_kind:
3875 case FormattedValue_kind:
3876 return compiler_warn(c, "'%.200s' object is not callable; "
3877 "perhaps you missed a comma?",
3878 infer_type(e)->tp_name);
3879 default:
3880 return 1;
3881 }
3882}
3883
3884static int
3885check_subscripter(struct compiler *c, expr_ty e)
3886{
3887 PyObject *v;
3888
3889 switch (e->kind) {
3890 case Constant_kind:
3891 v = e->v.Constant.value;
3892 if (!(v == Py_None || v == Py_Ellipsis ||
3893 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3894 PyAnySet_Check(v)))
3895 {
3896 return 1;
3897 }
3898 /* fall through */
3899 case Set_kind:
3900 case SetComp_kind:
3901 case GeneratorExp_kind:
3902 case Lambda_kind:
3903 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3904 "perhaps you missed a comma?",
3905 infer_type(e)->tp_name);
3906 default:
3907 return 1;
3908 }
3909}
3910
3911static int
3912check_index(struct compiler *c, expr_ty e, slice_ty s)
3913{
3914 PyObject *v;
3915
3916 if (s->kind != Index_kind) {
3917 return 1;
3918 }
3919 PyTypeObject *index_type = infer_type(s->v.Index.value);
3920 if (index_type == NULL
3921 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3922 || index_type == &PySlice_Type) {
3923 return 1;
3924 }
3925
3926 switch (e->kind) {
3927 case Constant_kind:
3928 v = e->v.Constant.value;
3929 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3930 return 1;
3931 }
3932 /* fall through */
3933 case Tuple_kind:
3934 case List_kind:
3935 case ListComp_kind:
3936 case JoinedStr_kind:
3937 case FormattedValue_kind:
3938 return compiler_warn(c, "%.200s indices must be integers or slices, "
3939 "not %.200s; "
3940 "perhaps you missed a comma?",
3941 infer_type(e)->tp_name,
3942 index_type->tp_name);
3943 default:
3944 return 1;
3945 }
3946}
3947
Zackery Spytz97f5de02019-03-22 01:30:32 -06003948// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003950maybe_optimize_method_call(struct compiler *c, expr_ty e)
3951{
3952 Py_ssize_t argsl, i;
3953 expr_ty meth = e->v.Call.func;
3954 asdl_seq *args = e->v.Call.args;
3955
3956 /* Check that the call node is an attribute access, and that
3957 the call doesn't have keyword parameters. */
3958 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3959 asdl_seq_LEN(e->v.Call.keywords))
3960 return -1;
3961
3962 /* Check that there are no *varargs types of arguments. */
3963 argsl = asdl_seq_LEN(args);
3964 for (i = 0; i < argsl; i++) {
3965 expr_ty elt = asdl_seq_GET(args, i);
3966 if (elt->kind == Starred_kind) {
3967 return -1;
3968 }
3969 }
3970
3971 /* Alright, we can optimize the code. */
3972 VISIT(c, expr, meth->v.Attribute.value);
3973 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3974 VISIT_SEQ(c, expr, e->v.Call.args);
3975 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3976 return 1;
3977}
3978
3979static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980compiler_call(struct compiler *c, expr_ty e)
3981{
Zackery Spytz97f5de02019-03-22 01:30:32 -06003982 int ret = maybe_optimize_method_call(c, e);
3983 if (ret >= 0) {
3984 return ret;
3985 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003986 if (!check_caller(c, e->v.Call.func)) {
3987 return 0;
3988 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 VISIT(c, expr, e->v.Call.func);
3990 return compiler_call_helper(c, 0,
3991 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003992 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003993}
3994
Eric V. Smith235a6f02015-09-19 14:51:32 -04003995static int
3996compiler_joined_str(struct compiler *c, expr_ty e)
3997{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003998 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003999 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4000 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004001 return 1;
4002}
4003
Eric V. Smitha78c7952015-11-03 12:45:05 -05004004/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004005static int
4006compiler_formatted_value(struct compiler *c, expr_ty e)
4007{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004008 /* Our oparg encodes 2 pieces of information: the conversion
4009 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004010
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004011 Convert the conversion char to 3 bits:
4012 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004013 !s : 001 0x1 FVC_STR
4014 !r : 010 0x2 FVC_REPR
4015 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004016
Eric V. Smitha78c7952015-11-03 12:45:05 -05004017 next bit is whether or not we have a format spec:
4018 yes : 100 0x4
4019 no : 000 0x0
4020 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004021
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004022 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004023 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004024
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004025 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004026 VISIT(c, expr, e->v.FormattedValue.value);
4027
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004028 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004029 case 's': oparg = FVC_STR; break;
4030 case 'r': oparg = FVC_REPR; break;
4031 case 'a': oparg = FVC_ASCII; break;
4032 case -1: oparg = FVC_NONE; break;
4033 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004034 PyErr_Format(PyExc_SystemError,
4035 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004036 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004037 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004038 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004039 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004040 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004041 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004042 }
4043
Eric V. Smitha78c7952015-11-03 12:45:05 -05004044 /* And push our opcode and oparg */
4045 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004046
Eric V. Smith235a6f02015-09-19 14:51:32 -04004047 return 1;
4048}
4049
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004050static int
4051compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4052{
4053 Py_ssize_t i, n = end - begin;
4054 keyword_ty kw;
4055 PyObject *keys, *key;
4056 assert(n > 0);
4057 if (n > 1) {
4058 for (i = begin; i < end; i++) {
4059 kw = asdl_seq_GET(keywords, i);
4060 VISIT(c, expr, kw->value);
4061 }
4062 keys = PyTuple_New(n);
4063 if (keys == NULL) {
4064 return 0;
4065 }
4066 for (i = begin; i < end; i++) {
4067 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4068 Py_INCREF(key);
4069 PyTuple_SET_ITEM(keys, i - begin, key);
4070 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004071 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004072 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4073 }
4074 else {
4075 /* a for loop only executes once */
4076 for (i = begin; i < end; i++) {
4077 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004078 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004079 VISIT(c, expr, kw->value);
4080 }
4081 ADDOP_I(c, BUILD_MAP, n);
4082 }
4083 return 1;
4084}
4085
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004086/* shared code between compiler_call and compiler_class */
4087static int
4088compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004089 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004090 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004091 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004092{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004093 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004094 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004095
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004096 /* the number of tuples and dictionaries on the stack */
4097 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4098
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004099 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004100 nkwelts = asdl_seq_LEN(keywords);
4101
4102 for (i = 0; i < nkwelts; i++) {
4103 keyword_ty kw = asdl_seq_GET(keywords, i);
4104 if (kw->arg == NULL) {
4105 mustdictunpack = 1;
4106 break;
4107 }
4108 }
4109
4110 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004111 for (i = 0; i < nelts; i++) {
4112 expr_ty elt = asdl_seq_GET(args, i);
4113 if (elt->kind == Starred_kind) {
4114 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004115 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004116 if (nseen) {
4117 ADDOP_I(c, BUILD_TUPLE, nseen);
4118 nseen = 0;
4119 nsubargs++;
4120 }
4121 VISIT(c, expr, elt->v.Starred.value);
4122 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004123 }
4124 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004125 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004126 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004129
4130 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004131 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004132 if (nseen) {
4133 /* Pack up any trailing positional arguments. */
4134 ADDOP_I(c, BUILD_TUPLE, nseen);
4135 nsubargs++;
4136 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004137 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004138 /* If we ended up with more than one stararg, we need
4139 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004140 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004141 }
4142 else if (nsubargs == 0) {
4143 ADDOP_I(c, BUILD_TUPLE, 0);
4144 }
4145 nseen = 0; /* the number of keyword arguments on the stack following */
4146 for (i = 0; i < nkwelts; i++) {
4147 keyword_ty kw = asdl_seq_GET(keywords, i);
4148 if (kw->arg == NULL) {
4149 /* A keyword argument unpacking. */
4150 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004151 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4152 return 0;
4153 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004154 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004155 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004156 VISIT(c, expr, kw->value);
4157 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004158 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004159 else {
4160 nseen++;
4161 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004162 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004163 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004164 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004165 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004166 return 0;
4167 nsubkwargs++;
4168 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004169 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004170 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004171 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004172 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004173 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4174 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004176 else if (nkwelts) {
4177 PyObject *names;
4178 VISIT_SEQ(c, keyword, keywords);
4179 names = PyTuple_New(nkwelts);
4180 if (names == NULL) {
4181 return 0;
4182 }
4183 for (i = 0; i < nkwelts; i++) {
4184 keyword_ty kw = asdl_seq_GET(keywords, i);
4185 Py_INCREF(kw->arg);
4186 PyTuple_SET_ITEM(names, i, kw->arg);
4187 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004188 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004189 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4190 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004192 else {
4193 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4194 return 1;
4195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196}
4197
Nick Coghlan650f0d02007-04-15 12:05:43 +00004198
4199/* List and set comprehensions and generator expressions work by creating a
4200 nested function to perform the actual iteration. This means that the
4201 iteration variables don't leak into the current scope.
4202 The defined function is called immediately following its definition, with the
4203 result of that call being the result of the expression.
4204 The LC/SC version returns the populated container, while the GE version is
4205 flagged in symtable.c as a generator, so it returns the generator object
4206 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004207
4208 Possible cleanups:
4209 - iterate over the generator sequence instead of using recursion
4210*/
4211
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004212
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214compiler_comprehension_generator(struct compiler *c,
4215 asdl_seq *generators, int gen_index,
4216 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004217{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004218 comprehension_ty gen;
4219 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4220 if (gen->is_async) {
4221 return compiler_async_comprehension_generator(
4222 c, generators, gen_index, elt, val, type);
4223 } else {
4224 return compiler_sync_comprehension_generator(
4225 c, generators, gen_index, elt, val, type);
4226 }
4227}
4228
4229static int
4230compiler_sync_comprehension_generator(struct compiler *c,
4231 asdl_seq *generators, int gen_index,
4232 expr_ty elt, expr_ty val, int type)
4233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 /* generate code for the iterator, then each of the ifs,
4235 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 comprehension_ty gen;
4238 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004239 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 start = compiler_new_block(c);
4242 skip = compiler_new_block(c);
4243 if_cleanup = compiler_new_block(c);
4244 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4247 anchor == NULL)
4248 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 if (gen_index == 0) {
4253 /* Receive outermost iter as an implicit argument */
4254 c->u->u_argcount = 1;
4255 ADDOP_I(c, LOAD_FAST, 0);
4256 }
4257 else {
4258 /* Sub-iter - calculate on the fly */
4259 VISIT(c, expr, gen->iter);
4260 ADDOP(c, GET_ITER);
4261 }
4262 compiler_use_next_block(c, start);
4263 ADDOP_JREL(c, FOR_ITER, anchor);
4264 NEXT_BLOCK(c);
4265 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 /* XXX this needs to be cleaned up...a lot! */
4268 n = asdl_seq_LEN(gen->ifs);
4269 for (i = 0; i < n; i++) {
4270 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004271 if (!compiler_jump_if(c, e, if_cleanup, 0))
4272 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 NEXT_BLOCK(c);
4274 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 if (++gen_index < asdl_seq_LEN(generators))
4277 if (!compiler_comprehension_generator(c,
4278 generators, gen_index,
4279 elt, val, type))
4280 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 /* only append after the last for generator */
4283 if (gen_index >= asdl_seq_LEN(generators)) {
4284 /* comprehension specific code */
4285 switch (type) {
4286 case COMP_GENEXP:
4287 VISIT(c, expr, elt);
4288 ADDOP(c, YIELD_VALUE);
4289 ADDOP(c, POP_TOP);
4290 break;
4291 case COMP_LISTCOMP:
4292 VISIT(c, expr, elt);
4293 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4294 break;
4295 case COMP_SETCOMP:
4296 VISIT(c, expr, elt);
4297 ADDOP_I(c, SET_ADD, gen_index + 1);
4298 break;
4299 case COMP_DICTCOMP:
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004300 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 VISIT(c, expr, elt);
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004303 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 ADDOP_I(c, MAP_ADD, gen_index + 1);
4305 break;
4306 default:
4307 return 0;
4308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 compiler_use_next_block(c, skip);
4311 }
4312 compiler_use_next_block(c, if_cleanup);
4313 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4314 compiler_use_next_block(c, anchor);
4315
4316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317}
4318
4319static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004320compiler_async_comprehension_generator(struct compiler *c,
4321 asdl_seq *generators, int gen_index,
4322 expr_ty elt, expr_ty val, int type)
4323{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004324 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004325 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004326 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004327 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004328 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004329 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004330
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004331 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004332 return 0;
4333 }
4334
4335 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4336
4337 if (gen_index == 0) {
4338 /* Receive outermost iter as an implicit argument */
4339 c->u->u_argcount = 1;
4340 ADDOP_I(c, LOAD_FAST, 0);
4341 }
4342 else {
4343 /* Sub-iter - calculate on the fly */
4344 VISIT(c, expr, gen->iter);
4345 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004346 }
4347
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004348 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004349
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004350 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004351 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004352 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004353 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004354 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004355 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004356
4357 n = asdl_seq_LEN(gen->ifs);
4358 for (i = 0; i < n; i++) {
4359 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004360 if (!compiler_jump_if(c, e, if_cleanup, 0))
4361 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004362 NEXT_BLOCK(c);
4363 }
4364
4365 if (++gen_index < asdl_seq_LEN(generators))
4366 if (!compiler_comprehension_generator(c,
4367 generators, gen_index,
4368 elt, val, type))
4369 return 0;
4370
4371 /* only append after the last for generator */
4372 if (gen_index >= asdl_seq_LEN(generators)) {
4373 /* comprehension specific code */
4374 switch (type) {
4375 case COMP_GENEXP:
4376 VISIT(c, expr, elt);
4377 ADDOP(c, YIELD_VALUE);
4378 ADDOP(c, POP_TOP);
4379 break;
4380 case COMP_LISTCOMP:
4381 VISIT(c, expr, elt);
4382 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4383 break;
4384 case COMP_SETCOMP:
4385 VISIT(c, expr, elt);
4386 ADDOP_I(c, SET_ADD, gen_index + 1);
4387 break;
4388 case COMP_DICTCOMP:
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004389 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004390 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004391 VISIT(c, expr, elt);
Miss Islington (bot)874ff652019-06-22 15:34:03 -07004392 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004393 ADDOP_I(c, MAP_ADD, gen_index + 1);
4394 break;
4395 default:
4396 return 0;
4397 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004398 }
4399 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004400 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4401
4402 compiler_use_next_block(c, except);
4403 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004404
4405 return 1;
4406}
4407
4408static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004409compiler_comprehension(struct compiler *c, expr_ty e, int type,
4410 identifier name, asdl_seq *generators, expr_ty elt,
4411 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004414 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004415 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004416 int is_async_function = c->u->u_ste->ste_coroutine;
4417 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004418
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004419 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004420
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004421 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4422 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004423 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425 }
4426
4427 is_async_generator = c->u->u_ste->ste_coroutine;
4428
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004429 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004430 compiler_error(c, "asynchronous comprehension outside of "
4431 "an asynchronous function");
4432 goto error_in_scope;
4433 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (type != COMP_GENEXP) {
4436 int op;
4437 switch (type) {
4438 case COMP_LISTCOMP:
4439 op = BUILD_LIST;
4440 break;
4441 case COMP_SETCOMP:
4442 op = BUILD_SET;
4443 break;
4444 case COMP_DICTCOMP:
4445 op = BUILD_MAP;
4446 break;
4447 default:
4448 PyErr_Format(PyExc_SystemError,
4449 "unknown comprehension type %d", type);
4450 goto error_in_scope;
4451 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 ADDOP_I(c, op, 0);
4454 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 if (!compiler_comprehension_generator(c, generators, 0, elt,
4457 val, type))
4458 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 if (type != COMP_GENEXP) {
4461 ADDOP(c, RETURN_VALUE);
4462 }
4463
4464 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004465 qualname = c->u->u_qualname;
4466 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004468 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 goto error;
4470
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004471 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004473 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 Py_DECREF(co);
4475
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004476 VISIT(c, expr, outermost->iter);
4477
4478 if (outermost->is_async) {
4479 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480 } else {
4481 ADDOP(c, GET_ITER);
4482 }
4483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004485
4486 if (is_async_generator && type != COMP_GENEXP) {
4487 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004488 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004489 ADDOP(c, YIELD_FROM);
4490 }
4491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004493error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004495error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004496 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 Py_XDECREF(co);
4498 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004499}
4500
4501static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004502compiler_genexp(struct compiler *c, expr_ty e)
4503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 static identifier name;
4505 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004506 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 if (!name)
4508 return 0;
4509 }
4510 assert(e->kind == GeneratorExp_kind);
4511 return compiler_comprehension(c, e, COMP_GENEXP, name,
4512 e->v.GeneratorExp.generators,
4513 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004514}
4515
4516static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004517compiler_listcomp(struct compiler *c, expr_ty e)
4518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 static identifier name;
4520 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004521 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 if (!name)
4523 return 0;
4524 }
4525 assert(e->kind == ListComp_kind);
4526 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4527 e->v.ListComp.generators,
4528 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004529}
4530
4531static int
4532compiler_setcomp(struct compiler *c, expr_ty e)
4533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 static identifier name;
4535 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004536 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 if (!name)
4538 return 0;
4539 }
4540 assert(e->kind == SetComp_kind);
4541 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4542 e->v.SetComp.generators,
4543 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004544}
4545
4546
4547static int
4548compiler_dictcomp(struct compiler *c, expr_ty e)
4549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 static identifier name;
4551 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004552 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 if (!name)
4554 return 0;
4555 }
4556 assert(e->kind == DictComp_kind);
4557 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4558 e->v.DictComp.generators,
4559 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004560}
4561
4562
4563static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004564compiler_visit_keyword(struct compiler *c, keyword_ty k)
4565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 VISIT(c, expr, k->value);
4567 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004568}
4569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004571 whether they are true or false.
4572
4573 Return values: 1 for true, 0 for false, -1 for non-constant.
4574 */
4575
4576static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004577expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004578{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004579 if (e->kind == Constant_kind) {
4580 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004581 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004582 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004583}
4584
Yury Selivanov75445082015-05-11 22:57:16 -04004585
4586/*
4587 Implements the async with statement.
4588
4589 The semantics outlined in that PEP are as follows:
4590
4591 async with EXPR as VAR:
4592 BLOCK
4593
4594 It is implemented roughly as:
4595
4596 context = EXPR
4597 exit = context.__aexit__ # not calling it
4598 value = await context.__aenter__()
4599 try:
4600 VAR = value # if VAR present in the syntax
4601 BLOCK
4602 finally:
4603 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004604 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004605 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004606 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004607 if not (await exit(*exc)):
4608 raise
4609 */
4610static int
4611compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4612{
4613 basicblock *block, *finally;
4614 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4615
4616 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004617 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4618 c->u->u_ste->ste_coroutine = 1;
4619 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004620 return compiler_error(c, "'async with' outside async function");
4621 }
Yury Selivanov75445082015-05-11 22:57:16 -04004622
4623 block = compiler_new_block(c);
4624 finally = compiler_new_block(c);
4625 if (!block || !finally)
4626 return 0;
4627
4628 /* Evaluate EXPR */
4629 VISIT(c, expr, item->context_expr);
4630
4631 ADDOP(c, BEFORE_ASYNC_WITH);
4632 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004633 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004634 ADDOP(c, YIELD_FROM);
4635
4636 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4637
4638 /* SETUP_ASYNC_WITH pushes a finally block. */
4639 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004640 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004641 return 0;
4642 }
4643
4644 if (item->optional_vars) {
4645 VISIT(c, expr, item->optional_vars);
4646 }
4647 else {
4648 /* Discard result from context.__aenter__() */
4649 ADDOP(c, POP_TOP);
4650 }
4651
4652 pos++;
4653 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4654 /* BLOCK code */
4655 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4656 else if (!compiler_async_with(c, s, pos))
4657 return 0;
4658
4659 /* End of try block; start the finally block */
4660 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004661 ADDOP(c, BEGIN_FINALLY);
4662 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004663
Yury Selivanov75445082015-05-11 22:57:16 -04004664 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004665 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004666 return 0;
4667
4668 /* Finally block starts; context.__exit__ is on the stack under
4669 the exception or return information. Just issue our magic
4670 opcode. */
4671 ADDOP(c, WITH_CLEANUP_START);
4672
4673 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004674 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004675 ADDOP(c, YIELD_FROM);
4676
4677 ADDOP(c, WITH_CLEANUP_FINISH);
4678
4679 /* Finally block ends. */
4680 ADDOP(c, END_FINALLY);
4681 compiler_pop_fblock(c, FINALLY_END, finally);
4682 return 1;
4683}
4684
4685
Guido van Rossumc2e20742006-02-27 22:32:47 +00004686/*
4687 Implements the with statement from PEP 343.
4688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004690
4691 with EXPR as VAR:
4692 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693
Guido van Rossumc2e20742006-02-27 22:32:47 +00004694 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695
Thomas Wouters477c8d52006-05-27 19:21:47 +00004696 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004697 exit = context.__exit__ # not calling it
4698 value = context.__enter__()
4699 try:
4700 VAR = value # if VAR present in the syntax
4701 BLOCK
4702 finally:
4703 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004704 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004705 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004706 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004707 exit(*exc)
4708 */
4709static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004710compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004711{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004712 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004713 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004714
4715 assert(s->kind == With_kind);
4716
Guido van Rossumc2e20742006-02-27 22:32:47 +00004717 block = compiler_new_block(c);
4718 finally = compiler_new_block(c);
4719 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004720 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004721
Thomas Wouters477c8d52006-05-27 19:21:47 +00004722 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004723 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004724 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004725
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004726 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004727 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004728 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004729 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004730 }
4731
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004732 if (item->optional_vars) {
4733 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004734 }
4735 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004737 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004738 }
4739
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004740 pos++;
4741 if (pos == asdl_seq_LEN(s->v.With.items))
4742 /* BLOCK code */
4743 VISIT_SEQ(c, stmt, s->v.With.body)
4744 else if (!compiler_with(c, s, pos))
4745 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004746
4747 /* End of try block; start the finally block */
4748 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004749 ADDOP(c, BEGIN_FINALLY);
4750 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004751
Guido van Rossumc2e20742006-02-27 22:32:47 +00004752 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004753 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004754 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004755
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004756 /* Finally block starts; context.__exit__ is on the stack under
4757 the exception or return information. Just issue our magic
4758 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004759 ADDOP(c, WITH_CLEANUP_START);
4760 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004761
4762 /* Finally block ends. */
4763 ADDOP(c, END_FINALLY);
4764 compiler_pop_fblock(c, FINALLY_END, finally);
4765 return 1;
4766}
4767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004768static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004769compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004772 case NamedExpr_kind:
4773 VISIT(c, expr, e->v.NamedExpr.value);
4774 ADDOP(c, DUP_TOP);
4775 VISIT(c, expr, e->v.NamedExpr.target);
4776 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 case BoolOp_kind:
4778 return compiler_boolop(c, e);
4779 case BinOp_kind:
4780 VISIT(c, expr, e->v.BinOp.left);
4781 VISIT(c, expr, e->v.BinOp.right);
4782 ADDOP(c, binop(c, e->v.BinOp.op));
4783 break;
4784 case UnaryOp_kind:
4785 VISIT(c, expr, e->v.UnaryOp.operand);
4786 ADDOP(c, unaryop(e->v.UnaryOp.op));
4787 break;
4788 case Lambda_kind:
4789 return compiler_lambda(c, e);
4790 case IfExp_kind:
4791 return compiler_ifexp(c, e);
4792 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004793 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004795 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 case GeneratorExp_kind:
4797 return compiler_genexp(c, e);
4798 case ListComp_kind:
4799 return compiler_listcomp(c, e);
4800 case SetComp_kind:
4801 return compiler_setcomp(c, e);
4802 case DictComp_kind:
4803 return compiler_dictcomp(c, e);
4804 case Yield_kind:
4805 if (c->u->u_ste->ste_type != FunctionBlock)
4806 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004807 if (e->v.Yield.value) {
4808 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 }
4810 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004811 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004813 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004815 case YieldFrom_kind:
4816 if (c->u->u_ste->ste_type != FunctionBlock)
4817 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004818
4819 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4820 return compiler_error(c, "'yield from' inside async function");
4821
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004822 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004823 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004824 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004825 ADDOP(c, YIELD_FROM);
4826 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004827 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004828 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4829 if (c->u->u_ste->ste_type != FunctionBlock){
4830 return compiler_error(c, "'await' outside function");
4831 }
Yury Selivanov75445082015-05-11 22:57:16 -04004832
Victor Stinner331a6a52019-05-27 16:39:22 +02004833 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004834 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4835 return compiler_error(c, "'await' outside async function");
4836 }
4837 }
Yury Selivanov75445082015-05-11 22:57:16 -04004838
4839 VISIT(c, expr, e->v.Await.value);
4840 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004841 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004842 ADDOP(c, YIELD_FROM);
4843 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 case Compare_kind:
4845 return compiler_compare(c, e);
4846 case Call_kind:
4847 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004848 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004849 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004850 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004851 case JoinedStr_kind:
4852 return compiler_joined_str(c, e);
4853 case FormattedValue_kind:
4854 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 /* The following exprs can be assignment targets. */
4856 case Attribute_kind:
4857 if (e->v.Attribute.ctx != AugStore)
4858 VISIT(c, expr, e->v.Attribute.value);
4859 switch (e->v.Attribute.ctx) {
4860 case AugLoad:
4861 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004862 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 case Load:
4864 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4865 break;
4866 case AugStore:
4867 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004868 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 case Store:
4870 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4871 break;
4872 case Del:
4873 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4874 break;
4875 case Param:
4876 default:
4877 PyErr_SetString(PyExc_SystemError,
4878 "param invalid in attribute expression");
4879 return 0;
4880 }
4881 break;
4882 case Subscript_kind:
4883 switch (e->v.Subscript.ctx) {
4884 case AugLoad:
4885 VISIT(c, expr, e->v.Subscript.value);
4886 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4887 break;
4888 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004889 if (!check_subscripter(c, e->v.Subscript.value)) {
4890 return 0;
4891 }
4892 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4893 return 0;
4894 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 VISIT(c, expr, e->v.Subscript.value);
4896 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4897 break;
4898 case AugStore:
4899 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4900 break;
4901 case Store:
4902 VISIT(c, expr, e->v.Subscript.value);
4903 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4904 break;
4905 case Del:
4906 VISIT(c, expr, e->v.Subscript.value);
4907 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4908 break;
4909 case Param:
4910 default:
4911 PyErr_SetString(PyExc_SystemError,
4912 "param invalid in subscript expression");
4913 return 0;
4914 }
4915 break;
4916 case Starred_kind:
4917 switch (e->v.Starred.ctx) {
4918 case Store:
4919 /* In all legitimate cases, the Starred node was already replaced
4920 * by compiler_list/compiler_tuple. XXX: is that okay? */
4921 return compiler_error(c,
4922 "starred assignment target must be in a list or tuple");
4923 default:
4924 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004925 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 case Name_kind:
4928 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4929 /* child nodes of List and Tuple will have expr_context set */
4930 case List_kind:
4931 return compiler_list(c, e);
4932 case Tuple_kind:
4933 return compiler_tuple(c, e);
4934 }
4935 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004936}
4937
4938static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004939compiler_visit_expr(struct compiler *c, expr_ty e)
4940{
4941 /* If expr e has a different line number than the last expr/stmt,
4942 set a new line number for the next instruction.
4943 */
4944 int old_lineno = c->u->u_lineno;
4945 int old_col_offset = c->u->u_col_offset;
4946 if (e->lineno != c->u->u_lineno) {
4947 c->u->u_lineno = e->lineno;
4948 c->u->u_lineno_set = 0;
4949 }
4950 /* Updating the column offset is always harmless. */
4951 c->u->u_col_offset = e->col_offset;
4952
4953 int res = compiler_visit_expr1(c, e);
4954
4955 if (old_lineno != c->u->u_lineno) {
4956 c->u->u_lineno = old_lineno;
4957 c->u->u_lineno_set = 0;
4958 }
4959 c->u->u_col_offset = old_col_offset;
4960 return res;
4961}
4962
4963static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004964compiler_augassign(struct compiler *c, stmt_ty s)
4965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 expr_ty e = s->v.AugAssign.target;
4967 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 switch (e->kind) {
4972 case Attribute_kind:
4973 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004974 AugLoad, e->lineno, e->col_offset,
4975 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 if (auge == NULL)
4977 return 0;
4978 VISIT(c, expr, auge);
4979 VISIT(c, expr, s->v.AugAssign.value);
4980 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4981 auge->v.Attribute.ctx = AugStore;
4982 VISIT(c, expr, auge);
4983 break;
4984 case Subscript_kind:
4985 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004986 AugLoad, e->lineno, e->col_offset,
4987 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 if (auge == NULL)
4989 return 0;
4990 VISIT(c, expr, auge);
4991 VISIT(c, expr, s->v.AugAssign.value);
4992 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4993 auge->v.Subscript.ctx = AugStore;
4994 VISIT(c, expr, auge);
4995 break;
4996 case Name_kind:
4997 if (!compiler_nameop(c, e->v.Name.id, Load))
4998 return 0;
4999 VISIT(c, expr, s->v.AugAssign.value);
5000 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5001 return compiler_nameop(c, e->v.Name.id, Store);
5002 default:
5003 PyErr_Format(PyExc_SystemError,
5004 "invalid node type (%d) for augmented assignment",
5005 e->kind);
5006 return 0;
5007 }
5008 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005009}
5010
5011static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005012check_ann_expr(struct compiler *c, expr_ty e)
5013{
5014 VISIT(c, expr, e);
5015 ADDOP(c, POP_TOP);
5016 return 1;
5017}
5018
5019static int
5020check_annotation(struct compiler *c, stmt_ty s)
5021{
5022 /* Annotations are only evaluated in a module or class. */
5023 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5024 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5025 return check_ann_expr(c, s->v.AnnAssign.annotation);
5026 }
5027 return 1;
5028}
5029
5030static int
5031check_ann_slice(struct compiler *c, slice_ty sl)
5032{
5033 switch(sl->kind) {
5034 case Index_kind:
5035 return check_ann_expr(c, sl->v.Index.value);
5036 case Slice_kind:
5037 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5038 return 0;
5039 }
5040 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5041 return 0;
5042 }
5043 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5044 return 0;
5045 }
5046 break;
5047 default:
5048 PyErr_SetString(PyExc_SystemError,
5049 "unexpected slice kind");
5050 return 0;
5051 }
5052 return 1;
5053}
5054
5055static int
5056check_ann_subscr(struct compiler *c, slice_ty sl)
5057{
5058 /* We check that everything in a subscript is defined at runtime. */
5059 Py_ssize_t i, n;
5060
5061 switch (sl->kind) {
5062 case Index_kind:
5063 case Slice_kind:
5064 if (!check_ann_slice(c, sl)) {
5065 return 0;
5066 }
5067 break;
5068 case ExtSlice_kind:
5069 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5070 for (i = 0; i < n; i++) {
5071 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5072 switch (subsl->kind) {
5073 case Index_kind:
5074 case Slice_kind:
5075 if (!check_ann_slice(c, subsl)) {
5076 return 0;
5077 }
5078 break;
5079 case ExtSlice_kind:
5080 default:
5081 PyErr_SetString(PyExc_SystemError,
5082 "extended slice invalid in nested slice");
5083 return 0;
5084 }
5085 }
5086 break;
5087 default:
5088 PyErr_Format(PyExc_SystemError,
5089 "invalid subscript kind %d", sl->kind);
5090 return 0;
5091 }
5092 return 1;
5093}
5094
5095static int
5096compiler_annassign(struct compiler *c, stmt_ty s)
5097{
5098 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005099 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005100
5101 assert(s->kind == AnnAssign_kind);
5102
5103 /* We perform the actual assignment first. */
5104 if (s->v.AnnAssign.value) {
5105 VISIT(c, expr, s->v.AnnAssign.value);
5106 VISIT(c, expr, targ);
5107 }
5108 switch (targ->kind) {
5109 case Name_kind:
5110 /* If we have a simple name in a module or class, store annotation. */
5111 if (s->v.AnnAssign.simple &&
5112 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5113 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005114 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5115 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5116 }
5117 else {
5118 VISIT(c, expr, s->v.AnnAssign.annotation);
5119 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005120 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005121 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005122 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005123 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005124 }
5125 break;
5126 case Attribute_kind:
5127 if (!s->v.AnnAssign.value &&
5128 !check_ann_expr(c, targ->v.Attribute.value)) {
5129 return 0;
5130 }
5131 break;
5132 case Subscript_kind:
5133 if (!s->v.AnnAssign.value &&
5134 (!check_ann_expr(c, targ->v.Subscript.value) ||
5135 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5136 return 0;
5137 }
5138 break;
5139 default:
5140 PyErr_Format(PyExc_SystemError,
5141 "invalid node type (%d) for annotated assignment",
5142 targ->kind);
5143 return 0;
5144 }
5145 /* Annotation is evaluated last. */
5146 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5147 return 0;
5148 }
5149 return 1;
5150}
5151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005152/* Raises a SyntaxError and returns 0.
5153 If something goes wrong, a different exception may be raised.
5154*/
5155
5156static int
5157compiler_error(struct compiler *c, const char *errstr)
5158{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005159 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005161
Victor Stinner14e461d2013-08-26 22:28:21 +02005162 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 if (!loc) {
5164 Py_INCREF(Py_None);
5165 loc = Py_None;
5166 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005167 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005168 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 if (!u)
5170 goto exit;
5171 v = Py_BuildValue("(zO)", errstr, u);
5172 if (!v)
5173 goto exit;
5174 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005175 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 Py_DECREF(loc);
5177 Py_XDECREF(u);
5178 Py_XDECREF(v);
5179 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005180}
5181
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005182/* Emits a SyntaxWarning and returns 1 on success.
5183 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5184 and returns 0.
5185*/
5186static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005187compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005188{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005189 va_list vargs;
5190#ifdef HAVE_STDARG_PROTOTYPES
5191 va_start(vargs, format);
5192#else
5193 va_start(vargs);
5194#endif
5195 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5196 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005197 if (msg == NULL) {
5198 return 0;
5199 }
5200 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5201 c->u->u_lineno, NULL, NULL) < 0)
5202 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005203 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005204 /* Replace the SyntaxWarning exception with a SyntaxError
5205 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005206 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005207 assert(PyUnicode_AsUTF8(msg) != NULL);
5208 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005209 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005210 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005211 return 0;
5212 }
5213 Py_DECREF(msg);
5214 return 1;
5215}
5216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005217static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218compiler_handle_subscr(struct compiler *c, const char *kind,
5219 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 /* XXX this code is duplicated */
5224 switch (ctx) {
5225 case AugLoad: /* fall through to Load */
5226 case Load: op = BINARY_SUBSCR; break;
5227 case AugStore:/* fall through to Store */
5228 case Store: op = STORE_SUBSCR; break;
5229 case Del: op = DELETE_SUBSCR; break;
5230 case Param:
5231 PyErr_Format(PyExc_SystemError,
5232 "invalid %s kind %d in subscript\n",
5233 kind, ctx);
5234 return 0;
5235 }
5236 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005237 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 }
5239 else if (ctx == AugStore) {
5240 ADDOP(c, ROT_THREE);
5241 }
5242 ADDOP(c, op);
5243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005244}
5245
5246static int
5247compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 int n = 2;
5250 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 /* only handles the cases where BUILD_SLICE is emitted */
5253 if (s->v.Slice.lower) {
5254 VISIT(c, expr, s->v.Slice.lower);
5255 }
5256 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005257 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 if (s->v.Slice.upper) {
5261 VISIT(c, expr, s->v.Slice.upper);
5262 }
5263 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005264 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 }
5266
5267 if (s->v.Slice.step) {
5268 n++;
5269 VISIT(c, expr, s->v.Slice.step);
5270 }
5271 ADDOP_I(c, BUILD_SLICE, n);
5272 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005273}
5274
5275static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5277 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 switch (s->kind) {
5280 case Slice_kind:
5281 return compiler_slice(c, s, ctx);
5282 case Index_kind:
5283 VISIT(c, expr, s->v.Index.value);
5284 break;
5285 case ExtSlice_kind:
5286 default:
5287 PyErr_SetString(PyExc_SystemError,
5288 "extended slice invalid in nested slice");
5289 return 0;
5290 }
5291 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005292}
5293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005294static int
5295compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5296{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005297 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 switch (s->kind) {
5299 case Index_kind:
5300 kindname = "index";
5301 if (ctx != AugStore) {
5302 VISIT(c, expr, s->v.Index.value);
5303 }
5304 break;
5305 case Slice_kind:
5306 kindname = "slice";
5307 if (ctx != AugStore) {
5308 if (!compiler_slice(c, s, ctx))
5309 return 0;
5310 }
5311 break;
5312 case ExtSlice_kind:
5313 kindname = "extended slice";
5314 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005315 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 for (i = 0; i < n; i++) {
5317 slice_ty sub = (slice_ty)asdl_seq_GET(
5318 s->v.ExtSlice.dims, i);
5319 if (!compiler_visit_nested_slice(c, sub, ctx))
5320 return 0;
5321 }
5322 ADDOP_I(c, BUILD_TUPLE, n);
5323 }
5324 break;
5325 default:
5326 PyErr_Format(PyExc_SystemError,
5327 "invalid subscript kind %d", s->kind);
5328 return 0;
5329 }
5330 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005331}
5332
Thomas Wouters89f507f2006-12-13 04:49:30 +00005333/* End of the compiler section, beginning of the assembler section */
5334
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005335/* do depth-first search of basic block graph, starting with block.
5336 post records the block indices in post-order.
5337
5338 XXX must handle implicit jumps from one block to next
5339*/
5340
Thomas Wouters89f507f2006-12-13 04:49:30 +00005341struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 PyObject *a_bytecode; /* string containing bytecode */
5343 int a_offset; /* offset into bytecode */
5344 int a_nblocks; /* number of reachable blocks */
5345 basicblock **a_postorder; /* list of blocks in dfs postorder */
5346 PyObject *a_lnotab; /* string containing lnotab */
5347 int a_lnotab_off; /* offset into lnotab */
5348 int a_lineno; /* last lineno of emitted instruction */
5349 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005350};
5351
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005352static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005353dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005354{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005355 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005356
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005357 /* Get rid of recursion for normal control flow.
5358 Since the number of blocks is limited, unused space in a_postorder
5359 (from a_nblocks to end) can be used as a stack for still not ordered
5360 blocks. */
5361 for (j = end; b && !b->b_seen; b = b->b_next) {
5362 b->b_seen = 1;
5363 assert(a->a_nblocks < j);
5364 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005366 while (j < end) {
5367 b = a->a_postorder[j++];
5368 for (i = 0; i < b->b_iused; i++) {
5369 struct instr *instr = &b->b_instr[i];
5370 if (instr->i_jrel || instr->i_jabs)
5371 dfs(c, instr->i_target, a, j);
5372 }
5373 assert(a->a_nblocks < j);
5374 a->a_postorder[a->a_nblocks++] = b;
5375 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005376}
5377
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005378Py_LOCAL_INLINE(void)
5379stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005380{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005381 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005382 if (b->b_startdepth < depth) {
5383 assert(b->b_startdepth < 0);
5384 b->b_startdepth = depth;
5385 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387}
5388
5389/* Find the flow path that needs the largest stack. We assume that
5390 * cycles in the flow graph have no net effect on the stack depth.
5391 */
5392static int
5393stackdepth(struct compiler *c)
5394{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005395 basicblock *b, *entryblock = NULL;
5396 basicblock **stack, **sp;
5397 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 b->b_startdepth = INT_MIN;
5400 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005401 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 }
5403 if (!entryblock)
5404 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005405 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5406 if (!stack) {
5407 PyErr_NoMemory();
5408 return -1;
5409 }
5410
5411 sp = stack;
5412 stackdepth_push(&sp, entryblock, 0);
5413 while (sp != stack) {
5414 b = *--sp;
5415 int depth = b->b_startdepth;
5416 assert(depth >= 0);
5417 basicblock *next = b->b_next;
5418 for (int i = 0; i < b->b_iused; i++) {
5419 struct instr *instr = &b->b_instr[i];
5420 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5421 if (effect == PY_INVALID_STACK_EFFECT) {
5422 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5423 Py_FatalError("PyCompile_OpcodeStackEffect()");
5424 }
5425 int new_depth = depth + effect;
5426 if (new_depth > maxdepth) {
5427 maxdepth = new_depth;
5428 }
5429 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5430 if (instr->i_jrel || instr->i_jabs) {
5431 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5432 assert(effect != PY_INVALID_STACK_EFFECT);
5433 int target_depth = depth + effect;
5434 if (target_depth > maxdepth) {
5435 maxdepth = target_depth;
5436 }
5437 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005438 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005440 assert(instr->i_target->b_startdepth >= target_depth);
5441 depth = new_depth;
5442 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005443 }
5444 stackdepth_push(&sp, instr->i_target, target_depth);
5445 }
5446 depth = new_depth;
5447 if (instr->i_opcode == JUMP_ABSOLUTE ||
5448 instr->i_opcode == JUMP_FORWARD ||
5449 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005450 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005451 {
5452 /* remaining code is dead */
5453 next = NULL;
5454 break;
5455 }
5456 }
5457 if (next != NULL) {
5458 stackdepth_push(&sp, next, depth);
5459 }
5460 }
5461 PyObject_Free(stack);
5462 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005463}
5464
5465static int
5466assemble_init(struct assembler *a, int nblocks, int firstlineno)
5467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 memset(a, 0, sizeof(struct assembler));
5469 a->a_lineno = firstlineno;
5470 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5471 if (!a->a_bytecode)
5472 return 0;
5473 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5474 if (!a->a_lnotab)
5475 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005476 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 PyErr_NoMemory();
5478 return 0;
5479 }
5480 a->a_postorder = (basicblock **)PyObject_Malloc(
5481 sizeof(basicblock *) * nblocks);
5482 if (!a->a_postorder) {
5483 PyErr_NoMemory();
5484 return 0;
5485 }
5486 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005487}
5488
5489static void
5490assemble_free(struct assembler *a)
5491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 Py_XDECREF(a->a_bytecode);
5493 Py_XDECREF(a->a_lnotab);
5494 if (a->a_postorder)
5495 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005496}
5497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005498static int
5499blocksize(basicblock *b)
5500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 int i;
5502 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005505 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507}
5508
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005509/* Appends a pair to the end of the line number table, a_lnotab, representing
5510 the instruction's bytecode offset and line number. See
5511 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005512
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005513static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005514assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005517 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005519
Serhiy Storchakaab874002016-09-11 13:48:15 +03005520 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 if(d_bytecode == 0 && d_lineno == 0)
5526 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 if (d_bytecode > 255) {
5529 int j, nbytes, ncodes = d_bytecode / 255;
5530 nbytes = a->a_lnotab_off + 2 * ncodes;
5531 len = PyBytes_GET_SIZE(a->a_lnotab);
5532 if (nbytes >= len) {
5533 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5534 len = nbytes;
5535 else if (len <= INT_MAX / 2)
5536 len *= 2;
5537 else {
5538 PyErr_NoMemory();
5539 return 0;
5540 }
5541 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5542 return 0;
5543 }
5544 lnotab = (unsigned char *)
5545 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5546 for (j = 0; j < ncodes; j++) {
5547 *lnotab++ = 255;
5548 *lnotab++ = 0;
5549 }
5550 d_bytecode -= ncodes * 255;
5551 a->a_lnotab_off += ncodes * 2;
5552 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005553 assert(0 <= d_bytecode && d_bytecode <= 255);
5554
5555 if (d_lineno < -128 || 127 < d_lineno) {
5556 int j, nbytes, ncodes, k;
5557 if (d_lineno < 0) {
5558 k = -128;
5559 /* use division on positive numbers */
5560 ncodes = (-d_lineno) / 128;
5561 }
5562 else {
5563 k = 127;
5564 ncodes = d_lineno / 127;
5565 }
5566 d_lineno -= ncodes * k;
5567 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 nbytes = a->a_lnotab_off + 2 * ncodes;
5569 len = PyBytes_GET_SIZE(a->a_lnotab);
5570 if (nbytes >= len) {
5571 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5572 len = nbytes;
5573 else if (len <= INT_MAX / 2)
5574 len *= 2;
5575 else {
5576 PyErr_NoMemory();
5577 return 0;
5578 }
5579 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5580 return 0;
5581 }
5582 lnotab = (unsigned char *)
5583 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5584 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005585 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 d_bytecode = 0;
5587 for (j = 1; j < ncodes; j++) {
5588 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005589 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005590 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 a->a_lnotab_off += ncodes * 2;
5592 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005593 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 len = PyBytes_GET_SIZE(a->a_lnotab);
5596 if (a->a_lnotab_off + 2 >= len) {
5597 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5598 return 0;
5599 }
5600 lnotab = (unsigned char *)
5601 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 a->a_lnotab_off += 2;
5604 if (d_bytecode) {
5605 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005606 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 }
5608 else { /* First line of a block; def stmt, etc. */
5609 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005610 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 }
5612 a->a_lineno = i->i_lineno;
5613 a->a_lineno_off = a->a_offset;
5614 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005615}
5616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005617/* assemble_emit()
5618 Extend the bytecode with a new instruction.
5619 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005620*/
5621
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005622static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005623assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005624{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005625 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005627 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005628
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005629 arg = i->i_oparg;
5630 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 if (i->i_lineno && !assemble_lnotab(a, i))
5632 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005633 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 if (len > PY_SSIZE_T_MAX / 2)
5635 return 0;
5636 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5637 return 0;
5638 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005639 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005641 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005643}
5644
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005645static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005646assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005649 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 /* Compute the size of each block and fixup jump args.
5653 Replace block pointer with position in bytecode. */
5654 do {
5655 totsize = 0;
5656 for (i = a->a_nblocks - 1; i >= 0; i--) {
5657 b = a->a_postorder[i];
5658 bsize = blocksize(b);
5659 b->b_offset = totsize;
5660 totsize += bsize;
5661 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005662 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5664 bsize = b->b_offset;
5665 for (i = 0; i < b->b_iused; i++) {
5666 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005667 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 /* Relative jumps are computed relative to
5669 the instruction pointer after fetching
5670 the jump instruction.
5671 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005672 bsize += isize;
5673 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005675 if (instr->i_jrel) {
5676 instr->i_oparg -= bsize;
5677 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005678 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005679 if (instrsize(instr->i_oparg) != isize) {
5680 extended_arg_recompile = 1;
5681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 }
5684 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 /* XXX: This is an awful hack that could hurt performance, but
5687 on the bright side it should work until we come up
5688 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 The issue is that in the first loop blocksize() is called
5691 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005692 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 So we loop until we stop seeing new EXTENDED_ARGs.
5696 The only EXTENDED_ARGs that could be popping up are
5697 ones in jump instructions. So this should converge
5698 fairly quickly.
5699 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005700 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005701}
5702
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005703static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005704dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005707 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 tuple = PyTuple_New(size);
5710 if (tuple == NULL)
5711 return NULL;
5712 while (PyDict_Next(dict, &pos, &k, &v)) {
5713 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005714 Py_INCREF(k);
5715 assert((i - offset) < size);
5716 assert((i - offset) >= 0);
5717 PyTuple_SET_ITEM(tuple, i - offset, k);
5718 }
5719 return tuple;
5720}
5721
5722static PyObject *
5723consts_dict_keys_inorder(PyObject *dict)
5724{
5725 PyObject *consts, *k, *v;
5726 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5727
5728 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5729 if (consts == NULL)
5730 return NULL;
5731 while (PyDict_Next(dict, &pos, &k, &v)) {
5732 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005733 /* The keys of the dictionary can be tuples wrapping a contant.
5734 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5735 * the object we want is always second. */
5736 if (PyTuple_CheckExact(k)) {
5737 k = PyTuple_GET_ITEM(k, 1);
5738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005740 assert(i < size);
5741 assert(i >= 0);
5742 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005744 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005745}
5746
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005747static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005748compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005751 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005753 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 if (ste->ste_nested)
5755 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005756 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005758 if (!ste->ste_generator && ste->ste_coroutine)
5759 flags |= CO_COROUTINE;
5760 if (ste->ste_generator && ste->ste_coroutine)
5761 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005762 if (ste->ste_varargs)
5763 flags |= CO_VARARGS;
5764 if (ste->ste_varkeywords)
5765 flags |= CO_VARKEYWORDS;
5766 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 /* (Only) inherit compilerflags in PyCF_MASK */
5769 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005770
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005771 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5772 ste->ste_coroutine &&
5773 !ste->ste_generator) {
5774 flags |= CO_COROUTINE;
5775 }
5776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005778}
5779
INADA Naokic2e16072018-11-26 21:23:22 +09005780// Merge *tuple* with constant cache.
5781// Unlike merge_consts_recursive(), this function doesn't work recursively.
5782static int
5783merge_const_tuple(struct compiler *c, PyObject **tuple)
5784{
5785 assert(PyTuple_CheckExact(*tuple));
5786
5787 PyObject *key = _PyCode_ConstantKey(*tuple);
5788 if (key == NULL) {
5789 return 0;
5790 }
5791
5792 // t is borrowed reference
5793 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5794 Py_DECREF(key);
5795 if (t == NULL) {
5796 return 0;
5797 }
5798 if (t == key) { // tuple is new constant.
5799 return 1;
5800 }
5801
5802 PyObject *u = PyTuple_GET_ITEM(t, 1);
5803 Py_INCREF(u);
5804 Py_DECREF(*tuple);
5805 *tuple = u;
5806 return 1;
5807}
5808
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005809static PyCodeObject *
5810makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 PyObject *tmp;
5813 PyCodeObject *co = NULL;
5814 PyObject *consts = NULL;
5815 PyObject *names = NULL;
5816 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 PyObject *name = NULL;
5818 PyObject *freevars = NULL;
5819 PyObject *cellvars = NULL;
5820 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005821 Py_ssize_t nlocals;
5822 int nlocals_int;
5823 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005824 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005825
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005826 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 names = dict_keys_inorder(c->u->u_names, 0);
5828 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5829 if (!consts || !names || !varnames)
5830 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5833 if (!cellvars)
5834 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005835 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 if (!freevars)
5837 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005838
INADA Naokic2e16072018-11-26 21:23:22 +09005839 if (!merge_const_tuple(c, &names) ||
5840 !merge_const_tuple(c, &varnames) ||
5841 !merge_const_tuple(c, &cellvars) ||
5842 !merge_const_tuple(c, &freevars))
5843 {
5844 goto error;
5845 }
5846
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005847 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005848 assert(nlocals < INT_MAX);
5849 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 flags = compute_code_flags(c);
5852 if (flags < 0)
5853 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5856 if (!bytecode)
5857 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5860 if (!tmp)
5861 goto error;
5862 Py_DECREF(consts);
5863 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005864 if (!merge_const_tuple(c, &consts)) {
5865 goto error;
5866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005868 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005869 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005870 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005871 maxdepth = stackdepth(c);
5872 if (maxdepth < 0) {
5873 goto error;
5874 }
Miss Islington (bot)cb083f72019-07-01 04:29:14 -07005875 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5876 posonlyargcount, kwonlyargcount, nlocals_int,
5877 maxdepth, flags, bytecode, consts, names,
5878 varnames, freevars, cellvars, c->c_filename,
5879 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005880 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005881 Py_XDECREF(consts);
5882 Py_XDECREF(names);
5883 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 Py_XDECREF(name);
5885 Py_XDECREF(freevars);
5886 Py_XDECREF(cellvars);
5887 Py_XDECREF(bytecode);
5888 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005889}
5890
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005891
5892/* For debugging purposes only */
5893#if 0
5894static void
5895dump_instr(const struct instr *i)
5896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005897 const char *jrel = i->i_jrel ? "jrel " : "";
5898 const char *jabs = i->i_jabs ? "jabs " : "";
5899 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005901 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005902 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005904 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5906 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005907}
5908
5909static void
5910dump_basicblock(const basicblock *b)
5911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 const char *seen = b->b_seen ? "seen " : "";
5913 const char *b_return = b->b_return ? "return " : "";
5914 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5915 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5916 if (b->b_instr) {
5917 int i;
5918 for (i = 0; i < b->b_iused; i++) {
5919 fprintf(stderr, " [%02d] ", i);
5920 dump_instr(b->b_instr + i);
5921 }
5922 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005923}
5924#endif
5925
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005926static PyCodeObject *
5927assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005929 basicblock *b, *entryblock;
5930 struct assembler a;
5931 int i, j, nblocks;
5932 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005934 /* Make sure every block that falls off the end returns None.
5935 XXX NEXT_BLOCK() isn't quite right, because if the last
5936 block ends with a jump or return b_next shouldn't set.
5937 */
5938 if (!c->u->u_curblock->b_return) {
5939 NEXT_BLOCK(c);
5940 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005941 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 ADDOP(c, RETURN_VALUE);
5943 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 nblocks = 0;
5946 entryblock = NULL;
5947 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5948 nblocks++;
5949 entryblock = b;
5950 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 /* Set firstlineno if it wasn't explicitly set. */
5953 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005954 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5956 else
5957 c->u->u_firstlineno = 1;
5958 }
5959 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5960 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005961 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005963 /* Can't modify the bytecode after computing jump offsets. */
5964 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 /* Emit code in reverse postorder from dfs. */
5967 for (i = a.a_nblocks - 1; i >= 0; i--) {
5968 b = a.a_postorder[i];
5969 for (j = 0; j < b->b_iused; j++)
5970 if (!assemble_emit(&a, &b->b_instr[j]))
5971 goto error;
5972 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5975 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005976 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005980 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 assemble_free(&a);
5982 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005983}
Georg Brandl8334fd92010-12-04 10:26:46 +00005984
5985#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005986PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005987PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5988 PyArena *arena)
5989{
5990 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5991}