blob: 9d2ba7b18f11fe8f00e483f67c1e35c6ba443de2 [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 Storchakaf93234b2017-05-09 22:31:05 +03002846 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002848 if (dot == -1) {
2849 break;
2850 }
2851 ADDOP(c, ROT_TWO);
2852 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002854 if (!compiler_nameop(c, asname, Store)) {
2855 return 0;
2856 }
2857 ADDOP(c, POP_TOP);
2858 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 }
2860 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861}
2862
2863static int
2864compiler_import(struct compiler *c, stmt_ty s)
2865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 /* The Import node stores a module name like a.b.c as a single
2867 string. This is convenient for all cases except
2868 import a.b.c as d
2869 where we need to parse that string to extract the individual
2870 module names.
2871 XXX Perhaps change the representation to make this case simpler?
2872 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002873 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 for (i = 0; i < n; i++) {
2876 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2877 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002879 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2881 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if (alias->asname) {
2884 r = compiler_import_as(c, alias->name, alias->asname);
2885 if (!r)
2886 return r;
2887 }
2888 else {
2889 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002890 Py_ssize_t dot = PyUnicode_FindChar(
2891 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002892 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002893 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002894 if (tmp == NULL)
2895 return 0;
2896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002898 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 Py_DECREF(tmp);
2900 }
2901 if (!r)
2902 return r;
2903 }
2904 }
2905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906}
2907
2908static int
2909compiler_from_import(struct compiler *c, stmt_ty s)
2910{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002911 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002912 PyObject *level, *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 if (!empty_string) {
2916 empty_string = PyUnicode_FromString("");
2917 if (!empty_string)
2918 return 0;
2919 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 level = PyLong_FromLong(s->v.ImportFrom.level);
2922 if (!level) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 return 0;
2924 }
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002925 ADDOP_N(c, LOAD_CONST, level, consts);
2926
2927 names = PyTuple_New(n);
2928 if (!names)
2929 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 /* build up the names */
2932 for (i = 0; i < n; i++) {
2933 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2934 Py_INCREF(alias->name);
2935 PyTuple_SET_ITEM(names, i, alias->name);
2936 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002939 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 Py_DECREF(names);
2941 return compiler_error(c, "from __future__ imports must occur "
2942 "at the beginning of the file");
2943 }
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002944 ADDOP_N(c, LOAD_CONST, names, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 if (s->v.ImportFrom.module) {
2947 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2948 }
2949 else {
2950 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2951 }
2952 for (i = 0; i < n; i++) {
2953 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2954 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002956 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 assert(n == 1);
2958 ADDOP(c, IMPORT_STAR);
2959 return 1;
2960 }
2961
2962 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2963 store_name = alias->name;
2964 if (alias->asname)
2965 store_name = alias->asname;
2966
2967 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 return 0;
2969 }
2970 }
2971 /* remove imported module */
2972 ADDOP(c, POP_TOP);
2973 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974}
2975
2976static int
2977compiler_assert(struct compiler *c, stmt_ty s)
2978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 static PyObject *assertion_error = NULL;
2980 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002981 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982
Georg Brandl8334fd92010-12-04 10:26:46 +00002983 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return 1;
2985 if (assertion_error == NULL) {
2986 assertion_error = PyUnicode_InternFromString("AssertionError");
2987 if (assertion_error == NULL)
2988 return 0;
2989 }
2990 if (s->v.Assert.test->kind == Tuple_kind &&
2991 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002992 msg = PyUnicode_FromString("assertion is always true, "
2993 "perhaps remove parentheses?");
2994 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002996 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2997 c->c_filename, c->u->u_lineno,
2998 NULL, NULL) == -1) {
2999 Py_DECREF(msg);
3000 return 0;
3001 }
3002 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 end = compiler_new_block(c);
3005 if (end == NULL)
3006 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003007 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3008 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3010 if (s->v.Assert.msg) {
3011 VISIT(c, expr, s->v.Assert.msg);
3012 ADDOP_I(c, CALL_FUNCTION, 1);
3013 }
3014 ADDOP_I(c, RAISE_VARARGS, 1);
3015 compiler_use_next_block(c, end);
3016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017}
3018
3019static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003020compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3021{
3022 if (c->c_interactive && c->c_nestlevel <= 1) {
3023 VISIT(c, expr, value);
3024 ADDOP(c, PRINT_EXPR);
3025 return 1;
3026 }
3027
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003028 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003029 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003030 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003031 }
3032
3033 VISIT(c, expr, value);
3034 ADDOP(c, POP_TOP);
3035 return 1;
3036}
3037
3038static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039compiler_visit_stmt(struct compiler *c, stmt_ty s)
3040{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003041 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 /* Always assign a lineno to the next instruction for a stmt. */
3044 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003045 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 switch (s->kind) {
3049 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003050 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 case ClassDef_kind:
3052 return compiler_class(c, s);
3053 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003054 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 case Delete_kind:
3056 VISIT_SEQ(c, expr, s->v.Delete.targets)
3057 break;
3058 case Assign_kind:
3059 n = asdl_seq_LEN(s->v.Assign.targets);
3060 VISIT(c, expr, s->v.Assign.value);
3061 for (i = 0; i < n; i++) {
3062 if (i < n - 1)
3063 ADDOP(c, DUP_TOP);
3064 VISIT(c, expr,
3065 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3066 }
3067 break;
3068 case AugAssign_kind:
3069 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003070 case AnnAssign_kind:
3071 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 case For_kind:
3073 return compiler_for(c, s);
3074 case While_kind:
3075 return compiler_while(c, s);
3076 case If_kind:
3077 return compiler_if(c, s);
3078 case Raise_kind:
3079 n = 0;
3080 if (s->v.Raise.exc) {
3081 VISIT(c, expr, s->v.Raise.exc);
3082 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003083 if (s->v.Raise.cause) {
3084 VISIT(c, expr, s->v.Raise.cause);
3085 n++;
3086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003088 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003090 case Try_kind:
3091 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 case Assert_kind:
3093 return compiler_assert(c, s);
3094 case Import_kind:
3095 return compiler_import(c, s);
3096 case ImportFrom_kind:
3097 return compiler_from_import(c, s);
3098 case Global_kind:
3099 case Nonlocal_kind:
3100 break;
3101 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003102 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 case Pass_kind:
3104 break;
3105 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003106 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 case Continue_kind:
3108 return compiler_continue(c);
3109 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003110 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003111 case AsyncFunctionDef_kind:
3112 return compiler_function(c, s, 1);
3113 case AsyncWith_kind:
3114 return compiler_async_with(c, s, 0);
3115 case AsyncFor_kind:
3116 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 }
Yury Selivanov75445082015-05-11 22:57:16 -04003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003120}
3121
3122static int
3123unaryop(unaryop_ty op)
3124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 switch (op) {
3126 case Invert:
3127 return UNARY_INVERT;
3128 case Not:
3129 return UNARY_NOT;
3130 case UAdd:
3131 return UNARY_POSITIVE;
3132 case USub:
3133 return UNARY_NEGATIVE;
3134 default:
3135 PyErr_Format(PyExc_SystemError,
3136 "unary op %d should not be possible", op);
3137 return 0;
3138 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139}
3140
3141static int
3142binop(struct compiler *c, operator_ty op)
3143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 switch (op) {
3145 case Add:
3146 return BINARY_ADD;
3147 case Sub:
3148 return BINARY_SUBTRACT;
3149 case Mult:
3150 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003151 case MatMult:
3152 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 case Div:
3154 return BINARY_TRUE_DIVIDE;
3155 case Mod:
3156 return BINARY_MODULO;
3157 case Pow:
3158 return BINARY_POWER;
3159 case LShift:
3160 return BINARY_LSHIFT;
3161 case RShift:
3162 return BINARY_RSHIFT;
3163 case BitOr:
3164 return BINARY_OR;
3165 case BitXor:
3166 return BINARY_XOR;
3167 case BitAnd:
3168 return BINARY_AND;
3169 case FloorDiv:
3170 return BINARY_FLOOR_DIVIDE;
3171 default:
3172 PyErr_Format(PyExc_SystemError,
3173 "binary op %d should not be possible", op);
3174 return 0;
3175 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176}
3177
3178static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179inplace_binop(struct compiler *c, operator_ty op)
3180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 switch (op) {
3182 case Add:
3183 return INPLACE_ADD;
3184 case Sub:
3185 return INPLACE_SUBTRACT;
3186 case Mult:
3187 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003188 case MatMult:
3189 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 case Div:
3191 return INPLACE_TRUE_DIVIDE;
3192 case Mod:
3193 return INPLACE_MODULO;
3194 case Pow:
3195 return INPLACE_POWER;
3196 case LShift:
3197 return INPLACE_LSHIFT;
3198 case RShift:
3199 return INPLACE_RSHIFT;
3200 case BitOr:
3201 return INPLACE_OR;
3202 case BitXor:
3203 return INPLACE_XOR;
3204 case BitAnd:
3205 return INPLACE_AND;
3206 case FloorDiv:
3207 return INPLACE_FLOOR_DIVIDE;
3208 default:
3209 PyErr_Format(PyExc_SystemError,
3210 "inplace binary op %d should not be possible", op);
3211 return 0;
3212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213}
3214
3215static int
3216compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3217{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003218 int op, scope;
3219 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 PyObject *dict = c->u->u_names;
3223 PyObject *mangled;
3224 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003226 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3227 !_PyUnicode_EqualToASCIIString(name, "True") &&
3228 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003229
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003230 mangled = _Py_Mangle(c->u->u_private, name);
3231 if (!mangled)
3232 return 0;
3233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 op = 0;
3235 optype = OP_NAME;
3236 scope = PyST_GetScope(c->u->u_ste, mangled);
3237 switch (scope) {
3238 case FREE:
3239 dict = c->u->u_freevars;
3240 optype = OP_DEREF;
3241 break;
3242 case CELL:
3243 dict = c->u->u_cellvars;
3244 optype = OP_DEREF;
3245 break;
3246 case LOCAL:
3247 if (c->u->u_ste->ste_type == FunctionBlock)
3248 optype = OP_FAST;
3249 break;
3250 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003251 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 optype = OP_GLOBAL;
3253 break;
3254 case GLOBAL_EXPLICIT:
3255 optype = OP_GLOBAL;
3256 break;
3257 default:
3258 /* scope can be 0 */
3259 break;
3260 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003263 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 switch (optype) {
3266 case OP_DEREF:
3267 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003268 case Load:
3269 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3270 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 case Store: op = STORE_DEREF; break;
3272 case AugLoad:
3273 case AugStore:
3274 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003275 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 case Param:
3277 default:
3278 PyErr_SetString(PyExc_SystemError,
3279 "param invalid for deref variable");
3280 return 0;
3281 }
3282 break;
3283 case OP_FAST:
3284 switch (ctx) {
3285 case Load: op = LOAD_FAST; break;
3286 case Store: op = STORE_FAST; break;
3287 case Del: op = DELETE_FAST; break;
3288 case AugLoad:
3289 case AugStore:
3290 break;
3291 case Param:
3292 default:
3293 PyErr_SetString(PyExc_SystemError,
3294 "param invalid for local variable");
3295 return 0;
3296 }
3297 ADDOP_O(c, op, mangled, varnames);
3298 Py_DECREF(mangled);
3299 return 1;
3300 case OP_GLOBAL:
3301 switch (ctx) {
3302 case Load: op = LOAD_GLOBAL; break;
3303 case Store: op = STORE_GLOBAL; break;
3304 case Del: op = DELETE_GLOBAL; break;
3305 case AugLoad:
3306 case AugStore:
3307 break;
3308 case Param:
3309 default:
3310 PyErr_SetString(PyExc_SystemError,
3311 "param invalid for global variable");
3312 return 0;
3313 }
3314 break;
3315 case OP_NAME:
3316 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003317 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 case Store: op = STORE_NAME; break;
3319 case Del: op = DELETE_NAME; break;
3320 case AugLoad:
3321 case AugStore:
3322 break;
3323 case Param:
3324 default:
3325 PyErr_SetString(PyExc_SystemError,
3326 "param invalid for name variable");
3327 return 0;
3328 }
3329 break;
3330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 assert(op);
3333 arg = compiler_add_o(c, dict, mangled);
3334 Py_DECREF(mangled);
3335 if (arg < 0)
3336 return 0;
3337 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338}
3339
3340static int
3341compiler_boolop(struct compiler *c, expr_ty e)
3342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003344 int jumpi;
3345 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 assert(e->kind == BoolOp_kind);
3349 if (e->v.BoolOp.op == And)
3350 jumpi = JUMP_IF_FALSE_OR_POP;
3351 else
3352 jumpi = JUMP_IF_TRUE_OR_POP;
3353 end = compiler_new_block(c);
3354 if (end == NULL)
3355 return 0;
3356 s = e->v.BoolOp.values;
3357 n = asdl_seq_LEN(s) - 1;
3358 assert(n >= 0);
3359 for (i = 0; i < n; ++i) {
3360 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3361 ADDOP_JABS(c, jumpi, end);
3362 }
3363 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3364 compiler_use_next_block(c, end);
3365 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366}
3367
3368static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003369starunpack_helper(struct compiler *c, asdl_seq *elts,
3370 int single_op, int inner_op, int outer_op)
3371{
3372 Py_ssize_t n = asdl_seq_LEN(elts);
3373 Py_ssize_t i, nsubitems = 0, nseen = 0;
3374 for (i = 0; i < n; i++) {
3375 expr_ty elt = asdl_seq_GET(elts, i);
3376 if (elt->kind == Starred_kind) {
3377 if (nseen) {
3378 ADDOP_I(c, inner_op, nseen);
3379 nseen = 0;
3380 nsubitems++;
3381 }
3382 VISIT(c, expr, elt->v.Starred.value);
3383 nsubitems++;
3384 }
3385 else {
3386 VISIT(c, expr, elt);
3387 nseen++;
3388 }
3389 }
3390 if (nsubitems) {
3391 if (nseen) {
3392 ADDOP_I(c, inner_op, nseen);
3393 nsubitems++;
3394 }
3395 ADDOP_I(c, outer_op, nsubitems);
3396 }
3397 else
3398 ADDOP_I(c, single_op, nseen);
3399 return 1;
3400}
3401
3402static int
3403assignment_helper(struct compiler *c, asdl_seq *elts)
3404{
3405 Py_ssize_t n = asdl_seq_LEN(elts);
3406 Py_ssize_t i;
3407 int seen_star = 0;
3408 for (i = 0; i < n; i++) {
3409 expr_ty elt = asdl_seq_GET(elts, i);
3410 if (elt->kind == Starred_kind && !seen_star) {
3411 if ((i >= (1 << 8)) ||
3412 (n-i-1 >= (INT_MAX >> 8)))
3413 return compiler_error(c,
3414 "too many expressions in "
3415 "star-unpacking assignment");
3416 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3417 seen_star = 1;
3418 asdl_seq_SET(elts, i, elt->v.Starred.value);
3419 }
3420 else if (elt->kind == Starred_kind) {
3421 return compiler_error(c,
3422 "two starred expressions in assignment");
3423 }
3424 }
3425 if (!seen_star) {
3426 ADDOP_I(c, UNPACK_SEQUENCE, n);
3427 }
3428 VISIT_SEQ(c, expr, elts);
3429 return 1;
3430}
3431
3432static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433compiler_list(struct compiler *c, expr_ty e)
3434{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003435 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003437 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003439 else if (e->v.List.ctx == Load) {
3440 return starunpack_helper(c, elts,
3441 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003443 else
3444 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446}
3447
3448static int
3449compiler_tuple(struct compiler *c, expr_ty e)
3450{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003451 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003453 return assignment_helper(c, elts);
3454 }
3455 else if (e->v.Tuple.ctx == Load) {
3456 return starunpack_helper(c, elts,
3457 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3458 }
3459 else
3460 VISIT_SEQ(c, expr, elts);
3461 return 1;
3462}
3463
3464static int
3465compiler_set(struct compiler *c, expr_ty e)
3466{
3467 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3468 BUILD_SET, BUILD_SET_UNPACK);
3469}
3470
3471static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003472are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3473{
3474 Py_ssize_t i;
3475 for (i = begin; i < end; i++) {
3476 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3477 if (key == NULL || !is_const(key))
3478 return 0;
3479 }
3480 return 1;
3481}
3482
3483static int
3484compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3485{
3486 Py_ssize_t i, n = end - begin;
3487 PyObject *keys, *key;
3488 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3489 for (i = begin; i < end; i++) {
3490 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3491 }
3492 keys = PyTuple_New(n);
3493 if (keys == NULL) {
3494 return 0;
3495 }
3496 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003497 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003498 Py_INCREF(key);
3499 PyTuple_SET_ITEM(keys, i - begin, key);
3500 }
3501 ADDOP_N(c, LOAD_CONST, keys, consts);
3502 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3503 }
3504 else {
3505 for (i = begin; i < end; i++) {
3506 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3507 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3508 }
3509 ADDOP_I(c, BUILD_MAP, n);
3510 }
3511 return 1;
3512}
3513
3514static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003515compiler_dict(struct compiler *c, expr_ty e)
3516{
Victor Stinner976bb402016-03-23 11:36:19 +01003517 Py_ssize_t i, n, elements;
3518 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003519 int is_unpacking = 0;
3520 n = asdl_seq_LEN(e->v.Dict.values);
3521 containers = 0;
3522 elements = 0;
3523 for (i = 0; i < n; i++) {
3524 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3525 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003526 if (!compiler_subdict(c, e, i - elements, i))
3527 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003528 containers++;
3529 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003531 if (is_unpacking) {
3532 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3533 containers++;
3534 }
3535 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003536 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 }
3538 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003539 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003540 if (!compiler_subdict(c, e, n - elements, n))
3541 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003542 containers++;
3543 }
3544 /* If there is more than one dict, they need to be merged into a new
3545 * dict. If there is one dict and it's an unpacking, then it needs
3546 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003547 if (containers > 1 || is_unpacking) {
3548 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 }
3550 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551}
3552
3553static int
3554compiler_compare(struct compiler *c, expr_ty e)
3555{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003556 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003559 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3560 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3561 if (n == 0) {
3562 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3563 ADDOP_I(c, COMPARE_OP,
3564 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3565 }
3566 else {
3567 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 if (cleanup == NULL)
3569 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003570 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 VISIT(c, expr,
3572 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003573 ADDOP(c, DUP_TOP);
3574 ADDOP(c, ROT_THREE);
3575 ADDOP_I(c, COMPARE_OP,
3576 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3577 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3578 NEXT_BLOCK(c);
3579 }
3580 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3581 ADDOP_I(c, COMPARE_OP,
3582 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 basicblock *end = compiler_new_block(c);
3584 if (end == NULL)
3585 return 0;
3586 ADDOP_JREL(c, JUMP_FORWARD, end);
3587 compiler_use_next_block(c, cleanup);
3588 ADDOP(c, ROT_TWO);
3589 ADDOP(c, POP_TOP);
3590 compiler_use_next_block(c, end);
3591 }
3592 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593}
3594
3595static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003596maybe_optimize_method_call(struct compiler *c, expr_ty e)
3597{
3598 Py_ssize_t argsl, i;
3599 expr_ty meth = e->v.Call.func;
3600 asdl_seq *args = e->v.Call.args;
3601
3602 /* Check that the call node is an attribute access, and that
3603 the call doesn't have keyword parameters. */
3604 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3605 asdl_seq_LEN(e->v.Call.keywords))
3606 return -1;
3607
3608 /* Check that there are no *varargs types of arguments. */
3609 argsl = asdl_seq_LEN(args);
3610 for (i = 0; i < argsl; i++) {
3611 expr_ty elt = asdl_seq_GET(args, i);
3612 if (elt->kind == Starred_kind) {
3613 return -1;
3614 }
3615 }
3616
3617 /* Alright, we can optimize the code. */
3618 VISIT(c, expr, meth->v.Attribute.value);
3619 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3620 VISIT_SEQ(c, expr, e->v.Call.args);
3621 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3622 return 1;
3623}
3624
3625static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626compiler_call(struct compiler *c, expr_ty e)
3627{
Yury Selivanovf2392132016-12-13 19:03:51 -05003628 if (maybe_optimize_method_call(c, e) > 0)
3629 return 1;
3630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 VISIT(c, expr, e->v.Call.func);
3632 return compiler_call_helper(c, 0,
3633 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003634 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003635}
3636
Eric V. Smith235a6f02015-09-19 14:51:32 -04003637static int
3638compiler_joined_str(struct compiler *c, expr_ty e)
3639{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003640 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003641 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3642 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003643 return 1;
3644}
3645
Eric V. Smitha78c7952015-11-03 12:45:05 -05003646/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003647static int
3648compiler_formatted_value(struct compiler *c, expr_ty e)
3649{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003650 /* Our oparg encodes 2 pieces of information: the conversion
3651 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003652
Eric V. Smitha78c7952015-11-03 12:45:05 -05003653 Convert the conversion char to 2 bits:
3654 None: 000 0x0 FVC_NONE
3655 !s : 001 0x1 FVC_STR
3656 !r : 010 0x2 FVC_REPR
3657 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003658
Eric V. Smitha78c7952015-11-03 12:45:05 -05003659 next bit is whether or not we have a format spec:
3660 yes : 100 0x4
3661 no : 000 0x0
3662 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003663
Eric V. Smitha78c7952015-11-03 12:45:05 -05003664 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003665
Eric V. Smitha78c7952015-11-03 12:45:05 -05003666 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003667 VISIT(c, expr, e->v.FormattedValue.value);
3668
Eric V. Smitha78c7952015-11-03 12:45:05 -05003669 switch (e->v.FormattedValue.conversion) {
3670 case 's': oparg = FVC_STR; break;
3671 case 'r': oparg = FVC_REPR; break;
3672 case 'a': oparg = FVC_ASCII; break;
3673 case -1: oparg = FVC_NONE; break;
3674 default:
3675 PyErr_SetString(PyExc_SystemError,
3676 "Unrecognized conversion character");
3677 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003678 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003679 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003680 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003681 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003682 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003683 }
3684
Eric V. Smitha78c7952015-11-03 12:45:05 -05003685 /* And push our opcode and oparg */
3686 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003687 return 1;
3688}
3689
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003690static int
3691compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3692{
3693 Py_ssize_t i, n = end - begin;
3694 keyword_ty kw;
3695 PyObject *keys, *key;
3696 assert(n > 0);
3697 if (n > 1) {
3698 for (i = begin; i < end; i++) {
3699 kw = asdl_seq_GET(keywords, i);
3700 VISIT(c, expr, kw->value);
3701 }
3702 keys = PyTuple_New(n);
3703 if (keys == NULL) {
3704 return 0;
3705 }
3706 for (i = begin; i < end; i++) {
3707 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3708 Py_INCREF(key);
3709 PyTuple_SET_ITEM(keys, i - begin, key);
3710 }
3711 ADDOP_N(c, LOAD_CONST, keys, consts);
3712 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3713 }
3714 else {
3715 /* a for loop only executes once */
3716 for (i = begin; i < end; i++) {
3717 kw = asdl_seq_GET(keywords, i);
3718 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3719 VISIT(c, expr, kw->value);
3720 }
3721 ADDOP_I(c, BUILD_MAP, n);
3722 }
3723 return 1;
3724}
3725
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003726/* shared code between compiler_call and compiler_class */
3727static int
3728compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003729 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003730 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003732{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003733 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003734 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003735
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 /* the number of tuples and dictionaries on the stack */
3737 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3738
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003740 nkwelts = asdl_seq_LEN(keywords);
3741
3742 for (i = 0; i < nkwelts; i++) {
3743 keyword_ty kw = asdl_seq_GET(keywords, i);
3744 if (kw->arg == NULL) {
3745 mustdictunpack = 1;
3746 break;
3747 }
3748 }
3749
3750 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 for (i = 0; i < nelts; i++) {
3752 expr_ty elt = asdl_seq_GET(args, i);
3753 if (elt->kind == Starred_kind) {
3754 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003755 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003756 if (nseen) {
3757 ADDOP_I(c, BUILD_TUPLE, nseen);
3758 nseen = 0;
3759 nsubargs++;
3760 }
3761 VISIT(c, expr, elt->v.Starred.value);
3762 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 }
3764 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003766 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003767 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769
3770 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003771 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003772 if (nseen) {
3773 /* Pack up any trailing positional arguments. */
3774 ADDOP_I(c, BUILD_TUPLE, nseen);
3775 nsubargs++;
3776 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003777 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003778 /* If we ended up with more than one stararg, we need
3779 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003780 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003781 }
3782 else if (nsubargs == 0) {
3783 ADDOP_I(c, BUILD_TUPLE, 0);
3784 }
3785 nseen = 0; /* the number of keyword arguments on the stack following */
3786 for (i = 0; i < nkwelts; i++) {
3787 keyword_ty kw = asdl_seq_GET(keywords, i);
3788 if (kw->arg == NULL) {
3789 /* A keyword argument unpacking. */
3790 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003791 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3792 return 0;
3793 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003794 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003795 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003796 VISIT(c, expr, kw->value);
3797 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003798 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003799 else {
3800 nseen++;
3801 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003802 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003803 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003804 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003805 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003806 return 0;
3807 nsubkwargs++;
3808 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003809 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003811 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003812 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003813 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3814 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003816 else if (nkwelts) {
3817 PyObject *names;
3818 VISIT_SEQ(c, keyword, keywords);
3819 names = PyTuple_New(nkwelts);
3820 if (names == NULL) {
3821 return 0;
3822 }
3823 for (i = 0; i < nkwelts; i++) {
3824 keyword_ty kw = asdl_seq_GET(keywords, i);
3825 Py_INCREF(kw->arg);
3826 PyTuple_SET_ITEM(names, i, kw->arg);
3827 }
3828 ADDOP_N(c, LOAD_CONST, names, consts);
3829 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3830 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003832 else {
3833 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3834 return 1;
3835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836}
3837
Nick Coghlan650f0d02007-04-15 12:05:43 +00003838
3839/* List and set comprehensions and generator expressions work by creating a
3840 nested function to perform the actual iteration. This means that the
3841 iteration variables don't leak into the current scope.
3842 The defined function is called immediately following its definition, with the
3843 result of that call being the result of the expression.
3844 The LC/SC version returns the populated container, while the GE version is
3845 flagged in symtable.c as a generator, so it returns the generator object
3846 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003847
3848 Possible cleanups:
3849 - iterate over the generator sequence instead of using recursion
3850*/
3851
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854compiler_comprehension_generator(struct compiler *c,
3855 asdl_seq *generators, int gen_index,
3856 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003858 comprehension_ty gen;
3859 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3860 if (gen->is_async) {
3861 return compiler_async_comprehension_generator(
3862 c, generators, gen_index, elt, val, type);
3863 } else {
3864 return compiler_sync_comprehension_generator(
3865 c, generators, gen_index, elt, val, type);
3866 }
3867}
3868
3869static int
3870compiler_sync_comprehension_generator(struct compiler *c,
3871 asdl_seq *generators, int gen_index,
3872 expr_ty elt, expr_ty val, int type)
3873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 /* generate code for the iterator, then each of the ifs,
3875 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 comprehension_ty gen;
3878 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003879 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 start = compiler_new_block(c);
3882 skip = compiler_new_block(c);
3883 if_cleanup = compiler_new_block(c);
3884 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3887 anchor == NULL)
3888 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 if (gen_index == 0) {
3893 /* Receive outermost iter as an implicit argument */
3894 c->u->u_argcount = 1;
3895 ADDOP_I(c, LOAD_FAST, 0);
3896 }
3897 else {
3898 /* Sub-iter - calculate on the fly */
3899 VISIT(c, expr, gen->iter);
3900 ADDOP(c, GET_ITER);
3901 }
3902 compiler_use_next_block(c, start);
3903 ADDOP_JREL(c, FOR_ITER, anchor);
3904 NEXT_BLOCK(c);
3905 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 /* XXX this needs to be cleaned up...a lot! */
3908 n = asdl_seq_LEN(gen->ifs);
3909 for (i = 0; i < n; i++) {
3910 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003911 if (!compiler_jump_if(c, e, if_cleanup, 0))
3912 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 NEXT_BLOCK(c);
3914 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 if (++gen_index < asdl_seq_LEN(generators))
3917 if (!compiler_comprehension_generator(c,
3918 generators, gen_index,
3919 elt, val, type))
3920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* only append after the last for generator */
3923 if (gen_index >= asdl_seq_LEN(generators)) {
3924 /* comprehension specific code */
3925 switch (type) {
3926 case COMP_GENEXP:
3927 VISIT(c, expr, elt);
3928 ADDOP(c, YIELD_VALUE);
3929 ADDOP(c, POP_TOP);
3930 break;
3931 case COMP_LISTCOMP:
3932 VISIT(c, expr, elt);
3933 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3934 break;
3935 case COMP_SETCOMP:
3936 VISIT(c, expr, elt);
3937 ADDOP_I(c, SET_ADD, gen_index + 1);
3938 break;
3939 case COMP_DICTCOMP:
3940 /* With 'd[k] = v', v is evaluated before k, so we do
3941 the same. */
3942 VISIT(c, expr, val);
3943 VISIT(c, expr, elt);
3944 ADDOP_I(c, MAP_ADD, gen_index + 1);
3945 break;
3946 default:
3947 return 0;
3948 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 compiler_use_next_block(c, skip);
3951 }
3952 compiler_use_next_block(c, if_cleanup);
3953 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3954 compiler_use_next_block(c, anchor);
3955
3956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957}
3958
3959static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003960compiler_async_comprehension_generator(struct compiler *c,
3961 asdl_seq *generators, int gen_index,
3962 expr_ty elt, expr_ty val, int type)
3963{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003964 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003965 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003967 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003969 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003970
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003971 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 return 0;
3973 }
3974
3975 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3976
3977 if (gen_index == 0) {
3978 /* Receive outermost iter as an implicit argument */
3979 c->u->u_argcount = 1;
3980 ADDOP_I(c, LOAD_FAST, 0);
3981 }
3982 else {
3983 /* Sub-iter - calculate on the fly */
3984 VISIT(c, expr, gen->iter);
3985 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003986 }
3987
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003988 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003989
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003990 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003991 ADDOP(c, GET_ANEXT);
3992 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3993 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003994 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02003995 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003996
3997 n = asdl_seq_LEN(gen->ifs);
3998 for (i = 0; i < n; i++) {
3999 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004000 if (!compiler_jump_if(c, e, if_cleanup, 0))
4001 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004002 NEXT_BLOCK(c);
4003 }
4004
4005 if (++gen_index < asdl_seq_LEN(generators))
4006 if (!compiler_comprehension_generator(c,
4007 generators, gen_index,
4008 elt, val, type))
4009 return 0;
4010
4011 /* only append after the last for generator */
4012 if (gen_index >= asdl_seq_LEN(generators)) {
4013 /* comprehension specific code */
4014 switch (type) {
4015 case COMP_GENEXP:
4016 VISIT(c, expr, elt);
4017 ADDOP(c, YIELD_VALUE);
4018 ADDOP(c, POP_TOP);
4019 break;
4020 case COMP_LISTCOMP:
4021 VISIT(c, expr, elt);
4022 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4023 break;
4024 case COMP_SETCOMP:
4025 VISIT(c, expr, elt);
4026 ADDOP_I(c, SET_ADD, gen_index + 1);
4027 break;
4028 case COMP_DICTCOMP:
4029 /* With 'd[k] = v', v is evaluated before k, so we do
4030 the same. */
4031 VISIT(c, expr, val);
4032 VISIT(c, expr, elt);
4033 ADDOP_I(c, MAP_ADD, gen_index + 1);
4034 break;
4035 default:
4036 return 0;
4037 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004038 }
4039 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004040 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4041
4042 compiler_use_next_block(c, except);
4043 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004044
4045 return 1;
4046}
4047
4048static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004049compiler_comprehension(struct compiler *c, expr_ty e, int type,
4050 identifier name, asdl_seq *generators, expr_ty elt,
4051 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004054 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004055 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004056 int is_async_function = c->u->u_ste->ste_coroutine;
4057 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004058
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004059 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004060
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004061 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4062 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004063 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004065 }
4066
4067 is_async_generator = c->u->u_ste->ste_coroutine;
4068
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004069 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004070 if (e->lineno > c->u->u_lineno) {
4071 c->u->u_lineno = e->lineno;
4072 c->u->u_lineno_set = 0;
4073 }
4074 compiler_error(c, "asynchronous comprehension outside of "
4075 "an asynchronous function");
4076 goto error_in_scope;
4077 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 if (type != COMP_GENEXP) {
4080 int op;
4081 switch (type) {
4082 case COMP_LISTCOMP:
4083 op = BUILD_LIST;
4084 break;
4085 case COMP_SETCOMP:
4086 op = BUILD_SET;
4087 break;
4088 case COMP_DICTCOMP:
4089 op = BUILD_MAP;
4090 break;
4091 default:
4092 PyErr_Format(PyExc_SystemError,
4093 "unknown comprehension type %d", type);
4094 goto error_in_scope;
4095 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 ADDOP_I(c, op, 0);
4098 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 if (!compiler_comprehension_generator(c, generators, 0, elt,
4101 val, type))
4102 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 if (type != COMP_GENEXP) {
4105 ADDOP(c, RETURN_VALUE);
4106 }
4107
4108 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004109 qualname = c->u->u_qualname;
4110 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004112 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 goto error;
4114
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004115 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004117 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 Py_DECREF(co);
4119
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004120 VISIT(c, expr, outermost->iter);
4121
4122 if (outermost->is_async) {
4123 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004124 } else {
4125 ADDOP(c, GET_ITER);
4126 }
4127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004129
4130 if (is_async_generator && type != COMP_GENEXP) {
4131 ADDOP(c, GET_AWAITABLE);
4132 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4133 ADDOP(c, YIELD_FROM);
4134 }
4135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004137error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004139error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004140 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 Py_XDECREF(co);
4142 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004143}
4144
4145static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146compiler_genexp(struct compiler *c, expr_ty e)
4147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 static identifier name;
4149 if (!name) {
4150 name = PyUnicode_FromString("<genexpr>");
4151 if (!name)
4152 return 0;
4153 }
4154 assert(e->kind == GeneratorExp_kind);
4155 return compiler_comprehension(c, e, COMP_GENEXP, name,
4156 e->v.GeneratorExp.generators,
4157 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158}
4159
4160static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004161compiler_listcomp(struct compiler *c, expr_ty e)
4162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 static identifier name;
4164 if (!name) {
4165 name = PyUnicode_FromString("<listcomp>");
4166 if (!name)
4167 return 0;
4168 }
4169 assert(e->kind == ListComp_kind);
4170 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4171 e->v.ListComp.generators,
4172 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004173}
4174
4175static int
4176compiler_setcomp(struct compiler *c, expr_ty e)
4177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 static identifier name;
4179 if (!name) {
4180 name = PyUnicode_FromString("<setcomp>");
4181 if (!name)
4182 return 0;
4183 }
4184 assert(e->kind == SetComp_kind);
4185 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4186 e->v.SetComp.generators,
4187 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004188}
4189
4190
4191static int
4192compiler_dictcomp(struct compiler *c, expr_ty e)
4193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 static identifier name;
4195 if (!name) {
4196 name = PyUnicode_FromString("<dictcomp>");
4197 if (!name)
4198 return 0;
4199 }
4200 assert(e->kind == DictComp_kind);
4201 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4202 e->v.DictComp.generators,
4203 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004204}
4205
4206
4207static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208compiler_visit_keyword(struct compiler *c, keyword_ty k)
4209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 VISIT(c, expr, k->value);
4211 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212}
4213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 whether they are true or false.
4216
4217 Return values: 1 for true, 0 for false, -1 for non-constant.
4218 */
4219
4220static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004221expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004222{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004223 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004224 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004225 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004226 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004227}
4228
Yury Selivanov75445082015-05-11 22:57:16 -04004229
4230/*
4231 Implements the async with statement.
4232
4233 The semantics outlined in that PEP are as follows:
4234
4235 async with EXPR as VAR:
4236 BLOCK
4237
4238 It is implemented roughly as:
4239
4240 context = EXPR
4241 exit = context.__aexit__ # not calling it
4242 value = await context.__aenter__()
4243 try:
4244 VAR = value # if VAR present in the syntax
4245 BLOCK
4246 finally:
4247 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004248 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004249 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004250 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004251 if not (await exit(*exc)):
4252 raise
4253 */
4254static int
4255compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4256{
4257 basicblock *block, *finally;
4258 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4259
4260 assert(s->kind == AsyncWith_kind);
4261
4262 block = compiler_new_block(c);
4263 finally = compiler_new_block(c);
4264 if (!block || !finally)
4265 return 0;
4266
4267 /* Evaluate EXPR */
4268 VISIT(c, expr, item->context_expr);
4269
4270 ADDOP(c, BEFORE_ASYNC_WITH);
4271 ADDOP(c, GET_AWAITABLE);
4272 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4273 ADDOP(c, YIELD_FROM);
4274
4275 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4276
4277 /* SETUP_ASYNC_WITH pushes a finally block. */
4278 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004279 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004280 return 0;
4281 }
4282
4283 if (item->optional_vars) {
4284 VISIT(c, expr, item->optional_vars);
4285 }
4286 else {
4287 /* Discard result from context.__aenter__() */
4288 ADDOP(c, POP_TOP);
4289 }
4290
4291 pos++;
4292 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4293 /* BLOCK code */
4294 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4295 else if (!compiler_async_with(c, s, pos))
4296 return 0;
4297
4298 /* End of try block; start the finally block */
4299 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004300 ADDOP(c, BEGIN_FINALLY);
4301 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004302
Yury Selivanov75445082015-05-11 22:57:16 -04004303 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004304 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004305 return 0;
4306
4307 /* Finally block starts; context.__exit__ is on the stack under
4308 the exception or return information. Just issue our magic
4309 opcode. */
4310 ADDOP(c, WITH_CLEANUP_START);
4311
4312 ADDOP(c, GET_AWAITABLE);
4313 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4314 ADDOP(c, YIELD_FROM);
4315
4316 ADDOP(c, WITH_CLEANUP_FINISH);
4317
4318 /* Finally block ends. */
4319 ADDOP(c, END_FINALLY);
4320 compiler_pop_fblock(c, FINALLY_END, finally);
4321 return 1;
4322}
4323
4324
Guido van Rossumc2e20742006-02-27 22:32:47 +00004325/*
4326 Implements the with statement from PEP 343.
4327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004329
4330 with EXPR as VAR:
4331 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332
Guido van Rossumc2e20742006-02-27 22:32:47 +00004333 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334
Thomas Wouters477c8d52006-05-27 19:21:47 +00004335 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004336 exit = context.__exit__ # not calling it
4337 value = context.__enter__()
4338 try:
4339 VAR = value # if VAR present in the syntax
4340 BLOCK
4341 finally:
4342 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004343 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004344 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004345 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004346 exit(*exc)
4347 */
4348static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004349compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004350{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004351 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004352 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004353
4354 assert(s->kind == With_kind);
4355
Guido van Rossumc2e20742006-02-27 22:32:47 +00004356 block = compiler_new_block(c);
4357 finally = compiler_new_block(c);
4358 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004359 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004360
Thomas Wouters477c8d52006-05-27 19:21:47 +00004361 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004362 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004363 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004364
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004365 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004366 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004367 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004368 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004369 }
4370
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004371 if (item->optional_vars) {
4372 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004373 }
4374 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004376 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004377 }
4378
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004379 pos++;
4380 if (pos == asdl_seq_LEN(s->v.With.items))
4381 /* BLOCK code */
4382 VISIT_SEQ(c, stmt, s->v.With.body)
4383 else if (!compiler_with(c, s, pos))
4384 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004385
4386 /* End of try block; start the finally block */
4387 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004388 ADDOP(c, BEGIN_FINALLY);
4389 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004390
Guido van Rossumc2e20742006-02-27 22:32:47 +00004391 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004392 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004393 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004394
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004395 /* Finally block starts; context.__exit__ is on the stack under
4396 the exception or return information. Just issue our magic
4397 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004398 ADDOP(c, WITH_CLEANUP_START);
4399 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004400
4401 /* Finally block ends. */
4402 ADDOP(c, END_FINALLY);
4403 compiler_pop_fblock(c, FINALLY_END, finally);
4404 return 1;
4405}
4406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004407static int
4408compiler_visit_expr(struct compiler *c, expr_ty e)
4409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 /* If expr e has a different line number than the last expr/stmt,
4411 set a new line number for the next instruction.
4412 */
4413 if (e->lineno > c->u->u_lineno) {
4414 c->u->u_lineno = e->lineno;
4415 c->u->u_lineno_set = 0;
4416 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004417 /* Updating the column offset is always harmless. */
4418 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 switch (e->kind) {
4420 case BoolOp_kind:
4421 return compiler_boolop(c, e);
4422 case BinOp_kind:
4423 VISIT(c, expr, e->v.BinOp.left);
4424 VISIT(c, expr, e->v.BinOp.right);
4425 ADDOP(c, binop(c, e->v.BinOp.op));
4426 break;
4427 case UnaryOp_kind:
4428 VISIT(c, expr, e->v.UnaryOp.operand);
4429 ADDOP(c, unaryop(e->v.UnaryOp.op));
4430 break;
4431 case Lambda_kind:
4432 return compiler_lambda(c, e);
4433 case IfExp_kind:
4434 return compiler_ifexp(c, e);
4435 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004436 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004438 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 case GeneratorExp_kind:
4440 return compiler_genexp(c, e);
4441 case ListComp_kind:
4442 return compiler_listcomp(c, e);
4443 case SetComp_kind:
4444 return compiler_setcomp(c, e);
4445 case DictComp_kind:
4446 return compiler_dictcomp(c, e);
4447 case Yield_kind:
4448 if (c->u->u_ste->ste_type != FunctionBlock)
4449 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004450 if (e->v.Yield.value) {
4451 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 }
4453 else {
4454 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4455 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004456 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004458 case YieldFrom_kind:
4459 if (c->u->u_ste->ste_type != FunctionBlock)
4460 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004461
4462 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4463 return compiler_error(c, "'yield from' inside async function");
4464
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004465 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004466 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004467 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4468 ADDOP(c, YIELD_FROM);
4469 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004470 case Await_kind:
4471 if (c->u->u_ste->ste_type != FunctionBlock)
4472 return compiler_error(c, "'await' outside function");
4473
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004474 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4475 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004476 return compiler_error(c, "'await' outside async function");
4477
4478 VISIT(c, expr, e->v.Await.value);
4479 ADDOP(c, GET_AWAITABLE);
4480 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4481 ADDOP(c, YIELD_FROM);
4482 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 case Compare_kind:
4484 return compiler_compare(c, e);
4485 case Call_kind:
4486 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004487 case Constant_kind:
4488 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4489 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 case Num_kind:
4491 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4492 break;
4493 case Str_kind:
4494 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4495 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004496 case JoinedStr_kind:
4497 return compiler_joined_str(c, e);
4498 case FormattedValue_kind:
4499 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 case Bytes_kind:
4501 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4502 break;
4503 case Ellipsis_kind:
4504 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4505 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004506 case NameConstant_kind:
4507 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4508 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 /* The following exprs can be assignment targets. */
4510 case Attribute_kind:
4511 if (e->v.Attribute.ctx != AugStore)
4512 VISIT(c, expr, e->v.Attribute.value);
4513 switch (e->v.Attribute.ctx) {
4514 case AugLoad:
4515 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004516 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 case Load:
4518 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4519 break;
4520 case AugStore:
4521 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004522 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 case Store:
4524 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4525 break;
4526 case Del:
4527 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4528 break;
4529 case Param:
4530 default:
4531 PyErr_SetString(PyExc_SystemError,
4532 "param invalid in attribute expression");
4533 return 0;
4534 }
4535 break;
4536 case Subscript_kind:
4537 switch (e->v.Subscript.ctx) {
4538 case AugLoad:
4539 VISIT(c, expr, e->v.Subscript.value);
4540 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4541 break;
4542 case Load:
4543 VISIT(c, expr, e->v.Subscript.value);
4544 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4545 break;
4546 case AugStore:
4547 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4548 break;
4549 case Store:
4550 VISIT(c, expr, e->v.Subscript.value);
4551 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4552 break;
4553 case Del:
4554 VISIT(c, expr, e->v.Subscript.value);
4555 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4556 break;
4557 case Param:
4558 default:
4559 PyErr_SetString(PyExc_SystemError,
4560 "param invalid in subscript expression");
4561 return 0;
4562 }
4563 break;
4564 case Starred_kind:
4565 switch (e->v.Starred.ctx) {
4566 case Store:
4567 /* In all legitimate cases, the Starred node was already replaced
4568 * by compiler_list/compiler_tuple. XXX: is that okay? */
4569 return compiler_error(c,
4570 "starred assignment target must be in a list or tuple");
4571 default:
4572 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004573 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 }
4575 break;
4576 case Name_kind:
4577 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4578 /* child nodes of List and Tuple will have expr_context set */
4579 case List_kind:
4580 return compiler_list(c, e);
4581 case Tuple_kind:
4582 return compiler_tuple(c, e);
4583 }
4584 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004585}
4586
4587static int
4588compiler_augassign(struct compiler *c, stmt_ty s)
4589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 expr_ty e = s->v.AugAssign.target;
4591 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 switch (e->kind) {
4596 case Attribute_kind:
4597 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4598 AugLoad, e->lineno, e->col_offset, c->c_arena);
4599 if (auge == NULL)
4600 return 0;
4601 VISIT(c, expr, auge);
4602 VISIT(c, expr, s->v.AugAssign.value);
4603 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4604 auge->v.Attribute.ctx = AugStore;
4605 VISIT(c, expr, auge);
4606 break;
4607 case Subscript_kind:
4608 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4609 AugLoad, e->lineno, e->col_offset, c->c_arena);
4610 if (auge == NULL)
4611 return 0;
4612 VISIT(c, expr, auge);
4613 VISIT(c, expr, s->v.AugAssign.value);
4614 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4615 auge->v.Subscript.ctx = AugStore;
4616 VISIT(c, expr, auge);
4617 break;
4618 case Name_kind:
4619 if (!compiler_nameop(c, e->v.Name.id, Load))
4620 return 0;
4621 VISIT(c, expr, s->v.AugAssign.value);
4622 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4623 return compiler_nameop(c, e->v.Name.id, Store);
4624 default:
4625 PyErr_Format(PyExc_SystemError,
4626 "invalid node type (%d) for augmented assignment",
4627 e->kind);
4628 return 0;
4629 }
4630 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004631}
4632
4633static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004634check_ann_expr(struct compiler *c, expr_ty e)
4635{
4636 VISIT(c, expr, e);
4637 ADDOP(c, POP_TOP);
4638 return 1;
4639}
4640
4641static int
4642check_annotation(struct compiler *c, stmt_ty s)
4643{
4644 /* Annotations are only evaluated in a module or class. */
4645 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4646 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4647 return check_ann_expr(c, s->v.AnnAssign.annotation);
4648 }
4649 return 1;
4650}
4651
4652static int
4653check_ann_slice(struct compiler *c, slice_ty sl)
4654{
4655 switch(sl->kind) {
4656 case Index_kind:
4657 return check_ann_expr(c, sl->v.Index.value);
4658 case Slice_kind:
4659 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4660 return 0;
4661 }
4662 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4663 return 0;
4664 }
4665 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4666 return 0;
4667 }
4668 break;
4669 default:
4670 PyErr_SetString(PyExc_SystemError,
4671 "unexpected slice kind");
4672 return 0;
4673 }
4674 return 1;
4675}
4676
4677static int
4678check_ann_subscr(struct compiler *c, slice_ty sl)
4679{
4680 /* We check that everything in a subscript is defined at runtime. */
4681 Py_ssize_t i, n;
4682
4683 switch (sl->kind) {
4684 case Index_kind:
4685 case Slice_kind:
4686 if (!check_ann_slice(c, sl)) {
4687 return 0;
4688 }
4689 break;
4690 case ExtSlice_kind:
4691 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4692 for (i = 0; i < n; i++) {
4693 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4694 switch (subsl->kind) {
4695 case Index_kind:
4696 case Slice_kind:
4697 if (!check_ann_slice(c, subsl)) {
4698 return 0;
4699 }
4700 break;
4701 case ExtSlice_kind:
4702 default:
4703 PyErr_SetString(PyExc_SystemError,
4704 "extended slice invalid in nested slice");
4705 return 0;
4706 }
4707 }
4708 break;
4709 default:
4710 PyErr_Format(PyExc_SystemError,
4711 "invalid subscript kind %d", sl->kind);
4712 return 0;
4713 }
4714 return 1;
4715}
4716
4717static int
4718compiler_annassign(struct compiler *c, stmt_ty s)
4719{
4720 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004721 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004722
4723 assert(s->kind == AnnAssign_kind);
4724
4725 /* We perform the actual assignment first. */
4726 if (s->v.AnnAssign.value) {
4727 VISIT(c, expr, s->v.AnnAssign.value);
4728 VISIT(c, expr, targ);
4729 }
4730 switch (targ->kind) {
4731 case Name_kind:
4732 /* If we have a simple name in a module or class, store annotation. */
4733 if (s->v.AnnAssign.simple &&
4734 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4735 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004736 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4737 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4738 }
4739 else {
4740 VISIT(c, expr, s->v.AnnAssign.annotation);
4741 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004742 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004743 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4744 if (!mangled) {
4745 return 0;
4746 }
4747 ADDOP_N(c, LOAD_CONST, mangled, consts);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004748 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004749 }
4750 break;
4751 case Attribute_kind:
4752 if (!s->v.AnnAssign.value &&
4753 !check_ann_expr(c, targ->v.Attribute.value)) {
4754 return 0;
4755 }
4756 break;
4757 case Subscript_kind:
4758 if (!s->v.AnnAssign.value &&
4759 (!check_ann_expr(c, targ->v.Subscript.value) ||
4760 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4761 return 0;
4762 }
4763 break;
4764 default:
4765 PyErr_Format(PyExc_SystemError,
4766 "invalid node type (%d) for annotated assignment",
4767 targ->kind);
4768 return 0;
4769 }
4770 /* Annotation is evaluated last. */
4771 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4772 return 0;
4773 }
4774 return 1;
4775}
4776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004777/* Raises a SyntaxError and returns 0.
4778 If something goes wrong, a different exception may be raised.
4779*/
4780
4781static int
4782compiler_error(struct compiler *c, const char *errstr)
4783{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004784 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004786
Victor Stinner14e461d2013-08-26 22:28:21 +02004787 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 if (!loc) {
4789 Py_INCREF(Py_None);
4790 loc = Py_None;
4791 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004792 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004793 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 if (!u)
4795 goto exit;
4796 v = Py_BuildValue("(zO)", errstr, u);
4797 if (!v)
4798 goto exit;
4799 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004800 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 Py_DECREF(loc);
4802 Py_XDECREF(u);
4803 Py_XDECREF(v);
4804 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004805}
4806
4807static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808compiler_handle_subscr(struct compiler *c, const char *kind,
4809 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 /* XXX this code is duplicated */
4814 switch (ctx) {
4815 case AugLoad: /* fall through to Load */
4816 case Load: op = BINARY_SUBSCR; break;
4817 case AugStore:/* fall through to Store */
4818 case Store: op = STORE_SUBSCR; break;
4819 case Del: op = DELETE_SUBSCR; break;
4820 case Param:
4821 PyErr_Format(PyExc_SystemError,
4822 "invalid %s kind %d in subscript\n",
4823 kind, ctx);
4824 return 0;
4825 }
4826 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004827 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 }
4829 else if (ctx == AugStore) {
4830 ADDOP(c, ROT_THREE);
4831 }
4832 ADDOP(c, op);
4833 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004834}
4835
4836static int
4837compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 int n = 2;
4840 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 /* only handles the cases where BUILD_SLICE is emitted */
4843 if (s->v.Slice.lower) {
4844 VISIT(c, expr, s->v.Slice.lower);
4845 }
4846 else {
4847 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 if (s->v.Slice.upper) {
4851 VISIT(c, expr, s->v.Slice.upper);
4852 }
4853 else {
4854 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4855 }
4856
4857 if (s->v.Slice.step) {
4858 n++;
4859 VISIT(c, expr, s->v.Slice.step);
4860 }
4861 ADDOP_I(c, BUILD_SLICE, n);
4862 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004863}
4864
4865static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4867 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 switch (s->kind) {
4870 case Slice_kind:
4871 return compiler_slice(c, s, ctx);
4872 case Index_kind:
4873 VISIT(c, expr, s->v.Index.value);
4874 break;
4875 case ExtSlice_kind:
4876 default:
4877 PyErr_SetString(PyExc_SystemError,
4878 "extended slice invalid in nested slice");
4879 return 0;
4880 }
4881 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004882}
4883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004884static int
4885compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4886{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004887 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 switch (s->kind) {
4889 case Index_kind:
4890 kindname = "index";
4891 if (ctx != AugStore) {
4892 VISIT(c, expr, s->v.Index.value);
4893 }
4894 break;
4895 case Slice_kind:
4896 kindname = "slice";
4897 if (ctx != AugStore) {
4898 if (!compiler_slice(c, s, ctx))
4899 return 0;
4900 }
4901 break;
4902 case ExtSlice_kind:
4903 kindname = "extended slice";
4904 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004905 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 for (i = 0; i < n; i++) {
4907 slice_ty sub = (slice_ty)asdl_seq_GET(
4908 s->v.ExtSlice.dims, i);
4909 if (!compiler_visit_nested_slice(c, sub, ctx))
4910 return 0;
4911 }
4912 ADDOP_I(c, BUILD_TUPLE, n);
4913 }
4914 break;
4915 default:
4916 PyErr_Format(PyExc_SystemError,
4917 "invalid subscript kind %d", s->kind);
4918 return 0;
4919 }
4920 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004921}
4922
Thomas Wouters89f507f2006-12-13 04:49:30 +00004923/* End of the compiler section, beginning of the assembler section */
4924
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004925/* do depth-first search of basic block graph, starting with block.
4926 post records the block indices in post-order.
4927
4928 XXX must handle implicit jumps from one block to next
4929*/
4930
Thomas Wouters89f507f2006-12-13 04:49:30 +00004931struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 PyObject *a_bytecode; /* string containing bytecode */
4933 int a_offset; /* offset into bytecode */
4934 int a_nblocks; /* number of reachable blocks */
4935 basicblock **a_postorder; /* list of blocks in dfs postorder */
4936 PyObject *a_lnotab; /* string containing lnotab */
4937 int a_lnotab_off; /* offset into lnotab */
4938 int a_lineno; /* last lineno of emitted instruction */
4939 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004940};
4941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004942static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004943dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004945 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004946
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004947 /* Get rid of recursion for normal control flow.
4948 Since the number of blocks is limited, unused space in a_postorder
4949 (from a_nblocks to end) can be used as a stack for still not ordered
4950 blocks. */
4951 for (j = end; b && !b->b_seen; b = b->b_next) {
4952 b->b_seen = 1;
4953 assert(a->a_nblocks < j);
4954 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004956 while (j < end) {
4957 b = a->a_postorder[j++];
4958 for (i = 0; i < b->b_iused; i++) {
4959 struct instr *instr = &b->b_instr[i];
4960 if (instr->i_jrel || instr->i_jabs)
4961 dfs(c, instr->i_target, a, j);
4962 }
4963 assert(a->a_nblocks < j);
4964 a->a_postorder[a->a_nblocks++] = b;
4965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004966}
4967
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004968Py_LOCAL_INLINE(void)
4969stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004970{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004971 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004972 if (b->b_startdepth < depth) {
4973 assert(b->b_startdepth < 0);
4974 b->b_startdepth = depth;
4975 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004976 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004977}
4978
4979/* Find the flow path that needs the largest stack. We assume that
4980 * cycles in the flow graph have no net effect on the stack depth.
4981 */
4982static int
4983stackdepth(struct compiler *c)
4984{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004985 basicblock *b, *entryblock = NULL;
4986 basicblock **stack, **sp;
4987 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 b->b_startdepth = INT_MIN;
4990 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004991 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 }
4993 if (!entryblock)
4994 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004995 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
4996 if (!stack) {
4997 PyErr_NoMemory();
4998 return -1;
4999 }
5000
5001 sp = stack;
5002 stackdepth_push(&sp, entryblock, 0);
5003 while (sp != stack) {
5004 b = *--sp;
5005 int depth = b->b_startdepth;
5006 assert(depth >= 0);
5007 basicblock *next = b->b_next;
5008 for (int i = 0; i < b->b_iused; i++) {
5009 struct instr *instr = &b->b_instr[i];
5010 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5011 if (effect == PY_INVALID_STACK_EFFECT) {
5012 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5013 Py_FatalError("PyCompile_OpcodeStackEffect()");
5014 }
5015 int new_depth = depth + effect;
5016 if (new_depth > maxdepth) {
5017 maxdepth = new_depth;
5018 }
5019 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5020 if (instr->i_jrel || instr->i_jabs) {
5021 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5022 assert(effect != PY_INVALID_STACK_EFFECT);
5023 int target_depth = depth + effect;
5024 if (target_depth > maxdepth) {
5025 maxdepth = target_depth;
5026 }
5027 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005028 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005029 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005030 assert(instr->i_target->b_startdepth >= target_depth);
5031 depth = new_depth;
5032 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005033 }
5034 stackdepth_push(&sp, instr->i_target, target_depth);
5035 }
5036 depth = new_depth;
5037 if (instr->i_opcode == JUMP_ABSOLUTE ||
5038 instr->i_opcode == JUMP_FORWARD ||
5039 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005040 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005041 {
5042 /* remaining code is dead */
5043 next = NULL;
5044 break;
5045 }
5046 }
5047 if (next != NULL) {
5048 stackdepth_push(&sp, next, depth);
5049 }
5050 }
5051 PyObject_Free(stack);
5052 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005053}
5054
5055static int
5056assemble_init(struct assembler *a, int nblocks, int firstlineno)
5057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 memset(a, 0, sizeof(struct assembler));
5059 a->a_lineno = firstlineno;
5060 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5061 if (!a->a_bytecode)
5062 return 0;
5063 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5064 if (!a->a_lnotab)
5065 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005066 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 PyErr_NoMemory();
5068 return 0;
5069 }
5070 a->a_postorder = (basicblock **)PyObject_Malloc(
5071 sizeof(basicblock *) * nblocks);
5072 if (!a->a_postorder) {
5073 PyErr_NoMemory();
5074 return 0;
5075 }
5076 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005077}
5078
5079static void
5080assemble_free(struct assembler *a)
5081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 Py_XDECREF(a->a_bytecode);
5083 Py_XDECREF(a->a_lnotab);
5084 if (a->a_postorder)
5085 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005086}
5087
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005088static int
5089blocksize(basicblock *b)
5090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 int i;
5092 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005095 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005097}
5098
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005099/* Appends a pair to the end of the line number table, a_lnotab, representing
5100 the instruction's bytecode offset and line number. See
5101 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005102
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005103static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005104assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005107 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005109
Serhiy Storchakaab874002016-09-11 13:48:15 +03005110 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 if(d_bytecode == 0 && d_lineno == 0)
5116 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 if (d_bytecode > 255) {
5119 int j, nbytes, ncodes = d_bytecode / 255;
5120 nbytes = a->a_lnotab_off + 2 * ncodes;
5121 len = PyBytes_GET_SIZE(a->a_lnotab);
5122 if (nbytes >= len) {
5123 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5124 len = nbytes;
5125 else if (len <= INT_MAX / 2)
5126 len *= 2;
5127 else {
5128 PyErr_NoMemory();
5129 return 0;
5130 }
5131 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5132 return 0;
5133 }
5134 lnotab = (unsigned char *)
5135 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5136 for (j = 0; j < ncodes; j++) {
5137 *lnotab++ = 255;
5138 *lnotab++ = 0;
5139 }
5140 d_bytecode -= ncodes * 255;
5141 a->a_lnotab_off += ncodes * 2;
5142 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005143 assert(0 <= d_bytecode && d_bytecode <= 255);
5144
5145 if (d_lineno < -128 || 127 < d_lineno) {
5146 int j, nbytes, ncodes, k;
5147 if (d_lineno < 0) {
5148 k = -128;
5149 /* use division on positive numbers */
5150 ncodes = (-d_lineno) / 128;
5151 }
5152 else {
5153 k = 127;
5154 ncodes = d_lineno / 127;
5155 }
5156 d_lineno -= ncodes * k;
5157 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 nbytes = a->a_lnotab_off + 2 * ncodes;
5159 len = PyBytes_GET_SIZE(a->a_lnotab);
5160 if (nbytes >= len) {
5161 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5162 len = nbytes;
5163 else if (len <= INT_MAX / 2)
5164 len *= 2;
5165 else {
5166 PyErr_NoMemory();
5167 return 0;
5168 }
5169 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5170 return 0;
5171 }
5172 lnotab = (unsigned char *)
5173 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5174 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005175 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 d_bytecode = 0;
5177 for (j = 1; j < ncodes; j++) {
5178 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005179 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 a->a_lnotab_off += ncodes * 2;
5182 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005183 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 len = PyBytes_GET_SIZE(a->a_lnotab);
5186 if (a->a_lnotab_off + 2 >= len) {
5187 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5188 return 0;
5189 }
5190 lnotab = (unsigned char *)
5191 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 a->a_lnotab_off += 2;
5194 if (d_bytecode) {
5195 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005196 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 }
5198 else { /* First line of a block; def stmt, etc. */
5199 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005200 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 }
5202 a->a_lineno = i->i_lineno;
5203 a->a_lineno_off = a->a_offset;
5204 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005205}
5206
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005207/* assemble_emit()
5208 Extend the bytecode with a new instruction.
5209 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005210*/
5211
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005212static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005213assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005214{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005215 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005217 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005218
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005219 arg = i->i_oparg;
5220 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 if (i->i_lineno && !assemble_lnotab(a, i))
5222 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005223 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 if (len > PY_SSIZE_T_MAX / 2)
5225 return 0;
5226 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5227 return 0;
5228 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005229 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005231 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005233}
5234
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005235static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005236assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005239 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 /* Compute the size of each block and fixup jump args.
5243 Replace block pointer with position in bytecode. */
5244 do {
5245 totsize = 0;
5246 for (i = a->a_nblocks - 1; i >= 0; i--) {
5247 b = a->a_postorder[i];
5248 bsize = blocksize(b);
5249 b->b_offset = totsize;
5250 totsize += bsize;
5251 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005252 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5254 bsize = b->b_offset;
5255 for (i = 0; i < b->b_iused; i++) {
5256 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005257 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 /* Relative jumps are computed relative to
5259 the instruction pointer after fetching
5260 the jump instruction.
5261 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005262 bsize += isize;
5263 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005265 if (instr->i_jrel) {
5266 instr->i_oparg -= bsize;
5267 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005268 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005269 if (instrsize(instr->i_oparg) != isize) {
5270 extended_arg_recompile = 1;
5271 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 }
5274 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 /* XXX: This is an awful hack that could hurt performance, but
5277 on the bright side it should work until we come up
5278 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 The issue is that in the first loop blocksize() is called
5281 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005282 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 So we loop until we stop seeing new EXTENDED_ARGs.
5286 The only EXTENDED_ARGs that could be popping up are
5287 ones in jump instructions. So this should converge
5288 fairly quickly.
5289 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005290 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005291}
5292
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005293static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005294dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005297 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 tuple = PyTuple_New(size);
5300 if (tuple == NULL)
5301 return NULL;
5302 while (PyDict_Next(dict, &pos, &k, &v)) {
5303 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005304 /* The keys of the dictionary are tuples. (see compiler_add_o
5305 * and _PyCode_ConstantKey). The object we want is always second,
5306 * though. */
5307 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 Py_INCREF(k);
5309 assert((i - offset) < size);
5310 assert((i - offset) >= 0);
5311 PyTuple_SET_ITEM(tuple, i - offset, k);
5312 }
5313 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005314}
5315
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005316static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005320 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005322 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 if (ste->ste_nested)
5324 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005325 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005327 if (!ste->ste_generator && ste->ste_coroutine)
5328 flags |= CO_COROUTINE;
5329 if (ste->ste_generator && ste->ste_coroutine)
5330 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 if (ste->ste_varargs)
5332 flags |= CO_VARARGS;
5333 if (ste->ste_varkeywords)
5334 flags |= CO_VARKEYWORDS;
5335 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 /* (Only) inherit compilerflags in PyCF_MASK */
5338 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005341}
5342
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005343static PyCodeObject *
5344makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 PyObject *tmp;
5347 PyCodeObject *co = NULL;
5348 PyObject *consts = NULL;
5349 PyObject *names = NULL;
5350 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 PyObject *name = NULL;
5352 PyObject *freevars = NULL;
5353 PyObject *cellvars = NULL;
5354 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005355 Py_ssize_t nlocals;
5356 int nlocals_int;
5357 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005358 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 tmp = dict_keys_inorder(c->u->u_consts, 0);
5361 if (!tmp)
5362 goto error;
5363 consts = PySequence_List(tmp); /* optimize_code requires a list */
5364 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 names = dict_keys_inorder(c->u->u_names, 0);
5367 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5368 if (!consts || !names || !varnames)
5369 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5372 if (!cellvars)
5373 goto error;
5374 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5375 if (!freevars)
5376 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005377
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005378 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005379 assert(nlocals < INT_MAX);
5380 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 flags = compute_code_flags(c);
5383 if (flags < 0)
5384 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5387 if (!bytecode)
5388 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5391 if (!tmp)
5392 goto error;
5393 Py_DECREF(consts);
5394 consts = tmp;
5395
Victor Stinnerf8e32212013-11-19 23:56:34 +01005396 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5397 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005398 maxdepth = stackdepth(c);
5399 if (maxdepth < 0) {
5400 goto error;
5401 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005402 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005403 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 bytecode, consts, names, varnames,
5405 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005406 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 c->u->u_firstlineno,
5408 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 Py_XDECREF(consts);
5411 Py_XDECREF(names);
5412 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 Py_XDECREF(name);
5414 Py_XDECREF(freevars);
5415 Py_XDECREF(cellvars);
5416 Py_XDECREF(bytecode);
5417 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005418}
5419
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005420
5421/* For debugging purposes only */
5422#if 0
5423static void
5424dump_instr(const struct instr *i)
5425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 const char *jrel = i->i_jrel ? "jrel " : "";
5427 const char *jabs = i->i_jabs ? "jabs " : "";
5428 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005431 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5435 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005436}
5437
5438static void
5439dump_basicblock(const basicblock *b)
5440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 const char *seen = b->b_seen ? "seen " : "";
5442 const char *b_return = b->b_return ? "return " : "";
5443 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5444 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5445 if (b->b_instr) {
5446 int i;
5447 for (i = 0; i < b->b_iused; i++) {
5448 fprintf(stderr, " [%02d] ", i);
5449 dump_instr(b->b_instr + i);
5450 }
5451 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005452}
5453#endif
5454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005455static PyCodeObject *
5456assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 basicblock *b, *entryblock;
5459 struct assembler a;
5460 int i, j, nblocks;
5461 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 /* Make sure every block that falls off the end returns None.
5464 XXX NEXT_BLOCK() isn't quite right, because if the last
5465 block ends with a jump or return b_next shouldn't set.
5466 */
5467 if (!c->u->u_curblock->b_return) {
5468 NEXT_BLOCK(c);
5469 if (addNone)
5470 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5471 ADDOP(c, RETURN_VALUE);
5472 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 nblocks = 0;
5475 entryblock = NULL;
5476 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5477 nblocks++;
5478 entryblock = b;
5479 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 /* Set firstlineno if it wasn't explicitly set. */
5482 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005483 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5485 else
5486 c->u->u_firstlineno = 1;
5487 }
5488 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5489 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005490 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 /* Can't modify the bytecode after computing jump offsets. */
5493 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 /* Emit code in reverse postorder from dfs. */
5496 for (i = a.a_nblocks - 1; i >= 0; i--) {
5497 b = a.a_postorder[i];
5498 for (j = 0; j < b->b_iused; j++)
5499 if (!assemble_emit(&a, &b->b_instr[j]))
5500 goto error;
5501 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5504 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005505 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005509 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 assemble_free(&a);
5511 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005512}
Georg Brandl8334fd92010-12-04 10:26:46 +00005513
5514#undef PyAST_Compile
5515PyAPI_FUNC(PyCodeObject *)
5516PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5517 PyArena *arena)
5518{
5519 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5520}