blob: 3e8323b933f49d9fce3137dae74d3de6d981d839 [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
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200194static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700205static int compiler_sync_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
210static int compiler_async_comprehension_generator(
211 struct compiler *c,
212 asdl_seq *generators, int gen_index,
213 expr_ty elt, expr_ty val, int type);
214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static PyCodeObject *assemble(struct compiler *, int addNone);
216static PyObject *__doc__;
217
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400218#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Name mangling: __private becomes _classname__private.
224 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyObject *result;
226 size_t nlen, plen, ipriv;
227 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyUnicode_READ_CHAR(ident, 0) != '_' ||
230 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident;
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 nlen = PyUnicode_GET_LENGTH(ident);
235 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 The only time a name with a dot can occur is when
239 we are compiling an import statement that has a
240 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 TODO(jhylton): Decide whether we want to support
243 mangling of the module name, e.g. __M.X.
244 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
246 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
247 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_INCREF(ident);
249 return ident; /* Don't mangle __whatever__ */
250 }
251 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 ipriv = 0;
253 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
254 ipriv++;
255 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle if class is just underscores */
258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000260
Antoine Pitrou55bff892013-04-06 21:21:04 +0200261 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
262 PyErr_SetString(PyExc_OverflowError,
263 "private identifier too large to be mangled");
264 return NULL;
265 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
268 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
269 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
270
271 result = PyUnicode_New(1 + nlen + plen, maxchar);
272 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
275 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200276 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
280 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
Victor Stinner8f825062012-04-27 13:55:39 +0200284 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000286}
287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288static int
289compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 c->c_stack = PyList_New(0);
294 if (!c->c_stack)
295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200301PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
302 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 struct compiler c;
305 PyCodeObject *co = NULL;
306 PyCompilerFlags local_flags;
307 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!__doc__) {
310 __doc__ = PyUnicode_InternFromString("__doc__");
311 if (!__doc__)
312 return NULL;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
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
845 - before the "except" clause
846 - 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:
880 return 0;
881 case DUP_TOP:
882 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000883 case DUP_TOP_TWO:
884 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000885
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200886 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 case UNARY_POSITIVE:
888 case UNARY_NEGATIVE:
889 case UNARY_NOT:
890 case UNARY_INVERT:
891 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 case SET_ADD:
894 case LIST_APPEND:
895 return -1;
896 case MAP_ADD:
897 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000898
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200899 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case BINARY_POWER:
901 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400902 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case BINARY_MODULO:
904 case BINARY_ADD:
905 case BINARY_SUBTRACT:
906 case BINARY_SUBSCR:
907 case BINARY_FLOOR_DIVIDE:
908 case BINARY_TRUE_DIVIDE:
909 return -1;
910 case INPLACE_FLOOR_DIVIDE:
911 case INPLACE_TRUE_DIVIDE:
912 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case INPLACE_ADD:
915 case INPLACE_SUBTRACT:
916 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400917 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case INPLACE_MODULO:
919 return -1;
920 case STORE_SUBSCR:
921 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case DELETE_SUBSCR:
923 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case BINARY_LSHIFT:
926 case BINARY_RSHIFT:
927 case BINARY_AND:
928 case BINARY_XOR:
929 case BINARY_OR:
930 return -1;
931 case INPLACE_POWER:
932 return -1;
933 case GET_ITER:
934 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case PRINT_EXPR:
937 return -1;
938 case LOAD_BUILD_CLASS:
939 return 1;
940 case INPLACE_LSHIFT:
941 case INPLACE_RSHIFT:
942 case INPLACE_AND:
943 case INPLACE_XOR:
944 case INPLACE_OR:
945 return -1;
946 case BREAK_LOOP:
947 return 0;
948 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 Storchakad4864c62018-01-09 21:54:52 +0200974 /* Pop 6 values when an exception was raised. */
975 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case STORE_NAME:
978 return -1;
979 case DELETE_NAME:
980 return 0;
981 case UNPACK_SEQUENCE:
982 return oparg-1;
983 case UNPACK_EX:
984 return (oparg&0xFF) + (oparg>>8);
985 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200986 /* -1 at end of iterator, 1 if continue iterating. */
987 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case STORE_ATTR:
990 return -2;
991 case DELETE_ATTR:
992 return -1;
993 case STORE_GLOBAL:
994 return -1;
995 case DELETE_GLOBAL:
996 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case LOAD_CONST:
998 return 1;
999 case LOAD_NAME:
1000 return 1;
1001 case BUILD_TUPLE:
1002 case BUILD_LIST:
1003 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001004 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001006 case BUILD_LIST_UNPACK:
1007 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001008 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001009 case BUILD_SET_UNPACK:
1010 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001011 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001012 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001014 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001015 case BUILD_CONST_KEY_MAP:
1016 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 case LOAD_ATTR:
1018 return 0;
1019 case COMPARE_OP:
1020 return -1;
1021 case IMPORT_NAME:
1022 return -1;
1023 case IMPORT_FROM:
1024 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001026 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case JUMP_ABSOLUTE:
1029 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001031 case JUMP_IF_TRUE_OR_POP:
1032 case JUMP_IF_FALSE_OR_POP:
1033 return jump ? 0 : -1;
1034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case POP_JUMP_IF_FALSE:
1036 case POP_JUMP_IF_TRUE:
1037 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case LOAD_GLOBAL:
1040 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case CONTINUE_LOOP:
1043 return 0;
1044 case SETUP_LOOP:
1045 return 0;
1046 case SETUP_EXCEPT:
1047 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* 0 in the normal flow.
1049 * Restore the stack position and push 6 values before jumping to
1050 * the handler if an exception be raised. */
1051 return jump ? 6 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 case LOAD_FAST:
1054 return 1;
1055 case STORE_FAST:
1056 return -1;
1057 case DELETE_FAST:
1058 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001059 case STORE_ANNOTATION:
1060 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 case RAISE_VARARGS:
1063 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001064
1065 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001067 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001068 case CALL_METHOD:
1069 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001071 return -oparg-1;
1072 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001073 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001074 case MAKE_FUNCTION:
1075 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1076 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 case BUILD_SLICE:
1078 if (oparg == 3)
1079 return -2;
1080 else
1081 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001083 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 case LOAD_CLOSURE:
1085 return 1;
1086 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001087 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 return 1;
1089 case STORE_DEREF:
1090 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001091 case DELETE_DEREF:
1092 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001093
1094 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001095 case GET_AWAITABLE:
1096 return 0;
1097 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098 /* 0 in the normal flow.
1099 * Restore the stack position to the position before the result
1100 * of __aenter__ and push 6 values before jumping to the handler
1101 * if an exception be raised. */
1102 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001103 case BEFORE_ASYNC_WITH:
1104 return 1;
1105 case GET_AITER:
1106 return 0;
1107 case GET_ANEXT:
1108 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001109 case GET_YIELD_FROM_ITER:
1110 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001111 case FORMAT_VALUE:
1112 /* If there's a fmt_spec on the stack, we go from 2->1,
1113 else 1->1. */
1114 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001115 case LOAD_METHOD:
1116 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001118 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 }
Larry Hastings3a907972013-11-23 14:49:22 -08001120 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121}
1122
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001123int
1124PyCompile_OpcodeStackEffect(int opcode, int oparg)
1125{
1126 return stack_effect(opcode, oparg, -1);
1127}
1128
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129/* Add an opcode with no argument.
1130 Returns 0 on failure, 1 on success.
1131*/
1132
1133static int
1134compiler_addop(struct compiler *c, int opcode)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 basicblock *b;
1137 struct instr *i;
1138 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001139 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 off = compiler_next_instr(c, c->u->u_curblock);
1141 if (off < 0)
1142 return 0;
1143 b = c->u->u_curblock;
1144 i = &b->b_instr[off];
1145 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001146 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (opcode == RETURN_VALUE)
1148 b->b_return = 1;
1149 compiler_set_lineno(c, off);
1150 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151}
1152
Victor Stinnerf8e32212013-11-19 23:56:34 +01001153static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 PyObject *t, *v;
1157 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158
Victor Stinnerefb24132016-01-22 12:33:12 +01001159 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (t == NULL)
1161 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 v = PyDict_GetItem(dict, t);
1164 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001165 if (PyErr_Occurred()) {
1166 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001168 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001169 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001170 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (!v) {
1172 Py_DECREF(t);
1173 return -1;
1174 }
1175 if (PyDict_SetItem(dict, t, v) < 0) {
1176 Py_DECREF(t);
1177 Py_DECREF(v);
1178 return -1;
1179 }
1180 Py_DECREF(v);
1181 }
1182 else
1183 arg = PyLong_AsLong(v);
1184 Py_DECREF(t);
1185 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
1188static int
1189compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001192 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001194 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 return compiler_addop_i(c, opcode, arg);
1196}
1197
1198static int
1199compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001202 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1204 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001205 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 arg = compiler_add_o(c, dict, mangled);
1207 Py_DECREF(mangled);
1208 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001209 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 return compiler_addop_i(c, opcode, arg);
1211}
1212
1213/* Add an opcode with an integer argument.
1214 Returns 0 on failure, 1 on success.
1215*/
1216
1217static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001218compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 struct instr *i;
1221 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001222
Victor Stinner2ad474b2016-03-01 23:34:47 +01001223 /* oparg value is unsigned, but a signed C int is usually used to store
1224 it in the C code (like Python/ceval.c).
1225
1226 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1227
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001228 The argument of a concrete bytecode instruction is limited to 8-bit.
1229 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1230 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001231 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 off = compiler_next_instr(c, c->u->u_curblock);
1234 if (off < 0)
1235 return 0;
1236 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001237 i->i_opcode = opcode;
1238 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 compiler_set_lineno(c, off);
1240 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241}
1242
1243static int
1244compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 struct instr *i;
1247 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001248
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001249 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 assert(b != NULL);
1251 off = compiler_next_instr(c, c->u->u_curblock);
1252 if (off < 0)
1253 return 0;
1254 i = &c->u->u_curblock->b_instr[off];
1255 i->i_opcode = opcode;
1256 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (absolute)
1258 i->i_jabs = 1;
1259 else
1260 i->i_jrel = 1;
1261 compiler_set_lineno(c, off);
1262 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001265/* NEXT_BLOCK() creates an implicit jump from the current block
1266 to the new block.
1267
1268 The returns inside this macro make it impossible to decref objects
1269 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (compiler_next_block((C)) == NULL) \
1273 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
1276#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!compiler_addop((C), (OP))) \
1278 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001281#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_addop((C), (OP))) { \
1283 compiler_exit_scope(c); \
1284 return 0; \
1285 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001286}
1287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1290 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291}
1292
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001293/* Same as ADDOP_O, but steals a reference. */
1294#define ADDOP_N(C, OP, O, TYPE) { \
1295 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1296 Py_DECREF((O)); \
1297 return 0; \
1298 } \
1299 Py_DECREF((O)); \
1300}
1301
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1304 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305}
1306
1307#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (!compiler_addop_i((C), (OP), (O))) \
1309 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (!compiler_addop_j((C), (OP), (O), 1)) \
1314 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315}
1316
1317#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (!compiler_addop_j((C), (OP), (O), 0)) \
1319 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320}
1321
1322/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1323 the ASDL name to synthesize the name of the C type and the visit function.
1324*/
1325
1326#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (!compiler_visit_ ## TYPE((C), (V))) \
1328 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329}
1330
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001331#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (!compiler_visit_ ## TYPE((C), (V))) { \
1333 compiler_exit_scope(c); \
1334 return 0; \
1335 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001336}
1337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (!compiler_visit_slice((C), (V), (CTX))) \
1340 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341}
1342
1343#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 int _i; \
1345 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1346 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1347 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1348 if (!compiler_visit_ ## TYPE((C), elt)) \
1349 return 0; \
1350 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351}
1352
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001353#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 int _i; \
1355 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1356 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1357 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1358 if (!compiler_visit_ ## TYPE((C), elt)) { \
1359 compiler_exit_scope(c); \
1360 return 0; \
1361 } \
1362 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001363}
1364
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001366is_const(expr_ty e)
1367{
1368 switch (e->kind) {
1369 case Constant_kind:
1370 case Num_kind:
1371 case Str_kind:
1372 case Bytes_kind:
1373 case Ellipsis_kind:
1374 case NameConstant_kind:
1375 return 1;
1376 default:
1377 return 0;
1378 }
1379}
1380
1381static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001382get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001383{
1384 switch (e->kind) {
1385 case Constant_kind:
1386 return e->v.Constant.value;
1387 case Num_kind:
1388 return e->v.Num.n;
1389 case Str_kind:
1390 return e->v.Str.s;
1391 case Bytes_kind:
1392 return e->v.Bytes.s;
1393 case Ellipsis_kind:
1394 return Py_Ellipsis;
1395 case NameConstant_kind:
1396 return e->v.NameConstant.value;
1397 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001398 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001399 }
1400}
1401
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001402/* Search if variable annotations are present statically in a block. */
1403
1404static int
1405find_ann(asdl_seq *stmts)
1406{
1407 int i, j, res = 0;
1408 stmt_ty st;
1409
1410 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1411 st = (stmt_ty)asdl_seq_GET(stmts, i);
1412 switch (st->kind) {
1413 case AnnAssign_kind:
1414 return 1;
1415 case For_kind:
1416 res = find_ann(st->v.For.body) ||
1417 find_ann(st->v.For.orelse);
1418 break;
1419 case AsyncFor_kind:
1420 res = find_ann(st->v.AsyncFor.body) ||
1421 find_ann(st->v.AsyncFor.orelse);
1422 break;
1423 case While_kind:
1424 res = find_ann(st->v.While.body) ||
1425 find_ann(st->v.While.orelse);
1426 break;
1427 case If_kind:
1428 res = find_ann(st->v.If.body) ||
1429 find_ann(st->v.If.orelse);
1430 break;
1431 case With_kind:
1432 res = find_ann(st->v.With.body);
1433 break;
1434 case AsyncWith_kind:
1435 res = find_ann(st->v.AsyncWith.body);
1436 break;
1437 case Try_kind:
1438 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1439 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1440 st->v.Try.handlers, j);
1441 if (find_ann(handler->v.ExceptHandler.body)) {
1442 return 1;
1443 }
1444 }
1445 res = find_ann(st->v.Try.body) ||
1446 find_ann(st->v.Try.finalbody) ||
1447 find_ann(st->v.Try.orelse);
1448 break;
1449 default:
1450 res = 0;
1451 }
1452 if (res) {
1453 break;
1454 }
1455 }
1456 return res;
1457}
1458
1459/* Compile a sequence of statements, checking for a docstring
1460 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461
1462static int
INADA Naokicb41b272017-02-23 00:31:59 +09001463compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001465 /* Set current line number to the line number of first statement.
1466 This way line number for SETUP_ANNOTATIONS will always
1467 coincide with the line number of first "real" statement in module.
1468 If body is empy, then lineno will be set later in assemble. */
1469 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1470 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001471 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001472 c->u->u_lineno = st->lineno;
1473 }
1474 /* Every annotated class and module should have __annotations__. */
1475 if (find_ann(stmts)) {
1476 ADDOP(c, SETUP_ANNOTATIONS);
1477 }
INADA Naokicb41b272017-02-23 00:31:59 +09001478 /* if not -OO mode, set docstring */
1479 if (c->c_optimize < 2 && docstring) {
1480 ADDOP_O(c, LOAD_CONST, docstring, consts);
1481 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 }
INADA Naokicb41b272017-02-23 00:31:59 +09001483 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485}
1486
1487static PyCodeObject *
1488compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyCodeObject *co;
1491 int addNone = 1;
1492 static PyObject *module;
1493 if (!module) {
1494 module = PyUnicode_InternFromString("<module>");
1495 if (!module)
1496 return NULL;
1497 }
1498 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001499 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 return NULL;
1501 switch (mod->kind) {
1502 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001503 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 compiler_exit_scope(c);
1505 return 0;
1506 }
1507 break;
1508 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001509 if (find_ann(mod->v.Interactive.body)) {
1510 ADDOP(c, SETUP_ANNOTATIONS);
1511 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 c->c_interactive = 1;
1513 VISIT_SEQ_IN_SCOPE(c, stmt,
1514 mod->v.Interactive.body);
1515 break;
1516 case Expression_kind:
1517 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1518 addNone = 0;
1519 break;
1520 case Suite_kind:
1521 PyErr_SetString(PyExc_SystemError,
1522 "suite should not be possible");
1523 return 0;
1524 default:
1525 PyErr_Format(PyExc_SystemError,
1526 "module kind %d should not be possible",
1527 mod->kind);
1528 return 0;
1529 }
1530 co = assemble(c, addNone);
1531 compiler_exit_scope(c);
1532 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001533}
1534
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535/* The test for LOCAL must come before the test for FREE in order to
1536 handle classes where name is both local and free. The local var is
1537 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001538*/
1539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540static int
1541get_ref_type(struct compiler *c, PyObject *name)
1542{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001543 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001544 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001545 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001546 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001547 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (scope == 0) {
1549 char buf[350];
1550 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001551 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001553 PyUnicode_AsUTF8(name),
1554 PyUnicode_AsUTF8(c->u->u_name),
1555 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1556 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1557 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1558 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 );
1560 Py_FatalError(buf);
1561 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001564}
1565
1566static int
1567compiler_lookup_arg(PyObject *dict, PyObject *name)
1568{
1569 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001570 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001571 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001572 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001574 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001576 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001577 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001578}
1579
1580static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001581compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001583 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001584 if (qualname == NULL)
1585 qualname = co->co_name;
1586
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001587 if (free) {
1588 for (i = 0; i < free; ++i) {
1589 /* Bypass com_addop_varname because it will generate
1590 LOAD_DEREF but LOAD_CLOSURE is needed.
1591 */
1592 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1593 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001595 /* Special case: If a class contains a method with a
1596 free variable that has the same name as a method,
1597 the name will be considered free *and* local in the
1598 class. It should be handled by the closure, as
1599 well as by the normal name loookup logic.
1600 */
1601 reftype = get_ref_type(c, name);
1602 if (reftype == CELL)
1603 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1604 else /* (reftype == FREE) */
1605 arg = compiler_lookup_arg(c->u->u_freevars, name);
1606 if (arg == -1) {
1607 fprintf(stderr,
1608 "lookup %s in %s %d %d\n"
1609 "freevars of %s: %s\n",
1610 PyUnicode_AsUTF8(PyObject_Repr(name)),
1611 PyUnicode_AsUTF8(c->u->u_name),
1612 reftype, arg,
1613 PyUnicode_AsUTF8(co->co_name),
1614 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1615 Py_FatalError("compiler_make_closure()");
1616 }
1617 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001619 flags |= 0x08;
1620 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001623 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001624 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626}
1627
1628static int
1629compiler_decorators(struct compiler *c, asdl_seq* decos)
1630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (!decos)
1634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1637 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1638 }
1639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640}
1641
1642static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001643compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001645{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001646 /* Push a dict of keyword-only default values.
1647
1648 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1649 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001650 int i;
1651 PyObject *keys = NULL;
1652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1654 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1655 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1656 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001657 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001658 if (!mangled) {
1659 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001661 if (keys == NULL) {
1662 keys = PyList_New(1);
1663 if (keys == NULL) {
1664 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001665 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001666 }
1667 PyList_SET_ITEM(keys, 0, mangled);
1668 }
1669 else {
1670 int res = PyList_Append(keys, mangled);
1671 Py_DECREF(mangled);
1672 if (res == -1) {
1673 goto error;
1674 }
1675 }
1676 if (!compiler_visit_expr(c, default_)) {
1677 goto error;
1678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 }
1680 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001681 if (keys != NULL) {
1682 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1683 PyObject *keys_tuple = PyList_AsTuple(keys);
1684 Py_DECREF(keys);
1685 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001686 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001687 }
1688 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1689 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001690 assert(default_count > 0);
1691 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001692 }
1693 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001694 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001695 }
1696
1697error:
1698 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001699 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001700}
1701
1702static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001703compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1704{
1705 PyObject *ann_as_str;
1706 ann_as_str = _PyAST_ExprAsUnicode(annotation, 1);
1707 if (!ann_as_str) {
1708 return 0;
1709 }
1710 ADDOP_N(c, LOAD_CONST, ann_as_str, consts);
1711 return 1;
1712}
1713
1714static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001715compiler_visit_argannotation(struct compiler *c, identifier id,
1716 expr_ty annotation, PyObject *names)
1717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001719 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001720 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1721 VISIT(c, annexpr, annotation)
1722 }
1723 else {
1724 VISIT(c, expr, annotation);
1725 }
Victor Stinner065efc32014-02-18 22:07:56 +01001726 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001727 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001728 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001729 if (PyList_Append(names, mangled) < 0) {
1730 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001731 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001732 }
1733 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001735 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001736}
1737
1738static int
1739compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1740 PyObject *names)
1741{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001742 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 for (i = 0; i < asdl_seq_LEN(args); i++) {
1744 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001745 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 c,
1747 arg->arg,
1748 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001749 names))
1750 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001752 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001753}
1754
1755static int
1756compiler_visit_annotations(struct compiler *c, arguments_ty args,
1757 expr_ty returns)
1758{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001759 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001760 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001761
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001762 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 */
1764 static identifier return_str;
1765 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001766 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 names = PyList_New(0);
1768 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001769 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001770
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001771 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001773 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001774 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001775 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001777 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001779 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001780 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001781 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (!return_str) {
1785 return_str = PyUnicode_InternFromString("return");
1786 if (!return_str)
1787 goto error;
1788 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001789 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 goto error;
1791 }
1792
1793 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001795 PyObject *keytuple = PyList_AsTuple(names);
1796 Py_DECREF(names);
1797 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001798 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001800 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1801 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001802 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001804 else {
1805 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001806 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001807 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001808
1809error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001811 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001812}
1813
1814static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001815compiler_visit_defaults(struct compiler *c, arguments_ty args)
1816{
1817 VISIT_SEQ(c, expr, args->defaults);
1818 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820}
1821
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001822static Py_ssize_t
1823compiler_default_arguments(struct compiler *c, arguments_ty args)
1824{
1825 Py_ssize_t funcflags = 0;
1826 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001827 if (!compiler_visit_defaults(c, args))
1828 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001829 funcflags |= 0x01;
1830 }
1831 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001832 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001833 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001834 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001835 return -1;
1836 }
1837 else if (res > 0) {
1838 funcflags |= 0x02;
1839 }
1840 }
1841 return funcflags;
1842}
1843
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844static int
Yury Selivanov75445082015-05-11 22:57:16 -04001845compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001848 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001849 arguments_ty args;
1850 expr_ty returns;
1851 identifier name;
1852 asdl_seq* decos;
1853 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001854 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001855 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001856 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857
Yury Selivanov75445082015-05-11 22:57:16 -04001858 if (is_async) {
1859 assert(s->kind == AsyncFunctionDef_kind);
1860
1861 args = s->v.AsyncFunctionDef.args;
1862 returns = s->v.AsyncFunctionDef.returns;
1863 decos = s->v.AsyncFunctionDef.decorator_list;
1864 name = s->v.AsyncFunctionDef.name;
1865 body = s->v.AsyncFunctionDef.body;
1866
1867 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1868 } else {
1869 assert(s->kind == FunctionDef_kind);
1870
1871 args = s->v.FunctionDef.args;
1872 returns = s->v.FunctionDef.returns;
1873 decos = s->v.FunctionDef.decorator_list;
1874 name = s->v.FunctionDef.name;
1875 body = s->v.FunctionDef.body;
1876
1877 scope_type = COMPILER_SCOPE_FUNCTION;
1878 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (!compiler_decorators(c, decos))
1881 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001882
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001883 funcflags = compiler_default_arguments(c, args);
1884 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001886 }
1887
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001888 annotations = compiler_visit_annotations(c, args, returns);
1889 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001890 return 0;
1891 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001892 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001893 funcflags |= 0x04;
1894 }
1895
1896 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1897 return 0;
1898 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899
INADA Naokicb41b272017-02-23 00:31:59 +09001900 /* if not -OO mode, add docstring */
1901 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1902 docstring = s->v.FunctionDef.docstring;
1903 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 compiler_exit_scope(c);
1905 return 0;
1906 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 c->u->u_argcount = asdl_seq_LEN(args->args);
1909 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001911 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001913 qualname = c->u->u_qualname;
1914 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001916 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001917 Py_XDECREF(qualname);
1918 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001920 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001923 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 /* decorators */
1927 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1928 ADDOP_I(c, CALL_FUNCTION, 1);
1929 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930
Yury Selivanov75445082015-05-11 22:57:16 -04001931 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932}
1933
1934static int
1935compiler_class(struct compiler *c, stmt_ty s)
1936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyCodeObject *co;
1938 PyObject *str;
1939 int i;
1940 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 if (!compiler_decorators(c, decos))
1943 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* ultimately generate code for:
1946 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1947 where:
1948 <func> is a function/closure created from the class body;
1949 it has a single argument (__locals__) where the dict
1950 (or MutableSequence) representing the locals is passed
1951 <name> is the class name
1952 <bases> is the positional arguments and *varargs argument
1953 <keywords> is the keyword arguments and **kwds argument
1954 This borrows from compiler_call.
1955 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001958 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1959 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 return 0;
1961 /* this block represents what we do in the new scope */
1962 {
1963 /* use the class name for name mangling */
1964 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001965 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 /* load (global) __name__ ... */
1967 str = PyUnicode_InternFromString("__name__");
1968 if (!str || !compiler_nameop(c, str, Load)) {
1969 Py_XDECREF(str);
1970 compiler_exit_scope(c);
1971 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 Py_DECREF(str);
1974 /* ... and store it as __module__ */
1975 str = PyUnicode_InternFromString("__module__");
1976 if (!str || !compiler_nameop(c, str, Store)) {
1977 Py_XDECREF(str);
1978 compiler_exit_scope(c);
1979 return 0;
1980 }
1981 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001982 assert(c->u->u_qualname);
1983 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001984 str = PyUnicode_InternFromString("__qualname__");
1985 if (!str || !compiler_nameop(c, str, Store)) {
1986 Py_XDECREF(str);
1987 compiler_exit_scope(c);
1988 return 0;
1989 }
1990 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001992 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 compiler_exit_scope(c);
1994 return 0;
1995 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001996 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001997 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001998 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001999 str = PyUnicode_InternFromString("__class__");
2000 if (str == NULL) {
2001 compiler_exit_scope(c);
2002 return 0;
2003 }
2004 i = compiler_lookup_arg(c->u->u_cellvars, str);
2005 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002006 if (i < 0) {
2007 compiler_exit_scope(c);
2008 return 0;
2009 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002010 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002013 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002014 str = PyUnicode_InternFromString("__classcell__");
2015 if (!str || !compiler_nameop(c, str, Store)) {
2016 Py_XDECREF(str);
2017 compiler_exit_scope(c);
2018 return 0;
2019 }
2020 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002022 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002023 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002024 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10002025 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002026 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002027 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* create the code object */
2029 co = assemble(c, 1);
2030 }
2031 /* leave the new scope */
2032 compiler_exit_scope(c);
2033 if (co == NULL)
2034 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* 2. load the 'build_class' function */
2037 ADDOP(c, LOAD_BUILD_CLASS);
2038
2039 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002040 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 Py_DECREF(co);
2042
2043 /* 4. load class name */
2044 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2045
2046 /* 5. generate the rest of the code for the call */
2047 if (!compiler_call_helper(c, 2,
2048 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002049 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 return 0;
2051
2052 /* 6. apply decorators */
2053 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2054 ADDOP_I(c, CALL_FUNCTION, 1);
2055 }
2056
2057 /* 7. store into <name> */
2058 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2059 return 0;
2060 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061}
2062
2063static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002064cmpop(cmpop_ty op)
2065{
2066 switch (op) {
2067 case Eq:
2068 return PyCmp_EQ;
2069 case NotEq:
2070 return PyCmp_NE;
2071 case Lt:
2072 return PyCmp_LT;
2073 case LtE:
2074 return PyCmp_LE;
2075 case Gt:
2076 return PyCmp_GT;
2077 case GtE:
2078 return PyCmp_GE;
2079 case Is:
2080 return PyCmp_IS;
2081 case IsNot:
2082 return PyCmp_IS_NOT;
2083 case In:
2084 return PyCmp_IN;
2085 case NotIn:
2086 return PyCmp_NOT_IN;
2087 default:
2088 return PyCmp_BAD;
2089 }
2090}
2091
2092static int
2093compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2094{
2095 switch (e->kind) {
2096 case UnaryOp_kind:
2097 if (e->v.UnaryOp.op == Not)
2098 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2099 /* fallback to general implementation */
2100 break;
2101 case BoolOp_kind: {
2102 asdl_seq *s = e->v.BoolOp.values;
2103 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2104 assert(n >= 0);
2105 int cond2 = e->v.BoolOp.op == Or;
2106 basicblock *next2 = next;
2107 if (!cond2 != !cond) {
2108 next2 = compiler_new_block(c);
2109 if (next2 == NULL)
2110 return 0;
2111 }
2112 for (i = 0; i < n; ++i) {
2113 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2114 return 0;
2115 }
2116 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2117 return 0;
2118 if (next2 != next)
2119 compiler_use_next_block(c, next2);
2120 return 1;
2121 }
2122 case IfExp_kind: {
2123 basicblock *end, *next2;
2124 end = compiler_new_block(c);
2125 if (end == NULL)
2126 return 0;
2127 next2 = compiler_new_block(c);
2128 if (next2 == NULL)
2129 return 0;
2130 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2131 return 0;
2132 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2133 return 0;
2134 ADDOP_JREL(c, JUMP_FORWARD, end);
2135 compiler_use_next_block(c, next2);
2136 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2137 return 0;
2138 compiler_use_next_block(c, end);
2139 return 1;
2140 }
2141 case Compare_kind: {
2142 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2143 if (n > 0) {
2144 basicblock *cleanup = compiler_new_block(c);
2145 if (cleanup == NULL)
2146 return 0;
2147 VISIT(c, expr, e->v.Compare.left);
2148 for (i = 0; i < n; i++) {
2149 VISIT(c, expr,
2150 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2151 ADDOP(c, DUP_TOP);
2152 ADDOP(c, ROT_THREE);
2153 ADDOP_I(c, COMPARE_OP,
2154 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2155 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2156 NEXT_BLOCK(c);
2157 }
2158 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2159 ADDOP_I(c, COMPARE_OP,
2160 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2161 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2162 basicblock *end = compiler_new_block(c);
2163 if (end == NULL)
2164 return 0;
2165 ADDOP_JREL(c, JUMP_FORWARD, end);
2166 compiler_use_next_block(c, cleanup);
2167 ADDOP(c, POP_TOP);
2168 if (!cond) {
2169 ADDOP_JREL(c, JUMP_FORWARD, next);
2170 }
2171 compiler_use_next_block(c, end);
2172 return 1;
2173 }
2174 /* fallback to general implementation */
2175 break;
2176 }
2177 default:
2178 /* fallback to general implementation */
2179 break;
2180 }
2181
2182 /* general implementation */
2183 VISIT(c, expr, e);
2184 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2185 return 1;
2186}
2187
2188static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002189compiler_ifexp(struct compiler *c, expr_ty e)
2190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 basicblock *end, *next;
2192
2193 assert(e->kind == IfExp_kind);
2194 end = compiler_new_block(c);
2195 if (end == NULL)
2196 return 0;
2197 next = compiler_new_block(c);
2198 if (next == NULL)
2199 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002200 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2201 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 VISIT(c, expr, e->v.IfExp.body);
2203 ADDOP_JREL(c, JUMP_FORWARD, end);
2204 compiler_use_next_block(c, next);
2205 VISIT(c, expr, e->v.IfExp.orelse);
2206 compiler_use_next_block(c, end);
2207 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002208}
2209
2210static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211compiler_lambda(struct compiler *c, expr_ty e)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002214 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002216 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 arguments_ty args = e->v.Lambda.args;
2218 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (!name) {
2221 name = PyUnicode_InternFromString("<lambda>");
2222 if (!name)
2223 return 0;
2224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002226 funcflags = compiler_default_arguments(c, args);
2227 if (funcflags == -1) {
2228 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002230
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002231 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002232 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* Make None the first constant, so the lambda can't have a
2236 docstring. */
2237 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2238 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 c->u->u_argcount = asdl_seq_LEN(args->args);
2241 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2242 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2243 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002244 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
2246 else {
2247 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002248 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002250 qualname = c->u->u_qualname;
2251 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002253 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002256 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002257 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 Py_DECREF(co);
2259
2260 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261}
2262
2263static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264compiler_if(struct compiler *c, stmt_ty s)
2265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 basicblock *end, *next;
2267 int constant;
2268 assert(s->kind == If_kind);
2269 end = compiler_new_block(c);
2270 if (end == NULL)
2271 return 0;
2272
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002273 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* constant = 0: "if 0"
2275 * constant = 1: "if 1", "if 2", ...
2276 * constant = -1: rest */
2277 if (constant == 0) {
2278 if (s->v.If.orelse)
2279 VISIT_SEQ(c, stmt, s->v.If.orelse);
2280 } else if (constant == 1) {
2281 VISIT_SEQ(c, stmt, s->v.If.body);
2282 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002283 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 next = compiler_new_block(c);
2285 if (next == NULL)
2286 return 0;
2287 }
2288 else
2289 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002290 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2291 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002293 if (asdl_seq_LEN(s->v.If.orelse)) {
2294 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 compiler_use_next_block(c, next);
2296 VISIT_SEQ(c, stmt, s->v.If.orelse);
2297 }
2298 }
2299 compiler_use_next_block(c, end);
2300 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301}
2302
2303static int
2304compiler_for(struct compiler *c, stmt_ty s)
2305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 start = compiler_new_block(c);
2309 cleanup = compiler_new_block(c);
2310 end = compiler_new_block(c);
2311 if (start == NULL || end == NULL || cleanup == NULL)
2312 return 0;
2313 ADDOP_JREL(c, SETUP_LOOP, end);
2314 if (!compiler_push_fblock(c, LOOP, start))
2315 return 0;
2316 VISIT(c, expr, s->v.For.iter);
2317 ADDOP(c, GET_ITER);
2318 compiler_use_next_block(c, start);
2319 ADDOP_JREL(c, FOR_ITER, cleanup);
2320 VISIT(c, expr, s->v.For.target);
2321 VISIT_SEQ(c, stmt, s->v.For.body);
2322 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2323 compiler_use_next_block(c, cleanup);
2324 ADDOP(c, POP_BLOCK);
2325 compiler_pop_fblock(c, LOOP, start);
2326 VISIT_SEQ(c, stmt, s->v.For.orelse);
2327 compiler_use_next_block(c, end);
2328 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329}
2330
Yury Selivanov75445082015-05-11 22:57:16 -04002331
2332static int
2333compiler_async_for(struct compiler *c, stmt_ty s)
2334{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002335 _Py_IDENTIFIER(StopAsyncIteration);
2336
Yury Selivanov75445082015-05-11 22:57:16 -04002337 basicblock *try, *except, *end, *after_try, *try_cleanup,
2338 *after_loop, *after_loop_else;
2339
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002340 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2341 if (stop_aiter_error == NULL) {
2342 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002343 }
2344
2345 try = compiler_new_block(c);
2346 except = compiler_new_block(c);
2347 end = compiler_new_block(c);
2348 after_try = compiler_new_block(c);
2349 try_cleanup = compiler_new_block(c);
2350 after_loop = compiler_new_block(c);
2351 after_loop_else = compiler_new_block(c);
2352
2353 if (try == NULL || except == NULL || end == NULL
2354 || after_try == NULL || try_cleanup == NULL)
2355 return 0;
2356
2357 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2358 if (!compiler_push_fblock(c, LOOP, try))
2359 return 0;
2360
2361 VISIT(c, expr, s->v.AsyncFor.iter);
2362 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002363
2364 compiler_use_next_block(c, try);
2365
2366
2367 ADDOP_JREL(c, SETUP_EXCEPT, except);
2368 if (!compiler_push_fblock(c, EXCEPT, try))
2369 return 0;
2370
2371 ADDOP(c, GET_ANEXT);
2372 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2373 ADDOP(c, YIELD_FROM);
2374 VISIT(c, expr, s->v.AsyncFor.target);
2375 ADDOP(c, POP_BLOCK);
2376 compiler_pop_fblock(c, EXCEPT, try);
2377 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2378
2379
2380 compiler_use_next_block(c, except);
2381 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002382 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002383 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2384 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2385
2386 ADDOP(c, POP_TOP);
2387 ADDOP(c, POP_TOP);
2388 ADDOP(c, POP_TOP);
2389 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002390 ADDOP(c, POP_TOP); /* for correct calculation of stack effect */
Yury Selivanov75445082015-05-11 22:57:16 -04002391 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2392 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2393
2394
2395 compiler_use_next_block(c, try_cleanup);
2396 ADDOP(c, END_FINALLY);
2397
2398 compiler_use_next_block(c, after_try);
2399 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2400 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2401
2402 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2403 compiler_pop_fblock(c, LOOP, try);
2404
2405 compiler_use_next_block(c, after_loop);
2406 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2407
2408 compiler_use_next_block(c, after_loop_else);
2409 VISIT_SEQ(c, stmt, s->v.For.orelse);
2410
2411 compiler_use_next_block(c, end);
2412
2413 return 1;
2414}
2415
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416static int
2417compiler_while(struct compiler *c, stmt_ty s)
2418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002420 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (constant == 0) {
2423 if (s->v.While.orelse)
2424 VISIT_SEQ(c, stmt, s->v.While.orelse);
2425 return 1;
2426 }
2427 loop = compiler_new_block(c);
2428 end = compiler_new_block(c);
2429 if (constant == -1) {
2430 anchor = compiler_new_block(c);
2431 if (anchor == NULL)
2432 return 0;
2433 }
2434 if (loop == NULL || end == NULL)
2435 return 0;
2436 if (s->v.While.orelse) {
2437 orelse = compiler_new_block(c);
2438 if (orelse == NULL)
2439 return 0;
2440 }
2441 else
2442 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 ADDOP_JREL(c, SETUP_LOOP, end);
2445 compiler_use_next_block(c, loop);
2446 if (!compiler_push_fblock(c, LOOP, loop))
2447 return 0;
2448 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2450 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 }
2452 VISIT_SEQ(c, stmt, s->v.While.body);
2453 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 /* XXX should the two POP instructions be in a separate block
2456 if there is no else clause ?
2457 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002459 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002461 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 compiler_pop_fblock(c, LOOP, loop);
2463 if (orelse != NULL) /* what if orelse is just pass? */
2464 VISIT_SEQ(c, stmt, s->v.While.orelse);
2465 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468}
2469
2470static int
2471compiler_continue(struct compiler *c)
2472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2474 static const char IN_FINALLY_ERROR_MSG[] =
2475 "'continue' not supported inside 'finally' clause";
2476 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (!c->u->u_nfblocks)
2479 return compiler_error(c, LOOP_ERROR_MSG);
2480 i = c->u->u_nfblocks - 1;
2481 switch (c->u->u_fblock[i].fb_type) {
2482 case LOOP:
2483 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2484 break;
2485 case EXCEPT:
2486 case FINALLY_TRY:
2487 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2488 /* Prevent continue anywhere under a finally
2489 even if hidden in a sub-try or except. */
2490 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2491 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2492 }
2493 if (i == -1)
2494 return compiler_error(c, LOOP_ERROR_MSG);
2495 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2496 break;
2497 case FINALLY_END:
2498 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002502}
2503
2504/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505
2506 SETUP_FINALLY L
2507 <code for body>
2508 POP_BLOCK
2509 LOAD_CONST <None>
2510 L: <code for finalbody>
2511 END_FINALLY
2512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 The special instructions use the block stack. Each block
2514 stack entry contains the instruction that created it (here
2515 SETUP_FINALLY), the level of the value stack at the time the
2516 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 Pushes the current value stack level and the label
2520 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 Pops en entry from the block stack, and pops the value
2523 stack until its level is the same as indicated on the
2524 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 Pops a variable number of entries from the *value* stack
2527 and re-raises the exception they specify. The number of
2528 entries popped depends on the (pseudo) exception type.
2529
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 The block stack is unwound when an exception is raised:
2531 when a SETUP_FINALLY entry is found, the exception is pushed
2532 onto the value stack (and the exception condition is cleared),
2533 and the interpreter jumps to the label gotten from the block
2534 stack.
2535*/
2536
2537static int
2538compiler_try_finally(struct compiler *c, stmt_ty s)
2539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 basicblock *body, *end;
2541 body = compiler_new_block(c);
2542 end = compiler_new_block(c);
2543 if (body == NULL || end == NULL)
2544 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 ADDOP_JREL(c, SETUP_FINALLY, end);
2547 compiler_use_next_block(c, body);
2548 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2549 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002550 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2551 if (!compiler_try_except(c, s))
2552 return 0;
2553 }
2554 else {
2555 VISIT_SEQ(c, stmt, s->v.Try.body);
2556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 ADDOP(c, POP_BLOCK);
2558 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2561 compiler_use_next_block(c, end);
2562 if (!compiler_push_fblock(c, FINALLY_END, end))
2563 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002564 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 ADDOP(c, END_FINALLY);
2566 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569}
2570
2571/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002572 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 (The contents of the value stack is shown in [], with the top
2574 at the right; 'tb' is trace-back info, 'val' the exception's
2575 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576
2577 Value stack Label Instruction Argument
2578 [] SETUP_EXCEPT L1
2579 [] <code for S>
2580 [] POP_BLOCK
2581 [] JUMP_FORWARD L0
2582
2583 [tb, val, exc] L1: DUP )
2584 [tb, val, exc, exc] <evaluate E1> )
2585 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2586 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2587 [tb, val, exc] POP
2588 [tb, val] <assign to V1> (or POP if no V1)
2589 [tb] POP
2590 [] <code for S1>
2591 JUMP_FORWARD L0
2592
2593 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 .............................etc.......................
2595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2597
2598 [] L0: <next statement>
2599
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 Of course, parts are not generated if Vi or Ei is not present.
2601*/
2602static int
2603compiler_try_except(struct compiler *c, stmt_ty s)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002606 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 body = compiler_new_block(c);
2609 except = compiler_new_block(c);
2610 orelse = compiler_new_block(c);
2611 end = compiler_new_block(c);
2612 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2613 return 0;
2614 ADDOP_JREL(c, SETUP_EXCEPT, except);
2615 compiler_use_next_block(c, body);
2616 if (!compiler_push_fblock(c, EXCEPT, body))
2617 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002618 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 ADDOP(c, POP_BLOCK);
2620 compiler_pop_fblock(c, EXCEPT, body);
2621 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002622 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 compiler_use_next_block(c, except);
2624 for (i = 0; i < n; i++) {
2625 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002626 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (!handler->v.ExceptHandler.type && i < n-1)
2628 return compiler_error(c, "default 'except:' must be last");
2629 c->u->u_lineno_set = 0;
2630 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002631 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 except = compiler_new_block(c);
2633 if (except == NULL)
2634 return 0;
2635 if (handler->v.ExceptHandler.type) {
2636 ADDOP(c, DUP_TOP);
2637 VISIT(c, expr, handler->v.ExceptHandler.type);
2638 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2639 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2640 }
2641 ADDOP(c, POP_TOP);
2642 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002643 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002644
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002645 cleanup_end = compiler_new_block(c);
2646 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002647 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002648 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002649
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002650 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2651 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002653 /*
2654 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002655 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002656 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002657 try:
2658 # body
2659 finally:
2660 name = None
2661 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002662 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002664 /* second try: */
2665 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2666 compiler_use_next_block(c, cleanup_body);
2667 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2668 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002670 /* second # body */
2671 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2672 ADDOP(c, POP_BLOCK);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002673 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002675 /* finally: */
2676 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2677 compiler_use_next_block(c, cleanup_end);
2678 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2679 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002681 /* name = None */
2682 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2683 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002685 /* del name */
2686 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002688 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002689 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002690 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 }
2692 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002693 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002695 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002696 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002697 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698
Guido van Rossumb940e112007-01-10 16:19:56 +00002699 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002700 ADDOP(c, POP_TOP);
2701 compiler_use_next_block(c, cleanup_body);
2702 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2703 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002705 ADDOP(c, POP_EXCEPT);
2706 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 }
2708 ADDOP_JREL(c, JUMP_FORWARD, end);
2709 compiler_use_next_block(c, except);
2710 }
2711 ADDOP(c, END_FINALLY);
2712 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002713 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 compiler_use_next_block(c, end);
2715 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716}
2717
2718static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002719compiler_try(struct compiler *c, stmt_ty s) {
2720 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2721 return compiler_try_finally(c, s);
2722 else
2723 return compiler_try_except(c, s);
2724}
2725
2726
2727static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728compiler_import_as(struct compiler *c, identifier name, identifier asname)
2729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 /* The IMPORT_NAME opcode was already generated. This function
2731 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002734 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002736 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2737 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002738 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002739 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002742 while (1) {
2743 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002745 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002746 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002747 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002748 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002750 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002751 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002753 if (dot == -1) {
2754 break;
2755 }
2756 ADDOP(c, ROT_TWO);
2757 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002759 if (!compiler_nameop(c, asname, Store)) {
2760 return 0;
2761 }
2762 ADDOP(c, POP_TOP);
2763 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 }
2765 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766}
2767
2768static int
2769compiler_import(struct compiler *c, stmt_ty s)
2770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* The Import node stores a module name like a.b.c as a single
2772 string. This is convenient for all cases except
2773 import a.b.c as d
2774 where we need to parse that string to extract the individual
2775 module names.
2776 XXX Perhaps change the representation to make this case simpler?
2777 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002778 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 for (i = 0; i < n; i++) {
2781 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2782 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002783
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002784 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2786 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 if (alias->asname) {
2789 r = compiler_import_as(c, alias->name, alias->asname);
2790 if (!r)
2791 return r;
2792 }
2793 else {
2794 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002795 Py_ssize_t dot = PyUnicode_FindChar(
2796 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002797 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002798 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002799 if (tmp == NULL)
2800 return 0;
2801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002803 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 Py_DECREF(tmp);
2805 }
2806 if (!r)
2807 return r;
2808 }
2809 }
2810 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811}
2812
2813static int
2814compiler_from_import(struct compiler *c, stmt_ty s)
2815{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002816 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 PyObject *names = PyTuple_New(n);
2819 PyObject *level;
2820 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 if (!empty_string) {
2823 empty_string = PyUnicode_FromString("");
2824 if (!empty_string)
2825 return 0;
2826 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 if (!names)
2829 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 level = PyLong_FromLong(s->v.ImportFrom.level);
2832 if (!level) {
2833 Py_DECREF(names);
2834 return 0;
2835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 /* build up the names */
2838 for (i = 0; i < n; i++) {
2839 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2840 Py_INCREF(alias->name);
2841 PyTuple_SET_ITEM(names, i, alias->name);
2842 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002845 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 Py_DECREF(level);
2847 Py_DECREF(names);
2848 return compiler_error(c, "from __future__ imports must occur "
2849 "at the beginning of the file");
2850 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 ADDOP_O(c, LOAD_CONST, level, consts);
2853 Py_DECREF(level);
2854 ADDOP_O(c, LOAD_CONST, names, consts);
2855 Py_DECREF(names);
2856 if (s->v.ImportFrom.module) {
2857 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2858 }
2859 else {
2860 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2861 }
2862 for (i = 0; i < n; i++) {
2863 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2864 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002866 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 assert(n == 1);
2868 ADDOP(c, IMPORT_STAR);
2869 return 1;
2870 }
2871
2872 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2873 store_name = alias->name;
2874 if (alias->asname)
2875 store_name = alias->asname;
2876
2877 if (!compiler_nameop(c, store_name, Store)) {
2878 Py_DECREF(names);
2879 return 0;
2880 }
2881 }
2882 /* remove imported module */
2883 ADDOP(c, POP_TOP);
2884 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885}
2886
2887static int
2888compiler_assert(struct compiler *c, stmt_ty s)
2889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 static PyObject *assertion_error = NULL;
2891 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002892 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893
Georg Brandl8334fd92010-12-04 10:26:46 +00002894 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 return 1;
2896 if (assertion_error == NULL) {
2897 assertion_error = PyUnicode_InternFromString("AssertionError");
2898 if (assertion_error == NULL)
2899 return 0;
2900 }
2901 if (s->v.Assert.test->kind == Tuple_kind &&
2902 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002903 msg = PyUnicode_FromString("assertion is always true, "
2904 "perhaps remove parentheses?");
2905 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002907 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2908 c->c_filename, c->u->u_lineno,
2909 NULL, NULL) == -1) {
2910 Py_DECREF(msg);
2911 return 0;
2912 }
2913 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 end = compiler_new_block(c);
2916 if (end == NULL)
2917 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002918 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2919 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2921 if (s->v.Assert.msg) {
2922 VISIT(c, expr, s->v.Assert.msg);
2923 ADDOP_I(c, CALL_FUNCTION, 1);
2924 }
2925 ADDOP_I(c, RAISE_VARARGS, 1);
2926 compiler_use_next_block(c, end);
2927 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928}
2929
2930static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002931compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2932{
2933 if (c->c_interactive && c->c_nestlevel <= 1) {
2934 VISIT(c, expr, value);
2935 ADDOP(c, PRINT_EXPR);
2936 return 1;
2937 }
2938
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002939 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002940 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002941 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002942 }
2943
2944 VISIT(c, expr, value);
2945 ADDOP(c, POP_TOP);
2946 return 1;
2947}
2948
2949static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950compiler_visit_stmt(struct compiler *c, stmt_ty s)
2951{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002952 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 /* Always assign a lineno to the next instruction for a stmt. */
2955 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002956 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 switch (s->kind) {
2960 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002961 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 case ClassDef_kind:
2963 return compiler_class(c, s);
2964 case Return_kind:
2965 if (c->u->u_ste->ste_type != FunctionBlock)
2966 return compiler_error(c, "'return' outside function");
2967 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002968 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2969 return compiler_error(
2970 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 VISIT(c, expr, s->v.Return.value);
2972 }
2973 else
2974 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2975 ADDOP(c, RETURN_VALUE);
2976 break;
2977 case Delete_kind:
2978 VISIT_SEQ(c, expr, s->v.Delete.targets)
2979 break;
2980 case Assign_kind:
2981 n = asdl_seq_LEN(s->v.Assign.targets);
2982 VISIT(c, expr, s->v.Assign.value);
2983 for (i = 0; i < n; i++) {
2984 if (i < n - 1)
2985 ADDOP(c, DUP_TOP);
2986 VISIT(c, expr,
2987 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2988 }
2989 break;
2990 case AugAssign_kind:
2991 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002992 case AnnAssign_kind:
2993 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 case For_kind:
2995 return compiler_for(c, s);
2996 case While_kind:
2997 return compiler_while(c, s);
2998 case If_kind:
2999 return compiler_if(c, s);
3000 case Raise_kind:
3001 n = 0;
3002 if (s->v.Raise.exc) {
3003 VISIT(c, expr, s->v.Raise.exc);
3004 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003005 if (s->v.Raise.cause) {
3006 VISIT(c, expr, s->v.Raise.cause);
3007 n++;
3008 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003010 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003012 case Try_kind:
3013 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 case Assert_kind:
3015 return compiler_assert(c, s);
3016 case Import_kind:
3017 return compiler_import(c, s);
3018 case ImportFrom_kind:
3019 return compiler_from_import(c, s);
3020 case Global_kind:
3021 case Nonlocal_kind:
3022 break;
3023 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003024 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 case Pass_kind:
3026 break;
3027 case Break_kind:
3028 if (!compiler_in_loop(c))
3029 return compiler_error(c, "'break' outside loop");
3030 ADDOP(c, BREAK_LOOP);
3031 break;
3032 case Continue_kind:
3033 return compiler_continue(c);
3034 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003035 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003036 case AsyncFunctionDef_kind:
3037 return compiler_function(c, s, 1);
3038 case AsyncWith_kind:
3039 return compiler_async_with(c, s, 0);
3040 case AsyncFor_kind:
3041 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 }
Yury Selivanov75445082015-05-11 22:57:16 -04003043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045}
3046
3047static int
3048unaryop(unaryop_ty op)
3049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 switch (op) {
3051 case Invert:
3052 return UNARY_INVERT;
3053 case Not:
3054 return UNARY_NOT;
3055 case UAdd:
3056 return UNARY_POSITIVE;
3057 case USub:
3058 return UNARY_NEGATIVE;
3059 default:
3060 PyErr_Format(PyExc_SystemError,
3061 "unary op %d should not be possible", op);
3062 return 0;
3063 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064}
3065
3066static int
3067binop(struct compiler *c, operator_ty op)
3068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 switch (op) {
3070 case Add:
3071 return BINARY_ADD;
3072 case Sub:
3073 return BINARY_SUBTRACT;
3074 case Mult:
3075 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003076 case MatMult:
3077 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 case Div:
3079 return BINARY_TRUE_DIVIDE;
3080 case Mod:
3081 return BINARY_MODULO;
3082 case Pow:
3083 return BINARY_POWER;
3084 case LShift:
3085 return BINARY_LSHIFT;
3086 case RShift:
3087 return BINARY_RSHIFT;
3088 case BitOr:
3089 return BINARY_OR;
3090 case BitXor:
3091 return BINARY_XOR;
3092 case BitAnd:
3093 return BINARY_AND;
3094 case FloorDiv:
3095 return BINARY_FLOOR_DIVIDE;
3096 default:
3097 PyErr_Format(PyExc_SystemError,
3098 "binary op %d should not be possible", op);
3099 return 0;
3100 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101}
3102
3103static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104inplace_binop(struct compiler *c, operator_ty op)
3105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 switch (op) {
3107 case Add:
3108 return INPLACE_ADD;
3109 case Sub:
3110 return INPLACE_SUBTRACT;
3111 case Mult:
3112 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003113 case MatMult:
3114 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 case Div:
3116 return INPLACE_TRUE_DIVIDE;
3117 case Mod:
3118 return INPLACE_MODULO;
3119 case Pow:
3120 return INPLACE_POWER;
3121 case LShift:
3122 return INPLACE_LSHIFT;
3123 case RShift:
3124 return INPLACE_RSHIFT;
3125 case BitOr:
3126 return INPLACE_OR;
3127 case BitXor:
3128 return INPLACE_XOR;
3129 case BitAnd:
3130 return INPLACE_AND;
3131 case FloorDiv:
3132 return INPLACE_FLOOR_DIVIDE;
3133 default:
3134 PyErr_Format(PyExc_SystemError,
3135 "inplace binary op %d should not be possible", op);
3136 return 0;
3137 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138}
3139
3140static int
3141compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3142{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003143 int op, scope;
3144 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 PyObject *dict = c->u->u_names;
3148 PyObject *mangled;
3149 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003151 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3152 !_PyUnicode_EqualToASCIIString(name, "True") &&
3153 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003154
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003155 mangled = _Py_Mangle(c->u->u_private, name);
3156 if (!mangled)
3157 return 0;
3158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 op = 0;
3160 optype = OP_NAME;
3161 scope = PyST_GetScope(c->u->u_ste, mangled);
3162 switch (scope) {
3163 case FREE:
3164 dict = c->u->u_freevars;
3165 optype = OP_DEREF;
3166 break;
3167 case CELL:
3168 dict = c->u->u_cellvars;
3169 optype = OP_DEREF;
3170 break;
3171 case LOCAL:
3172 if (c->u->u_ste->ste_type == FunctionBlock)
3173 optype = OP_FAST;
3174 break;
3175 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003176 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 optype = OP_GLOBAL;
3178 break;
3179 case GLOBAL_EXPLICIT:
3180 optype = OP_GLOBAL;
3181 break;
3182 default:
3183 /* scope can be 0 */
3184 break;
3185 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003188 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 switch (optype) {
3191 case OP_DEREF:
3192 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003193 case Load:
3194 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3195 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 case Store: op = STORE_DEREF; break;
3197 case AugLoad:
3198 case AugStore:
3199 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003200 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 case Param:
3202 default:
3203 PyErr_SetString(PyExc_SystemError,
3204 "param invalid for deref variable");
3205 return 0;
3206 }
3207 break;
3208 case OP_FAST:
3209 switch (ctx) {
3210 case Load: op = LOAD_FAST; break;
3211 case Store: op = STORE_FAST; break;
3212 case Del: op = DELETE_FAST; break;
3213 case AugLoad:
3214 case AugStore:
3215 break;
3216 case Param:
3217 default:
3218 PyErr_SetString(PyExc_SystemError,
3219 "param invalid for local variable");
3220 return 0;
3221 }
3222 ADDOP_O(c, op, mangled, varnames);
3223 Py_DECREF(mangled);
3224 return 1;
3225 case OP_GLOBAL:
3226 switch (ctx) {
3227 case Load: op = LOAD_GLOBAL; break;
3228 case Store: op = STORE_GLOBAL; break;
3229 case Del: op = DELETE_GLOBAL; break;
3230 case AugLoad:
3231 case AugStore:
3232 break;
3233 case Param:
3234 default:
3235 PyErr_SetString(PyExc_SystemError,
3236 "param invalid for global variable");
3237 return 0;
3238 }
3239 break;
3240 case OP_NAME:
3241 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003242 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 case Store: op = STORE_NAME; break;
3244 case Del: op = DELETE_NAME; break;
3245 case AugLoad:
3246 case AugStore:
3247 break;
3248 case Param:
3249 default:
3250 PyErr_SetString(PyExc_SystemError,
3251 "param invalid for name variable");
3252 return 0;
3253 }
3254 break;
3255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 assert(op);
3258 arg = compiler_add_o(c, dict, mangled);
3259 Py_DECREF(mangled);
3260 if (arg < 0)
3261 return 0;
3262 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263}
3264
3265static int
3266compiler_boolop(struct compiler *c, expr_ty e)
3267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003269 int jumpi;
3270 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 assert(e->kind == BoolOp_kind);
3274 if (e->v.BoolOp.op == And)
3275 jumpi = JUMP_IF_FALSE_OR_POP;
3276 else
3277 jumpi = JUMP_IF_TRUE_OR_POP;
3278 end = compiler_new_block(c);
3279 if (end == NULL)
3280 return 0;
3281 s = e->v.BoolOp.values;
3282 n = asdl_seq_LEN(s) - 1;
3283 assert(n >= 0);
3284 for (i = 0; i < n; ++i) {
3285 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3286 ADDOP_JABS(c, jumpi, end);
3287 }
3288 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3289 compiler_use_next_block(c, end);
3290 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291}
3292
3293static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003294starunpack_helper(struct compiler *c, asdl_seq *elts,
3295 int single_op, int inner_op, int outer_op)
3296{
3297 Py_ssize_t n = asdl_seq_LEN(elts);
3298 Py_ssize_t i, nsubitems = 0, nseen = 0;
3299 for (i = 0; i < n; i++) {
3300 expr_ty elt = asdl_seq_GET(elts, i);
3301 if (elt->kind == Starred_kind) {
3302 if (nseen) {
3303 ADDOP_I(c, inner_op, nseen);
3304 nseen = 0;
3305 nsubitems++;
3306 }
3307 VISIT(c, expr, elt->v.Starred.value);
3308 nsubitems++;
3309 }
3310 else {
3311 VISIT(c, expr, elt);
3312 nseen++;
3313 }
3314 }
3315 if (nsubitems) {
3316 if (nseen) {
3317 ADDOP_I(c, inner_op, nseen);
3318 nsubitems++;
3319 }
3320 ADDOP_I(c, outer_op, nsubitems);
3321 }
3322 else
3323 ADDOP_I(c, single_op, nseen);
3324 return 1;
3325}
3326
3327static int
3328assignment_helper(struct compiler *c, asdl_seq *elts)
3329{
3330 Py_ssize_t n = asdl_seq_LEN(elts);
3331 Py_ssize_t i;
3332 int seen_star = 0;
3333 for (i = 0; i < n; i++) {
3334 expr_ty elt = asdl_seq_GET(elts, i);
3335 if (elt->kind == Starred_kind && !seen_star) {
3336 if ((i >= (1 << 8)) ||
3337 (n-i-1 >= (INT_MAX >> 8)))
3338 return compiler_error(c,
3339 "too many expressions in "
3340 "star-unpacking assignment");
3341 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3342 seen_star = 1;
3343 asdl_seq_SET(elts, i, elt->v.Starred.value);
3344 }
3345 else if (elt->kind == Starred_kind) {
3346 return compiler_error(c,
3347 "two starred expressions in assignment");
3348 }
3349 }
3350 if (!seen_star) {
3351 ADDOP_I(c, UNPACK_SEQUENCE, n);
3352 }
3353 VISIT_SEQ(c, expr, elts);
3354 return 1;
3355}
3356
3357static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358compiler_list(struct compiler *c, expr_ty e)
3359{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003360 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003362 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003364 else if (e->v.List.ctx == Load) {
3365 return starunpack_helper(c, elts,
3366 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003368 else
3369 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371}
3372
3373static int
3374compiler_tuple(struct compiler *c, expr_ty e)
3375{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003376 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003378 return assignment_helper(c, elts);
3379 }
3380 else if (e->v.Tuple.ctx == Load) {
3381 return starunpack_helper(c, elts,
3382 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3383 }
3384 else
3385 VISIT_SEQ(c, expr, elts);
3386 return 1;
3387}
3388
3389static int
3390compiler_set(struct compiler *c, expr_ty e)
3391{
3392 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3393 BUILD_SET, BUILD_SET_UNPACK);
3394}
3395
3396static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003397are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3398{
3399 Py_ssize_t i;
3400 for (i = begin; i < end; i++) {
3401 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3402 if (key == NULL || !is_const(key))
3403 return 0;
3404 }
3405 return 1;
3406}
3407
3408static int
3409compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3410{
3411 Py_ssize_t i, n = end - begin;
3412 PyObject *keys, *key;
3413 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3414 for (i = begin; i < end; i++) {
3415 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3416 }
3417 keys = PyTuple_New(n);
3418 if (keys == NULL) {
3419 return 0;
3420 }
3421 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003422 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003423 Py_INCREF(key);
3424 PyTuple_SET_ITEM(keys, i - begin, key);
3425 }
3426 ADDOP_N(c, LOAD_CONST, keys, consts);
3427 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3428 }
3429 else {
3430 for (i = begin; i < end; i++) {
3431 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3432 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3433 }
3434 ADDOP_I(c, BUILD_MAP, n);
3435 }
3436 return 1;
3437}
3438
3439static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003440compiler_dict(struct compiler *c, expr_ty e)
3441{
Victor Stinner976bb402016-03-23 11:36:19 +01003442 Py_ssize_t i, n, elements;
3443 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003444 int is_unpacking = 0;
3445 n = asdl_seq_LEN(e->v.Dict.values);
3446 containers = 0;
3447 elements = 0;
3448 for (i = 0; i < n; i++) {
3449 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3450 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003451 if (!compiler_subdict(c, e, i - elements, i))
3452 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003453 containers++;
3454 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003456 if (is_unpacking) {
3457 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3458 containers++;
3459 }
3460 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003461 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 }
3463 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003464 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003465 if (!compiler_subdict(c, e, n - elements, n))
3466 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003467 containers++;
3468 }
3469 /* If there is more than one dict, they need to be merged into a new
3470 * dict. If there is one dict and it's an unpacking, then it needs
3471 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003472 if (containers > 1 || is_unpacking) {
3473 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 }
3475 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476}
3477
3478static int
3479compiler_compare(struct compiler *c, expr_ty e)
3480{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003481 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003484 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3485 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3486 if (n == 0) {
3487 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3488 ADDOP_I(c, COMPARE_OP,
3489 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3490 }
3491 else {
3492 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 if (cleanup == NULL)
3494 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003495 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 VISIT(c, expr,
3497 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003498 ADDOP(c, DUP_TOP);
3499 ADDOP(c, ROT_THREE);
3500 ADDOP_I(c, COMPARE_OP,
3501 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3502 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3503 NEXT_BLOCK(c);
3504 }
3505 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3506 ADDOP_I(c, COMPARE_OP,
3507 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 basicblock *end = compiler_new_block(c);
3509 if (end == NULL)
3510 return 0;
3511 ADDOP_JREL(c, JUMP_FORWARD, end);
3512 compiler_use_next_block(c, cleanup);
3513 ADDOP(c, ROT_TWO);
3514 ADDOP(c, POP_TOP);
3515 compiler_use_next_block(c, end);
3516 }
3517 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518}
3519
3520static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003521maybe_optimize_method_call(struct compiler *c, expr_ty e)
3522{
3523 Py_ssize_t argsl, i;
3524 expr_ty meth = e->v.Call.func;
3525 asdl_seq *args = e->v.Call.args;
3526
3527 /* Check that the call node is an attribute access, and that
3528 the call doesn't have keyword parameters. */
3529 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3530 asdl_seq_LEN(e->v.Call.keywords))
3531 return -1;
3532
3533 /* Check that there are no *varargs types of arguments. */
3534 argsl = asdl_seq_LEN(args);
3535 for (i = 0; i < argsl; i++) {
3536 expr_ty elt = asdl_seq_GET(args, i);
3537 if (elt->kind == Starred_kind) {
3538 return -1;
3539 }
3540 }
3541
3542 /* Alright, we can optimize the code. */
3543 VISIT(c, expr, meth->v.Attribute.value);
3544 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3545 VISIT_SEQ(c, expr, e->v.Call.args);
3546 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3547 return 1;
3548}
3549
3550static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551compiler_call(struct compiler *c, expr_ty e)
3552{
Yury Selivanovf2392132016-12-13 19:03:51 -05003553 if (maybe_optimize_method_call(c, e) > 0)
3554 return 1;
3555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 VISIT(c, expr, e->v.Call.func);
3557 return compiler_call_helper(c, 0,
3558 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003559 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003560}
3561
Eric V. Smith235a6f02015-09-19 14:51:32 -04003562static int
3563compiler_joined_str(struct compiler *c, expr_ty e)
3564{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003565 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003566 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3567 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003568 return 1;
3569}
3570
Eric V. Smitha78c7952015-11-03 12:45:05 -05003571/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003572static int
3573compiler_formatted_value(struct compiler *c, expr_ty e)
3574{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003575 /* Our oparg encodes 2 pieces of information: the conversion
3576 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003577
Eric V. Smitha78c7952015-11-03 12:45:05 -05003578 Convert the conversion char to 2 bits:
3579 None: 000 0x0 FVC_NONE
3580 !s : 001 0x1 FVC_STR
3581 !r : 010 0x2 FVC_REPR
3582 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003583
Eric V. Smitha78c7952015-11-03 12:45:05 -05003584 next bit is whether or not we have a format spec:
3585 yes : 100 0x4
3586 no : 000 0x0
3587 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003588
Eric V. Smitha78c7952015-11-03 12:45:05 -05003589 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003590
Eric V. Smitha78c7952015-11-03 12:45:05 -05003591 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003592 VISIT(c, expr, e->v.FormattedValue.value);
3593
Eric V. Smitha78c7952015-11-03 12:45:05 -05003594 switch (e->v.FormattedValue.conversion) {
3595 case 's': oparg = FVC_STR; break;
3596 case 'r': oparg = FVC_REPR; break;
3597 case 'a': oparg = FVC_ASCII; break;
3598 case -1: oparg = FVC_NONE; break;
3599 default:
3600 PyErr_SetString(PyExc_SystemError,
3601 "Unrecognized conversion character");
3602 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003603 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003604 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003605 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003606 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003607 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003608 }
3609
Eric V. Smitha78c7952015-11-03 12:45:05 -05003610 /* And push our opcode and oparg */
3611 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003612 return 1;
3613}
3614
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003615static int
3616compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3617{
3618 Py_ssize_t i, n = end - begin;
3619 keyword_ty kw;
3620 PyObject *keys, *key;
3621 assert(n > 0);
3622 if (n > 1) {
3623 for (i = begin; i < end; i++) {
3624 kw = asdl_seq_GET(keywords, i);
3625 VISIT(c, expr, kw->value);
3626 }
3627 keys = PyTuple_New(n);
3628 if (keys == NULL) {
3629 return 0;
3630 }
3631 for (i = begin; i < end; i++) {
3632 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3633 Py_INCREF(key);
3634 PyTuple_SET_ITEM(keys, i - begin, key);
3635 }
3636 ADDOP_N(c, LOAD_CONST, keys, consts);
3637 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3638 }
3639 else {
3640 /* a for loop only executes once */
3641 for (i = begin; i < end; i++) {
3642 kw = asdl_seq_GET(keywords, i);
3643 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3644 VISIT(c, expr, kw->value);
3645 }
3646 ADDOP_I(c, BUILD_MAP, n);
3647 }
3648 return 1;
3649}
3650
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003651/* shared code between compiler_call and compiler_class */
3652static int
3653compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003654 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003655 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003656 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003657{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003658 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003659 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003660
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003661 /* the number of tuples and dictionaries on the stack */
3662 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3663
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003664 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003665 nkwelts = asdl_seq_LEN(keywords);
3666
3667 for (i = 0; i < nkwelts; i++) {
3668 keyword_ty kw = asdl_seq_GET(keywords, i);
3669 if (kw->arg == NULL) {
3670 mustdictunpack = 1;
3671 break;
3672 }
3673 }
3674
3675 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003676 for (i = 0; i < nelts; i++) {
3677 expr_ty elt = asdl_seq_GET(args, i);
3678 if (elt->kind == Starred_kind) {
3679 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003680 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003681 if (nseen) {
3682 ADDOP_I(c, BUILD_TUPLE, nseen);
3683 nseen = 0;
3684 nsubargs++;
3685 }
3686 VISIT(c, expr, elt->v.Starred.value);
3687 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003688 }
3689 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003690 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003691 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003694
3695 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003696 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003697 if (nseen) {
3698 /* Pack up any trailing positional arguments. */
3699 ADDOP_I(c, BUILD_TUPLE, nseen);
3700 nsubargs++;
3701 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003702 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003703 /* If we ended up with more than one stararg, we need
3704 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003705 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003706 }
3707 else if (nsubargs == 0) {
3708 ADDOP_I(c, BUILD_TUPLE, 0);
3709 }
3710 nseen = 0; /* the number of keyword arguments on the stack following */
3711 for (i = 0; i < nkwelts; i++) {
3712 keyword_ty kw = asdl_seq_GET(keywords, i);
3713 if (kw->arg == NULL) {
3714 /* A keyword argument unpacking. */
3715 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003716 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3717 return 0;
3718 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003719 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003720 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003721 VISIT(c, expr, kw->value);
3722 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003723 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003724 else {
3725 nseen++;
3726 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003728 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003729 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003730 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003731 return 0;
3732 nsubkwargs++;
3733 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003734 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003735 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003736 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003738 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3739 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003741 else if (nkwelts) {
3742 PyObject *names;
3743 VISIT_SEQ(c, keyword, keywords);
3744 names = PyTuple_New(nkwelts);
3745 if (names == NULL) {
3746 return 0;
3747 }
3748 for (i = 0; i < nkwelts; i++) {
3749 keyword_ty kw = asdl_seq_GET(keywords, i);
3750 Py_INCREF(kw->arg);
3751 PyTuple_SET_ITEM(names, i, kw->arg);
3752 }
3753 ADDOP_N(c, LOAD_CONST, names, consts);
3754 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3755 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003757 else {
3758 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3759 return 1;
3760 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761}
3762
Nick Coghlan650f0d02007-04-15 12:05:43 +00003763
3764/* List and set comprehensions and generator expressions work by creating a
3765 nested function to perform the actual iteration. This means that the
3766 iteration variables don't leak into the current scope.
3767 The defined function is called immediately following its definition, with the
3768 result of that call being the result of the expression.
3769 The LC/SC version returns the populated container, while the GE version is
3770 flagged in symtable.c as a generator, so it returns the generator object
3771 when the function is called.
3772 This code *knows* that the loop cannot contain break, continue, or return,
3773 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3774
3775 Possible cleanups:
3776 - iterate over the generator sequence instead of using recursion
3777*/
3778
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781compiler_comprehension_generator(struct compiler *c,
3782 asdl_seq *generators, int gen_index,
3783 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003785 comprehension_ty gen;
3786 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3787 if (gen->is_async) {
3788 return compiler_async_comprehension_generator(
3789 c, generators, gen_index, elt, val, type);
3790 } else {
3791 return compiler_sync_comprehension_generator(
3792 c, generators, gen_index, elt, val, type);
3793 }
3794}
3795
3796static int
3797compiler_sync_comprehension_generator(struct compiler *c,
3798 asdl_seq *generators, int gen_index,
3799 expr_ty elt, expr_ty val, int type)
3800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 /* generate code for the iterator, then each of the ifs,
3802 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 comprehension_ty gen;
3805 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003806 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 start = compiler_new_block(c);
3809 skip = compiler_new_block(c);
3810 if_cleanup = compiler_new_block(c);
3811 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3814 anchor == NULL)
3815 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 if (gen_index == 0) {
3820 /* Receive outermost iter as an implicit argument */
3821 c->u->u_argcount = 1;
3822 ADDOP_I(c, LOAD_FAST, 0);
3823 }
3824 else {
3825 /* Sub-iter - calculate on the fly */
3826 VISIT(c, expr, gen->iter);
3827 ADDOP(c, GET_ITER);
3828 }
3829 compiler_use_next_block(c, start);
3830 ADDOP_JREL(c, FOR_ITER, anchor);
3831 NEXT_BLOCK(c);
3832 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 /* XXX this needs to be cleaned up...a lot! */
3835 n = asdl_seq_LEN(gen->ifs);
3836 for (i = 0; i < n; i++) {
3837 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003838 if (!compiler_jump_if(c, e, if_cleanup, 0))
3839 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 NEXT_BLOCK(c);
3841 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 if (++gen_index < asdl_seq_LEN(generators))
3844 if (!compiler_comprehension_generator(c,
3845 generators, gen_index,
3846 elt, val, type))
3847 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 /* only append after the last for generator */
3850 if (gen_index >= asdl_seq_LEN(generators)) {
3851 /* comprehension specific code */
3852 switch (type) {
3853 case COMP_GENEXP:
3854 VISIT(c, expr, elt);
3855 ADDOP(c, YIELD_VALUE);
3856 ADDOP(c, POP_TOP);
3857 break;
3858 case COMP_LISTCOMP:
3859 VISIT(c, expr, elt);
3860 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3861 break;
3862 case COMP_SETCOMP:
3863 VISIT(c, expr, elt);
3864 ADDOP_I(c, SET_ADD, gen_index + 1);
3865 break;
3866 case COMP_DICTCOMP:
3867 /* With 'd[k] = v', v is evaluated before k, so we do
3868 the same. */
3869 VISIT(c, expr, val);
3870 VISIT(c, expr, elt);
3871 ADDOP_I(c, MAP_ADD, gen_index + 1);
3872 break;
3873 default:
3874 return 0;
3875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 compiler_use_next_block(c, skip);
3878 }
3879 compiler_use_next_block(c, if_cleanup);
3880 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3881 compiler_use_next_block(c, anchor);
3882
3883 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884}
3885
3886static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003887compiler_async_comprehension_generator(struct compiler *c,
3888 asdl_seq *generators, int gen_index,
3889 expr_ty elt, expr_ty val, int type)
3890{
3891 _Py_IDENTIFIER(StopAsyncIteration);
3892
3893 comprehension_ty gen;
3894 basicblock *anchor, *skip, *if_cleanup, *try,
3895 *after_try, *except, *try_cleanup;
3896 Py_ssize_t i, n;
3897
3898 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3899 if (stop_aiter_error == NULL) {
3900 return 0;
3901 }
3902
3903 try = compiler_new_block(c);
3904 after_try = compiler_new_block(c);
3905 try_cleanup = compiler_new_block(c);
3906 except = compiler_new_block(c);
3907 skip = compiler_new_block(c);
3908 if_cleanup = compiler_new_block(c);
3909 anchor = compiler_new_block(c);
3910
3911 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3912 try == NULL || after_try == NULL ||
3913 except == NULL || after_try == NULL) {
3914 return 0;
3915 }
3916
3917 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3918
3919 if (gen_index == 0) {
3920 /* Receive outermost iter as an implicit argument */
3921 c->u->u_argcount = 1;
3922 ADDOP_I(c, LOAD_FAST, 0);
3923 }
3924 else {
3925 /* Sub-iter - calculate on the fly */
3926 VISIT(c, expr, gen->iter);
3927 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003928 }
3929
3930 compiler_use_next_block(c, try);
3931
3932
3933 ADDOP_JREL(c, SETUP_EXCEPT, except);
3934 if (!compiler_push_fblock(c, EXCEPT, try))
3935 return 0;
3936
3937 ADDOP(c, GET_ANEXT);
3938 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3939 ADDOP(c, YIELD_FROM);
3940 VISIT(c, expr, gen->target);
3941 ADDOP(c, POP_BLOCK);
3942 compiler_pop_fblock(c, EXCEPT, try);
3943 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3944
3945
3946 compiler_use_next_block(c, except);
3947 ADDOP(c, DUP_TOP);
3948 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3949 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3950 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3951
3952 ADDOP(c, POP_TOP);
3953 ADDOP(c, POP_TOP);
3954 ADDOP(c, POP_TOP);
3955 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3956 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3957
3958
3959 compiler_use_next_block(c, try_cleanup);
3960 ADDOP(c, END_FINALLY);
3961
3962 compiler_use_next_block(c, after_try);
3963
3964 n = asdl_seq_LEN(gen->ifs);
3965 for (i = 0; i < n; i++) {
3966 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003967 if (!compiler_jump_if(c, e, if_cleanup, 0))
3968 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003969 NEXT_BLOCK(c);
3970 }
3971
3972 if (++gen_index < asdl_seq_LEN(generators))
3973 if (!compiler_comprehension_generator(c,
3974 generators, gen_index,
3975 elt, val, type))
3976 return 0;
3977
3978 /* only append after the last for generator */
3979 if (gen_index >= asdl_seq_LEN(generators)) {
3980 /* comprehension specific code */
3981 switch (type) {
3982 case COMP_GENEXP:
3983 VISIT(c, expr, elt);
3984 ADDOP(c, YIELD_VALUE);
3985 ADDOP(c, POP_TOP);
3986 break;
3987 case COMP_LISTCOMP:
3988 VISIT(c, expr, elt);
3989 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3990 break;
3991 case COMP_SETCOMP:
3992 VISIT(c, expr, elt);
3993 ADDOP_I(c, SET_ADD, gen_index + 1);
3994 break;
3995 case COMP_DICTCOMP:
3996 /* With 'd[k] = v', v is evaluated before k, so we do
3997 the same. */
3998 VISIT(c, expr, val);
3999 VISIT(c, expr, elt);
4000 ADDOP_I(c, MAP_ADD, gen_index + 1);
4001 break;
4002 default:
4003 return 0;
4004 }
4005
4006 compiler_use_next_block(c, skip);
4007 }
4008 compiler_use_next_block(c, if_cleanup);
4009 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
4010 compiler_use_next_block(c, anchor);
4011 ADDOP(c, POP_TOP);
4012
4013 return 1;
4014}
4015
4016static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004017compiler_comprehension(struct compiler *c, expr_ty e, int type,
4018 identifier name, asdl_seq *generators, expr_ty elt,
4019 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004022 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004023 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004024 int is_async_function = c->u->u_ste->ste_coroutine;
4025 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004026
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004027 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004028
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004029 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4030 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004031 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004033 }
4034
4035 is_async_generator = c->u->u_ste->ste_coroutine;
4036
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004037 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004038 if (e->lineno > c->u->u_lineno) {
4039 c->u->u_lineno = e->lineno;
4040 c->u->u_lineno_set = 0;
4041 }
4042 compiler_error(c, "asynchronous comprehension outside of "
4043 "an asynchronous function");
4044 goto error_in_scope;
4045 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 if (type != COMP_GENEXP) {
4048 int op;
4049 switch (type) {
4050 case COMP_LISTCOMP:
4051 op = BUILD_LIST;
4052 break;
4053 case COMP_SETCOMP:
4054 op = BUILD_SET;
4055 break;
4056 case COMP_DICTCOMP:
4057 op = BUILD_MAP;
4058 break;
4059 default:
4060 PyErr_Format(PyExc_SystemError,
4061 "unknown comprehension type %d", type);
4062 goto error_in_scope;
4063 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 ADDOP_I(c, op, 0);
4066 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 if (!compiler_comprehension_generator(c, generators, 0, elt,
4069 val, type))
4070 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 if (type != COMP_GENEXP) {
4073 ADDOP(c, RETURN_VALUE);
4074 }
4075
4076 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004077 qualname = c->u->u_qualname;
4078 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004080 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 goto error;
4082
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004083 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004085 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 Py_DECREF(co);
4087
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004088 VISIT(c, expr, outermost->iter);
4089
4090 if (outermost->is_async) {
4091 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004092 } else {
4093 ADDOP(c, GET_ITER);
4094 }
4095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004097
4098 if (is_async_generator && type != COMP_GENEXP) {
4099 ADDOP(c, GET_AWAITABLE);
4100 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4101 ADDOP(c, YIELD_FROM);
4102 }
4103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004105error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004107error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004108 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 Py_XDECREF(co);
4110 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004111}
4112
4113static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114compiler_genexp(struct compiler *c, expr_ty e)
4115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 static identifier name;
4117 if (!name) {
4118 name = PyUnicode_FromString("<genexpr>");
4119 if (!name)
4120 return 0;
4121 }
4122 assert(e->kind == GeneratorExp_kind);
4123 return compiler_comprehension(c, e, COMP_GENEXP, name,
4124 e->v.GeneratorExp.generators,
4125 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126}
4127
4128static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004129compiler_listcomp(struct compiler *c, expr_ty e)
4130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 static identifier name;
4132 if (!name) {
4133 name = PyUnicode_FromString("<listcomp>");
4134 if (!name)
4135 return 0;
4136 }
4137 assert(e->kind == ListComp_kind);
4138 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4139 e->v.ListComp.generators,
4140 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004141}
4142
4143static int
4144compiler_setcomp(struct compiler *c, expr_ty e)
4145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 static identifier name;
4147 if (!name) {
4148 name = PyUnicode_FromString("<setcomp>");
4149 if (!name)
4150 return 0;
4151 }
4152 assert(e->kind == SetComp_kind);
4153 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4154 e->v.SetComp.generators,
4155 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004156}
4157
4158
4159static int
4160compiler_dictcomp(struct compiler *c, expr_ty e)
4161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 static identifier name;
4163 if (!name) {
4164 name = PyUnicode_FromString("<dictcomp>");
4165 if (!name)
4166 return 0;
4167 }
4168 assert(e->kind == DictComp_kind);
4169 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4170 e->v.DictComp.generators,
4171 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004172}
4173
4174
4175static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176compiler_visit_keyword(struct compiler *c, keyword_ty k)
4177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 VISIT(c, expr, k->value);
4179 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004180}
4181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183 whether they are true or false.
4184
4185 Return values: 1 for true, 0 for false, -1 for non-constant.
4186 */
4187
4188static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004189expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004191 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004192 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004193 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004194 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195}
4196
Yury Selivanov75445082015-05-11 22:57:16 -04004197
4198/*
4199 Implements the async with statement.
4200
4201 The semantics outlined in that PEP are as follows:
4202
4203 async with EXPR as VAR:
4204 BLOCK
4205
4206 It is implemented roughly as:
4207
4208 context = EXPR
4209 exit = context.__aexit__ # not calling it
4210 value = await context.__aenter__()
4211 try:
4212 VAR = value # if VAR present in the syntax
4213 BLOCK
4214 finally:
4215 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004216 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004217 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004218 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004219 if not (await exit(*exc)):
4220 raise
4221 */
4222static int
4223compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4224{
4225 basicblock *block, *finally;
4226 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4227
4228 assert(s->kind == AsyncWith_kind);
4229
4230 block = compiler_new_block(c);
4231 finally = compiler_new_block(c);
4232 if (!block || !finally)
4233 return 0;
4234
4235 /* Evaluate EXPR */
4236 VISIT(c, expr, item->context_expr);
4237
4238 ADDOP(c, BEFORE_ASYNC_WITH);
4239 ADDOP(c, GET_AWAITABLE);
4240 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4241 ADDOP(c, YIELD_FROM);
4242
4243 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4244
4245 /* SETUP_ASYNC_WITH pushes a finally block. */
4246 compiler_use_next_block(c, block);
4247 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4248 return 0;
4249 }
4250
4251 if (item->optional_vars) {
4252 VISIT(c, expr, item->optional_vars);
4253 }
4254 else {
4255 /* Discard result from context.__aenter__() */
4256 ADDOP(c, POP_TOP);
4257 }
4258
4259 pos++;
4260 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4261 /* BLOCK code */
4262 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4263 else if (!compiler_async_with(c, s, pos))
4264 return 0;
4265
4266 /* End of try block; start the finally block */
4267 ADDOP(c, POP_BLOCK);
4268 compiler_pop_fblock(c, FINALLY_TRY, block);
4269
4270 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4271 compiler_use_next_block(c, finally);
4272 if (!compiler_push_fblock(c, FINALLY_END, finally))
4273 return 0;
4274
4275 /* Finally block starts; context.__exit__ is on the stack under
4276 the exception or return information. Just issue our magic
4277 opcode. */
4278 ADDOP(c, WITH_CLEANUP_START);
4279
4280 ADDOP(c, GET_AWAITABLE);
4281 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4282 ADDOP(c, YIELD_FROM);
4283
4284 ADDOP(c, WITH_CLEANUP_FINISH);
4285
4286 /* Finally block ends. */
4287 ADDOP(c, END_FINALLY);
4288 compiler_pop_fblock(c, FINALLY_END, finally);
4289 return 1;
4290}
4291
4292
Guido van Rossumc2e20742006-02-27 22:32:47 +00004293/*
4294 Implements the with statement from PEP 343.
4295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004297
4298 with EXPR as VAR:
4299 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300
Guido van Rossumc2e20742006-02-27 22:32:47 +00004301 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302
Thomas Wouters477c8d52006-05-27 19:21:47 +00004303 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004304 exit = context.__exit__ # not calling it
4305 value = context.__enter__()
4306 try:
4307 VAR = value # if VAR present in the syntax
4308 BLOCK
4309 finally:
4310 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004311 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004312 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004313 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004314 exit(*exc)
4315 */
4316static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004317compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004318{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004319 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004320 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004321
4322 assert(s->kind == With_kind);
4323
Guido van Rossumc2e20742006-02-27 22:32:47 +00004324 block = compiler_new_block(c);
4325 finally = compiler_new_block(c);
4326 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004327 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004328
Thomas Wouters477c8d52006-05-27 19:21:47 +00004329 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004330 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004331 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004332
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004333 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004334 compiler_use_next_block(c, block);
4335 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004336 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004337 }
4338
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004339 if (item->optional_vars) {
4340 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004341 }
4342 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004344 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004345 }
4346
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004347 pos++;
4348 if (pos == asdl_seq_LEN(s->v.With.items))
4349 /* BLOCK code */
4350 VISIT_SEQ(c, stmt, s->v.With.body)
4351 else if (!compiler_with(c, s, pos))
4352 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004353
4354 /* End of try block; start the finally block */
4355 ADDOP(c, POP_BLOCK);
4356 compiler_pop_fblock(c, FINALLY_TRY, block);
4357
4358 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4359 compiler_use_next_block(c, finally);
4360 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004361 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004362
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004363 /* Finally block starts; context.__exit__ is on the stack under
4364 the exception or return information. Just issue our magic
4365 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004366 ADDOP(c, WITH_CLEANUP_START);
4367 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004368
4369 /* Finally block ends. */
4370 ADDOP(c, END_FINALLY);
4371 compiler_pop_fblock(c, FINALLY_END, finally);
4372 return 1;
4373}
4374
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375static int
4376compiler_visit_expr(struct compiler *c, expr_ty e)
4377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 /* If expr e has a different line number than the last expr/stmt,
4379 set a new line number for the next instruction.
4380 */
4381 if (e->lineno > c->u->u_lineno) {
4382 c->u->u_lineno = e->lineno;
4383 c->u->u_lineno_set = 0;
4384 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004385 /* Updating the column offset is always harmless. */
4386 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 switch (e->kind) {
4388 case BoolOp_kind:
4389 return compiler_boolop(c, e);
4390 case BinOp_kind:
4391 VISIT(c, expr, e->v.BinOp.left);
4392 VISIT(c, expr, e->v.BinOp.right);
4393 ADDOP(c, binop(c, e->v.BinOp.op));
4394 break;
4395 case UnaryOp_kind:
4396 VISIT(c, expr, e->v.UnaryOp.operand);
4397 ADDOP(c, unaryop(e->v.UnaryOp.op));
4398 break;
4399 case Lambda_kind:
4400 return compiler_lambda(c, e);
4401 case IfExp_kind:
4402 return compiler_ifexp(c, e);
4403 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004404 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004406 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 case GeneratorExp_kind:
4408 return compiler_genexp(c, e);
4409 case ListComp_kind:
4410 return compiler_listcomp(c, e);
4411 case SetComp_kind:
4412 return compiler_setcomp(c, e);
4413 case DictComp_kind:
4414 return compiler_dictcomp(c, e);
4415 case Yield_kind:
4416 if (c->u->u_ste->ste_type != FunctionBlock)
4417 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004418 if (e->v.Yield.value) {
4419 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 }
4421 else {
4422 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4423 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004424 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004426 case YieldFrom_kind:
4427 if (c->u->u_ste->ste_type != FunctionBlock)
4428 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004429
4430 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4431 return compiler_error(c, "'yield from' inside async function");
4432
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004433 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004434 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004435 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4436 ADDOP(c, YIELD_FROM);
4437 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004438 case Await_kind:
4439 if (c->u->u_ste->ste_type != FunctionBlock)
4440 return compiler_error(c, "'await' outside function");
4441
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004442 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4443 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004444 return compiler_error(c, "'await' outside async function");
4445
4446 VISIT(c, expr, e->v.Await.value);
4447 ADDOP(c, GET_AWAITABLE);
4448 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4449 ADDOP(c, YIELD_FROM);
4450 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 case Compare_kind:
4452 return compiler_compare(c, e);
4453 case Call_kind:
4454 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004455 case Constant_kind:
4456 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4457 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 case Num_kind:
4459 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4460 break;
4461 case Str_kind:
4462 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4463 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004464 case JoinedStr_kind:
4465 return compiler_joined_str(c, e);
4466 case FormattedValue_kind:
4467 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 case Bytes_kind:
4469 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4470 break;
4471 case Ellipsis_kind:
4472 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4473 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004474 case NameConstant_kind:
4475 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4476 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 /* The following exprs can be assignment targets. */
4478 case Attribute_kind:
4479 if (e->v.Attribute.ctx != AugStore)
4480 VISIT(c, expr, e->v.Attribute.value);
4481 switch (e->v.Attribute.ctx) {
4482 case AugLoad:
4483 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004484 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 case Load:
4486 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4487 break;
4488 case AugStore:
4489 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004490 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 case Store:
4492 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4493 break;
4494 case Del:
4495 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4496 break;
4497 case Param:
4498 default:
4499 PyErr_SetString(PyExc_SystemError,
4500 "param invalid in attribute expression");
4501 return 0;
4502 }
4503 break;
4504 case Subscript_kind:
4505 switch (e->v.Subscript.ctx) {
4506 case AugLoad:
4507 VISIT(c, expr, e->v.Subscript.value);
4508 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4509 break;
4510 case Load:
4511 VISIT(c, expr, e->v.Subscript.value);
4512 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4513 break;
4514 case AugStore:
4515 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4516 break;
4517 case Store:
4518 VISIT(c, expr, e->v.Subscript.value);
4519 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4520 break;
4521 case Del:
4522 VISIT(c, expr, e->v.Subscript.value);
4523 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4524 break;
4525 case Param:
4526 default:
4527 PyErr_SetString(PyExc_SystemError,
4528 "param invalid in subscript expression");
4529 return 0;
4530 }
4531 break;
4532 case Starred_kind:
4533 switch (e->v.Starred.ctx) {
4534 case Store:
4535 /* In all legitimate cases, the Starred node was already replaced
4536 * by compiler_list/compiler_tuple. XXX: is that okay? */
4537 return compiler_error(c,
4538 "starred assignment target must be in a list or tuple");
4539 default:
4540 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004541 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 }
4543 break;
4544 case Name_kind:
4545 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4546 /* child nodes of List and Tuple will have expr_context set */
4547 case List_kind:
4548 return compiler_list(c, e);
4549 case Tuple_kind:
4550 return compiler_tuple(c, e);
4551 }
4552 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553}
4554
4555static int
4556compiler_augassign(struct compiler *c, stmt_ty s)
4557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 expr_ty e = s->v.AugAssign.target;
4559 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 switch (e->kind) {
4564 case Attribute_kind:
4565 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4566 AugLoad, e->lineno, e->col_offset, c->c_arena);
4567 if (auge == NULL)
4568 return 0;
4569 VISIT(c, expr, auge);
4570 VISIT(c, expr, s->v.AugAssign.value);
4571 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4572 auge->v.Attribute.ctx = AugStore;
4573 VISIT(c, expr, auge);
4574 break;
4575 case Subscript_kind:
4576 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4577 AugLoad, e->lineno, e->col_offset, c->c_arena);
4578 if (auge == NULL)
4579 return 0;
4580 VISIT(c, expr, auge);
4581 VISIT(c, expr, s->v.AugAssign.value);
4582 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4583 auge->v.Subscript.ctx = AugStore;
4584 VISIT(c, expr, auge);
4585 break;
4586 case Name_kind:
4587 if (!compiler_nameop(c, e->v.Name.id, Load))
4588 return 0;
4589 VISIT(c, expr, s->v.AugAssign.value);
4590 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4591 return compiler_nameop(c, e->v.Name.id, Store);
4592 default:
4593 PyErr_Format(PyExc_SystemError,
4594 "invalid node type (%d) for augmented assignment",
4595 e->kind);
4596 return 0;
4597 }
4598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004599}
4600
4601static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004602check_ann_expr(struct compiler *c, expr_ty e)
4603{
4604 VISIT(c, expr, e);
4605 ADDOP(c, POP_TOP);
4606 return 1;
4607}
4608
4609static int
4610check_annotation(struct compiler *c, stmt_ty s)
4611{
4612 /* Annotations are only evaluated in a module or class. */
4613 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4614 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4615 return check_ann_expr(c, s->v.AnnAssign.annotation);
4616 }
4617 return 1;
4618}
4619
4620static int
4621check_ann_slice(struct compiler *c, slice_ty sl)
4622{
4623 switch(sl->kind) {
4624 case Index_kind:
4625 return check_ann_expr(c, sl->v.Index.value);
4626 case Slice_kind:
4627 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4628 return 0;
4629 }
4630 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4631 return 0;
4632 }
4633 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4634 return 0;
4635 }
4636 break;
4637 default:
4638 PyErr_SetString(PyExc_SystemError,
4639 "unexpected slice kind");
4640 return 0;
4641 }
4642 return 1;
4643}
4644
4645static int
4646check_ann_subscr(struct compiler *c, slice_ty sl)
4647{
4648 /* We check that everything in a subscript is defined at runtime. */
4649 Py_ssize_t i, n;
4650
4651 switch (sl->kind) {
4652 case Index_kind:
4653 case Slice_kind:
4654 if (!check_ann_slice(c, sl)) {
4655 return 0;
4656 }
4657 break;
4658 case ExtSlice_kind:
4659 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4660 for (i = 0; i < n; i++) {
4661 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4662 switch (subsl->kind) {
4663 case Index_kind:
4664 case Slice_kind:
4665 if (!check_ann_slice(c, subsl)) {
4666 return 0;
4667 }
4668 break;
4669 case ExtSlice_kind:
4670 default:
4671 PyErr_SetString(PyExc_SystemError,
4672 "extended slice invalid in nested slice");
4673 return 0;
4674 }
4675 }
4676 break;
4677 default:
4678 PyErr_Format(PyExc_SystemError,
4679 "invalid subscript kind %d", sl->kind);
4680 return 0;
4681 }
4682 return 1;
4683}
4684
4685static int
4686compiler_annassign(struct compiler *c, stmt_ty s)
4687{
4688 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004689 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004690
4691 assert(s->kind == AnnAssign_kind);
4692
4693 /* We perform the actual assignment first. */
4694 if (s->v.AnnAssign.value) {
4695 VISIT(c, expr, s->v.AnnAssign.value);
4696 VISIT(c, expr, targ);
4697 }
4698 switch (targ->kind) {
4699 case Name_kind:
4700 /* If we have a simple name in a module or class, store annotation. */
4701 if (s->v.AnnAssign.simple &&
4702 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4703 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004704 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4705 if (!mangled) {
4706 return 0;
4707 }
Guido van Rossum95e4d582018-01-26 08:20:18 -08004708 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4709 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4710 }
4711 else {
4712 VISIT(c, expr, s->v.AnnAssign.annotation);
4713 }
Guido van Rossum015d8742016-09-11 09:45:24 -07004714 /* ADDOP_N decrefs its argument */
4715 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004716 }
4717 break;
4718 case Attribute_kind:
4719 if (!s->v.AnnAssign.value &&
4720 !check_ann_expr(c, targ->v.Attribute.value)) {
4721 return 0;
4722 }
4723 break;
4724 case Subscript_kind:
4725 if (!s->v.AnnAssign.value &&
4726 (!check_ann_expr(c, targ->v.Subscript.value) ||
4727 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4728 return 0;
4729 }
4730 break;
4731 default:
4732 PyErr_Format(PyExc_SystemError,
4733 "invalid node type (%d) for annotated assignment",
4734 targ->kind);
4735 return 0;
4736 }
4737 /* Annotation is evaluated last. */
4738 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4739 return 0;
4740 }
4741 return 1;
4742}
4743
4744static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 struct fblockinfo *f;
4748 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004749 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 "too many statically nested blocks");
4751 return 0;
4752 }
4753 f = &c->u->u_fblock[c->u->u_nfblocks++];
4754 f->fb_type = t;
4755 f->fb_block = b;
4756 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004757}
4758
4759static void
4760compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 struct compiler_unit *u = c->u;
4763 assert(u->u_nfblocks > 0);
4764 u->u_nfblocks--;
4765 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4766 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004767}
4768
Thomas Wouters89f507f2006-12-13 04:49:30 +00004769static int
4770compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 int i;
4772 struct compiler_unit *u = c->u;
4773 for (i = 0; i < u->u_nfblocks; ++i) {
4774 if (u->u_fblock[i].fb_type == LOOP)
4775 return 1;
4776 }
4777 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004778}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004779/* Raises a SyntaxError and returns 0.
4780 If something goes wrong, a different exception may be raised.
4781*/
4782
4783static int
4784compiler_error(struct compiler *c, const char *errstr)
4785{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004786 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004788
Victor Stinner14e461d2013-08-26 22:28:21 +02004789 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 if (!loc) {
4791 Py_INCREF(Py_None);
4792 loc = Py_None;
4793 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004794 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004795 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 if (!u)
4797 goto exit;
4798 v = Py_BuildValue("(zO)", errstr, u);
4799 if (!v)
4800 goto exit;
4801 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004802 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 Py_DECREF(loc);
4804 Py_XDECREF(u);
4805 Py_XDECREF(v);
4806 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004807}
4808
4809static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810compiler_handle_subscr(struct compiler *c, const char *kind,
4811 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 /* XXX this code is duplicated */
4816 switch (ctx) {
4817 case AugLoad: /* fall through to Load */
4818 case Load: op = BINARY_SUBSCR; break;
4819 case AugStore:/* fall through to Store */
4820 case Store: op = STORE_SUBSCR; break;
4821 case Del: op = DELETE_SUBSCR; break;
4822 case Param:
4823 PyErr_Format(PyExc_SystemError,
4824 "invalid %s kind %d in subscript\n",
4825 kind, ctx);
4826 return 0;
4827 }
4828 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004829 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 }
4831 else if (ctx == AugStore) {
4832 ADDOP(c, ROT_THREE);
4833 }
4834 ADDOP(c, op);
4835 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004836}
4837
4838static int
4839compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 int n = 2;
4842 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 /* only handles the cases where BUILD_SLICE is emitted */
4845 if (s->v.Slice.lower) {
4846 VISIT(c, expr, s->v.Slice.lower);
4847 }
4848 else {
4849 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4850 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 if (s->v.Slice.upper) {
4853 VISIT(c, expr, s->v.Slice.upper);
4854 }
4855 else {
4856 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4857 }
4858
4859 if (s->v.Slice.step) {
4860 n++;
4861 VISIT(c, expr, s->v.Slice.step);
4862 }
4863 ADDOP_I(c, BUILD_SLICE, n);
4864 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004865}
4866
4867static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4869 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004871 switch (s->kind) {
4872 case Slice_kind:
4873 return compiler_slice(c, s, ctx);
4874 case Index_kind:
4875 VISIT(c, expr, s->v.Index.value);
4876 break;
4877 case ExtSlice_kind:
4878 default:
4879 PyErr_SetString(PyExc_SystemError,
4880 "extended slice invalid in nested slice");
4881 return 0;
4882 }
4883 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004884}
4885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004886static int
4887compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4888{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004889 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 switch (s->kind) {
4891 case Index_kind:
4892 kindname = "index";
4893 if (ctx != AugStore) {
4894 VISIT(c, expr, s->v.Index.value);
4895 }
4896 break;
4897 case Slice_kind:
4898 kindname = "slice";
4899 if (ctx != AugStore) {
4900 if (!compiler_slice(c, s, ctx))
4901 return 0;
4902 }
4903 break;
4904 case ExtSlice_kind:
4905 kindname = "extended slice";
4906 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004907 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 for (i = 0; i < n; i++) {
4909 slice_ty sub = (slice_ty)asdl_seq_GET(
4910 s->v.ExtSlice.dims, i);
4911 if (!compiler_visit_nested_slice(c, sub, ctx))
4912 return 0;
4913 }
4914 ADDOP_I(c, BUILD_TUPLE, n);
4915 }
4916 break;
4917 default:
4918 PyErr_Format(PyExc_SystemError,
4919 "invalid subscript kind %d", s->kind);
4920 return 0;
4921 }
4922 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004923}
4924
Thomas Wouters89f507f2006-12-13 04:49:30 +00004925/* End of the compiler section, beginning of the assembler section */
4926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004927/* do depth-first search of basic block graph, starting with block.
4928 post records the block indices in post-order.
4929
4930 XXX must handle implicit jumps from one block to next
4931*/
4932
Thomas Wouters89f507f2006-12-13 04:49:30 +00004933struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 PyObject *a_bytecode; /* string containing bytecode */
4935 int a_offset; /* offset into bytecode */
4936 int a_nblocks; /* number of reachable blocks */
4937 basicblock **a_postorder; /* list of blocks in dfs postorder */
4938 PyObject *a_lnotab; /* string containing lnotab */
4939 int a_lnotab_off; /* offset into lnotab */
4940 int a_lineno; /* last lineno of emitted instruction */
4941 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004942};
4943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004945dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004946{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004947 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004948
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004949 /* Get rid of recursion for normal control flow.
4950 Since the number of blocks is limited, unused space in a_postorder
4951 (from a_nblocks to end) can be used as a stack for still not ordered
4952 blocks. */
4953 for (j = end; b && !b->b_seen; b = b->b_next) {
4954 b->b_seen = 1;
4955 assert(a->a_nblocks < j);
4956 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004958 while (j < end) {
4959 b = a->a_postorder[j++];
4960 for (i = 0; i < b->b_iused; i++) {
4961 struct instr *instr = &b->b_instr[i];
4962 if (instr->i_jrel || instr->i_jabs)
4963 dfs(c, instr->i_target, a, j);
4964 }
4965 assert(a->a_nblocks < j);
4966 a->a_postorder[a->a_nblocks++] = b;
4967 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004968}
4969
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004970Py_LOCAL_INLINE(void)
4971stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004972{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004973 /* XXX b->b_startdepth > depth only for the target of SETUP_FINALLY,
4974 * SETUP_WITH and SETUP_ASYNC_WITH. */
4975 assert(b->b_startdepth < 0 || b->b_startdepth >= depth);
4976 if (b->b_startdepth < depth) {
4977 assert(b->b_startdepth < 0);
4978 b->b_startdepth = depth;
4979 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004980 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004981}
4982
4983/* Find the flow path that needs the largest stack. We assume that
4984 * cycles in the flow graph have no net effect on the stack depth.
4985 */
4986static int
4987stackdepth(struct compiler *c)
4988{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004989 basicblock *b, *entryblock = NULL;
4990 basicblock **stack, **sp;
4991 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 b->b_startdepth = INT_MIN;
4994 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004995 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 }
4997 if (!entryblock)
4998 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004999 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5000 if (!stack) {
5001 PyErr_NoMemory();
5002 return -1;
5003 }
5004
5005 sp = stack;
5006 stackdepth_push(&sp, entryblock, 0);
5007 while (sp != stack) {
5008 b = *--sp;
5009 int depth = b->b_startdepth;
5010 assert(depth >= 0);
5011 basicblock *next = b->b_next;
5012 for (int i = 0; i < b->b_iused; i++) {
5013 struct instr *instr = &b->b_instr[i];
5014 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5015 if (effect == PY_INVALID_STACK_EFFECT) {
5016 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5017 Py_FatalError("PyCompile_OpcodeStackEffect()");
5018 }
5019 int new_depth = depth + effect;
5020 if (new_depth > maxdepth) {
5021 maxdepth = new_depth;
5022 }
5023 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5024 if (instr->i_jrel || instr->i_jabs) {
5025 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5026 assert(effect != PY_INVALID_STACK_EFFECT);
5027 int target_depth = depth + effect;
5028 if (target_depth > maxdepth) {
5029 maxdepth = target_depth;
5030 }
5031 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
5032 if (instr->i_opcode == CONTINUE_LOOP) {
5033 /* Pops a variable number of values from the stack,
5034 * but the target should be already proceeding.
5035 */
5036 assert(instr->i_target->b_startdepth >= 0);
5037 assert(instr->i_target->b_startdepth <= depth);
5038 /* remaining code is dead */
5039 next = NULL;
5040 break;
5041 }
5042 stackdepth_push(&sp, instr->i_target, target_depth);
5043 }
5044 depth = new_depth;
5045 if (instr->i_opcode == JUMP_ABSOLUTE ||
5046 instr->i_opcode == JUMP_FORWARD ||
5047 instr->i_opcode == RETURN_VALUE ||
5048 instr->i_opcode == RAISE_VARARGS ||
5049 instr->i_opcode == BREAK_LOOP)
5050 {
5051 /* remaining code is dead */
5052 next = NULL;
5053 break;
5054 }
5055 }
5056 if (next != NULL) {
5057 stackdepth_push(&sp, next, depth);
5058 }
5059 }
5060 PyObject_Free(stack);
5061 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005062}
5063
5064static int
5065assemble_init(struct assembler *a, int nblocks, int firstlineno)
5066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 memset(a, 0, sizeof(struct assembler));
5068 a->a_lineno = firstlineno;
5069 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5070 if (!a->a_bytecode)
5071 return 0;
5072 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5073 if (!a->a_lnotab)
5074 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005075 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 PyErr_NoMemory();
5077 return 0;
5078 }
5079 a->a_postorder = (basicblock **)PyObject_Malloc(
5080 sizeof(basicblock *) * nblocks);
5081 if (!a->a_postorder) {
5082 PyErr_NoMemory();
5083 return 0;
5084 }
5085 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005086}
5087
5088static void
5089assemble_free(struct assembler *a)
5090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 Py_XDECREF(a->a_bytecode);
5092 Py_XDECREF(a->a_lnotab);
5093 if (a->a_postorder)
5094 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095}
5096
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005097static int
5098blocksize(basicblock *b)
5099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 int i;
5101 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005104 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005106}
5107
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005108/* Appends a pair to the end of the line number table, a_lnotab, representing
5109 the instruction's bytecode offset and line number. See
5110 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005111
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005112static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005113assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005116 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005118
Serhiy Storchakaab874002016-09-11 13:48:15 +03005119 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 if(d_bytecode == 0 && d_lineno == 0)
5125 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 if (d_bytecode > 255) {
5128 int j, nbytes, ncodes = d_bytecode / 255;
5129 nbytes = a->a_lnotab_off + 2 * ncodes;
5130 len = PyBytes_GET_SIZE(a->a_lnotab);
5131 if (nbytes >= len) {
5132 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5133 len = nbytes;
5134 else if (len <= INT_MAX / 2)
5135 len *= 2;
5136 else {
5137 PyErr_NoMemory();
5138 return 0;
5139 }
5140 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5141 return 0;
5142 }
5143 lnotab = (unsigned char *)
5144 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5145 for (j = 0; j < ncodes; j++) {
5146 *lnotab++ = 255;
5147 *lnotab++ = 0;
5148 }
5149 d_bytecode -= ncodes * 255;
5150 a->a_lnotab_off += ncodes * 2;
5151 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005152 assert(0 <= d_bytecode && d_bytecode <= 255);
5153
5154 if (d_lineno < -128 || 127 < d_lineno) {
5155 int j, nbytes, ncodes, k;
5156 if (d_lineno < 0) {
5157 k = -128;
5158 /* use division on positive numbers */
5159 ncodes = (-d_lineno) / 128;
5160 }
5161 else {
5162 k = 127;
5163 ncodes = d_lineno / 127;
5164 }
5165 d_lineno -= ncodes * k;
5166 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 nbytes = a->a_lnotab_off + 2 * ncodes;
5168 len = PyBytes_GET_SIZE(a->a_lnotab);
5169 if (nbytes >= len) {
5170 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5171 len = nbytes;
5172 else if (len <= INT_MAX / 2)
5173 len *= 2;
5174 else {
5175 PyErr_NoMemory();
5176 return 0;
5177 }
5178 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5179 return 0;
5180 }
5181 lnotab = (unsigned char *)
5182 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5183 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005184 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 d_bytecode = 0;
5186 for (j = 1; j < ncodes; j++) {
5187 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005188 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 a->a_lnotab_off += ncodes * 2;
5191 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005192 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 len = PyBytes_GET_SIZE(a->a_lnotab);
5195 if (a->a_lnotab_off + 2 >= len) {
5196 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5197 return 0;
5198 }
5199 lnotab = (unsigned char *)
5200 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 a->a_lnotab_off += 2;
5203 if (d_bytecode) {
5204 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005205 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 }
5207 else { /* First line of a block; def stmt, etc. */
5208 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005209 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 }
5211 a->a_lineno = i->i_lineno;
5212 a->a_lineno_off = a->a_offset;
5213 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005214}
5215
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005216/* assemble_emit()
5217 Extend the bytecode with a new instruction.
5218 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005219*/
5220
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005221static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005222assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005223{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005224 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005226 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005227
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005228 arg = i->i_oparg;
5229 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 if (i->i_lineno && !assemble_lnotab(a, i))
5231 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005232 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 if (len > PY_SSIZE_T_MAX / 2)
5234 return 0;
5235 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5236 return 0;
5237 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005238 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005240 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005242}
5243
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005244static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005245assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005248 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 /* Compute the size of each block and fixup jump args.
5252 Replace block pointer with position in bytecode. */
5253 do {
5254 totsize = 0;
5255 for (i = a->a_nblocks - 1; i >= 0; i--) {
5256 b = a->a_postorder[i];
5257 bsize = blocksize(b);
5258 b->b_offset = totsize;
5259 totsize += bsize;
5260 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005261 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5263 bsize = b->b_offset;
5264 for (i = 0; i < b->b_iused; i++) {
5265 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005266 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 /* Relative jumps are computed relative to
5268 the instruction pointer after fetching
5269 the jump instruction.
5270 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005271 bsize += isize;
5272 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005274 if (instr->i_jrel) {
5275 instr->i_oparg -= bsize;
5276 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005277 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005278 if (instrsize(instr->i_oparg) != isize) {
5279 extended_arg_recompile = 1;
5280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 }
5283 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 /* XXX: This is an awful hack that could hurt performance, but
5286 on the bright side it should work until we come up
5287 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 The issue is that in the first loop blocksize() is called
5290 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005291 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 So we loop until we stop seeing new EXTENDED_ARGs.
5295 The only EXTENDED_ARGs that could be popping up are
5296 ones in jump instructions. So this should converge
5297 fairly quickly.
5298 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005299 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005300}
5301
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005302static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005303dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005306 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 tuple = PyTuple_New(size);
5309 if (tuple == NULL)
5310 return NULL;
5311 while (PyDict_Next(dict, &pos, &k, &v)) {
5312 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005313 /* The keys of the dictionary are tuples. (see compiler_add_o
5314 * and _PyCode_ConstantKey). The object we want is always second,
5315 * though. */
5316 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 Py_INCREF(k);
5318 assert((i - offset) < size);
5319 assert((i - offset) >= 0);
5320 PyTuple_SET_ITEM(tuple, i - offset, k);
5321 }
5322 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005323}
5324
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005325static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005326compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005329 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005331 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 if (ste->ste_nested)
5333 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005334 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005336 if (!ste->ste_generator && ste->ste_coroutine)
5337 flags |= CO_COROUTINE;
5338 if (ste->ste_generator && ste->ste_coroutine)
5339 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 if (ste->ste_varargs)
5341 flags |= CO_VARARGS;
5342 if (ste->ste_varkeywords)
5343 flags |= CO_VARKEYWORDS;
5344 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 /* (Only) inherit compilerflags in PyCF_MASK */
5347 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005350}
5351
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005352static PyCodeObject *
5353makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 PyObject *tmp;
5356 PyCodeObject *co = NULL;
5357 PyObject *consts = NULL;
5358 PyObject *names = NULL;
5359 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 PyObject *name = NULL;
5361 PyObject *freevars = NULL;
5362 PyObject *cellvars = NULL;
5363 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005364 Py_ssize_t nlocals;
5365 int nlocals_int;
5366 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005367 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 tmp = dict_keys_inorder(c->u->u_consts, 0);
5370 if (!tmp)
5371 goto error;
5372 consts = PySequence_List(tmp); /* optimize_code requires a list */
5373 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 names = dict_keys_inorder(c->u->u_names, 0);
5376 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5377 if (!consts || !names || !varnames)
5378 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5381 if (!cellvars)
5382 goto error;
5383 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5384 if (!freevars)
5385 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005386
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005387 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005388 assert(nlocals < INT_MAX);
5389 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 flags = compute_code_flags(c);
5392 if (flags < 0)
5393 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5396 if (!bytecode)
5397 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5400 if (!tmp)
5401 goto error;
5402 Py_DECREF(consts);
5403 consts = tmp;
5404
Victor Stinnerf8e32212013-11-19 23:56:34 +01005405 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5406 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005407 maxdepth = stackdepth(c);
5408 if (maxdepth < 0) {
5409 goto error;
5410 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005411 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005412 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 bytecode, consts, names, varnames,
5414 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005415 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 c->u->u_firstlineno,
5417 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005418 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 Py_XDECREF(consts);
5420 Py_XDECREF(names);
5421 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005422 Py_XDECREF(name);
5423 Py_XDECREF(freevars);
5424 Py_XDECREF(cellvars);
5425 Py_XDECREF(bytecode);
5426 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005427}
5428
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005429
5430/* For debugging purposes only */
5431#if 0
5432static void
5433dump_instr(const struct instr *i)
5434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 const char *jrel = i->i_jrel ? "jrel " : "";
5436 const char *jabs = i->i_jabs ? "jabs " : "";
5437 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005440 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005442 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5444 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005445}
5446
5447static void
5448dump_basicblock(const basicblock *b)
5449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 const char *seen = b->b_seen ? "seen " : "";
5451 const char *b_return = b->b_return ? "return " : "";
5452 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5453 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5454 if (b->b_instr) {
5455 int i;
5456 for (i = 0; i < b->b_iused; i++) {
5457 fprintf(stderr, " [%02d] ", i);
5458 dump_instr(b->b_instr + i);
5459 }
5460 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005461}
5462#endif
5463
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005464static PyCodeObject *
5465assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 basicblock *b, *entryblock;
5468 struct assembler a;
5469 int i, j, nblocks;
5470 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 /* Make sure every block that falls off the end returns None.
5473 XXX NEXT_BLOCK() isn't quite right, because if the last
5474 block ends with a jump or return b_next shouldn't set.
5475 */
5476 if (!c->u->u_curblock->b_return) {
5477 NEXT_BLOCK(c);
5478 if (addNone)
5479 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5480 ADDOP(c, RETURN_VALUE);
5481 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 nblocks = 0;
5484 entryblock = NULL;
5485 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5486 nblocks++;
5487 entryblock = b;
5488 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 /* Set firstlineno if it wasn't explicitly set. */
5491 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005492 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5494 else
5495 c->u->u_firstlineno = 1;
5496 }
5497 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5498 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005499 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 /* Can't modify the bytecode after computing jump offsets. */
5502 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 /* Emit code in reverse postorder from dfs. */
5505 for (i = a.a_nblocks - 1; i >= 0; i--) {
5506 b = a.a_postorder[i];
5507 for (j = 0; j < b->b_iused; j++)
5508 if (!assemble_emit(&a, &b->b_instr[j]))
5509 goto error;
5510 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5513 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005514 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005518 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 assemble_free(&a);
5520 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005521}
Georg Brandl8334fd92010-12-04 10:26:46 +00005522
5523#undef PyAST_Compile
5524PyAPI_FUNC(PyCodeObject *)
5525PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5526 PyArena *arena)
5527{
5528 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5529}