blob: 725bb9b213a262e5bcff16daa2375e80d8784e11 [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);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyObject *names = PyTuple_New(n);
2914 PyObject *level;
2915 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 if (!empty_string) {
2918 empty_string = PyUnicode_FromString("");
2919 if (!empty_string)
2920 return 0;
2921 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 if (!names)
2924 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 level = PyLong_FromLong(s->v.ImportFrom.level);
2927 if (!level) {
2928 Py_DECREF(names);
2929 return 0;
2930 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 /* build up the names */
2933 for (i = 0; i < n; i++) {
2934 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2935 Py_INCREF(alias->name);
2936 PyTuple_SET_ITEM(names, i, alias->name);
2937 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002940 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 Py_DECREF(level);
2942 Py_DECREF(names);
2943 return compiler_error(c, "from __future__ imports must occur "
2944 "at the beginning of the file");
2945 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 ADDOP_O(c, LOAD_CONST, level, consts);
2948 Py_DECREF(level);
2949 ADDOP_O(c, LOAD_CONST, names, consts);
2950 Py_DECREF(names);
2951 if (s->v.ImportFrom.module) {
2952 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2953 }
2954 else {
2955 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2956 }
2957 for (i = 0; i < n; i++) {
2958 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2959 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002961 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 assert(n == 1);
2963 ADDOP(c, IMPORT_STAR);
2964 return 1;
2965 }
2966
2967 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2968 store_name = alias->name;
2969 if (alias->asname)
2970 store_name = alias->asname;
2971
2972 if (!compiler_nameop(c, store_name, Store)) {
2973 Py_DECREF(names);
2974 return 0;
2975 }
2976 }
2977 /* remove imported module */
2978 ADDOP(c, POP_TOP);
2979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980}
2981
2982static int
2983compiler_assert(struct compiler *c, stmt_ty s)
2984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 static PyObject *assertion_error = NULL;
2986 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002987 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988
Georg Brandl8334fd92010-12-04 10:26:46 +00002989 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 return 1;
2991 if (assertion_error == NULL) {
2992 assertion_error = PyUnicode_InternFromString("AssertionError");
2993 if (assertion_error == NULL)
2994 return 0;
2995 }
2996 if (s->v.Assert.test->kind == Tuple_kind &&
2997 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002998 msg = PyUnicode_FromString("assertion is always true, "
2999 "perhaps remove parentheses?");
3000 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02003002 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
3003 c->c_filename, c->u->u_lineno,
3004 NULL, NULL) == -1) {
3005 Py_DECREF(msg);
3006 return 0;
3007 }
3008 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 end = compiler_new_block(c);
3011 if (end == NULL)
3012 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003013 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3014 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3016 if (s->v.Assert.msg) {
3017 VISIT(c, expr, s->v.Assert.msg);
3018 ADDOP_I(c, CALL_FUNCTION, 1);
3019 }
3020 ADDOP_I(c, RAISE_VARARGS, 1);
3021 compiler_use_next_block(c, end);
3022 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023}
3024
3025static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003026compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3027{
3028 if (c->c_interactive && c->c_nestlevel <= 1) {
3029 VISIT(c, expr, value);
3030 ADDOP(c, PRINT_EXPR);
3031 return 1;
3032 }
3033
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003034 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003035 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003036 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003037 }
3038
3039 VISIT(c, expr, value);
3040 ADDOP(c, POP_TOP);
3041 return 1;
3042}
3043
3044static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045compiler_visit_stmt(struct compiler *c, stmt_ty s)
3046{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003047 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 /* Always assign a lineno to the next instruction for a stmt. */
3050 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003051 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 switch (s->kind) {
3055 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003056 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 case ClassDef_kind:
3058 return compiler_class(c, s);
3059 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003060 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 case Delete_kind:
3062 VISIT_SEQ(c, expr, s->v.Delete.targets)
3063 break;
3064 case Assign_kind:
3065 n = asdl_seq_LEN(s->v.Assign.targets);
3066 VISIT(c, expr, s->v.Assign.value);
3067 for (i = 0; i < n; i++) {
3068 if (i < n - 1)
3069 ADDOP(c, DUP_TOP);
3070 VISIT(c, expr,
3071 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3072 }
3073 break;
3074 case AugAssign_kind:
3075 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003076 case AnnAssign_kind:
3077 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 case For_kind:
3079 return compiler_for(c, s);
3080 case While_kind:
3081 return compiler_while(c, s);
3082 case If_kind:
3083 return compiler_if(c, s);
3084 case Raise_kind:
3085 n = 0;
3086 if (s->v.Raise.exc) {
3087 VISIT(c, expr, s->v.Raise.exc);
3088 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003089 if (s->v.Raise.cause) {
3090 VISIT(c, expr, s->v.Raise.cause);
3091 n++;
3092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003094 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003096 case Try_kind:
3097 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 case Assert_kind:
3099 return compiler_assert(c, s);
3100 case Import_kind:
3101 return compiler_import(c, s);
3102 case ImportFrom_kind:
3103 return compiler_from_import(c, s);
3104 case Global_kind:
3105 case Nonlocal_kind:
3106 break;
3107 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003108 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 case Pass_kind:
3110 break;
3111 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003112 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 case Continue_kind:
3114 return compiler_continue(c);
3115 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003116 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003117 case AsyncFunctionDef_kind:
3118 return compiler_function(c, s, 1);
3119 case AsyncWith_kind:
3120 return compiler_async_with(c, s, 0);
3121 case AsyncFor_kind:
3122 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
Yury Selivanov75445082015-05-11 22:57:16 -04003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126}
3127
3128static int
3129unaryop(unaryop_ty op)
3130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 switch (op) {
3132 case Invert:
3133 return UNARY_INVERT;
3134 case Not:
3135 return UNARY_NOT;
3136 case UAdd:
3137 return UNARY_POSITIVE;
3138 case USub:
3139 return UNARY_NEGATIVE;
3140 default:
3141 PyErr_Format(PyExc_SystemError,
3142 "unary op %d should not be possible", op);
3143 return 0;
3144 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145}
3146
3147static int
3148binop(struct compiler *c, operator_ty op)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 switch (op) {
3151 case Add:
3152 return BINARY_ADD;
3153 case Sub:
3154 return BINARY_SUBTRACT;
3155 case Mult:
3156 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003157 case MatMult:
3158 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 case Div:
3160 return BINARY_TRUE_DIVIDE;
3161 case Mod:
3162 return BINARY_MODULO;
3163 case Pow:
3164 return BINARY_POWER;
3165 case LShift:
3166 return BINARY_LSHIFT;
3167 case RShift:
3168 return BINARY_RSHIFT;
3169 case BitOr:
3170 return BINARY_OR;
3171 case BitXor:
3172 return BINARY_XOR;
3173 case BitAnd:
3174 return BINARY_AND;
3175 case FloorDiv:
3176 return BINARY_FLOOR_DIVIDE;
3177 default:
3178 PyErr_Format(PyExc_SystemError,
3179 "binary op %d should not be possible", op);
3180 return 0;
3181 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182}
3183
3184static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185inplace_binop(struct compiler *c, operator_ty op)
3186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 switch (op) {
3188 case Add:
3189 return INPLACE_ADD;
3190 case Sub:
3191 return INPLACE_SUBTRACT;
3192 case Mult:
3193 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003194 case MatMult:
3195 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 case Div:
3197 return INPLACE_TRUE_DIVIDE;
3198 case Mod:
3199 return INPLACE_MODULO;
3200 case Pow:
3201 return INPLACE_POWER;
3202 case LShift:
3203 return INPLACE_LSHIFT;
3204 case RShift:
3205 return INPLACE_RSHIFT;
3206 case BitOr:
3207 return INPLACE_OR;
3208 case BitXor:
3209 return INPLACE_XOR;
3210 case BitAnd:
3211 return INPLACE_AND;
3212 case FloorDiv:
3213 return INPLACE_FLOOR_DIVIDE;
3214 default:
3215 PyErr_Format(PyExc_SystemError,
3216 "inplace binary op %d should not be possible", op);
3217 return 0;
3218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219}
3220
3221static int
3222compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3223{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003224 int op, scope;
3225 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 PyObject *dict = c->u->u_names;
3229 PyObject *mangled;
3230 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003231
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003232 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3233 !_PyUnicode_EqualToASCIIString(name, "True") &&
3234 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003235
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003236 mangled = _Py_Mangle(c->u->u_private, name);
3237 if (!mangled)
3238 return 0;
3239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 op = 0;
3241 optype = OP_NAME;
3242 scope = PyST_GetScope(c->u->u_ste, mangled);
3243 switch (scope) {
3244 case FREE:
3245 dict = c->u->u_freevars;
3246 optype = OP_DEREF;
3247 break;
3248 case CELL:
3249 dict = c->u->u_cellvars;
3250 optype = OP_DEREF;
3251 break;
3252 case LOCAL:
3253 if (c->u->u_ste->ste_type == FunctionBlock)
3254 optype = OP_FAST;
3255 break;
3256 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003257 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 optype = OP_GLOBAL;
3259 break;
3260 case GLOBAL_EXPLICIT:
3261 optype = OP_GLOBAL;
3262 break;
3263 default:
3264 /* scope can be 0 */
3265 break;
3266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003269 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 switch (optype) {
3272 case OP_DEREF:
3273 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003274 case Load:
3275 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3276 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 case Store: op = STORE_DEREF; break;
3278 case AugLoad:
3279 case AugStore:
3280 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003281 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 case Param:
3283 default:
3284 PyErr_SetString(PyExc_SystemError,
3285 "param invalid for deref variable");
3286 return 0;
3287 }
3288 break;
3289 case OP_FAST:
3290 switch (ctx) {
3291 case Load: op = LOAD_FAST; break;
3292 case Store: op = STORE_FAST; break;
3293 case Del: op = DELETE_FAST; break;
3294 case AugLoad:
3295 case AugStore:
3296 break;
3297 case Param:
3298 default:
3299 PyErr_SetString(PyExc_SystemError,
3300 "param invalid for local variable");
3301 return 0;
3302 }
3303 ADDOP_O(c, op, mangled, varnames);
3304 Py_DECREF(mangled);
3305 return 1;
3306 case OP_GLOBAL:
3307 switch (ctx) {
3308 case Load: op = LOAD_GLOBAL; break;
3309 case Store: op = STORE_GLOBAL; break;
3310 case Del: op = DELETE_GLOBAL; break;
3311 case AugLoad:
3312 case AugStore:
3313 break;
3314 case Param:
3315 default:
3316 PyErr_SetString(PyExc_SystemError,
3317 "param invalid for global variable");
3318 return 0;
3319 }
3320 break;
3321 case OP_NAME:
3322 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003323 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 case Store: op = STORE_NAME; break;
3325 case Del: op = DELETE_NAME; break;
3326 case AugLoad:
3327 case AugStore:
3328 break;
3329 case Param:
3330 default:
3331 PyErr_SetString(PyExc_SystemError,
3332 "param invalid for name variable");
3333 return 0;
3334 }
3335 break;
3336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 assert(op);
3339 arg = compiler_add_o(c, dict, mangled);
3340 Py_DECREF(mangled);
3341 if (arg < 0)
3342 return 0;
3343 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344}
3345
3346static int
3347compiler_boolop(struct compiler *c, expr_ty e)
3348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003350 int jumpi;
3351 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 assert(e->kind == BoolOp_kind);
3355 if (e->v.BoolOp.op == And)
3356 jumpi = JUMP_IF_FALSE_OR_POP;
3357 else
3358 jumpi = JUMP_IF_TRUE_OR_POP;
3359 end = compiler_new_block(c);
3360 if (end == NULL)
3361 return 0;
3362 s = e->v.BoolOp.values;
3363 n = asdl_seq_LEN(s) - 1;
3364 assert(n >= 0);
3365 for (i = 0; i < n; ++i) {
3366 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3367 ADDOP_JABS(c, jumpi, end);
3368 }
3369 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3370 compiler_use_next_block(c, end);
3371 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372}
3373
3374static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003375starunpack_helper(struct compiler *c, asdl_seq *elts,
3376 int single_op, int inner_op, int outer_op)
3377{
3378 Py_ssize_t n = asdl_seq_LEN(elts);
3379 Py_ssize_t i, nsubitems = 0, nseen = 0;
3380 for (i = 0; i < n; i++) {
3381 expr_ty elt = asdl_seq_GET(elts, i);
3382 if (elt->kind == Starred_kind) {
3383 if (nseen) {
3384 ADDOP_I(c, inner_op, nseen);
3385 nseen = 0;
3386 nsubitems++;
3387 }
3388 VISIT(c, expr, elt->v.Starred.value);
3389 nsubitems++;
3390 }
3391 else {
3392 VISIT(c, expr, elt);
3393 nseen++;
3394 }
3395 }
3396 if (nsubitems) {
3397 if (nseen) {
3398 ADDOP_I(c, inner_op, nseen);
3399 nsubitems++;
3400 }
3401 ADDOP_I(c, outer_op, nsubitems);
3402 }
3403 else
3404 ADDOP_I(c, single_op, nseen);
3405 return 1;
3406}
3407
3408static int
3409assignment_helper(struct compiler *c, asdl_seq *elts)
3410{
3411 Py_ssize_t n = asdl_seq_LEN(elts);
3412 Py_ssize_t i;
3413 int seen_star = 0;
3414 for (i = 0; i < n; i++) {
3415 expr_ty elt = asdl_seq_GET(elts, i);
3416 if (elt->kind == Starred_kind && !seen_star) {
3417 if ((i >= (1 << 8)) ||
3418 (n-i-1 >= (INT_MAX >> 8)))
3419 return compiler_error(c,
3420 "too many expressions in "
3421 "star-unpacking assignment");
3422 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3423 seen_star = 1;
3424 asdl_seq_SET(elts, i, elt->v.Starred.value);
3425 }
3426 else if (elt->kind == Starred_kind) {
3427 return compiler_error(c,
3428 "two starred expressions in assignment");
3429 }
3430 }
3431 if (!seen_star) {
3432 ADDOP_I(c, UNPACK_SEQUENCE, n);
3433 }
3434 VISIT_SEQ(c, expr, elts);
3435 return 1;
3436}
3437
3438static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439compiler_list(struct compiler *c, expr_ty e)
3440{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003441 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003443 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003445 else if (e->v.List.ctx == Load) {
3446 return starunpack_helper(c, elts,
3447 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003449 else
3450 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452}
3453
3454static int
3455compiler_tuple(struct compiler *c, expr_ty e)
3456{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003457 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003459 return assignment_helper(c, elts);
3460 }
3461 else if (e->v.Tuple.ctx == Load) {
3462 return starunpack_helper(c, elts,
3463 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3464 }
3465 else
3466 VISIT_SEQ(c, expr, elts);
3467 return 1;
3468}
3469
3470static int
3471compiler_set(struct compiler *c, expr_ty e)
3472{
3473 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3474 BUILD_SET, BUILD_SET_UNPACK);
3475}
3476
3477static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003478are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3479{
3480 Py_ssize_t i;
3481 for (i = begin; i < end; i++) {
3482 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3483 if (key == NULL || !is_const(key))
3484 return 0;
3485 }
3486 return 1;
3487}
3488
3489static int
3490compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3491{
3492 Py_ssize_t i, n = end - begin;
3493 PyObject *keys, *key;
3494 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3495 for (i = begin; i < end; i++) {
3496 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3497 }
3498 keys = PyTuple_New(n);
3499 if (keys == NULL) {
3500 return 0;
3501 }
3502 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003503 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003504 Py_INCREF(key);
3505 PyTuple_SET_ITEM(keys, i - begin, key);
3506 }
3507 ADDOP_N(c, LOAD_CONST, keys, consts);
3508 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3509 }
3510 else {
3511 for (i = begin; i < end; i++) {
3512 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3513 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3514 }
3515 ADDOP_I(c, BUILD_MAP, n);
3516 }
3517 return 1;
3518}
3519
3520static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003521compiler_dict(struct compiler *c, expr_ty e)
3522{
Victor Stinner976bb402016-03-23 11:36:19 +01003523 Py_ssize_t i, n, elements;
3524 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003525 int is_unpacking = 0;
3526 n = asdl_seq_LEN(e->v.Dict.values);
3527 containers = 0;
3528 elements = 0;
3529 for (i = 0; i < n; i++) {
3530 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3531 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003532 if (!compiler_subdict(c, e, i - elements, i))
3533 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003534 containers++;
3535 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537 if (is_unpacking) {
3538 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3539 containers++;
3540 }
3541 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003542 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 }
3544 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003545 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003546 if (!compiler_subdict(c, e, n - elements, n))
3547 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003548 containers++;
3549 }
3550 /* If there is more than one dict, they need to be merged into a new
3551 * dict. If there is one dict and it's an unpacking, then it needs
3552 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003553 if (containers > 1 || is_unpacking) {
3554 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 }
3556 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557}
3558
3559static int
3560compiler_compare(struct compiler *c, expr_ty e)
3561{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003562 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003565 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3566 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3567 if (n == 0) {
3568 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3569 ADDOP_I(c, COMPARE_OP,
3570 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3571 }
3572 else {
3573 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 if (cleanup == NULL)
3575 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003576 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 VISIT(c, expr,
3578 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003579 ADDOP(c, DUP_TOP);
3580 ADDOP(c, ROT_THREE);
3581 ADDOP_I(c, COMPARE_OP,
3582 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3583 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3584 NEXT_BLOCK(c);
3585 }
3586 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3587 ADDOP_I(c, COMPARE_OP,
3588 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 basicblock *end = compiler_new_block(c);
3590 if (end == NULL)
3591 return 0;
3592 ADDOP_JREL(c, JUMP_FORWARD, end);
3593 compiler_use_next_block(c, cleanup);
3594 ADDOP(c, ROT_TWO);
3595 ADDOP(c, POP_TOP);
3596 compiler_use_next_block(c, end);
3597 }
3598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599}
3600
3601static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003602maybe_optimize_method_call(struct compiler *c, expr_ty e)
3603{
3604 Py_ssize_t argsl, i;
3605 expr_ty meth = e->v.Call.func;
3606 asdl_seq *args = e->v.Call.args;
3607
3608 /* Check that the call node is an attribute access, and that
3609 the call doesn't have keyword parameters. */
3610 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3611 asdl_seq_LEN(e->v.Call.keywords))
3612 return -1;
3613
3614 /* Check that there are no *varargs types of arguments. */
3615 argsl = asdl_seq_LEN(args);
3616 for (i = 0; i < argsl; i++) {
3617 expr_ty elt = asdl_seq_GET(args, i);
3618 if (elt->kind == Starred_kind) {
3619 return -1;
3620 }
3621 }
3622
3623 /* Alright, we can optimize the code. */
3624 VISIT(c, expr, meth->v.Attribute.value);
3625 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3626 VISIT_SEQ(c, expr, e->v.Call.args);
3627 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3628 return 1;
3629}
3630
3631static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632compiler_call(struct compiler *c, expr_ty e)
3633{
Yury Selivanovf2392132016-12-13 19:03:51 -05003634 if (maybe_optimize_method_call(c, e) > 0)
3635 return 1;
3636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 VISIT(c, expr, e->v.Call.func);
3638 return compiler_call_helper(c, 0,
3639 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003640 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003641}
3642
Eric V. Smith235a6f02015-09-19 14:51:32 -04003643static int
3644compiler_joined_str(struct compiler *c, expr_ty e)
3645{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003646 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003647 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3648 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003649 return 1;
3650}
3651
Eric V. Smitha78c7952015-11-03 12:45:05 -05003652/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003653static int
3654compiler_formatted_value(struct compiler *c, expr_ty e)
3655{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003656 /* Our oparg encodes 2 pieces of information: the conversion
3657 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003658
Eric V. Smitha78c7952015-11-03 12:45:05 -05003659 Convert the conversion char to 2 bits:
3660 None: 000 0x0 FVC_NONE
3661 !s : 001 0x1 FVC_STR
3662 !r : 010 0x2 FVC_REPR
3663 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003664
Eric V. Smitha78c7952015-11-03 12:45:05 -05003665 next bit is whether or not we have a format spec:
3666 yes : 100 0x4
3667 no : 000 0x0
3668 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003669
Eric V. Smitha78c7952015-11-03 12:45:05 -05003670 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003671
Eric V. Smitha78c7952015-11-03 12:45:05 -05003672 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003673 VISIT(c, expr, e->v.FormattedValue.value);
3674
Eric V. Smitha78c7952015-11-03 12:45:05 -05003675 switch (e->v.FormattedValue.conversion) {
3676 case 's': oparg = FVC_STR; break;
3677 case 'r': oparg = FVC_REPR; break;
3678 case 'a': oparg = FVC_ASCII; break;
3679 case -1: oparg = FVC_NONE; break;
3680 default:
3681 PyErr_SetString(PyExc_SystemError,
3682 "Unrecognized conversion character");
3683 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003684 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003685 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003686 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003687 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003688 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003689 }
3690
Eric V. Smitha78c7952015-11-03 12:45:05 -05003691 /* And push our opcode and oparg */
3692 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003693 return 1;
3694}
3695
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003696static int
3697compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3698{
3699 Py_ssize_t i, n = end - begin;
3700 keyword_ty kw;
3701 PyObject *keys, *key;
3702 assert(n > 0);
3703 if (n > 1) {
3704 for (i = begin; i < end; i++) {
3705 kw = asdl_seq_GET(keywords, i);
3706 VISIT(c, expr, kw->value);
3707 }
3708 keys = PyTuple_New(n);
3709 if (keys == NULL) {
3710 return 0;
3711 }
3712 for (i = begin; i < end; i++) {
3713 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3714 Py_INCREF(key);
3715 PyTuple_SET_ITEM(keys, i - begin, key);
3716 }
3717 ADDOP_N(c, LOAD_CONST, keys, consts);
3718 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3719 }
3720 else {
3721 /* a for loop only executes once */
3722 for (i = begin; i < end; i++) {
3723 kw = asdl_seq_GET(keywords, i);
3724 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3725 VISIT(c, expr, kw->value);
3726 }
3727 ADDOP_I(c, BUILD_MAP, n);
3728 }
3729 return 1;
3730}
3731
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003732/* shared code between compiler_call and compiler_class */
3733static int
3734compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003735 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003736 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003738{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003739 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003740 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003741
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003742 /* the number of tuples and dictionaries on the stack */
3743 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3744
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003745 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003746 nkwelts = asdl_seq_LEN(keywords);
3747
3748 for (i = 0; i < nkwelts; i++) {
3749 keyword_ty kw = asdl_seq_GET(keywords, i);
3750 if (kw->arg == NULL) {
3751 mustdictunpack = 1;
3752 break;
3753 }
3754 }
3755
3756 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003757 for (i = 0; i < nelts; i++) {
3758 expr_ty elt = asdl_seq_GET(args, i);
3759 if (elt->kind == Starred_kind) {
3760 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003761 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 if (nseen) {
3763 ADDOP_I(c, BUILD_TUPLE, nseen);
3764 nseen = 0;
3765 nsubargs++;
3766 }
3767 VISIT(c, expr, elt->v.Starred.value);
3768 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769 }
3770 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003771 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003772 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003775
3776 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003777 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003778 if (nseen) {
3779 /* Pack up any trailing positional arguments. */
3780 ADDOP_I(c, BUILD_TUPLE, nseen);
3781 nsubargs++;
3782 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003783 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003784 /* If we ended up with more than one stararg, we need
3785 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003786 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003787 }
3788 else if (nsubargs == 0) {
3789 ADDOP_I(c, BUILD_TUPLE, 0);
3790 }
3791 nseen = 0; /* the number of keyword arguments on the stack following */
3792 for (i = 0; i < nkwelts; i++) {
3793 keyword_ty kw = asdl_seq_GET(keywords, i);
3794 if (kw->arg == NULL) {
3795 /* A keyword argument unpacking. */
3796 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003797 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3798 return 0;
3799 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003800 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003801 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003802 VISIT(c, expr, kw->value);
3803 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003804 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003805 else {
3806 nseen++;
3807 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003808 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003809 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003810 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003811 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003812 return 0;
3813 nsubkwargs++;
3814 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003815 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003816 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003817 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003819 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3820 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003822 else if (nkwelts) {
3823 PyObject *names;
3824 VISIT_SEQ(c, keyword, keywords);
3825 names = PyTuple_New(nkwelts);
3826 if (names == NULL) {
3827 return 0;
3828 }
3829 for (i = 0; i < nkwelts; i++) {
3830 keyword_ty kw = asdl_seq_GET(keywords, i);
3831 Py_INCREF(kw->arg);
3832 PyTuple_SET_ITEM(names, i, kw->arg);
3833 }
3834 ADDOP_N(c, LOAD_CONST, names, consts);
3835 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3836 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003838 else {
3839 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3840 return 1;
3841 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842}
3843
Nick Coghlan650f0d02007-04-15 12:05:43 +00003844
3845/* List and set comprehensions and generator expressions work by creating a
3846 nested function to perform the actual iteration. This means that the
3847 iteration variables don't leak into the current scope.
3848 The defined function is called immediately following its definition, with the
3849 result of that call being the result of the expression.
3850 The LC/SC version returns the populated container, while the GE version is
3851 flagged in symtable.c as a generator, so it returns the generator object
3852 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003853
3854 Possible cleanups:
3855 - iterate over the generator sequence instead of using recursion
3856*/
3857
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860compiler_comprehension_generator(struct compiler *c,
3861 asdl_seq *generators, int gen_index,
3862 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003864 comprehension_ty gen;
3865 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3866 if (gen->is_async) {
3867 return compiler_async_comprehension_generator(
3868 c, generators, gen_index, elt, val, type);
3869 } else {
3870 return compiler_sync_comprehension_generator(
3871 c, generators, gen_index, elt, val, type);
3872 }
3873}
3874
3875static int
3876compiler_sync_comprehension_generator(struct compiler *c,
3877 asdl_seq *generators, int gen_index,
3878 expr_ty elt, expr_ty val, int type)
3879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 /* generate code for the iterator, then each of the ifs,
3881 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 comprehension_ty gen;
3884 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003885 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 start = compiler_new_block(c);
3888 skip = compiler_new_block(c);
3889 if_cleanup = compiler_new_block(c);
3890 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3893 anchor == NULL)
3894 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 if (gen_index == 0) {
3899 /* Receive outermost iter as an implicit argument */
3900 c->u->u_argcount = 1;
3901 ADDOP_I(c, LOAD_FAST, 0);
3902 }
3903 else {
3904 /* Sub-iter - calculate on the fly */
3905 VISIT(c, expr, gen->iter);
3906 ADDOP(c, GET_ITER);
3907 }
3908 compiler_use_next_block(c, start);
3909 ADDOP_JREL(c, FOR_ITER, anchor);
3910 NEXT_BLOCK(c);
3911 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 /* XXX this needs to be cleaned up...a lot! */
3914 n = asdl_seq_LEN(gen->ifs);
3915 for (i = 0; i < n; i++) {
3916 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003917 if (!compiler_jump_if(c, e, if_cleanup, 0))
3918 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 NEXT_BLOCK(c);
3920 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 if (++gen_index < asdl_seq_LEN(generators))
3923 if (!compiler_comprehension_generator(c,
3924 generators, gen_index,
3925 elt, val, type))
3926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 /* only append after the last for generator */
3929 if (gen_index >= asdl_seq_LEN(generators)) {
3930 /* comprehension specific code */
3931 switch (type) {
3932 case COMP_GENEXP:
3933 VISIT(c, expr, elt);
3934 ADDOP(c, YIELD_VALUE);
3935 ADDOP(c, POP_TOP);
3936 break;
3937 case COMP_LISTCOMP:
3938 VISIT(c, expr, elt);
3939 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3940 break;
3941 case COMP_SETCOMP:
3942 VISIT(c, expr, elt);
3943 ADDOP_I(c, SET_ADD, gen_index + 1);
3944 break;
3945 case COMP_DICTCOMP:
3946 /* With 'd[k] = v', v is evaluated before k, so we do
3947 the same. */
3948 VISIT(c, expr, val);
3949 VISIT(c, expr, elt);
3950 ADDOP_I(c, MAP_ADD, gen_index + 1);
3951 break;
3952 default:
3953 return 0;
3954 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 compiler_use_next_block(c, skip);
3957 }
3958 compiler_use_next_block(c, if_cleanup);
3959 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3960 compiler_use_next_block(c, anchor);
3961
3962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003963}
3964
3965static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966compiler_async_comprehension_generator(struct compiler *c,
3967 asdl_seq *generators, int gen_index,
3968 expr_ty elt, expr_ty val, int type)
3969{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003970 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003971 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003973 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003974 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003975 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003976
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003977 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003978 return 0;
3979 }
3980
3981 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3982
3983 if (gen_index == 0) {
3984 /* Receive outermost iter as an implicit argument */
3985 c->u->u_argcount = 1;
3986 ADDOP_I(c, LOAD_FAST, 0);
3987 }
3988 else {
3989 /* Sub-iter - calculate on the fly */
3990 VISIT(c, expr, gen->iter);
3991 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003992 }
3993
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003994 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003995
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003996 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003997 ADDOP(c, GET_ANEXT);
3998 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3999 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004000 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004001 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004002
4003 n = asdl_seq_LEN(gen->ifs);
4004 for (i = 0; i < n; i++) {
4005 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004006 if (!compiler_jump_if(c, e, if_cleanup, 0))
4007 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004008 NEXT_BLOCK(c);
4009 }
4010
4011 if (++gen_index < asdl_seq_LEN(generators))
4012 if (!compiler_comprehension_generator(c,
4013 generators, gen_index,
4014 elt, val, type))
4015 return 0;
4016
4017 /* only append after the last for generator */
4018 if (gen_index >= asdl_seq_LEN(generators)) {
4019 /* comprehension specific code */
4020 switch (type) {
4021 case COMP_GENEXP:
4022 VISIT(c, expr, elt);
4023 ADDOP(c, YIELD_VALUE);
4024 ADDOP(c, POP_TOP);
4025 break;
4026 case COMP_LISTCOMP:
4027 VISIT(c, expr, elt);
4028 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4029 break;
4030 case COMP_SETCOMP:
4031 VISIT(c, expr, elt);
4032 ADDOP_I(c, SET_ADD, gen_index + 1);
4033 break;
4034 case COMP_DICTCOMP:
4035 /* With 'd[k] = v', v is evaluated before k, so we do
4036 the same. */
4037 VISIT(c, expr, val);
4038 VISIT(c, expr, elt);
4039 ADDOP_I(c, MAP_ADD, gen_index + 1);
4040 break;
4041 default:
4042 return 0;
4043 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004044 }
4045 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004046 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4047
4048 compiler_use_next_block(c, except);
4049 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004050
4051 return 1;
4052}
4053
4054static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004055compiler_comprehension(struct compiler *c, expr_ty e, int type,
4056 identifier name, asdl_seq *generators, expr_ty elt,
4057 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004060 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004061 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004062 int is_async_function = c->u->u_ste->ste_coroutine;
4063 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004064
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004065 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004066
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004067 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4068 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004069 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004071 }
4072
4073 is_async_generator = c->u->u_ste->ste_coroutine;
4074
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004075 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004076 if (e->lineno > c->u->u_lineno) {
4077 c->u->u_lineno = e->lineno;
4078 c->u->u_lineno_set = 0;
4079 }
4080 compiler_error(c, "asynchronous comprehension outside of "
4081 "an asynchronous function");
4082 goto error_in_scope;
4083 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 if (type != COMP_GENEXP) {
4086 int op;
4087 switch (type) {
4088 case COMP_LISTCOMP:
4089 op = BUILD_LIST;
4090 break;
4091 case COMP_SETCOMP:
4092 op = BUILD_SET;
4093 break;
4094 case COMP_DICTCOMP:
4095 op = BUILD_MAP;
4096 break;
4097 default:
4098 PyErr_Format(PyExc_SystemError,
4099 "unknown comprehension type %d", type);
4100 goto error_in_scope;
4101 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 ADDOP_I(c, op, 0);
4104 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 if (!compiler_comprehension_generator(c, generators, 0, elt,
4107 val, type))
4108 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 if (type != COMP_GENEXP) {
4111 ADDOP(c, RETURN_VALUE);
4112 }
4113
4114 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004115 qualname = c->u->u_qualname;
4116 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004118 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 goto error;
4120
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004121 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004123 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 Py_DECREF(co);
4125
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004126 VISIT(c, expr, outermost->iter);
4127
4128 if (outermost->is_async) {
4129 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004130 } else {
4131 ADDOP(c, GET_ITER);
4132 }
4133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004135
4136 if (is_async_generator && type != COMP_GENEXP) {
4137 ADDOP(c, GET_AWAITABLE);
4138 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4139 ADDOP(c, YIELD_FROM);
4140 }
4141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004143error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004145error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004146 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 Py_XDECREF(co);
4148 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004149}
4150
4151static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152compiler_genexp(struct compiler *c, expr_ty e)
4153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 static identifier name;
4155 if (!name) {
4156 name = PyUnicode_FromString("<genexpr>");
4157 if (!name)
4158 return 0;
4159 }
4160 assert(e->kind == GeneratorExp_kind);
4161 return compiler_comprehension(c, e, COMP_GENEXP, name,
4162 e->v.GeneratorExp.generators,
4163 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004164}
4165
4166static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004167compiler_listcomp(struct compiler *c, expr_ty e)
4168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 static identifier name;
4170 if (!name) {
4171 name = PyUnicode_FromString("<listcomp>");
4172 if (!name)
4173 return 0;
4174 }
4175 assert(e->kind == ListComp_kind);
4176 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4177 e->v.ListComp.generators,
4178 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004179}
4180
4181static int
4182compiler_setcomp(struct compiler *c, expr_ty e)
4183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 static identifier name;
4185 if (!name) {
4186 name = PyUnicode_FromString("<setcomp>");
4187 if (!name)
4188 return 0;
4189 }
4190 assert(e->kind == SetComp_kind);
4191 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4192 e->v.SetComp.generators,
4193 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004194}
4195
4196
4197static int
4198compiler_dictcomp(struct compiler *c, expr_ty e)
4199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 static identifier name;
4201 if (!name) {
4202 name = PyUnicode_FromString("<dictcomp>");
4203 if (!name)
4204 return 0;
4205 }
4206 assert(e->kind == DictComp_kind);
4207 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4208 e->v.DictComp.generators,
4209 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004210}
4211
4212
4213static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004214compiler_visit_keyword(struct compiler *c, keyword_ty k)
4215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 VISIT(c, expr, k->value);
4217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218}
4219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 whether they are true or false.
4222
4223 Return values: 1 for true, 0 for false, -1 for non-constant.
4224 */
4225
4226static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004227expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004228{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004229 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004230 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004231 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004232 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233}
4234
Yury Selivanov75445082015-05-11 22:57:16 -04004235
4236/*
4237 Implements the async with statement.
4238
4239 The semantics outlined in that PEP are as follows:
4240
4241 async with EXPR as VAR:
4242 BLOCK
4243
4244 It is implemented roughly as:
4245
4246 context = EXPR
4247 exit = context.__aexit__ # not calling it
4248 value = await context.__aenter__()
4249 try:
4250 VAR = value # if VAR present in the syntax
4251 BLOCK
4252 finally:
4253 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004254 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004255 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004256 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004257 if not (await exit(*exc)):
4258 raise
4259 */
4260static int
4261compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4262{
4263 basicblock *block, *finally;
4264 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4265
4266 assert(s->kind == AsyncWith_kind);
4267
4268 block = compiler_new_block(c);
4269 finally = compiler_new_block(c);
4270 if (!block || !finally)
4271 return 0;
4272
4273 /* Evaluate EXPR */
4274 VISIT(c, expr, item->context_expr);
4275
4276 ADDOP(c, BEFORE_ASYNC_WITH);
4277 ADDOP(c, GET_AWAITABLE);
4278 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4279 ADDOP(c, YIELD_FROM);
4280
4281 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4282
4283 /* SETUP_ASYNC_WITH pushes a finally block. */
4284 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004285 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004286 return 0;
4287 }
4288
4289 if (item->optional_vars) {
4290 VISIT(c, expr, item->optional_vars);
4291 }
4292 else {
4293 /* Discard result from context.__aenter__() */
4294 ADDOP(c, POP_TOP);
4295 }
4296
4297 pos++;
4298 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4299 /* BLOCK code */
4300 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4301 else if (!compiler_async_with(c, s, pos))
4302 return 0;
4303
4304 /* End of try block; start the finally block */
4305 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004306 ADDOP(c, BEGIN_FINALLY);
4307 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004308
Yury Selivanov75445082015-05-11 22:57:16 -04004309 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004310 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004311 return 0;
4312
4313 /* Finally block starts; context.__exit__ is on the stack under
4314 the exception or return information. Just issue our magic
4315 opcode. */
4316 ADDOP(c, WITH_CLEANUP_START);
4317
4318 ADDOP(c, GET_AWAITABLE);
4319 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4320 ADDOP(c, YIELD_FROM);
4321
4322 ADDOP(c, WITH_CLEANUP_FINISH);
4323
4324 /* Finally block ends. */
4325 ADDOP(c, END_FINALLY);
4326 compiler_pop_fblock(c, FINALLY_END, finally);
4327 return 1;
4328}
4329
4330
Guido van Rossumc2e20742006-02-27 22:32:47 +00004331/*
4332 Implements the with statement from PEP 343.
4333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004335
4336 with EXPR as VAR:
4337 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338
Guido van Rossumc2e20742006-02-27 22:32:47 +00004339 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340
Thomas Wouters477c8d52006-05-27 19:21:47 +00004341 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004342 exit = context.__exit__ # not calling it
4343 value = context.__enter__()
4344 try:
4345 VAR = value # if VAR present in the syntax
4346 BLOCK
4347 finally:
4348 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004349 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004350 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004351 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004352 exit(*exc)
4353 */
4354static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004355compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004356{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004357 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004358 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004359
4360 assert(s->kind == With_kind);
4361
Guido van Rossumc2e20742006-02-27 22:32:47 +00004362 block = compiler_new_block(c);
4363 finally = compiler_new_block(c);
4364 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004365 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004366
Thomas Wouters477c8d52006-05-27 19:21:47 +00004367 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004368 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004369 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004370
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004371 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004372 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004373 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004374 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004375 }
4376
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004377 if (item->optional_vars) {
4378 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004379 }
4380 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004382 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004383 }
4384
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004385 pos++;
4386 if (pos == asdl_seq_LEN(s->v.With.items))
4387 /* BLOCK code */
4388 VISIT_SEQ(c, stmt, s->v.With.body)
4389 else if (!compiler_with(c, s, pos))
4390 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004391
4392 /* End of try block; start the finally block */
4393 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004394 ADDOP(c, BEGIN_FINALLY);
4395 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004396
Guido van Rossumc2e20742006-02-27 22:32:47 +00004397 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004398 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004399 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004400
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004401 /* Finally block starts; context.__exit__ is on the stack under
4402 the exception or return information. Just issue our magic
4403 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004404 ADDOP(c, WITH_CLEANUP_START);
4405 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004406
4407 /* Finally block ends. */
4408 ADDOP(c, END_FINALLY);
4409 compiler_pop_fblock(c, FINALLY_END, finally);
4410 return 1;
4411}
4412
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004413static int
4414compiler_visit_expr(struct compiler *c, expr_ty e)
4415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 /* If expr e has a different line number than the last expr/stmt,
4417 set a new line number for the next instruction.
4418 */
4419 if (e->lineno > c->u->u_lineno) {
4420 c->u->u_lineno = e->lineno;
4421 c->u->u_lineno_set = 0;
4422 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004423 /* Updating the column offset is always harmless. */
4424 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 switch (e->kind) {
4426 case BoolOp_kind:
4427 return compiler_boolop(c, e);
4428 case BinOp_kind:
4429 VISIT(c, expr, e->v.BinOp.left);
4430 VISIT(c, expr, e->v.BinOp.right);
4431 ADDOP(c, binop(c, e->v.BinOp.op));
4432 break;
4433 case UnaryOp_kind:
4434 VISIT(c, expr, e->v.UnaryOp.operand);
4435 ADDOP(c, unaryop(e->v.UnaryOp.op));
4436 break;
4437 case Lambda_kind:
4438 return compiler_lambda(c, e);
4439 case IfExp_kind:
4440 return compiler_ifexp(c, e);
4441 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004442 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004444 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 case GeneratorExp_kind:
4446 return compiler_genexp(c, e);
4447 case ListComp_kind:
4448 return compiler_listcomp(c, e);
4449 case SetComp_kind:
4450 return compiler_setcomp(c, e);
4451 case DictComp_kind:
4452 return compiler_dictcomp(c, e);
4453 case Yield_kind:
4454 if (c->u->u_ste->ste_type != FunctionBlock)
4455 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004456 if (e->v.Yield.value) {
4457 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 }
4459 else {
4460 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4461 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004462 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004464 case YieldFrom_kind:
4465 if (c->u->u_ste->ste_type != FunctionBlock)
4466 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004467
4468 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4469 return compiler_error(c, "'yield from' inside async function");
4470
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004471 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004472 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004473 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4474 ADDOP(c, YIELD_FROM);
4475 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004476 case Await_kind:
4477 if (c->u->u_ste->ste_type != FunctionBlock)
4478 return compiler_error(c, "'await' outside function");
4479
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4481 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004482 return compiler_error(c, "'await' outside async function");
4483
4484 VISIT(c, expr, e->v.Await.value);
4485 ADDOP(c, GET_AWAITABLE);
4486 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4487 ADDOP(c, YIELD_FROM);
4488 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 case Compare_kind:
4490 return compiler_compare(c, e);
4491 case Call_kind:
4492 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004493 case Constant_kind:
4494 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4495 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 case Num_kind:
4497 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4498 break;
4499 case Str_kind:
4500 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4501 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004502 case JoinedStr_kind:
4503 return compiler_joined_str(c, e);
4504 case FormattedValue_kind:
4505 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 case Bytes_kind:
4507 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4508 break;
4509 case Ellipsis_kind:
4510 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4511 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004512 case NameConstant_kind:
4513 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4514 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 /* The following exprs can be assignment targets. */
4516 case Attribute_kind:
4517 if (e->v.Attribute.ctx != AugStore)
4518 VISIT(c, expr, e->v.Attribute.value);
4519 switch (e->v.Attribute.ctx) {
4520 case AugLoad:
4521 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004522 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 case Load:
4524 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4525 break;
4526 case AugStore:
4527 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004528 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 case Store:
4530 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4531 break;
4532 case Del:
4533 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4534 break;
4535 case Param:
4536 default:
4537 PyErr_SetString(PyExc_SystemError,
4538 "param invalid in attribute expression");
4539 return 0;
4540 }
4541 break;
4542 case Subscript_kind:
4543 switch (e->v.Subscript.ctx) {
4544 case AugLoad:
4545 VISIT(c, expr, e->v.Subscript.value);
4546 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4547 break;
4548 case Load:
4549 VISIT(c, expr, e->v.Subscript.value);
4550 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4551 break;
4552 case AugStore:
4553 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4554 break;
4555 case Store:
4556 VISIT(c, expr, e->v.Subscript.value);
4557 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4558 break;
4559 case Del:
4560 VISIT(c, expr, e->v.Subscript.value);
4561 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4562 break;
4563 case Param:
4564 default:
4565 PyErr_SetString(PyExc_SystemError,
4566 "param invalid in subscript expression");
4567 return 0;
4568 }
4569 break;
4570 case Starred_kind:
4571 switch (e->v.Starred.ctx) {
4572 case Store:
4573 /* In all legitimate cases, the Starred node was already replaced
4574 * by compiler_list/compiler_tuple. XXX: is that okay? */
4575 return compiler_error(c,
4576 "starred assignment target must be in a list or tuple");
4577 default:
4578 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004579 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 }
4581 break;
4582 case Name_kind:
4583 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4584 /* child nodes of List and Tuple will have expr_context set */
4585 case List_kind:
4586 return compiler_list(c, e);
4587 case Tuple_kind:
4588 return compiler_tuple(c, e);
4589 }
4590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004591}
4592
4593static int
4594compiler_augassign(struct compiler *c, stmt_ty s)
4595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 expr_ty e = s->v.AugAssign.target;
4597 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 switch (e->kind) {
4602 case Attribute_kind:
4603 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4604 AugLoad, e->lineno, e->col_offset, c->c_arena);
4605 if (auge == NULL)
4606 return 0;
4607 VISIT(c, expr, auge);
4608 VISIT(c, expr, s->v.AugAssign.value);
4609 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4610 auge->v.Attribute.ctx = AugStore;
4611 VISIT(c, expr, auge);
4612 break;
4613 case Subscript_kind:
4614 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4615 AugLoad, e->lineno, e->col_offset, c->c_arena);
4616 if (auge == NULL)
4617 return 0;
4618 VISIT(c, expr, auge);
4619 VISIT(c, expr, s->v.AugAssign.value);
4620 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4621 auge->v.Subscript.ctx = AugStore;
4622 VISIT(c, expr, auge);
4623 break;
4624 case Name_kind:
4625 if (!compiler_nameop(c, e->v.Name.id, Load))
4626 return 0;
4627 VISIT(c, expr, s->v.AugAssign.value);
4628 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4629 return compiler_nameop(c, e->v.Name.id, Store);
4630 default:
4631 PyErr_Format(PyExc_SystemError,
4632 "invalid node type (%d) for augmented assignment",
4633 e->kind);
4634 return 0;
4635 }
4636 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004637}
4638
4639static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004640check_ann_expr(struct compiler *c, expr_ty e)
4641{
4642 VISIT(c, expr, e);
4643 ADDOP(c, POP_TOP);
4644 return 1;
4645}
4646
4647static int
4648check_annotation(struct compiler *c, stmt_ty s)
4649{
4650 /* Annotations are only evaluated in a module or class. */
4651 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4652 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4653 return check_ann_expr(c, s->v.AnnAssign.annotation);
4654 }
4655 return 1;
4656}
4657
4658static int
4659check_ann_slice(struct compiler *c, slice_ty sl)
4660{
4661 switch(sl->kind) {
4662 case Index_kind:
4663 return check_ann_expr(c, sl->v.Index.value);
4664 case Slice_kind:
4665 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4666 return 0;
4667 }
4668 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4669 return 0;
4670 }
4671 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4672 return 0;
4673 }
4674 break;
4675 default:
4676 PyErr_SetString(PyExc_SystemError,
4677 "unexpected slice kind");
4678 return 0;
4679 }
4680 return 1;
4681}
4682
4683static int
4684check_ann_subscr(struct compiler *c, slice_ty sl)
4685{
4686 /* We check that everything in a subscript is defined at runtime. */
4687 Py_ssize_t i, n;
4688
4689 switch (sl->kind) {
4690 case Index_kind:
4691 case Slice_kind:
4692 if (!check_ann_slice(c, sl)) {
4693 return 0;
4694 }
4695 break;
4696 case ExtSlice_kind:
4697 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4698 for (i = 0; i < n; i++) {
4699 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4700 switch (subsl->kind) {
4701 case Index_kind:
4702 case Slice_kind:
4703 if (!check_ann_slice(c, subsl)) {
4704 return 0;
4705 }
4706 break;
4707 case ExtSlice_kind:
4708 default:
4709 PyErr_SetString(PyExc_SystemError,
4710 "extended slice invalid in nested slice");
4711 return 0;
4712 }
4713 }
4714 break;
4715 default:
4716 PyErr_Format(PyExc_SystemError,
4717 "invalid subscript kind %d", sl->kind);
4718 return 0;
4719 }
4720 return 1;
4721}
4722
4723static int
4724compiler_annassign(struct compiler *c, stmt_ty s)
4725{
4726 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004727 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004728
4729 assert(s->kind == AnnAssign_kind);
4730
4731 /* We perform the actual assignment first. */
4732 if (s->v.AnnAssign.value) {
4733 VISIT(c, expr, s->v.AnnAssign.value);
4734 VISIT(c, expr, targ);
4735 }
4736 switch (targ->kind) {
4737 case Name_kind:
4738 /* If we have a simple name in a module or class, store annotation. */
4739 if (s->v.AnnAssign.simple &&
4740 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4741 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004742 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4743 if (!mangled) {
4744 return 0;
4745 }
Guido van Rossum95e4d582018-01-26 08:20:18 -08004746 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4747 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4748 }
4749 else {
4750 VISIT(c, expr, s->v.AnnAssign.annotation);
4751 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004752 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
4753 ADDOP_O(c, LOAD_CONST, mangled, consts);
4754 Py_DECREF(mangled);
4755 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004756 }
4757 break;
4758 case Attribute_kind:
4759 if (!s->v.AnnAssign.value &&
4760 !check_ann_expr(c, targ->v.Attribute.value)) {
4761 return 0;
4762 }
4763 break;
4764 case Subscript_kind:
4765 if (!s->v.AnnAssign.value &&
4766 (!check_ann_expr(c, targ->v.Subscript.value) ||
4767 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4768 return 0;
4769 }
4770 break;
4771 default:
4772 PyErr_Format(PyExc_SystemError,
4773 "invalid node type (%d) for annotated assignment",
4774 targ->kind);
4775 return 0;
4776 }
4777 /* Annotation is evaluated last. */
4778 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4779 return 0;
4780 }
4781 return 1;
4782}
4783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004784/* Raises a SyntaxError and returns 0.
4785 If something goes wrong, a different exception may be raised.
4786*/
4787
4788static int
4789compiler_error(struct compiler *c, const char *errstr)
4790{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004791 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004793
Victor Stinner14e461d2013-08-26 22:28:21 +02004794 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 if (!loc) {
4796 Py_INCREF(Py_None);
4797 loc = Py_None;
4798 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004799 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004800 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 if (!u)
4802 goto exit;
4803 v = Py_BuildValue("(zO)", errstr, u);
4804 if (!v)
4805 goto exit;
4806 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004807 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 Py_DECREF(loc);
4809 Py_XDECREF(u);
4810 Py_XDECREF(v);
4811 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004812}
4813
4814static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815compiler_handle_subscr(struct compiler *c, const char *kind,
4816 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 /* XXX this code is duplicated */
4821 switch (ctx) {
4822 case AugLoad: /* fall through to Load */
4823 case Load: op = BINARY_SUBSCR; break;
4824 case AugStore:/* fall through to Store */
4825 case Store: op = STORE_SUBSCR; break;
4826 case Del: op = DELETE_SUBSCR; break;
4827 case Param:
4828 PyErr_Format(PyExc_SystemError,
4829 "invalid %s kind %d in subscript\n",
4830 kind, ctx);
4831 return 0;
4832 }
4833 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004834 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 }
4836 else if (ctx == AugStore) {
4837 ADDOP(c, ROT_THREE);
4838 }
4839 ADDOP(c, op);
4840 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004841}
4842
4843static int
4844compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 int n = 2;
4847 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 /* only handles the cases where BUILD_SLICE is emitted */
4850 if (s->v.Slice.lower) {
4851 VISIT(c, expr, s->v.Slice.lower);
4852 }
4853 else {
4854 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4855 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 if (s->v.Slice.upper) {
4858 VISIT(c, expr, s->v.Slice.upper);
4859 }
4860 else {
4861 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4862 }
4863
4864 if (s->v.Slice.step) {
4865 n++;
4866 VISIT(c, expr, s->v.Slice.step);
4867 }
4868 ADDOP_I(c, BUILD_SLICE, n);
4869 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004870}
4871
4872static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4874 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 switch (s->kind) {
4877 case Slice_kind:
4878 return compiler_slice(c, s, ctx);
4879 case Index_kind:
4880 VISIT(c, expr, s->v.Index.value);
4881 break;
4882 case ExtSlice_kind:
4883 default:
4884 PyErr_SetString(PyExc_SystemError,
4885 "extended slice invalid in nested slice");
4886 return 0;
4887 }
4888 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004889}
4890
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004891static int
4892compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4893{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004894 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 switch (s->kind) {
4896 case Index_kind:
4897 kindname = "index";
4898 if (ctx != AugStore) {
4899 VISIT(c, expr, s->v.Index.value);
4900 }
4901 break;
4902 case Slice_kind:
4903 kindname = "slice";
4904 if (ctx != AugStore) {
4905 if (!compiler_slice(c, s, ctx))
4906 return 0;
4907 }
4908 break;
4909 case ExtSlice_kind:
4910 kindname = "extended slice";
4911 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004912 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 for (i = 0; i < n; i++) {
4914 slice_ty sub = (slice_ty)asdl_seq_GET(
4915 s->v.ExtSlice.dims, i);
4916 if (!compiler_visit_nested_slice(c, sub, ctx))
4917 return 0;
4918 }
4919 ADDOP_I(c, BUILD_TUPLE, n);
4920 }
4921 break;
4922 default:
4923 PyErr_Format(PyExc_SystemError,
4924 "invalid subscript kind %d", s->kind);
4925 return 0;
4926 }
4927 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004928}
4929
Thomas Wouters89f507f2006-12-13 04:49:30 +00004930/* End of the compiler section, beginning of the assembler section */
4931
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004932/* do depth-first search of basic block graph, starting with block.
4933 post records the block indices in post-order.
4934
4935 XXX must handle implicit jumps from one block to next
4936*/
4937
Thomas Wouters89f507f2006-12-13 04:49:30 +00004938struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 PyObject *a_bytecode; /* string containing bytecode */
4940 int a_offset; /* offset into bytecode */
4941 int a_nblocks; /* number of reachable blocks */
4942 basicblock **a_postorder; /* list of blocks in dfs postorder */
4943 PyObject *a_lnotab; /* string containing lnotab */
4944 int a_lnotab_off; /* offset into lnotab */
4945 int a_lineno; /* last lineno of emitted instruction */
4946 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004947};
4948
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004949static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004950dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004951{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004952 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004953
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004954 /* Get rid of recursion for normal control flow.
4955 Since the number of blocks is limited, unused space in a_postorder
4956 (from a_nblocks to end) can be used as a stack for still not ordered
4957 blocks. */
4958 for (j = end; b && !b->b_seen; b = b->b_next) {
4959 b->b_seen = 1;
4960 assert(a->a_nblocks < j);
4961 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004963 while (j < end) {
4964 b = a->a_postorder[j++];
4965 for (i = 0; i < b->b_iused; i++) {
4966 struct instr *instr = &b->b_instr[i];
4967 if (instr->i_jrel || instr->i_jabs)
4968 dfs(c, instr->i_target, a, j);
4969 }
4970 assert(a->a_nblocks < j);
4971 a->a_postorder[a->a_nblocks++] = b;
4972 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004973}
4974
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004975Py_LOCAL_INLINE(void)
4976stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004977{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004978 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004979 if (b->b_startdepth < depth) {
4980 assert(b->b_startdepth < 0);
4981 b->b_startdepth = depth;
4982 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004983 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004984}
4985
4986/* Find the flow path that needs the largest stack. We assume that
4987 * cycles in the flow graph have no net effect on the stack depth.
4988 */
4989static int
4990stackdepth(struct compiler *c)
4991{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004992 basicblock *b, *entryblock = NULL;
4993 basicblock **stack, **sp;
4994 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 b->b_startdepth = INT_MIN;
4997 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004998 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 }
5000 if (!entryblock)
5001 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005002 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5003 if (!stack) {
5004 PyErr_NoMemory();
5005 return -1;
5006 }
5007
5008 sp = stack;
5009 stackdepth_push(&sp, entryblock, 0);
5010 while (sp != stack) {
5011 b = *--sp;
5012 int depth = b->b_startdepth;
5013 assert(depth >= 0);
5014 basicblock *next = b->b_next;
5015 for (int i = 0; i < b->b_iused; i++) {
5016 struct instr *instr = &b->b_instr[i];
5017 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5018 if (effect == PY_INVALID_STACK_EFFECT) {
5019 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5020 Py_FatalError("PyCompile_OpcodeStackEffect()");
5021 }
5022 int new_depth = depth + effect;
5023 if (new_depth > maxdepth) {
5024 maxdepth = new_depth;
5025 }
5026 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5027 if (instr->i_jrel || instr->i_jabs) {
5028 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5029 assert(effect != PY_INVALID_STACK_EFFECT);
5030 int target_depth = depth + effect;
5031 if (target_depth > maxdepth) {
5032 maxdepth = target_depth;
5033 }
5034 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005035 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005036 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005037 assert(instr->i_target->b_startdepth >= target_depth);
5038 depth = new_depth;
5039 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005040 }
5041 stackdepth_push(&sp, instr->i_target, target_depth);
5042 }
5043 depth = new_depth;
5044 if (instr->i_opcode == JUMP_ABSOLUTE ||
5045 instr->i_opcode == JUMP_FORWARD ||
5046 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005047 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005048 {
5049 /* remaining code is dead */
5050 next = NULL;
5051 break;
5052 }
5053 }
5054 if (next != NULL) {
5055 stackdepth_push(&sp, next, depth);
5056 }
5057 }
5058 PyObject_Free(stack);
5059 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005060}
5061
5062static int
5063assemble_init(struct assembler *a, int nblocks, int firstlineno)
5064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 memset(a, 0, sizeof(struct assembler));
5066 a->a_lineno = firstlineno;
5067 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5068 if (!a->a_bytecode)
5069 return 0;
5070 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5071 if (!a->a_lnotab)
5072 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005073 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 PyErr_NoMemory();
5075 return 0;
5076 }
5077 a->a_postorder = (basicblock **)PyObject_Malloc(
5078 sizeof(basicblock *) * nblocks);
5079 if (!a->a_postorder) {
5080 PyErr_NoMemory();
5081 return 0;
5082 }
5083 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005084}
5085
5086static void
5087assemble_free(struct assembler *a)
5088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 Py_XDECREF(a->a_bytecode);
5090 Py_XDECREF(a->a_lnotab);
5091 if (a->a_postorder)
5092 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005093}
5094
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095static int
5096blocksize(basicblock *b)
5097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 int i;
5099 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005102 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005104}
5105
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005106/* Appends a pair to the end of the line number table, a_lnotab, representing
5107 the instruction's bytecode offset and line number. See
5108 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005109
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005110static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005114 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005116
Serhiy Storchakaab874002016-09-11 13:48:15 +03005117 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 if(d_bytecode == 0 && d_lineno == 0)
5123 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 if (d_bytecode > 255) {
5126 int j, nbytes, ncodes = d_bytecode / 255;
5127 nbytes = a->a_lnotab_off + 2 * ncodes;
5128 len = PyBytes_GET_SIZE(a->a_lnotab);
5129 if (nbytes >= len) {
5130 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5131 len = nbytes;
5132 else if (len <= INT_MAX / 2)
5133 len *= 2;
5134 else {
5135 PyErr_NoMemory();
5136 return 0;
5137 }
5138 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5139 return 0;
5140 }
5141 lnotab = (unsigned char *)
5142 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5143 for (j = 0; j < ncodes; j++) {
5144 *lnotab++ = 255;
5145 *lnotab++ = 0;
5146 }
5147 d_bytecode -= ncodes * 255;
5148 a->a_lnotab_off += ncodes * 2;
5149 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005150 assert(0 <= d_bytecode && d_bytecode <= 255);
5151
5152 if (d_lineno < -128 || 127 < d_lineno) {
5153 int j, nbytes, ncodes, k;
5154 if (d_lineno < 0) {
5155 k = -128;
5156 /* use division on positive numbers */
5157 ncodes = (-d_lineno) / 128;
5158 }
5159 else {
5160 k = 127;
5161 ncodes = d_lineno / 127;
5162 }
5163 d_lineno -= ncodes * k;
5164 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 nbytes = a->a_lnotab_off + 2 * ncodes;
5166 len = PyBytes_GET_SIZE(a->a_lnotab);
5167 if (nbytes >= len) {
5168 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5169 len = nbytes;
5170 else if (len <= INT_MAX / 2)
5171 len *= 2;
5172 else {
5173 PyErr_NoMemory();
5174 return 0;
5175 }
5176 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5177 return 0;
5178 }
5179 lnotab = (unsigned char *)
5180 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5181 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005182 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 d_bytecode = 0;
5184 for (j = 1; j < ncodes; j++) {
5185 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005186 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 a->a_lnotab_off += ncodes * 2;
5189 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005190 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 len = PyBytes_GET_SIZE(a->a_lnotab);
5193 if (a->a_lnotab_off + 2 >= len) {
5194 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5195 return 0;
5196 }
5197 lnotab = (unsigned char *)
5198 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 a->a_lnotab_off += 2;
5201 if (d_bytecode) {
5202 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005203 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 }
5205 else { /* First line of a block; def stmt, etc. */
5206 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005207 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 }
5209 a->a_lineno = i->i_lineno;
5210 a->a_lineno_off = a->a_offset;
5211 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005212}
5213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005214/* assemble_emit()
5215 Extend the bytecode with a new instruction.
5216 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005217*/
5218
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005219static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005220assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005221{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005222 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005224 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005225
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005226 arg = i->i_oparg;
5227 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 if (i->i_lineno && !assemble_lnotab(a, i))
5229 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005230 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 if (len > PY_SSIZE_T_MAX / 2)
5232 return 0;
5233 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5234 return 0;
5235 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005236 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005237 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005238 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005240}
5241
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005242static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005243assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005246 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 /* Compute the size of each block and fixup jump args.
5250 Replace block pointer with position in bytecode. */
5251 do {
5252 totsize = 0;
5253 for (i = a->a_nblocks - 1; i >= 0; i--) {
5254 b = a->a_postorder[i];
5255 bsize = blocksize(b);
5256 b->b_offset = totsize;
5257 totsize += bsize;
5258 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005259 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5261 bsize = b->b_offset;
5262 for (i = 0; i < b->b_iused; i++) {
5263 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005264 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 /* Relative jumps are computed relative to
5266 the instruction pointer after fetching
5267 the jump instruction.
5268 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005269 bsize += isize;
5270 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005272 if (instr->i_jrel) {
5273 instr->i_oparg -= bsize;
5274 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005275 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005276 if (instrsize(instr->i_oparg) != isize) {
5277 extended_arg_recompile = 1;
5278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 }
5281 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 /* XXX: This is an awful hack that could hurt performance, but
5284 on the bright side it should work until we come up
5285 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 The issue is that in the first loop blocksize() is called
5288 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005289 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 So we loop until we stop seeing new EXTENDED_ARGs.
5293 The only EXTENDED_ARGs that could be popping up are
5294 ones in jump instructions. So this should converge
5295 fairly quickly.
5296 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005297 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005298}
5299
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005300static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005301dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005304 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 tuple = PyTuple_New(size);
5307 if (tuple == NULL)
5308 return NULL;
5309 while (PyDict_Next(dict, &pos, &k, &v)) {
5310 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005311 /* The keys of the dictionary are tuples. (see compiler_add_o
5312 * and _PyCode_ConstantKey). The object we want is always second,
5313 * though. */
5314 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 Py_INCREF(k);
5316 assert((i - offset) < size);
5317 assert((i - offset) >= 0);
5318 PyTuple_SET_ITEM(tuple, i - offset, k);
5319 }
5320 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005321}
5322
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005323static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005324compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005327 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005329 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 if (ste->ste_nested)
5331 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005332 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005334 if (!ste->ste_generator && ste->ste_coroutine)
5335 flags |= CO_COROUTINE;
5336 if (ste->ste_generator && ste->ste_coroutine)
5337 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 if (ste->ste_varargs)
5339 flags |= CO_VARARGS;
5340 if (ste->ste_varkeywords)
5341 flags |= CO_VARKEYWORDS;
5342 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 /* (Only) inherit compilerflags in PyCF_MASK */
5345 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005348}
5349
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350static PyCodeObject *
5351makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 PyObject *tmp;
5354 PyCodeObject *co = NULL;
5355 PyObject *consts = NULL;
5356 PyObject *names = NULL;
5357 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 PyObject *name = NULL;
5359 PyObject *freevars = NULL;
5360 PyObject *cellvars = NULL;
5361 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005362 Py_ssize_t nlocals;
5363 int nlocals_int;
5364 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005365 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 tmp = dict_keys_inorder(c->u->u_consts, 0);
5368 if (!tmp)
5369 goto error;
5370 consts = PySequence_List(tmp); /* optimize_code requires a list */
5371 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 names = dict_keys_inorder(c->u->u_names, 0);
5374 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5375 if (!consts || !names || !varnames)
5376 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5379 if (!cellvars)
5380 goto error;
5381 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5382 if (!freevars)
5383 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005384
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005385 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005386 assert(nlocals < INT_MAX);
5387 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 flags = compute_code_flags(c);
5390 if (flags < 0)
5391 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5394 if (!bytecode)
5395 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5398 if (!tmp)
5399 goto error;
5400 Py_DECREF(consts);
5401 consts = tmp;
5402
Victor Stinnerf8e32212013-11-19 23:56:34 +01005403 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5404 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005405 maxdepth = stackdepth(c);
5406 if (maxdepth < 0) {
5407 goto error;
5408 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005409 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005410 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 bytecode, consts, names, varnames,
5412 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005413 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 c->u->u_firstlineno,
5415 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005416 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 Py_XDECREF(consts);
5418 Py_XDECREF(names);
5419 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 Py_XDECREF(name);
5421 Py_XDECREF(freevars);
5422 Py_XDECREF(cellvars);
5423 Py_XDECREF(bytecode);
5424 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005425}
5426
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005427
5428/* For debugging purposes only */
5429#if 0
5430static void
5431dump_instr(const struct instr *i)
5432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 const char *jrel = i->i_jrel ? "jrel " : "";
5434 const char *jabs = i->i_jabs ? "jabs " : "";
5435 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005438 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5442 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005443}
5444
5445static void
5446dump_basicblock(const basicblock *b)
5447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 const char *seen = b->b_seen ? "seen " : "";
5449 const char *b_return = b->b_return ? "return " : "";
5450 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5451 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5452 if (b->b_instr) {
5453 int i;
5454 for (i = 0; i < b->b_iused; i++) {
5455 fprintf(stderr, " [%02d] ", i);
5456 dump_instr(b->b_instr + i);
5457 }
5458 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005459}
5460#endif
5461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005462static PyCodeObject *
5463assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 basicblock *b, *entryblock;
5466 struct assembler a;
5467 int i, j, nblocks;
5468 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 /* Make sure every block that falls off the end returns None.
5471 XXX NEXT_BLOCK() isn't quite right, because if the last
5472 block ends with a jump or return b_next shouldn't set.
5473 */
5474 if (!c->u->u_curblock->b_return) {
5475 NEXT_BLOCK(c);
5476 if (addNone)
5477 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5478 ADDOP(c, RETURN_VALUE);
5479 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 nblocks = 0;
5482 entryblock = NULL;
5483 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5484 nblocks++;
5485 entryblock = b;
5486 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 /* Set firstlineno if it wasn't explicitly set. */
5489 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005490 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5492 else
5493 c->u->u_firstlineno = 1;
5494 }
5495 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5496 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005497 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 /* Can't modify the bytecode after computing jump offsets. */
5500 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 /* Emit code in reverse postorder from dfs. */
5503 for (i = a.a_nblocks - 1; i >= 0; i--) {
5504 b = a.a_postorder[i];
5505 for (j = 0; j < b->b_iused; j++)
5506 if (!assemble_emit(&a, &b->b_instr[j]))
5507 goto error;
5508 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5511 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005512 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005516 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 assemble_free(&a);
5518 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005519}
Georg Brandl8334fd92010-12-04 10:26:46 +00005520
5521#undef PyAST_Compile
5522PyAPI_FUNC(PyCodeObject *)
5523PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5524 PyArena *arena)
5525{
5526 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5527}