blob: 392de40f20a854e1eeff17653938106555e38768 [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);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, 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
INADA Naoki7ea143a2017-12-14 16:47:20 +0900334 if (!_PyAST_Optimize(mod, arena)) {
335 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
Larry Hastings3a907972013-11-23 14:49:22 -0800860int
861PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 switch (opcode) {
864 case POP_TOP:
865 return -1;
866 case ROT_TWO:
867 case ROT_THREE:
868 return 0;
869 case DUP_TOP:
870 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000871 case DUP_TOP_TWO:
872 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 case UNARY_POSITIVE:
875 case UNARY_NEGATIVE:
876 case UNARY_NOT:
877 case UNARY_INVERT:
878 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case SET_ADD:
881 case LIST_APPEND:
882 return -1;
883 case MAP_ADD:
884 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case BINARY_POWER:
887 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400888 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case BINARY_MODULO:
890 case BINARY_ADD:
891 case BINARY_SUBTRACT:
892 case BINARY_SUBSCR:
893 case BINARY_FLOOR_DIVIDE:
894 case BINARY_TRUE_DIVIDE:
895 return -1;
896 case INPLACE_FLOOR_DIVIDE:
897 case INPLACE_TRUE_DIVIDE:
898 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_ADD:
901 case INPLACE_SUBTRACT:
902 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400903 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case INPLACE_MODULO:
905 return -1;
906 case STORE_SUBSCR:
907 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 case DELETE_SUBSCR:
909 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case BINARY_LSHIFT:
912 case BINARY_RSHIFT:
913 case BINARY_AND:
914 case BINARY_XOR:
915 case BINARY_OR:
916 return -1;
917 case INPLACE_POWER:
918 return -1;
919 case GET_ITER:
920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case PRINT_EXPR:
923 return -1;
924 case LOAD_BUILD_CLASS:
925 return 1;
926 case INPLACE_LSHIFT:
927 case INPLACE_RSHIFT:
928 case INPLACE_AND:
929 case INPLACE_XOR:
930 case INPLACE_OR:
931 return -1;
932 case BREAK_LOOP:
933 return 0;
934 case SETUP_WITH:
935 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400936 case WITH_CLEANUP_START:
937 return 1;
938 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case RETURN_VALUE:
941 return -1;
942 case IMPORT_STAR:
943 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700944 case SETUP_ANNOTATIONS:
945 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case YIELD_VALUE:
947 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500948 case YIELD_FROM:
949 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case POP_BLOCK:
951 return 0;
952 case POP_EXCEPT:
953 return 0; /* -3 except if bad bytecode */
954 case END_FINALLY:
955 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case STORE_NAME:
958 return -1;
959 case DELETE_NAME:
960 return 0;
961 case UNPACK_SEQUENCE:
962 return oparg-1;
963 case UNPACK_EX:
964 return (oparg&0xFF) + (oparg>>8);
965 case FOR_ITER:
966 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case STORE_ATTR:
969 return -2;
970 case DELETE_ATTR:
971 return -1;
972 case STORE_GLOBAL:
973 return -1;
974 case DELETE_GLOBAL:
975 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case LOAD_CONST:
977 return 1;
978 case LOAD_NAME:
979 return 1;
980 case BUILD_TUPLE:
981 case BUILD_LIST:
982 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300983 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400985 case BUILD_LIST_UNPACK:
986 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300987 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400988 case BUILD_SET_UNPACK:
989 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400990 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700991 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700993 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300994 case BUILD_CONST_KEY_MAP:
995 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 case LOAD_ATTR:
997 return 0;
998 case COMPARE_OP:
999 return -1;
1000 case IMPORT_NAME:
1001 return -1;
1002 case IMPORT_FROM:
1003 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case JUMP_FORWARD:
1006 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1007 case JUMP_IF_FALSE_OR_POP: /* "" */
1008 case JUMP_ABSOLUTE:
1009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case POP_JUMP_IF_FALSE:
1012 case POP_JUMP_IF_TRUE:
1013 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case LOAD_GLOBAL:
1016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case CONTINUE_LOOP:
1019 return 0;
1020 case SETUP_LOOP:
1021 return 0;
1022 case SETUP_EXCEPT:
1023 case SETUP_FINALLY:
1024 return 6; /* can push 3 values for the new exception
1025 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case LOAD_FAST:
1028 return 1;
1029 case STORE_FAST:
1030 return -1;
1031 case DELETE_FAST:
1032 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001033 case STORE_ANNOTATION:
1034 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case RAISE_VARARGS:
1037 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001039 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001040 case CALL_METHOD:
1041 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001043 return -oparg-1;
1044 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001045 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001046 case MAKE_FUNCTION:
1047 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1048 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case BUILD_SLICE:
1050 if (oparg == 3)
1051 return -2;
1052 else
1053 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case LOAD_CLOSURE:
1056 return 1;
1057 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001058 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return 1;
1060 case STORE_DEREF:
1061 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001062 case DELETE_DEREF:
1063 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001064 case GET_AWAITABLE:
1065 return 0;
1066 case SETUP_ASYNC_WITH:
1067 return 6;
1068 case BEFORE_ASYNC_WITH:
1069 return 1;
1070 case GET_AITER:
1071 return 0;
1072 case GET_ANEXT:
1073 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001074 case GET_YIELD_FROM_ITER:
1075 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001076 case FORMAT_VALUE:
1077 /* If there's a fmt_spec on the stack, we go from 2->1,
1078 else 1->1. */
1079 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001080 case LOAD_METHOD:
1081 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001083 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
Larry Hastings3a907972013-11-23 14:49:22 -08001085 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086}
1087
1088/* Add an opcode with no argument.
1089 Returns 0 on failure, 1 on success.
1090*/
1091
1092static int
1093compiler_addop(struct compiler *c, int opcode)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 basicblock *b;
1096 struct instr *i;
1097 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001098 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 off = compiler_next_instr(c, c->u->u_curblock);
1100 if (off < 0)
1101 return 0;
1102 b = c->u->u_curblock;
1103 i = &b->b_instr[off];
1104 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001105 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (opcode == RETURN_VALUE)
1107 b->b_return = 1;
1108 compiler_set_lineno(c, off);
1109 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001110}
1111
Victor Stinnerf8e32212013-11-19 23:56:34 +01001112static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *t, *v;
1116 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
Victor Stinnerefb24132016-01-22 12:33:12 +01001118 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (t == NULL)
1120 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 v = PyDict_GetItem(dict, t);
1123 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001124 if (PyErr_Occurred()) {
1125 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001127 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001128 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001129 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!v) {
1131 Py_DECREF(t);
1132 return -1;
1133 }
1134 if (PyDict_SetItem(dict, t, v) < 0) {
1135 Py_DECREF(t);
1136 Py_DECREF(v);
1137 return -1;
1138 }
1139 Py_DECREF(v);
1140 }
1141 else
1142 arg = PyLong_AsLong(v);
1143 Py_DECREF(t);
1144 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145}
1146
1147static int
1148compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001151 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return compiler_addop_i(c, opcode, arg);
1155}
1156
1157static int
1158compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001161 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1163 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 arg = compiler_add_o(c, dict, mangled);
1166 Py_DECREF(mangled);
1167 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001168 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 return compiler_addop_i(c, opcode, arg);
1170}
1171
1172/* Add an opcode with an integer argument.
1173 Returns 0 on failure, 1 on success.
1174*/
1175
1176static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 struct instr *i;
1180 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001181
Victor Stinner2ad474b2016-03-01 23:34:47 +01001182 /* oparg value is unsigned, but a signed C int is usually used to store
1183 it in the C code (like Python/ceval.c).
1184
1185 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1186
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001187 The argument of a concrete bytecode instruction is limited to 8-bit.
1188 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1189 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001190 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 off = compiler_next_instr(c, c->u->u_curblock);
1193 if (off < 0)
1194 return 0;
1195 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001196 i->i_opcode = opcode;
1197 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 compiler_set_lineno(c, off);
1199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200}
1201
1202static int
1203compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 struct instr *i;
1206 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001208 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 assert(b != NULL);
1210 off = compiler_next_instr(c, c->u->u_curblock);
1211 if (off < 0)
1212 return 0;
1213 i = &c->u->u_curblock->b_instr[off];
1214 i->i_opcode = opcode;
1215 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (absolute)
1217 i->i_jabs = 1;
1218 else
1219 i->i_jrel = 1;
1220 compiler_set_lineno(c, off);
1221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222}
1223
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001224/* NEXT_BLOCK() creates an implicit jump from the current block
1225 to the new block.
1226
1227 The returns inside this macro make it impossible to decref objects
1228 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (compiler_next_block((C)) == NULL) \
1232 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233}
1234
1235#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (!compiler_addop((C), (OP))) \
1237 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238}
1239
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001240#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (!compiler_addop((C), (OP))) { \
1242 compiler_exit_scope(c); \
1243 return 0; \
1244 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001245}
1246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1249 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001252/* Same as ADDOP_O, but steals a reference. */
1253#define ADDOP_N(C, OP, O, TYPE) { \
1254 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1255 Py_DECREF((O)); \
1256 return 0; \
1257 } \
1258 Py_DECREF((O)); \
1259}
1260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1263 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264}
1265
1266#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (!compiler_addop_i((C), (OP), (O))) \
1268 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269}
1270
1271#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!compiler_addop_j((C), (OP), (O), 1)) \
1273 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
1276#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!compiler_addop_j((C), (OP), (O), 0)) \
1278 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1282 the ASDL name to synthesize the name of the C type and the visit function.
1283*/
1284
1285#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (!compiler_visit_ ## TYPE((C), (V))) \
1287 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288}
1289
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001290#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (!compiler_visit_ ## TYPE((C), (V))) { \
1292 compiler_exit_scope(c); \
1293 return 0; \
1294 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001295}
1296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (!compiler_visit_slice((C), (V), (CTX))) \
1299 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300}
1301
1302#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 int _i; \
1304 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1305 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1306 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1307 if (!compiler_visit_ ## TYPE((C), elt)) \
1308 return 0; \
1309 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001312#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 int _i; \
1314 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1315 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1316 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1317 if (!compiler_visit_ ## TYPE((C), elt)) { \
1318 compiler_exit_scope(c); \
1319 return 0; \
1320 } \
1321 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001322}
1323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001325is_const(expr_ty e)
1326{
1327 switch (e->kind) {
1328 case Constant_kind:
1329 case Num_kind:
1330 case Str_kind:
1331 case Bytes_kind:
1332 case Ellipsis_kind:
1333 case NameConstant_kind:
1334 return 1;
Serhiy Storchaka3325a672017-12-15 12:35:48 +02001335 case Name_kind:
1336 return _PyUnicode_EqualToASCIIString(e->v.Name.id, "__debug__");
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001337 default:
1338 return 0;
1339 }
1340}
1341
1342static PyObject *
Serhiy Storchaka3325a672017-12-15 12:35:48 +02001343get_const_value(struct compiler *c, expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001344{
1345 switch (e->kind) {
1346 case Constant_kind:
1347 return e->v.Constant.value;
1348 case Num_kind:
1349 return e->v.Num.n;
1350 case Str_kind:
1351 return e->v.Str.s;
1352 case Bytes_kind:
1353 return e->v.Bytes.s;
1354 case Ellipsis_kind:
1355 return Py_Ellipsis;
1356 case NameConstant_kind:
1357 return e->v.NameConstant.value;
Serhiy Storchaka3325a672017-12-15 12:35:48 +02001358 case Name_kind:
1359 assert(_PyUnicode_EqualToASCIIString(e->v.Name.id, "__debug__"));
1360 return c->c_optimize ? Py_False : Py_True;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001361 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001362 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001363 }
1364}
1365
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001366/* Search if variable annotations are present statically in a block. */
1367
1368static int
1369find_ann(asdl_seq *stmts)
1370{
1371 int i, j, res = 0;
1372 stmt_ty st;
1373
1374 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1375 st = (stmt_ty)asdl_seq_GET(stmts, i);
1376 switch (st->kind) {
1377 case AnnAssign_kind:
1378 return 1;
1379 case For_kind:
1380 res = find_ann(st->v.For.body) ||
1381 find_ann(st->v.For.orelse);
1382 break;
1383 case AsyncFor_kind:
1384 res = find_ann(st->v.AsyncFor.body) ||
1385 find_ann(st->v.AsyncFor.orelse);
1386 break;
1387 case While_kind:
1388 res = find_ann(st->v.While.body) ||
1389 find_ann(st->v.While.orelse);
1390 break;
1391 case If_kind:
1392 res = find_ann(st->v.If.body) ||
1393 find_ann(st->v.If.orelse);
1394 break;
1395 case With_kind:
1396 res = find_ann(st->v.With.body);
1397 break;
1398 case AsyncWith_kind:
1399 res = find_ann(st->v.AsyncWith.body);
1400 break;
1401 case Try_kind:
1402 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1403 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1404 st->v.Try.handlers, j);
1405 if (find_ann(handler->v.ExceptHandler.body)) {
1406 return 1;
1407 }
1408 }
1409 res = find_ann(st->v.Try.body) ||
1410 find_ann(st->v.Try.finalbody) ||
1411 find_ann(st->v.Try.orelse);
1412 break;
1413 default:
1414 res = 0;
1415 }
1416 if (res) {
1417 break;
1418 }
1419 }
1420 return res;
1421}
1422
1423/* Compile a sequence of statements, checking for a docstring
1424 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425
1426static int
INADA Naokicb41b272017-02-23 00:31:59 +09001427compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001429 /* Set current line number to the line number of first statement.
1430 This way line number for SETUP_ANNOTATIONS will always
1431 coincide with the line number of first "real" statement in module.
1432 If body is empy, then lineno will be set later in assemble. */
1433 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1434 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001435 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001436 c->u->u_lineno = st->lineno;
1437 }
1438 /* Every annotated class and module should have __annotations__. */
1439 if (find_ann(stmts)) {
1440 ADDOP(c, SETUP_ANNOTATIONS);
1441 }
INADA Naokicb41b272017-02-23 00:31:59 +09001442 /* if not -OO mode, set docstring */
1443 if (c->c_optimize < 2 && docstring) {
1444 ADDOP_O(c, LOAD_CONST, docstring, consts);
1445 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 }
INADA Naokicb41b272017-02-23 00:31:59 +09001447 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
1451static PyCodeObject *
1452compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyCodeObject *co;
1455 int addNone = 1;
1456 static PyObject *module;
1457 if (!module) {
1458 module = PyUnicode_InternFromString("<module>");
1459 if (!module)
1460 return NULL;
1461 }
1462 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001463 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return NULL;
1465 switch (mod->kind) {
1466 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001467 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 compiler_exit_scope(c);
1469 return 0;
1470 }
1471 break;
1472 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001473 if (find_ann(mod->v.Interactive.body)) {
1474 ADDOP(c, SETUP_ANNOTATIONS);
1475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 c->c_interactive = 1;
1477 VISIT_SEQ_IN_SCOPE(c, stmt,
1478 mod->v.Interactive.body);
1479 break;
1480 case Expression_kind:
1481 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1482 addNone = 0;
1483 break;
1484 case Suite_kind:
1485 PyErr_SetString(PyExc_SystemError,
1486 "suite should not be possible");
1487 return 0;
1488 default:
1489 PyErr_Format(PyExc_SystemError,
1490 "module kind %d should not be possible",
1491 mod->kind);
1492 return 0;
1493 }
1494 co = assemble(c, addNone);
1495 compiler_exit_scope(c);
1496 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001497}
1498
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499/* The test for LOCAL must come before the test for FREE in order to
1500 handle classes where name is both local and free. The local var is
1501 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001502*/
1503
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504static int
1505get_ref_type(struct compiler *c, PyObject *name)
1506{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001507 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001508 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001509 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001510 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001511 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (scope == 0) {
1513 char buf[350];
1514 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001515 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001517 PyUnicode_AsUTF8(name),
1518 PyUnicode_AsUTF8(c->u->u_name),
1519 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1520 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1521 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1522 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 );
1524 Py_FatalError(buf);
1525 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528}
1529
1530static int
1531compiler_lookup_arg(PyObject *dict, PyObject *name)
1532{
1533 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001534 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001536 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001538 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001540 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001541 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542}
1543
1544static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001545compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001546{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001547 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001548 if (qualname == NULL)
1549 qualname = co->co_name;
1550
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001551 if (free) {
1552 for (i = 0; i < free; ++i) {
1553 /* Bypass com_addop_varname because it will generate
1554 LOAD_DEREF but LOAD_CLOSURE is needed.
1555 */
1556 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1557 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001558
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001559 /* Special case: If a class contains a method with a
1560 free variable that has the same name as a method,
1561 the name will be considered free *and* local in the
1562 class. It should be handled by the closure, as
1563 well as by the normal name loookup logic.
1564 */
1565 reftype = get_ref_type(c, name);
1566 if (reftype == CELL)
1567 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1568 else /* (reftype == FREE) */
1569 arg = compiler_lookup_arg(c->u->u_freevars, name);
1570 if (arg == -1) {
1571 fprintf(stderr,
1572 "lookup %s in %s %d %d\n"
1573 "freevars of %s: %s\n",
1574 PyUnicode_AsUTF8(PyObject_Repr(name)),
1575 PyUnicode_AsUTF8(c->u->u_name),
1576 reftype, arg,
1577 PyUnicode_AsUTF8(co->co_name),
1578 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1579 Py_FatalError("compiler_make_closure()");
1580 }
1581 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001583 flags |= 0x08;
1584 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001587 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001588 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590}
1591
1592static int
1593compiler_decorators(struct compiler *c, asdl_seq* decos)
1594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (!decos)
1598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1601 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1602 }
1603 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001604}
1605
1606static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001607compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001609{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001610 /* Push a dict of keyword-only default values.
1611
1612 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1613 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001614 int i;
1615 PyObject *keys = NULL;
1616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1618 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1619 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1620 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001621 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001622 if (!mangled) {
1623 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001625 if (keys == NULL) {
1626 keys = PyList_New(1);
1627 if (keys == NULL) {
1628 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001629 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001630 }
1631 PyList_SET_ITEM(keys, 0, mangled);
1632 }
1633 else {
1634 int res = PyList_Append(keys, mangled);
1635 Py_DECREF(mangled);
1636 if (res == -1) {
1637 goto error;
1638 }
1639 }
1640 if (!compiler_visit_expr(c, default_)) {
1641 goto error;
1642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 }
1644 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001645 if (keys != NULL) {
1646 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1647 PyObject *keys_tuple = PyList_AsTuple(keys);
1648 Py_DECREF(keys);
1649 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001650 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001651 }
1652 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1653 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001654 assert(default_count > 0);
1655 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001656 }
1657 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001658 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001659 }
1660
1661error:
1662 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001663 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001664}
1665
1666static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001667compiler_visit_argannotation(struct compiler *c, identifier id,
1668 expr_ty annotation, PyObject *names)
1669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001671 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001673 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001674 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001675 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001676 if (PyList_Append(names, mangled) < 0) {
1677 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001678 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001679 }
1680 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001682 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001683}
1684
1685static int
1686compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1687 PyObject *names)
1688{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001689 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 for (i = 0; i < asdl_seq_LEN(args); i++) {
1691 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001692 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 c,
1694 arg->arg,
1695 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001696 names))
1697 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001699 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001700}
1701
1702static int
1703compiler_visit_annotations(struct compiler *c, arguments_ty args,
1704 expr_ty returns)
1705{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001706 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001707 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001708
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001709 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 */
1711 static identifier return_str;
1712 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001713 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 names = PyList_New(0);
1715 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001716 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001717
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001718 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001720 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001721 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001722 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001724 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001726 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001727 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001728 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 if (!return_str) {
1732 return_str = PyUnicode_InternFromString("return");
1733 if (!return_str)
1734 goto error;
1735 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001736 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 goto error;
1738 }
1739
1740 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001742 PyObject *keytuple = PyList_AsTuple(names);
1743 Py_DECREF(names);
1744 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001745 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001747 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1748 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001749 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001751 else {
1752 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001753 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001754 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001755
1756error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001758 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001759}
1760
1761static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001762compiler_visit_defaults(struct compiler *c, arguments_ty args)
1763{
1764 VISIT_SEQ(c, expr, args->defaults);
1765 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1766 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001767}
1768
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001769static Py_ssize_t
1770compiler_default_arguments(struct compiler *c, arguments_ty args)
1771{
1772 Py_ssize_t funcflags = 0;
1773 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001774 if (!compiler_visit_defaults(c, args))
1775 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001776 funcflags |= 0x01;
1777 }
1778 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001779 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001780 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001781 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001782 return -1;
1783 }
1784 else if (res > 0) {
1785 funcflags |= 0x02;
1786 }
1787 }
1788 return funcflags;
1789}
1790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791static int
Yury Selivanov75445082015-05-11 22:57:16 -04001792compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001795 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001796 arguments_ty args;
1797 expr_ty returns;
1798 identifier name;
1799 asdl_seq* decos;
1800 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001801 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001802 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001803 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804
Yury Selivanov75445082015-05-11 22:57:16 -04001805 if (is_async) {
1806 assert(s->kind == AsyncFunctionDef_kind);
1807
1808 args = s->v.AsyncFunctionDef.args;
1809 returns = s->v.AsyncFunctionDef.returns;
1810 decos = s->v.AsyncFunctionDef.decorator_list;
1811 name = s->v.AsyncFunctionDef.name;
1812 body = s->v.AsyncFunctionDef.body;
1813
1814 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1815 } else {
1816 assert(s->kind == FunctionDef_kind);
1817
1818 args = s->v.FunctionDef.args;
1819 returns = s->v.FunctionDef.returns;
1820 decos = s->v.FunctionDef.decorator_list;
1821 name = s->v.FunctionDef.name;
1822 body = s->v.FunctionDef.body;
1823
1824 scope_type = COMPILER_SCOPE_FUNCTION;
1825 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (!compiler_decorators(c, decos))
1828 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001829
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001830 funcflags = compiler_default_arguments(c, args);
1831 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001833 }
1834
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001835 annotations = compiler_visit_annotations(c, args, returns);
1836 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001837 return 0;
1838 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001839 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001840 funcflags |= 0x04;
1841 }
1842
1843 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1844 return 0;
1845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846
INADA Naokicb41b272017-02-23 00:31:59 +09001847 /* if not -OO mode, add docstring */
1848 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1849 docstring = s->v.FunctionDef.docstring;
1850 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 compiler_exit_scope(c);
1852 return 0;
1853 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 c->u->u_argcount = asdl_seq_LEN(args->args);
1856 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001858 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001860 qualname = c->u->u_qualname;
1861 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001863 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001864 Py_XDECREF(qualname);
1865 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001869 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001870 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 /* decorators */
1874 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1875 ADDOP_I(c, CALL_FUNCTION, 1);
1876 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877
Yury Selivanov75445082015-05-11 22:57:16 -04001878 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879}
1880
1881static int
1882compiler_class(struct compiler *c, stmt_ty s)
1883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 PyCodeObject *co;
1885 PyObject *str;
1886 int i;
1887 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (!compiler_decorators(c, decos))
1890 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* ultimately generate code for:
1893 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1894 where:
1895 <func> is a function/closure created from the class body;
1896 it has a single argument (__locals__) where the dict
1897 (or MutableSequence) representing the locals is passed
1898 <name> is the class name
1899 <bases> is the positional arguments and *varargs argument
1900 <keywords> is the keyword arguments and **kwds argument
1901 This borrows from compiler_call.
1902 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001905 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1906 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return 0;
1908 /* this block represents what we do in the new scope */
1909 {
1910 /* use the class name for name mangling */
1911 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001912 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* load (global) __name__ ... */
1914 str = PyUnicode_InternFromString("__name__");
1915 if (!str || !compiler_nameop(c, str, Load)) {
1916 Py_XDECREF(str);
1917 compiler_exit_scope(c);
1918 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001919 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 Py_DECREF(str);
1921 /* ... and store it as __module__ */
1922 str = PyUnicode_InternFromString("__module__");
1923 if (!str || !compiler_nameop(c, str, Store)) {
1924 Py_XDECREF(str);
1925 compiler_exit_scope(c);
1926 return 0;
1927 }
1928 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001929 assert(c->u->u_qualname);
1930 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001931 str = PyUnicode_InternFromString("__qualname__");
1932 if (!str || !compiler_nameop(c, str, Store)) {
1933 Py_XDECREF(str);
1934 compiler_exit_scope(c);
1935 return 0;
1936 }
1937 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001939 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 compiler_exit_scope(c);
1941 return 0;
1942 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001943 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001944 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001945 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001946 str = PyUnicode_InternFromString("__class__");
1947 if (str == NULL) {
1948 compiler_exit_scope(c);
1949 return 0;
1950 }
1951 i = compiler_lookup_arg(c->u->u_cellvars, str);
1952 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001953 if (i < 0) {
1954 compiler_exit_scope(c);
1955 return 0;
1956 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001957 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001960 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001961 str = PyUnicode_InternFromString("__classcell__");
1962 if (!str || !compiler_nameop(c, str, Store)) {
1963 Py_XDECREF(str);
1964 compiler_exit_scope(c);
1965 return 0;
1966 }
1967 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001969 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001970 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001971 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001972 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001973 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001974 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* create the code object */
1976 co = assemble(c, 1);
1977 }
1978 /* leave the new scope */
1979 compiler_exit_scope(c);
1980 if (co == NULL)
1981 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 /* 2. load the 'build_class' function */
1984 ADDOP(c, LOAD_BUILD_CLASS);
1985
1986 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001987 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 Py_DECREF(co);
1989
1990 /* 4. load class name */
1991 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1992
1993 /* 5. generate the rest of the code for the call */
1994 if (!compiler_call_helper(c, 2,
1995 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001996 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 return 0;
1998
1999 /* 6. apply decorators */
2000 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2001 ADDOP_I(c, CALL_FUNCTION, 1);
2002 }
2003
2004 /* 7. store into <name> */
2005 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2006 return 0;
2007 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008}
2009
2010static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002011cmpop(cmpop_ty op)
2012{
2013 switch (op) {
2014 case Eq:
2015 return PyCmp_EQ;
2016 case NotEq:
2017 return PyCmp_NE;
2018 case Lt:
2019 return PyCmp_LT;
2020 case LtE:
2021 return PyCmp_LE;
2022 case Gt:
2023 return PyCmp_GT;
2024 case GtE:
2025 return PyCmp_GE;
2026 case Is:
2027 return PyCmp_IS;
2028 case IsNot:
2029 return PyCmp_IS_NOT;
2030 case In:
2031 return PyCmp_IN;
2032 case NotIn:
2033 return PyCmp_NOT_IN;
2034 default:
2035 return PyCmp_BAD;
2036 }
2037}
2038
2039static int
2040compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2041{
2042 switch (e->kind) {
2043 case UnaryOp_kind:
2044 if (e->v.UnaryOp.op == Not)
2045 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2046 /* fallback to general implementation */
2047 break;
2048 case BoolOp_kind: {
2049 asdl_seq *s = e->v.BoolOp.values;
2050 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2051 assert(n >= 0);
2052 int cond2 = e->v.BoolOp.op == Or;
2053 basicblock *next2 = next;
2054 if (!cond2 != !cond) {
2055 next2 = compiler_new_block(c);
2056 if (next2 == NULL)
2057 return 0;
2058 }
2059 for (i = 0; i < n; ++i) {
2060 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2061 return 0;
2062 }
2063 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2064 return 0;
2065 if (next2 != next)
2066 compiler_use_next_block(c, next2);
2067 return 1;
2068 }
2069 case IfExp_kind: {
2070 basicblock *end, *next2;
2071 end = compiler_new_block(c);
2072 if (end == NULL)
2073 return 0;
2074 next2 = compiler_new_block(c);
2075 if (next2 == NULL)
2076 return 0;
2077 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2078 return 0;
2079 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2080 return 0;
2081 ADDOP_JREL(c, JUMP_FORWARD, end);
2082 compiler_use_next_block(c, next2);
2083 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2084 return 0;
2085 compiler_use_next_block(c, end);
2086 return 1;
2087 }
2088 case Compare_kind: {
2089 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2090 if (n > 0) {
2091 basicblock *cleanup = compiler_new_block(c);
2092 if (cleanup == NULL)
2093 return 0;
2094 VISIT(c, expr, e->v.Compare.left);
2095 for (i = 0; i < n; i++) {
2096 VISIT(c, expr,
2097 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2098 ADDOP(c, DUP_TOP);
2099 ADDOP(c, ROT_THREE);
2100 ADDOP_I(c, COMPARE_OP,
2101 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2102 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2103 NEXT_BLOCK(c);
2104 }
2105 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2106 ADDOP_I(c, COMPARE_OP,
2107 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2108 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2109 basicblock *end = compiler_new_block(c);
2110 if (end == NULL)
2111 return 0;
2112 ADDOP_JREL(c, JUMP_FORWARD, end);
2113 compiler_use_next_block(c, cleanup);
2114 ADDOP(c, POP_TOP);
2115 if (!cond) {
2116 ADDOP_JREL(c, JUMP_FORWARD, next);
2117 }
2118 compiler_use_next_block(c, end);
2119 return 1;
2120 }
2121 /* fallback to general implementation */
2122 break;
2123 }
2124 default:
2125 /* fallback to general implementation */
2126 break;
2127 }
2128
2129 /* general implementation */
2130 VISIT(c, expr, e);
2131 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2132 return 1;
2133}
2134
2135static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002136compiler_ifexp(struct compiler *c, expr_ty e)
2137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 basicblock *end, *next;
2139
2140 assert(e->kind == IfExp_kind);
2141 end = compiler_new_block(c);
2142 if (end == NULL)
2143 return 0;
2144 next = compiler_new_block(c);
2145 if (next == NULL)
2146 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002147 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2148 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 VISIT(c, expr, e->v.IfExp.body);
2150 ADDOP_JREL(c, JUMP_FORWARD, end);
2151 compiler_use_next_block(c, next);
2152 VISIT(c, expr, e->v.IfExp.orelse);
2153 compiler_use_next_block(c, end);
2154 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002155}
2156
2157static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158compiler_lambda(struct compiler *c, expr_ty e)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002161 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002163 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 arguments_ty args = e->v.Lambda.args;
2165 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (!name) {
2168 name = PyUnicode_InternFromString("<lambda>");
2169 if (!name)
2170 return 0;
2171 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002173 funcflags = compiler_default_arguments(c, args);
2174 if (funcflags == -1) {
2175 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002177
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002178 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002179 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* Make None the first constant, so the lambda can't have a
2183 docstring. */
2184 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2185 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 c->u->u_argcount = asdl_seq_LEN(args->args);
2188 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2189 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2190 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002191 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 }
2193 else {
2194 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002195 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002197 qualname = c->u->u_qualname;
2198 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002200 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002203 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002204 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 Py_DECREF(co);
2206
2207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208}
2209
2210static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211compiler_if(struct compiler *c, stmt_ty s)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 basicblock *end, *next;
2214 int constant;
2215 assert(s->kind == If_kind);
2216 end = compiler_new_block(c);
2217 if (end == NULL)
2218 return 0;
2219
Georg Brandl8334fd92010-12-04 10:26:46 +00002220 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* constant = 0: "if 0"
2222 * constant = 1: "if 1", "if 2", ...
2223 * constant = -1: rest */
2224 if (constant == 0) {
2225 if (s->v.If.orelse)
2226 VISIT_SEQ(c, stmt, s->v.If.orelse);
2227 } else if (constant == 1) {
2228 VISIT_SEQ(c, stmt, s->v.If.body);
2229 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002230 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 next = compiler_new_block(c);
2232 if (next == NULL)
2233 return 0;
2234 }
2235 else
2236 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002237 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2238 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002240 if (asdl_seq_LEN(s->v.If.orelse)) {
2241 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 compiler_use_next_block(c, next);
2243 VISIT_SEQ(c, stmt, s->v.If.orelse);
2244 }
2245 }
2246 compiler_use_next_block(c, end);
2247 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248}
2249
2250static int
2251compiler_for(struct compiler *c, stmt_ty s)
2252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 start = compiler_new_block(c);
2256 cleanup = compiler_new_block(c);
2257 end = compiler_new_block(c);
2258 if (start == NULL || end == NULL || cleanup == NULL)
2259 return 0;
2260 ADDOP_JREL(c, SETUP_LOOP, end);
2261 if (!compiler_push_fblock(c, LOOP, start))
2262 return 0;
2263 VISIT(c, expr, s->v.For.iter);
2264 ADDOP(c, GET_ITER);
2265 compiler_use_next_block(c, start);
2266 ADDOP_JREL(c, FOR_ITER, cleanup);
2267 VISIT(c, expr, s->v.For.target);
2268 VISIT_SEQ(c, stmt, s->v.For.body);
2269 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2270 compiler_use_next_block(c, cleanup);
2271 ADDOP(c, POP_BLOCK);
2272 compiler_pop_fblock(c, LOOP, start);
2273 VISIT_SEQ(c, stmt, s->v.For.orelse);
2274 compiler_use_next_block(c, end);
2275 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276}
2277
Yury Selivanov75445082015-05-11 22:57:16 -04002278
2279static int
2280compiler_async_for(struct compiler *c, stmt_ty s)
2281{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002282 _Py_IDENTIFIER(StopAsyncIteration);
2283
Yury Selivanov75445082015-05-11 22:57:16 -04002284 basicblock *try, *except, *end, *after_try, *try_cleanup,
2285 *after_loop, *after_loop_else;
2286
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002287 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2288 if (stop_aiter_error == NULL) {
2289 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002290 }
2291
2292 try = compiler_new_block(c);
2293 except = compiler_new_block(c);
2294 end = compiler_new_block(c);
2295 after_try = compiler_new_block(c);
2296 try_cleanup = compiler_new_block(c);
2297 after_loop = compiler_new_block(c);
2298 after_loop_else = compiler_new_block(c);
2299
2300 if (try == NULL || except == NULL || end == NULL
2301 || after_try == NULL || try_cleanup == NULL)
2302 return 0;
2303
2304 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2305 if (!compiler_push_fblock(c, LOOP, try))
2306 return 0;
2307
2308 VISIT(c, expr, s->v.AsyncFor.iter);
2309 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002310
2311 compiler_use_next_block(c, try);
2312
2313
2314 ADDOP_JREL(c, SETUP_EXCEPT, except);
2315 if (!compiler_push_fblock(c, EXCEPT, try))
2316 return 0;
2317
2318 ADDOP(c, GET_ANEXT);
2319 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2320 ADDOP(c, YIELD_FROM);
2321 VISIT(c, expr, s->v.AsyncFor.target);
2322 ADDOP(c, POP_BLOCK);
2323 compiler_pop_fblock(c, EXCEPT, try);
2324 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2325
2326
2327 compiler_use_next_block(c, except);
2328 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002329 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002330 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2331 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2332
2333 ADDOP(c, POP_TOP);
2334 ADDOP(c, POP_TOP);
2335 ADDOP(c, POP_TOP);
2336 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2337 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2338 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2339
2340
2341 compiler_use_next_block(c, try_cleanup);
2342 ADDOP(c, END_FINALLY);
2343
2344 compiler_use_next_block(c, after_try);
2345 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2346 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2347
2348 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2349 compiler_pop_fblock(c, LOOP, try);
2350
2351 compiler_use_next_block(c, after_loop);
2352 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2353
2354 compiler_use_next_block(c, after_loop_else);
2355 VISIT_SEQ(c, stmt, s->v.For.orelse);
2356
2357 compiler_use_next_block(c, end);
2358
2359 return 1;
2360}
2361
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362static int
2363compiler_while(struct compiler *c, stmt_ty s)
2364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002366 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (constant == 0) {
2369 if (s->v.While.orelse)
2370 VISIT_SEQ(c, stmt, s->v.While.orelse);
2371 return 1;
2372 }
2373 loop = compiler_new_block(c);
2374 end = compiler_new_block(c);
2375 if (constant == -1) {
2376 anchor = compiler_new_block(c);
2377 if (anchor == NULL)
2378 return 0;
2379 }
2380 if (loop == NULL || end == NULL)
2381 return 0;
2382 if (s->v.While.orelse) {
2383 orelse = compiler_new_block(c);
2384 if (orelse == NULL)
2385 return 0;
2386 }
2387 else
2388 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 ADDOP_JREL(c, SETUP_LOOP, end);
2391 compiler_use_next_block(c, loop);
2392 if (!compiler_push_fblock(c, LOOP, loop))
2393 return 0;
2394 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002395 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2396 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 }
2398 VISIT_SEQ(c, stmt, s->v.While.body);
2399 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 /* XXX should the two POP instructions be in a separate block
2402 if there is no else clause ?
2403 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002405 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002407 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 compiler_pop_fblock(c, LOOP, loop);
2409 if (orelse != NULL) /* what if orelse is just pass? */
2410 VISIT_SEQ(c, stmt, s->v.While.orelse);
2411 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414}
2415
2416static int
2417compiler_continue(struct compiler *c)
2418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2420 static const char IN_FINALLY_ERROR_MSG[] =
2421 "'continue' not supported inside 'finally' clause";
2422 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 if (!c->u->u_nfblocks)
2425 return compiler_error(c, LOOP_ERROR_MSG);
2426 i = c->u->u_nfblocks - 1;
2427 switch (c->u->u_fblock[i].fb_type) {
2428 case LOOP:
2429 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2430 break;
2431 case EXCEPT:
2432 case FINALLY_TRY:
2433 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2434 /* Prevent continue anywhere under a finally
2435 even if hidden in a sub-try or except. */
2436 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2437 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2438 }
2439 if (i == -1)
2440 return compiler_error(c, LOOP_ERROR_MSG);
2441 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2442 break;
2443 case FINALLY_END:
2444 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2445 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448}
2449
2450/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451
2452 SETUP_FINALLY L
2453 <code for body>
2454 POP_BLOCK
2455 LOAD_CONST <None>
2456 L: <code for finalbody>
2457 END_FINALLY
2458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459 The special instructions use the block stack. Each block
2460 stack entry contains the instruction that created it (here
2461 SETUP_FINALLY), the level of the value stack at the time the
2462 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 Pushes the current value stack level and the label
2466 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 Pops en entry from the block stack, and pops the value
2469 stack until its level is the same as indicated on the
2470 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 Pops a variable number of entries from the *value* stack
2473 and re-raises the exception they specify. The number of
2474 entries popped depends on the (pseudo) exception type.
2475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 The block stack is unwound when an exception is raised:
2477 when a SETUP_FINALLY entry is found, the exception is pushed
2478 onto the value stack (and the exception condition is cleared),
2479 and the interpreter jumps to the label gotten from the block
2480 stack.
2481*/
2482
2483static int
2484compiler_try_finally(struct compiler *c, stmt_ty s)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 basicblock *body, *end;
2487 body = compiler_new_block(c);
2488 end = compiler_new_block(c);
2489 if (body == NULL || end == NULL)
2490 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 ADDOP_JREL(c, SETUP_FINALLY, end);
2493 compiler_use_next_block(c, body);
2494 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2495 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002496 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2497 if (!compiler_try_except(c, s))
2498 return 0;
2499 }
2500 else {
2501 VISIT_SEQ(c, stmt, s->v.Try.body);
2502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 ADDOP(c, POP_BLOCK);
2504 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2507 compiler_use_next_block(c, end);
2508 if (!compiler_push_fblock(c, FINALLY_END, end))
2509 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002510 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 ADDOP(c, END_FINALLY);
2512 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515}
2516
2517/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002518 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 (The contents of the value stack is shown in [], with the top
2520 at the right; 'tb' is trace-back info, 'val' the exception's
2521 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522
2523 Value stack Label Instruction Argument
2524 [] SETUP_EXCEPT L1
2525 [] <code for S>
2526 [] POP_BLOCK
2527 [] JUMP_FORWARD L0
2528
2529 [tb, val, exc] L1: DUP )
2530 [tb, val, exc, exc] <evaluate E1> )
2531 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2532 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2533 [tb, val, exc] POP
2534 [tb, val] <assign to V1> (or POP if no V1)
2535 [tb] POP
2536 [] <code for S1>
2537 JUMP_FORWARD L0
2538
2539 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 .............................etc.......................
2541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2543
2544 [] L0: <next statement>
2545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546 Of course, parts are not generated if Vi or Ei is not present.
2547*/
2548static int
2549compiler_try_except(struct compiler *c, stmt_ty s)
2550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002552 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 body = compiler_new_block(c);
2555 except = compiler_new_block(c);
2556 orelse = compiler_new_block(c);
2557 end = compiler_new_block(c);
2558 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2559 return 0;
2560 ADDOP_JREL(c, SETUP_EXCEPT, except);
2561 compiler_use_next_block(c, body);
2562 if (!compiler_push_fblock(c, EXCEPT, body))
2563 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002564 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 ADDOP(c, POP_BLOCK);
2566 compiler_pop_fblock(c, EXCEPT, body);
2567 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002568 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 compiler_use_next_block(c, except);
2570 for (i = 0; i < n; i++) {
2571 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002572 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (!handler->v.ExceptHandler.type && i < n-1)
2574 return compiler_error(c, "default 'except:' must be last");
2575 c->u->u_lineno_set = 0;
2576 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002577 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 except = compiler_new_block(c);
2579 if (except == NULL)
2580 return 0;
2581 if (handler->v.ExceptHandler.type) {
2582 ADDOP(c, DUP_TOP);
2583 VISIT(c, expr, handler->v.ExceptHandler.type);
2584 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2585 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2586 }
2587 ADDOP(c, POP_TOP);
2588 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002589 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002590
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002591 cleanup_end = compiler_new_block(c);
2592 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002593 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002594 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002595
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002596 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2597 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002599 /*
2600 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002601 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002602 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002603 try:
2604 # body
2605 finally:
2606 name = None
2607 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002608 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002610 /* second try: */
2611 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2612 compiler_use_next_block(c, cleanup_body);
2613 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2614 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002616 /* second # body */
2617 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2618 ADDOP(c, POP_BLOCK);
2619 ADDOP(c, POP_EXCEPT);
2620 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002622 /* finally: */
2623 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2624 compiler_use_next_block(c, cleanup_end);
2625 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2626 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002628 /* name = None */
2629 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2630 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002632 /* del name */
2633 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002635 ADDOP(c, END_FINALLY);
2636 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 }
2638 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002639 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002641 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002642 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002643 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644
Guido van Rossumb940e112007-01-10 16:19:56 +00002645 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002646 ADDOP(c, POP_TOP);
2647 compiler_use_next_block(c, cleanup_body);
2648 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2649 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002651 ADDOP(c, POP_EXCEPT);
2652 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 }
2654 ADDOP_JREL(c, JUMP_FORWARD, end);
2655 compiler_use_next_block(c, except);
2656 }
2657 ADDOP(c, END_FINALLY);
2658 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002659 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 compiler_use_next_block(c, end);
2661 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662}
2663
2664static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002665compiler_try(struct compiler *c, stmt_ty s) {
2666 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2667 return compiler_try_finally(c, s);
2668 else
2669 return compiler_try_except(c, s);
2670}
2671
2672
2673static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674compiler_import_as(struct compiler *c, identifier name, identifier asname)
2675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 /* The IMPORT_NAME opcode was already generated. This function
2677 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002680 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002682 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2683 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002684 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002685 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002686 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002688 while (1) {
2689 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002691 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002693 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002694 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002696 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002697 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002699 if (dot == -1) {
2700 break;
2701 }
2702 ADDOP(c, ROT_TWO);
2703 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002705 if (!compiler_nameop(c, asname, Store)) {
2706 return 0;
2707 }
2708 ADDOP(c, POP_TOP);
2709 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 }
2711 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712}
2713
2714static int
2715compiler_import(struct compiler *c, stmt_ty s)
2716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 /* The Import node stores a module name like a.b.c as a single
2718 string. This is convenient for all cases except
2719 import a.b.c as d
2720 where we need to parse that string to extract the individual
2721 module names.
2722 XXX Perhaps change the representation to make this case simpler?
2723 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002724 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 for (i = 0; i < n; i++) {
2727 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2728 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002730 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2732 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 if (alias->asname) {
2735 r = compiler_import_as(c, alias->name, alias->asname);
2736 if (!r)
2737 return r;
2738 }
2739 else {
2740 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 Py_ssize_t dot = PyUnicode_FindChar(
2742 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002743 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002745 if (tmp == NULL)
2746 return 0;
2747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 Py_DECREF(tmp);
2751 }
2752 if (!r)
2753 return r;
2754 }
2755 }
2756 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757}
2758
2759static int
2760compiler_from_import(struct compiler *c, stmt_ty s)
2761{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002762 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 PyObject *names = PyTuple_New(n);
2765 PyObject *level;
2766 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 if (!empty_string) {
2769 empty_string = PyUnicode_FromString("");
2770 if (!empty_string)
2771 return 0;
2772 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (!names)
2775 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 level = PyLong_FromLong(s->v.ImportFrom.level);
2778 if (!level) {
2779 Py_DECREF(names);
2780 return 0;
2781 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 /* build up the names */
2784 for (i = 0; i < n; i++) {
2785 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2786 Py_INCREF(alias->name);
2787 PyTuple_SET_ITEM(names, i, alias->name);
2788 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002791 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 Py_DECREF(level);
2793 Py_DECREF(names);
2794 return compiler_error(c, "from __future__ imports must occur "
2795 "at the beginning of the file");
2796 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 ADDOP_O(c, LOAD_CONST, level, consts);
2799 Py_DECREF(level);
2800 ADDOP_O(c, LOAD_CONST, names, consts);
2801 Py_DECREF(names);
2802 if (s->v.ImportFrom.module) {
2803 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2804 }
2805 else {
2806 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2807 }
2808 for (i = 0; i < n; i++) {
2809 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2810 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 assert(n == 1);
2814 ADDOP(c, IMPORT_STAR);
2815 return 1;
2816 }
2817
2818 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2819 store_name = alias->name;
2820 if (alias->asname)
2821 store_name = alias->asname;
2822
2823 if (!compiler_nameop(c, store_name, Store)) {
2824 Py_DECREF(names);
2825 return 0;
2826 }
2827 }
2828 /* remove imported module */
2829 ADDOP(c, POP_TOP);
2830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831}
2832
2833static int
2834compiler_assert(struct compiler *c, stmt_ty s)
2835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 static PyObject *assertion_error = NULL;
2837 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002838 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839
Georg Brandl8334fd92010-12-04 10:26:46 +00002840 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 return 1;
2842 if (assertion_error == NULL) {
2843 assertion_error = PyUnicode_InternFromString("AssertionError");
2844 if (assertion_error == NULL)
2845 return 0;
2846 }
2847 if (s->v.Assert.test->kind == Tuple_kind &&
2848 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002849 msg = PyUnicode_FromString("assertion is always true, "
2850 "perhaps remove parentheses?");
2851 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002853 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2854 c->c_filename, c->u->u_lineno,
2855 NULL, NULL) == -1) {
2856 Py_DECREF(msg);
2857 return 0;
2858 }
2859 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 end = compiler_new_block(c);
2862 if (end == NULL)
2863 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002864 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2865 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2867 if (s->v.Assert.msg) {
2868 VISIT(c, expr, s->v.Assert.msg);
2869 ADDOP_I(c, CALL_FUNCTION, 1);
2870 }
2871 ADDOP_I(c, RAISE_VARARGS, 1);
2872 compiler_use_next_block(c, end);
2873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874}
2875
2876static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002877compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2878{
2879 if (c->c_interactive && c->c_nestlevel <= 1) {
2880 VISIT(c, expr, value);
2881 ADDOP(c, PRINT_EXPR);
2882 return 1;
2883 }
2884
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002885 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002886 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002887 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002888 }
2889
2890 VISIT(c, expr, value);
2891 ADDOP(c, POP_TOP);
2892 return 1;
2893}
2894
2895static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896compiler_visit_stmt(struct compiler *c, stmt_ty s)
2897{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002898 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 /* Always assign a lineno to the next instruction for a stmt. */
2901 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002902 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 switch (s->kind) {
2906 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002907 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 case ClassDef_kind:
2909 return compiler_class(c, s);
2910 case Return_kind:
2911 if (c->u->u_ste->ste_type != FunctionBlock)
2912 return compiler_error(c, "'return' outside function");
2913 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002914 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2915 return compiler_error(
2916 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 VISIT(c, expr, s->v.Return.value);
2918 }
2919 else
2920 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2921 ADDOP(c, RETURN_VALUE);
2922 break;
2923 case Delete_kind:
2924 VISIT_SEQ(c, expr, s->v.Delete.targets)
2925 break;
2926 case Assign_kind:
2927 n = asdl_seq_LEN(s->v.Assign.targets);
2928 VISIT(c, expr, s->v.Assign.value);
2929 for (i = 0; i < n; i++) {
2930 if (i < n - 1)
2931 ADDOP(c, DUP_TOP);
2932 VISIT(c, expr,
2933 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2934 }
2935 break;
2936 case AugAssign_kind:
2937 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002938 case AnnAssign_kind:
2939 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 case For_kind:
2941 return compiler_for(c, s);
2942 case While_kind:
2943 return compiler_while(c, s);
2944 case If_kind:
2945 return compiler_if(c, s);
2946 case Raise_kind:
2947 n = 0;
2948 if (s->v.Raise.exc) {
2949 VISIT(c, expr, s->v.Raise.exc);
2950 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002951 if (s->v.Raise.cause) {
2952 VISIT(c, expr, s->v.Raise.cause);
2953 n++;
2954 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002956 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002958 case Try_kind:
2959 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 case Assert_kind:
2961 return compiler_assert(c, s);
2962 case Import_kind:
2963 return compiler_import(c, s);
2964 case ImportFrom_kind:
2965 return compiler_from_import(c, s);
2966 case Global_kind:
2967 case Nonlocal_kind:
2968 break;
2969 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002970 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 case Pass_kind:
2972 break;
2973 case Break_kind:
2974 if (!compiler_in_loop(c))
2975 return compiler_error(c, "'break' outside loop");
2976 ADDOP(c, BREAK_LOOP);
2977 break;
2978 case Continue_kind:
2979 return compiler_continue(c);
2980 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002981 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002982 case AsyncFunctionDef_kind:
2983 return compiler_function(c, s, 1);
2984 case AsyncWith_kind:
2985 return compiler_async_with(c, s, 0);
2986 case AsyncFor_kind:
2987 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 }
Yury Selivanov75445082015-05-11 22:57:16 -04002989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991}
2992
2993static int
2994unaryop(unaryop_ty op)
2995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 switch (op) {
2997 case Invert:
2998 return UNARY_INVERT;
2999 case Not:
3000 return UNARY_NOT;
3001 case UAdd:
3002 return UNARY_POSITIVE;
3003 case USub:
3004 return UNARY_NEGATIVE;
3005 default:
3006 PyErr_Format(PyExc_SystemError,
3007 "unary op %d should not be possible", op);
3008 return 0;
3009 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010}
3011
3012static int
3013binop(struct compiler *c, operator_ty op)
3014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 switch (op) {
3016 case Add:
3017 return BINARY_ADD;
3018 case Sub:
3019 return BINARY_SUBTRACT;
3020 case Mult:
3021 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003022 case MatMult:
3023 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 case Div:
3025 return BINARY_TRUE_DIVIDE;
3026 case Mod:
3027 return BINARY_MODULO;
3028 case Pow:
3029 return BINARY_POWER;
3030 case LShift:
3031 return BINARY_LSHIFT;
3032 case RShift:
3033 return BINARY_RSHIFT;
3034 case BitOr:
3035 return BINARY_OR;
3036 case BitXor:
3037 return BINARY_XOR;
3038 case BitAnd:
3039 return BINARY_AND;
3040 case FloorDiv:
3041 return BINARY_FLOOR_DIVIDE;
3042 default:
3043 PyErr_Format(PyExc_SystemError,
3044 "binary op %d should not be possible", op);
3045 return 0;
3046 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047}
3048
3049static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050inplace_binop(struct compiler *c, operator_ty op)
3051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 switch (op) {
3053 case Add:
3054 return INPLACE_ADD;
3055 case Sub:
3056 return INPLACE_SUBTRACT;
3057 case Mult:
3058 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003059 case MatMult:
3060 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 case Div:
3062 return INPLACE_TRUE_DIVIDE;
3063 case Mod:
3064 return INPLACE_MODULO;
3065 case Pow:
3066 return INPLACE_POWER;
3067 case LShift:
3068 return INPLACE_LSHIFT;
3069 case RShift:
3070 return INPLACE_RSHIFT;
3071 case BitOr:
3072 return INPLACE_OR;
3073 case BitXor:
3074 return INPLACE_XOR;
3075 case BitAnd:
3076 return INPLACE_AND;
3077 case FloorDiv:
3078 return INPLACE_FLOOR_DIVIDE;
3079 default:
3080 PyErr_Format(PyExc_SystemError,
3081 "inplace binary op %d should not be possible", op);
3082 return 0;
3083 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003084}
3085
3086static int
3087compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3088{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003089 int op, scope;
3090 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 PyObject *dict = c->u->u_names;
3094 PyObject *mangled;
3095 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003097 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3098 !_PyUnicode_EqualToASCIIString(name, "True") &&
3099 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003100
Serhiy Storchaka3325a672017-12-15 12:35:48 +02003101 if (ctx == Load && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
3102 ADDOP_O(c, LOAD_CONST, c->c_optimize ? Py_False : Py_True, consts);
3103 return 1;
3104 }
3105
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003106 mangled = _Py_Mangle(c->u->u_private, name);
3107 if (!mangled)
3108 return 0;
3109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 op = 0;
3111 optype = OP_NAME;
3112 scope = PyST_GetScope(c->u->u_ste, mangled);
3113 switch (scope) {
3114 case FREE:
3115 dict = c->u->u_freevars;
3116 optype = OP_DEREF;
3117 break;
3118 case CELL:
3119 dict = c->u->u_cellvars;
3120 optype = OP_DEREF;
3121 break;
3122 case LOCAL:
3123 if (c->u->u_ste->ste_type == FunctionBlock)
3124 optype = OP_FAST;
3125 break;
3126 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003127 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 optype = OP_GLOBAL;
3129 break;
3130 case GLOBAL_EXPLICIT:
3131 optype = OP_GLOBAL;
3132 break;
3133 default:
3134 /* scope can be 0 */
3135 break;
3136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003139 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 switch (optype) {
3142 case OP_DEREF:
3143 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003144 case Load:
3145 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3146 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 case Store: op = STORE_DEREF; break;
3148 case AugLoad:
3149 case AugStore:
3150 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003151 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 case Param:
3153 default:
3154 PyErr_SetString(PyExc_SystemError,
3155 "param invalid for deref variable");
3156 return 0;
3157 }
3158 break;
3159 case OP_FAST:
3160 switch (ctx) {
3161 case Load: op = LOAD_FAST; break;
3162 case Store: op = STORE_FAST; break;
3163 case Del: op = DELETE_FAST; break;
3164 case AugLoad:
3165 case AugStore:
3166 break;
3167 case Param:
3168 default:
3169 PyErr_SetString(PyExc_SystemError,
3170 "param invalid for local variable");
3171 return 0;
3172 }
3173 ADDOP_O(c, op, mangled, varnames);
3174 Py_DECREF(mangled);
3175 return 1;
3176 case OP_GLOBAL:
3177 switch (ctx) {
3178 case Load: op = LOAD_GLOBAL; break;
3179 case Store: op = STORE_GLOBAL; break;
3180 case Del: op = DELETE_GLOBAL; break;
3181 case AugLoad:
3182 case AugStore:
3183 break;
3184 case Param:
3185 default:
3186 PyErr_SetString(PyExc_SystemError,
3187 "param invalid for global variable");
3188 return 0;
3189 }
3190 break;
3191 case OP_NAME:
3192 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003193 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 case Store: op = STORE_NAME; break;
3195 case Del: op = DELETE_NAME; break;
3196 case AugLoad:
3197 case AugStore:
3198 break;
3199 case Param:
3200 default:
3201 PyErr_SetString(PyExc_SystemError,
3202 "param invalid for name variable");
3203 return 0;
3204 }
3205 break;
3206 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 assert(op);
3209 arg = compiler_add_o(c, dict, mangled);
3210 Py_DECREF(mangled);
3211 if (arg < 0)
3212 return 0;
3213 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214}
3215
3216static int
3217compiler_boolop(struct compiler *c, expr_ty e)
3218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003220 int jumpi;
3221 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 assert(e->kind == BoolOp_kind);
3225 if (e->v.BoolOp.op == And)
3226 jumpi = JUMP_IF_FALSE_OR_POP;
3227 else
3228 jumpi = JUMP_IF_TRUE_OR_POP;
3229 end = compiler_new_block(c);
3230 if (end == NULL)
3231 return 0;
3232 s = e->v.BoolOp.values;
3233 n = asdl_seq_LEN(s) - 1;
3234 assert(n >= 0);
3235 for (i = 0; i < n; ++i) {
3236 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3237 ADDOP_JABS(c, jumpi, end);
3238 }
3239 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3240 compiler_use_next_block(c, end);
3241 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242}
3243
3244static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003245starunpack_helper(struct compiler *c, asdl_seq *elts,
3246 int single_op, int inner_op, int outer_op)
3247{
3248 Py_ssize_t n = asdl_seq_LEN(elts);
3249 Py_ssize_t i, nsubitems = 0, nseen = 0;
3250 for (i = 0; i < n; i++) {
3251 expr_ty elt = asdl_seq_GET(elts, i);
3252 if (elt->kind == Starred_kind) {
3253 if (nseen) {
3254 ADDOP_I(c, inner_op, nseen);
3255 nseen = 0;
3256 nsubitems++;
3257 }
3258 VISIT(c, expr, elt->v.Starred.value);
3259 nsubitems++;
3260 }
3261 else {
3262 VISIT(c, expr, elt);
3263 nseen++;
3264 }
3265 }
3266 if (nsubitems) {
3267 if (nseen) {
3268 ADDOP_I(c, inner_op, nseen);
3269 nsubitems++;
3270 }
3271 ADDOP_I(c, outer_op, nsubitems);
3272 }
3273 else
3274 ADDOP_I(c, single_op, nseen);
3275 return 1;
3276}
3277
3278static int
3279assignment_helper(struct compiler *c, asdl_seq *elts)
3280{
3281 Py_ssize_t n = asdl_seq_LEN(elts);
3282 Py_ssize_t i;
3283 int seen_star = 0;
3284 for (i = 0; i < n; i++) {
3285 expr_ty elt = asdl_seq_GET(elts, i);
3286 if (elt->kind == Starred_kind && !seen_star) {
3287 if ((i >= (1 << 8)) ||
3288 (n-i-1 >= (INT_MAX >> 8)))
3289 return compiler_error(c,
3290 "too many expressions in "
3291 "star-unpacking assignment");
3292 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3293 seen_star = 1;
3294 asdl_seq_SET(elts, i, elt->v.Starred.value);
3295 }
3296 else if (elt->kind == Starred_kind) {
3297 return compiler_error(c,
3298 "two starred expressions in assignment");
3299 }
3300 }
3301 if (!seen_star) {
3302 ADDOP_I(c, UNPACK_SEQUENCE, n);
3303 }
3304 VISIT_SEQ(c, expr, elts);
3305 return 1;
3306}
3307
3308static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309compiler_list(struct compiler *c, expr_ty e)
3310{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003311 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003313 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003315 else if (e->v.List.ctx == Load) {
3316 return starunpack_helper(c, elts,
3317 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003319 else
3320 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322}
3323
3324static int
3325compiler_tuple(struct compiler *c, expr_ty e)
3326{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003327 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003329 return assignment_helper(c, elts);
3330 }
3331 else if (e->v.Tuple.ctx == Load) {
3332 return starunpack_helper(c, elts,
3333 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3334 }
3335 else
3336 VISIT_SEQ(c, expr, elts);
3337 return 1;
3338}
3339
3340static int
3341compiler_set(struct compiler *c, expr_ty e)
3342{
3343 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3344 BUILD_SET, BUILD_SET_UNPACK);
3345}
3346
3347static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003348are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3349{
3350 Py_ssize_t i;
3351 for (i = begin; i < end; i++) {
3352 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3353 if (key == NULL || !is_const(key))
3354 return 0;
3355 }
3356 return 1;
3357}
3358
3359static int
3360compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3361{
3362 Py_ssize_t i, n = end - begin;
3363 PyObject *keys, *key;
3364 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3365 for (i = begin; i < end; i++) {
3366 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3367 }
3368 keys = PyTuple_New(n);
3369 if (keys == NULL) {
3370 return 0;
3371 }
3372 for (i = begin; i < end; i++) {
Serhiy Storchaka3325a672017-12-15 12:35:48 +02003373 key = get_const_value(c, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003374 Py_INCREF(key);
3375 PyTuple_SET_ITEM(keys, i - begin, key);
3376 }
3377 ADDOP_N(c, LOAD_CONST, keys, consts);
3378 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3379 }
3380 else {
3381 for (i = begin; i < end; i++) {
3382 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3383 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3384 }
3385 ADDOP_I(c, BUILD_MAP, n);
3386 }
3387 return 1;
3388}
3389
3390static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003391compiler_dict(struct compiler *c, expr_ty e)
3392{
Victor Stinner976bb402016-03-23 11:36:19 +01003393 Py_ssize_t i, n, elements;
3394 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003395 int is_unpacking = 0;
3396 n = asdl_seq_LEN(e->v.Dict.values);
3397 containers = 0;
3398 elements = 0;
3399 for (i = 0; i < n; i++) {
3400 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3401 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003402 if (!compiler_subdict(c, e, i - elements, i))
3403 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003404 containers++;
3405 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003407 if (is_unpacking) {
3408 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3409 containers++;
3410 }
3411 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003412 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 }
3414 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003415 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003416 if (!compiler_subdict(c, e, n - elements, n))
3417 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003418 containers++;
3419 }
3420 /* If there is more than one dict, they need to be merged into a new
3421 * dict. If there is one dict and it's an unpacking, then it needs
3422 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003423 if (containers > 1 || is_unpacking) {
3424 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 }
3426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427}
3428
3429static int
3430compiler_compare(struct compiler *c, expr_ty e)
3431{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003432 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3436 VISIT(c, expr, e->v.Compare.left);
3437 n = asdl_seq_LEN(e->v.Compare.ops);
3438 assert(n > 0);
3439 if (n > 1) {
3440 cleanup = compiler_new_block(c);
3441 if (cleanup == NULL)
3442 return 0;
3443 VISIT(c, expr,
3444 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3445 }
3446 for (i = 1; i < n; i++) {
3447 ADDOP(c, DUP_TOP);
3448 ADDOP(c, ROT_THREE);
3449 ADDOP_I(c, COMPARE_OP,
3450 cmpop((cmpop_ty)(asdl_seq_GET(
3451 e->v.Compare.ops, i - 1))));
3452 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3453 NEXT_BLOCK(c);
3454 if (i < (n - 1))
3455 VISIT(c, expr,
3456 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3457 }
3458 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3459 ADDOP_I(c, COMPARE_OP,
3460 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3461 if (n > 1) {
3462 basicblock *end = compiler_new_block(c);
3463 if (end == NULL)
3464 return 0;
3465 ADDOP_JREL(c, JUMP_FORWARD, end);
3466 compiler_use_next_block(c, cleanup);
3467 ADDOP(c, ROT_TWO);
3468 ADDOP(c, POP_TOP);
3469 compiler_use_next_block(c, end);
3470 }
3471 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003472}
3473
3474static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003475maybe_optimize_method_call(struct compiler *c, expr_ty e)
3476{
3477 Py_ssize_t argsl, i;
3478 expr_ty meth = e->v.Call.func;
3479 asdl_seq *args = e->v.Call.args;
3480
3481 /* Check that the call node is an attribute access, and that
3482 the call doesn't have keyword parameters. */
3483 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3484 asdl_seq_LEN(e->v.Call.keywords))
3485 return -1;
3486
3487 /* Check that there are no *varargs types of arguments. */
3488 argsl = asdl_seq_LEN(args);
3489 for (i = 0; i < argsl; i++) {
3490 expr_ty elt = asdl_seq_GET(args, i);
3491 if (elt->kind == Starred_kind) {
3492 return -1;
3493 }
3494 }
3495
3496 /* Alright, we can optimize the code. */
3497 VISIT(c, expr, meth->v.Attribute.value);
3498 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3499 VISIT_SEQ(c, expr, e->v.Call.args);
3500 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3501 return 1;
3502}
3503
3504static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505compiler_call(struct compiler *c, expr_ty e)
3506{
Yury Selivanovf2392132016-12-13 19:03:51 -05003507 if (maybe_optimize_method_call(c, e) > 0)
3508 return 1;
3509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 VISIT(c, expr, e->v.Call.func);
3511 return compiler_call_helper(c, 0,
3512 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003513 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003514}
3515
Eric V. Smith235a6f02015-09-19 14:51:32 -04003516static int
3517compiler_joined_str(struct compiler *c, expr_ty e)
3518{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003519 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003520 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3521 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003522 return 1;
3523}
3524
Eric V. Smitha78c7952015-11-03 12:45:05 -05003525/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003526static int
3527compiler_formatted_value(struct compiler *c, expr_ty e)
3528{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003529 /* Our oparg encodes 2 pieces of information: the conversion
3530 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003531
Eric V. Smitha78c7952015-11-03 12:45:05 -05003532 Convert the conversion char to 2 bits:
3533 None: 000 0x0 FVC_NONE
3534 !s : 001 0x1 FVC_STR
3535 !r : 010 0x2 FVC_REPR
3536 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003537
Eric V. Smitha78c7952015-11-03 12:45:05 -05003538 next bit is whether or not we have a format spec:
3539 yes : 100 0x4
3540 no : 000 0x0
3541 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003542
Eric V. Smitha78c7952015-11-03 12:45:05 -05003543 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003544
Eric V. Smitha78c7952015-11-03 12:45:05 -05003545 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003546 VISIT(c, expr, e->v.FormattedValue.value);
3547
Eric V. Smitha78c7952015-11-03 12:45:05 -05003548 switch (e->v.FormattedValue.conversion) {
3549 case 's': oparg = FVC_STR; break;
3550 case 'r': oparg = FVC_REPR; break;
3551 case 'a': oparg = FVC_ASCII; break;
3552 case -1: oparg = FVC_NONE; break;
3553 default:
3554 PyErr_SetString(PyExc_SystemError,
3555 "Unrecognized conversion character");
3556 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003557 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003558 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003559 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003560 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003561 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003562 }
3563
Eric V. Smitha78c7952015-11-03 12:45:05 -05003564 /* And push our opcode and oparg */
3565 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003566 return 1;
3567}
3568
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003569static int
3570compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3571{
3572 Py_ssize_t i, n = end - begin;
3573 keyword_ty kw;
3574 PyObject *keys, *key;
3575 assert(n > 0);
3576 if (n > 1) {
3577 for (i = begin; i < end; i++) {
3578 kw = asdl_seq_GET(keywords, i);
3579 VISIT(c, expr, kw->value);
3580 }
3581 keys = PyTuple_New(n);
3582 if (keys == NULL) {
3583 return 0;
3584 }
3585 for (i = begin; i < end; i++) {
3586 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3587 Py_INCREF(key);
3588 PyTuple_SET_ITEM(keys, i - begin, key);
3589 }
3590 ADDOP_N(c, LOAD_CONST, keys, consts);
3591 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3592 }
3593 else {
3594 /* a for loop only executes once */
3595 for (i = begin; i < end; i++) {
3596 kw = asdl_seq_GET(keywords, i);
3597 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3598 VISIT(c, expr, kw->value);
3599 }
3600 ADDOP_I(c, BUILD_MAP, n);
3601 }
3602 return 1;
3603}
3604
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003605/* shared code between compiler_call and compiler_class */
3606static int
3607compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003608 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003609 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003610 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003611{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003612 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003613 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003614
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003615 /* the number of tuples and dictionaries on the stack */
3616 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3617
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003618 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003619 nkwelts = asdl_seq_LEN(keywords);
3620
3621 for (i = 0; i < nkwelts; i++) {
3622 keyword_ty kw = asdl_seq_GET(keywords, i);
3623 if (kw->arg == NULL) {
3624 mustdictunpack = 1;
3625 break;
3626 }
3627 }
3628
3629 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003630 for (i = 0; i < nelts; i++) {
3631 expr_ty elt = asdl_seq_GET(args, i);
3632 if (elt->kind == Starred_kind) {
3633 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003634 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003635 if (nseen) {
3636 ADDOP_I(c, BUILD_TUPLE, nseen);
3637 nseen = 0;
3638 nsubargs++;
3639 }
3640 VISIT(c, expr, elt->v.Starred.value);
3641 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003642 }
3643 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003644 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003645 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003648
3649 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003650 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003651 if (nseen) {
3652 /* Pack up any trailing positional arguments. */
3653 ADDOP_I(c, BUILD_TUPLE, nseen);
3654 nsubargs++;
3655 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003656 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003657 /* If we ended up with more than one stararg, we need
3658 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003659 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003660 }
3661 else if (nsubargs == 0) {
3662 ADDOP_I(c, BUILD_TUPLE, 0);
3663 }
3664 nseen = 0; /* the number of keyword arguments on the stack following */
3665 for (i = 0; i < nkwelts; i++) {
3666 keyword_ty kw = asdl_seq_GET(keywords, i);
3667 if (kw->arg == NULL) {
3668 /* A keyword argument unpacking. */
3669 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003670 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3671 return 0;
3672 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003673 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003674 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003675 VISIT(c, expr, kw->value);
3676 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003677 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003678 else {
3679 nseen++;
3680 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003681 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003682 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003683 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003684 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003685 return 0;
3686 nsubkwargs++;
3687 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003688 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003689 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003690 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003691 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003692 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3693 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003695 else if (nkwelts) {
3696 PyObject *names;
3697 VISIT_SEQ(c, keyword, keywords);
3698 names = PyTuple_New(nkwelts);
3699 if (names == NULL) {
3700 return 0;
3701 }
3702 for (i = 0; i < nkwelts; i++) {
3703 keyword_ty kw = asdl_seq_GET(keywords, i);
3704 Py_INCREF(kw->arg);
3705 PyTuple_SET_ITEM(names, i, kw->arg);
3706 }
3707 ADDOP_N(c, LOAD_CONST, names, consts);
3708 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3709 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003711 else {
3712 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3713 return 1;
3714 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003715}
3716
Nick Coghlan650f0d02007-04-15 12:05:43 +00003717
3718/* List and set comprehensions and generator expressions work by creating a
3719 nested function to perform the actual iteration. This means that the
3720 iteration variables don't leak into the current scope.
3721 The defined function is called immediately following its definition, with the
3722 result of that call being the result of the expression.
3723 The LC/SC version returns the populated container, while the GE version is
3724 flagged in symtable.c as a generator, so it returns the generator object
3725 when the function is called.
3726 This code *knows* that the loop cannot contain break, continue, or return,
3727 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3728
3729 Possible cleanups:
3730 - iterate over the generator sequence instead of using recursion
3731*/
3732
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003733
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735compiler_comprehension_generator(struct compiler *c,
3736 asdl_seq *generators, int gen_index,
3737 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003739 comprehension_ty gen;
3740 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3741 if (gen->is_async) {
3742 return compiler_async_comprehension_generator(
3743 c, generators, gen_index, elt, val, type);
3744 } else {
3745 return compiler_sync_comprehension_generator(
3746 c, generators, gen_index, elt, val, type);
3747 }
3748}
3749
3750static int
3751compiler_sync_comprehension_generator(struct compiler *c,
3752 asdl_seq *generators, int gen_index,
3753 expr_ty elt, expr_ty val, int type)
3754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 /* generate code for the iterator, then each of the ifs,
3756 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 comprehension_ty gen;
3759 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003760 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 start = compiler_new_block(c);
3763 skip = compiler_new_block(c);
3764 if_cleanup = compiler_new_block(c);
3765 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3768 anchor == NULL)
3769 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 if (gen_index == 0) {
3774 /* Receive outermost iter as an implicit argument */
3775 c->u->u_argcount = 1;
3776 ADDOP_I(c, LOAD_FAST, 0);
3777 }
3778 else {
3779 /* Sub-iter - calculate on the fly */
3780 VISIT(c, expr, gen->iter);
3781 ADDOP(c, GET_ITER);
3782 }
3783 compiler_use_next_block(c, start);
3784 ADDOP_JREL(c, FOR_ITER, anchor);
3785 NEXT_BLOCK(c);
3786 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 /* XXX this needs to be cleaned up...a lot! */
3789 n = asdl_seq_LEN(gen->ifs);
3790 for (i = 0; i < n; i++) {
3791 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003792 if (!compiler_jump_if(c, e, if_cleanup, 0))
3793 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 NEXT_BLOCK(c);
3795 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 if (++gen_index < asdl_seq_LEN(generators))
3798 if (!compiler_comprehension_generator(c,
3799 generators, gen_index,
3800 elt, val, type))
3801 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 /* only append after the last for generator */
3804 if (gen_index >= asdl_seq_LEN(generators)) {
3805 /* comprehension specific code */
3806 switch (type) {
3807 case COMP_GENEXP:
3808 VISIT(c, expr, elt);
3809 ADDOP(c, YIELD_VALUE);
3810 ADDOP(c, POP_TOP);
3811 break;
3812 case COMP_LISTCOMP:
3813 VISIT(c, expr, elt);
3814 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3815 break;
3816 case COMP_SETCOMP:
3817 VISIT(c, expr, elt);
3818 ADDOP_I(c, SET_ADD, gen_index + 1);
3819 break;
3820 case COMP_DICTCOMP:
3821 /* With 'd[k] = v', v is evaluated before k, so we do
3822 the same. */
3823 VISIT(c, expr, val);
3824 VISIT(c, expr, elt);
3825 ADDOP_I(c, MAP_ADD, gen_index + 1);
3826 break;
3827 default:
3828 return 0;
3829 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 compiler_use_next_block(c, skip);
3832 }
3833 compiler_use_next_block(c, if_cleanup);
3834 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3835 compiler_use_next_block(c, anchor);
3836
3837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838}
3839
3840static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003841compiler_async_comprehension_generator(struct compiler *c,
3842 asdl_seq *generators, int gen_index,
3843 expr_ty elt, expr_ty val, int type)
3844{
3845 _Py_IDENTIFIER(StopAsyncIteration);
3846
3847 comprehension_ty gen;
3848 basicblock *anchor, *skip, *if_cleanup, *try,
3849 *after_try, *except, *try_cleanup;
3850 Py_ssize_t i, n;
3851
3852 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3853 if (stop_aiter_error == NULL) {
3854 return 0;
3855 }
3856
3857 try = compiler_new_block(c);
3858 after_try = compiler_new_block(c);
3859 try_cleanup = compiler_new_block(c);
3860 except = compiler_new_block(c);
3861 skip = compiler_new_block(c);
3862 if_cleanup = compiler_new_block(c);
3863 anchor = compiler_new_block(c);
3864
3865 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3866 try == NULL || after_try == NULL ||
3867 except == NULL || after_try == NULL) {
3868 return 0;
3869 }
3870
3871 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3872
3873 if (gen_index == 0) {
3874 /* Receive outermost iter as an implicit argument */
3875 c->u->u_argcount = 1;
3876 ADDOP_I(c, LOAD_FAST, 0);
3877 }
3878 else {
3879 /* Sub-iter - calculate on the fly */
3880 VISIT(c, expr, gen->iter);
3881 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003882 }
3883
3884 compiler_use_next_block(c, try);
3885
3886
3887 ADDOP_JREL(c, SETUP_EXCEPT, except);
3888 if (!compiler_push_fblock(c, EXCEPT, try))
3889 return 0;
3890
3891 ADDOP(c, GET_ANEXT);
3892 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3893 ADDOP(c, YIELD_FROM);
3894 VISIT(c, expr, gen->target);
3895 ADDOP(c, POP_BLOCK);
3896 compiler_pop_fblock(c, EXCEPT, try);
3897 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3898
3899
3900 compiler_use_next_block(c, except);
3901 ADDOP(c, DUP_TOP);
3902 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3903 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3904 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3905
3906 ADDOP(c, POP_TOP);
3907 ADDOP(c, POP_TOP);
3908 ADDOP(c, POP_TOP);
3909 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3910 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3911
3912
3913 compiler_use_next_block(c, try_cleanup);
3914 ADDOP(c, END_FINALLY);
3915
3916 compiler_use_next_block(c, after_try);
3917
3918 n = asdl_seq_LEN(gen->ifs);
3919 for (i = 0; i < n; i++) {
3920 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003921 if (!compiler_jump_if(c, e, if_cleanup, 0))
3922 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003923 NEXT_BLOCK(c);
3924 }
3925
3926 if (++gen_index < asdl_seq_LEN(generators))
3927 if (!compiler_comprehension_generator(c,
3928 generators, gen_index,
3929 elt, val, type))
3930 return 0;
3931
3932 /* only append after the last for generator */
3933 if (gen_index >= asdl_seq_LEN(generators)) {
3934 /* comprehension specific code */
3935 switch (type) {
3936 case COMP_GENEXP:
3937 VISIT(c, expr, elt);
3938 ADDOP(c, YIELD_VALUE);
3939 ADDOP(c, POP_TOP);
3940 break;
3941 case COMP_LISTCOMP:
3942 VISIT(c, expr, elt);
3943 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3944 break;
3945 case COMP_SETCOMP:
3946 VISIT(c, expr, elt);
3947 ADDOP_I(c, SET_ADD, gen_index + 1);
3948 break;
3949 case COMP_DICTCOMP:
3950 /* With 'd[k] = v', v is evaluated before k, so we do
3951 the same. */
3952 VISIT(c, expr, val);
3953 VISIT(c, expr, elt);
3954 ADDOP_I(c, MAP_ADD, gen_index + 1);
3955 break;
3956 default:
3957 return 0;
3958 }
3959
3960 compiler_use_next_block(c, skip);
3961 }
3962 compiler_use_next_block(c, if_cleanup);
3963 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3964 compiler_use_next_block(c, anchor);
3965 ADDOP(c, POP_TOP);
3966
3967 return 1;
3968}
3969
3970static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003971compiler_comprehension(struct compiler *c, expr_ty e, int type,
3972 identifier name, asdl_seq *generators, expr_ty elt,
3973 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003976 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003977 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003978 int is_async_function = c->u->u_ste->ste_coroutine;
3979 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003980
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003981 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003982
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003983 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3984 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003985 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003987 }
3988
3989 is_async_generator = c->u->u_ste->ste_coroutine;
3990
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04003991 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003992 if (e->lineno > c->u->u_lineno) {
3993 c->u->u_lineno = e->lineno;
3994 c->u->u_lineno_set = 0;
3995 }
3996 compiler_error(c, "asynchronous comprehension outside of "
3997 "an asynchronous function");
3998 goto error_in_scope;
3999 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 if (type != COMP_GENEXP) {
4002 int op;
4003 switch (type) {
4004 case COMP_LISTCOMP:
4005 op = BUILD_LIST;
4006 break;
4007 case COMP_SETCOMP:
4008 op = BUILD_SET;
4009 break;
4010 case COMP_DICTCOMP:
4011 op = BUILD_MAP;
4012 break;
4013 default:
4014 PyErr_Format(PyExc_SystemError,
4015 "unknown comprehension type %d", type);
4016 goto error_in_scope;
4017 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 ADDOP_I(c, op, 0);
4020 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 if (!compiler_comprehension_generator(c, generators, 0, elt,
4023 val, type))
4024 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 if (type != COMP_GENEXP) {
4027 ADDOP(c, RETURN_VALUE);
4028 }
4029
4030 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004031 qualname = c->u->u_qualname;
4032 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004034 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 goto error;
4036
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004037 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004039 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 Py_DECREF(co);
4041
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004042 VISIT(c, expr, outermost->iter);
4043
4044 if (outermost->is_async) {
4045 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004046 } else {
4047 ADDOP(c, GET_ITER);
4048 }
4049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004051
4052 if (is_async_generator && type != COMP_GENEXP) {
4053 ADDOP(c, GET_AWAITABLE);
4054 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4055 ADDOP(c, YIELD_FROM);
4056 }
4057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004059error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004061error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004062 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 Py_XDECREF(co);
4064 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004065}
4066
4067static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068compiler_genexp(struct compiler *c, expr_ty e)
4069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 static identifier name;
4071 if (!name) {
4072 name = PyUnicode_FromString("<genexpr>");
4073 if (!name)
4074 return 0;
4075 }
4076 assert(e->kind == GeneratorExp_kind);
4077 return compiler_comprehension(c, e, COMP_GENEXP, name,
4078 e->v.GeneratorExp.generators,
4079 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080}
4081
4082static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004083compiler_listcomp(struct compiler *c, expr_ty e)
4084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 static identifier name;
4086 if (!name) {
4087 name = PyUnicode_FromString("<listcomp>");
4088 if (!name)
4089 return 0;
4090 }
4091 assert(e->kind == ListComp_kind);
4092 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4093 e->v.ListComp.generators,
4094 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004095}
4096
4097static int
4098compiler_setcomp(struct compiler *c, expr_ty e)
4099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 static identifier name;
4101 if (!name) {
4102 name = PyUnicode_FromString("<setcomp>");
4103 if (!name)
4104 return 0;
4105 }
4106 assert(e->kind == SetComp_kind);
4107 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4108 e->v.SetComp.generators,
4109 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004110}
4111
4112
4113static int
4114compiler_dictcomp(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("<dictcomp>");
4119 if (!name)
4120 return 0;
4121 }
4122 assert(e->kind == DictComp_kind);
4123 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4124 e->v.DictComp.generators,
4125 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004126}
4127
4128
4129static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130compiler_visit_keyword(struct compiler *c, keyword_ty k)
4131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 VISIT(c, expr, k->value);
4133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134}
4135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137 whether they are true or false.
4138
4139 Return values: 1 for true, 0 for false, -1 for non-constant.
4140 */
4141
4142static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004143expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004145 if (is_const(e)) {
4146 return PyObject_IsTrue(get_const_value(c, e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004147 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004148 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149}
4150
Yury Selivanov75445082015-05-11 22:57:16 -04004151
4152/*
4153 Implements the async with statement.
4154
4155 The semantics outlined in that PEP are as follows:
4156
4157 async with EXPR as VAR:
4158 BLOCK
4159
4160 It is implemented roughly as:
4161
4162 context = EXPR
4163 exit = context.__aexit__ # not calling it
4164 value = await context.__aenter__()
4165 try:
4166 VAR = value # if VAR present in the syntax
4167 BLOCK
4168 finally:
4169 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004170 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004171 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004172 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004173 if not (await exit(*exc)):
4174 raise
4175 */
4176static int
4177compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4178{
4179 basicblock *block, *finally;
4180 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4181
4182 assert(s->kind == AsyncWith_kind);
4183
4184 block = compiler_new_block(c);
4185 finally = compiler_new_block(c);
4186 if (!block || !finally)
4187 return 0;
4188
4189 /* Evaluate EXPR */
4190 VISIT(c, expr, item->context_expr);
4191
4192 ADDOP(c, BEFORE_ASYNC_WITH);
4193 ADDOP(c, GET_AWAITABLE);
4194 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4195 ADDOP(c, YIELD_FROM);
4196
4197 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4198
4199 /* SETUP_ASYNC_WITH pushes a finally block. */
4200 compiler_use_next_block(c, block);
4201 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4202 return 0;
4203 }
4204
4205 if (item->optional_vars) {
4206 VISIT(c, expr, item->optional_vars);
4207 }
4208 else {
4209 /* Discard result from context.__aenter__() */
4210 ADDOP(c, POP_TOP);
4211 }
4212
4213 pos++;
4214 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4215 /* BLOCK code */
4216 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4217 else if (!compiler_async_with(c, s, pos))
4218 return 0;
4219
4220 /* End of try block; start the finally block */
4221 ADDOP(c, POP_BLOCK);
4222 compiler_pop_fblock(c, FINALLY_TRY, block);
4223
4224 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4225 compiler_use_next_block(c, finally);
4226 if (!compiler_push_fblock(c, FINALLY_END, finally))
4227 return 0;
4228
4229 /* Finally block starts; context.__exit__ is on the stack under
4230 the exception or return information. Just issue our magic
4231 opcode. */
4232 ADDOP(c, WITH_CLEANUP_START);
4233
4234 ADDOP(c, GET_AWAITABLE);
4235 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4236 ADDOP(c, YIELD_FROM);
4237
4238 ADDOP(c, WITH_CLEANUP_FINISH);
4239
4240 /* Finally block ends. */
4241 ADDOP(c, END_FINALLY);
4242 compiler_pop_fblock(c, FINALLY_END, finally);
4243 return 1;
4244}
4245
4246
Guido van Rossumc2e20742006-02-27 22:32:47 +00004247/*
4248 Implements the with statement from PEP 343.
4249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004251
4252 with EXPR as VAR:
4253 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254
Guido van Rossumc2e20742006-02-27 22:32:47 +00004255 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256
Thomas Wouters477c8d52006-05-27 19:21:47 +00004257 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004258 exit = context.__exit__ # not calling it
4259 value = context.__enter__()
4260 try:
4261 VAR = value # if VAR present in the syntax
4262 BLOCK
4263 finally:
4264 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004265 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004266 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004267 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004268 exit(*exc)
4269 */
4270static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004271compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004272{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004273 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004274 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004275
4276 assert(s->kind == With_kind);
4277
Guido van Rossumc2e20742006-02-27 22:32:47 +00004278 block = compiler_new_block(c);
4279 finally = compiler_new_block(c);
4280 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004281 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004282
Thomas Wouters477c8d52006-05-27 19:21:47 +00004283 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004284 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004285 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004286
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004287 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004288 compiler_use_next_block(c, block);
4289 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004290 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004291 }
4292
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004293 if (item->optional_vars) {
4294 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004295 }
4296 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004298 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004299 }
4300
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004301 pos++;
4302 if (pos == asdl_seq_LEN(s->v.With.items))
4303 /* BLOCK code */
4304 VISIT_SEQ(c, stmt, s->v.With.body)
4305 else if (!compiler_with(c, s, pos))
4306 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004307
4308 /* End of try block; start the finally block */
4309 ADDOP(c, POP_BLOCK);
4310 compiler_pop_fblock(c, FINALLY_TRY, block);
4311
4312 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4313 compiler_use_next_block(c, finally);
4314 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004315 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004316
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004317 /* Finally block starts; context.__exit__ is on the stack under
4318 the exception or return information. Just issue our magic
4319 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004320 ADDOP(c, WITH_CLEANUP_START);
4321 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004322
4323 /* Finally block ends. */
4324 ADDOP(c, END_FINALLY);
4325 compiler_pop_fblock(c, FINALLY_END, finally);
4326 return 1;
4327}
4328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004329static int
4330compiler_visit_expr(struct compiler *c, expr_ty e)
4331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 /* If expr e has a different line number than the last expr/stmt,
4333 set a new line number for the next instruction.
4334 */
4335 if (e->lineno > c->u->u_lineno) {
4336 c->u->u_lineno = e->lineno;
4337 c->u->u_lineno_set = 0;
4338 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004339 /* Updating the column offset is always harmless. */
4340 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 switch (e->kind) {
4342 case BoolOp_kind:
4343 return compiler_boolop(c, e);
4344 case BinOp_kind:
4345 VISIT(c, expr, e->v.BinOp.left);
4346 VISIT(c, expr, e->v.BinOp.right);
4347 ADDOP(c, binop(c, e->v.BinOp.op));
4348 break;
4349 case UnaryOp_kind:
4350 VISIT(c, expr, e->v.UnaryOp.operand);
4351 ADDOP(c, unaryop(e->v.UnaryOp.op));
4352 break;
4353 case Lambda_kind:
4354 return compiler_lambda(c, e);
4355 case IfExp_kind:
4356 return compiler_ifexp(c, e);
4357 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004358 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004360 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 case GeneratorExp_kind:
4362 return compiler_genexp(c, e);
4363 case ListComp_kind:
4364 return compiler_listcomp(c, e);
4365 case SetComp_kind:
4366 return compiler_setcomp(c, e);
4367 case DictComp_kind:
4368 return compiler_dictcomp(c, e);
4369 case Yield_kind:
4370 if (c->u->u_ste->ste_type != FunctionBlock)
4371 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004372 if (e->v.Yield.value) {
4373 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 }
4375 else {
4376 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4377 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004378 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004380 case YieldFrom_kind:
4381 if (c->u->u_ste->ste_type != FunctionBlock)
4382 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004383
4384 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4385 return compiler_error(c, "'yield from' inside async function");
4386
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004387 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004388 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004389 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4390 ADDOP(c, YIELD_FROM);
4391 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004392 case Await_kind:
4393 if (c->u->u_ste->ste_type != FunctionBlock)
4394 return compiler_error(c, "'await' outside function");
4395
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4397 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004398 return compiler_error(c, "'await' outside async function");
4399
4400 VISIT(c, expr, e->v.Await.value);
4401 ADDOP(c, GET_AWAITABLE);
4402 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4403 ADDOP(c, YIELD_FROM);
4404 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 case Compare_kind:
4406 return compiler_compare(c, e);
4407 case Call_kind:
4408 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004409 case Constant_kind:
4410 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4411 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 case Num_kind:
4413 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4414 break;
4415 case Str_kind:
4416 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4417 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004418 case JoinedStr_kind:
4419 return compiler_joined_str(c, e);
4420 case FormattedValue_kind:
4421 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 case Bytes_kind:
4423 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4424 break;
4425 case Ellipsis_kind:
4426 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4427 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004428 case NameConstant_kind:
4429 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4430 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 /* The following exprs can be assignment targets. */
4432 case Attribute_kind:
4433 if (e->v.Attribute.ctx != AugStore)
4434 VISIT(c, expr, e->v.Attribute.value);
4435 switch (e->v.Attribute.ctx) {
4436 case AugLoad:
4437 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004438 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 case Load:
4440 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4441 break;
4442 case AugStore:
4443 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004444 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 case Store:
4446 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4447 break;
4448 case Del:
4449 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4450 break;
4451 case Param:
4452 default:
4453 PyErr_SetString(PyExc_SystemError,
4454 "param invalid in attribute expression");
4455 return 0;
4456 }
4457 break;
4458 case Subscript_kind:
4459 switch (e->v.Subscript.ctx) {
4460 case AugLoad:
4461 VISIT(c, expr, e->v.Subscript.value);
4462 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4463 break;
4464 case Load:
4465 VISIT(c, expr, e->v.Subscript.value);
4466 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4467 break;
4468 case AugStore:
4469 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4470 break;
4471 case Store:
4472 VISIT(c, expr, e->v.Subscript.value);
4473 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4474 break;
4475 case Del:
4476 VISIT(c, expr, e->v.Subscript.value);
4477 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4478 break;
4479 case Param:
4480 default:
4481 PyErr_SetString(PyExc_SystemError,
4482 "param invalid in subscript expression");
4483 return 0;
4484 }
4485 break;
4486 case Starred_kind:
4487 switch (e->v.Starred.ctx) {
4488 case Store:
4489 /* In all legitimate cases, the Starred node was already replaced
4490 * by compiler_list/compiler_tuple. XXX: is that okay? */
4491 return compiler_error(c,
4492 "starred assignment target must be in a list or tuple");
4493 default:
4494 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004495 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 }
4497 break;
4498 case Name_kind:
4499 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4500 /* child nodes of List and Tuple will have expr_context set */
4501 case List_kind:
4502 return compiler_list(c, e);
4503 case Tuple_kind:
4504 return compiler_tuple(c, e);
4505 }
4506 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004507}
4508
4509static int
4510compiler_augassign(struct compiler *c, stmt_ty s)
4511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 expr_ty e = s->v.AugAssign.target;
4513 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 switch (e->kind) {
4518 case Attribute_kind:
4519 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4520 AugLoad, e->lineno, e->col_offset, c->c_arena);
4521 if (auge == NULL)
4522 return 0;
4523 VISIT(c, expr, auge);
4524 VISIT(c, expr, s->v.AugAssign.value);
4525 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4526 auge->v.Attribute.ctx = AugStore;
4527 VISIT(c, expr, auge);
4528 break;
4529 case Subscript_kind:
4530 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4531 AugLoad, e->lineno, e->col_offset, c->c_arena);
4532 if (auge == NULL)
4533 return 0;
4534 VISIT(c, expr, auge);
4535 VISIT(c, expr, s->v.AugAssign.value);
4536 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4537 auge->v.Subscript.ctx = AugStore;
4538 VISIT(c, expr, auge);
4539 break;
4540 case Name_kind:
4541 if (!compiler_nameop(c, e->v.Name.id, Load))
4542 return 0;
4543 VISIT(c, expr, s->v.AugAssign.value);
4544 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4545 return compiler_nameop(c, e->v.Name.id, Store);
4546 default:
4547 PyErr_Format(PyExc_SystemError,
4548 "invalid node type (%d) for augmented assignment",
4549 e->kind);
4550 return 0;
4551 }
4552 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553}
4554
4555static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004556check_ann_expr(struct compiler *c, expr_ty e)
4557{
4558 VISIT(c, expr, e);
4559 ADDOP(c, POP_TOP);
4560 return 1;
4561}
4562
4563static int
4564check_annotation(struct compiler *c, stmt_ty s)
4565{
4566 /* Annotations are only evaluated in a module or class. */
4567 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4568 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4569 return check_ann_expr(c, s->v.AnnAssign.annotation);
4570 }
4571 return 1;
4572}
4573
4574static int
4575check_ann_slice(struct compiler *c, slice_ty sl)
4576{
4577 switch(sl->kind) {
4578 case Index_kind:
4579 return check_ann_expr(c, sl->v.Index.value);
4580 case Slice_kind:
4581 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4582 return 0;
4583 }
4584 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4585 return 0;
4586 }
4587 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4588 return 0;
4589 }
4590 break;
4591 default:
4592 PyErr_SetString(PyExc_SystemError,
4593 "unexpected slice kind");
4594 return 0;
4595 }
4596 return 1;
4597}
4598
4599static int
4600check_ann_subscr(struct compiler *c, slice_ty sl)
4601{
4602 /* We check that everything in a subscript is defined at runtime. */
4603 Py_ssize_t i, n;
4604
4605 switch (sl->kind) {
4606 case Index_kind:
4607 case Slice_kind:
4608 if (!check_ann_slice(c, sl)) {
4609 return 0;
4610 }
4611 break;
4612 case ExtSlice_kind:
4613 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4614 for (i = 0; i < n; i++) {
4615 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4616 switch (subsl->kind) {
4617 case Index_kind:
4618 case Slice_kind:
4619 if (!check_ann_slice(c, subsl)) {
4620 return 0;
4621 }
4622 break;
4623 case ExtSlice_kind:
4624 default:
4625 PyErr_SetString(PyExc_SystemError,
4626 "extended slice invalid in nested slice");
4627 return 0;
4628 }
4629 }
4630 break;
4631 default:
4632 PyErr_Format(PyExc_SystemError,
4633 "invalid subscript kind %d", sl->kind);
4634 return 0;
4635 }
4636 return 1;
4637}
4638
4639static int
4640compiler_annassign(struct compiler *c, stmt_ty s)
4641{
4642 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004643 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004644
4645 assert(s->kind == AnnAssign_kind);
4646
4647 /* We perform the actual assignment first. */
4648 if (s->v.AnnAssign.value) {
4649 VISIT(c, expr, s->v.AnnAssign.value);
4650 VISIT(c, expr, targ);
4651 }
4652 switch (targ->kind) {
4653 case Name_kind:
4654 /* If we have a simple name in a module or class, store annotation. */
4655 if (s->v.AnnAssign.simple &&
4656 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4657 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004658 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4659 if (!mangled) {
4660 return 0;
4661 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004662 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004663 /* ADDOP_N decrefs its argument */
4664 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004665 }
4666 break;
4667 case Attribute_kind:
4668 if (!s->v.AnnAssign.value &&
4669 !check_ann_expr(c, targ->v.Attribute.value)) {
4670 return 0;
4671 }
4672 break;
4673 case Subscript_kind:
4674 if (!s->v.AnnAssign.value &&
4675 (!check_ann_expr(c, targ->v.Subscript.value) ||
4676 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4677 return 0;
4678 }
4679 break;
4680 default:
4681 PyErr_Format(PyExc_SystemError,
4682 "invalid node type (%d) for annotated assignment",
4683 targ->kind);
4684 return 0;
4685 }
4686 /* Annotation is evaluated last. */
4687 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4688 return 0;
4689 }
4690 return 1;
4691}
4692
4693static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004694compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 struct fblockinfo *f;
4697 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004698 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 "too many statically nested blocks");
4700 return 0;
4701 }
4702 f = &c->u->u_fblock[c->u->u_nfblocks++];
4703 f->fb_type = t;
4704 f->fb_block = b;
4705 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004706}
4707
4708static void
4709compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 struct compiler_unit *u = c->u;
4712 assert(u->u_nfblocks > 0);
4713 u->u_nfblocks--;
4714 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4715 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004716}
4717
Thomas Wouters89f507f2006-12-13 04:49:30 +00004718static int
4719compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 int i;
4721 struct compiler_unit *u = c->u;
4722 for (i = 0; i < u->u_nfblocks; ++i) {
4723 if (u->u_fblock[i].fb_type == LOOP)
4724 return 1;
4725 }
4726 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004727}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004728/* Raises a SyntaxError and returns 0.
4729 If something goes wrong, a different exception may be raised.
4730*/
4731
4732static int
4733compiler_error(struct compiler *c, const char *errstr)
4734{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004735 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004737
Victor Stinner14e461d2013-08-26 22:28:21 +02004738 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 if (!loc) {
4740 Py_INCREF(Py_None);
4741 loc = Py_None;
4742 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004743 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004744 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 if (!u)
4746 goto exit;
4747 v = Py_BuildValue("(zO)", errstr, u);
4748 if (!v)
4749 goto exit;
4750 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004751 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 Py_DECREF(loc);
4753 Py_XDECREF(u);
4754 Py_XDECREF(v);
4755 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004756}
4757
4758static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759compiler_handle_subscr(struct compiler *c, const char *kind,
4760 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 /* XXX this code is duplicated */
4765 switch (ctx) {
4766 case AugLoad: /* fall through to Load */
4767 case Load: op = BINARY_SUBSCR; break;
4768 case AugStore:/* fall through to Store */
4769 case Store: op = STORE_SUBSCR; break;
4770 case Del: op = DELETE_SUBSCR; break;
4771 case Param:
4772 PyErr_Format(PyExc_SystemError,
4773 "invalid %s kind %d in subscript\n",
4774 kind, ctx);
4775 return 0;
4776 }
4777 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004778 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 }
4780 else if (ctx == AugStore) {
4781 ADDOP(c, ROT_THREE);
4782 }
4783 ADDOP(c, op);
4784 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004785}
4786
4787static int
4788compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 int n = 2;
4791 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 /* only handles the cases where BUILD_SLICE is emitted */
4794 if (s->v.Slice.lower) {
4795 VISIT(c, expr, s->v.Slice.lower);
4796 }
4797 else {
4798 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4799 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 if (s->v.Slice.upper) {
4802 VISIT(c, expr, s->v.Slice.upper);
4803 }
4804 else {
4805 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4806 }
4807
4808 if (s->v.Slice.step) {
4809 n++;
4810 VISIT(c, expr, s->v.Slice.step);
4811 }
4812 ADDOP_I(c, BUILD_SLICE, n);
4813 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004814}
4815
4816static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4818 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 switch (s->kind) {
4821 case Slice_kind:
4822 return compiler_slice(c, s, ctx);
4823 case Index_kind:
4824 VISIT(c, expr, s->v.Index.value);
4825 break;
4826 case ExtSlice_kind:
4827 default:
4828 PyErr_SetString(PyExc_SystemError,
4829 "extended slice invalid in nested slice");
4830 return 0;
4831 }
4832 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004833}
4834
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004835static int
4836compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4837{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004838 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 switch (s->kind) {
4840 case Index_kind:
4841 kindname = "index";
4842 if (ctx != AugStore) {
4843 VISIT(c, expr, s->v.Index.value);
4844 }
4845 break;
4846 case Slice_kind:
4847 kindname = "slice";
4848 if (ctx != AugStore) {
4849 if (!compiler_slice(c, s, ctx))
4850 return 0;
4851 }
4852 break;
4853 case ExtSlice_kind:
4854 kindname = "extended slice";
4855 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004856 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 for (i = 0; i < n; i++) {
4858 slice_ty sub = (slice_ty)asdl_seq_GET(
4859 s->v.ExtSlice.dims, i);
4860 if (!compiler_visit_nested_slice(c, sub, ctx))
4861 return 0;
4862 }
4863 ADDOP_I(c, BUILD_TUPLE, n);
4864 }
4865 break;
4866 default:
4867 PyErr_Format(PyExc_SystemError,
4868 "invalid subscript kind %d", s->kind);
4869 return 0;
4870 }
4871 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004872}
4873
Thomas Wouters89f507f2006-12-13 04:49:30 +00004874/* End of the compiler section, beginning of the assembler section */
4875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004876/* do depth-first search of basic block graph, starting with block.
4877 post records the block indices in post-order.
4878
4879 XXX must handle implicit jumps from one block to next
4880*/
4881
Thomas Wouters89f507f2006-12-13 04:49:30 +00004882struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 PyObject *a_bytecode; /* string containing bytecode */
4884 int a_offset; /* offset into bytecode */
4885 int a_nblocks; /* number of reachable blocks */
4886 basicblock **a_postorder; /* list of blocks in dfs postorder */
4887 PyObject *a_lnotab; /* string containing lnotab */
4888 int a_lnotab_off; /* offset into lnotab */
4889 int a_lineno; /* last lineno of emitted instruction */
4890 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004891};
4892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004893static void
4894dfs(struct compiler *c, basicblock *b, struct assembler *a)
4895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 int i;
4897 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 if (b->b_seen)
4900 return;
4901 b->b_seen = 1;
4902 if (b->b_next != NULL)
4903 dfs(c, b->b_next, a);
4904 for (i = 0; i < b->b_iused; i++) {
4905 instr = &b->b_instr[i];
4906 if (instr->i_jrel || instr->i_jabs)
4907 dfs(c, instr->i_target, a);
4908 }
4909 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004910}
4911
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004912static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004913stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4914{
Larry Hastings3a907972013-11-23 14:49:22 -08004915 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 struct instr *instr;
4917 if (b->b_seen || b->b_startdepth >= depth)
4918 return maxdepth;
4919 b->b_seen = 1;
4920 b->b_startdepth = depth;
4921 for (i = 0; i < b->b_iused; i++) {
4922 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004923 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4924 if (effect == PY_INVALID_STACK_EFFECT) {
4925 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4926 Py_FatalError("PyCompile_OpcodeStackEffect()");
4927 }
4928 depth += effect;
4929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 if (depth > maxdepth)
4931 maxdepth = depth;
4932 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4933 if (instr->i_jrel || instr->i_jabs) {
4934 target_depth = depth;
4935 if (instr->i_opcode == FOR_ITER) {
4936 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004937 }
4938 else if (instr->i_opcode == SETUP_FINALLY ||
4939 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 target_depth = depth+3;
4941 if (target_depth > maxdepth)
4942 maxdepth = target_depth;
4943 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004944 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4945 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4946 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 maxdepth = stackdepth_walk(c, instr->i_target,
4948 target_depth, maxdepth);
4949 if (instr->i_opcode == JUMP_ABSOLUTE ||
4950 instr->i_opcode == JUMP_FORWARD) {
4951 goto out; /* remaining code is dead */
4952 }
4953 }
4954 }
4955 if (b->b_next)
4956 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004957out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 b->b_seen = 0;
4959 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004960}
4961
4962/* Find the flow path that needs the largest stack. We assume that
4963 * cycles in the flow graph have no net effect on the stack depth.
4964 */
4965static int
4966stackdepth(struct compiler *c)
4967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 basicblock *b, *entryblock;
4969 entryblock = NULL;
4970 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4971 b->b_seen = 0;
4972 b->b_startdepth = INT_MIN;
4973 entryblock = b;
4974 }
4975 if (!entryblock)
4976 return 0;
4977 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978}
4979
4980static int
4981assemble_init(struct assembler *a, int nblocks, int firstlineno)
4982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 memset(a, 0, sizeof(struct assembler));
4984 a->a_lineno = firstlineno;
4985 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4986 if (!a->a_bytecode)
4987 return 0;
4988 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4989 if (!a->a_lnotab)
4990 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004991 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 PyErr_NoMemory();
4993 return 0;
4994 }
4995 a->a_postorder = (basicblock **)PyObject_Malloc(
4996 sizeof(basicblock *) * nblocks);
4997 if (!a->a_postorder) {
4998 PyErr_NoMemory();
4999 return 0;
5000 }
5001 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005002}
5003
5004static void
5005assemble_free(struct assembler *a)
5006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 Py_XDECREF(a->a_bytecode);
5008 Py_XDECREF(a->a_lnotab);
5009 if (a->a_postorder)
5010 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005011}
5012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005013static int
5014blocksize(basicblock *b)
5015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 int i;
5017 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005020 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005022}
5023
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005024/* Appends a pair to the end of the line number table, a_lnotab, representing
5025 the instruction's bytecode offset and line number. See
5026 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005027
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005028static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005029assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005032 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005034
Serhiy Storchakaab874002016-09-11 13:48:15 +03005035 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 if(d_bytecode == 0 && d_lineno == 0)
5041 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 if (d_bytecode > 255) {
5044 int j, nbytes, ncodes = d_bytecode / 255;
5045 nbytes = a->a_lnotab_off + 2 * ncodes;
5046 len = PyBytes_GET_SIZE(a->a_lnotab);
5047 if (nbytes >= len) {
5048 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5049 len = nbytes;
5050 else if (len <= INT_MAX / 2)
5051 len *= 2;
5052 else {
5053 PyErr_NoMemory();
5054 return 0;
5055 }
5056 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5057 return 0;
5058 }
5059 lnotab = (unsigned char *)
5060 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5061 for (j = 0; j < ncodes; j++) {
5062 *lnotab++ = 255;
5063 *lnotab++ = 0;
5064 }
5065 d_bytecode -= ncodes * 255;
5066 a->a_lnotab_off += ncodes * 2;
5067 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005068 assert(0 <= d_bytecode && d_bytecode <= 255);
5069
5070 if (d_lineno < -128 || 127 < d_lineno) {
5071 int j, nbytes, ncodes, k;
5072 if (d_lineno < 0) {
5073 k = -128;
5074 /* use division on positive numbers */
5075 ncodes = (-d_lineno) / 128;
5076 }
5077 else {
5078 k = 127;
5079 ncodes = d_lineno / 127;
5080 }
5081 d_lineno -= ncodes * k;
5082 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 nbytes = a->a_lnotab_off + 2 * ncodes;
5084 len = PyBytes_GET_SIZE(a->a_lnotab);
5085 if (nbytes >= len) {
5086 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5087 len = nbytes;
5088 else if (len <= INT_MAX / 2)
5089 len *= 2;
5090 else {
5091 PyErr_NoMemory();
5092 return 0;
5093 }
5094 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5095 return 0;
5096 }
5097 lnotab = (unsigned char *)
5098 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5099 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005100 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 d_bytecode = 0;
5102 for (j = 1; j < ncodes; j++) {
5103 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005104 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 a->a_lnotab_off += ncodes * 2;
5107 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005108 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 len = PyBytes_GET_SIZE(a->a_lnotab);
5111 if (a->a_lnotab_off + 2 >= len) {
5112 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5113 return 0;
5114 }
5115 lnotab = (unsigned char *)
5116 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 a->a_lnotab_off += 2;
5119 if (d_bytecode) {
5120 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005121 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 }
5123 else { /* First line of a block; def stmt, etc. */
5124 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005125 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 }
5127 a->a_lineno = i->i_lineno;
5128 a->a_lineno_off = a->a_offset;
5129 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005130}
5131
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005132/* assemble_emit()
5133 Extend the bytecode with a new instruction.
5134 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005135*/
5136
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005137static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005138assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005139{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005140 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005142 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005143
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005144 arg = i->i_oparg;
5145 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 if (i->i_lineno && !assemble_lnotab(a, i))
5147 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005148 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 if (len > PY_SSIZE_T_MAX / 2)
5150 return 0;
5151 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5152 return 0;
5153 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005154 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005156 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005157 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005158}
5159
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005160static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005161assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005164 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 /* Compute the size of each block and fixup jump args.
5168 Replace block pointer with position in bytecode. */
5169 do {
5170 totsize = 0;
5171 for (i = a->a_nblocks - 1; i >= 0; i--) {
5172 b = a->a_postorder[i];
5173 bsize = blocksize(b);
5174 b->b_offset = totsize;
5175 totsize += bsize;
5176 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005177 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5179 bsize = b->b_offset;
5180 for (i = 0; i < b->b_iused; i++) {
5181 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005182 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 /* Relative jumps are computed relative to
5184 the instruction pointer after fetching
5185 the jump instruction.
5186 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005187 bsize += isize;
5188 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005190 if (instr->i_jrel) {
5191 instr->i_oparg -= bsize;
5192 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005193 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005194 if (instrsize(instr->i_oparg) != isize) {
5195 extended_arg_recompile = 1;
5196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 }
5199 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 /* XXX: This is an awful hack that could hurt performance, but
5202 on the bright side it should work until we come up
5203 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 The issue is that in the first loop blocksize() is called
5206 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005207 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 So we loop until we stop seeing new EXTENDED_ARGs.
5211 The only EXTENDED_ARGs that could be popping up are
5212 ones in jump instructions. So this should converge
5213 fairly quickly.
5214 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005215 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005216}
5217
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005218static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005219dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005222 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 tuple = PyTuple_New(size);
5225 if (tuple == NULL)
5226 return NULL;
5227 while (PyDict_Next(dict, &pos, &k, &v)) {
5228 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005229 /* The keys of the dictionary are tuples. (see compiler_add_o
5230 * and _PyCode_ConstantKey). The object we want is always second,
5231 * though. */
5232 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 Py_INCREF(k);
5234 assert((i - offset) < size);
5235 assert((i - offset) >= 0);
5236 PyTuple_SET_ITEM(tuple, i - offset, k);
5237 }
5238 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005239}
5240
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005241static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005242compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005245 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005247 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 if (ste->ste_nested)
5249 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005250 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005252 if (!ste->ste_generator && ste->ste_coroutine)
5253 flags |= CO_COROUTINE;
5254 if (ste->ste_generator && ste->ste_coroutine)
5255 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 if (ste->ste_varargs)
5257 flags |= CO_VARARGS;
5258 if (ste->ste_varkeywords)
5259 flags |= CO_VARKEYWORDS;
5260 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 /* (Only) inherit compilerflags in PyCF_MASK */
5263 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005266}
5267
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005268static PyCodeObject *
5269makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 PyObject *tmp;
5272 PyCodeObject *co = NULL;
5273 PyObject *consts = NULL;
5274 PyObject *names = NULL;
5275 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 PyObject *name = NULL;
5277 PyObject *freevars = NULL;
5278 PyObject *cellvars = NULL;
5279 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005280 Py_ssize_t nlocals;
5281 int nlocals_int;
5282 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005283 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 tmp = dict_keys_inorder(c->u->u_consts, 0);
5286 if (!tmp)
5287 goto error;
5288 consts = PySequence_List(tmp); /* optimize_code requires a list */
5289 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 names = dict_keys_inorder(c->u->u_names, 0);
5292 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5293 if (!consts || !names || !varnames)
5294 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5297 if (!cellvars)
5298 goto error;
5299 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5300 if (!freevars)
5301 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005302
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005303 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005304 assert(nlocals < INT_MAX);
5305 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 flags = compute_code_flags(c);
5308 if (flags < 0)
5309 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5312 if (!bytecode)
5313 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5316 if (!tmp)
5317 goto error;
5318 Py_DECREF(consts);
5319 consts = tmp;
5320
Victor Stinnerf8e32212013-11-19 23:56:34 +01005321 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5322 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5323 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005324 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 bytecode, consts, names, varnames,
5326 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005327 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 c->u->u_firstlineno,
5329 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005330 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 Py_XDECREF(consts);
5332 Py_XDECREF(names);
5333 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 Py_XDECREF(name);
5335 Py_XDECREF(freevars);
5336 Py_XDECREF(cellvars);
5337 Py_XDECREF(bytecode);
5338 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005339}
5340
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005341
5342/* For debugging purposes only */
5343#if 0
5344static void
5345dump_instr(const struct instr *i)
5346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 const char *jrel = i->i_jrel ? "jrel " : "";
5348 const char *jabs = i->i_jabs ? "jabs " : "";
5349 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005352 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5356 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005357}
5358
5359static void
5360dump_basicblock(const basicblock *b)
5361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 const char *seen = b->b_seen ? "seen " : "";
5363 const char *b_return = b->b_return ? "return " : "";
5364 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5365 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5366 if (b->b_instr) {
5367 int i;
5368 for (i = 0; i < b->b_iused; i++) {
5369 fprintf(stderr, " [%02d] ", i);
5370 dump_instr(b->b_instr + i);
5371 }
5372 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005373}
5374#endif
5375
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005376static PyCodeObject *
5377assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 basicblock *b, *entryblock;
5380 struct assembler a;
5381 int i, j, nblocks;
5382 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 /* Make sure every block that falls off the end returns None.
5385 XXX NEXT_BLOCK() isn't quite right, because if the last
5386 block ends with a jump or return b_next shouldn't set.
5387 */
5388 if (!c->u->u_curblock->b_return) {
5389 NEXT_BLOCK(c);
5390 if (addNone)
5391 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5392 ADDOP(c, RETURN_VALUE);
5393 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 nblocks = 0;
5396 entryblock = NULL;
5397 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5398 nblocks++;
5399 entryblock = b;
5400 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 /* Set firstlineno if it wasn't explicitly set. */
5403 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005404 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5406 else
5407 c->u->u_firstlineno = 1;
5408 }
5409 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5410 goto error;
5411 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 /* Can't modify the bytecode after computing jump offsets. */
5414 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 /* Emit code in reverse postorder from dfs. */
5417 for (i = a.a_nblocks - 1; i >= 0; i--) {
5418 b = a.a_postorder[i];
5419 for (j = 0; j < b->b_iused; j++)
5420 if (!assemble_emit(&a, &b->b_instr[j]))
5421 goto error;
5422 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5425 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005426 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 assemble_free(&a);
5432 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005433}
Georg Brandl8334fd92010-12-04 10:26:46 +00005434
5435#undef PyAST_Compile
5436PyAPI_FUNC(PyCodeObject *)
5437PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5438 PyArena *arena)
5439{
5440 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5441}