blob: 9e4a2094ac9b92d34b7ea96fe30bf3da06a5def1 [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;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164
INADA Naokic2e16072018-11-26 21:23:22 +0900165 PyObject *c_const_cache; /* Python dict holding all constants,
166 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 struct compiler_unit *u; /* compiler state for current block */
168 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
169 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170};
171
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100172static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static void compiler_free(struct compiler *);
174static basicblock *compiler_new_block(struct compiler *);
175static int compiler_next_instr(struct compiler *, basicblock *);
176static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100177static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200180static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
182
183static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
184static int compiler_visit_stmt(struct compiler *, stmt_ty);
185static int compiler_visit_keyword(struct compiler *, keyword_ty);
186static int compiler_visit_expr(struct compiler *, expr_ty);
187static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700188static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200193static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500195static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400196static int compiler_async_with(struct compiler *, stmt_ty, int);
197static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400200 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500201static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400202static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700204static int compiler_sync_comprehension_generator(
205 struct compiler *c,
206 asdl_seq *generators, int gen_index,
207 expr_ty elt, expr_ty val, int type);
208
209static int compiler_async_comprehension_generator(
210 struct compiler *c,
211 asdl_seq *generators, int gen_index,
212 expr_ty elt, expr_ty val, int type);
213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000215static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400217#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000219PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 /* Name mangling: __private becomes _classname__private.
223 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 PyObject *result;
225 size_t nlen, plen, ipriv;
226 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200228 PyUnicode_READ_CHAR(ident, 0) != '_' ||
229 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 Py_INCREF(ident);
231 return ident;
232 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200233 nlen = PyUnicode_GET_LENGTH(ident);
234 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 The only time a name with a dot can occur is when
238 we are compiling an import statement that has a
239 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 TODO(jhylton): Decide whether we want to support
242 mangling of the module name, e.g. __M.X.
243 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200244 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
245 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
246 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 Py_INCREF(ident);
248 return ident; /* Don't mangle __whatever__ */
249 }
250 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200251 ipriv = 0;
252 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
253 ipriv++;
254 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_INCREF(ident);
256 return ident; /* Don't mangle if class is just underscores */
257 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200258 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000259
Antoine Pitrou55bff892013-04-06 21:21:04 +0200260 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
261 PyErr_SetString(PyExc_OverflowError,
262 "private identifier too large to be mangled");
263 return NULL;
264 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000265
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200266 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
267 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
268 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
269
270 result = PyUnicode_New(1 + nlen + plen, maxchar);
271 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200273 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
274 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200275 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
276 Py_DECREF(result);
277 return NULL;
278 }
279 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
280 Py_DECREF(result);
281 return NULL;
282 }
Victor Stinner8f825062012-04-27 13:55:39 +0200283 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200284 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000285}
286
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287static int
288compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000291
INADA Naokic2e16072018-11-26 21:23:22 +0900292 c->c_const_cache = PyDict_New();
293 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900295 }
296
297 c->c_stack = PyList_New(0);
298 if (!c->c_stack) {
299 Py_CLEAR(c->c_const_cache);
300 return 0;
301 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304}
305
306PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200307PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
308 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 struct compiler c;
311 PyCodeObject *co = NULL;
312 PyCompilerFlags local_flags;
313 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200314 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (!__doc__) {
317 __doc__ = PyUnicode_InternFromString("__doc__");
318 if (!__doc__)
319 return NULL;
320 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000321 if (!__annotations__) {
322 __annotations__ = PyUnicode_InternFromString("__annotations__");
323 if (!__annotations__)
324 return NULL;
325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (!compiler_init(&c))
327 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200328 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 c.c_filename = filename;
330 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200331 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 if (c.c_future == NULL)
333 goto finally;
334 if (!flags) {
335 local_flags.cf_flags = 0;
Guido van Rossum495da292019-03-07 12:38:08 -0800336 local_flags.cf_feature_version = PY_MINOR_VERSION;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 flags = &local_flags;
338 }
339 merged = c.c_future->ff_features | flags->cf_flags;
340 c.c_future->ff_features = merged;
341 flags->cf_flags = merged;
342 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200343 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200346 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900347 goto finally;
348 }
349
Victor Stinner14e461d2013-08-26 22:28:21 +0200350 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (c.c_st == NULL) {
352 if (!PyErr_Occurred())
353 PyErr_SetString(PyExc_SystemError, "no symtable");
354 goto finally;
355 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358
Thomas Wouters1175c432006-02-27 22:49:54 +0000359 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 compiler_free(&c);
361 assert(co || PyErr_Occurred());
362 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363}
364
365PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200366PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
367 int optimize, PyArena *arena)
368{
369 PyObject *filename;
370 PyCodeObject *co;
371 filename = PyUnicode_DecodeFSDefault(filename_str);
372 if (filename == NULL)
373 return NULL;
374 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
375 Py_DECREF(filename);
376 return co;
377
378}
379
380PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381PyNode_Compile(struct _node *n, const char *filename)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyCodeObject *co = NULL;
384 mod_ty mod;
385 PyArena *arena = PyArena_New();
386 if (!arena)
387 return NULL;
388 mod = PyAST_FromNode(n, NULL, filename, arena);
389 if (mod)
390 co = PyAST_Compile(mod, filename, NULL, arena);
391 PyArena_Free(arena);
392 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000393}
394
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000395static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (c->c_st)
399 PySymtable_Free(c->c_st);
400 if (c->c_future)
401 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200402 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900403 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000405}
406
Guido van Rossum79f25d91997-04-29 20:08:16 +0000407static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000408list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_ssize_t i, n;
411 PyObject *v, *k;
412 PyObject *dict = PyDict_New();
413 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 n = PyList_Size(list);
416 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100417 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (!v) {
419 Py_DECREF(dict);
420 return NULL;
421 }
422 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300423 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_DECREF(v);
425 Py_DECREF(dict);
426 return NULL;
427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 Py_DECREF(v);
429 }
430 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000431}
432
433/* Return new dict containing names from src that match scope(s).
434
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000435src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000437values are integers, starting at offset and increasing by one for
438each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439*/
440
441static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100442dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700444 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500446 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 assert(offset >= 0);
449 if (dest == NULL)
450 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Meador Inge2ca63152012-07-18 14:20:11 -0500452 /* Sort the keys so that we have a deterministic order on the indexes
453 saved in the returned dictionary. These indexes are used as indexes
454 into the free and cell var storage. Therefore if they aren't
455 deterministic, then the generated bytecode is not deterministic.
456 */
457 sorted_keys = PyDict_Keys(src);
458 if (sorted_keys == NULL)
459 return NULL;
460 if (PyList_Sort(sorted_keys) != 0) {
461 Py_DECREF(sorted_keys);
462 return NULL;
463 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500464 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500465
466 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* XXX this should probably be a macro in symtable.h */
468 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500469 k = PyList_GET_ITEM(sorted_keys, key_i);
470 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 assert(PyLong_Check(v));
472 vi = PyLong_AS_LONG(v);
473 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300476 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500478 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Py_DECREF(dest);
480 return NULL;
481 }
482 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300483 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500484 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 Py_DECREF(item);
486 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return NULL;
488 }
489 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 }
491 }
Meador Inge2ca63152012-07-18 14:20:11 -0500492 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000494}
495
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496static void
497compiler_unit_check(struct compiler_unit *u)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 basicblock *block;
500 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700501 assert((uintptr_t)block != 0xcbcbcbcbU);
502 assert((uintptr_t)block != 0xfbfbfbfbU);
503 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (block->b_instr != NULL) {
505 assert(block->b_ialloc > 0);
506 assert(block->b_iused > 0);
507 assert(block->b_ialloc >= block->b_iused);
508 }
509 else {
510 assert (block->b_iused == 0);
511 assert (block->b_ialloc == 0);
512 }
513 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000514}
515
516static void
517compiler_unit_free(struct compiler_unit *u)
518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 compiler_unit_check(u);
522 b = u->u_blocks;
523 while (b != NULL) {
524 if (b->b_instr)
525 PyObject_Free((void *)b->b_instr);
526 next = b->b_list;
527 PyObject_Free((void *)b);
528 b = next;
529 }
530 Py_CLEAR(u->u_ste);
531 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400532 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 Py_CLEAR(u->u_consts);
534 Py_CLEAR(u->u_names);
535 Py_CLEAR(u->u_varnames);
536 Py_CLEAR(u->u_freevars);
537 Py_CLEAR(u->u_cellvars);
538 Py_CLEAR(u->u_private);
539 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000540}
541
542static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100543compiler_enter_scope(struct compiler *c, identifier name,
544 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100547 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
550 struct compiler_unit));
551 if (!u) {
552 PyErr_NoMemory();
553 return 0;
554 }
555 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100556 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100558 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 u->u_kwonlyargcount = 0;
560 u->u_ste = PySymtable_Lookup(c->c_st, key);
561 if (!u->u_ste) {
562 compiler_unit_free(u);
563 return 0;
564 }
565 Py_INCREF(name);
566 u->u_name = name;
567 u->u_varnames = list2dict(u->u_ste->ste_varnames);
568 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
569 if (!u->u_varnames || !u->u_cellvars) {
570 compiler_unit_free(u);
571 return 0;
572 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500573 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000574 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500575 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300576 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500577 int res;
578 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200579 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 name = _PyUnicode_FromId(&PyId___class__);
581 if (!name) {
582 compiler_unit_free(u);
583 return 0;
584 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300585 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500586 if (res < 0) {
587 compiler_unit_free(u);
588 return 0;
589 }
590 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200593 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (!u->u_freevars) {
595 compiler_unit_free(u);
596 return 0;
597 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_blocks = NULL;
600 u->u_nfblocks = 0;
601 u->u_firstlineno = lineno;
602 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000603 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 u->u_lineno_set = 0;
605 u->u_consts = PyDict_New();
606 if (!u->u_consts) {
607 compiler_unit_free(u);
608 return 0;
609 }
610 u->u_names = PyDict_New();
611 if (!u->u_names) {
612 compiler_unit_free(u);
613 return 0;
614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Push the old compiler_unit on the stack. */
619 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400620 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
622 Py_XDECREF(capsule);
623 compiler_unit_free(u);
624 return 0;
625 }
626 Py_DECREF(capsule);
627 u->u_private = c->u->u_private;
628 Py_XINCREF(u->u_private);
629 }
630 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100633
634 block = compiler_new_block(c);
635 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100637 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400639 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
640 if (!compiler_set_qualname(c))
641 return 0;
642 }
643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645}
646
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000647static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648compiler_exit_scope(struct compiler *c)
649{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100650 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 c->c_nestlevel--;
654 compiler_unit_free(c->u);
655 /* Restore c->u to the parent unit. */
656 n = PyList_GET_SIZE(c->c_stack) - 1;
657 if (n >= 0) {
658 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400659 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 assert(c->u);
661 /* we are deleting from a list so this really shouldn't fail */
662 if (PySequence_DelItem(c->c_stack, n) < 0)
663 Py_FatalError("compiler_exit_scope()");
664 compiler_unit_check(c->u);
665 }
666 else
667 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669}
670
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671static int
672compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 _Py_static_string(dot_locals, ".<locals>");
676 Py_ssize_t stack_size;
677 struct compiler_unit *u = c->u;
678 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400682 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400683 if (stack_size > 1) {
684 int scope, force_global = 0;
685 struct compiler_unit *parent;
686 PyObject *mangled, *capsule;
687
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400688 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400689 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 assert(parent);
691
Yury Selivanov75445082015-05-11 22:57:16 -0400692 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
693 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
694 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400695 assert(u->u_name);
696 mangled = _Py_Mangle(parent->u_private, u->u_name);
697 if (!mangled)
698 return 0;
699 scope = PyST_GetScope(parent->u_ste, mangled);
700 Py_DECREF(mangled);
701 assert(scope != GLOBAL_IMPLICIT);
702 if (scope == GLOBAL_EXPLICIT)
703 force_global = 1;
704 }
705
706 if (!force_global) {
707 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400708 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
710 dot_locals_str = _PyUnicode_FromId(&dot_locals);
711 if (dot_locals_str == NULL)
712 return 0;
713 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
714 if (base == NULL)
715 return 0;
716 }
717 else {
718 Py_INCREF(parent->u_qualname);
719 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400720 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100721 }
722 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400723
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400724 if (base != NULL) {
725 dot_str = _PyUnicode_FromId(&dot);
726 if (dot_str == NULL) {
727 Py_DECREF(base);
728 return 0;
729 }
730 name = PyUnicode_Concat(base, dot_str);
731 Py_DECREF(base);
732 if (name == NULL)
733 return 0;
734 PyUnicode_Append(&name, u->u_name);
735 if (name == NULL)
736 return 0;
737 }
738 else {
739 Py_INCREF(u->u_name);
740 name = u->u_name;
741 }
742 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100743
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400744 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100745}
746
Eric V. Smith235a6f02015-09-19 14:51:32 -0400747
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000748/* Allocate a new block and return a pointer to it.
749 Returns NULL on error.
750*/
751
752static basicblock *
753compiler_new_block(struct compiler *c)
754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 basicblock *b;
756 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 u = c->u;
759 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
760 if (b == NULL) {
761 PyErr_NoMemory();
762 return NULL;
763 }
764 memset((void *)b, 0, sizeof(basicblock));
765 /* Extend the singly linked list of blocks with new block. */
766 b->b_list = u->u_blocks;
767 u->u_blocks = b;
768 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769}
770
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772compiler_next_block(struct compiler *c)
773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 basicblock *block = compiler_new_block(c);
775 if (block == NULL)
776 return NULL;
777 c->u->u_curblock->b_next = block;
778 c->u->u_curblock = block;
779 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780}
781
782static basicblock *
783compiler_use_next_block(struct compiler *c, basicblock *block)
784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 assert(block != NULL);
786 c->u->u_curblock->b_next = block;
787 c->u->u_curblock = block;
788 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789}
790
791/* Returns the offset of the next instruction in the current block's
792 b_instr array. Resizes the b_instr as necessary.
793 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000794*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795
796static int
797compiler_next_instr(struct compiler *c, basicblock *b)
798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 assert(b != NULL);
800 if (b->b_instr == NULL) {
801 b->b_instr = (struct instr *)PyObject_Malloc(
802 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
803 if (b->b_instr == NULL) {
804 PyErr_NoMemory();
805 return -1;
806 }
807 b->b_ialloc = DEFAULT_BLOCK_SIZE;
808 memset((char *)b->b_instr, 0,
809 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
810 }
811 else if (b->b_iused == b->b_ialloc) {
812 struct instr *tmp;
813 size_t oldsize, newsize;
814 oldsize = b->b_ialloc * sizeof(struct instr);
815 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000816
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700817 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyErr_NoMemory();
819 return -1;
820 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (newsize == 0) {
823 PyErr_NoMemory();
824 return -1;
825 }
826 b->b_ialloc <<= 1;
827 tmp = (struct instr *)PyObject_Realloc(
828 (void *)b->b_instr, newsize);
829 if (tmp == NULL) {
830 PyErr_NoMemory();
831 return -1;
832 }
833 b->b_instr = tmp;
834 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
835 }
836 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837}
838
Christian Heimes2202f872008-02-06 14:31:34 +0000839/* Set the i_lineno member of the instruction at offset off if the
840 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841 already been set. If it has been set, the call has no effect.
842
Christian Heimes2202f872008-02-06 14:31:34 +0000843 The line number is reset in the following cases:
844 - when entering a new scope
845 - on each statement
846 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200847 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000848 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000849*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851static void
852compiler_set_lineno(struct compiler *c, int off)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 basicblock *b;
855 if (c->u->u_lineno_set)
856 return;
857 c->u->u_lineno_set = 1;
858 b = c->u->u_curblock;
859 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860}
861
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200862/* Return the stack effect of opcode with argument oparg.
863
864 Some opcodes have different stack effect when jump to the target and
865 when not jump. The 'jump' parameter specifies the case:
866
867 * 0 -- when not jump
868 * 1 -- when jump
869 * -1 -- maximal
870 */
871/* XXX Make the stack effect of WITH_CLEANUP_START and
872 WITH_CLEANUP_FINISH deterministic. */
873static int
874stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300877 case NOP:
878 case EXTENDED_ARG:
879 return 0;
880
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200881 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case POP_TOP:
883 return -1;
884 case ROT_TWO:
885 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200886 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return 0;
888 case DUP_TOP:
889 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000890 case DUP_TOP_TWO:
891 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200893 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case UNARY_POSITIVE:
895 case UNARY_NEGATIVE:
896 case UNARY_NOT:
897 case UNARY_INVERT:
898 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case SET_ADD:
901 case LIST_APPEND:
902 return -1;
903 case MAP_ADD:
904 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000905
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200906 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_POWER:
908 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400909 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case BINARY_MODULO:
911 case BINARY_ADD:
912 case BINARY_SUBTRACT:
913 case BINARY_SUBSCR:
914 case BINARY_FLOOR_DIVIDE:
915 case BINARY_TRUE_DIVIDE:
916 return -1;
917 case INPLACE_FLOOR_DIVIDE:
918 case INPLACE_TRUE_DIVIDE:
919 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case INPLACE_ADD:
922 case INPLACE_SUBTRACT:
923 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400924 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case INPLACE_MODULO:
926 return -1;
927 case STORE_SUBSCR:
928 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case DELETE_SUBSCR:
930 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case BINARY_LSHIFT:
933 case BINARY_RSHIFT:
934 case BINARY_AND:
935 case BINARY_XOR:
936 case BINARY_OR:
937 return -1;
938 case INPLACE_POWER:
939 return -1;
940 case GET_ITER:
941 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 case PRINT_EXPR:
944 return -1;
945 case LOAD_BUILD_CLASS:
946 return 1;
947 case INPLACE_LSHIFT:
948 case INPLACE_RSHIFT:
949 case INPLACE_AND:
950 case INPLACE_XOR:
951 case INPLACE_OR:
952 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200955 /* 1 in the normal flow.
956 * Restore the stack position and push 6 values before jumping to
957 * the handler if an exception be raised. */
958 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400959 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200960 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400961 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200962 /* Pop a variable number of values pushed by WITH_CLEANUP_START
963 * + __exit__ or __aexit__. */
964 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case RETURN_VALUE:
966 return -1;
967 case IMPORT_STAR:
968 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700969 case SETUP_ANNOTATIONS:
970 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case YIELD_VALUE:
972 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500973 case YIELD_FROM:
974 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case POP_BLOCK:
976 return 0;
977 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200978 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200980 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200981 /* Pop 6 values when an exception was raised. */
982 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 case STORE_NAME:
985 return -1;
986 case DELETE_NAME:
987 return 0;
988 case UNPACK_SEQUENCE:
989 return oparg-1;
990 case UNPACK_EX:
991 return (oparg&0xFF) + (oparg>>8);
992 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200993 /* -1 at end of iterator, 1 if continue iterating. */
994 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 case STORE_ATTR:
997 return -2;
998 case DELETE_ATTR:
999 return -1;
1000 case STORE_GLOBAL:
1001 return -1;
1002 case DELETE_GLOBAL:
1003 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case LOAD_CONST:
1005 return 1;
1006 case LOAD_NAME:
1007 return 1;
1008 case BUILD_TUPLE:
1009 case BUILD_LIST:
1010 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001011 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_LIST_UNPACK:
1014 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001015 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001016 case BUILD_SET_UNPACK:
1017 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001018 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001019 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001021 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001022 case BUILD_CONST_KEY_MAP:
1023 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case LOAD_ATTR:
1025 return 0;
1026 case COMPARE_OP:
1027 return -1;
1028 case IMPORT_NAME:
1029 return -1;
1030 case IMPORT_FROM:
1031 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001033 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case JUMP_ABSOLUTE:
1036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001038 case JUMP_IF_TRUE_OR_POP:
1039 case JUMP_IF_FALSE_OR_POP:
1040 return jump ? 0 : -1;
1041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case POP_JUMP_IF_FALSE:
1043 case POP_JUMP_IF_TRUE:
1044 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case LOAD_GLOBAL:
1047 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001049 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001051 /* 0 in the normal flow.
1052 * Restore the stack position and push 6 values before jumping to
1053 * the handler if an exception be raised. */
1054 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001055 case BEGIN_FINALLY:
1056 /* Actually pushes 1 value, but count 6 for balancing with
1057 * END_FINALLY and POP_FINALLY.
1058 * This is the main reason of using this opcode instead of
1059 * "LOAD_CONST None". */
1060 return 6;
1061 case CALL_FINALLY:
1062 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case LOAD_FAST:
1065 return 1;
1066 case STORE_FAST:
1067 return -1;
1068 case DELETE_FAST:
1069 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case RAISE_VARARGS:
1072 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001073
1074 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001076 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001077 case CALL_METHOD:
1078 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001080 return -oparg-1;
1081 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001082 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001083 case MAKE_FUNCTION:
1084 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1085 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 case BUILD_SLICE:
1087 if (oparg == 3)
1088 return -2;
1089 else
1090 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001091
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001092 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 case LOAD_CLOSURE:
1094 return 1;
1095 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001096 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 return 1;
1098 case STORE_DEREF:
1099 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001100 case DELETE_DEREF:
1101 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001102
1103 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001104 case GET_AWAITABLE:
1105 return 0;
1106 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001107 /* 0 in the normal flow.
1108 * Restore the stack position to the position before the result
1109 * of __aenter__ and push 6 values before jumping to the handler
1110 * if an exception be raised. */
1111 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001112 case BEFORE_ASYNC_WITH:
1113 return 1;
1114 case GET_AITER:
1115 return 0;
1116 case GET_ANEXT:
1117 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001118 case GET_YIELD_FROM_ITER:
1119 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001120 case END_ASYNC_FOR:
1121 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001122 case FORMAT_VALUE:
1123 /* If there's a fmt_spec on the stack, we go from 2->1,
1124 else 1->1. */
1125 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001126 case LOAD_METHOD:
1127 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001129 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
Larry Hastings3a907972013-11-23 14:49:22 -08001131 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132}
1133
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001134int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001135PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1136{
1137 return stack_effect(opcode, oparg, jump);
1138}
1139
1140int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001141PyCompile_OpcodeStackEffect(int opcode, int oparg)
1142{
1143 return stack_effect(opcode, oparg, -1);
1144}
1145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146/* Add an opcode with no argument.
1147 Returns 0 on failure, 1 on success.
1148*/
1149
1150static int
1151compiler_addop(struct compiler *c, int opcode)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 basicblock *b;
1154 struct instr *i;
1155 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001156 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 off = compiler_next_instr(c, c->u->u_curblock);
1158 if (off < 0)
1159 return 0;
1160 b = c->u->u_curblock;
1161 i = &b->b_instr[off];
1162 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001163 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (opcode == RETURN_VALUE)
1165 b->b_return = 1;
1166 compiler_set_lineno(c, off);
1167 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168}
1169
Victor Stinnerf8e32212013-11-19 23:56:34 +01001170static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1172{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001173 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001176 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001178 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001180 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001181 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001182 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return -1;
1185 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001186 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_DECREF(v);
1188 return -1;
1189 }
1190 Py_DECREF(v);
1191 }
1192 else
1193 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001194 return arg;
1195}
1196
INADA Naokic2e16072018-11-26 21:23:22 +09001197// Merge const *o* recursively and return constant key object.
1198static PyObject*
1199merge_consts_recursive(struct compiler *c, PyObject *o)
1200{
1201 // None and Ellipsis are singleton, and key is the singleton.
1202 // No need to merge object and key.
1203 if (o == Py_None || o == Py_Ellipsis) {
1204 Py_INCREF(o);
1205 return o;
1206 }
1207
1208 PyObject *key = _PyCode_ConstantKey(o);
1209 if (key == NULL) {
1210 return NULL;
1211 }
1212
1213 // t is borrowed reference
1214 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1215 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001216 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001217 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001218 Py_DECREF(key);
1219 return t;
1220 }
1221
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001223 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001224 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001225 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001226 Py_ssize_t len = PyTuple_GET_SIZE(o);
1227 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001228 PyObject *item = PyTuple_GET_ITEM(o, i);
1229 PyObject *u = merge_consts_recursive(c, item);
1230 if (u == NULL) {
1231 Py_DECREF(key);
1232 return NULL;
1233 }
1234
1235 // See _PyCode_ConstantKey()
1236 PyObject *v; // borrowed
1237 if (PyTuple_CheckExact(u)) {
1238 v = PyTuple_GET_ITEM(u, 1);
1239 }
1240 else {
1241 v = u;
1242 }
1243 if (v != item) {
1244 Py_INCREF(v);
1245 PyTuple_SET_ITEM(o, i, v);
1246 Py_DECREF(item);
1247 }
1248
1249 Py_DECREF(u);
1250 }
1251 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001253 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001254 // constant keys.
1255 // See _PyCode_ConstantKey() for detail.
1256 assert(PyTuple_CheckExact(key));
1257 assert(PyTuple_GET_SIZE(key) == 2);
1258
1259 Py_ssize_t len = PySet_GET_SIZE(o);
1260 if (len == 0) { // empty frozenset should not be re-created.
1261 return key;
1262 }
1263 PyObject *tuple = PyTuple_New(len);
1264 if (tuple == NULL) {
1265 Py_DECREF(key);
1266 return NULL;
1267 }
1268 Py_ssize_t i = 0, pos = 0;
1269 PyObject *item;
1270 Py_hash_t hash;
1271 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1272 PyObject *k = merge_consts_recursive(c, item);
1273 if (k == NULL) {
1274 Py_DECREF(tuple);
1275 Py_DECREF(key);
1276 return NULL;
1277 }
1278 PyObject *u;
1279 if (PyTuple_CheckExact(k)) {
1280 u = PyTuple_GET_ITEM(k, 1);
1281 Py_INCREF(u);
1282 Py_DECREF(k);
1283 }
1284 else {
1285 u = k;
1286 }
1287 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1288 i++;
1289 }
1290
1291 // Instead of rewriting o, we create new frozenset and embed in the
1292 // key tuple. Caller should get merged frozenset from the key tuple.
1293 PyObject *new = PyFrozenSet_New(tuple);
1294 Py_DECREF(tuple);
1295 if (new == NULL) {
1296 Py_DECREF(key);
1297 return NULL;
1298 }
1299 assert(PyTuple_GET_ITEM(key, 1) == o);
1300 Py_DECREF(o);
1301 PyTuple_SET_ITEM(key, 1, new);
1302 }
INADA Naokic2e16072018-11-26 21:23:22 +09001303
1304 return key;
1305}
1306
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001307static Py_ssize_t
1308compiler_add_const(struct compiler *c, PyObject *o)
1309{
INADA Naokic2e16072018-11-26 21:23:22 +09001310 PyObject *key = merge_consts_recursive(c, o);
1311 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001312 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001313 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001314
INADA Naokic2e16072018-11-26 21:23:22 +09001315 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1316 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318}
1319
1320static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001321compiler_addop_load_const(struct compiler *c, PyObject *o)
1322{
1323 Py_ssize_t arg = compiler_add_const(c, o);
1324 if (arg < 0)
1325 return 0;
1326 return compiler_addop_i(c, LOAD_CONST, arg);
1327}
1328
1329static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001333 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336 return compiler_addop_i(c, opcode, arg);
1337}
1338
1339static int
1340compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001343 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1345 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 arg = compiler_add_o(c, dict, mangled);
1348 Py_DECREF(mangled);
1349 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001350 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351 return compiler_addop_i(c, opcode, arg);
1352}
1353
1354/* Add an opcode with an integer argument.
1355 Returns 0 on failure, 1 on success.
1356*/
1357
1358static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001359compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 struct instr *i;
1362 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001363
Victor Stinner2ad474b2016-03-01 23:34:47 +01001364 /* oparg value is unsigned, but a signed C int is usually used to store
1365 it in the C code (like Python/ceval.c).
1366
1367 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1368
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001369 The argument of a concrete bytecode instruction is limited to 8-bit.
1370 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1371 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001372 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 off = compiler_next_instr(c, c->u->u_curblock);
1375 if (off < 0)
1376 return 0;
1377 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001378 i->i_opcode = opcode;
1379 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 compiler_set_lineno(c, off);
1381 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382}
1383
1384static int
1385compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 struct instr *i;
1388 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001390 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 assert(b != NULL);
1392 off = compiler_next_instr(c, c->u->u_curblock);
1393 if (off < 0)
1394 return 0;
1395 i = &c->u->u_curblock->b_instr[off];
1396 i->i_opcode = opcode;
1397 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (absolute)
1399 i->i_jabs = 1;
1400 else
1401 i->i_jrel = 1;
1402 compiler_set_lineno(c, off);
1403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404}
1405
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001406/* NEXT_BLOCK() creates an implicit jump from the current block
1407 to the new block.
1408
1409 The returns inside this macro make it impossible to decref objects
1410 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (compiler_next_block((C)) == NULL) \
1414 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415}
1416
1417#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!compiler_addop((C), (OP))) \
1419 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420}
1421
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001422#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (!compiler_addop((C), (OP))) { \
1424 compiler_exit_scope(c); \
1425 return 0; \
1426 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001427}
1428
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001429#define ADDOP_LOAD_CONST(C, O) { \
1430 if (!compiler_addop_load_const((C), (O))) \
1431 return 0; \
1432}
1433
1434/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1435#define ADDOP_LOAD_CONST_NEW(C, O) { \
1436 PyObject *__new_const = (O); \
1437 if (__new_const == NULL) { \
1438 return 0; \
1439 } \
1440 if (!compiler_addop_load_const((C), __new_const)) { \
1441 Py_DECREF(__new_const); \
1442 return 0; \
1443 } \
1444 Py_DECREF(__new_const); \
1445}
1446
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1449 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450}
1451
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001452/* Same as ADDOP_O, but steals a reference. */
1453#define ADDOP_N(C, OP, O, TYPE) { \
1454 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1455 Py_DECREF((O)); \
1456 return 0; \
1457 } \
1458 Py_DECREF((O)); \
1459}
1460
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1463 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!compiler_addop_i((C), (OP), (O))) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop_j((C), (OP), (O), 1)) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
1476#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (!compiler_addop_j((C), (OP), (O), 0)) \
1478 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479}
1480
1481/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1482 the ASDL name to synthesize the name of the C type and the visit function.
1483*/
1484
1485#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_visit_ ## TYPE((C), (V))) \
1487 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488}
1489
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001490#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_visit_ ## TYPE((C), (V))) { \
1492 compiler_exit_scope(c); \
1493 return 0; \
1494 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001495}
1496
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (!compiler_visit_slice((C), (V), (CTX))) \
1499 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
1502#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 int _i; \
1504 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1505 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1506 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1507 if (!compiler_visit_ ## TYPE((C), elt)) \
1508 return 0; \
1509 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510}
1511
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001512#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 int _i; \
1514 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1515 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1516 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1517 if (!compiler_visit_ ## TYPE((C), elt)) { \
1518 compiler_exit_scope(c); \
1519 return 0; \
1520 } \
1521 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001522}
1523
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001524/* Search if variable annotations are present statically in a block. */
1525
1526static int
1527find_ann(asdl_seq *stmts)
1528{
1529 int i, j, res = 0;
1530 stmt_ty st;
1531
1532 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1533 st = (stmt_ty)asdl_seq_GET(stmts, i);
1534 switch (st->kind) {
1535 case AnnAssign_kind:
1536 return 1;
1537 case For_kind:
1538 res = find_ann(st->v.For.body) ||
1539 find_ann(st->v.For.orelse);
1540 break;
1541 case AsyncFor_kind:
1542 res = find_ann(st->v.AsyncFor.body) ||
1543 find_ann(st->v.AsyncFor.orelse);
1544 break;
1545 case While_kind:
1546 res = find_ann(st->v.While.body) ||
1547 find_ann(st->v.While.orelse);
1548 break;
1549 case If_kind:
1550 res = find_ann(st->v.If.body) ||
1551 find_ann(st->v.If.orelse);
1552 break;
1553 case With_kind:
1554 res = find_ann(st->v.With.body);
1555 break;
1556 case AsyncWith_kind:
1557 res = find_ann(st->v.AsyncWith.body);
1558 break;
1559 case Try_kind:
1560 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1561 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1562 st->v.Try.handlers, j);
1563 if (find_ann(handler->v.ExceptHandler.body)) {
1564 return 1;
1565 }
1566 }
1567 res = find_ann(st->v.Try.body) ||
1568 find_ann(st->v.Try.finalbody) ||
1569 find_ann(st->v.Try.orelse);
1570 break;
1571 default:
1572 res = 0;
1573 }
1574 if (res) {
1575 break;
1576 }
1577 }
1578 return res;
1579}
1580
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001581/*
1582 * Frame block handling functions
1583 */
1584
1585static int
1586compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1587 basicblock *exit)
1588{
1589 struct fblockinfo *f;
1590 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1591 PyErr_SetString(PyExc_SyntaxError,
1592 "too many statically nested blocks");
1593 return 0;
1594 }
1595 f = &c->u->u_fblock[c->u->u_nfblocks++];
1596 f->fb_type = t;
1597 f->fb_block = b;
1598 f->fb_exit = exit;
1599 return 1;
1600}
1601
1602static void
1603compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1604{
1605 struct compiler_unit *u = c->u;
1606 assert(u->u_nfblocks > 0);
1607 u->u_nfblocks--;
1608 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1609 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1610}
1611
1612/* Unwind a frame block. If preserve_tos is true, the TOS before
1613 * popping the blocks will be restored afterwards.
1614 */
1615static int
1616compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1617 int preserve_tos)
1618{
1619 switch (info->fb_type) {
1620 case WHILE_LOOP:
1621 return 1;
1622
1623 case FINALLY_END:
1624 ADDOP_I(c, POP_FINALLY, preserve_tos);
1625 return 1;
1626
1627 case FOR_LOOP:
1628 /* Pop the iterator */
1629 if (preserve_tos) {
1630 ADDOP(c, ROT_TWO);
1631 }
1632 ADDOP(c, POP_TOP);
1633 return 1;
1634
1635 case EXCEPT:
1636 ADDOP(c, POP_BLOCK);
1637 return 1;
1638
1639 case FINALLY_TRY:
1640 ADDOP(c, POP_BLOCK);
1641 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1642 return 1;
1643
1644 case WITH:
1645 case ASYNC_WITH:
1646 ADDOP(c, POP_BLOCK);
1647 if (preserve_tos) {
1648 ADDOP(c, ROT_TWO);
1649 }
1650 ADDOP(c, BEGIN_FINALLY);
1651 ADDOP(c, WITH_CLEANUP_START);
1652 if (info->fb_type == ASYNC_WITH) {
1653 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001654 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001655 ADDOP(c, YIELD_FROM);
1656 }
1657 ADDOP(c, WITH_CLEANUP_FINISH);
1658 ADDOP_I(c, POP_FINALLY, 0);
1659 return 1;
1660
1661 case HANDLER_CLEANUP:
1662 if (preserve_tos) {
1663 ADDOP(c, ROT_FOUR);
1664 }
1665 if (info->fb_exit) {
1666 ADDOP(c, POP_BLOCK);
1667 ADDOP(c, POP_EXCEPT);
1668 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1669 }
1670 else {
1671 ADDOP(c, POP_EXCEPT);
1672 }
1673 return 1;
1674 }
1675 Py_UNREACHABLE();
1676}
1677
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001678/* Compile a sequence of statements, checking for a docstring
1679 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680
1681static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001682compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001684 int i = 0;
1685 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001686 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001687
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001688 /* Set current line number to the line number of first statement.
1689 This way line number for SETUP_ANNOTATIONS will always
1690 coincide with the line number of first "real" statement in module.
1691 If body is empy, then lineno will be set later in assemble. */
1692 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1693 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001694 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001695 c->u->u_lineno = st->lineno;
1696 }
1697 /* Every annotated class and module should have __annotations__. */
1698 if (find_ann(stmts)) {
1699 ADDOP(c, SETUP_ANNOTATIONS);
1700 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001701 if (!asdl_seq_LEN(stmts))
1702 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001703 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001704 if (c->c_optimize < 2) {
1705 docstring = _PyAST_GetDocString(stmts);
1706 if (docstring) {
1707 i = 1;
1708 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1709 assert(st->kind == Expr_kind);
1710 VISIT(c, expr, st->v.Expr.value);
1711 if (!compiler_nameop(c, __doc__, Store))
1712 return 0;
1713 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001715 for (; i < asdl_seq_LEN(stmts); i++)
1716 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718}
1719
1720static PyCodeObject *
1721compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyCodeObject *co;
1724 int addNone = 1;
1725 static PyObject *module;
1726 if (!module) {
1727 module = PyUnicode_InternFromString("<module>");
1728 if (!module)
1729 return NULL;
1730 }
1731 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001732 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return NULL;
1734 switch (mod->kind) {
1735 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001736 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 compiler_exit_scope(c);
1738 return 0;
1739 }
1740 break;
1741 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001742 if (find_ann(mod->v.Interactive.body)) {
1743 ADDOP(c, SETUP_ANNOTATIONS);
1744 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 c->c_interactive = 1;
1746 VISIT_SEQ_IN_SCOPE(c, stmt,
1747 mod->v.Interactive.body);
1748 break;
1749 case Expression_kind:
1750 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1751 addNone = 0;
1752 break;
1753 case Suite_kind:
1754 PyErr_SetString(PyExc_SystemError,
1755 "suite should not be possible");
1756 return 0;
1757 default:
1758 PyErr_Format(PyExc_SystemError,
1759 "module kind %d should not be possible",
1760 mod->kind);
1761 return 0;
1762 }
1763 co = assemble(c, addNone);
1764 compiler_exit_scope(c);
1765 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001766}
1767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768/* The test for LOCAL must come before the test for FREE in order to
1769 handle classes where name is both local and free. The local var is
1770 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001771*/
1772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773static int
1774get_ref_type(struct compiler *c, PyObject *name)
1775{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001776 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001777 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001778 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001779 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001780 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (scope == 0) {
1782 char buf[350];
1783 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001784 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001786 PyUnicode_AsUTF8(name),
1787 PyUnicode_AsUTF8(c->u->u_name),
1788 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1789 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1790 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1791 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 );
1793 Py_FatalError(buf);
1794 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797}
1798
1799static int
1800compiler_lookup_arg(PyObject *dict, PyObject *name)
1801{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001802 PyObject *v;
1803 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001805 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001806 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807}
1808
1809static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001810compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001812 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001813 if (qualname == NULL)
1814 qualname = co->co_name;
1815
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001816 if (free) {
1817 for (i = 0; i < free; ++i) {
1818 /* Bypass com_addop_varname because it will generate
1819 LOAD_DEREF but LOAD_CLOSURE is needed.
1820 */
1821 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1822 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001823
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001824 /* Special case: If a class contains a method with a
1825 free variable that has the same name as a method,
1826 the name will be considered free *and* local in the
1827 class. It should be handled by the closure, as
1828 well as by the normal name loookup logic.
1829 */
1830 reftype = get_ref_type(c, name);
1831 if (reftype == CELL)
1832 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1833 else /* (reftype == FREE) */
1834 arg = compiler_lookup_arg(c->u->u_freevars, name);
1835 if (arg == -1) {
1836 fprintf(stderr,
1837 "lookup %s in %s %d %d\n"
1838 "freevars of %s: %s\n",
1839 PyUnicode_AsUTF8(PyObject_Repr(name)),
1840 PyUnicode_AsUTF8(c->u->u_name),
1841 reftype, arg,
1842 PyUnicode_AsUTF8(co->co_name),
1843 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1844 Py_FatalError("compiler_make_closure()");
1845 }
1846 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001848 flags |= 0x08;
1849 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001851 ADDOP_LOAD_CONST(c, (PyObject*)co);
1852 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001853 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855}
1856
1857static int
1858compiler_decorators(struct compiler *c, asdl_seq* decos)
1859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (!decos)
1863 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1866 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1867 }
1868 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869}
1870
1871static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001872compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001874{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001875 /* Push a dict of keyword-only default values.
1876
1877 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1878 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001879 int i;
1880 PyObject *keys = NULL;
1881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1883 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1884 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1885 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001886 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001887 if (!mangled) {
1888 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001890 if (keys == NULL) {
1891 keys = PyList_New(1);
1892 if (keys == NULL) {
1893 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001894 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001895 }
1896 PyList_SET_ITEM(keys, 0, mangled);
1897 }
1898 else {
1899 int res = PyList_Append(keys, mangled);
1900 Py_DECREF(mangled);
1901 if (res == -1) {
1902 goto error;
1903 }
1904 }
1905 if (!compiler_visit_expr(c, default_)) {
1906 goto error;
1907 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
1909 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 if (keys != NULL) {
1911 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1912 PyObject *keys_tuple = PyList_AsTuple(keys);
1913 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001915 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001916 assert(default_count > 0);
1917 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918 }
1919 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001920 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001921 }
1922
1923error:
1924 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001925 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001926}
1927
1928static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001929compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1930{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001931 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001932 return 1;
1933}
1934
1935static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001936compiler_visit_argannotation(struct compiler *c, identifier id,
1937 expr_ty annotation, PyObject *names)
1938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001940 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001941 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1942 VISIT(c, annexpr, annotation)
1943 }
1944 else {
1945 VISIT(c, expr, annotation);
1946 }
Victor Stinner065efc32014-02-18 22:07:56 +01001947 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001948 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001949 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001950 if (PyList_Append(names, mangled) < 0) {
1951 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001952 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001953 }
1954 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001956 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001957}
1958
1959static int
1960compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1961 PyObject *names)
1962{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001963 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 for (i = 0; i < asdl_seq_LEN(args); i++) {
1965 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001966 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 c,
1968 arg->arg,
1969 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001970 names))
1971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001973 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001974}
1975
1976static int
1977compiler_visit_annotations(struct compiler *c, arguments_ty args,
1978 expr_ty returns)
1979{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001980 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001981 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001982
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001983 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 */
1985 static identifier return_str;
1986 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001987 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 names = PyList_New(0);
1989 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001990 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001991
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001992 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01001994 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
1995 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001996 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001997 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001998 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002000 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002002 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002003 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002004 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (!return_str) {
2008 return_str = PyUnicode_InternFromString("return");
2009 if (!return_str)
2010 goto error;
2011 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002012 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 goto error;
2014 }
2015
2016 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 PyObject *keytuple = PyList_AsTuple(names);
2019 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002020 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002022 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002024 else {
2025 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002026 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002027 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002028
2029error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002031 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002032}
2033
2034static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002035compiler_visit_defaults(struct compiler *c, arguments_ty args)
2036{
2037 VISIT_SEQ(c, expr, args->defaults);
2038 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2039 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040}
2041
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002042static Py_ssize_t
2043compiler_default_arguments(struct compiler *c, arguments_ty args)
2044{
2045 Py_ssize_t funcflags = 0;
2046 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002047 if (!compiler_visit_defaults(c, args))
2048 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002049 funcflags |= 0x01;
2050 }
2051 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002052 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002053 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002054 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002055 return -1;
2056 }
2057 else if (res > 0) {
2058 funcflags |= 0x02;
2059 }
2060 }
2061 return funcflags;
2062}
2063
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064static int
Yury Selivanov75445082015-05-11 22:57:16 -04002065compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002068 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002069 arguments_ty args;
2070 expr_ty returns;
2071 identifier name;
2072 asdl_seq* decos;
2073 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002074 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002075 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002076 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002077 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078
Yury Selivanov75445082015-05-11 22:57:16 -04002079 if (is_async) {
2080 assert(s->kind == AsyncFunctionDef_kind);
2081
2082 args = s->v.AsyncFunctionDef.args;
2083 returns = s->v.AsyncFunctionDef.returns;
2084 decos = s->v.AsyncFunctionDef.decorator_list;
2085 name = s->v.AsyncFunctionDef.name;
2086 body = s->v.AsyncFunctionDef.body;
2087
2088 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2089 } else {
2090 assert(s->kind == FunctionDef_kind);
2091
2092 args = s->v.FunctionDef.args;
2093 returns = s->v.FunctionDef.returns;
2094 decos = s->v.FunctionDef.decorator_list;
2095 name = s->v.FunctionDef.name;
2096 body = s->v.FunctionDef.body;
2097
2098 scope_type = COMPILER_SCOPE_FUNCTION;
2099 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (!compiler_decorators(c, decos))
2102 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002103
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002104 firstlineno = s->lineno;
2105 if (asdl_seq_LEN(decos)) {
2106 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2107 }
2108
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 funcflags = compiler_default_arguments(c, args);
2110 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 }
2113
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002114 annotations = compiler_visit_annotations(c, args, returns);
2115 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116 return 0;
2117 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002118 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002119 funcflags |= 0x04;
2120 }
2121
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002122 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002123 return 0;
2124 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125
INADA Naokicb41b272017-02-23 00:31:59 +09002126 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002127 if (c->c_optimize < 2) {
2128 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002129 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002130 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 compiler_exit_scope(c);
2132 return 0;
2133 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002136 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002138 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002140 qualname = c->u->u_qualname;
2141 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002143 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002144 Py_XDECREF(qualname);
2145 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002147 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002149 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002150 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 /* decorators */
2154 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2155 ADDOP_I(c, CALL_FUNCTION, 1);
2156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Yury Selivanov75445082015-05-11 22:57:16 -04002158 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159}
2160
2161static int
2162compiler_class(struct compiler *c, stmt_ty s)
2163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyCodeObject *co;
2165 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002166 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (!compiler_decorators(c, decos))
2170 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002171
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002172 firstlineno = s->lineno;
2173 if (asdl_seq_LEN(decos)) {
2174 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2175 }
2176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* ultimately generate code for:
2178 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2179 where:
2180 <func> is a function/closure created from the class body;
2181 it has a single argument (__locals__) where the dict
2182 (or MutableSequence) representing the locals is passed
2183 <name> is the class name
2184 <bases> is the positional arguments and *varargs argument
2185 <keywords> is the keyword arguments and **kwds argument
2186 This borrows from compiler_call.
2187 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002190 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002191 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return 0;
2193 /* this block represents what we do in the new scope */
2194 {
2195 /* use the class name for name mangling */
2196 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002197 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* load (global) __name__ ... */
2199 str = PyUnicode_InternFromString("__name__");
2200 if (!str || !compiler_nameop(c, str, Load)) {
2201 Py_XDECREF(str);
2202 compiler_exit_scope(c);
2203 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 Py_DECREF(str);
2206 /* ... and store it as __module__ */
2207 str = PyUnicode_InternFromString("__module__");
2208 if (!str || !compiler_nameop(c, str, Store)) {
2209 Py_XDECREF(str);
2210 compiler_exit_scope(c);
2211 return 0;
2212 }
2213 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002214 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002215 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002216 str = PyUnicode_InternFromString("__qualname__");
2217 if (!str || !compiler_nameop(c, str, Store)) {
2218 Py_XDECREF(str);
2219 compiler_exit_scope(c);
2220 return 0;
2221 }
2222 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002224 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 compiler_exit_scope(c);
2226 return 0;
2227 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002228 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002229 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002230 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002231 str = PyUnicode_InternFromString("__class__");
2232 if (str == NULL) {
2233 compiler_exit_scope(c);
2234 return 0;
2235 }
2236 i = compiler_lookup_arg(c->u->u_cellvars, str);
2237 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002238 if (i < 0) {
2239 compiler_exit_scope(c);
2240 return 0;
2241 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002242 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002245 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002246 str = PyUnicode_InternFromString("__classcell__");
2247 if (!str || !compiler_nameop(c, str, Store)) {
2248 Py_XDECREF(str);
2249 compiler_exit_scope(c);
2250 return 0;
2251 }
2252 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002254 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002255 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002256 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002257 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002258 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002259 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* create the code object */
2261 co = assemble(c, 1);
2262 }
2263 /* leave the new scope */
2264 compiler_exit_scope(c);
2265 if (co == NULL)
2266 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 /* 2. load the 'build_class' function */
2269 ADDOP(c, LOAD_BUILD_CLASS);
2270
2271 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002272 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 Py_DECREF(co);
2274
2275 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002276 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277
2278 /* 5. generate the rest of the code for the call */
2279 if (!compiler_call_helper(c, 2,
2280 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002281 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 return 0;
2283
2284 /* 6. apply decorators */
2285 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2286 ADDOP_I(c, CALL_FUNCTION, 1);
2287 }
2288
2289 /* 7. store into <name> */
2290 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2291 return 0;
2292 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293}
2294
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002295/* Return 0 if the expression is a constant value except named singletons.
2296 Return 1 otherwise. */
2297static int
2298check_is_arg(expr_ty e)
2299{
2300 if (e->kind != Constant_kind) {
2301 return 1;
2302 }
2303 PyObject *value = e->v.Constant.value;
2304 return (value == Py_None
2305 || value == Py_False
2306 || value == Py_True
2307 || value == Py_Ellipsis);
2308}
2309
2310/* Check operands of identity chacks ("is" and "is not").
2311 Emit a warning if any operand is a constant except named singletons.
2312 Return 0 on error.
2313 */
2314static int
2315check_compare(struct compiler *c, expr_ty e)
2316{
2317 Py_ssize_t i, n;
2318 int left = check_is_arg(e->v.Compare.left);
2319 n = asdl_seq_LEN(e->v.Compare.ops);
2320 for (i = 0; i < n; i++) {
2321 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2322 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2323 if (op == Is || op == IsNot) {
2324 if (!right || !left) {
2325 const char *msg = (op == Is)
2326 ? "\"is\" with a literal. Did you mean \"==\"?"
2327 : "\"is not\" with a literal. Did you mean \"!=\"?";
2328 return compiler_warn(c, msg);
2329 }
2330 }
2331 left = right;
2332 }
2333 return 1;
2334}
2335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002337cmpop(cmpop_ty op)
2338{
2339 switch (op) {
2340 case Eq:
2341 return PyCmp_EQ;
2342 case NotEq:
2343 return PyCmp_NE;
2344 case Lt:
2345 return PyCmp_LT;
2346 case LtE:
2347 return PyCmp_LE;
2348 case Gt:
2349 return PyCmp_GT;
2350 case GtE:
2351 return PyCmp_GE;
2352 case Is:
2353 return PyCmp_IS;
2354 case IsNot:
2355 return PyCmp_IS_NOT;
2356 case In:
2357 return PyCmp_IN;
2358 case NotIn:
2359 return PyCmp_NOT_IN;
2360 default:
2361 return PyCmp_BAD;
2362 }
2363}
2364
2365static int
2366compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2367{
2368 switch (e->kind) {
2369 case UnaryOp_kind:
2370 if (e->v.UnaryOp.op == Not)
2371 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2372 /* fallback to general implementation */
2373 break;
2374 case BoolOp_kind: {
2375 asdl_seq *s = e->v.BoolOp.values;
2376 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2377 assert(n >= 0);
2378 int cond2 = e->v.BoolOp.op == Or;
2379 basicblock *next2 = next;
2380 if (!cond2 != !cond) {
2381 next2 = compiler_new_block(c);
2382 if (next2 == NULL)
2383 return 0;
2384 }
2385 for (i = 0; i < n; ++i) {
2386 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2387 return 0;
2388 }
2389 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2390 return 0;
2391 if (next2 != next)
2392 compiler_use_next_block(c, next2);
2393 return 1;
2394 }
2395 case IfExp_kind: {
2396 basicblock *end, *next2;
2397 end = compiler_new_block(c);
2398 if (end == NULL)
2399 return 0;
2400 next2 = compiler_new_block(c);
2401 if (next2 == NULL)
2402 return 0;
2403 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2404 return 0;
2405 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2406 return 0;
2407 ADDOP_JREL(c, JUMP_FORWARD, end);
2408 compiler_use_next_block(c, next2);
2409 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2410 return 0;
2411 compiler_use_next_block(c, end);
2412 return 1;
2413 }
2414 case Compare_kind: {
2415 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2416 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002417 if (!check_compare(c, e)) {
2418 return 0;
2419 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002420 basicblock *cleanup = compiler_new_block(c);
2421 if (cleanup == NULL)
2422 return 0;
2423 VISIT(c, expr, e->v.Compare.left);
2424 for (i = 0; i < n; i++) {
2425 VISIT(c, expr,
2426 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2427 ADDOP(c, DUP_TOP);
2428 ADDOP(c, ROT_THREE);
2429 ADDOP_I(c, COMPARE_OP,
2430 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2431 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2432 NEXT_BLOCK(c);
2433 }
2434 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2435 ADDOP_I(c, COMPARE_OP,
2436 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2437 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2438 basicblock *end = compiler_new_block(c);
2439 if (end == NULL)
2440 return 0;
2441 ADDOP_JREL(c, JUMP_FORWARD, end);
2442 compiler_use_next_block(c, cleanup);
2443 ADDOP(c, POP_TOP);
2444 if (!cond) {
2445 ADDOP_JREL(c, JUMP_FORWARD, next);
2446 }
2447 compiler_use_next_block(c, end);
2448 return 1;
2449 }
2450 /* fallback to general implementation */
2451 break;
2452 }
2453 default:
2454 /* fallback to general implementation */
2455 break;
2456 }
2457
2458 /* general implementation */
2459 VISIT(c, expr, e);
2460 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2461 return 1;
2462}
2463
2464static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002465compiler_ifexp(struct compiler *c, expr_ty e)
2466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 basicblock *end, *next;
2468
2469 assert(e->kind == IfExp_kind);
2470 end = compiler_new_block(c);
2471 if (end == NULL)
2472 return 0;
2473 next = compiler_new_block(c);
2474 if (next == NULL)
2475 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2477 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 VISIT(c, expr, e->v.IfExp.body);
2479 ADDOP_JREL(c, JUMP_FORWARD, end);
2480 compiler_use_next_block(c, next);
2481 VISIT(c, expr, e->v.IfExp.orelse);
2482 compiler_use_next_block(c, end);
2483 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002484}
2485
2486static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487compiler_lambda(struct compiler *c, expr_ty e)
2488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002490 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002492 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 arguments_ty args = e->v.Lambda.args;
2494 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (!name) {
2497 name = PyUnicode_InternFromString("<lambda>");
2498 if (!name)
2499 return 0;
2500 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002502 funcflags = compiler_default_arguments(c, args);
2503 if (funcflags == -1) {
2504 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002506
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002507 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002508 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 /* Make None the first constant, so the lambda can't have a
2512 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002513 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002517 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2519 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2520 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002521 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 }
2523 else {
2524 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002525 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002527 qualname = c->u->u_qualname;
2528 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002530 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002533 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002534 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 Py_DECREF(co);
2536
2537 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538}
2539
2540static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541compiler_if(struct compiler *c, stmt_ty s)
2542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 basicblock *end, *next;
2544 int constant;
2545 assert(s->kind == If_kind);
2546 end = compiler_new_block(c);
2547 if (end == NULL)
2548 return 0;
2549
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002550 constant = expr_constant(s->v.If.test);
Pablo Galindoaf8646c2019-05-17 11:37:08 +01002551 /* constant = 0: "if 0" Leave the optimizations to
2552 * the pephole optimizer to check for syntax errors
2553 * in the block.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 * constant = 1: "if 1", "if 2", ...
2555 * constant = -1: rest */
Pablo Galindoaf8646c2019-05-17 11:37:08 +01002556 if (constant == 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 VISIT_SEQ(c, stmt, s->v.If.body);
2558 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002559 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 next = compiler_new_block(c);
2561 if (next == NULL)
2562 return 0;
2563 }
2564 else
2565 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002566 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2567 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002569 if (asdl_seq_LEN(s->v.If.orelse)) {
2570 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 compiler_use_next_block(c, next);
2572 VISIT_SEQ(c, stmt, s->v.If.orelse);
2573 }
2574 }
2575 compiler_use_next_block(c, end);
2576 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002577}
2578
2579static int
2580compiler_for(struct compiler *c, stmt_ty s)
2581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 start = compiler_new_block(c);
2585 cleanup = compiler_new_block(c);
2586 end = compiler_new_block(c);
2587 if (start == NULL || end == NULL || cleanup == NULL)
2588 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002589
2590 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 VISIT(c, expr, s->v.For.iter);
2594 ADDOP(c, GET_ITER);
2595 compiler_use_next_block(c, start);
2596 ADDOP_JREL(c, FOR_ITER, cleanup);
2597 VISIT(c, expr, s->v.For.target);
2598 VISIT_SEQ(c, stmt, s->v.For.body);
2599 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2600 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002601
2602 compiler_pop_fblock(c, FOR_LOOP, start);
2603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 VISIT_SEQ(c, stmt, s->v.For.orelse);
2605 compiler_use_next_block(c, end);
2606 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607}
2608
Yury Selivanov75445082015-05-11 22:57:16 -04002609
2610static int
2611compiler_async_for(struct compiler *c, stmt_ty s)
2612{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002613 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002614 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2615 c->u->u_ste->ste_coroutine = 1;
2616 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002617 return compiler_error(c, "'async for' outside async function");
2618 }
2619
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002620 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002621 except = compiler_new_block(c);
2622 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002623
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002624 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002625 return 0;
2626
2627 VISIT(c, expr, s->v.AsyncFor.iter);
2628 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002629
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002630 compiler_use_next_block(c, start);
2631 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2632 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002633
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002634 /* SETUP_FINALLY to guard the __anext__ call */
2635 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002636 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002637 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002638 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002639 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002640
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002641 /* Success block for __anext__ */
2642 VISIT(c, expr, s->v.AsyncFor.target);
2643 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2644 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2645
2646 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002647
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002648 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002649 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002650 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002651
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002652 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002653 VISIT_SEQ(c, stmt, s->v.For.orelse);
2654
2655 compiler_use_next_block(c, end);
2656
2657 return 1;
2658}
2659
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660static int
2661compiler_while(struct compiler *c, stmt_ty s)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002664 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 if (constant == 0) {
2667 if (s->v.While.orelse)
2668 VISIT_SEQ(c, stmt, s->v.While.orelse);
2669 return 1;
2670 }
2671 loop = compiler_new_block(c);
2672 end = compiler_new_block(c);
2673 if (constant == -1) {
2674 anchor = compiler_new_block(c);
2675 if (anchor == NULL)
2676 return 0;
2677 }
2678 if (loop == NULL || end == NULL)
2679 return 0;
2680 if (s->v.While.orelse) {
2681 orelse = compiler_new_block(c);
2682 if (orelse == NULL)
2683 return 0;
2684 }
2685 else
2686 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002689 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 return 0;
2691 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002692 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2693 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
2695 VISIT_SEQ(c, stmt, s->v.While.body);
2696 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 /* XXX should the two POP instructions be in a separate block
2699 if there is no else clause ?
2700 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002702 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002704 compiler_pop_fblock(c, WHILE_LOOP, loop);
2705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 if (orelse != NULL) /* what if orelse is just pass? */
2707 VISIT_SEQ(c, stmt, s->v.While.orelse);
2708 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711}
2712
2713static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002714compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002716 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002717 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002718 if (c->u->u_ste->ste_type != FunctionBlock)
2719 return compiler_error(c, "'return' outside function");
2720 if (s->v.Return.value != NULL &&
2721 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2722 {
2723 return compiler_error(
2724 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002726 if (preserve_tos) {
2727 VISIT(c, expr, s->v.Return.value);
2728 }
2729 for (int depth = c->u->u_nfblocks; depth--;) {
2730 struct fblockinfo *info = &c->u->u_fblock[depth];
2731
2732 if (!compiler_unwind_fblock(c, info, preserve_tos))
2733 return 0;
2734 }
2735 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002736 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002737 }
2738 else if (!preserve_tos) {
2739 VISIT(c, expr, s->v.Return.value);
2740 }
2741 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744}
2745
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002746static int
2747compiler_break(struct compiler *c)
2748{
2749 for (int depth = c->u->u_nfblocks; depth--;) {
2750 struct fblockinfo *info = &c->u->u_fblock[depth];
2751
2752 if (!compiler_unwind_fblock(c, info, 0))
2753 return 0;
2754 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2755 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2756 return 1;
2757 }
2758 }
2759 return compiler_error(c, "'break' outside loop");
2760}
2761
2762static int
2763compiler_continue(struct compiler *c)
2764{
2765 for (int depth = c->u->u_nfblocks; depth--;) {
2766 struct fblockinfo *info = &c->u->u_fblock[depth];
2767
2768 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2769 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2770 return 1;
2771 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002772 if (!compiler_unwind_fblock(c, info, 0))
2773 return 0;
2774 }
2775 return compiler_error(c, "'continue' not properly in loop");
2776}
2777
2778
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780
2781 SETUP_FINALLY L
2782 <code for body>
2783 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 BEGIN_FINALLY
2785 L:
2786 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 END_FINALLY
2788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789 The special instructions use the block stack. Each block
2790 stack entry contains the instruction that created it (here
2791 SETUP_FINALLY), the level of the value stack at the time the
2792 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 Pushes the current value stack level and the label
2796 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002798 Pops en entry from the block stack.
2799 BEGIN_FINALLY
2800 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002802 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2803 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806 when a SETUP_FINALLY entry is found, the raised and the caught
2807 exceptions are pushed onto the value stack (and the exception
2808 condition is cleared), and the interpreter jumps to the label
2809 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810*/
2811
2812static int
2813compiler_try_finally(struct compiler *c, stmt_ty s)
2814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 body = compiler_new_block(c);
2818 end = compiler_new_block(c);
2819 if (body == NULL || end == NULL)
2820 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002822 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 ADDOP_JREL(c, SETUP_FINALLY, end);
2824 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002827 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2828 if (!compiler_try_except(c, s))
2829 return 0;
2830 }
2831 else {
2832 VISIT_SEQ(c, stmt, s->v.Try.body);
2833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002835 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002838 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002840 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002842 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 ADDOP(c, END_FINALLY);
2844 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846}
2847
2848/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002849 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850 (The contents of the value stack is shown in [], with the top
2851 at the right; 'tb' is trace-back info, 'val' the exception's
2852 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853
2854 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002855 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 [] <code for S>
2857 [] POP_BLOCK
2858 [] JUMP_FORWARD L0
2859
2860 [tb, val, exc] L1: DUP )
2861 [tb, val, exc, exc] <evaluate E1> )
2862 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2863 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2864 [tb, val, exc] POP
2865 [tb, val] <assign to V1> (or POP if no V1)
2866 [tb] POP
2867 [] <code for S1>
2868 JUMP_FORWARD L0
2869
2870 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871 .............................etc.......................
2872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2874
2875 [] L0: <next statement>
2876
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877 Of course, parts are not generated if Vi or Ei is not present.
2878*/
2879static int
2880compiler_try_except(struct compiler *c, stmt_ty s)
2881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002883 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 body = compiler_new_block(c);
2886 except = compiler_new_block(c);
2887 orelse = compiler_new_block(c);
2888 end = compiler_new_block(c);
2889 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2890 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002893 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002895 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 ADDOP(c, POP_BLOCK);
2897 compiler_pop_fblock(c, EXCEPT, body);
2898 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002899 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 compiler_use_next_block(c, except);
2901 for (i = 0; i < n; i++) {
2902 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002903 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 if (!handler->v.ExceptHandler.type && i < n-1)
2905 return compiler_error(c, "default 'except:' must be last");
2906 c->u->u_lineno_set = 0;
2907 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002908 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 except = compiler_new_block(c);
2910 if (except == NULL)
2911 return 0;
2912 if (handler->v.ExceptHandler.type) {
2913 ADDOP(c, DUP_TOP);
2914 VISIT(c, expr, handler->v.ExceptHandler.type);
2915 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2916 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2917 }
2918 ADDOP(c, POP_TOP);
2919 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002920 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002921
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002922 cleanup_end = compiler_new_block(c);
2923 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002924 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002925 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002926 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002927
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002928 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2929 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002931 /*
2932 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002933 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002934 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002935 try:
2936 # body
2937 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10002938 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002939 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002940 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002942 /* second try: */
2943 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2944 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002945 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002946 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002948 /* second # body */
2949 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2950 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002951 ADDOP(c, BEGIN_FINALLY);
2952 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002954 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002955 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002956 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002957 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002959 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002960 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002961 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002962 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002964 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002965 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002966 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 }
2968 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002969 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002971 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002972 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002973 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974
Guido van Rossumb940e112007-01-10 16:19:56 +00002975 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002976 ADDOP(c, POP_TOP);
2977 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002978 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002979 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002981 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002982 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 }
2984 ADDOP_JREL(c, JUMP_FORWARD, end);
2985 compiler_use_next_block(c, except);
2986 }
2987 ADDOP(c, END_FINALLY);
2988 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002989 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 compiler_use_next_block(c, end);
2991 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992}
2993
2994static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002995compiler_try(struct compiler *c, stmt_ty s) {
2996 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2997 return compiler_try_finally(c, s);
2998 else
2999 return compiler_try_except(c, s);
3000}
3001
3002
3003static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004compiler_import_as(struct compiler *c, identifier name, identifier asname)
3005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* The IMPORT_NAME opcode was already generated. This function
3007 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003010 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003012 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3013 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003015 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003016 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003018 while (1) {
3019 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003021 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003022 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003023 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003024 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003026 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003027 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003028 if (dot == -1) {
3029 break;
3030 }
3031 ADDOP(c, ROT_TWO);
3032 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003034 if (!compiler_nameop(c, asname, Store)) {
3035 return 0;
3036 }
3037 ADDOP(c, POP_TOP);
3038 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 }
3040 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041}
3042
3043static int
3044compiler_import(struct compiler *c, stmt_ty s)
3045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 /* The Import node stores a module name like a.b.c as a single
3047 string. This is convenient for all cases except
3048 import a.b.c as d
3049 where we need to parse that string to extract the individual
3050 module names.
3051 XXX Perhaps change the representation to make this case simpler?
3052 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003053 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 for (i = 0; i < n; i++) {
3056 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3057 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003059 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3060 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 if (alias->asname) {
3064 r = compiler_import_as(c, alias->name, alias->asname);
3065 if (!r)
3066 return r;
3067 }
3068 else {
3069 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003070 Py_ssize_t dot = PyUnicode_FindChar(
3071 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003072 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003074 if (tmp == NULL)
3075 return 0;
3076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003078 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 Py_DECREF(tmp);
3080 }
3081 if (!r)
3082 return r;
3083 }
3084 }
3085 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086}
3087
3088static int
3089compiler_from_import(struct compiler *c, stmt_ty s)
3090{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003091 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003092 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 if (!empty_string) {
3096 empty_string = PyUnicode_FromString("");
3097 if (!empty_string)
3098 return 0;
3099 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003100
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003101 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003102
3103 names = PyTuple_New(n);
3104 if (!names)
3105 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 /* build up the names */
3108 for (i = 0; i < n; i++) {
3109 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3110 Py_INCREF(alias->name);
3111 PyTuple_SET_ITEM(names, i, alias->name);
3112 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003115 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 Py_DECREF(names);
3117 return compiler_error(c, "from __future__ imports must occur "
3118 "at the beginning of the file");
3119 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003120 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 if (s->v.ImportFrom.module) {
3123 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3124 }
3125 else {
3126 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3127 }
3128 for (i = 0; i < n; i++) {
3129 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3130 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003132 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 assert(n == 1);
3134 ADDOP(c, IMPORT_STAR);
3135 return 1;
3136 }
3137
3138 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3139 store_name = alias->name;
3140 if (alias->asname)
3141 store_name = alias->asname;
3142
3143 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 return 0;
3145 }
3146 }
3147 /* remove imported module */
3148 ADDOP(c, POP_TOP);
3149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150}
3151
3152static int
3153compiler_assert(struct compiler *c, stmt_ty s)
3154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 static PyObject *assertion_error = NULL;
3156 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157
Georg Brandl8334fd92010-12-04 10:26:46 +00003158 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 return 1;
3160 if (assertion_error == NULL) {
3161 assertion_error = PyUnicode_InternFromString("AssertionError");
3162 if (assertion_error == NULL)
3163 return 0;
3164 }
3165 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003166 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3167 {
3168 if (!compiler_warn(c, "assertion is always true, "
3169 "perhaps remove parentheses?"))
3170 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003171 return 0;
3172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 end = compiler_new_block(c);
3175 if (end == NULL)
3176 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003177 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3178 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3180 if (s->v.Assert.msg) {
3181 VISIT(c, expr, s->v.Assert.msg);
3182 ADDOP_I(c, CALL_FUNCTION, 1);
3183 }
3184 ADDOP_I(c, RAISE_VARARGS, 1);
3185 compiler_use_next_block(c, end);
3186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187}
3188
3189static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003190compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3191{
3192 if (c->c_interactive && c->c_nestlevel <= 1) {
3193 VISIT(c, expr, value);
3194 ADDOP(c, PRINT_EXPR);
3195 return 1;
3196 }
3197
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003198 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003199 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003200 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003201 }
3202
3203 VISIT(c, expr, value);
3204 ADDOP(c, POP_TOP);
3205 return 1;
3206}
3207
3208static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209compiler_visit_stmt(struct compiler *c, stmt_ty s)
3210{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003211 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 /* Always assign a lineno to the next instruction for a stmt. */
3214 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003215 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 switch (s->kind) {
3219 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003220 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 case ClassDef_kind:
3222 return compiler_class(c, s);
3223 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003224 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 case Delete_kind:
3226 VISIT_SEQ(c, expr, s->v.Delete.targets)
3227 break;
3228 case Assign_kind:
3229 n = asdl_seq_LEN(s->v.Assign.targets);
3230 VISIT(c, expr, s->v.Assign.value);
3231 for (i = 0; i < n; i++) {
3232 if (i < n - 1)
3233 ADDOP(c, DUP_TOP);
3234 VISIT(c, expr,
3235 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3236 }
3237 break;
3238 case AugAssign_kind:
3239 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003240 case AnnAssign_kind:
3241 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 case For_kind:
3243 return compiler_for(c, s);
3244 case While_kind:
3245 return compiler_while(c, s);
3246 case If_kind:
3247 return compiler_if(c, s);
3248 case Raise_kind:
3249 n = 0;
3250 if (s->v.Raise.exc) {
3251 VISIT(c, expr, s->v.Raise.exc);
3252 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003253 if (s->v.Raise.cause) {
3254 VISIT(c, expr, s->v.Raise.cause);
3255 n++;
3256 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003258 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003260 case Try_kind:
3261 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 case Assert_kind:
3263 return compiler_assert(c, s);
3264 case Import_kind:
3265 return compiler_import(c, s);
3266 case ImportFrom_kind:
3267 return compiler_from_import(c, s);
3268 case Global_kind:
3269 case Nonlocal_kind:
3270 break;
3271 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003272 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 case Pass_kind:
3274 break;
3275 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003276 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 case Continue_kind:
3278 return compiler_continue(c);
3279 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003280 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003281 case AsyncFunctionDef_kind:
3282 return compiler_function(c, s, 1);
3283 case AsyncWith_kind:
3284 return compiler_async_with(c, s, 0);
3285 case AsyncFor_kind:
3286 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 }
Yury Selivanov75445082015-05-11 22:57:16 -04003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290}
3291
3292static int
3293unaryop(unaryop_ty op)
3294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 switch (op) {
3296 case Invert:
3297 return UNARY_INVERT;
3298 case Not:
3299 return UNARY_NOT;
3300 case UAdd:
3301 return UNARY_POSITIVE;
3302 case USub:
3303 return UNARY_NEGATIVE;
3304 default:
3305 PyErr_Format(PyExc_SystemError,
3306 "unary op %d should not be possible", op);
3307 return 0;
3308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309}
3310
3311static int
3312binop(struct compiler *c, operator_ty op)
3313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 switch (op) {
3315 case Add:
3316 return BINARY_ADD;
3317 case Sub:
3318 return BINARY_SUBTRACT;
3319 case Mult:
3320 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003321 case MatMult:
3322 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 case Div:
3324 return BINARY_TRUE_DIVIDE;
3325 case Mod:
3326 return BINARY_MODULO;
3327 case Pow:
3328 return BINARY_POWER;
3329 case LShift:
3330 return BINARY_LSHIFT;
3331 case RShift:
3332 return BINARY_RSHIFT;
3333 case BitOr:
3334 return BINARY_OR;
3335 case BitXor:
3336 return BINARY_XOR;
3337 case BitAnd:
3338 return BINARY_AND;
3339 case FloorDiv:
3340 return BINARY_FLOOR_DIVIDE;
3341 default:
3342 PyErr_Format(PyExc_SystemError,
3343 "binary op %d should not be possible", op);
3344 return 0;
3345 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346}
3347
3348static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349inplace_binop(struct compiler *c, operator_ty op)
3350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 switch (op) {
3352 case Add:
3353 return INPLACE_ADD;
3354 case Sub:
3355 return INPLACE_SUBTRACT;
3356 case Mult:
3357 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003358 case MatMult:
3359 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 case Div:
3361 return INPLACE_TRUE_DIVIDE;
3362 case Mod:
3363 return INPLACE_MODULO;
3364 case Pow:
3365 return INPLACE_POWER;
3366 case LShift:
3367 return INPLACE_LSHIFT;
3368 case RShift:
3369 return INPLACE_RSHIFT;
3370 case BitOr:
3371 return INPLACE_OR;
3372 case BitXor:
3373 return INPLACE_XOR;
3374 case BitAnd:
3375 return INPLACE_AND;
3376 case FloorDiv:
3377 return INPLACE_FLOOR_DIVIDE;
3378 default:
3379 PyErr_Format(PyExc_SystemError,
3380 "inplace binary op %d should not be possible", op);
3381 return 0;
3382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383}
3384
3385static int
3386compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3387{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003388 int op, scope;
3389 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 PyObject *dict = c->u->u_names;
3393 PyObject *mangled;
3394 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003396 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3397 !_PyUnicode_EqualToASCIIString(name, "True") &&
3398 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003399
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003400 mangled = _Py_Mangle(c->u->u_private, name);
3401 if (!mangled)
3402 return 0;
3403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 op = 0;
3405 optype = OP_NAME;
3406 scope = PyST_GetScope(c->u->u_ste, mangled);
3407 switch (scope) {
3408 case FREE:
3409 dict = c->u->u_freevars;
3410 optype = OP_DEREF;
3411 break;
3412 case CELL:
3413 dict = c->u->u_cellvars;
3414 optype = OP_DEREF;
3415 break;
3416 case LOCAL:
3417 if (c->u->u_ste->ste_type == FunctionBlock)
3418 optype = OP_FAST;
3419 break;
3420 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003421 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 optype = OP_GLOBAL;
3423 break;
3424 case GLOBAL_EXPLICIT:
3425 optype = OP_GLOBAL;
3426 break;
3427 default:
3428 /* scope can be 0 */
3429 break;
3430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003433 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 switch (optype) {
3436 case OP_DEREF:
3437 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003438 case Load:
3439 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3440 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003441 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003442 op = STORE_DEREF;
3443 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 case AugLoad:
3445 case AugStore:
3446 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003447 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 case Param:
3449 default:
3450 PyErr_SetString(PyExc_SystemError,
3451 "param invalid for deref variable");
3452 return 0;
3453 }
3454 break;
3455 case OP_FAST:
3456 switch (ctx) {
3457 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003458 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003459 op = STORE_FAST;
3460 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 case Del: op = DELETE_FAST; break;
3462 case AugLoad:
3463 case AugStore:
3464 break;
3465 case Param:
3466 default:
3467 PyErr_SetString(PyExc_SystemError,
3468 "param invalid for local variable");
3469 return 0;
3470 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003471 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 return 1;
3473 case OP_GLOBAL:
3474 switch (ctx) {
3475 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003476 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003477 op = STORE_GLOBAL;
3478 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 case Del: op = DELETE_GLOBAL; break;
3480 case AugLoad:
3481 case AugStore:
3482 break;
3483 case Param:
3484 default:
3485 PyErr_SetString(PyExc_SystemError,
3486 "param invalid for global variable");
3487 return 0;
3488 }
3489 break;
3490 case OP_NAME:
3491 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003492 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003493 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003494 op = STORE_NAME;
3495 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 case Del: op = DELETE_NAME; break;
3497 case AugLoad:
3498 case AugStore:
3499 break;
3500 case Param:
3501 default:
3502 PyErr_SetString(PyExc_SystemError,
3503 "param invalid for name variable");
3504 return 0;
3505 }
3506 break;
3507 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 assert(op);
3510 arg = compiler_add_o(c, dict, mangled);
3511 Py_DECREF(mangled);
3512 if (arg < 0)
3513 return 0;
3514 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515}
3516
3517static int
3518compiler_boolop(struct compiler *c, expr_ty e)
3519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003521 int jumpi;
3522 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 assert(e->kind == BoolOp_kind);
3526 if (e->v.BoolOp.op == And)
3527 jumpi = JUMP_IF_FALSE_OR_POP;
3528 else
3529 jumpi = JUMP_IF_TRUE_OR_POP;
3530 end = compiler_new_block(c);
3531 if (end == NULL)
3532 return 0;
3533 s = e->v.BoolOp.values;
3534 n = asdl_seq_LEN(s) - 1;
3535 assert(n >= 0);
3536 for (i = 0; i < n; ++i) {
3537 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3538 ADDOP_JABS(c, jumpi, end);
3539 }
3540 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3541 compiler_use_next_block(c, end);
3542 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543}
3544
3545static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003546starunpack_helper(struct compiler *c, asdl_seq *elts,
3547 int single_op, int inner_op, int outer_op)
3548{
3549 Py_ssize_t n = asdl_seq_LEN(elts);
3550 Py_ssize_t i, nsubitems = 0, nseen = 0;
3551 for (i = 0; i < n; i++) {
3552 expr_ty elt = asdl_seq_GET(elts, i);
3553 if (elt->kind == Starred_kind) {
3554 if (nseen) {
3555 ADDOP_I(c, inner_op, nseen);
3556 nseen = 0;
3557 nsubitems++;
3558 }
3559 VISIT(c, expr, elt->v.Starred.value);
3560 nsubitems++;
3561 }
3562 else {
3563 VISIT(c, expr, elt);
3564 nseen++;
3565 }
3566 }
3567 if (nsubitems) {
3568 if (nseen) {
3569 ADDOP_I(c, inner_op, nseen);
3570 nsubitems++;
3571 }
3572 ADDOP_I(c, outer_op, nsubitems);
3573 }
3574 else
3575 ADDOP_I(c, single_op, nseen);
3576 return 1;
3577}
3578
3579static int
3580assignment_helper(struct compiler *c, asdl_seq *elts)
3581{
3582 Py_ssize_t n = asdl_seq_LEN(elts);
3583 Py_ssize_t i;
3584 int seen_star = 0;
3585 for (i = 0; i < n; i++) {
3586 expr_ty elt = asdl_seq_GET(elts, i);
3587 if (elt->kind == Starred_kind && !seen_star) {
3588 if ((i >= (1 << 8)) ||
3589 (n-i-1 >= (INT_MAX >> 8)))
3590 return compiler_error(c,
3591 "too many expressions in "
3592 "star-unpacking assignment");
3593 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3594 seen_star = 1;
3595 asdl_seq_SET(elts, i, elt->v.Starred.value);
3596 }
3597 else if (elt->kind == Starred_kind) {
3598 return compiler_error(c,
3599 "two starred expressions in assignment");
3600 }
3601 }
3602 if (!seen_star) {
3603 ADDOP_I(c, UNPACK_SEQUENCE, n);
3604 }
3605 VISIT_SEQ(c, expr, elts);
3606 return 1;
3607}
3608
3609static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610compiler_list(struct compiler *c, expr_ty e)
3611{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003612 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003613 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003614 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003616 else if (e->v.List.ctx == Load) {
3617 return starunpack_helper(c, elts,
3618 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003620 else
3621 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623}
3624
3625static int
3626compiler_tuple(struct compiler *c, expr_ty e)
3627{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003628 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003629 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003630 return assignment_helper(c, elts);
3631 }
3632 else if (e->v.Tuple.ctx == Load) {
3633 return starunpack_helper(c, elts,
3634 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3635 }
3636 else
3637 VISIT_SEQ(c, expr, elts);
3638 return 1;
3639}
3640
3641static int
3642compiler_set(struct compiler *c, expr_ty e)
3643{
3644 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3645 BUILD_SET, BUILD_SET_UNPACK);
3646}
3647
3648static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003649are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3650{
3651 Py_ssize_t i;
3652 for (i = begin; i < end; i++) {
3653 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003654 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003655 return 0;
3656 }
3657 return 1;
3658}
3659
3660static int
3661compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3662{
3663 Py_ssize_t i, n = end - begin;
3664 PyObject *keys, *key;
3665 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3666 for (i = begin; i < end; i++) {
3667 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3668 }
3669 keys = PyTuple_New(n);
3670 if (keys == NULL) {
3671 return 0;
3672 }
3673 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003674 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003675 Py_INCREF(key);
3676 PyTuple_SET_ITEM(keys, i - begin, key);
3677 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003678 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003679 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3680 }
3681 else {
3682 for (i = begin; i < end; i++) {
3683 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3684 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3685 }
3686 ADDOP_I(c, BUILD_MAP, n);
3687 }
3688 return 1;
3689}
3690
3691static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003692compiler_dict(struct compiler *c, expr_ty e)
3693{
Victor Stinner976bb402016-03-23 11:36:19 +01003694 Py_ssize_t i, n, elements;
3695 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003696 int is_unpacking = 0;
3697 n = asdl_seq_LEN(e->v.Dict.values);
3698 containers = 0;
3699 elements = 0;
3700 for (i = 0; i < n; i++) {
3701 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3702 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003703 if (!compiler_subdict(c, e, i - elements, i))
3704 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003705 containers++;
3706 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003708 if (is_unpacking) {
3709 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3710 containers++;
3711 }
3712 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003713 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 }
3715 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003716 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003717 if (!compiler_subdict(c, e, n - elements, n))
3718 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003719 containers++;
3720 }
3721 /* If there is more than one dict, they need to be merged into a new
3722 * dict. If there is one dict and it's an unpacking, then it needs
3723 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003724 if (containers > 1 || is_unpacking) {
3725 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 }
3727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728}
3729
3730static int
3731compiler_compare(struct compiler *c, expr_ty e)
3732{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003733 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003735 if (!check_compare(c, e)) {
3736 return 0;
3737 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003739 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3740 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3741 if (n == 0) {
3742 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3743 ADDOP_I(c, COMPARE_OP,
3744 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3745 }
3746 else {
3747 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 if (cleanup == NULL)
3749 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003750 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 VISIT(c, expr,
3752 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003753 ADDOP(c, DUP_TOP);
3754 ADDOP(c, ROT_THREE);
3755 ADDOP_I(c, COMPARE_OP,
3756 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3757 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3758 NEXT_BLOCK(c);
3759 }
3760 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3761 ADDOP_I(c, COMPARE_OP,
3762 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 basicblock *end = compiler_new_block(c);
3764 if (end == NULL)
3765 return 0;
3766 ADDOP_JREL(c, JUMP_FORWARD, end);
3767 compiler_use_next_block(c, cleanup);
3768 ADDOP(c, ROT_TWO);
3769 ADDOP(c, POP_TOP);
3770 compiler_use_next_block(c, end);
3771 }
3772 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773}
3774
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003775static PyTypeObject *
3776infer_type(expr_ty e)
3777{
3778 switch (e->kind) {
3779 case Tuple_kind:
3780 return &PyTuple_Type;
3781 case List_kind:
3782 case ListComp_kind:
3783 return &PyList_Type;
3784 case Dict_kind:
3785 case DictComp_kind:
3786 return &PyDict_Type;
3787 case Set_kind:
3788 case SetComp_kind:
3789 return &PySet_Type;
3790 case GeneratorExp_kind:
3791 return &PyGen_Type;
3792 case Lambda_kind:
3793 return &PyFunction_Type;
3794 case JoinedStr_kind:
3795 case FormattedValue_kind:
3796 return &PyUnicode_Type;
3797 case Constant_kind:
3798 return e->v.Constant.value->ob_type;
3799 default:
3800 return NULL;
3801 }
3802}
3803
3804static int
3805check_caller(struct compiler *c, expr_ty e)
3806{
3807 switch (e->kind) {
3808 case Constant_kind:
3809 case Tuple_kind:
3810 case List_kind:
3811 case ListComp_kind:
3812 case Dict_kind:
3813 case DictComp_kind:
3814 case Set_kind:
3815 case SetComp_kind:
3816 case GeneratorExp_kind:
3817 case JoinedStr_kind:
3818 case FormattedValue_kind:
3819 return compiler_warn(c, "'%.200s' object is not callable; "
3820 "perhaps you missed a comma?",
3821 infer_type(e)->tp_name);
3822 default:
3823 return 1;
3824 }
3825}
3826
3827static int
3828check_subscripter(struct compiler *c, expr_ty e)
3829{
3830 PyObject *v;
3831
3832 switch (e->kind) {
3833 case Constant_kind:
3834 v = e->v.Constant.value;
3835 if (!(v == Py_None || v == Py_Ellipsis ||
3836 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3837 PyAnySet_Check(v)))
3838 {
3839 return 1;
3840 }
3841 /* fall through */
3842 case Set_kind:
3843 case SetComp_kind:
3844 case GeneratorExp_kind:
3845 case Lambda_kind:
3846 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3847 "perhaps you missed a comma?",
3848 infer_type(e)->tp_name);
3849 default:
3850 return 1;
3851 }
3852}
3853
3854static int
3855check_index(struct compiler *c, expr_ty e, slice_ty s)
3856{
3857 PyObject *v;
3858
3859 if (s->kind != Index_kind) {
3860 return 1;
3861 }
3862 PyTypeObject *index_type = infer_type(s->v.Index.value);
3863 if (index_type == NULL
3864 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3865 || index_type == &PySlice_Type) {
3866 return 1;
3867 }
3868
3869 switch (e->kind) {
3870 case Constant_kind:
3871 v = e->v.Constant.value;
3872 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3873 return 1;
3874 }
3875 /* fall through */
3876 case Tuple_kind:
3877 case List_kind:
3878 case ListComp_kind:
3879 case JoinedStr_kind:
3880 case FormattedValue_kind:
3881 return compiler_warn(c, "%.200s indices must be integers or slices, "
3882 "not %.200s; "
3883 "perhaps you missed a comma?",
3884 infer_type(e)->tp_name,
3885 index_type->tp_name);
3886 default:
3887 return 1;
3888 }
3889}
3890
Zackery Spytz97f5de02019-03-22 01:30:32 -06003891// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003892static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003893maybe_optimize_method_call(struct compiler *c, expr_ty e)
3894{
3895 Py_ssize_t argsl, i;
3896 expr_ty meth = e->v.Call.func;
3897 asdl_seq *args = e->v.Call.args;
3898
3899 /* Check that the call node is an attribute access, and that
3900 the call doesn't have keyword parameters. */
3901 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3902 asdl_seq_LEN(e->v.Call.keywords))
3903 return -1;
3904
3905 /* Check that there are no *varargs types of arguments. */
3906 argsl = asdl_seq_LEN(args);
3907 for (i = 0; i < argsl; i++) {
3908 expr_ty elt = asdl_seq_GET(args, i);
3909 if (elt->kind == Starred_kind) {
3910 return -1;
3911 }
3912 }
3913
3914 /* Alright, we can optimize the code. */
3915 VISIT(c, expr, meth->v.Attribute.value);
3916 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3917 VISIT_SEQ(c, expr, e->v.Call.args);
3918 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3919 return 1;
3920}
3921
3922static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923compiler_call(struct compiler *c, expr_ty e)
3924{
Zackery Spytz97f5de02019-03-22 01:30:32 -06003925 int ret = maybe_optimize_method_call(c, e);
3926 if (ret >= 0) {
3927 return ret;
3928 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003929 if (!check_caller(c, e->v.Call.func)) {
3930 return 0;
3931 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 VISIT(c, expr, e->v.Call.func);
3933 return compiler_call_helper(c, 0,
3934 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003935 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003936}
3937
Eric V. Smith235a6f02015-09-19 14:51:32 -04003938static int
3939compiler_joined_str(struct compiler *c, expr_ty e)
3940{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003941 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003942 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3943 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003944 return 1;
3945}
3946
Eric V. Smitha78c7952015-11-03 12:45:05 -05003947/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003948static int
3949compiler_formatted_value(struct compiler *c, expr_ty e)
3950{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003951 /* Our oparg encodes 2 pieces of information: the conversion
3952 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003953
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003954 Convert the conversion char to 3 bits:
3955 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05003956 !s : 001 0x1 FVC_STR
3957 !r : 010 0x2 FVC_REPR
3958 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003959
Eric V. Smitha78c7952015-11-03 12:45:05 -05003960 next bit is whether or not we have a format spec:
3961 yes : 100 0x4
3962 no : 000 0x0
3963 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003964
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003965 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05003966 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003967
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003968 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003969 VISIT(c, expr, e->v.FormattedValue.value);
3970
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003971 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003972 case 's': oparg = FVC_STR; break;
3973 case 'r': oparg = FVC_REPR; break;
3974 case 'a': oparg = FVC_ASCII; break;
3975 case -1: oparg = FVC_NONE; break;
3976 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003977 PyErr_Format(PyExc_SystemError,
3978 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003979 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003980 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003981 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003982 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003983 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003984 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003985 }
3986
Eric V. Smitha78c7952015-11-03 12:45:05 -05003987 /* And push our opcode and oparg */
3988 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003989
Eric V. Smith235a6f02015-09-19 14:51:32 -04003990 return 1;
3991}
3992
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003993static int
3994compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3995{
3996 Py_ssize_t i, n = end - begin;
3997 keyword_ty kw;
3998 PyObject *keys, *key;
3999 assert(n > 0);
4000 if (n > 1) {
4001 for (i = begin; i < end; i++) {
4002 kw = asdl_seq_GET(keywords, i);
4003 VISIT(c, expr, kw->value);
4004 }
4005 keys = PyTuple_New(n);
4006 if (keys == NULL) {
4007 return 0;
4008 }
4009 for (i = begin; i < end; i++) {
4010 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4011 Py_INCREF(key);
4012 PyTuple_SET_ITEM(keys, i - begin, key);
4013 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004014 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004015 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4016 }
4017 else {
4018 /* a for loop only executes once */
4019 for (i = begin; i < end; i++) {
4020 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004021 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004022 VISIT(c, expr, kw->value);
4023 }
4024 ADDOP_I(c, BUILD_MAP, n);
4025 }
4026 return 1;
4027}
4028
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004029/* shared code between compiler_call and compiler_class */
4030static int
4031compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004032 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004033 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004034 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004035{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004036 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004037 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004038
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004039 /* the number of tuples and dictionaries on the stack */
4040 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4041
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004042 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004043 nkwelts = asdl_seq_LEN(keywords);
4044
4045 for (i = 0; i < nkwelts; i++) {
4046 keyword_ty kw = asdl_seq_GET(keywords, i);
4047 if (kw->arg == NULL) {
4048 mustdictunpack = 1;
4049 break;
4050 }
4051 }
4052
4053 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004054 for (i = 0; i < nelts; i++) {
4055 expr_ty elt = asdl_seq_GET(args, i);
4056 if (elt->kind == Starred_kind) {
4057 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004058 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004059 if (nseen) {
4060 ADDOP_I(c, BUILD_TUPLE, nseen);
4061 nseen = 0;
4062 nsubargs++;
4063 }
4064 VISIT(c, expr, elt->v.Starred.value);
4065 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004066 }
4067 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004068 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004069 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004072
4073 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004074 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004075 if (nseen) {
4076 /* Pack up any trailing positional arguments. */
4077 ADDOP_I(c, BUILD_TUPLE, nseen);
4078 nsubargs++;
4079 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004080 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004081 /* If we ended up with more than one stararg, we need
4082 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004083 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004084 }
4085 else if (nsubargs == 0) {
4086 ADDOP_I(c, BUILD_TUPLE, 0);
4087 }
4088 nseen = 0; /* the number of keyword arguments on the stack following */
4089 for (i = 0; i < nkwelts; i++) {
4090 keyword_ty kw = asdl_seq_GET(keywords, i);
4091 if (kw->arg == NULL) {
4092 /* A keyword argument unpacking. */
4093 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004094 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4095 return 0;
4096 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004097 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004098 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004099 VISIT(c, expr, kw->value);
4100 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004101 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004102 else {
4103 nseen++;
4104 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004105 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004106 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004107 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004108 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004109 return 0;
4110 nsubkwargs++;
4111 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004112 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004113 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004114 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004115 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004116 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4117 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004119 else if (nkwelts) {
4120 PyObject *names;
4121 VISIT_SEQ(c, keyword, keywords);
4122 names = PyTuple_New(nkwelts);
4123 if (names == NULL) {
4124 return 0;
4125 }
4126 for (i = 0; i < nkwelts; i++) {
4127 keyword_ty kw = asdl_seq_GET(keywords, i);
4128 Py_INCREF(kw->arg);
4129 PyTuple_SET_ITEM(names, i, kw->arg);
4130 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004131 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004132 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4133 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004135 else {
4136 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4137 return 1;
4138 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139}
4140
Nick Coghlan650f0d02007-04-15 12:05:43 +00004141
4142/* List and set comprehensions and generator expressions work by creating a
4143 nested function to perform the actual iteration. This means that the
4144 iteration variables don't leak into the current scope.
4145 The defined function is called immediately following its definition, with the
4146 result of that call being the result of the expression.
4147 The LC/SC version returns the populated container, while the GE version is
4148 flagged in symtable.c as a generator, so it returns the generator object
4149 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004150
4151 Possible cleanups:
4152 - iterate over the generator sequence instead of using recursion
4153*/
4154
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004155
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004156static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157compiler_comprehension_generator(struct compiler *c,
4158 asdl_seq *generators, int gen_index,
4159 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004160{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004161 comprehension_ty gen;
4162 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4163 if (gen->is_async) {
4164 return compiler_async_comprehension_generator(
4165 c, generators, gen_index, elt, val, type);
4166 } else {
4167 return compiler_sync_comprehension_generator(
4168 c, generators, gen_index, elt, val, type);
4169 }
4170}
4171
4172static int
4173compiler_sync_comprehension_generator(struct compiler *c,
4174 asdl_seq *generators, int gen_index,
4175 expr_ty elt, expr_ty val, int type)
4176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 /* generate code for the iterator, then each of the ifs,
4178 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 comprehension_ty gen;
4181 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004182 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 start = compiler_new_block(c);
4185 skip = compiler_new_block(c);
4186 if_cleanup = compiler_new_block(c);
4187 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4190 anchor == NULL)
4191 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 if (gen_index == 0) {
4196 /* Receive outermost iter as an implicit argument */
4197 c->u->u_argcount = 1;
4198 ADDOP_I(c, LOAD_FAST, 0);
4199 }
4200 else {
4201 /* Sub-iter - calculate on the fly */
4202 VISIT(c, expr, gen->iter);
4203 ADDOP(c, GET_ITER);
4204 }
4205 compiler_use_next_block(c, start);
4206 ADDOP_JREL(c, FOR_ITER, anchor);
4207 NEXT_BLOCK(c);
4208 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 /* XXX this needs to be cleaned up...a lot! */
4211 n = asdl_seq_LEN(gen->ifs);
4212 for (i = 0; i < n; i++) {
4213 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004214 if (!compiler_jump_if(c, e, if_cleanup, 0))
4215 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 NEXT_BLOCK(c);
4217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 if (++gen_index < asdl_seq_LEN(generators))
4220 if (!compiler_comprehension_generator(c,
4221 generators, gen_index,
4222 elt, val, type))
4223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* only append after the last for generator */
4226 if (gen_index >= asdl_seq_LEN(generators)) {
4227 /* comprehension specific code */
4228 switch (type) {
4229 case COMP_GENEXP:
4230 VISIT(c, expr, elt);
4231 ADDOP(c, YIELD_VALUE);
4232 ADDOP(c, POP_TOP);
4233 break;
4234 case COMP_LISTCOMP:
4235 VISIT(c, expr, elt);
4236 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4237 break;
4238 case COMP_SETCOMP:
4239 VISIT(c, expr, elt);
4240 ADDOP_I(c, SET_ADD, gen_index + 1);
4241 break;
4242 case COMP_DICTCOMP:
4243 /* With 'd[k] = v', v is evaluated before k, so we do
4244 the same. */
4245 VISIT(c, expr, val);
4246 VISIT(c, expr, elt);
4247 ADDOP_I(c, MAP_ADD, gen_index + 1);
4248 break;
4249 default:
4250 return 0;
4251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 compiler_use_next_block(c, skip);
4254 }
4255 compiler_use_next_block(c, if_cleanup);
4256 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4257 compiler_use_next_block(c, anchor);
4258
4259 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260}
4261
4262static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004263compiler_async_comprehension_generator(struct compiler *c,
4264 asdl_seq *generators, int gen_index,
4265 expr_ty elt, expr_ty val, int type)
4266{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004267 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004268 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004269 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004270 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004271 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004272 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004273
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004274 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004275 return 0;
4276 }
4277
4278 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4279
4280 if (gen_index == 0) {
4281 /* Receive outermost iter as an implicit argument */
4282 c->u->u_argcount = 1;
4283 ADDOP_I(c, LOAD_FAST, 0);
4284 }
4285 else {
4286 /* Sub-iter - calculate on the fly */
4287 VISIT(c, expr, gen->iter);
4288 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004289 }
4290
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004291 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004292
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004293 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004294 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004295 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004296 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004297 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004298 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004299
4300 n = asdl_seq_LEN(gen->ifs);
4301 for (i = 0; i < n; i++) {
4302 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004303 if (!compiler_jump_if(c, e, if_cleanup, 0))
4304 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004305 NEXT_BLOCK(c);
4306 }
4307
4308 if (++gen_index < asdl_seq_LEN(generators))
4309 if (!compiler_comprehension_generator(c,
4310 generators, gen_index,
4311 elt, val, type))
4312 return 0;
4313
4314 /* only append after the last for generator */
4315 if (gen_index >= asdl_seq_LEN(generators)) {
4316 /* comprehension specific code */
4317 switch (type) {
4318 case COMP_GENEXP:
4319 VISIT(c, expr, elt);
4320 ADDOP(c, YIELD_VALUE);
4321 ADDOP(c, POP_TOP);
4322 break;
4323 case COMP_LISTCOMP:
4324 VISIT(c, expr, elt);
4325 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4326 break;
4327 case COMP_SETCOMP:
4328 VISIT(c, expr, elt);
4329 ADDOP_I(c, SET_ADD, gen_index + 1);
4330 break;
4331 case COMP_DICTCOMP:
4332 /* With 'd[k] = v', v is evaluated before k, so we do
4333 the same. */
4334 VISIT(c, expr, val);
4335 VISIT(c, expr, elt);
4336 ADDOP_I(c, MAP_ADD, gen_index + 1);
4337 break;
4338 default:
4339 return 0;
4340 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004341 }
4342 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004343 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4344
4345 compiler_use_next_block(c, except);
4346 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004347
4348 return 1;
4349}
4350
4351static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004352compiler_comprehension(struct compiler *c, expr_ty e, int type,
4353 identifier name, asdl_seq *generators, expr_ty elt,
4354 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004357 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004358 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004359 int is_async_function = c->u->u_ste->ste_coroutine;
4360 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004361
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004362 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004363
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004364 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4365 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004366 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368 }
4369
4370 is_async_generator = c->u->u_ste->ste_coroutine;
4371
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004372 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004373 compiler_error(c, "asynchronous comprehension outside of "
4374 "an asynchronous function");
4375 goto error_in_scope;
4376 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 if (type != COMP_GENEXP) {
4379 int op;
4380 switch (type) {
4381 case COMP_LISTCOMP:
4382 op = BUILD_LIST;
4383 break;
4384 case COMP_SETCOMP:
4385 op = BUILD_SET;
4386 break;
4387 case COMP_DICTCOMP:
4388 op = BUILD_MAP;
4389 break;
4390 default:
4391 PyErr_Format(PyExc_SystemError,
4392 "unknown comprehension type %d", type);
4393 goto error_in_scope;
4394 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 ADDOP_I(c, op, 0);
4397 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 if (!compiler_comprehension_generator(c, generators, 0, elt,
4400 val, type))
4401 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 if (type != COMP_GENEXP) {
4404 ADDOP(c, RETURN_VALUE);
4405 }
4406
4407 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004408 qualname = c->u->u_qualname;
4409 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004411 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 goto error;
4413
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004414 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004416 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 Py_DECREF(co);
4418
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004419 VISIT(c, expr, outermost->iter);
4420
4421 if (outermost->is_async) {
4422 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004423 } else {
4424 ADDOP(c, GET_ITER);
4425 }
4426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004428
4429 if (is_async_generator && type != COMP_GENEXP) {
4430 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004431 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004432 ADDOP(c, YIELD_FROM);
4433 }
4434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004436error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004438error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004439 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 Py_XDECREF(co);
4441 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004442}
4443
4444static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004445compiler_genexp(struct compiler *c, expr_ty e)
4446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 static identifier name;
4448 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004449 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 if (!name)
4451 return 0;
4452 }
4453 assert(e->kind == GeneratorExp_kind);
4454 return compiler_comprehension(c, e, COMP_GENEXP, name,
4455 e->v.GeneratorExp.generators,
4456 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004457}
4458
4459static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004460compiler_listcomp(struct compiler *c, expr_ty e)
4461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 static identifier name;
4463 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004464 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 if (!name)
4466 return 0;
4467 }
4468 assert(e->kind == ListComp_kind);
4469 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4470 e->v.ListComp.generators,
4471 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004472}
4473
4474static int
4475compiler_setcomp(struct compiler *c, expr_ty e)
4476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 static identifier name;
4478 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004479 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 if (!name)
4481 return 0;
4482 }
4483 assert(e->kind == SetComp_kind);
4484 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4485 e->v.SetComp.generators,
4486 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004487}
4488
4489
4490static int
4491compiler_dictcomp(struct compiler *c, expr_ty e)
4492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 static identifier name;
4494 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004495 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (!name)
4497 return 0;
4498 }
4499 assert(e->kind == DictComp_kind);
4500 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4501 e->v.DictComp.generators,
4502 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004503}
4504
4505
4506static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004507compiler_visit_keyword(struct compiler *c, keyword_ty k)
4508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 VISIT(c, expr, k->value);
4510 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004511}
4512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004514 whether they are true or false.
4515
4516 Return values: 1 for true, 0 for false, -1 for non-constant.
4517 */
4518
4519static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004520expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004521{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004522 if (e->kind == Constant_kind) {
4523 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004524 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004525 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004526}
4527
Yury Selivanov75445082015-05-11 22:57:16 -04004528
4529/*
4530 Implements the async with statement.
4531
4532 The semantics outlined in that PEP are as follows:
4533
4534 async with EXPR as VAR:
4535 BLOCK
4536
4537 It is implemented roughly as:
4538
4539 context = EXPR
4540 exit = context.__aexit__ # not calling it
4541 value = await context.__aenter__()
4542 try:
4543 VAR = value # if VAR present in the syntax
4544 BLOCK
4545 finally:
4546 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004547 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004548 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004549 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004550 if not (await exit(*exc)):
4551 raise
4552 */
4553static int
4554compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4555{
4556 basicblock *block, *finally;
4557 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4558
4559 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004560 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4561 c->u->u_ste->ste_coroutine = 1;
4562 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004563 return compiler_error(c, "'async with' outside async function");
4564 }
Yury Selivanov75445082015-05-11 22:57:16 -04004565
4566 block = compiler_new_block(c);
4567 finally = compiler_new_block(c);
4568 if (!block || !finally)
4569 return 0;
4570
4571 /* Evaluate EXPR */
4572 VISIT(c, expr, item->context_expr);
4573
4574 ADDOP(c, BEFORE_ASYNC_WITH);
4575 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004576 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004577 ADDOP(c, YIELD_FROM);
4578
4579 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4580
4581 /* SETUP_ASYNC_WITH pushes a finally block. */
4582 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004583 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004584 return 0;
4585 }
4586
4587 if (item->optional_vars) {
4588 VISIT(c, expr, item->optional_vars);
4589 }
4590 else {
4591 /* Discard result from context.__aenter__() */
4592 ADDOP(c, POP_TOP);
4593 }
4594
4595 pos++;
4596 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4597 /* BLOCK code */
4598 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4599 else if (!compiler_async_with(c, s, pos))
4600 return 0;
4601
4602 /* End of try block; start the finally block */
4603 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004604 ADDOP(c, BEGIN_FINALLY);
4605 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004606
Yury Selivanov75445082015-05-11 22:57:16 -04004607 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004608 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004609 return 0;
4610
4611 /* Finally block starts; context.__exit__ is on the stack under
4612 the exception or return information. Just issue our magic
4613 opcode. */
4614 ADDOP(c, WITH_CLEANUP_START);
4615
4616 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004617 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004618 ADDOP(c, YIELD_FROM);
4619
4620 ADDOP(c, WITH_CLEANUP_FINISH);
4621
4622 /* Finally block ends. */
4623 ADDOP(c, END_FINALLY);
4624 compiler_pop_fblock(c, FINALLY_END, finally);
4625 return 1;
4626}
4627
4628
Guido van Rossumc2e20742006-02-27 22:32:47 +00004629/*
4630 Implements the with statement from PEP 343.
4631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004633
4634 with EXPR as VAR:
4635 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636
Guido van Rossumc2e20742006-02-27 22:32:47 +00004637 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638
Thomas Wouters477c8d52006-05-27 19:21:47 +00004639 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004640 exit = context.__exit__ # not calling it
4641 value = context.__enter__()
4642 try:
4643 VAR = value # if VAR present in the syntax
4644 BLOCK
4645 finally:
4646 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004647 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004648 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004649 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004650 exit(*exc)
4651 */
4652static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004653compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004654{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004655 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004656 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004657
4658 assert(s->kind == With_kind);
4659
Guido van Rossumc2e20742006-02-27 22:32:47 +00004660 block = compiler_new_block(c);
4661 finally = compiler_new_block(c);
4662 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004663 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004664
Thomas Wouters477c8d52006-05-27 19:21:47 +00004665 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004666 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004667 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004668
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004669 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004670 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004671 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004672 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004673 }
4674
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004675 if (item->optional_vars) {
4676 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004677 }
4678 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004680 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004681 }
4682
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004683 pos++;
4684 if (pos == asdl_seq_LEN(s->v.With.items))
4685 /* BLOCK code */
4686 VISIT_SEQ(c, stmt, s->v.With.body)
4687 else if (!compiler_with(c, s, pos))
4688 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004689
4690 /* End of try block; start the finally block */
4691 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004692 ADDOP(c, BEGIN_FINALLY);
4693 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004694
Guido van Rossumc2e20742006-02-27 22:32:47 +00004695 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004696 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004697 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004698
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004699 /* Finally block starts; context.__exit__ is on the stack under
4700 the exception or return information. Just issue our magic
4701 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004702 ADDOP(c, WITH_CLEANUP_START);
4703 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004704
4705 /* Finally block ends. */
4706 ADDOP(c, END_FINALLY);
4707 compiler_pop_fblock(c, FINALLY_END, finally);
4708 return 1;
4709}
4710
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004712compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004715 case NamedExpr_kind:
4716 VISIT(c, expr, e->v.NamedExpr.value);
4717 ADDOP(c, DUP_TOP);
4718 VISIT(c, expr, e->v.NamedExpr.target);
4719 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 case BoolOp_kind:
4721 return compiler_boolop(c, e);
4722 case BinOp_kind:
4723 VISIT(c, expr, e->v.BinOp.left);
4724 VISIT(c, expr, e->v.BinOp.right);
4725 ADDOP(c, binop(c, e->v.BinOp.op));
4726 break;
4727 case UnaryOp_kind:
4728 VISIT(c, expr, e->v.UnaryOp.operand);
4729 ADDOP(c, unaryop(e->v.UnaryOp.op));
4730 break;
4731 case Lambda_kind:
4732 return compiler_lambda(c, e);
4733 case IfExp_kind:
4734 return compiler_ifexp(c, e);
4735 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004736 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004738 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 case GeneratorExp_kind:
4740 return compiler_genexp(c, e);
4741 case ListComp_kind:
4742 return compiler_listcomp(c, e);
4743 case SetComp_kind:
4744 return compiler_setcomp(c, e);
4745 case DictComp_kind:
4746 return compiler_dictcomp(c, e);
4747 case Yield_kind:
4748 if (c->u->u_ste->ste_type != FunctionBlock)
4749 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004750 if (e->v.Yield.value) {
4751 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 }
4753 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004754 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004756 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004758 case YieldFrom_kind:
4759 if (c->u->u_ste->ste_type != FunctionBlock)
4760 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004761
4762 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4763 return compiler_error(c, "'yield from' inside async function");
4764
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004765 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004766 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004767 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004768 ADDOP(c, YIELD_FROM);
4769 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004770 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004771 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4772 if (c->u->u_ste->ste_type != FunctionBlock){
4773 return compiler_error(c, "'await' outside function");
4774 }
Yury Selivanov75445082015-05-11 22:57:16 -04004775
Victor Stinner331a6a52019-05-27 16:39:22 +02004776 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004777 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4778 return compiler_error(c, "'await' outside async function");
4779 }
4780 }
Yury Selivanov75445082015-05-11 22:57:16 -04004781
4782 VISIT(c, expr, e->v.Await.value);
4783 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004784 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004785 ADDOP(c, YIELD_FROM);
4786 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 case Compare_kind:
4788 return compiler_compare(c, e);
4789 case Call_kind:
4790 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004791 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004792 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004793 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004794 case JoinedStr_kind:
4795 return compiler_joined_str(c, e);
4796 case FormattedValue_kind:
4797 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 /* The following exprs can be assignment targets. */
4799 case Attribute_kind:
4800 if (e->v.Attribute.ctx != AugStore)
4801 VISIT(c, expr, e->v.Attribute.value);
4802 switch (e->v.Attribute.ctx) {
4803 case AugLoad:
4804 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004805 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 case Load:
4807 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4808 break;
4809 case AugStore:
4810 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004811 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 case Store:
4813 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4814 break;
4815 case Del:
4816 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4817 break;
4818 case Param:
4819 default:
4820 PyErr_SetString(PyExc_SystemError,
4821 "param invalid in attribute expression");
4822 return 0;
4823 }
4824 break;
4825 case Subscript_kind:
4826 switch (e->v.Subscript.ctx) {
4827 case AugLoad:
4828 VISIT(c, expr, e->v.Subscript.value);
4829 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4830 break;
4831 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004832 if (!check_subscripter(c, e->v.Subscript.value)) {
4833 return 0;
4834 }
4835 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4836 return 0;
4837 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 VISIT(c, expr, e->v.Subscript.value);
4839 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4840 break;
4841 case AugStore:
4842 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4843 break;
4844 case Store:
4845 VISIT(c, expr, e->v.Subscript.value);
4846 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4847 break;
4848 case Del:
4849 VISIT(c, expr, e->v.Subscript.value);
4850 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4851 break;
4852 case Param:
4853 default:
4854 PyErr_SetString(PyExc_SystemError,
4855 "param invalid in subscript expression");
4856 return 0;
4857 }
4858 break;
4859 case Starred_kind:
4860 switch (e->v.Starred.ctx) {
4861 case Store:
4862 /* In all legitimate cases, the Starred node was already replaced
4863 * by compiler_list/compiler_tuple. XXX: is that okay? */
4864 return compiler_error(c,
4865 "starred assignment target must be in a list or tuple");
4866 default:
4867 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004868 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 case Name_kind:
4871 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4872 /* child nodes of List and Tuple will have expr_context set */
4873 case List_kind:
4874 return compiler_list(c, e);
4875 case Tuple_kind:
4876 return compiler_tuple(c, e);
4877 }
4878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004879}
4880
4881static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004882compiler_visit_expr(struct compiler *c, expr_ty e)
4883{
4884 /* If expr e has a different line number than the last expr/stmt,
4885 set a new line number for the next instruction.
4886 */
4887 int old_lineno = c->u->u_lineno;
4888 int old_col_offset = c->u->u_col_offset;
4889 if (e->lineno != c->u->u_lineno) {
4890 c->u->u_lineno = e->lineno;
4891 c->u->u_lineno_set = 0;
4892 }
4893 /* Updating the column offset is always harmless. */
4894 c->u->u_col_offset = e->col_offset;
4895
4896 int res = compiler_visit_expr1(c, e);
4897
4898 if (old_lineno != c->u->u_lineno) {
4899 c->u->u_lineno = old_lineno;
4900 c->u->u_lineno_set = 0;
4901 }
4902 c->u->u_col_offset = old_col_offset;
4903 return res;
4904}
4905
4906static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004907compiler_augassign(struct compiler *c, stmt_ty s)
4908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 expr_ty e = s->v.AugAssign.target;
4910 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 switch (e->kind) {
4915 case Attribute_kind:
4916 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004917 AugLoad, e->lineno, e->col_offset,
4918 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 if (auge == NULL)
4920 return 0;
4921 VISIT(c, expr, auge);
4922 VISIT(c, expr, s->v.AugAssign.value);
4923 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4924 auge->v.Attribute.ctx = AugStore;
4925 VISIT(c, expr, auge);
4926 break;
4927 case Subscript_kind:
4928 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004929 AugLoad, e->lineno, e->col_offset,
4930 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 if (auge == NULL)
4932 return 0;
4933 VISIT(c, expr, auge);
4934 VISIT(c, expr, s->v.AugAssign.value);
4935 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4936 auge->v.Subscript.ctx = AugStore;
4937 VISIT(c, expr, auge);
4938 break;
4939 case Name_kind:
4940 if (!compiler_nameop(c, e->v.Name.id, Load))
4941 return 0;
4942 VISIT(c, expr, s->v.AugAssign.value);
4943 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4944 return compiler_nameop(c, e->v.Name.id, Store);
4945 default:
4946 PyErr_Format(PyExc_SystemError,
4947 "invalid node type (%d) for augmented assignment",
4948 e->kind);
4949 return 0;
4950 }
4951 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004952}
4953
4954static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004955check_ann_expr(struct compiler *c, expr_ty e)
4956{
4957 VISIT(c, expr, e);
4958 ADDOP(c, POP_TOP);
4959 return 1;
4960}
4961
4962static int
4963check_annotation(struct compiler *c, stmt_ty s)
4964{
4965 /* Annotations are only evaluated in a module or class. */
4966 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4967 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4968 return check_ann_expr(c, s->v.AnnAssign.annotation);
4969 }
4970 return 1;
4971}
4972
4973static int
4974check_ann_slice(struct compiler *c, slice_ty sl)
4975{
4976 switch(sl->kind) {
4977 case Index_kind:
4978 return check_ann_expr(c, sl->v.Index.value);
4979 case Slice_kind:
4980 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4981 return 0;
4982 }
4983 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4984 return 0;
4985 }
4986 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4987 return 0;
4988 }
4989 break;
4990 default:
4991 PyErr_SetString(PyExc_SystemError,
4992 "unexpected slice kind");
4993 return 0;
4994 }
4995 return 1;
4996}
4997
4998static int
4999check_ann_subscr(struct compiler *c, slice_ty sl)
5000{
5001 /* We check that everything in a subscript is defined at runtime. */
5002 Py_ssize_t i, n;
5003
5004 switch (sl->kind) {
5005 case Index_kind:
5006 case Slice_kind:
5007 if (!check_ann_slice(c, sl)) {
5008 return 0;
5009 }
5010 break;
5011 case ExtSlice_kind:
5012 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5013 for (i = 0; i < n; i++) {
5014 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5015 switch (subsl->kind) {
5016 case Index_kind:
5017 case Slice_kind:
5018 if (!check_ann_slice(c, subsl)) {
5019 return 0;
5020 }
5021 break;
5022 case ExtSlice_kind:
5023 default:
5024 PyErr_SetString(PyExc_SystemError,
5025 "extended slice invalid in nested slice");
5026 return 0;
5027 }
5028 }
5029 break;
5030 default:
5031 PyErr_Format(PyExc_SystemError,
5032 "invalid subscript kind %d", sl->kind);
5033 return 0;
5034 }
5035 return 1;
5036}
5037
5038static int
5039compiler_annassign(struct compiler *c, stmt_ty s)
5040{
5041 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005042 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005043
5044 assert(s->kind == AnnAssign_kind);
5045
5046 /* We perform the actual assignment first. */
5047 if (s->v.AnnAssign.value) {
5048 VISIT(c, expr, s->v.AnnAssign.value);
5049 VISIT(c, expr, targ);
5050 }
5051 switch (targ->kind) {
5052 case Name_kind:
5053 /* If we have a simple name in a module or class, store annotation. */
5054 if (s->v.AnnAssign.simple &&
5055 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5056 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005057 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5058 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5059 }
5060 else {
5061 VISIT(c, expr, s->v.AnnAssign.annotation);
5062 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005063 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005064 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005065 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005066 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005067 }
5068 break;
5069 case Attribute_kind:
5070 if (!s->v.AnnAssign.value &&
5071 !check_ann_expr(c, targ->v.Attribute.value)) {
5072 return 0;
5073 }
5074 break;
5075 case Subscript_kind:
5076 if (!s->v.AnnAssign.value &&
5077 (!check_ann_expr(c, targ->v.Subscript.value) ||
5078 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5079 return 0;
5080 }
5081 break;
5082 default:
5083 PyErr_Format(PyExc_SystemError,
5084 "invalid node type (%d) for annotated assignment",
5085 targ->kind);
5086 return 0;
5087 }
5088 /* Annotation is evaluated last. */
5089 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5090 return 0;
5091 }
5092 return 1;
5093}
5094
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095/* Raises a SyntaxError and returns 0.
5096 If something goes wrong, a different exception may be raised.
5097*/
5098
5099static int
5100compiler_error(struct compiler *c, const char *errstr)
5101{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005102 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005104
Victor Stinner14e461d2013-08-26 22:28:21 +02005105 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 if (!loc) {
5107 Py_INCREF(Py_None);
5108 loc = Py_None;
5109 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005110 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005111 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 if (!u)
5113 goto exit;
5114 v = Py_BuildValue("(zO)", errstr, u);
5115 if (!v)
5116 goto exit;
5117 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005118 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 Py_DECREF(loc);
5120 Py_XDECREF(u);
5121 Py_XDECREF(v);
5122 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123}
5124
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005125/* Emits a SyntaxWarning and returns 1 on success.
5126 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5127 and returns 0.
5128*/
5129static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005130compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005131{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005132 va_list vargs;
5133#ifdef HAVE_STDARG_PROTOTYPES
5134 va_start(vargs, format);
5135#else
5136 va_start(vargs);
5137#endif
5138 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5139 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005140 if (msg == NULL) {
5141 return 0;
5142 }
5143 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5144 c->u->u_lineno, NULL, NULL) < 0)
5145 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005146 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005147 /* Replace the SyntaxWarning exception with a SyntaxError
5148 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005149 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005150 assert(PyUnicode_AsUTF8(msg) != NULL);
5151 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005152 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005153 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005154 return 0;
5155 }
5156 Py_DECREF(msg);
5157 return 1;
5158}
5159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005160static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161compiler_handle_subscr(struct compiler *c, const char *kind,
5162 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 /* XXX this code is duplicated */
5167 switch (ctx) {
5168 case AugLoad: /* fall through to Load */
5169 case Load: op = BINARY_SUBSCR; break;
5170 case AugStore:/* fall through to Store */
5171 case Store: op = STORE_SUBSCR; break;
5172 case Del: op = DELETE_SUBSCR; break;
5173 case Param:
5174 PyErr_Format(PyExc_SystemError,
5175 "invalid %s kind %d in subscript\n",
5176 kind, ctx);
5177 return 0;
5178 }
5179 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005180 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 }
5182 else if (ctx == AugStore) {
5183 ADDOP(c, ROT_THREE);
5184 }
5185 ADDOP(c, op);
5186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005187}
5188
5189static int
5190compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 int n = 2;
5193 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 /* only handles the cases where BUILD_SLICE is emitted */
5196 if (s->v.Slice.lower) {
5197 VISIT(c, expr, s->v.Slice.lower);
5198 }
5199 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005200 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 if (s->v.Slice.upper) {
5204 VISIT(c, expr, s->v.Slice.upper);
5205 }
5206 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005207 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 }
5209
5210 if (s->v.Slice.step) {
5211 n++;
5212 VISIT(c, expr, s->v.Slice.step);
5213 }
5214 ADDOP_I(c, BUILD_SLICE, n);
5215 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005216}
5217
5218static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5220 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 switch (s->kind) {
5223 case Slice_kind:
5224 return compiler_slice(c, s, ctx);
5225 case Index_kind:
5226 VISIT(c, expr, s->v.Index.value);
5227 break;
5228 case ExtSlice_kind:
5229 default:
5230 PyErr_SetString(PyExc_SystemError,
5231 "extended slice invalid in nested slice");
5232 return 0;
5233 }
5234 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005235}
5236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005237static int
5238compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5239{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005240 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 switch (s->kind) {
5242 case Index_kind:
5243 kindname = "index";
5244 if (ctx != AugStore) {
5245 VISIT(c, expr, s->v.Index.value);
5246 }
5247 break;
5248 case Slice_kind:
5249 kindname = "slice";
5250 if (ctx != AugStore) {
5251 if (!compiler_slice(c, s, ctx))
5252 return 0;
5253 }
5254 break;
5255 case ExtSlice_kind:
5256 kindname = "extended slice";
5257 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005258 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 for (i = 0; i < n; i++) {
5260 slice_ty sub = (slice_ty)asdl_seq_GET(
5261 s->v.ExtSlice.dims, i);
5262 if (!compiler_visit_nested_slice(c, sub, ctx))
5263 return 0;
5264 }
5265 ADDOP_I(c, BUILD_TUPLE, n);
5266 }
5267 break;
5268 default:
5269 PyErr_Format(PyExc_SystemError,
5270 "invalid subscript kind %d", s->kind);
5271 return 0;
5272 }
5273 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005274}
5275
Thomas Wouters89f507f2006-12-13 04:49:30 +00005276/* End of the compiler section, beginning of the assembler section */
5277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005278/* do depth-first search of basic block graph, starting with block.
5279 post records the block indices in post-order.
5280
5281 XXX must handle implicit jumps from one block to next
5282*/
5283
Thomas Wouters89f507f2006-12-13 04:49:30 +00005284struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 PyObject *a_bytecode; /* string containing bytecode */
5286 int a_offset; /* offset into bytecode */
5287 int a_nblocks; /* number of reachable blocks */
5288 basicblock **a_postorder; /* list of blocks in dfs postorder */
5289 PyObject *a_lnotab; /* string containing lnotab */
5290 int a_lnotab_off; /* offset into lnotab */
5291 int a_lineno; /* last lineno of emitted instruction */
5292 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005293};
5294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005296dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005297{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005298 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005300 /* Get rid of recursion for normal control flow.
5301 Since the number of blocks is limited, unused space in a_postorder
5302 (from a_nblocks to end) can be used as a stack for still not ordered
5303 blocks. */
5304 for (j = end; b && !b->b_seen; b = b->b_next) {
5305 b->b_seen = 1;
5306 assert(a->a_nblocks < j);
5307 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005309 while (j < end) {
5310 b = a->a_postorder[j++];
5311 for (i = 0; i < b->b_iused; i++) {
5312 struct instr *instr = &b->b_instr[i];
5313 if (instr->i_jrel || instr->i_jabs)
5314 dfs(c, instr->i_target, a, j);
5315 }
5316 assert(a->a_nblocks < j);
5317 a->a_postorder[a->a_nblocks++] = b;
5318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005319}
5320
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005321Py_LOCAL_INLINE(void)
5322stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005323{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005324 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005325 if (b->b_startdepth < depth) {
5326 assert(b->b_startdepth < 0);
5327 b->b_startdepth = depth;
5328 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005329 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005330}
5331
5332/* Find the flow path that needs the largest stack. We assume that
5333 * cycles in the flow graph have no net effect on the stack depth.
5334 */
5335static int
5336stackdepth(struct compiler *c)
5337{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005338 basicblock *b, *entryblock = NULL;
5339 basicblock **stack, **sp;
5340 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 b->b_startdepth = INT_MIN;
5343 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005344 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 }
5346 if (!entryblock)
5347 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005348 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5349 if (!stack) {
5350 PyErr_NoMemory();
5351 return -1;
5352 }
5353
5354 sp = stack;
5355 stackdepth_push(&sp, entryblock, 0);
5356 while (sp != stack) {
5357 b = *--sp;
5358 int depth = b->b_startdepth;
5359 assert(depth >= 0);
5360 basicblock *next = b->b_next;
5361 for (int i = 0; i < b->b_iused; i++) {
5362 struct instr *instr = &b->b_instr[i];
5363 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5364 if (effect == PY_INVALID_STACK_EFFECT) {
5365 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5366 Py_FatalError("PyCompile_OpcodeStackEffect()");
5367 }
5368 int new_depth = depth + effect;
5369 if (new_depth > maxdepth) {
5370 maxdepth = new_depth;
5371 }
5372 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5373 if (instr->i_jrel || instr->i_jabs) {
5374 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5375 assert(effect != PY_INVALID_STACK_EFFECT);
5376 int target_depth = depth + effect;
5377 if (target_depth > maxdepth) {
5378 maxdepth = target_depth;
5379 }
5380 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005381 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005382 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005383 assert(instr->i_target->b_startdepth >= target_depth);
5384 depth = new_depth;
5385 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005386 }
5387 stackdepth_push(&sp, instr->i_target, target_depth);
5388 }
5389 depth = new_depth;
5390 if (instr->i_opcode == JUMP_ABSOLUTE ||
5391 instr->i_opcode == JUMP_FORWARD ||
5392 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005393 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005394 {
5395 /* remaining code is dead */
5396 next = NULL;
5397 break;
5398 }
5399 }
5400 if (next != NULL) {
5401 stackdepth_push(&sp, next, depth);
5402 }
5403 }
5404 PyObject_Free(stack);
5405 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005406}
5407
5408static int
5409assemble_init(struct assembler *a, int nblocks, int firstlineno)
5410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 memset(a, 0, sizeof(struct assembler));
5412 a->a_lineno = firstlineno;
5413 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5414 if (!a->a_bytecode)
5415 return 0;
5416 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5417 if (!a->a_lnotab)
5418 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005419 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 PyErr_NoMemory();
5421 return 0;
5422 }
5423 a->a_postorder = (basicblock **)PyObject_Malloc(
5424 sizeof(basicblock *) * nblocks);
5425 if (!a->a_postorder) {
5426 PyErr_NoMemory();
5427 return 0;
5428 }
5429 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430}
5431
5432static void
5433assemble_free(struct assembler *a)
5434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 Py_XDECREF(a->a_bytecode);
5436 Py_XDECREF(a->a_lnotab);
5437 if (a->a_postorder)
5438 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005439}
5440
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005441static int
5442blocksize(basicblock *b)
5443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 int i;
5445 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005448 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005450}
5451
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005452/* Appends a pair to the end of the line number table, a_lnotab, representing
5453 the instruction's bytecode offset and line number. See
5454 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005455
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005456static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005457assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005460 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005462
Serhiy Storchakaab874002016-09-11 13:48:15 +03005463 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 if(d_bytecode == 0 && d_lineno == 0)
5469 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 if (d_bytecode > 255) {
5472 int j, nbytes, ncodes = d_bytecode / 255;
5473 nbytes = a->a_lnotab_off + 2 * ncodes;
5474 len = PyBytes_GET_SIZE(a->a_lnotab);
5475 if (nbytes >= len) {
5476 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5477 len = nbytes;
5478 else if (len <= INT_MAX / 2)
5479 len *= 2;
5480 else {
5481 PyErr_NoMemory();
5482 return 0;
5483 }
5484 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5485 return 0;
5486 }
5487 lnotab = (unsigned char *)
5488 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5489 for (j = 0; j < ncodes; j++) {
5490 *lnotab++ = 255;
5491 *lnotab++ = 0;
5492 }
5493 d_bytecode -= ncodes * 255;
5494 a->a_lnotab_off += ncodes * 2;
5495 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005496 assert(0 <= d_bytecode && d_bytecode <= 255);
5497
5498 if (d_lineno < -128 || 127 < d_lineno) {
5499 int j, nbytes, ncodes, k;
5500 if (d_lineno < 0) {
5501 k = -128;
5502 /* use division on positive numbers */
5503 ncodes = (-d_lineno) / 128;
5504 }
5505 else {
5506 k = 127;
5507 ncodes = d_lineno / 127;
5508 }
5509 d_lineno -= ncodes * k;
5510 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 nbytes = a->a_lnotab_off + 2 * ncodes;
5512 len = PyBytes_GET_SIZE(a->a_lnotab);
5513 if (nbytes >= len) {
5514 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5515 len = nbytes;
5516 else if (len <= INT_MAX / 2)
5517 len *= 2;
5518 else {
5519 PyErr_NoMemory();
5520 return 0;
5521 }
5522 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5523 return 0;
5524 }
5525 lnotab = (unsigned char *)
5526 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5527 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005528 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 d_bytecode = 0;
5530 for (j = 1; j < ncodes; j++) {
5531 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005532 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 a->a_lnotab_off += ncodes * 2;
5535 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005536 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 len = PyBytes_GET_SIZE(a->a_lnotab);
5539 if (a->a_lnotab_off + 2 >= len) {
5540 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5541 return 0;
5542 }
5543 lnotab = (unsigned char *)
5544 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 a->a_lnotab_off += 2;
5547 if (d_bytecode) {
5548 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005549 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 }
5551 else { /* First line of a block; def stmt, etc. */
5552 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005553 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 }
5555 a->a_lineno = i->i_lineno;
5556 a->a_lineno_off = a->a_offset;
5557 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005558}
5559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005560/* assemble_emit()
5561 Extend the bytecode with a new instruction.
5562 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005563*/
5564
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005565static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005567{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005568 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005570 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005571
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005572 arg = i->i_oparg;
5573 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 if (i->i_lineno && !assemble_lnotab(a, i))
5575 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005576 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 if (len > PY_SSIZE_T_MAX / 2)
5578 return 0;
5579 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5580 return 0;
5581 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005582 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005584 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005586}
5587
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005588static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005589assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005592 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 /* Compute the size of each block and fixup jump args.
5596 Replace block pointer with position in bytecode. */
5597 do {
5598 totsize = 0;
5599 for (i = a->a_nblocks - 1; i >= 0; i--) {
5600 b = a->a_postorder[i];
5601 bsize = blocksize(b);
5602 b->b_offset = totsize;
5603 totsize += bsize;
5604 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005605 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5607 bsize = b->b_offset;
5608 for (i = 0; i < b->b_iused; i++) {
5609 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005610 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 /* Relative jumps are computed relative to
5612 the instruction pointer after fetching
5613 the jump instruction.
5614 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005615 bsize += isize;
5616 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005618 if (instr->i_jrel) {
5619 instr->i_oparg -= bsize;
5620 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005621 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005622 if (instrsize(instr->i_oparg) != isize) {
5623 extended_arg_recompile = 1;
5624 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 }
5627 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 /* XXX: This is an awful hack that could hurt performance, but
5630 on the bright side it should work until we come up
5631 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 The issue is that in the first loop blocksize() is called
5634 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005635 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 So we loop until we stop seeing new EXTENDED_ARGs.
5639 The only EXTENDED_ARGs that could be popping up are
5640 ones in jump instructions. So this should converge
5641 fairly quickly.
5642 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005643 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005644}
5645
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005646static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005647dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005650 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 tuple = PyTuple_New(size);
5653 if (tuple == NULL)
5654 return NULL;
5655 while (PyDict_Next(dict, &pos, &k, &v)) {
5656 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005657 Py_INCREF(k);
5658 assert((i - offset) < size);
5659 assert((i - offset) >= 0);
5660 PyTuple_SET_ITEM(tuple, i - offset, k);
5661 }
5662 return tuple;
5663}
5664
5665static PyObject *
5666consts_dict_keys_inorder(PyObject *dict)
5667{
5668 PyObject *consts, *k, *v;
5669 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5670
5671 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5672 if (consts == NULL)
5673 return NULL;
5674 while (PyDict_Next(dict, &pos, &k, &v)) {
5675 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005676 /* The keys of the dictionary can be tuples wrapping a contant.
5677 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5678 * the object we want is always second. */
5679 if (PyTuple_CheckExact(k)) {
5680 k = PyTuple_GET_ITEM(k, 1);
5681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005683 assert(i < size);
5684 assert(i >= 0);
5685 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005687 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005688}
5689
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005690static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005691compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005694 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005696 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 if (ste->ste_nested)
5698 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005699 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005701 if (!ste->ste_generator && ste->ste_coroutine)
5702 flags |= CO_COROUTINE;
5703 if (ste->ste_generator && ste->ste_coroutine)
5704 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 if (ste->ste_varargs)
5706 flags |= CO_VARARGS;
5707 if (ste->ste_varkeywords)
5708 flags |= CO_VARKEYWORDS;
5709 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 /* (Only) inherit compilerflags in PyCF_MASK */
5712 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005713
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005714 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5715 ste->ste_coroutine &&
5716 !ste->ste_generator) {
5717 flags |= CO_COROUTINE;
5718 }
5719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005721}
5722
INADA Naokic2e16072018-11-26 21:23:22 +09005723// Merge *tuple* with constant cache.
5724// Unlike merge_consts_recursive(), this function doesn't work recursively.
5725static int
5726merge_const_tuple(struct compiler *c, PyObject **tuple)
5727{
5728 assert(PyTuple_CheckExact(*tuple));
5729
5730 PyObject *key = _PyCode_ConstantKey(*tuple);
5731 if (key == NULL) {
5732 return 0;
5733 }
5734
5735 // t is borrowed reference
5736 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5737 Py_DECREF(key);
5738 if (t == NULL) {
5739 return 0;
5740 }
5741 if (t == key) { // tuple is new constant.
5742 return 1;
5743 }
5744
5745 PyObject *u = PyTuple_GET_ITEM(t, 1);
5746 Py_INCREF(u);
5747 Py_DECREF(*tuple);
5748 *tuple = u;
5749 return 1;
5750}
5751
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005752static PyCodeObject *
5753makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 PyObject *tmp;
5756 PyCodeObject *co = NULL;
5757 PyObject *consts = NULL;
5758 PyObject *names = NULL;
5759 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 PyObject *name = NULL;
5761 PyObject *freevars = NULL;
5762 PyObject *cellvars = NULL;
5763 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005764 Py_ssize_t nlocals;
5765 int nlocals_int;
5766 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005767 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005768
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005769 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 names = dict_keys_inorder(c->u->u_names, 0);
5771 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5772 if (!consts || !names || !varnames)
5773 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5776 if (!cellvars)
5777 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005778 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 if (!freevars)
5780 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005781
INADA Naokic2e16072018-11-26 21:23:22 +09005782 if (!merge_const_tuple(c, &names) ||
5783 !merge_const_tuple(c, &varnames) ||
5784 !merge_const_tuple(c, &cellvars) ||
5785 !merge_const_tuple(c, &freevars))
5786 {
5787 goto error;
5788 }
5789
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005790 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005791 assert(nlocals < INT_MAX);
5792 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 flags = compute_code_flags(c);
5795 if (flags < 0)
5796 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5799 if (!bytecode)
5800 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5803 if (!tmp)
5804 goto error;
5805 Py_DECREF(consts);
5806 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005807 if (!merge_const_tuple(c, &consts)) {
5808 goto error;
5809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005811 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005812 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005813 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005814 maxdepth = stackdepth(c);
5815 if (maxdepth < 0) {
5816 goto error;
5817 }
Pablo Galindocd74e662019-06-01 18:08:04 +01005818 co = PyCode_New(posonlyargcount+posorkeywordargcount, posonlyargcount,
5819 kwonlyargcount, nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 bytecode, consts, names, varnames,
5821 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005822 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 c->u->u_firstlineno,
5824 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005825 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 Py_XDECREF(consts);
5827 Py_XDECREF(names);
5828 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 Py_XDECREF(name);
5830 Py_XDECREF(freevars);
5831 Py_XDECREF(cellvars);
5832 Py_XDECREF(bytecode);
5833 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005834}
5835
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005836
5837/* For debugging purposes only */
5838#if 0
5839static void
5840dump_instr(const struct instr *i)
5841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 const char *jrel = i->i_jrel ? "jrel " : "";
5843 const char *jabs = i->i_jabs ? "jabs " : "";
5844 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005847 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5851 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005852}
5853
5854static void
5855dump_basicblock(const basicblock *b)
5856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 const char *seen = b->b_seen ? "seen " : "";
5858 const char *b_return = b->b_return ? "return " : "";
5859 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5860 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5861 if (b->b_instr) {
5862 int i;
5863 for (i = 0; i < b->b_iused; i++) {
5864 fprintf(stderr, " [%02d] ", i);
5865 dump_instr(b->b_instr + i);
5866 }
5867 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005868}
5869#endif
5870
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005871static PyCodeObject *
5872assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 basicblock *b, *entryblock;
5875 struct assembler a;
5876 int i, j, nblocks;
5877 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 /* Make sure every block that falls off the end returns None.
5880 XXX NEXT_BLOCK() isn't quite right, because if the last
5881 block ends with a jump or return b_next shouldn't set.
5882 */
5883 if (!c->u->u_curblock->b_return) {
5884 NEXT_BLOCK(c);
5885 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005886 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 ADDOP(c, RETURN_VALUE);
5888 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 nblocks = 0;
5891 entryblock = NULL;
5892 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5893 nblocks++;
5894 entryblock = b;
5895 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005897 /* Set firstlineno if it wasn't explicitly set. */
5898 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005899 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5901 else
5902 c->u->u_firstlineno = 1;
5903 }
5904 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5905 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005906 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908 /* Can't modify the bytecode after computing jump offsets. */
5909 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005911 /* Emit code in reverse postorder from dfs. */
5912 for (i = a.a_nblocks - 1; i >= 0; i--) {
5913 b = a.a_postorder[i];
5914 for (j = 0; j < b->b_iused; j++)
5915 if (!assemble_emit(&a, &b->b_instr[j]))
5916 goto error;
5917 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5920 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005921 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005925 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 assemble_free(&a);
5927 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005928}
Georg Brandl8334fd92010-12-04 10:26:46 +00005929
5930#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005931PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005932PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5933 PyArena *arena)
5934{
5935 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5936}