blob: 03b703deb041f3253c8b72c8bf46f5abb87f4bde [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"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
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 */
126 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 /* Pointer to the most recently allocated block. By following b_list
128 members, you can reach all early allocated blocks. */
129 basicblock *u_blocks;
130 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_nfblocks;
133 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_firstlineno; /* the first lineno of the block */
136 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000137 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_lineno_set; /* boolean to indicate whether instr
139 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140};
141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000147
148Note that we don't track recursion levels during compilation - the
149task of detecting and rejecting excessive levels of nesting is
150handled by the symbol analysis pass.
151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152*/
153
154struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200155 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 struct symtable *c_st;
157 PyFutureFeatures *c_future; /* pointer to module's __future__ */
158 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Georg Brandl8334fd92010-12-04 10:26:46 +0000160 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 int c_interactive; /* true if in interactive mode */
162 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 struct compiler_unit *u; /* compiler state for current block */
165 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
166 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167};
168
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100169static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170static void compiler_free(struct compiler *);
171static basicblock *compiler_new_block(struct compiler *);
172static int compiler_next_instr(struct compiler *, basicblock *);
173static int compiler_addop(struct compiler *, int);
174static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100175static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_error(struct compiler *, const char *);
178static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
179
180static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
181static int compiler_visit_stmt(struct compiler *, stmt_ty);
182static int compiler_visit_keyword(struct compiler *, keyword_ty);
183static int compiler_visit_expr(struct compiler *, expr_ty);
184static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700185static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200190static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500192static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400193static int compiler_async_with(struct compiler *, stmt_ty, int);
194static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100195static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400197 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500198static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400199static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000200
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700201static int compiler_sync_comprehension_generator(
202 struct compiler *c,
203 asdl_seq *generators, int gen_index,
204 expr_ty elt, expr_ty val, int type);
205
206static int compiler_async_comprehension_generator(
207 struct compiler *c,
208 asdl_seq *generators, int gen_index,
209 expr_ty elt, expr_ty val, int type);
210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000212static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400214#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000215
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 /* Name mangling: __private becomes _classname__private.
220 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200221 PyObject *result;
222 size_t nlen, plen, ipriv;
223 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyUnicode_READ_CHAR(ident, 0) != '_' ||
226 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_INCREF(ident);
228 return ident;
229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200230 nlen = PyUnicode_GET_LENGTH(ident);
231 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 The only time a name with a dot can occur is when
235 we are compiling an import statement that has a
236 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 TODO(jhylton): Decide whether we want to support
239 mangling of the module name, e.g. __M.X.
240 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
242 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
243 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Py_INCREF(ident);
245 return ident; /* Don't mangle __whatever__ */
246 }
247 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 ipriv = 0;
249 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
250 ipriv++;
251 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_INCREF(ident);
253 return ident; /* Don't mangle if class is just underscores */
254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200255 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Antoine Pitrou55bff892013-04-06 21:21:04 +0200257 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
258 PyErr_SetString(PyExc_OverflowError,
259 "private identifier too large to be mangled");
260 return NULL;
261 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
264 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
265 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
266
267 result = PyUnicode_New(1 + nlen + plen, maxchar);
268 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200270 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
271 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200272 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
273 Py_DECREF(result);
274 return NULL;
275 }
276 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
Victor Stinner8f825062012-04-27 13:55:39 +0200280 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000282}
283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284static int
285compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 c->c_stack = PyList_New(0);
290 if (!c->c_stack)
291 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294}
295
296PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200297PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
298 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 struct compiler c;
301 PyCodeObject *co = NULL;
302 PyCompilerFlags local_flags;
303 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!__doc__) {
306 __doc__ = PyUnicode_InternFromString("__doc__");
307 if (!__doc__)
308 return NULL;
309 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000310 if (!__annotations__) {
311 __annotations__ = PyUnicode_InternFromString("__annotations__");
312 if (!__annotations__)
313 return NULL;
314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200334 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900335 goto finally;
336 }
337
Victor Stinner14e461d2013-08-26 22:28:21 +0200338 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (c.c_st == NULL) {
340 if (!PyErr_Occurred())
341 PyErr_SetString(PyExc_SystemError, "no symtable");
342 goto finally;
343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000346
Thomas Wouters1175c432006-02-27 22:49:54 +0000347 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 compiler_free(&c);
349 assert(co || PyErr_Occurred());
350 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351}
352
353PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200354PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
355 int optimize, PyArena *arena)
356{
357 PyObject *filename;
358 PyCodeObject *co;
359 filename = PyUnicode_DecodeFSDefault(filename_str);
360 if (filename == NULL)
361 return NULL;
362 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
363 Py_DECREF(filename);
364 return co;
365
366}
367
368PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369PyNode_Compile(struct _node *n, const char *filename)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyCodeObject *co = NULL;
372 mod_ty mod;
373 PyArena *arena = PyArena_New();
374 if (!arena)
375 return NULL;
376 mod = PyAST_FromNode(n, NULL, filename, arena);
377 if (mod)
378 co = PyAST_Compile(mod, filename, NULL, arena);
379 PyArena_Free(arena);
380 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000381}
382
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000383static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (c->c_st)
387 PySymtable_Free(c->c_st);
388 if (c->c_future)
389 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200390 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000392}
393
Guido van Rossum79f25d91997-04-29 20:08:16 +0000394static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 Py_ssize_t i, n;
398 PyObject *v, *k;
399 PyObject *dict = PyDict_New();
400 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 n = PyList_Size(list);
403 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100404 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (!v) {
406 Py_DECREF(dict);
407 return NULL;
408 }
409 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100410 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
412 Py_XDECREF(k);
413 Py_DECREF(v);
414 Py_DECREF(dict);
415 return NULL;
416 }
417 Py_DECREF(k);
418 Py_DECREF(v);
419 }
420 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421}
422
423/* Return new dict containing names from src that match scope(s).
424
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000425src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000427values are integers, starting at offset and increasing by one for
428each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429*/
430
431static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100432dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700434 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500436 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 assert(offset >= 0);
439 if (dest == NULL)
440 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441
Meador Inge2ca63152012-07-18 14:20:11 -0500442 /* Sort the keys so that we have a deterministic order on the indexes
443 saved in the returned dictionary. These indexes are used as indexes
444 into the free and cell var storage. Therefore if they aren't
445 deterministic, then the generated bytecode is not deterministic.
446 */
447 sorted_keys = PyDict_Keys(src);
448 if (sorted_keys == NULL)
449 return NULL;
450 if (PyList_Sort(sorted_keys) != 0) {
451 Py_DECREF(sorted_keys);
452 return NULL;
453 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500454 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500455
456 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* XXX this should probably be a macro in symtable.h */
458 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500459 k = PyList_GET_ITEM(sorted_keys, key_i);
460 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 assert(PyLong_Check(v));
462 vi = PyLong_AS_LONG(v);
463 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100466 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500468 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_DECREF(dest);
470 return NULL;
471 }
472 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100473 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500475 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(item);
477 Py_DECREF(dest);
478 Py_XDECREF(tuple);
479 return NULL;
480 }
481 Py_DECREF(item);
482 Py_DECREF(tuple);
483 }
484 }
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000487}
488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000489static void
490compiler_unit_check(struct compiler_unit *u)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 basicblock *block;
493 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700494 assert((uintptr_t)block != 0xcbcbcbcbU);
495 assert((uintptr_t)block != 0xfbfbfbfbU);
496 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (block->b_instr != NULL) {
498 assert(block->b_ialloc > 0);
499 assert(block->b_iused > 0);
500 assert(block->b_ialloc >= block->b_iused);
501 }
502 else {
503 assert (block->b_iused == 0);
504 assert (block->b_ialloc == 0);
505 }
506 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507}
508
509static void
510compiler_unit_free(struct compiler_unit *u)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 compiler_unit_check(u);
515 b = u->u_blocks;
516 while (b != NULL) {
517 if (b->b_instr)
518 PyObject_Free((void *)b->b_instr);
519 next = b->b_list;
520 PyObject_Free((void *)b);
521 b = next;
522 }
523 Py_CLEAR(u->u_ste);
524 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400525 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 Py_CLEAR(u->u_consts);
527 Py_CLEAR(u->u_names);
528 Py_CLEAR(u->u_varnames);
529 Py_CLEAR(u->u_freevars);
530 Py_CLEAR(u->u_cellvars);
531 Py_CLEAR(u->u_private);
532 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533}
534
535static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100536compiler_enter_scope(struct compiler *c, identifier name,
537 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100540 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
543 struct compiler_unit));
544 if (!u) {
545 PyErr_NoMemory();
546 return 0;
547 }
548 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100549 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 u->u_argcount = 0;
551 u->u_kwonlyargcount = 0;
552 u->u_ste = PySymtable_Lookup(c->c_st, key);
553 if (!u->u_ste) {
554 compiler_unit_free(u);
555 return 0;
556 }
557 Py_INCREF(name);
558 u->u_name = name;
559 u->u_varnames = list2dict(u->u_ste->ste_varnames);
560 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
561 if (!u->u_varnames || !u->u_cellvars) {
562 compiler_unit_free(u);
563 return 0;
564 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000566 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500567 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300568 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 int res;
570 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200571 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 name = _PyUnicode_FromId(&PyId___class__);
573 if (!name) {
574 compiler_unit_free(u);
575 return 0;
576 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100577 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500578 if (!tuple) {
579 compiler_unit_free(u);
580 return 0;
581 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300582 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500583 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 if (res < 0) {
585 compiler_unit_free(u);
586 return 0;
587 }
588 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200591 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (!u->u_freevars) {
593 compiler_unit_free(u);
594 return 0;
595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 u->u_blocks = NULL;
598 u->u_nfblocks = 0;
599 u->u_firstlineno = lineno;
600 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000601 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 u->u_lineno_set = 0;
603 u->u_consts = PyDict_New();
604 if (!u->u_consts) {
605 compiler_unit_free(u);
606 return 0;
607 }
608 u->u_names = PyDict_New();
609 if (!u->u_names) {
610 compiler_unit_free(u);
611 return 0;
612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Push the old compiler_unit on the stack. */
617 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400618 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
620 Py_XDECREF(capsule);
621 compiler_unit_free(u);
622 return 0;
623 }
624 Py_DECREF(capsule);
625 u->u_private = c->u->u_private;
626 Py_XINCREF(u->u_private);
627 }
628 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631
632 block = compiler_new_block(c);
633 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100635 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400637 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
638 if (!compiler_set_qualname(c))
639 return 0;
640 }
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643}
644
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000645static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646compiler_exit_scope(struct compiler *c)
647{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100648 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c->c_nestlevel--;
652 compiler_unit_free(c->u);
653 /* Restore c->u to the parent unit. */
654 n = PyList_GET_SIZE(c->c_stack) - 1;
655 if (n >= 0) {
656 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400657 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 assert(c->u);
659 /* we are deleting from a list so this really shouldn't fail */
660 if (PySequence_DelItem(c->c_stack, n) < 0)
661 Py_FatalError("compiler_exit_scope()");
662 compiler_unit_check(c->u);
663 }
664 else
665 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667}
668
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669static int
670compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100672 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 _Py_static_string(dot_locals, ".<locals>");
674 Py_ssize_t stack_size;
675 struct compiler_unit *u = c->u;
676 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400680 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 if (stack_size > 1) {
682 int scope, force_global = 0;
683 struct compiler_unit *parent;
684 PyObject *mangled, *capsule;
685
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400686 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400687 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400688 assert(parent);
689
Yury Selivanov75445082015-05-11 22:57:16 -0400690 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
691 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
692 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400693 assert(u->u_name);
694 mangled = _Py_Mangle(parent->u_private, u->u_name);
695 if (!mangled)
696 return 0;
697 scope = PyST_GetScope(parent->u_ste, mangled);
698 Py_DECREF(mangled);
699 assert(scope != GLOBAL_IMPLICIT);
700 if (scope == GLOBAL_EXPLICIT)
701 force_global = 1;
702 }
703
704 if (!force_global) {
705 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400706 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400707 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
708 dot_locals_str = _PyUnicode_FromId(&dot_locals);
709 if (dot_locals_str == NULL)
710 return 0;
711 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
712 if (base == NULL)
713 return 0;
714 }
715 else {
716 Py_INCREF(parent->u_qualname);
717 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100719 }
720 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400721
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400722 if (base != NULL) {
723 dot_str = _PyUnicode_FromId(&dot);
724 if (dot_str == NULL) {
725 Py_DECREF(base);
726 return 0;
727 }
728 name = PyUnicode_Concat(base, dot_str);
729 Py_DECREF(base);
730 if (name == NULL)
731 return 0;
732 PyUnicode_Append(&name, u->u_name);
733 if (name == NULL)
734 return 0;
735 }
736 else {
737 Py_INCREF(u->u_name);
738 name = u->u_name;
739 }
740 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400742 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100743}
744
Eric V. Smith235a6f02015-09-19 14:51:32 -0400745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000746/* Allocate a new block and return a pointer to it.
747 Returns NULL on error.
748*/
749
750static basicblock *
751compiler_new_block(struct compiler *c)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 basicblock *b;
754 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 u = c->u;
757 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
758 if (b == NULL) {
759 PyErr_NoMemory();
760 return NULL;
761 }
762 memset((void *)b, 0, sizeof(basicblock));
763 /* Extend the singly linked list of blocks with new block. */
764 b->b_list = u->u_blocks;
765 u->u_blocks = b;
766 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767}
768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770compiler_next_block(struct compiler *c)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 basicblock *block = compiler_new_block(c);
773 if (block == NULL)
774 return NULL;
775 c->u->u_curblock->b_next = block;
776 c->u->u_curblock = block;
777 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778}
779
780static basicblock *
781compiler_use_next_block(struct compiler *c, basicblock *block)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 assert(block != NULL);
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789/* Returns the offset of the next instruction in the current block's
790 b_instr array. Resizes the b_instr as necessary.
791 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793
794static int
795compiler_next_instr(struct compiler *c, basicblock *b)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 assert(b != NULL);
798 if (b->b_instr == NULL) {
799 b->b_instr = (struct instr *)PyObject_Malloc(
800 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
801 if (b->b_instr == NULL) {
802 PyErr_NoMemory();
803 return -1;
804 }
805 b->b_ialloc = DEFAULT_BLOCK_SIZE;
806 memset((char *)b->b_instr, 0,
807 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
808 }
809 else if (b->b_iused == b->b_ialloc) {
810 struct instr *tmp;
811 size_t oldsize, newsize;
812 oldsize = b->b_ialloc * sizeof(struct instr);
813 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000814
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700815 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyErr_NoMemory();
817 return -1;
818 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (newsize == 0) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 b->b_ialloc <<= 1;
825 tmp = (struct instr *)PyObject_Realloc(
826 (void *)b->b_instr, newsize);
827 if (tmp == NULL) {
828 PyErr_NoMemory();
829 return -1;
830 }
831 b->b_instr = tmp;
832 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
833 }
834 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835}
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837/* Set the i_lineno member of the instruction at offset off if the
838 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 already been set. If it has been set, the call has no effect.
840
Christian Heimes2202f872008-02-06 14:31:34 +0000841 The line number is reset in the following cases:
842 - when entering a new scope
843 - on each statement
844 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200845 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000846 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849static void
850compiler_set_lineno(struct compiler *c, int off)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 basicblock *b;
853 if (c->u->u_lineno_set)
854 return;
855 c->u->u_lineno_set = 1;
856 b = c->u->u_curblock;
857 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858}
859
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200860/* Return the stack effect of opcode with argument oparg.
861
862 Some opcodes have different stack effect when jump to the target and
863 when not jump. The 'jump' parameter specifies the case:
864
865 * 0 -- when not jump
866 * 1 -- when jump
867 * -1 -- maximal
868 */
869/* XXX Make the stack effect of WITH_CLEANUP_START and
870 WITH_CLEANUP_FINISH deterministic. */
871static int
872stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 switch (opcode) {
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200875 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case POP_TOP:
877 return -1;
878 case ROT_TWO:
879 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200880 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return 0;
882 case DUP_TOP:
883 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000884 case DUP_TOP_TWO:
885 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000886
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200887 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case UNARY_POSITIVE:
889 case UNARY_NEGATIVE:
890 case UNARY_NOT:
891 case UNARY_INVERT:
892 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case SET_ADD:
895 case LIST_APPEND:
896 return -1;
897 case MAP_ADD:
898 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000899
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case BINARY_POWER:
902 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400903 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case BINARY_MODULO:
905 case BINARY_ADD:
906 case BINARY_SUBTRACT:
907 case BINARY_SUBSCR:
908 case BINARY_FLOOR_DIVIDE:
909 case BINARY_TRUE_DIVIDE:
910 return -1;
911 case INPLACE_FLOOR_DIVIDE:
912 case INPLACE_TRUE_DIVIDE:
913 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case INPLACE_ADD:
916 case INPLACE_SUBTRACT:
917 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400918 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case INPLACE_MODULO:
920 return -1;
921 case STORE_SUBSCR:
922 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 case DELETE_SUBSCR:
924 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 case BINARY_LSHIFT:
927 case BINARY_RSHIFT:
928 case BINARY_AND:
929 case BINARY_XOR:
930 case BINARY_OR:
931 return -1;
932 case INPLACE_POWER:
933 return -1;
934 case GET_ITER:
935 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case PRINT_EXPR:
938 return -1;
939 case LOAD_BUILD_CLASS:
940 return 1;
941 case INPLACE_LSHIFT:
942 case INPLACE_RSHIFT:
943 case INPLACE_AND:
944 case INPLACE_XOR:
945 case INPLACE_OR:
946 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200949 /* 1 in the normal flow.
950 * Restore the stack position and push 6 values before jumping to
951 * the handler if an exception be raised. */
952 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400953 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200954 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400955 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200956 /* Pop a variable number of values pushed by WITH_CLEANUP_START
957 * + __exit__ or __aexit__. */
958 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case RETURN_VALUE:
960 return -1;
961 case IMPORT_STAR:
962 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700963 case SETUP_ANNOTATIONS:
964 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case YIELD_VALUE:
966 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500967 case YIELD_FROM:
968 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case POP_BLOCK:
970 return 0;
971 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200972 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200974 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200975 /* Pop 6 values when an exception was raised. */
976 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case STORE_NAME:
979 return -1;
980 case DELETE_NAME:
981 return 0;
982 case UNPACK_SEQUENCE:
983 return oparg-1;
984 case UNPACK_EX:
985 return (oparg&0xFF) + (oparg>>8);
986 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200987 /* -1 at end of iterator, 1 if continue iterating. */
988 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case STORE_ATTR:
991 return -2;
992 case DELETE_ATTR:
993 return -1;
994 case STORE_GLOBAL:
995 return -1;
996 case DELETE_GLOBAL:
997 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case LOAD_CONST:
999 return 1;
1000 case LOAD_NAME:
1001 return 1;
1002 case BUILD_TUPLE:
1003 case BUILD_LIST:
1004 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001005 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001007 case BUILD_LIST_UNPACK:
1008 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001009 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001010 case BUILD_SET_UNPACK:
1011 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001012 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001013 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001015 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001016 case BUILD_CONST_KEY_MAP:
1017 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case LOAD_ATTR:
1019 return 0;
1020 case COMPARE_OP:
1021 return -1;
1022 case IMPORT_NAME:
1023 return -1;
1024 case IMPORT_FROM:
1025 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001027 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case JUMP_ABSOLUTE:
1030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001032 case JUMP_IF_TRUE_OR_POP:
1033 case JUMP_IF_FALSE_OR_POP:
1034 return jump ? 0 : -1;
1035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case POP_JUMP_IF_FALSE:
1037 case POP_JUMP_IF_TRUE:
1038 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case LOAD_GLOBAL:
1041 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001043 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001045 /* 0 in the normal flow.
1046 * Restore the stack position and push 6 values before jumping to
1047 * the handler if an exception be raised. */
1048 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001049 case BEGIN_FINALLY:
1050 /* Actually pushes 1 value, but count 6 for balancing with
1051 * END_FINALLY and POP_FINALLY.
1052 * This is the main reason of using this opcode instead of
1053 * "LOAD_CONST None". */
1054 return 6;
1055 case CALL_FINALLY:
1056 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_FAST:
1059 return 1;
1060 case STORE_FAST:
1061 return -1;
1062 case DELETE_FAST:
1063 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case RAISE_VARARGS:
1066 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001067
1068 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001070 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001071 case CALL_METHOD:
1072 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg-1;
1075 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001076 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001077 case MAKE_FUNCTION:
1078 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1079 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 case BUILD_SLICE:
1081 if (oparg == 3)
1082 return -2;
1083 else
1084 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001086 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case LOAD_CLOSURE:
1088 return 1;
1089 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001090 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 return 1;
1092 case STORE_DEREF:
1093 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001094 case DELETE_DEREF:
1095 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096
1097 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001098 case GET_AWAITABLE:
1099 return 0;
1100 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001101 /* 0 in the normal flow.
1102 * Restore the stack position to the position before the result
1103 * of __aenter__ and push 6 values before jumping to the handler
1104 * if an exception be raised. */
1105 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001106 case BEFORE_ASYNC_WITH:
1107 return 1;
1108 case GET_AITER:
1109 return 0;
1110 case GET_ANEXT:
1111 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001112 case GET_YIELD_FROM_ITER:
1113 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001114 case END_ASYNC_FOR:
1115 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001116 case FORMAT_VALUE:
1117 /* If there's a fmt_spec on the stack, we go from 2->1,
1118 else 1->1. */
1119 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001120 case LOAD_METHOD:
1121 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001123 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 }
Larry Hastings3a907972013-11-23 14:49:22 -08001125 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126}
1127
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001128int
1129PyCompile_OpcodeStackEffect(int opcode, int oparg)
1130{
1131 return stack_effect(opcode, oparg, -1);
1132}
1133
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134/* Add an opcode with no argument.
1135 Returns 0 on failure, 1 on success.
1136*/
1137
1138static int
1139compiler_addop(struct compiler *c, int opcode)
1140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 basicblock *b;
1142 struct instr *i;
1143 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001144 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 off = compiler_next_instr(c, c->u->u_curblock);
1146 if (off < 0)
1147 return 0;
1148 b = c->u->u_curblock;
1149 i = &b->b_instr[off];
1150 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001151 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (opcode == RETURN_VALUE)
1153 b->b_return = 1;
1154 compiler_set_lineno(c, off);
1155 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156}
1157
Victor Stinnerf8e32212013-11-19 23:56:34 +01001158static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *t, *v;
1162 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163
Victor Stinnerefb24132016-01-22 12:33:12 +01001164 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (t == NULL)
1166 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 v = PyDict_GetItem(dict, t);
1169 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001170 if (PyErr_Occurred()) {
1171 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001173 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001174 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001175 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (!v) {
1177 Py_DECREF(t);
1178 return -1;
1179 }
1180 if (PyDict_SetItem(dict, t, v) < 0) {
1181 Py_DECREF(t);
1182 Py_DECREF(v);
1183 return -1;
1184 }
1185 Py_DECREF(v);
1186 }
1187 else
1188 arg = PyLong_AsLong(v);
1189 Py_DECREF(t);
1190 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191}
1192
1193static int
1194compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001197 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001199 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 return compiler_addop_i(c, opcode, arg);
1201}
1202
1203static int
1204compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001207 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1209 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001210 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 arg = compiler_add_o(c, dict, mangled);
1212 Py_DECREF(mangled);
1213 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001214 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215 return compiler_addop_i(c, opcode, arg);
1216}
1217
1218/* Add an opcode with an integer argument.
1219 Returns 0 on failure, 1 on success.
1220*/
1221
1222static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001223compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 struct instr *i;
1226 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001227
Victor Stinner2ad474b2016-03-01 23:34:47 +01001228 /* oparg value is unsigned, but a signed C int is usually used to store
1229 it in the C code (like Python/ceval.c).
1230
1231 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1232
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001233 The argument of a concrete bytecode instruction is limited to 8-bit.
1234 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1235 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001236 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 off = compiler_next_instr(c, c->u->u_curblock);
1239 if (off < 0)
1240 return 0;
1241 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001242 i->i_opcode = opcode;
1243 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 compiler_set_lineno(c, off);
1245 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
1248static int
1249compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 struct instr *i;
1252 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001254 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 assert(b != NULL);
1256 off = compiler_next_instr(c, c->u->u_curblock);
1257 if (off < 0)
1258 return 0;
1259 i = &c->u->u_curblock->b_instr[off];
1260 i->i_opcode = opcode;
1261 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (absolute)
1263 i->i_jabs = 1;
1264 else
1265 i->i_jrel = 1;
1266 compiler_set_lineno(c, off);
1267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268}
1269
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001270/* NEXT_BLOCK() creates an implicit jump from the current block
1271 to the new block.
1272
1273 The returns inside this macro make it impossible to decref objects
1274 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (compiler_next_block((C)) == NULL) \
1278 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_addop((C), (OP))) \
1283 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001286#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!compiler_addop((C), (OP))) { \
1288 compiler_exit_scope(c); \
1289 return 0; \
1290 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001291}
1292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1295 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001298/* Same as ADDOP_O, but steals a reference. */
1299#define ADDOP_N(C, OP, O, TYPE) { \
1300 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1301 Py_DECREF((O)); \
1302 return 0; \
1303 } \
1304 Py_DECREF((O)); \
1305}
1306
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1309 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (!compiler_addop_i((C), (OP), (O))) \
1314 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315}
1316
1317#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (!compiler_addop_j((C), (OP), (O), 1)) \
1319 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320}
1321
1322#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (!compiler_addop_j((C), (OP), (O), 0)) \
1324 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325}
1326
1327/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1328 the ASDL name to synthesize the name of the C type and the visit function.
1329*/
1330
1331#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (!compiler_visit_ ## TYPE((C), (V))) \
1333 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334}
1335
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001336#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (!compiler_visit_ ## TYPE((C), (V))) { \
1338 compiler_exit_scope(c); \
1339 return 0; \
1340 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001341}
1342
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (!compiler_visit_slice((C), (V), (CTX))) \
1345 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346}
1347
1348#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 int _i; \
1350 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1351 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1352 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1353 if (!compiler_visit_ ## TYPE((C), elt)) \
1354 return 0; \
1355 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356}
1357
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001358#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 int _i; \
1360 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1361 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1362 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1363 if (!compiler_visit_ ## TYPE((C), elt)) { \
1364 compiler_exit_scope(c); \
1365 return 0; \
1366 } \
1367 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001368}
1369
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001371is_const(expr_ty e)
1372{
1373 switch (e->kind) {
1374 case Constant_kind:
1375 case Num_kind:
1376 case Str_kind:
1377 case Bytes_kind:
1378 case Ellipsis_kind:
1379 case NameConstant_kind:
1380 return 1;
1381 default:
1382 return 0;
1383 }
1384}
1385
1386static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001387get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001388{
1389 switch (e->kind) {
1390 case Constant_kind:
1391 return e->v.Constant.value;
1392 case Num_kind:
1393 return e->v.Num.n;
1394 case Str_kind:
1395 return e->v.Str.s;
1396 case Bytes_kind:
1397 return e->v.Bytes.s;
1398 case Ellipsis_kind:
1399 return Py_Ellipsis;
1400 case NameConstant_kind:
1401 return e->v.NameConstant.value;
1402 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001403 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001404 }
1405}
1406
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001407/* Search if variable annotations are present statically in a block. */
1408
1409static int
1410find_ann(asdl_seq *stmts)
1411{
1412 int i, j, res = 0;
1413 stmt_ty st;
1414
1415 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1416 st = (stmt_ty)asdl_seq_GET(stmts, i);
1417 switch (st->kind) {
1418 case AnnAssign_kind:
1419 return 1;
1420 case For_kind:
1421 res = find_ann(st->v.For.body) ||
1422 find_ann(st->v.For.orelse);
1423 break;
1424 case AsyncFor_kind:
1425 res = find_ann(st->v.AsyncFor.body) ||
1426 find_ann(st->v.AsyncFor.orelse);
1427 break;
1428 case While_kind:
1429 res = find_ann(st->v.While.body) ||
1430 find_ann(st->v.While.orelse);
1431 break;
1432 case If_kind:
1433 res = find_ann(st->v.If.body) ||
1434 find_ann(st->v.If.orelse);
1435 break;
1436 case With_kind:
1437 res = find_ann(st->v.With.body);
1438 break;
1439 case AsyncWith_kind:
1440 res = find_ann(st->v.AsyncWith.body);
1441 break;
1442 case Try_kind:
1443 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1444 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1445 st->v.Try.handlers, j);
1446 if (find_ann(handler->v.ExceptHandler.body)) {
1447 return 1;
1448 }
1449 }
1450 res = find_ann(st->v.Try.body) ||
1451 find_ann(st->v.Try.finalbody) ||
1452 find_ann(st->v.Try.orelse);
1453 break;
1454 default:
1455 res = 0;
1456 }
1457 if (res) {
1458 break;
1459 }
1460 }
1461 return res;
1462}
1463
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001464/*
1465 * Frame block handling functions
1466 */
1467
1468static int
1469compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1470 basicblock *exit)
1471{
1472 struct fblockinfo *f;
1473 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1474 PyErr_SetString(PyExc_SyntaxError,
1475 "too many statically nested blocks");
1476 return 0;
1477 }
1478 f = &c->u->u_fblock[c->u->u_nfblocks++];
1479 f->fb_type = t;
1480 f->fb_block = b;
1481 f->fb_exit = exit;
1482 return 1;
1483}
1484
1485static void
1486compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1487{
1488 struct compiler_unit *u = c->u;
1489 assert(u->u_nfblocks > 0);
1490 u->u_nfblocks--;
1491 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1492 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1493}
1494
1495/* Unwind a frame block. If preserve_tos is true, the TOS before
1496 * popping the blocks will be restored afterwards.
1497 */
1498static int
1499compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1500 int preserve_tos)
1501{
1502 switch (info->fb_type) {
1503 case WHILE_LOOP:
1504 return 1;
1505
1506 case FINALLY_END:
1507 ADDOP_I(c, POP_FINALLY, preserve_tos);
1508 return 1;
1509
1510 case FOR_LOOP:
1511 /* Pop the iterator */
1512 if (preserve_tos) {
1513 ADDOP(c, ROT_TWO);
1514 }
1515 ADDOP(c, POP_TOP);
1516 return 1;
1517
1518 case EXCEPT:
1519 ADDOP(c, POP_BLOCK);
1520 return 1;
1521
1522 case FINALLY_TRY:
1523 ADDOP(c, POP_BLOCK);
1524 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1525 return 1;
1526
1527 case WITH:
1528 case ASYNC_WITH:
1529 ADDOP(c, POP_BLOCK);
1530 if (preserve_tos) {
1531 ADDOP(c, ROT_TWO);
1532 }
1533 ADDOP(c, BEGIN_FINALLY);
1534 ADDOP(c, WITH_CLEANUP_START);
1535 if (info->fb_type == ASYNC_WITH) {
1536 ADDOP(c, GET_AWAITABLE);
1537 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1538 ADDOP(c, YIELD_FROM);
1539 }
1540 ADDOP(c, WITH_CLEANUP_FINISH);
1541 ADDOP_I(c, POP_FINALLY, 0);
1542 return 1;
1543
1544 case HANDLER_CLEANUP:
1545 if (preserve_tos) {
1546 ADDOP(c, ROT_FOUR);
1547 }
1548 if (info->fb_exit) {
1549 ADDOP(c, POP_BLOCK);
1550 ADDOP(c, POP_EXCEPT);
1551 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1552 }
1553 else {
1554 ADDOP(c, POP_EXCEPT);
1555 }
1556 return 1;
1557 }
1558 Py_UNREACHABLE();
1559}
1560
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001561/* Compile a sequence of statements, checking for a docstring
1562 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563
1564static int
INADA Naokicb41b272017-02-23 00:31:59 +09001565compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001567 /* Set current line number to the line number of first statement.
1568 This way line number for SETUP_ANNOTATIONS will always
1569 coincide with the line number of first "real" statement in module.
1570 If body is empy, then lineno will be set later in assemble. */
1571 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1572 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001573 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001574 c->u->u_lineno = st->lineno;
1575 }
1576 /* Every annotated class and module should have __annotations__. */
1577 if (find_ann(stmts)) {
1578 ADDOP(c, SETUP_ANNOTATIONS);
1579 }
INADA Naokicb41b272017-02-23 00:31:59 +09001580 /* if not -OO mode, set docstring */
1581 if (c->c_optimize < 2 && docstring) {
1582 ADDOP_O(c, LOAD_CONST, docstring, consts);
1583 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 }
INADA Naokicb41b272017-02-23 00:31:59 +09001585 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587}
1588
1589static PyCodeObject *
1590compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyCodeObject *co;
1593 int addNone = 1;
1594 static PyObject *module;
1595 if (!module) {
1596 module = PyUnicode_InternFromString("<module>");
1597 if (!module)
1598 return NULL;
1599 }
1600 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001601 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 return NULL;
1603 switch (mod->kind) {
1604 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001605 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 compiler_exit_scope(c);
1607 return 0;
1608 }
1609 break;
1610 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001611 if (find_ann(mod->v.Interactive.body)) {
1612 ADDOP(c, SETUP_ANNOTATIONS);
1613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 c->c_interactive = 1;
1615 VISIT_SEQ_IN_SCOPE(c, stmt,
1616 mod->v.Interactive.body);
1617 break;
1618 case Expression_kind:
1619 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1620 addNone = 0;
1621 break;
1622 case Suite_kind:
1623 PyErr_SetString(PyExc_SystemError,
1624 "suite should not be possible");
1625 return 0;
1626 default:
1627 PyErr_Format(PyExc_SystemError,
1628 "module kind %d should not be possible",
1629 mod->kind);
1630 return 0;
1631 }
1632 co = assemble(c, addNone);
1633 compiler_exit_scope(c);
1634 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001635}
1636
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637/* The test for LOCAL must come before the test for FREE in order to
1638 handle classes where name is both local and free. The local var is
1639 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001640*/
1641
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642static int
1643get_ref_type(struct compiler *c, PyObject *name)
1644{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001645 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001646 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001647 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001648 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001649 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 if (scope == 0) {
1651 char buf[350];
1652 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001653 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001655 PyUnicode_AsUTF8(name),
1656 PyUnicode_AsUTF8(c->u->u_name),
1657 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1658 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1659 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1660 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 );
1662 Py_FatalError(buf);
1663 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001666}
1667
1668static int
1669compiler_lookup_arg(PyObject *dict, PyObject *name)
1670{
1671 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001672 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001674 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001676 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001678 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001679 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680}
1681
1682static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001683compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001685 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001686 if (qualname == NULL)
1687 qualname = co->co_name;
1688
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001689 if (free) {
1690 for (i = 0; i < free; ++i) {
1691 /* Bypass com_addop_varname because it will generate
1692 LOAD_DEREF but LOAD_CLOSURE is needed.
1693 */
1694 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1695 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001697 /* Special case: If a class contains a method with a
1698 free variable that has the same name as a method,
1699 the name will be considered free *and* local in the
1700 class. It should be handled by the closure, as
1701 well as by the normal name loookup logic.
1702 */
1703 reftype = get_ref_type(c, name);
1704 if (reftype == CELL)
1705 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1706 else /* (reftype == FREE) */
1707 arg = compiler_lookup_arg(c->u->u_freevars, name);
1708 if (arg == -1) {
1709 fprintf(stderr,
1710 "lookup %s in %s %d %d\n"
1711 "freevars of %s: %s\n",
1712 PyUnicode_AsUTF8(PyObject_Repr(name)),
1713 PyUnicode_AsUTF8(c->u->u_name),
1714 reftype, arg,
1715 PyUnicode_AsUTF8(co->co_name),
1716 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1717 Py_FatalError("compiler_make_closure()");
1718 }
1719 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001721 flags |= 0x08;
1722 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001725 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001726 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001728}
1729
1730static int
1731compiler_decorators(struct compiler *c, asdl_seq* decos)
1732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (!decos)
1736 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1739 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1740 }
1741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001742}
1743
1744static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001745compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001747{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001748 /* Push a dict of keyword-only default values.
1749
1750 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1751 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001752 int i;
1753 PyObject *keys = NULL;
1754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1756 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1757 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1758 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001759 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001760 if (!mangled) {
1761 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001763 if (keys == NULL) {
1764 keys = PyList_New(1);
1765 if (keys == NULL) {
1766 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001767 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768 }
1769 PyList_SET_ITEM(keys, 0, mangled);
1770 }
1771 else {
1772 int res = PyList_Append(keys, mangled);
1773 Py_DECREF(mangled);
1774 if (res == -1) {
1775 goto error;
1776 }
1777 }
1778 if (!compiler_visit_expr(c, default_)) {
1779 goto error;
1780 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 }
1782 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001783 if (keys != NULL) {
1784 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1785 PyObject *keys_tuple = PyList_AsTuple(keys);
1786 Py_DECREF(keys);
1787 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001788 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001789 }
1790 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1791 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001792 assert(default_count > 0);
1793 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001794 }
1795 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001796 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001797 }
1798
1799error:
1800 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001801 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001802}
1803
1804static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001805compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1806{
1807 PyObject *ann_as_str;
1808 ann_as_str = _PyAST_ExprAsUnicode(annotation, 1);
1809 if (!ann_as_str) {
1810 return 0;
1811 }
1812 ADDOP_N(c, LOAD_CONST, ann_as_str, consts);
1813 return 1;
1814}
1815
1816static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001817compiler_visit_argannotation(struct compiler *c, identifier id,
1818 expr_ty annotation, PyObject *names)
1819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001821 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001822 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1823 VISIT(c, annexpr, annotation)
1824 }
1825 else {
1826 VISIT(c, expr, annotation);
1827 }
Victor Stinner065efc32014-02-18 22:07:56 +01001828 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001829 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001830 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001831 if (PyList_Append(names, mangled) < 0) {
1832 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001833 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001834 }
1835 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001837 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001838}
1839
1840static int
1841compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1842 PyObject *names)
1843{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001844 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 for (i = 0; i < asdl_seq_LEN(args); i++) {
1846 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001847 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 c,
1849 arg->arg,
1850 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001851 names))
1852 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001854 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001855}
1856
1857static int
1858compiler_visit_annotations(struct compiler *c, arguments_ty args,
1859 expr_ty returns)
1860{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001861 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001862 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001863
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001864 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 */
1866 static identifier return_str;
1867 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001868 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 names = PyList_New(0);
1870 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001871 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001872
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001873 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001875 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001876 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001877 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001879 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001881 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001882 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001883 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (!return_str) {
1887 return_str = PyUnicode_InternFromString("return");
1888 if (!return_str)
1889 goto error;
1890 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001891 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 goto error;
1893 }
1894
1895 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001897 PyObject *keytuple = PyList_AsTuple(names);
1898 Py_DECREF(names);
1899 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001900 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001902 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1903 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001904 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001906 else {
1907 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001908 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001909 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001910
1911error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001913 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001914}
1915
1916static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001917compiler_visit_defaults(struct compiler *c, arguments_ty args)
1918{
1919 VISIT_SEQ(c, expr, args->defaults);
1920 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1921 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922}
1923
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924static Py_ssize_t
1925compiler_default_arguments(struct compiler *c, arguments_ty args)
1926{
1927 Py_ssize_t funcflags = 0;
1928 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001929 if (!compiler_visit_defaults(c, args))
1930 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001931 funcflags |= 0x01;
1932 }
1933 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001934 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001935 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001936 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001937 return -1;
1938 }
1939 else if (res > 0) {
1940 funcflags |= 0x02;
1941 }
1942 }
1943 return funcflags;
1944}
1945
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946static int
Yury Selivanov75445082015-05-11 22:57:16 -04001947compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001950 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001951 arguments_ty args;
1952 expr_ty returns;
1953 identifier name;
1954 asdl_seq* decos;
1955 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001956 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001957 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001958 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959
Yury Selivanov75445082015-05-11 22:57:16 -04001960 if (is_async) {
1961 assert(s->kind == AsyncFunctionDef_kind);
1962
1963 args = s->v.AsyncFunctionDef.args;
1964 returns = s->v.AsyncFunctionDef.returns;
1965 decos = s->v.AsyncFunctionDef.decorator_list;
1966 name = s->v.AsyncFunctionDef.name;
1967 body = s->v.AsyncFunctionDef.body;
1968
1969 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1970 } else {
1971 assert(s->kind == FunctionDef_kind);
1972
1973 args = s->v.FunctionDef.args;
1974 returns = s->v.FunctionDef.returns;
1975 decos = s->v.FunctionDef.decorator_list;
1976 name = s->v.FunctionDef.name;
1977 body = s->v.FunctionDef.body;
1978
1979 scope_type = COMPILER_SCOPE_FUNCTION;
1980 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (!compiler_decorators(c, decos))
1983 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001984
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001985 funcflags = compiler_default_arguments(c, args);
1986 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001988 }
1989
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 annotations = compiler_visit_annotations(c, args, returns);
1991 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001992 return 0;
1993 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001994 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001995 funcflags |= 0x04;
1996 }
1997
1998 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1999 return 0;
2000 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001
INADA Naokicb41b272017-02-23 00:31:59 +09002002 /* if not -OO mode, add docstring */
2003 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
2004 docstring = s->v.FunctionDef.docstring;
2005 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 compiler_exit_scope(c);
2007 return 0;
2008 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 c->u->u_argcount = asdl_seq_LEN(args->args);
2011 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09002013 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002015 qualname = c->u->u_qualname;
2016 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002018 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002019 Py_XDECREF(qualname);
2020 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002022 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002024 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002025 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* decorators */
2029 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2030 ADDOP_I(c, CALL_FUNCTION, 1);
2031 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032
Yury Selivanov75445082015-05-11 22:57:16 -04002033 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
2036static int
2037compiler_class(struct compiler *c, stmt_ty s)
2038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyCodeObject *co;
2040 PyObject *str;
2041 int i;
2042 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 if (!compiler_decorators(c, decos))
2045 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 /* ultimately generate code for:
2048 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2049 where:
2050 <func> is a function/closure created from the class body;
2051 it has a single argument (__locals__) where the dict
2052 (or MutableSequence) representing the locals is passed
2053 <name> is the class name
2054 <bases> is the positional arguments and *varargs argument
2055 <keywords> is the keyword arguments and **kwds argument
2056 This borrows from compiler_call.
2057 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002060 if (!compiler_enter_scope(c, s->v.ClassDef.name,
2061 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 return 0;
2063 /* this block represents what we do in the new scope */
2064 {
2065 /* use the class name for name mangling */
2066 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002067 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 /* load (global) __name__ ... */
2069 str = PyUnicode_InternFromString("__name__");
2070 if (!str || !compiler_nameop(c, str, Load)) {
2071 Py_XDECREF(str);
2072 compiler_exit_scope(c);
2073 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_DECREF(str);
2076 /* ... and store it as __module__ */
2077 str = PyUnicode_InternFromString("__module__");
2078 if (!str || !compiler_nameop(c, str, Store)) {
2079 Py_XDECREF(str);
2080 compiler_exit_scope(c);
2081 return 0;
2082 }
2083 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002084 assert(c->u->u_qualname);
2085 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002086 str = PyUnicode_InternFromString("__qualname__");
2087 if (!str || !compiler_nameop(c, str, Store)) {
2088 Py_XDECREF(str);
2089 compiler_exit_scope(c);
2090 return 0;
2091 }
2092 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09002094 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 compiler_exit_scope(c);
2096 return 0;
2097 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002098 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002099 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002100 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002101 str = PyUnicode_InternFromString("__class__");
2102 if (str == NULL) {
2103 compiler_exit_scope(c);
2104 return 0;
2105 }
2106 i = compiler_lookup_arg(c->u->u_cellvars, str);
2107 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002108 if (i < 0) {
2109 compiler_exit_scope(c);
2110 return 0;
2111 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002112 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002115 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002116 str = PyUnicode_InternFromString("__classcell__");
2117 if (!str || !compiler_nameop(c, str, Store)) {
2118 Py_XDECREF(str);
2119 compiler_exit_scope(c);
2120 return 0;
2121 }
2122 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002124 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002125 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002126 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10002127 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002128 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002129 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 /* create the code object */
2131 co = assemble(c, 1);
2132 }
2133 /* leave the new scope */
2134 compiler_exit_scope(c);
2135 if (co == NULL)
2136 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 /* 2. load the 'build_class' function */
2139 ADDOP(c, LOAD_BUILD_CLASS);
2140
2141 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002142 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 Py_DECREF(co);
2144
2145 /* 4. load class name */
2146 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2147
2148 /* 5. generate the rest of the code for the call */
2149 if (!compiler_call_helper(c, 2,
2150 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002151 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 return 0;
2153
2154 /* 6. apply decorators */
2155 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2156 ADDOP_I(c, CALL_FUNCTION, 1);
2157 }
2158
2159 /* 7. store into <name> */
2160 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2161 return 0;
2162 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163}
2164
2165static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002166cmpop(cmpop_ty op)
2167{
2168 switch (op) {
2169 case Eq:
2170 return PyCmp_EQ;
2171 case NotEq:
2172 return PyCmp_NE;
2173 case Lt:
2174 return PyCmp_LT;
2175 case LtE:
2176 return PyCmp_LE;
2177 case Gt:
2178 return PyCmp_GT;
2179 case GtE:
2180 return PyCmp_GE;
2181 case Is:
2182 return PyCmp_IS;
2183 case IsNot:
2184 return PyCmp_IS_NOT;
2185 case In:
2186 return PyCmp_IN;
2187 case NotIn:
2188 return PyCmp_NOT_IN;
2189 default:
2190 return PyCmp_BAD;
2191 }
2192}
2193
2194static int
2195compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2196{
2197 switch (e->kind) {
2198 case UnaryOp_kind:
2199 if (e->v.UnaryOp.op == Not)
2200 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2201 /* fallback to general implementation */
2202 break;
2203 case BoolOp_kind: {
2204 asdl_seq *s = e->v.BoolOp.values;
2205 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2206 assert(n >= 0);
2207 int cond2 = e->v.BoolOp.op == Or;
2208 basicblock *next2 = next;
2209 if (!cond2 != !cond) {
2210 next2 = compiler_new_block(c);
2211 if (next2 == NULL)
2212 return 0;
2213 }
2214 for (i = 0; i < n; ++i) {
2215 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2216 return 0;
2217 }
2218 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2219 return 0;
2220 if (next2 != next)
2221 compiler_use_next_block(c, next2);
2222 return 1;
2223 }
2224 case IfExp_kind: {
2225 basicblock *end, *next2;
2226 end = compiler_new_block(c);
2227 if (end == NULL)
2228 return 0;
2229 next2 = compiler_new_block(c);
2230 if (next2 == NULL)
2231 return 0;
2232 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2233 return 0;
2234 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2235 return 0;
2236 ADDOP_JREL(c, JUMP_FORWARD, end);
2237 compiler_use_next_block(c, next2);
2238 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2239 return 0;
2240 compiler_use_next_block(c, end);
2241 return 1;
2242 }
2243 case Compare_kind: {
2244 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2245 if (n > 0) {
2246 basicblock *cleanup = compiler_new_block(c);
2247 if (cleanup == NULL)
2248 return 0;
2249 VISIT(c, expr, e->v.Compare.left);
2250 for (i = 0; i < n; i++) {
2251 VISIT(c, expr,
2252 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2253 ADDOP(c, DUP_TOP);
2254 ADDOP(c, ROT_THREE);
2255 ADDOP_I(c, COMPARE_OP,
2256 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2257 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2258 NEXT_BLOCK(c);
2259 }
2260 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2261 ADDOP_I(c, COMPARE_OP,
2262 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2263 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2264 basicblock *end = compiler_new_block(c);
2265 if (end == NULL)
2266 return 0;
2267 ADDOP_JREL(c, JUMP_FORWARD, end);
2268 compiler_use_next_block(c, cleanup);
2269 ADDOP(c, POP_TOP);
2270 if (!cond) {
2271 ADDOP_JREL(c, JUMP_FORWARD, next);
2272 }
2273 compiler_use_next_block(c, end);
2274 return 1;
2275 }
2276 /* fallback to general implementation */
2277 break;
2278 }
2279 default:
2280 /* fallback to general implementation */
2281 break;
2282 }
2283
2284 /* general implementation */
2285 VISIT(c, expr, e);
2286 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2287 return 1;
2288}
2289
2290static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002291compiler_ifexp(struct compiler *c, expr_ty e)
2292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 basicblock *end, *next;
2294
2295 assert(e->kind == IfExp_kind);
2296 end = compiler_new_block(c);
2297 if (end == NULL)
2298 return 0;
2299 next = compiler_new_block(c);
2300 if (next == NULL)
2301 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002302 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2303 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 VISIT(c, expr, e->v.IfExp.body);
2305 ADDOP_JREL(c, JUMP_FORWARD, end);
2306 compiler_use_next_block(c, next);
2307 VISIT(c, expr, e->v.IfExp.orelse);
2308 compiler_use_next_block(c, end);
2309 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002310}
2311
2312static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313compiler_lambda(struct compiler *c, expr_ty e)
2314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002316 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002318 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 arguments_ty args = e->v.Lambda.args;
2320 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (!name) {
2323 name = PyUnicode_InternFromString("<lambda>");
2324 if (!name)
2325 return 0;
2326 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002328 funcflags = compiler_default_arguments(c, args);
2329 if (funcflags == -1) {
2330 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002332
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002333 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002334 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Make None the first constant, so the lambda can't have a
2338 docstring. */
2339 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2340 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 c->u->u_argcount = asdl_seq_LEN(args->args);
2343 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2344 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2345 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002346 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 }
2348 else {
2349 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002350 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002352 qualname = c->u->u_qualname;
2353 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002355 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002358 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002359 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 Py_DECREF(co);
2361
2362 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363}
2364
2365static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366compiler_if(struct compiler *c, stmt_ty s)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 basicblock *end, *next;
2369 int constant;
2370 assert(s->kind == If_kind);
2371 end = compiler_new_block(c);
2372 if (end == NULL)
2373 return 0;
2374
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002375 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* constant = 0: "if 0"
2377 * constant = 1: "if 1", "if 2", ...
2378 * constant = -1: rest */
2379 if (constant == 0) {
2380 if (s->v.If.orelse)
2381 VISIT_SEQ(c, stmt, s->v.If.orelse);
2382 } else if (constant == 1) {
2383 VISIT_SEQ(c, stmt, s->v.If.body);
2384 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002385 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 next = compiler_new_block(c);
2387 if (next == NULL)
2388 return 0;
2389 }
2390 else
2391 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002392 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2393 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002395 if (asdl_seq_LEN(s->v.If.orelse)) {
2396 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 compiler_use_next_block(c, next);
2398 VISIT_SEQ(c, stmt, s->v.If.orelse);
2399 }
2400 }
2401 compiler_use_next_block(c, end);
2402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403}
2404
2405static int
2406compiler_for(struct compiler *c, stmt_ty s)
2407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 start = compiler_new_block(c);
2411 cleanup = compiler_new_block(c);
2412 end = compiler_new_block(c);
2413 if (start == NULL || end == NULL || cleanup == NULL)
2414 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002415
2416 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 VISIT(c, expr, s->v.For.iter);
2420 ADDOP(c, GET_ITER);
2421 compiler_use_next_block(c, start);
2422 ADDOP_JREL(c, FOR_ITER, cleanup);
2423 VISIT(c, expr, s->v.For.target);
2424 VISIT_SEQ(c, stmt, s->v.For.body);
2425 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2426 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002427
2428 compiler_pop_fblock(c, FOR_LOOP, start);
2429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 VISIT_SEQ(c, stmt, s->v.For.orelse);
2431 compiler_use_next_block(c, end);
2432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433}
2434
Yury Selivanov75445082015-05-11 22:57:16 -04002435
2436static int
2437compiler_async_for(struct compiler *c, stmt_ty s)
2438{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002439 basicblock *start, *except, *end;
2440 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002441 except = compiler_new_block(c);
2442 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002443
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002444 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002445 return 0;
2446
2447 VISIT(c, expr, s->v.AsyncFor.iter);
2448 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002449
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002450 compiler_use_next_block(c, start);
2451 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2452 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002453
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002454 /* SETUP_FINALLY to guard the __anext__ call */
2455 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002456 ADDOP(c, GET_ANEXT);
2457 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2458 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002459 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002460
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002461 /* Success block for __anext__ */
2462 VISIT(c, expr, s->v.AsyncFor.target);
2463 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2464 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2465
2466 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002467
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002468 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002469 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002470 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002471
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002472 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002473 VISIT_SEQ(c, stmt, s->v.For.orelse);
2474
2475 compiler_use_next_block(c, end);
2476
2477 return 1;
2478}
2479
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480static int
2481compiler_while(struct compiler *c, stmt_ty s)
2482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002484 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (constant == 0) {
2487 if (s->v.While.orelse)
2488 VISIT_SEQ(c, stmt, s->v.While.orelse);
2489 return 1;
2490 }
2491 loop = compiler_new_block(c);
2492 end = compiler_new_block(c);
2493 if (constant == -1) {
2494 anchor = compiler_new_block(c);
2495 if (anchor == NULL)
2496 return 0;
2497 }
2498 if (loop == NULL || end == NULL)
2499 return 0;
2500 if (s->v.While.orelse) {
2501 orelse = compiler_new_block(c);
2502 if (orelse == NULL)
2503 return 0;
2504 }
2505 else
2506 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002509 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 return 0;
2511 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002512 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2513 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 }
2515 VISIT_SEQ(c, stmt, s->v.While.body);
2516 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 /* XXX should the two POP instructions be in a separate block
2519 if there is no else clause ?
2520 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002522 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002524 compiler_pop_fblock(c, WHILE_LOOP, loop);
2525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 if (orelse != NULL) /* what if orelse is just pass? */
2527 VISIT_SEQ(c, stmt, s->v.While.orelse);
2528 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531}
2532
2533static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002534compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002536 int preserve_tos = ((s->v.Return.value != NULL) &&
2537 !is_const(s->v.Return.value));
2538 if (c->u->u_ste->ste_type != FunctionBlock)
2539 return compiler_error(c, "'return' outside function");
2540 if (s->v.Return.value != NULL &&
2541 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2542 {
2543 return compiler_error(
2544 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002546 if (preserve_tos) {
2547 VISIT(c, expr, s->v.Return.value);
2548 }
2549 for (int depth = c->u->u_nfblocks; depth--;) {
2550 struct fblockinfo *info = &c->u->u_fblock[depth];
2551
2552 if (!compiler_unwind_fblock(c, info, preserve_tos))
2553 return 0;
2554 }
2555 if (s->v.Return.value == NULL) {
2556 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2557 }
2558 else if (!preserve_tos) {
2559 VISIT(c, expr, s->v.Return.value);
2560 }
2561 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564}
2565
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002566static int
2567compiler_break(struct compiler *c)
2568{
2569 for (int depth = c->u->u_nfblocks; depth--;) {
2570 struct fblockinfo *info = &c->u->u_fblock[depth];
2571
2572 if (!compiler_unwind_fblock(c, info, 0))
2573 return 0;
2574 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2575 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2576 return 1;
2577 }
2578 }
2579 return compiler_error(c, "'break' outside loop");
2580}
2581
2582static int
2583compiler_continue(struct compiler *c)
2584{
2585 for (int depth = c->u->u_nfblocks; depth--;) {
2586 struct fblockinfo *info = &c->u->u_fblock[depth];
2587
2588 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2589 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2590 return 1;
2591 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002592 if (!compiler_unwind_fblock(c, info, 0))
2593 return 0;
2594 }
2595 return compiler_error(c, "'continue' not properly in loop");
2596}
2597
2598
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600
2601 SETUP_FINALLY L
2602 <code for body>
2603 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002604 BEGIN_FINALLY
2605 L:
2606 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 END_FINALLY
2608
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 The special instructions use the block stack. Each block
2610 stack entry contains the instruction that created it (here
2611 SETUP_FINALLY), the level of the value stack at the time the
2612 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 Pushes the current value stack level and the label
2616 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002618 Pops en entry from the block stack.
2619 BEGIN_FINALLY
2620 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002622 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2623 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002626 when a SETUP_FINALLY entry is found, the raised and the caught
2627 exceptions are pushed onto the value stack (and the exception
2628 condition is cleared), and the interpreter jumps to the label
2629 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630*/
2631
2632static int
2633compiler_try_finally(struct compiler *c, stmt_ty s)
2634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 body = compiler_new_block(c);
2638 end = compiler_new_block(c);
2639 if (body == NULL || end == NULL)
2640 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002642 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 ADDOP_JREL(c, SETUP_FINALLY, end);
2644 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002645 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002647 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2648 if (!compiler_try_except(c, s))
2649 return 0;
2650 }
2651 else {
2652 VISIT_SEQ(c, stmt, s->v.Try.body);
2653 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002655 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002658 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002660 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002662 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 ADDOP(c, END_FINALLY);
2664 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666}
2667
2668/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002669 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 (The contents of the value stack is shown in [], with the top
2671 at the right; 'tb' is trace-back info, 'val' the exception's
2672 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673
2674 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002675 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 [] <code for S>
2677 [] POP_BLOCK
2678 [] JUMP_FORWARD L0
2679
2680 [tb, val, exc] L1: DUP )
2681 [tb, val, exc, exc] <evaluate E1> )
2682 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2683 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2684 [tb, val, exc] POP
2685 [tb, val] <assign to V1> (or POP if no V1)
2686 [tb] POP
2687 [] <code for S1>
2688 JUMP_FORWARD L0
2689
2690 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691 .............................etc.......................
2692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2694
2695 [] L0: <next statement>
2696
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 Of course, parts are not generated if Vi or Ei is not present.
2698*/
2699static int
2700compiler_try_except(struct compiler *c, stmt_ty s)
2701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002703 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 body = compiler_new_block(c);
2706 except = compiler_new_block(c);
2707 orelse = compiler_new_block(c);
2708 end = compiler_new_block(c);
2709 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2710 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002711 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002713 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002715 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 ADDOP(c, POP_BLOCK);
2717 compiler_pop_fblock(c, EXCEPT, body);
2718 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002719 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 compiler_use_next_block(c, except);
2721 for (i = 0; i < n; i++) {
2722 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002723 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 if (!handler->v.ExceptHandler.type && i < n-1)
2725 return compiler_error(c, "default 'except:' must be last");
2726 c->u->u_lineno_set = 0;
2727 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002728 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 except = compiler_new_block(c);
2730 if (except == NULL)
2731 return 0;
2732 if (handler->v.ExceptHandler.type) {
2733 ADDOP(c, DUP_TOP);
2734 VISIT(c, expr, handler->v.ExceptHandler.type);
2735 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2736 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2737 }
2738 ADDOP(c, POP_TOP);
2739 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002740 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002741
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002742 cleanup_end = compiler_new_block(c);
2743 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002744 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002745 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002746
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002747 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2748 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002750 /*
2751 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002752 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002753 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002754 try:
2755 # body
2756 finally:
2757 name = None
2758 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002759 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002761 /* second try: */
2762 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2763 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002764 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002765 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002767 /* second # body */
2768 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2769 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002770 ADDOP(c, BEGIN_FINALLY);
2771 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002773 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002774 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002775 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002776 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002778 /* name = None; del name */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002779 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2780 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002781 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002783 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002784 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002785 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 }
2787 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002788 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002790 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002791 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002792 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793
Guido van Rossumb940e112007-01-10 16:19:56 +00002794 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002795 ADDOP(c, POP_TOP);
2796 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002797 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002798 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002800 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 }
2803 ADDOP_JREL(c, JUMP_FORWARD, end);
2804 compiler_use_next_block(c, except);
2805 }
2806 ADDOP(c, END_FINALLY);
2807 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002808 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 compiler_use_next_block(c, end);
2810 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811}
2812
2813static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002814compiler_try(struct compiler *c, stmt_ty s) {
2815 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2816 return compiler_try_finally(c, s);
2817 else
2818 return compiler_try_except(c, s);
2819}
2820
2821
2822static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002823compiler_import_as(struct compiler *c, identifier name, identifier asname)
2824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* The IMPORT_NAME opcode was already generated. This function
2826 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002829 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002831 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2832 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002833 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002834 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002837 while (1) {
2838 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002840 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002842 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002843 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002845 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002846 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002847 if (dot == -1) {
2848 break;
2849 }
2850 ADDOP(c, ROT_TWO);
2851 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002853 if (!compiler_nameop(c, asname, Store)) {
2854 return 0;
2855 }
2856 ADDOP(c, POP_TOP);
2857 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 }
2859 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860}
2861
2862static int
2863compiler_import(struct compiler *c, stmt_ty s)
2864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 /* The Import node stores a module name like a.b.c as a single
2866 string. This is convenient for all cases except
2867 import a.b.c as d
2868 where we need to parse that string to extract the individual
2869 module names.
2870 XXX Perhaps change the representation to make this case simpler?
2871 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002872 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 for (i = 0; i < n; i++) {
2875 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2876 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002878 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2880 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 if (alias->asname) {
2883 r = compiler_import_as(c, alias->name, alias->asname);
2884 if (!r)
2885 return r;
2886 }
2887 else {
2888 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002889 Py_ssize_t dot = PyUnicode_FindChar(
2890 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002891 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002892 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002893 if (tmp == NULL)
2894 return 0;
2895 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002897 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 Py_DECREF(tmp);
2899 }
2900 if (!r)
2901 return r;
2902 }
2903 }
2904 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905}
2906
2907static int
2908compiler_from_import(struct compiler *c, stmt_ty s)
2909{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002910 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002911 PyObject *level, *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 if (!empty_string) {
2915 empty_string = PyUnicode_FromString("");
2916 if (!empty_string)
2917 return 0;
2918 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 level = PyLong_FromLong(s->v.ImportFrom.level);
2921 if (!level) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 return 0;
2923 }
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002924 ADDOP_N(c, LOAD_CONST, level, consts);
2925
2926 names = PyTuple_New(n);
2927 if (!names)
2928 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 /* build up the names */
2931 for (i = 0; i < n; i++) {
2932 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2933 Py_INCREF(alias->name);
2934 PyTuple_SET_ITEM(names, i, alias->name);
2935 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002938 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 Py_DECREF(names);
2940 return compiler_error(c, "from __future__ imports must occur "
2941 "at the beginning of the file");
2942 }
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002943 ADDOP_N(c, LOAD_CONST, names, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 if (s->v.ImportFrom.module) {
2946 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2947 }
2948 else {
2949 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2950 }
2951 for (i = 0; i < n; i++) {
2952 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2953 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002955 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 assert(n == 1);
2957 ADDOP(c, IMPORT_STAR);
2958 return 1;
2959 }
2960
2961 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2962 store_name = alias->name;
2963 if (alias->asname)
2964 store_name = alias->asname;
2965
2966 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 return 0;
2968 }
2969 }
2970 /* remove imported module */
2971 ADDOP(c, POP_TOP);
2972 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973}
2974
2975static int
2976compiler_assert(struct compiler *c, stmt_ty s)
2977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 static PyObject *assertion_error = NULL;
2979 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002980 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981
Georg Brandl8334fd92010-12-04 10:26:46 +00002982 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 return 1;
2984 if (assertion_error == NULL) {
2985 assertion_error = PyUnicode_InternFromString("AssertionError");
2986 if (assertion_error == NULL)
2987 return 0;
2988 }
2989 if (s->v.Assert.test->kind == Tuple_kind &&
2990 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002991 msg = PyUnicode_FromString("assertion is always true, "
2992 "perhaps remove parentheses?");
2993 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002995 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2996 c->c_filename, c->u->u_lineno,
2997 NULL, NULL) == -1) {
2998 Py_DECREF(msg);
2999 return 0;
3000 }
3001 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 end = compiler_new_block(c);
3004 if (end == NULL)
3005 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003006 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3007 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3009 if (s->v.Assert.msg) {
3010 VISIT(c, expr, s->v.Assert.msg);
3011 ADDOP_I(c, CALL_FUNCTION, 1);
3012 }
3013 ADDOP_I(c, RAISE_VARARGS, 1);
3014 compiler_use_next_block(c, end);
3015 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016}
3017
3018static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003019compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3020{
3021 if (c->c_interactive && c->c_nestlevel <= 1) {
3022 VISIT(c, expr, value);
3023 ADDOP(c, PRINT_EXPR);
3024 return 1;
3025 }
3026
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003027 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003028 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003029 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003030 }
3031
3032 VISIT(c, expr, value);
3033 ADDOP(c, POP_TOP);
3034 return 1;
3035}
3036
3037static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038compiler_visit_stmt(struct compiler *c, stmt_ty s)
3039{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003040 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 /* Always assign a lineno to the next instruction for a stmt. */
3043 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003044 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 switch (s->kind) {
3048 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003049 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 case ClassDef_kind:
3051 return compiler_class(c, s);
3052 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003053 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 case Delete_kind:
3055 VISIT_SEQ(c, expr, s->v.Delete.targets)
3056 break;
3057 case Assign_kind:
3058 n = asdl_seq_LEN(s->v.Assign.targets);
3059 VISIT(c, expr, s->v.Assign.value);
3060 for (i = 0; i < n; i++) {
3061 if (i < n - 1)
3062 ADDOP(c, DUP_TOP);
3063 VISIT(c, expr,
3064 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3065 }
3066 break;
3067 case AugAssign_kind:
3068 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003069 case AnnAssign_kind:
3070 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 case For_kind:
3072 return compiler_for(c, s);
3073 case While_kind:
3074 return compiler_while(c, s);
3075 case If_kind:
3076 return compiler_if(c, s);
3077 case Raise_kind:
3078 n = 0;
3079 if (s->v.Raise.exc) {
3080 VISIT(c, expr, s->v.Raise.exc);
3081 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003082 if (s->v.Raise.cause) {
3083 VISIT(c, expr, s->v.Raise.cause);
3084 n++;
3085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003087 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003089 case Try_kind:
3090 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 case Assert_kind:
3092 return compiler_assert(c, s);
3093 case Import_kind:
3094 return compiler_import(c, s);
3095 case ImportFrom_kind:
3096 return compiler_from_import(c, s);
3097 case Global_kind:
3098 case Nonlocal_kind:
3099 break;
3100 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003101 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 case Pass_kind:
3103 break;
3104 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003105 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 case Continue_kind:
3107 return compiler_continue(c);
3108 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003109 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003110 case AsyncFunctionDef_kind:
3111 return compiler_function(c, s, 1);
3112 case AsyncWith_kind:
3113 return compiler_async_with(c, s, 0);
3114 case AsyncFor_kind:
3115 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
Yury Selivanov75445082015-05-11 22:57:16 -04003117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119}
3120
3121static int
3122unaryop(unaryop_ty op)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 switch (op) {
3125 case Invert:
3126 return UNARY_INVERT;
3127 case Not:
3128 return UNARY_NOT;
3129 case UAdd:
3130 return UNARY_POSITIVE;
3131 case USub:
3132 return UNARY_NEGATIVE;
3133 default:
3134 PyErr_Format(PyExc_SystemError,
3135 "unary op %d should not be possible", op);
3136 return 0;
3137 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138}
3139
3140static int
3141binop(struct compiler *c, operator_ty op)
3142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 switch (op) {
3144 case Add:
3145 return BINARY_ADD;
3146 case Sub:
3147 return BINARY_SUBTRACT;
3148 case Mult:
3149 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003150 case MatMult:
3151 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 case Div:
3153 return BINARY_TRUE_DIVIDE;
3154 case Mod:
3155 return BINARY_MODULO;
3156 case Pow:
3157 return BINARY_POWER;
3158 case LShift:
3159 return BINARY_LSHIFT;
3160 case RShift:
3161 return BINARY_RSHIFT;
3162 case BitOr:
3163 return BINARY_OR;
3164 case BitXor:
3165 return BINARY_XOR;
3166 case BitAnd:
3167 return BINARY_AND;
3168 case FloorDiv:
3169 return BINARY_FLOOR_DIVIDE;
3170 default:
3171 PyErr_Format(PyExc_SystemError,
3172 "binary op %d should not be possible", op);
3173 return 0;
3174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175}
3176
3177static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178inplace_binop(struct compiler *c, operator_ty op)
3179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 switch (op) {
3181 case Add:
3182 return INPLACE_ADD;
3183 case Sub:
3184 return INPLACE_SUBTRACT;
3185 case Mult:
3186 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003187 case MatMult:
3188 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 case Div:
3190 return INPLACE_TRUE_DIVIDE;
3191 case Mod:
3192 return INPLACE_MODULO;
3193 case Pow:
3194 return INPLACE_POWER;
3195 case LShift:
3196 return INPLACE_LSHIFT;
3197 case RShift:
3198 return INPLACE_RSHIFT;
3199 case BitOr:
3200 return INPLACE_OR;
3201 case BitXor:
3202 return INPLACE_XOR;
3203 case BitAnd:
3204 return INPLACE_AND;
3205 case FloorDiv:
3206 return INPLACE_FLOOR_DIVIDE;
3207 default:
3208 PyErr_Format(PyExc_SystemError,
3209 "inplace binary op %d should not be possible", op);
3210 return 0;
3211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212}
3213
3214static int
3215compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3216{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003217 int op, scope;
3218 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 PyObject *dict = c->u->u_names;
3222 PyObject *mangled;
3223 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003225 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3226 !_PyUnicode_EqualToASCIIString(name, "True") &&
3227 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003228
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003229 mangled = _Py_Mangle(c->u->u_private, name);
3230 if (!mangled)
3231 return 0;
3232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 op = 0;
3234 optype = OP_NAME;
3235 scope = PyST_GetScope(c->u->u_ste, mangled);
3236 switch (scope) {
3237 case FREE:
3238 dict = c->u->u_freevars;
3239 optype = OP_DEREF;
3240 break;
3241 case CELL:
3242 dict = c->u->u_cellvars;
3243 optype = OP_DEREF;
3244 break;
3245 case LOCAL:
3246 if (c->u->u_ste->ste_type == FunctionBlock)
3247 optype = OP_FAST;
3248 break;
3249 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003250 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 optype = OP_GLOBAL;
3252 break;
3253 case GLOBAL_EXPLICIT:
3254 optype = OP_GLOBAL;
3255 break;
3256 default:
3257 /* scope can be 0 */
3258 break;
3259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003262 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 switch (optype) {
3265 case OP_DEREF:
3266 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003267 case Load:
3268 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3269 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 case Store: op = STORE_DEREF; break;
3271 case AugLoad:
3272 case AugStore:
3273 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003274 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 case Param:
3276 default:
3277 PyErr_SetString(PyExc_SystemError,
3278 "param invalid for deref variable");
3279 return 0;
3280 }
3281 break;
3282 case OP_FAST:
3283 switch (ctx) {
3284 case Load: op = LOAD_FAST; break;
3285 case Store: op = STORE_FAST; break;
3286 case Del: op = DELETE_FAST; break;
3287 case AugLoad:
3288 case AugStore:
3289 break;
3290 case Param:
3291 default:
3292 PyErr_SetString(PyExc_SystemError,
3293 "param invalid for local variable");
3294 return 0;
3295 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003296 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 return 1;
3298 case OP_GLOBAL:
3299 switch (ctx) {
3300 case Load: op = LOAD_GLOBAL; break;
3301 case Store: op = STORE_GLOBAL; break;
3302 case Del: op = DELETE_GLOBAL; break;
3303 case AugLoad:
3304 case AugStore:
3305 break;
3306 case Param:
3307 default:
3308 PyErr_SetString(PyExc_SystemError,
3309 "param invalid for global variable");
3310 return 0;
3311 }
3312 break;
3313 case OP_NAME:
3314 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003315 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 case Store: op = STORE_NAME; break;
3317 case Del: op = DELETE_NAME; break;
3318 case AugLoad:
3319 case AugStore:
3320 break;
3321 case Param:
3322 default:
3323 PyErr_SetString(PyExc_SystemError,
3324 "param invalid for name variable");
3325 return 0;
3326 }
3327 break;
3328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 assert(op);
3331 arg = compiler_add_o(c, dict, mangled);
3332 Py_DECREF(mangled);
3333 if (arg < 0)
3334 return 0;
3335 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336}
3337
3338static int
3339compiler_boolop(struct compiler *c, expr_ty e)
3340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003342 int jumpi;
3343 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 assert(e->kind == BoolOp_kind);
3347 if (e->v.BoolOp.op == And)
3348 jumpi = JUMP_IF_FALSE_OR_POP;
3349 else
3350 jumpi = JUMP_IF_TRUE_OR_POP;
3351 end = compiler_new_block(c);
3352 if (end == NULL)
3353 return 0;
3354 s = e->v.BoolOp.values;
3355 n = asdl_seq_LEN(s) - 1;
3356 assert(n >= 0);
3357 for (i = 0; i < n; ++i) {
3358 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3359 ADDOP_JABS(c, jumpi, end);
3360 }
3361 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3362 compiler_use_next_block(c, end);
3363 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364}
3365
3366static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003367starunpack_helper(struct compiler *c, asdl_seq *elts,
3368 int single_op, int inner_op, int outer_op)
3369{
3370 Py_ssize_t n = asdl_seq_LEN(elts);
3371 Py_ssize_t i, nsubitems = 0, nseen = 0;
3372 for (i = 0; i < n; i++) {
3373 expr_ty elt = asdl_seq_GET(elts, i);
3374 if (elt->kind == Starred_kind) {
3375 if (nseen) {
3376 ADDOP_I(c, inner_op, nseen);
3377 nseen = 0;
3378 nsubitems++;
3379 }
3380 VISIT(c, expr, elt->v.Starred.value);
3381 nsubitems++;
3382 }
3383 else {
3384 VISIT(c, expr, elt);
3385 nseen++;
3386 }
3387 }
3388 if (nsubitems) {
3389 if (nseen) {
3390 ADDOP_I(c, inner_op, nseen);
3391 nsubitems++;
3392 }
3393 ADDOP_I(c, outer_op, nsubitems);
3394 }
3395 else
3396 ADDOP_I(c, single_op, nseen);
3397 return 1;
3398}
3399
3400static int
3401assignment_helper(struct compiler *c, asdl_seq *elts)
3402{
3403 Py_ssize_t n = asdl_seq_LEN(elts);
3404 Py_ssize_t i;
3405 int seen_star = 0;
3406 for (i = 0; i < n; i++) {
3407 expr_ty elt = asdl_seq_GET(elts, i);
3408 if (elt->kind == Starred_kind && !seen_star) {
3409 if ((i >= (1 << 8)) ||
3410 (n-i-1 >= (INT_MAX >> 8)))
3411 return compiler_error(c,
3412 "too many expressions in "
3413 "star-unpacking assignment");
3414 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3415 seen_star = 1;
3416 asdl_seq_SET(elts, i, elt->v.Starred.value);
3417 }
3418 else if (elt->kind == Starred_kind) {
3419 return compiler_error(c,
3420 "two starred expressions in assignment");
3421 }
3422 }
3423 if (!seen_star) {
3424 ADDOP_I(c, UNPACK_SEQUENCE, n);
3425 }
3426 VISIT_SEQ(c, expr, elts);
3427 return 1;
3428}
3429
3430static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431compiler_list(struct compiler *c, expr_ty e)
3432{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003433 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003435 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003437 else if (e->v.List.ctx == Load) {
3438 return starunpack_helper(c, elts,
3439 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003441 else
3442 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444}
3445
3446static int
3447compiler_tuple(struct compiler *c, expr_ty e)
3448{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003449 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003451 return assignment_helper(c, elts);
3452 }
3453 else if (e->v.Tuple.ctx == Load) {
3454 return starunpack_helper(c, elts,
3455 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3456 }
3457 else
3458 VISIT_SEQ(c, expr, elts);
3459 return 1;
3460}
3461
3462static int
3463compiler_set(struct compiler *c, expr_ty e)
3464{
3465 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3466 BUILD_SET, BUILD_SET_UNPACK);
3467}
3468
3469static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003470are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3471{
3472 Py_ssize_t i;
3473 for (i = begin; i < end; i++) {
3474 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3475 if (key == NULL || !is_const(key))
3476 return 0;
3477 }
3478 return 1;
3479}
3480
3481static int
3482compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3483{
3484 Py_ssize_t i, n = end - begin;
3485 PyObject *keys, *key;
3486 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3487 for (i = begin; i < end; i++) {
3488 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3489 }
3490 keys = PyTuple_New(n);
3491 if (keys == NULL) {
3492 return 0;
3493 }
3494 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003495 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003496 Py_INCREF(key);
3497 PyTuple_SET_ITEM(keys, i - begin, key);
3498 }
3499 ADDOP_N(c, LOAD_CONST, keys, consts);
3500 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3501 }
3502 else {
3503 for (i = begin; i < end; i++) {
3504 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3505 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3506 }
3507 ADDOP_I(c, BUILD_MAP, n);
3508 }
3509 return 1;
3510}
3511
3512static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003513compiler_dict(struct compiler *c, expr_ty e)
3514{
Victor Stinner976bb402016-03-23 11:36:19 +01003515 Py_ssize_t i, n, elements;
3516 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003517 int is_unpacking = 0;
3518 n = asdl_seq_LEN(e->v.Dict.values);
3519 containers = 0;
3520 elements = 0;
3521 for (i = 0; i < n; i++) {
3522 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3523 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003524 if (!compiler_subdict(c, e, i - elements, i))
3525 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003526 containers++;
3527 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003529 if (is_unpacking) {
3530 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3531 containers++;
3532 }
3533 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003534 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 }
3536 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003538 if (!compiler_subdict(c, e, n - elements, n))
3539 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003540 containers++;
3541 }
3542 /* If there is more than one dict, they need to be merged into a new
3543 * dict. If there is one dict and it's an unpacking, then it needs
3544 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003545 if (containers > 1 || is_unpacking) {
3546 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 }
3548 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549}
3550
3551static int
3552compiler_compare(struct compiler *c, expr_ty e)
3553{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003554 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003557 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3558 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3559 if (n == 0) {
3560 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3561 ADDOP_I(c, COMPARE_OP,
3562 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3563 }
3564 else {
3565 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 if (cleanup == NULL)
3567 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003568 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 VISIT(c, expr,
3570 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003571 ADDOP(c, DUP_TOP);
3572 ADDOP(c, ROT_THREE);
3573 ADDOP_I(c, COMPARE_OP,
3574 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3575 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3576 NEXT_BLOCK(c);
3577 }
3578 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3579 ADDOP_I(c, COMPARE_OP,
3580 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 basicblock *end = compiler_new_block(c);
3582 if (end == NULL)
3583 return 0;
3584 ADDOP_JREL(c, JUMP_FORWARD, end);
3585 compiler_use_next_block(c, cleanup);
3586 ADDOP(c, ROT_TWO);
3587 ADDOP(c, POP_TOP);
3588 compiler_use_next_block(c, end);
3589 }
3590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591}
3592
3593static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003594maybe_optimize_method_call(struct compiler *c, expr_ty e)
3595{
3596 Py_ssize_t argsl, i;
3597 expr_ty meth = e->v.Call.func;
3598 asdl_seq *args = e->v.Call.args;
3599
3600 /* Check that the call node is an attribute access, and that
3601 the call doesn't have keyword parameters. */
3602 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3603 asdl_seq_LEN(e->v.Call.keywords))
3604 return -1;
3605
3606 /* Check that there are no *varargs types of arguments. */
3607 argsl = asdl_seq_LEN(args);
3608 for (i = 0; i < argsl; i++) {
3609 expr_ty elt = asdl_seq_GET(args, i);
3610 if (elt->kind == Starred_kind) {
3611 return -1;
3612 }
3613 }
3614
3615 /* Alright, we can optimize the code. */
3616 VISIT(c, expr, meth->v.Attribute.value);
3617 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3618 VISIT_SEQ(c, expr, e->v.Call.args);
3619 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3620 return 1;
3621}
3622
3623static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624compiler_call(struct compiler *c, expr_ty e)
3625{
Yury Selivanovf2392132016-12-13 19:03:51 -05003626 if (maybe_optimize_method_call(c, e) > 0)
3627 return 1;
3628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 VISIT(c, expr, e->v.Call.func);
3630 return compiler_call_helper(c, 0,
3631 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003632 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003633}
3634
Eric V. Smith235a6f02015-09-19 14:51:32 -04003635static int
3636compiler_joined_str(struct compiler *c, expr_ty e)
3637{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003638 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003639 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3640 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003641 return 1;
3642}
3643
Eric V. Smitha78c7952015-11-03 12:45:05 -05003644/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003645static int
3646compiler_formatted_value(struct compiler *c, expr_ty e)
3647{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003648 /* Our oparg encodes 2 pieces of information: the conversion
3649 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003650
Eric V. Smitha78c7952015-11-03 12:45:05 -05003651 Convert the conversion char to 2 bits:
3652 None: 000 0x0 FVC_NONE
3653 !s : 001 0x1 FVC_STR
3654 !r : 010 0x2 FVC_REPR
3655 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003656
Eric V. Smitha78c7952015-11-03 12:45:05 -05003657 next bit is whether or not we have a format spec:
3658 yes : 100 0x4
3659 no : 000 0x0
3660 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003661
Eric V. Smitha78c7952015-11-03 12:45:05 -05003662 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003663
Eric V. Smitha78c7952015-11-03 12:45:05 -05003664 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003665 VISIT(c, expr, e->v.FormattedValue.value);
3666
Eric V. Smitha78c7952015-11-03 12:45:05 -05003667 switch (e->v.FormattedValue.conversion) {
3668 case 's': oparg = FVC_STR; break;
3669 case 'r': oparg = FVC_REPR; break;
3670 case 'a': oparg = FVC_ASCII; break;
3671 case -1: oparg = FVC_NONE; break;
3672 default:
3673 PyErr_SetString(PyExc_SystemError,
3674 "Unrecognized conversion character");
3675 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003676 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003677 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003678 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003679 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003680 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003681 }
3682
Eric V. Smitha78c7952015-11-03 12:45:05 -05003683 /* And push our opcode and oparg */
3684 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003685 return 1;
3686}
3687
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003688static int
3689compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3690{
3691 Py_ssize_t i, n = end - begin;
3692 keyword_ty kw;
3693 PyObject *keys, *key;
3694 assert(n > 0);
3695 if (n > 1) {
3696 for (i = begin; i < end; i++) {
3697 kw = asdl_seq_GET(keywords, i);
3698 VISIT(c, expr, kw->value);
3699 }
3700 keys = PyTuple_New(n);
3701 if (keys == NULL) {
3702 return 0;
3703 }
3704 for (i = begin; i < end; i++) {
3705 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3706 Py_INCREF(key);
3707 PyTuple_SET_ITEM(keys, i - begin, key);
3708 }
3709 ADDOP_N(c, LOAD_CONST, keys, consts);
3710 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3711 }
3712 else {
3713 /* a for loop only executes once */
3714 for (i = begin; i < end; i++) {
3715 kw = asdl_seq_GET(keywords, i);
3716 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3717 VISIT(c, expr, kw->value);
3718 }
3719 ADDOP_I(c, BUILD_MAP, n);
3720 }
3721 return 1;
3722}
3723
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003724/* shared code between compiler_call and compiler_class */
3725static int
3726compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003727 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003728 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003730{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003731 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003732 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003733
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734 /* the number of tuples and dictionaries on the stack */
3735 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3736
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003738 nkwelts = asdl_seq_LEN(keywords);
3739
3740 for (i = 0; i < nkwelts; i++) {
3741 keyword_ty kw = asdl_seq_GET(keywords, i);
3742 if (kw->arg == NULL) {
3743 mustdictunpack = 1;
3744 break;
3745 }
3746 }
3747
3748 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 for (i = 0; i < nelts; i++) {
3750 expr_ty elt = asdl_seq_GET(args, i);
3751 if (elt->kind == Starred_kind) {
3752 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003753 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003754 if (nseen) {
3755 ADDOP_I(c, BUILD_TUPLE, nseen);
3756 nseen = 0;
3757 nsubargs++;
3758 }
3759 VISIT(c, expr, elt->v.Starred.value);
3760 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003761 }
3762 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003764 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003767
3768 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003769 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003770 if (nseen) {
3771 /* Pack up any trailing positional arguments. */
3772 ADDOP_I(c, BUILD_TUPLE, nseen);
3773 nsubargs++;
3774 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003775 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003776 /* If we ended up with more than one stararg, we need
3777 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003778 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003779 }
3780 else if (nsubargs == 0) {
3781 ADDOP_I(c, BUILD_TUPLE, 0);
3782 }
3783 nseen = 0; /* the number of keyword arguments on the stack following */
3784 for (i = 0; i < nkwelts; i++) {
3785 keyword_ty kw = asdl_seq_GET(keywords, i);
3786 if (kw->arg == NULL) {
3787 /* A keyword argument unpacking. */
3788 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003789 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3790 return 0;
3791 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003792 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003793 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003794 VISIT(c, expr, kw->value);
3795 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003796 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003797 else {
3798 nseen++;
3799 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003800 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003801 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003802 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003803 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003804 return 0;
3805 nsubkwargs++;
3806 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003807 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003808 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003809 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003811 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3812 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003814 else if (nkwelts) {
3815 PyObject *names;
3816 VISIT_SEQ(c, keyword, keywords);
3817 names = PyTuple_New(nkwelts);
3818 if (names == NULL) {
3819 return 0;
3820 }
3821 for (i = 0; i < nkwelts; i++) {
3822 keyword_ty kw = asdl_seq_GET(keywords, i);
3823 Py_INCREF(kw->arg);
3824 PyTuple_SET_ITEM(names, i, kw->arg);
3825 }
3826 ADDOP_N(c, LOAD_CONST, names, consts);
3827 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3828 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003830 else {
3831 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3832 return 1;
3833 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003834}
3835
Nick Coghlan650f0d02007-04-15 12:05:43 +00003836
3837/* List and set comprehensions and generator expressions work by creating a
3838 nested function to perform the actual iteration. This means that the
3839 iteration variables don't leak into the current scope.
3840 The defined function is called immediately following its definition, with the
3841 result of that call being the result of the expression.
3842 The LC/SC version returns the populated container, while the GE version is
3843 flagged in symtable.c as a generator, so it returns the generator object
3844 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003845
3846 Possible cleanups:
3847 - iterate over the generator sequence instead of using recursion
3848*/
3849
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852compiler_comprehension_generator(struct compiler *c,
3853 asdl_seq *generators, int gen_index,
3854 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003856 comprehension_ty gen;
3857 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3858 if (gen->is_async) {
3859 return compiler_async_comprehension_generator(
3860 c, generators, gen_index, elt, val, type);
3861 } else {
3862 return compiler_sync_comprehension_generator(
3863 c, generators, gen_index, elt, val, type);
3864 }
3865}
3866
3867static int
3868compiler_sync_comprehension_generator(struct compiler *c,
3869 asdl_seq *generators, int gen_index,
3870 expr_ty elt, expr_ty val, int type)
3871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 /* generate code for the iterator, then each of the ifs,
3873 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 comprehension_ty gen;
3876 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003877 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 start = compiler_new_block(c);
3880 skip = compiler_new_block(c);
3881 if_cleanup = compiler_new_block(c);
3882 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3885 anchor == NULL)
3886 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 if (gen_index == 0) {
3891 /* Receive outermost iter as an implicit argument */
3892 c->u->u_argcount = 1;
3893 ADDOP_I(c, LOAD_FAST, 0);
3894 }
3895 else {
3896 /* Sub-iter - calculate on the fly */
3897 VISIT(c, expr, gen->iter);
3898 ADDOP(c, GET_ITER);
3899 }
3900 compiler_use_next_block(c, start);
3901 ADDOP_JREL(c, FOR_ITER, anchor);
3902 NEXT_BLOCK(c);
3903 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 /* XXX this needs to be cleaned up...a lot! */
3906 n = asdl_seq_LEN(gen->ifs);
3907 for (i = 0; i < n; i++) {
3908 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003909 if (!compiler_jump_if(c, e, if_cleanup, 0))
3910 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 NEXT_BLOCK(c);
3912 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 if (++gen_index < asdl_seq_LEN(generators))
3915 if (!compiler_comprehension_generator(c,
3916 generators, gen_index,
3917 elt, val, type))
3918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 /* only append after the last for generator */
3921 if (gen_index >= asdl_seq_LEN(generators)) {
3922 /* comprehension specific code */
3923 switch (type) {
3924 case COMP_GENEXP:
3925 VISIT(c, expr, elt);
3926 ADDOP(c, YIELD_VALUE);
3927 ADDOP(c, POP_TOP);
3928 break;
3929 case COMP_LISTCOMP:
3930 VISIT(c, expr, elt);
3931 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3932 break;
3933 case COMP_SETCOMP:
3934 VISIT(c, expr, elt);
3935 ADDOP_I(c, SET_ADD, gen_index + 1);
3936 break;
3937 case COMP_DICTCOMP:
3938 /* With 'd[k] = v', v is evaluated before k, so we do
3939 the same. */
3940 VISIT(c, expr, val);
3941 VISIT(c, expr, elt);
3942 ADDOP_I(c, MAP_ADD, gen_index + 1);
3943 break;
3944 default:
3945 return 0;
3946 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 compiler_use_next_block(c, skip);
3949 }
3950 compiler_use_next_block(c, if_cleanup);
3951 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3952 compiler_use_next_block(c, anchor);
3953
3954 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955}
3956
3957static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003958compiler_async_comprehension_generator(struct compiler *c,
3959 asdl_seq *generators, int gen_index,
3960 expr_ty elt, expr_ty val, int type)
3961{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003962 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003963 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003964 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003965 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003967 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003969 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003970 return 0;
3971 }
3972
3973 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3974
3975 if (gen_index == 0) {
3976 /* Receive outermost iter as an implicit argument */
3977 c->u->u_argcount = 1;
3978 ADDOP_I(c, LOAD_FAST, 0);
3979 }
3980 else {
3981 /* Sub-iter - calculate on the fly */
3982 VISIT(c, expr, gen->iter);
3983 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003984 }
3985
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003986 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003987
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003988 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003989 ADDOP(c, GET_ANEXT);
3990 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3991 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003992 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02003993 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003994
3995 n = asdl_seq_LEN(gen->ifs);
3996 for (i = 0; i < n; i++) {
3997 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003998 if (!compiler_jump_if(c, e, if_cleanup, 0))
3999 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004000 NEXT_BLOCK(c);
4001 }
4002
4003 if (++gen_index < asdl_seq_LEN(generators))
4004 if (!compiler_comprehension_generator(c,
4005 generators, gen_index,
4006 elt, val, type))
4007 return 0;
4008
4009 /* only append after the last for generator */
4010 if (gen_index >= asdl_seq_LEN(generators)) {
4011 /* comprehension specific code */
4012 switch (type) {
4013 case COMP_GENEXP:
4014 VISIT(c, expr, elt);
4015 ADDOP(c, YIELD_VALUE);
4016 ADDOP(c, POP_TOP);
4017 break;
4018 case COMP_LISTCOMP:
4019 VISIT(c, expr, elt);
4020 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4021 break;
4022 case COMP_SETCOMP:
4023 VISIT(c, expr, elt);
4024 ADDOP_I(c, SET_ADD, gen_index + 1);
4025 break;
4026 case COMP_DICTCOMP:
4027 /* With 'd[k] = v', v is evaluated before k, so we do
4028 the same. */
4029 VISIT(c, expr, val);
4030 VISIT(c, expr, elt);
4031 ADDOP_I(c, MAP_ADD, gen_index + 1);
4032 break;
4033 default:
4034 return 0;
4035 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004036 }
4037 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004038 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4039
4040 compiler_use_next_block(c, except);
4041 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004042
4043 return 1;
4044}
4045
4046static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004047compiler_comprehension(struct compiler *c, expr_ty e, int type,
4048 identifier name, asdl_seq *generators, expr_ty elt,
4049 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004052 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004053 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004054 int is_async_function = c->u->u_ste->ste_coroutine;
4055 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004056
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004057 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004058
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004059 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4060 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004061 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004063 }
4064
4065 is_async_generator = c->u->u_ste->ste_coroutine;
4066
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004067 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004068 if (e->lineno > c->u->u_lineno) {
4069 c->u->u_lineno = e->lineno;
4070 c->u->u_lineno_set = 0;
4071 }
4072 compiler_error(c, "asynchronous comprehension outside of "
4073 "an asynchronous function");
4074 goto error_in_scope;
4075 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 if (type != COMP_GENEXP) {
4078 int op;
4079 switch (type) {
4080 case COMP_LISTCOMP:
4081 op = BUILD_LIST;
4082 break;
4083 case COMP_SETCOMP:
4084 op = BUILD_SET;
4085 break;
4086 case COMP_DICTCOMP:
4087 op = BUILD_MAP;
4088 break;
4089 default:
4090 PyErr_Format(PyExc_SystemError,
4091 "unknown comprehension type %d", type);
4092 goto error_in_scope;
4093 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 ADDOP_I(c, op, 0);
4096 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 if (!compiler_comprehension_generator(c, generators, 0, elt,
4099 val, type))
4100 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 if (type != COMP_GENEXP) {
4103 ADDOP(c, RETURN_VALUE);
4104 }
4105
4106 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004107 qualname = c->u->u_qualname;
4108 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004110 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 goto error;
4112
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004113 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004115 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 Py_DECREF(co);
4117
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004118 VISIT(c, expr, outermost->iter);
4119
4120 if (outermost->is_async) {
4121 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004122 } else {
4123 ADDOP(c, GET_ITER);
4124 }
4125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004127
4128 if (is_async_generator && type != COMP_GENEXP) {
4129 ADDOP(c, GET_AWAITABLE);
4130 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4131 ADDOP(c, YIELD_FROM);
4132 }
4133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004135error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004137error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004138 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 Py_XDECREF(co);
4140 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004141}
4142
4143static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144compiler_genexp(struct compiler *c, expr_ty e)
4145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 static identifier name;
4147 if (!name) {
4148 name = PyUnicode_FromString("<genexpr>");
4149 if (!name)
4150 return 0;
4151 }
4152 assert(e->kind == GeneratorExp_kind);
4153 return compiler_comprehension(c, e, COMP_GENEXP, name,
4154 e->v.GeneratorExp.generators,
4155 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004156}
4157
4158static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004159compiler_listcomp(struct compiler *c, expr_ty e)
4160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 static identifier name;
4162 if (!name) {
4163 name = PyUnicode_FromString("<listcomp>");
4164 if (!name)
4165 return 0;
4166 }
4167 assert(e->kind == ListComp_kind);
4168 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4169 e->v.ListComp.generators,
4170 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004171}
4172
4173static int
4174compiler_setcomp(struct compiler *c, expr_ty e)
4175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 static identifier name;
4177 if (!name) {
4178 name = PyUnicode_FromString("<setcomp>");
4179 if (!name)
4180 return 0;
4181 }
4182 assert(e->kind == SetComp_kind);
4183 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4184 e->v.SetComp.generators,
4185 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004186}
4187
4188
4189static int
4190compiler_dictcomp(struct compiler *c, expr_ty e)
4191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 static identifier name;
4193 if (!name) {
4194 name = PyUnicode_FromString("<dictcomp>");
4195 if (!name)
4196 return 0;
4197 }
4198 assert(e->kind == DictComp_kind);
4199 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4200 e->v.DictComp.generators,
4201 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004202}
4203
4204
4205static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206compiler_visit_keyword(struct compiler *c, keyword_ty k)
4207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 VISIT(c, expr, k->value);
4209 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004210}
4211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213 whether they are true or false.
4214
4215 Return values: 1 for true, 0 for false, -1 for non-constant.
4216 */
4217
4218static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004219expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004221 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004222 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004223 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004224 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004225}
4226
Yury Selivanov75445082015-05-11 22:57:16 -04004227
4228/*
4229 Implements the async with statement.
4230
4231 The semantics outlined in that PEP are as follows:
4232
4233 async with EXPR as VAR:
4234 BLOCK
4235
4236 It is implemented roughly as:
4237
4238 context = EXPR
4239 exit = context.__aexit__ # not calling it
4240 value = await context.__aenter__()
4241 try:
4242 VAR = value # if VAR present in the syntax
4243 BLOCK
4244 finally:
4245 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004246 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004247 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004248 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004249 if not (await exit(*exc)):
4250 raise
4251 */
4252static int
4253compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4254{
4255 basicblock *block, *finally;
4256 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4257
4258 assert(s->kind == AsyncWith_kind);
4259
4260 block = compiler_new_block(c);
4261 finally = compiler_new_block(c);
4262 if (!block || !finally)
4263 return 0;
4264
4265 /* Evaluate EXPR */
4266 VISIT(c, expr, item->context_expr);
4267
4268 ADDOP(c, BEFORE_ASYNC_WITH);
4269 ADDOP(c, GET_AWAITABLE);
4270 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4271 ADDOP(c, YIELD_FROM);
4272
4273 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4274
4275 /* SETUP_ASYNC_WITH pushes a finally block. */
4276 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004277 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004278 return 0;
4279 }
4280
4281 if (item->optional_vars) {
4282 VISIT(c, expr, item->optional_vars);
4283 }
4284 else {
4285 /* Discard result from context.__aenter__() */
4286 ADDOP(c, POP_TOP);
4287 }
4288
4289 pos++;
4290 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4291 /* BLOCK code */
4292 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4293 else if (!compiler_async_with(c, s, pos))
4294 return 0;
4295
4296 /* End of try block; start the finally block */
4297 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004298 ADDOP(c, BEGIN_FINALLY);
4299 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004300
Yury Selivanov75445082015-05-11 22:57:16 -04004301 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004302 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004303 return 0;
4304
4305 /* Finally block starts; context.__exit__ is on the stack under
4306 the exception or return information. Just issue our magic
4307 opcode. */
4308 ADDOP(c, WITH_CLEANUP_START);
4309
4310 ADDOP(c, GET_AWAITABLE);
4311 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4312 ADDOP(c, YIELD_FROM);
4313
4314 ADDOP(c, WITH_CLEANUP_FINISH);
4315
4316 /* Finally block ends. */
4317 ADDOP(c, END_FINALLY);
4318 compiler_pop_fblock(c, FINALLY_END, finally);
4319 return 1;
4320}
4321
4322
Guido van Rossumc2e20742006-02-27 22:32:47 +00004323/*
4324 Implements the with statement from PEP 343.
4325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004327
4328 with EXPR as VAR:
4329 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330
Guido van Rossumc2e20742006-02-27 22:32:47 +00004331 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332
Thomas Wouters477c8d52006-05-27 19:21:47 +00004333 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004334 exit = context.__exit__ # not calling it
4335 value = context.__enter__()
4336 try:
4337 VAR = value # if VAR present in the syntax
4338 BLOCK
4339 finally:
4340 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004341 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004342 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004343 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004344 exit(*exc)
4345 */
4346static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004347compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004348{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004349 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004350 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004351
4352 assert(s->kind == With_kind);
4353
Guido van Rossumc2e20742006-02-27 22:32:47 +00004354 block = compiler_new_block(c);
4355 finally = compiler_new_block(c);
4356 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004357 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004358
Thomas Wouters477c8d52006-05-27 19:21:47 +00004359 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004360 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004361 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004362
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004363 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004364 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004365 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004366 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004367 }
4368
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004369 if (item->optional_vars) {
4370 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004371 }
4372 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004374 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004375 }
4376
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004377 pos++;
4378 if (pos == asdl_seq_LEN(s->v.With.items))
4379 /* BLOCK code */
4380 VISIT_SEQ(c, stmt, s->v.With.body)
4381 else if (!compiler_with(c, s, pos))
4382 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004383
4384 /* End of try block; start the finally block */
4385 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004386 ADDOP(c, BEGIN_FINALLY);
4387 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004388
Guido van Rossumc2e20742006-02-27 22:32:47 +00004389 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004390 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004391 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004392
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004393 /* Finally block starts; context.__exit__ is on the stack under
4394 the exception or return information. Just issue our magic
4395 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004396 ADDOP(c, WITH_CLEANUP_START);
4397 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004398
4399 /* Finally block ends. */
4400 ADDOP(c, END_FINALLY);
4401 compiler_pop_fblock(c, FINALLY_END, finally);
4402 return 1;
4403}
4404
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405static int
4406compiler_visit_expr(struct compiler *c, expr_ty e)
4407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 /* If expr e has a different line number than the last expr/stmt,
4409 set a new line number for the next instruction.
4410 */
4411 if (e->lineno > c->u->u_lineno) {
4412 c->u->u_lineno = e->lineno;
4413 c->u->u_lineno_set = 0;
4414 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004415 /* Updating the column offset is always harmless. */
4416 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 switch (e->kind) {
4418 case BoolOp_kind:
4419 return compiler_boolop(c, e);
4420 case BinOp_kind:
4421 VISIT(c, expr, e->v.BinOp.left);
4422 VISIT(c, expr, e->v.BinOp.right);
4423 ADDOP(c, binop(c, e->v.BinOp.op));
4424 break;
4425 case UnaryOp_kind:
4426 VISIT(c, expr, e->v.UnaryOp.operand);
4427 ADDOP(c, unaryop(e->v.UnaryOp.op));
4428 break;
4429 case Lambda_kind:
4430 return compiler_lambda(c, e);
4431 case IfExp_kind:
4432 return compiler_ifexp(c, e);
4433 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004434 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004436 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 case GeneratorExp_kind:
4438 return compiler_genexp(c, e);
4439 case ListComp_kind:
4440 return compiler_listcomp(c, e);
4441 case SetComp_kind:
4442 return compiler_setcomp(c, e);
4443 case DictComp_kind:
4444 return compiler_dictcomp(c, e);
4445 case Yield_kind:
4446 if (c->u->u_ste->ste_type != FunctionBlock)
4447 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004448 if (e->v.Yield.value) {
4449 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 }
4451 else {
4452 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4453 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004454 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004456 case YieldFrom_kind:
4457 if (c->u->u_ste->ste_type != FunctionBlock)
4458 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004459
4460 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4461 return compiler_error(c, "'yield from' inside async function");
4462
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004463 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004464 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004465 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4466 ADDOP(c, YIELD_FROM);
4467 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004468 case Await_kind:
4469 if (c->u->u_ste->ste_type != FunctionBlock)
4470 return compiler_error(c, "'await' outside function");
4471
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004472 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4473 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004474 return compiler_error(c, "'await' outside async function");
4475
4476 VISIT(c, expr, e->v.Await.value);
4477 ADDOP(c, GET_AWAITABLE);
4478 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4479 ADDOP(c, YIELD_FROM);
4480 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 case Compare_kind:
4482 return compiler_compare(c, e);
4483 case Call_kind:
4484 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004485 case Constant_kind:
4486 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4487 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488 case Num_kind:
4489 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4490 break;
4491 case Str_kind:
4492 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4493 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004494 case JoinedStr_kind:
4495 return compiler_joined_str(c, e);
4496 case FormattedValue_kind:
4497 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 case Bytes_kind:
4499 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4500 break;
4501 case Ellipsis_kind:
4502 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4503 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004504 case NameConstant_kind:
4505 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4506 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 /* The following exprs can be assignment targets. */
4508 case Attribute_kind:
4509 if (e->v.Attribute.ctx != AugStore)
4510 VISIT(c, expr, e->v.Attribute.value);
4511 switch (e->v.Attribute.ctx) {
4512 case AugLoad:
4513 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004514 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 case Load:
4516 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4517 break;
4518 case AugStore:
4519 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004520 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 case Store:
4522 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4523 break;
4524 case Del:
4525 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4526 break;
4527 case Param:
4528 default:
4529 PyErr_SetString(PyExc_SystemError,
4530 "param invalid in attribute expression");
4531 return 0;
4532 }
4533 break;
4534 case Subscript_kind:
4535 switch (e->v.Subscript.ctx) {
4536 case AugLoad:
4537 VISIT(c, expr, e->v.Subscript.value);
4538 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4539 break;
4540 case Load:
4541 VISIT(c, expr, e->v.Subscript.value);
4542 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4543 break;
4544 case AugStore:
4545 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4546 break;
4547 case Store:
4548 VISIT(c, expr, e->v.Subscript.value);
4549 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4550 break;
4551 case Del:
4552 VISIT(c, expr, e->v.Subscript.value);
4553 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4554 break;
4555 case Param:
4556 default:
4557 PyErr_SetString(PyExc_SystemError,
4558 "param invalid in subscript expression");
4559 return 0;
4560 }
4561 break;
4562 case Starred_kind:
4563 switch (e->v.Starred.ctx) {
4564 case Store:
4565 /* In all legitimate cases, the Starred node was already replaced
4566 * by compiler_list/compiler_tuple. XXX: is that okay? */
4567 return compiler_error(c,
4568 "starred assignment target must be in a list or tuple");
4569 default:
4570 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004571 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 }
4573 break;
4574 case Name_kind:
4575 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4576 /* child nodes of List and Tuple will have expr_context set */
4577 case List_kind:
4578 return compiler_list(c, e);
4579 case Tuple_kind:
4580 return compiler_tuple(c, e);
4581 }
4582 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004583}
4584
4585static int
4586compiler_augassign(struct compiler *c, stmt_ty s)
4587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 expr_ty e = s->v.AugAssign.target;
4589 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 switch (e->kind) {
4594 case Attribute_kind:
4595 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4596 AugLoad, e->lineno, e->col_offset, c->c_arena);
4597 if (auge == NULL)
4598 return 0;
4599 VISIT(c, expr, auge);
4600 VISIT(c, expr, s->v.AugAssign.value);
4601 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4602 auge->v.Attribute.ctx = AugStore;
4603 VISIT(c, expr, auge);
4604 break;
4605 case Subscript_kind:
4606 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4607 AugLoad, e->lineno, e->col_offset, c->c_arena);
4608 if (auge == NULL)
4609 return 0;
4610 VISIT(c, expr, auge);
4611 VISIT(c, expr, s->v.AugAssign.value);
4612 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4613 auge->v.Subscript.ctx = AugStore;
4614 VISIT(c, expr, auge);
4615 break;
4616 case Name_kind:
4617 if (!compiler_nameop(c, e->v.Name.id, Load))
4618 return 0;
4619 VISIT(c, expr, s->v.AugAssign.value);
4620 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4621 return compiler_nameop(c, e->v.Name.id, Store);
4622 default:
4623 PyErr_Format(PyExc_SystemError,
4624 "invalid node type (%d) for augmented assignment",
4625 e->kind);
4626 return 0;
4627 }
4628 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004629}
4630
4631static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004632check_ann_expr(struct compiler *c, expr_ty e)
4633{
4634 VISIT(c, expr, e);
4635 ADDOP(c, POP_TOP);
4636 return 1;
4637}
4638
4639static int
4640check_annotation(struct compiler *c, stmt_ty s)
4641{
4642 /* Annotations are only evaluated in a module or class. */
4643 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4644 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4645 return check_ann_expr(c, s->v.AnnAssign.annotation);
4646 }
4647 return 1;
4648}
4649
4650static int
4651check_ann_slice(struct compiler *c, slice_ty sl)
4652{
4653 switch(sl->kind) {
4654 case Index_kind:
4655 return check_ann_expr(c, sl->v.Index.value);
4656 case Slice_kind:
4657 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4658 return 0;
4659 }
4660 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4661 return 0;
4662 }
4663 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4664 return 0;
4665 }
4666 break;
4667 default:
4668 PyErr_SetString(PyExc_SystemError,
4669 "unexpected slice kind");
4670 return 0;
4671 }
4672 return 1;
4673}
4674
4675static int
4676check_ann_subscr(struct compiler *c, slice_ty sl)
4677{
4678 /* We check that everything in a subscript is defined at runtime. */
4679 Py_ssize_t i, n;
4680
4681 switch (sl->kind) {
4682 case Index_kind:
4683 case Slice_kind:
4684 if (!check_ann_slice(c, sl)) {
4685 return 0;
4686 }
4687 break;
4688 case ExtSlice_kind:
4689 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4690 for (i = 0; i < n; i++) {
4691 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4692 switch (subsl->kind) {
4693 case Index_kind:
4694 case Slice_kind:
4695 if (!check_ann_slice(c, subsl)) {
4696 return 0;
4697 }
4698 break;
4699 case ExtSlice_kind:
4700 default:
4701 PyErr_SetString(PyExc_SystemError,
4702 "extended slice invalid in nested slice");
4703 return 0;
4704 }
4705 }
4706 break;
4707 default:
4708 PyErr_Format(PyExc_SystemError,
4709 "invalid subscript kind %d", sl->kind);
4710 return 0;
4711 }
4712 return 1;
4713}
4714
4715static int
4716compiler_annassign(struct compiler *c, stmt_ty s)
4717{
4718 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004719 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004720
4721 assert(s->kind == AnnAssign_kind);
4722
4723 /* We perform the actual assignment first. */
4724 if (s->v.AnnAssign.value) {
4725 VISIT(c, expr, s->v.AnnAssign.value);
4726 VISIT(c, expr, targ);
4727 }
4728 switch (targ->kind) {
4729 case Name_kind:
4730 /* If we have a simple name in a module or class, store annotation. */
4731 if (s->v.AnnAssign.simple &&
4732 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4733 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004734 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4735 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4736 }
4737 else {
4738 VISIT(c, expr, s->v.AnnAssign.annotation);
4739 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004740 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004741 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4742 if (!mangled) {
4743 return 0;
4744 }
4745 ADDOP_N(c, LOAD_CONST, mangled, consts);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004746 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004747 }
4748 break;
4749 case Attribute_kind:
4750 if (!s->v.AnnAssign.value &&
4751 !check_ann_expr(c, targ->v.Attribute.value)) {
4752 return 0;
4753 }
4754 break;
4755 case Subscript_kind:
4756 if (!s->v.AnnAssign.value &&
4757 (!check_ann_expr(c, targ->v.Subscript.value) ||
4758 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4759 return 0;
4760 }
4761 break;
4762 default:
4763 PyErr_Format(PyExc_SystemError,
4764 "invalid node type (%d) for annotated assignment",
4765 targ->kind);
4766 return 0;
4767 }
4768 /* Annotation is evaluated last. */
4769 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4770 return 0;
4771 }
4772 return 1;
4773}
4774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004775/* Raises a SyntaxError and returns 0.
4776 If something goes wrong, a different exception may be raised.
4777*/
4778
4779static int
4780compiler_error(struct compiler *c, const char *errstr)
4781{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004782 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004784
Victor Stinner14e461d2013-08-26 22:28:21 +02004785 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 if (!loc) {
4787 Py_INCREF(Py_None);
4788 loc = Py_None;
4789 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004790 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004791 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 if (!u)
4793 goto exit;
4794 v = Py_BuildValue("(zO)", errstr, u);
4795 if (!v)
4796 goto exit;
4797 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004798 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 Py_DECREF(loc);
4800 Py_XDECREF(u);
4801 Py_XDECREF(v);
4802 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004803}
4804
4805static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806compiler_handle_subscr(struct compiler *c, const char *kind,
4807 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 /* XXX this code is duplicated */
4812 switch (ctx) {
4813 case AugLoad: /* fall through to Load */
4814 case Load: op = BINARY_SUBSCR; break;
4815 case AugStore:/* fall through to Store */
4816 case Store: op = STORE_SUBSCR; break;
4817 case Del: op = DELETE_SUBSCR; break;
4818 case Param:
4819 PyErr_Format(PyExc_SystemError,
4820 "invalid %s kind %d in subscript\n",
4821 kind, ctx);
4822 return 0;
4823 }
4824 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004825 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 }
4827 else if (ctx == AugStore) {
4828 ADDOP(c, ROT_THREE);
4829 }
4830 ADDOP(c, op);
4831 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004832}
4833
4834static int
4835compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 int n = 2;
4838 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 /* only handles the cases where BUILD_SLICE is emitted */
4841 if (s->v.Slice.lower) {
4842 VISIT(c, expr, s->v.Slice.lower);
4843 }
4844 else {
4845 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4846 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 if (s->v.Slice.upper) {
4849 VISIT(c, expr, s->v.Slice.upper);
4850 }
4851 else {
4852 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4853 }
4854
4855 if (s->v.Slice.step) {
4856 n++;
4857 VISIT(c, expr, s->v.Slice.step);
4858 }
4859 ADDOP_I(c, BUILD_SLICE, n);
4860 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004861}
4862
4863static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004864compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4865 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 switch (s->kind) {
4868 case Slice_kind:
4869 return compiler_slice(c, s, ctx);
4870 case Index_kind:
4871 VISIT(c, expr, s->v.Index.value);
4872 break;
4873 case ExtSlice_kind:
4874 default:
4875 PyErr_SetString(PyExc_SystemError,
4876 "extended slice invalid in nested slice");
4877 return 0;
4878 }
4879 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004880}
4881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004882static int
4883compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4884{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004885 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 switch (s->kind) {
4887 case Index_kind:
4888 kindname = "index";
4889 if (ctx != AugStore) {
4890 VISIT(c, expr, s->v.Index.value);
4891 }
4892 break;
4893 case Slice_kind:
4894 kindname = "slice";
4895 if (ctx != AugStore) {
4896 if (!compiler_slice(c, s, ctx))
4897 return 0;
4898 }
4899 break;
4900 case ExtSlice_kind:
4901 kindname = "extended slice";
4902 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004903 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 for (i = 0; i < n; i++) {
4905 slice_ty sub = (slice_ty)asdl_seq_GET(
4906 s->v.ExtSlice.dims, i);
4907 if (!compiler_visit_nested_slice(c, sub, ctx))
4908 return 0;
4909 }
4910 ADDOP_I(c, BUILD_TUPLE, n);
4911 }
4912 break;
4913 default:
4914 PyErr_Format(PyExc_SystemError,
4915 "invalid subscript kind %d", s->kind);
4916 return 0;
4917 }
4918 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004919}
4920
Thomas Wouters89f507f2006-12-13 04:49:30 +00004921/* End of the compiler section, beginning of the assembler section */
4922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004923/* do depth-first search of basic block graph, starting with block.
4924 post records the block indices in post-order.
4925
4926 XXX must handle implicit jumps from one block to next
4927*/
4928
Thomas Wouters89f507f2006-12-13 04:49:30 +00004929struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 PyObject *a_bytecode; /* string containing bytecode */
4931 int a_offset; /* offset into bytecode */
4932 int a_nblocks; /* number of reachable blocks */
4933 basicblock **a_postorder; /* list of blocks in dfs postorder */
4934 PyObject *a_lnotab; /* string containing lnotab */
4935 int a_lnotab_off; /* offset into lnotab */
4936 int a_lineno; /* last lineno of emitted instruction */
4937 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004938};
4939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004940static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004941dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004942{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004943 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004945 /* Get rid of recursion for normal control flow.
4946 Since the number of blocks is limited, unused space in a_postorder
4947 (from a_nblocks to end) can be used as a stack for still not ordered
4948 blocks. */
4949 for (j = end; b && !b->b_seen; b = b->b_next) {
4950 b->b_seen = 1;
4951 assert(a->a_nblocks < j);
4952 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004954 while (j < end) {
4955 b = a->a_postorder[j++];
4956 for (i = 0; i < b->b_iused; i++) {
4957 struct instr *instr = &b->b_instr[i];
4958 if (instr->i_jrel || instr->i_jabs)
4959 dfs(c, instr->i_target, a, j);
4960 }
4961 assert(a->a_nblocks < j);
4962 a->a_postorder[a->a_nblocks++] = b;
4963 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004964}
4965
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004966Py_LOCAL_INLINE(void)
4967stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004968{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004969 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004970 if (b->b_startdepth < depth) {
4971 assert(b->b_startdepth < 0);
4972 b->b_startdepth = depth;
4973 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004975}
4976
4977/* Find the flow path that needs the largest stack. We assume that
4978 * cycles in the flow graph have no net effect on the stack depth.
4979 */
4980static int
4981stackdepth(struct compiler *c)
4982{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004983 basicblock *b, *entryblock = NULL;
4984 basicblock **stack, **sp;
4985 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 b->b_startdepth = INT_MIN;
4988 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004989 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 }
4991 if (!entryblock)
4992 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004993 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
4994 if (!stack) {
4995 PyErr_NoMemory();
4996 return -1;
4997 }
4998
4999 sp = stack;
5000 stackdepth_push(&sp, entryblock, 0);
5001 while (sp != stack) {
5002 b = *--sp;
5003 int depth = b->b_startdepth;
5004 assert(depth >= 0);
5005 basicblock *next = b->b_next;
5006 for (int i = 0; i < b->b_iused; i++) {
5007 struct instr *instr = &b->b_instr[i];
5008 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5009 if (effect == PY_INVALID_STACK_EFFECT) {
5010 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5011 Py_FatalError("PyCompile_OpcodeStackEffect()");
5012 }
5013 int new_depth = depth + effect;
5014 if (new_depth > maxdepth) {
5015 maxdepth = new_depth;
5016 }
5017 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5018 if (instr->i_jrel || instr->i_jabs) {
5019 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5020 assert(effect != PY_INVALID_STACK_EFFECT);
5021 int target_depth = depth + effect;
5022 if (target_depth > maxdepth) {
5023 maxdepth = target_depth;
5024 }
5025 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005026 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005027 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005028 assert(instr->i_target->b_startdepth >= target_depth);
5029 depth = new_depth;
5030 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005031 }
5032 stackdepth_push(&sp, instr->i_target, target_depth);
5033 }
5034 depth = new_depth;
5035 if (instr->i_opcode == JUMP_ABSOLUTE ||
5036 instr->i_opcode == JUMP_FORWARD ||
5037 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005038 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005039 {
5040 /* remaining code is dead */
5041 next = NULL;
5042 break;
5043 }
5044 }
5045 if (next != NULL) {
5046 stackdepth_push(&sp, next, depth);
5047 }
5048 }
5049 PyObject_Free(stack);
5050 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005051}
5052
5053static int
5054assemble_init(struct assembler *a, int nblocks, int firstlineno)
5055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 memset(a, 0, sizeof(struct assembler));
5057 a->a_lineno = firstlineno;
5058 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5059 if (!a->a_bytecode)
5060 return 0;
5061 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5062 if (!a->a_lnotab)
5063 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005064 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 PyErr_NoMemory();
5066 return 0;
5067 }
5068 a->a_postorder = (basicblock **)PyObject_Malloc(
5069 sizeof(basicblock *) * nblocks);
5070 if (!a->a_postorder) {
5071 PyErr_NoMemory();
5072 return 0;
5073 }
5074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005075}
5076
5077static void
5078assemble_free(struct assembler *a)
5079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 Py_XDECREF(a->a_bytecode);
5081 Py_XDECREF(a->a_lnotab);
5082 if (a->a_postorder)
5083 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005084}
5085
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005086static int
5087blocksize(basicblock *b)
5088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 int i;
5090 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005093 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095}
5096
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005097/* Appends a pair to the end of the line number table, a_lnotab, representing
5098 the instruction's bytecode offset and line number. See
5099 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005100
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005101static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005102assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005105 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107
Serhiy Storchakaab874002016-09-11 13:48:15 +03005108 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 if(d_bytecode == 0 && d_lineno == 0)
5114 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 if (d_bytecode > 255) {
5117 int j, nbytes, ncodes = d_bytecode / 255;
5118 nbytes = a->a_lnotab_off + 2 * ncodes;
5119 len = PyBytes_GET_SIZE(a->a_lnotab);
5120 if (nbytes >= len) {
5121 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5122 len = nbytes;
5123 else if (len <= INT_MAX / 2)
5124 len *= 2;
5125 else {
5126 PyErr_NoMemory();
5127 return 0;
5128 }
5129 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5130 return 0;
5131 }
5132 lnotab = (unsigned char *)
5133 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5134 for (j = 0; j < ncodes; j++) {
5135 *lnotab++ = 255;
5136 *lnotab++ = 0;
5137 }
5138 d_bytecode -= ncodes * 255;
5139 a->a_lnotab_off += ncodes * 2;
5140 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005141 assert(0 <= d_bytecode && d_bytecode <= 255);
5142
5143 if (d_lineno < -128 || 127 < d_lineno) {
5144 int j, nbytes, ncodes, k;
5145 if (d_lineno < 0) {
5146 k = -128;
5147 /* use division on positive numbers */
5148 ncodes = (-d_lineno) / 128;
5149 }
5150 else {
5151 k = 127;
5152 ncodes = d_lineno / 127;
5153 }
5154 d_lineno -= ncodes * k;
5155 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 nbytes = a->a_lnotab_off + 2 * ncodes;
5157 len = PyBytes_GET_SIZE(a->a_lnotab);
5158 if (nbytes >= len) {
5159 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5160 len = nbytes;
5161 else if (len <= INT_MAX / 2)
5162 len *= 2;
5163 else {
5164 PyErr_NoMemory();
5165 return 0;
5166 }
5167 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5168 return 0;
5169 }
5170 lnotab = (unsigned char *)
5171 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5172 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005173 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 d_bytecode = 0;
5175 for (j = 1; j < ncodes; j++) {
5176 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005177 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 a->a_lnotab_off += ncodes * 2;
5180 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005181 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 len = PyBytes_GET_SIZE(a->a_lnotab);
5184 if (a->a_lnotab_off + 2 >= len) {
5185 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5186 return 0;
5187 }
5188 lnotab = (unsigned char *)
5189 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 a->a_lnotab_off += 2;
5192 if (d_bytecode) {
5193 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005194 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 }
5196 else { /* First line of a block; def stmt, etc. */
5197 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005198 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 }
5200 a->a_lineno = i->i_lineno;
5201 a->a_lineno_off = a->a_offset;
5202 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005203}
5204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005205/* assemble_emit()
5206 Extend the bytecode with a new instruction.
5207 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005208*/
5209
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005210static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005211assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005212{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005213 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005215 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005216
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005217 arg = i->i_oparg;
5218 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 if (i->i_lineno && !assemble_lnotab(a, i))
5220 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005221 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 if (len > PY_SSIZE_T_MAX / 2)
5223 return 0;
5224 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5225 return 0;
5226 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005227 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005229 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005231}
5232
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005233static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005234assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005237 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 /* Compute the size of each block and fixup jump args.
5241 Replace block pointer with position in bytecode. */
5242 do {
5243 totsize = 0;
5244 for (i = a->a_nblocks - 1; i >= 0; i--) {
5245 b = a->a_postorder[i];
5246 bsize = blocksize(b);
5247 b->b_offset = totsize;
5248 totsize += bsize;
5249 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005250 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5252 bsize = b->b_offset;
5253 for (i = 0; i < b->b_iused; i++) {
5254 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005255 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 /* Relative jumps are computed relative to
5257 the instruction pointer after fetching
5258 the jump instruction.
5259 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005260 bsize += isize;
5261 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005263 if (instr->i_jrel) {
5264 instr->i_oparg -= bsize;
5265 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005266 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005267 if (instrsize(instr->i_oparg) != isize) {
5268 extended_arg_recompile = 1;
5269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 }
5272 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 /* XXX: This is an awful hack that could hurt performance, but
5275 on the bright side it should work until we come up
5276 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 The issue is that in the first loop blocksize() is called
5279 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005280 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 So we loop until we stop seeing new EXTENDED_ARGs.
5284 The only EXTENDED_ARGs that could be popping up are
5285 ones in jump instructions. So this should converge
5286 fairly quickly.
5287 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005288 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005289}
5290
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005291static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005292dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005295 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 tuple = PyTuple_New(size);
5298 if (tuple == NULL)
5299 return NULL;
5300 while (PyDict_Next(dict, &pos, &k, &v)) {
5301 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005302 /* The keys of the dictionary are tuples. (see compiler_add_o
5303 * and _PyCode_ConstantKey). The object we want is always second,
5304 * though. */
5305 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 Py_INCREF(k);
5307 assert((i - offset) < size);
5308 assert((i - offset) >= 0);
5309 PyTuple_SET_ITEM(tuple, i - offset, k);
5310 }
5311 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005312}
5313
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005314static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005315compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005318 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005320 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 if (ste->ste_nested)
5322 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005323 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005325 if (!ste->ste_generator && ste->ste_coroutine)
5326 flags |= CO_COROUTINE;
5327 if (ste->ste_generator && ste->ste_coroutine)
5328 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 if (ste->ste_varargs)
5330 flags |= CO_VARARGS;
5331 if (ste->ste_varkeywords)
5332 flags |= CO_VARKEYWORDS;
5333 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 /* (Only) inherit compilerflags in PyCF_MASK */
5336 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005339}
5340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005341static PyCodeObject *
5342makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 PyObject *tmp;
5345 PyCodeObject *co = NULL;
5346 PyObject *consts = NULL;
5347 PyObject *names = NULL;
5348 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 PyObject *name = NULL;
5350 PyObject *freevars = NULL;
5351 PyObject *cellvars = NULL;
5352 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005353 Py_ssize_t nlocals;
5354 int nlocals_int;
5355 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005356 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 tmp = dict_keys_inorder(c->u->u_consts, 0);
5359 if (!tmp)
5360 goto error;
5361 consts = PySequence_List(tmp); /* optimize_code requires a list */
5362 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 names = dict_keys_inorder(c->u->u_names, 0);
5365 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5366 if (!consts || !names || !varnames)
5367 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5370 if (!cellvars)
5371 goto error;
5372 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5373 if (!freevars)
5374 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005375
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005376 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005377 assert(nlocals < INT_MAX);
5378 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 flags = compute_code_flags(c);
5381 if (flags < 0)
5382 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5385 if (!bytecode)
5386 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5389 if (!tmp)
5390 goto error;
5391 Py_DECREF(consts);
5392 consts = tmp;
5393
Victor Stinnerf8e32212013-11-19 23:56:34 +01005394 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5395 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005396 maxdepth = stackdepth(c);
5397 if (maxdepth < 0) {
5398 goto error;
5399 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005400 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005401 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 bytecode, consts, names, varnames,
5403 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005404 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 c->u->u_firstlineno,
5406 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005407 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 Py_XDECREF(consts);
5409 Py_XDECREF(names);
5410 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 Py_XDECREF(name);
5412 Py_XDECREF(freevars);
5413 Py_XDECREF(cellvars);
5414 Py_XDECREF(bytecode);
5415 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005416}
5417
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005418
5419/* For debugging purposes only */
5420#if 0
5421static void
5422dump_instr(const struct instr *i)
5423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 const char *jrel = i->i_jrel ? "jrel " : "";
5425 const char *jabs = i->i_jabs ? "jabs " : "";
5426 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005429 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5433 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005434}
5435
5436static void
5437dump_basicblock(const basicblock *b)
5438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 const char *seen = b->b_seen ? "seen " : "";
5440 const char *b_return = b->b_return ? "return " : "";
5441 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5442 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5443 if (b->b_instr) {
5444 int i;
5445 for (i = 0; i < b->b_iused; i++) {
5446 fprintf(stderr, " [%02d] ", i);
5447 dump_instr(b->b_instr + i);
5448 }
5449 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005450}
5451#endif
5452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453static PyCodeObject *
5454assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 basicblock *b, *entryblock;
5457 struct assembler a;
5458 int i, j, nblocks;
5459 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 /* Make sure every block that falls off the end returns None.
5462 XXX NEXT_BLOCK() isn't quite right, because if the last
5463 block ends with a jump or return b_next shouldn't set.
5464 */
5465 if (!c->u->u_curblock->b_return) {
5466 NEXT_BLOCK(c);
5467 if (addNone)
5468 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5469 ADDOP(c, RETURN_VALUE);
5470 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 nblocks = 0;
5473 entryblock = NULL;
5474 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5475 nblocks++;
5476 entryblock = b;
5477 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 /* Set firstlineno if it wasn't explicitly set. */
5480 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005481 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5483 else
5484 c->u->u_firstlineno = 1;
5485 }
5486 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5487 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005488 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 /* Can't modify the bytecode after computing jump offsets. */
5491 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 /* Emit code in reverse postorder from dfs. */
5494 for (i = a.a_nblocks - 1; i >= 0; i--) {
5495 b = a.a_postorder[i];
5496 for (j = 0; j < b->b_iused; j++)
5497 if (!assemble_emit(&a, &b->b_instr[j]))
5498 goto error;
5499 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5502 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005503 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 assemble_free(&a);
5509 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005510}
Georg Brandl8334fd92010-12-04 10:26:46 +00005511
5512#undef PyAST_Compile
5513PyAPI_FUNC(PyCodeObject *)
5514PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5515 PyArena *arena)
5516{
5517 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5518}