blob: 78e797a2c331f36c7dff4b4cb2de8e3d0747c98c [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
Victor Stinner14e461d2013-08-26 22:28:21 +0200334 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (c.c_st == NULL) {
336 if (!PyErr_Occurred())
337 PyErr_SetString(PyExc_SystemError, "no symtable");
338 goto finally;
339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Thomas Wouters1175c432006-02-27 22:49:54 +0000343 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 compiler_free(&c);
345 assert(co || PyErr_Occurred());
346 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347}
348
349PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200350PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
351 int optimize, PyArena *arena)
352{
353 PyObject *filename;
354 PyCodeObject *co;
355 filename = PyUnicode_DecodeFSDefault(filename_str);
356 if (filename == NULL)
357 return NULL;
358 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
359 Py_DECREF(filename);
360 return co;
361
362}
363
364PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365PyNode_Compile(struct _node *n, const char *filename)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyCodeObject *co = NULL;
368 mod_ty mod;
369 PyArena *arena = PyArena_New();
370 if (!arena)
371 return NULL;
372 mod = PyAST_FromNode(n, NULL, filename, arena);
373 if (mod)
374 co = PyAST_Compile(mod, filename, NULL, arena);
375 PyArena_Free(arena);
376 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000377}
378
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (c->c_st)
383 PySymtable_Free(c->c_st);
384 if (c->c_future)
385 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200386 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000388}
389
Guido van Rossum79f25d91997-04-29 20:08:16 +0000390static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000391list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ssize_t i, n;
394 PyObject *v, *k;
395 PyObject *dict = PyDict_New();
396 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 n = PyList_Size(list);
399 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100400 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (!v) {
402 Py_DECREF(dict);
403 return NULL;
404 }
405 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100406 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
408 Py_XDECREF(k);
409 Py_DECREF(v);
410 Py_DECREF(dict);
411 return NULL;
412 }
413 Py_DECREF(k);
414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100462 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100469 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_DECREF(item);
473 Py_DECREF(dest);
474 Py_XDECREF(tuple);
475 return NULL;
476 }
477 Py_DECREF(item);
478 Py_DECREF(tuple);
479 }
480 }
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000483}
484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485static void
486compiler_unit_check(struct compiler_unit *u)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 basicblock *block;
489 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700490 assert((uintptr_t)block != 0xcbcbcbcbU);
491 assert((uintptr_t)block != 0xfbfbfbfbU);
492 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (block->b_instr != NULL) {
494 assert(block->b_ialloc > 0);
495 assert(block->b_iused > 0);
496 assert(block->b_ialloc >= block->b_iused);
497 }
498 else {
499 assert (block->b_iused == 0);
500 assert (block->b_ialloc == 0);
501 }
502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503}
504
505static void
506compiler_unit_free(struct compiler_unit *u)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 compiler_unit_check(u);
511 b = u->u_blocks;
512 while (b != NULL) {
513 if (b->b_instr)
514 PyObject_Free((void *)b->b_instr);
515 next = b->b_list;
516 PyObject_Free((void *)b);
517 b = next;
518 }
519 Py_CLEAR(u->u_ste);
520 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400521 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 Py_CLEAR(u->u_consts);
523 Py_CLEAR(u->u_names);
524 Py_CLEAR(u->u_varnames);
525 Py_CLEAR(u->u_freevars);
526 Py_CLEAR(u->u_cellvars);
527 Py_CLEAR(u->u_private);
528 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529}
530
531static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100532compiler_enter_scope(struct compiler *c, identifier name,
533 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100536 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
539 struct compiler_unit));
540 if (!u) {
541 PyErr_NoMemory();
542 return 0;
543 }
544 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100545 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u->u_argcount = 0;
547 u->u_kwonlyargcount = 0;
548 u->u_ste = PySymtable_Lookup(c->c_st, key);
549 if (!u->u_ste) {
550 compiler_unit_free(u);
551 return 0;
552 }
553 Py_INCREF(name);
554 u->u_name = name;
555 u->u_varnames = list2dict(u->u_ste->ste_varnames);
556 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
557 if (!u->u_varnames || !u->u_cellvars) {
558 compiler_unit_free(u);
559 return 0;
560 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500561 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000562 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300564 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 int res;
566 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200567 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 name = _PyUnicode_FromId(&PyId___class__);
569 if (!name) {
570 compiler_unit_free(u);
571 return 0;
572 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100573 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500574 if (!tuple) {
575 compiler_unit_free(u);
576 return 0;
577 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300578 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500579 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (res < 0) {
581 compiler_unit_free(u);
582 return 0;
583 }
584 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200587 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (!u->u_freevars) {
589 compiler_unit_free(u);
590 return 0;
591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_blocks = NULL;
594 u->u_nfblocks = 0;
595 u->u_firstlineno = lineno;
596 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000597 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 u->u_lineno_set = 0;
599 u->u_consts = PyDict_New();
600 if (!u->u_consts) {
601 compiler_unit_free(u);
602 return 0;
603 }
604 u->u_names = PyDict_New();
605 if (!u->u_names) {
606 compiler_unit_free(u);
607 return 0;
608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Push the old compiler_unit on the stack. */
613 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400614 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
616 Py_XDECREF(capsule);
617 compiler_unit_free(u);
618 return 0;
619 }
620 Py_DECREF(capsule);
621 u->u_private = c->u->u_private;
622 Py_XINCREF(u->u_private);
623 }
624 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627
628 block = compiler_new_block(c);
629 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400633 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
634 if (!compiler_set_qualname(c))
635 return 0;
636 }
637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639}
640
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000641static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642compiler_exit_scope(struct compiler *c)
643{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100644 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 c->c_nestlevel--;
648 compiler_unit_free(c->u);
649 /* Restore c->u to the parent unit. */
650 n = PyList_GET_SIZE(c->c_stack) - 1;
651 if (n >= 0) {
652 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400653 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(c->u);
655 /* we are deleting from a list so this really shouldn't fail */
656 if (PySequence_DelItem(c->c_stack, n) < 0)
657 Py_FatalError("compiler_exit_scope()");
658 compiler_unit_check(c->u);
659 }
660 else
661 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663}
664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665static int
666compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 _Py_static_string(dot_locals, ".<locals>");
670 Py_ssize_t stack_size;
671 struct compiler_unit *u = c->u;
672 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400676 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 if (stack_size > 1) {
678 int scope, force_global = 0;
679 struct compiler_unit *parent;
680 PyObject *mangled, *capsule;
681
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400682 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400683 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 assert(parent);
685
Yury Selivanov75445082015-05-11 22:57:16 -0400686 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
687 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 assert(u->u_name);
690 mangled = _Py_Mangle(parent->u_private, u->u_name);
691 if (!mangled)
692 return 0;
693 scope = PyST_GetScope(parent->u_ste, mangled);
694 Py_DECREF(mangled);
695 assert(scope != GLOBAL_IMPLICIT);
696 if (scope == GLOBAL_EXPLICIT)
697 force_global = 1;
698 }
699
700 if (!force_global) {
701 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400702 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
704 dot_locals_str = _PyUnicode_FromId(&dot_locals);
705 if (dot_locals_str == NULL)
706 return 0;
707 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
708 if (base == NULL)
709 return 0;
710 }
711 else {
712 Py_INCREF(parent->u_qualname);
713 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400714 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100715 }
716 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400717
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400718 if (base != NULL) {
719 dot_str = _PyUnicode_FromId(&dot);
720 if (dot_str == NULL) {
721 Py_DECREF(base);
722 return 0;
723 }
724 name = PyUnicode_Concat(base, dot_str);
725 Py_DECREF(base);
726 if (name == NULL)
727 return 0;
728 PyUnicode_Append(&name, u->u_name);
729 if (name == NULL)
730 return 0;
731 }
732 else {
733 Py_INCREF(u->u_name);
734 name = u->u_name;
735 }
736 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100737
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400738 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739}
740
Eric V. Smith235a6f02015-09-19 14:51:32 -0400741
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742/* Allocate a new block and return a pointer to it.
743 Returns NULL on error.
744*/
745
746static basicblock *
747compiler_new_block(struct compiler *c)
748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 basicblock *b;
750 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 u = c->u;
753 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
754 if (b == NULL) {
755 PyErr_NoMemory();
756 return NULL;
757 }
758 memset((void *)b, 0, sizeof(basicblock));
759 /* Extend the singly linked list of blocks with new block. */
760 b->b_list = u->u_blocks;
761 u->u_blocks = b;
762 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
791compiler_next_instr(struct compiler *c, basicblock *b)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
795 b->b_instr = (struct instr *)PyObject_Malloc(
796 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
802 memset((char *)b->b_instr, 0,
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 }
805 else if (b->b_iused == b->b_ialloc) {
806 struct instr *tmp;
807 size_t oldsize, newsize;
808 oldsize = b->b_ialloc * sizeof(struct instr);
809 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000810
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700811 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyErr_NoMemory();
813 return -1;
814 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (newsize == 0) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc <<= 1;
821 tmp = (struct instr *)PyObject_Realloc(
822 (void *)b->b_instr, newsize);
823 if (tmp == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_instr = tmp;
828 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
829 }
830 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831}
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833/* Set the i_lineno member of the instruction at offset off if the
834 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 already been set. If it has been set, the call has no effect.
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837 The line number is reset in the following cases:
838 - when entering a new scope
839 - on each statement
840 - on each expression that start a new line
841 - before the "except" clause
842 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845static void
846compiler_set_lineno(struct compiler *c, int off)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 basicblock *b;
849 if (c->u->u_lineno_set)
850 return;
851 c->u->u_lineno_set = 1;
852 b = c->u->u_curblock;
853 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854}
855
Larry Hastings3a907972013-11-23 14:49:22 -0800856int
857PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
860 case POP_TOP:
861 return -1;
862 case ROT_TWO:
863 case ROT_THREE:
864 return 0;
865 case DUP_TOP:
866 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000867 case DUP_TOP_TWO:
868 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case UNARY_POSITIVE:
871 case UNARY_NEGATIVE:
872 case UNARY_NOT:
873 case UNARY_INVERT:
874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case SET_ADD:
877 case LIST_APPEND:
878 return -1;
879 case MAP_ADD:
880 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_POWER:
883 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400884 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_MODULO:
886 case BINARY_ADD:
887 case BINARY_SUBTRACT:
888 case BINARY_SUBSCR:
889 case BINARY_FLOOR_DIVIDE:
890 case BINARY_TRUE_DIVIDE:
891 return -1;
892 case INPLACE_FLOOR_DIVIDE:
893 case INPLACE_TRUE_DIVIDE:
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_ADD:
897 case INPLACE_SUBTRACT:
898 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400899 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_MODULO:
901 return -1;
902 case STORE_SUBSCR:
903 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400932 case WITH_CLEANUP_START:
933 return 1;
934 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case RETURN_VALUE:
937 return -1;
938 case IMPORT_STAR:
939 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700940 case SETUP_ANNOTATIONS:
941 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case YIELD_VALUE:
943 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500944 case YIELD_FROM:
945 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case POP_BLOCK:
947 return 0;
948 case POP_EXCEPT:
949 return 0; /* -3 except if bad bytecode */
950 case END_FINALLY:
951 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case STORE_NAME:
954 return -1;
955 case DELETE_NAME:
956 return 0;
957 case UNPACK_SEQUENCE:
958 return oparg-1;
959 case UNPACK_EX:
960 return (oparg&0xFF) + (oparg>>8);
961 case FOR_ITER:
962 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case STORE_ATTR:
965 return -2;
966 case DELETE_ATTR:
967 return -1;
968 case STORE_GLOBAL:
969 return -1;
970 case DELETE_GLOBAL:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case LOAD_CONST:
973 return 1;
974 case LOAD_NAME:
975 return 1;
976 case BUILD_TUPLE:
977 case BUILD_LIST:
978 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300979 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400981 case BUILD_LIST_UNPACK:
982 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300983 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400984 case BUILD_SET_UNPACK:
985 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400986 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700987 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700989 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300990 case BUILD_CONST_KEY_MAP:
991 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case LOAD_ATTR:
993 return 0;
994 case COMPARE_OP:
995 return -1;
996 case IMPORT_NAME:
997 return -1;
998 case IMPORT_FROM:
999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case JUMP_FORWARD:
1002 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1003 case JUMP_IF_FALSE_OR_POP: /* "" */
1004 case JUMP_ABSOLUTE:
1005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case POP_JUMP_IF_FALSE:
1008 case POP_JUMP_IF_TRUE:
1009 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case LOAD_GLOBAL:
1012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case CONTINUE_LOOP:
1015 return 0;
1016 case SETUP_LOOP:
1017 return 0;
1018 case SETUP_EXCEPT:
1019 case SETUP_FINALLY:
1020 return 6; /* can push 3 values for the new exception
1021 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case LOAD_FAST:
1024 return 1;
1025 case STORE_FAST:
1026 return -1;
1027 case DELETE_FAST:
1028 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001029 case STORE_ANNOTATION:
1030 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case RAISE_VARARGS:
1033 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001035 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001036 case CALL_METHOD:
1037 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001039 return -oparg-1;
1040 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001041 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001042 case MAKE_FUNCTION:
1043 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1044 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case BUILD_SLICE:
1046 if (oparg == 3)
1047 return -2;
1048 else
1049 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 case LOAD_CLOSURE:
1052 return 1;
1053 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001054 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return 1;
1056 case STORE_DEREF:
1057 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001058 case DELETE_DEREF:
1059 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001060 case GET_AWAITABLE:
1061 return 0;
1062 case SETUP_ASYNC_WITH:
1063 return 6;
1064 case BEFORE_ASYNC_WITH:
1065 return 1;
1066 case GET_AITER:
1067 return 0;
1068 case GET_ANEXT:
1069 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001070 case GET_YIELD_FROM_ITER:
1071 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001072 case FORMAT_VALUE:
1073 /* If there's a fmt_spec on the stack, we go from 2->1,
1074 else 1->1. */
1075 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001076 case LOAD_METHOD:
1077 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001079 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
Larry Hastings3a907972013-11-23 14:49:22 -08001081 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082}
1083
1084/* Add an opcode with no argument.
1085 Returns 0 on failure, 1 on success.
1086*/
1087
1088static int
1089compiler_addop(struct compiler *c, int opcode)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 basicblock *b;
1092 struct instr *i;
1093 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001094 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 off = compiler_next_instr(c, c->u->u_curblock);
1096 if (off < 0)
1097 return 0;
1098 b = c->u->u_curblock;
1099 i = &b->b_instr[off];
1100 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001101 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (opcode == RETURN_VALUE)
1103 b->b_return = 1;
1104 compiler_set_lineno(c, off);
1105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106}
1107
Victor Stinnerf8e32212013-11-19 23:56:34 +01001108static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *t, *v;
1112 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113
Victor Stinnerefb24132016-01-22 12:33:12 +01001114 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (t == NULL)
1116 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 v = PyDict_GetItem(dict, t);
1119 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001120 if (PyErr_Occurred()) {
1121 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001123 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001124 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001125 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!v) {
1127 Py_DECREF(t);
1128 return -1;
1129 }
1130 if (PyDict_SetItem(dict, t, v) < 0) {
1131 Py_DECREF(t);
1132 Py_DECREF(v);
1133 return -1;
1134 }
1135 Py_DECREF(v);
1136 }
1137 else
1138 arg = PyLong_AsLong(v);
1139 Py_DECREF(t);
1140 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141}
1142
1143static int
1144compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001147 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001149 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 return compiler_addop_i(c, opcode, arg);
1151}
1152
1153static int
1154compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001157 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1159 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 arg = compiler_add_o(c, dict, mangled);
1162 Py_DECREF(mangled);
1163 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return compiler_addop_i(c, opcode, arg);
1166}
1167
1168/* Add an opcode with an integer argument.
1169 Returns 0 on failure, 1 on success.
1170*/
1171
1172static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001173compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 struct instr *i;
1176 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Victor Stinner2ad474b2016-03-01 23:34:47 +01001178 /* oparg value is unsigned, but a signed C int is usually used to store
1179 it in the C code (like Python/ceval.c).
1180
1181 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1182
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 The argument of a concrete bytecode instruction is limited to 8-bit.
1184 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1185 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001186 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 off = compiler_next_instr(c, c->u->u_curblock);
1189 if (off < 0)
1190 return 0;
1191 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001192 i->i_opcode = opcode;
1193 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 compiler_set_lineno(c, off);
1195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
1199compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct instr *i;
1202 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001204 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 assert(b != NULL);
1206 off = compiler_next_instr(c, c->u->u_curblock);
1207 if (off < 0)
1208 return 0;
1209 i = &c->u->u_curblock->b_instr[off];
1210 i->i_opcode = opcode;
1211 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (absolute)
1213 i->i_jabs = 1;
1214 else
1215 i->i_jrel = 1;
1216 compiler_set_lineno(c, off);
1217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001220/* NEXT_BLOCK() creates an implicit jump from the current block
1221 to the new block.
1222
1223 The returns inside this macro make it impossible to decref objects
1224 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (compiler_next_block((C)) == NULL) \
1228 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229}
1230
1231#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop((C), (OP))) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001236#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!compiler_addop((C), (OP))) { \
1238 compiler_exit_scope(c); \
1239 return 0; \
1240 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001241}
1242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1245 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001248/* Same as ADDOP_O, but steals a reference. */
1249#define ADDOP_N(C, OP, O, TYPE) { \
1250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1251 Py_DECREF((O)); \
1252 return 0; \
1253 } \
1254 Py_DECREF((O)); \
1255}
1256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1259 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!compiler_addop_i((C), (OP), (O))) \
1264 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (!compiler_addop_j((C), (OP), (O), 1)) \
1269 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270}
1271
1272#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_addop_j((C), (OP), (O), 0)) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
1277/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1278 the ASDL name to synthesize the name of the C type and the visit function.
1279*/
1280
1281#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_visit_ ## TYPE((C), (V))) \
1283 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001286#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!compiler_visit_ ## TYPE((C), (V))) { \
1288 compiler_exit_scope(c); \
1289 return 0; \
1290 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001291}
1292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_visit_slice((C), (V), (CTX))) \
1295 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
1298#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 int _i; \
1300 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1301 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1302 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1303 if (!compiler_visit_ ## TYPE((C), elt)) \
1304 return 0; \
1305 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001308#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 int _i; \
1310 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1311 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1312 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1313 if (!compiler_visit_ ## TYPE((C), elt)) { \
1314 compiler_exit_scope(c); \
1315 return 0; \
1316 } \
1317 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001318}
1319
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001321is_const(expr_ty e)
1322{
1323 switch (e->kind) {
1324 case Constant_kind:
1325 case Num_kind:
1326 case Str_kind:
1327 case Bytes_kind:
1328 case Ellipsis_kind:
1329 case NameConstant_kind:
1330 return 1;
1331 default:
1332 return 0;
1333 }
1334}
1335
1336static PyObject *
1337get_const_value(expr_ty e)
1338{
1339 switch (e->kind) {
1340 case Constant_kind:
1341 return e->v.Constant.value;
1342 case Num_kind:
1343 return e->v.Num.n;
1344 case Str_kind:
1345 return e->v.Str.s;
1346 case Bytes_kind:
1347 return e->v.Bytes.s;
1348 case Ellipsis_kind:
1349 return Py_Ellipsis;
1350 case NameConstant_kind:
1351 return e->v.NameConstant.value;
1352 default:
1353 assert(!is_const(e));
1354 return NULL;
1355 }
1356}
1357
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001358/* Search if variable annotations are present statically in a block. */
1359
1360static int
1361find_ann(asdl_seq *stmts)
1362{
1363 int i, j, res = 0;
1364 stmt_ty st;
1365
1366 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1367 st = (stmt_ty)asdl_seq_GET(stmts, i);
1368 switch (st->kind) {
1369 case AnnAssign_kind:
1370 return 1;
1371 case For_kind:
1372 res = find_ann(st->v.For.body) ||
1373 find_ann(st->v.For.orelse);
1374 break;
1375 case AsyncFor_kind:
1376 res = find_ann(st->v.AsyncFor.body) ||
1377 find_ann(st->v.AsyncFor.orelse);
1378 break;
1379 case While_kind:
1380 res = find_ann(st->v.While.body) ||
1381 find_ann(st->v.While.orelse);
1382 break;
1383 case If_kind:
1384 res = find_ann(st->v.If.body) ||
1385 find_ann(st->v.If.orelse);
1386 break;
1387 case With_kind:
1388 res = find_ann(st->v.With.body);
1389 break;
1390 case AsyncWith_kind:
1391 res = find_ann(st->v.AsyncWith.body);
1392 break;
1393 case Try_kind:
1394 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1395 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1396 st->v.Try.handlers, j);
1397 if (find_ann(handler->v.ExceptHandler.body)) {
1398 return 1;
1399 }
1400 }
1401 res = find_ann(st->v.Try.body) ||
1402 find_ann(st->v.Try.finalbody) ||
1403 find_ann(st->v.Try.orelse);
1404 break;
1405 default:
1406 res = 0;
1407 }
1408 if (res) {
1409 break;
1410 }
1411 }
1412 return res;
1413}
1414
1415/* Compile a sequence of statements, checking for a docstring
1416 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
1418static int
INADA Naokicb41b272017-02-23 00:31:59 +09001419compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001421 /* Set current line number to the line number of first statement.
1422 This way line number for SETUP_ANNOTATIONS will always
1423 coincide with the line number of first "real" statement in module.
1424 If body is empy, then lineno will be set later in assemble. */
1425 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1426 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001427 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001428 c->u->u_lineno = st->lineno;
1429 }
1430 /* Every annotated class and module should have __annotations__. */
1431 if (find_ann(stmts)) {
1432 ADDOP(c, SETUP_ANNOTATIONS);
1433 }
INADA Naokicb41b272017-02-23 00:31:59 +09001434 /* if not -OO mode, set docstring */
1435 if (c->c_optimize < 2 && docstring) {
1436 ADDOP_O(c, LOAD_CONST, docstring, consts);
1437 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
INADA Naokicb41b272017-02-23 00:31:59 +09001439 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441}
1442
1443static PyCodeObject *
1444compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyCodeObject *co;
1447 int addNone = 1;
1448 static PyObject *module;
1449 if (!module) {
1450 module = PyUnicode_InternFromString("<module>");
1451 if (!module)
1452 return NULL;
1453 }
1454 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001455 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return NULL;
1457 switch (mod->kind) {
1458 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001459 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 compiler_exit_scope(c);
1461 return 0;
1462 }
1463 break;
1464 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001465 if (find_ann(mod->v.Interactive.body)) {
1466 ADDOP(c, SETUP_ANNOTATIONS);
1467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 c->c_interactive = 1;
1469 VISIT_SEQ_IN_SCOPE(c, stmt,
1470 mod->v.Interactive.body);
1471 break;
1472 case Expression_kind:
1473 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1474 addNone = 0;
1475 break;
1476 case Suite_kind:
1477 PyErr_SetString(PyExc_SystemError,
1478 "suite should not be possible");
1479 return 0;
1480 default:
1481 PyErr_Format(PyExc_SystemError,
1482 "module kind %d should not be possible",
1483 mod->kind);
1484 return 0;
1485 }
1486 co = assemble(c, addNone);
1487 compiler_exit_scope(c);
1488 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001489}
1490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491/* The test for LOCAL must come before the test for FREE in order to
1492 handle classes where name is both local and free. The local var is
1493 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001494*/
1495
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496static int
1497get_ref_type(struct compiler *c, PyObject *name)
1498{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001499 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001500 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001501 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001502 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001503 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (scope == 0) {
1505 char buf[350];
1506 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001507 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001509 PyUnicode_AsUTF8(name),
1510 PyUnicode_AsUTF8(c->u->u_name),
1511 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1512 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1513 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1514 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 );
1516 Py_FatalError(buf);
1517 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
1522static int
1523compiler_lookup_arg(PyObject *dict, PyObject *name)
1524{
1525 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001526 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001528 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001530 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001532 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001533 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001537compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001539 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001540 if (qualname == NULL)
1541 qualname = co->co_name;
1542
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001543 if (free) {
1544 for (i = 0; i < free; ++i) {
1545 /* Bypass com_addop_varname because it will generate
1546 LOAD_DEREF but LOAD_CLOSURE is needed.
1547 */
1548 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1549 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001551 /* Special case: If a class contains a method with a
1552 free variable that has the same name as a method,
1553 the name will be considered free *and* local in the
1554 class. It should be handled by the closure, as
1555 well as by the normal name loookup logic.
1556 */
1557 reftype = get_ref_type(c, name);
1558 if (reftype == CELL)
1559 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1560 else /* (reftype == FREE) */
1561 arg = compiler_lookup_arg(c->u->u_freevars, name);
1562 if (arg == -1) {
1563 fprintf(stderr,
1564 "lookup %s in %s %d %d\n"
1565 "freevars of %s: %s\n",
1566 PyUnicode_AsUTF8(PyObject_Repr(name)),
1567 PyUnicode_AsUTF8(c->u->u_name),
1568 reftype, arg,
1569 PyUnicode_AsUTF8(co->co_name),
1570 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1571 Py_FatalError("compiler_make_closure()");
1572 }
1573 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001575 flags |= 0x08;
1576 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001579 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001580 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582}
1583
1584static int
1585compiler_decorators(struct compiler *c, asdl_seq* decos)
1586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (!decos)
1590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1593 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1594 }
1595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596}
1597
1598static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001599compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001601{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001602 /* Push a dict of keyword-only default values.
1603
1604 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1605 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001606 int i;
1607 PyObject *keys = NULL;
1608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1610 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1611 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1612 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001613 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001614 if (!mangled) {
1615 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001617 if (keys == NULL) {
1618 keys = PyList_New(1);
1619 if (keys == NULL) {
1620 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001621 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001622 }
1623 PyList_SET_ITEM(keys, 0, mangled);
1624 }
1625 else {
1626 int res = PyList_Append(keys, mangled);
1627 Py_DECREF(mangled);
1628 if (res == -1) {
1629 goto error;
1630 }
1631 }
1632 if (!compiler_visit_expr(c, default_)) {
1633 goto error;
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 }
1636 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001637 if (keys != NULL) {
1638 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1639 PyObject *keys_tuple = PyList_AsTuple(keys);
1640 Py_DECREF(keys);
1641 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001642 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001643 }
1644 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1645 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001646 assert(default_count > 0);
1647 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001648 }
1649 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001650 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001651 }
1652
1653error:
1654 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001655 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001656}
1657
1658static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001659compiler_visit_argannotation(struct compiler *c, identifier id,
1660 expr_ty annotation, PyObject *names)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001663 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001665 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001666 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001667 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001668 if (PyList_Append(names, mangled) < 0) {
1669 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001670 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001671 }
1672 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001674 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001675}
1676
1677static int
1678compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1679 PyObject *names)
1680{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001681 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 for (i = 0; i < asdl_seq_LEN(args); i++) {
1683 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001684 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 c,
1686 arg->arg,
1687 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001688 names))
1689 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001692}
1693
1694static int
1695compiler_visit_annotations(struct compiler *c, arguments_ty args,
1696 expr_ty returns)
1697{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001698 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001699 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001700
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001701 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 */
1703 static identifier return_str;
1704 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001705 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 names = PyList_New(0);
1707 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001708 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001709
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001710 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001712 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001713 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001714 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001716 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001718 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001719 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001720 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (!return_str) {
1724 return_str = PyUnicode_InternFromString("return");
1725 if (!return_str)
1726 goto error;
1727 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001728 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 goto error;
1730 }
1731
1732 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001734 PyObject *keytuple = PyList_AsTuple(names);
1735 Py_DECREF(names);
1736 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001737 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001739 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1740 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001741 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001743 else {
1744 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001745 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001746 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001747
1748error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001750 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001751}
1752
1753static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001754compiler_visit_defaults(struct compiler *c, arguments_ty args)
1755{
1756 VISIT_SEQ(c, expr, args->defaults);
1757 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1758 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759}
1760
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761static Py_ssize_t
1762compiler_default_arguments(struct compiler *c, arguments_ty args)
1763{
1764 Py_ssize_t funcflags = 0;
1765 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001766 if (!compiler_visit_defaults(c, args))
1767 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768 funcflags |= 0x01;
1769 }
1770 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001771 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001772 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001773 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001774 return -1;
1775 }
1776 else if (res > 0) {
1777 funcflags |= 0x02;
1778 }
1779 }
1780 return funcflags;
1781}
1782
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783static int
Yury Selivanov75445082015-05-11 22:57:16 -04001784compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001787 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001788 arguments_ty args;
1789 expr_ty returns;
1790 identifier name;
1791 asdl_seq* decos;
1792 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001793 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001794 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001795 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796
Yury Selivanov75445082015-05-11 22:57:16 -04001797 if (is_async) {
1798 assert(s->kind == AsyncFunctionDef_kind);
1799
1800 args = s->v.AsyncFunctionDef.args;
1801 returns = s->v.AsyncFunctionDef.returns;
1802 decos = s->v.AsyncFunctionDef.decorator_list;
1803 name = s->v.AsyncFunctionDef.name;
1804 body = s->v.AsyncFunctionDef.body;
1805
1806 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1807 } else {
1808 assert(s->kind == FunctionDef_kind);
1809
1810 args = s->v.FunctionDef.args;
1811 returns = s->v.FunctionDef.returns;
1812 decos = s->v.FunctionDef.decorator_list;
1813 name = s->v.FunctionDef.name;
1814 body = s->v.FunctionDef.body;
1815
1816 scope_type = COMPILER_SCOPE_FUNCTION;
1817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (!compiler_decorators(c, decos))
1820 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001821
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001822 funcflags = compiler_default_arguments(c, args);
1823 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001825 }
1826
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001827 annotations = compiler_visit_annotations(c, args, returns);
1828 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001829 return 0;
1830 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001831 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001832 funcflags |= 0x04;
1833 }
1834
1835 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1836 return 0;
1837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838
INADA Naokicb41b272017-02-23 00:31:59 +09001839 /* if not -OO mode, add docstring */
1840 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1841 docstring = s->v.FunctionDef.docstring;
1842 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 compiler_exit_scope(c);
1844 return 0;
1845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 c->u->u_argcount = asdl_seq_LEN(args->args);
1848 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001850 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001852 qualname = c->u->u_qualname;
1853 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001855 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001856 Py_XDECREF(qualname);
1857 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001861 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001862 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* decorators */
1866 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1867 ADDOP_I(c, CALL_FUNCTION, 1);
1868 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
Yury Selivanov75445082015-05-11 22:57:16 -04001870 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871}
1872
1873static int
1874compiler_class(struct compiler *c, stmt_ty s)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyCodeObject *co;
1877 PyObject *str;
1878 int i;
1879 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (!compiler_decorators(c, decos))
1882 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* ultimately generate code for:
1885 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1886 where:
1887 <func> is a function/closure created from the class body;
1888 it has a single argument (__locals__) where the dict
1889 (or MutableSequence) representing the locals is passed
1890 <name> is the class name
1891 <bases> is the positional arguments and *varargs argument
1892 <keywords> is the keyword arguments and **kwds argument
1893 This borrows from compiler_call.
1894 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001897 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1898 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 return 0;
1900 /* this block represents what we do in the new scope */
1901 {
1902 /* use the class name for name mangling */
1903 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001904 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* load (global) __name__ ... */
1906 str = PyUnicode_InternFromString("__name__");
1907 if (!str || !compiler_nameop(c, str, Load)) {
1908 Py_XDECREF(str);
1909 compiler_exit_scope(c);
1910 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_DECREF(str);
1913 /* ... and store it as __module__ */
1914 str = PyUnicode_InternFromString("__module__");
1915 if (!str || !compiler_nameop(c, str, Store)) {
1916 Py_XDECREF(str);
1917 compiler_exit_scope(c);
1918 return 0;
1919 }
1920 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001921 assert(c->u->u_qualname);
1922 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001923 str = PyUnicode_InternFromString("__qualname__");
1924 if (!str || !compiler_nameop(c, str, Store)) {
1925 Py_XDECREF(str);
1926 compiler_exit_scope(c);
1927 return 0;
1928 }
1929 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001931 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 compiler_exit_scope(c);
1933 return 0;
1934 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001935 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001936 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001937 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001938 str = PyUnicode_InternFromString("__class__");
1939 if (str == NULL) {
1940 compiler_exit_scope(c);
1941 return 0;
1942 }
1943 i = compiler_lookup_arg(c->u->u_cellvars, str);
1944 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001945 if (i < 0) {
1946 compiler_exit_scope(c);
1947 return 0;
1948 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001949 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001952 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001953 str = PyUnicode_InternFromString("__classcell__");
1954 if (!str || !compiler_nameop(c, str, Store)) {
1955 Py_XDECREF(str);
1956 compiler_exit_scope(c);
1957 return 0;
1958 }
1959 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001961 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001962 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001963 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001964 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001965 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001966 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 /* create the code object */
1968 co = assemble(c, 1);
1969 }
1970 /* leave the new scope */
1971 compiler_exit_scope(c);
1972 if (co == NULL)
1973 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* 2. load the 'build_class' function */
1976 ADDOP(c, LOAD_BUILD_CLASS);
1977
1978 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001979 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 Py_DECREF(co);
1981
1982 /* 4. load class name */
1983 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1984
1985 /* 5. generate the rest of the code for the call */
1986 if (!compiler_call_helper(c, 2,
1987 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001988 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return 0;
1990
1991 /* 6. apply decorators */
1992 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1993 ADDOP_I(c, CALL_FUNCTION, 1);
1994 }
1995
1996 /* 7. store into <name> */
1997 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1998 return 0;
1999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000}
2001
2002static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002003cmpop(cmpop_ty op)
2004{
2005 switch (op) {
2006 case Eq:
2007 return PyCmp_EQ;
2008 case NotEq:
2009 return PyCmp_NE;
2010 case Lt:
2011 return PyCmp_LT;
2012 case LtE:
2013 return PyCmp_LE;
2014 case Gt:
2015 return PyCmp_GT;
2016 case GtE:
2017 return PyCmp_GE;
2018 case Is:
2019 return PyCmp_IS;
2020 case IsNot:
2021 return PyCmp_IS_NOT;
2022 case In:
2023 return PyCmp_IN;
2024 case NotIn:
2025 return PyCmp_NOT_IN;
2026 default:
2027 return PyCmp_BAD;
2028 }
2029}
2030
2031static int
2032compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2033{
2034 switch (e->kind) {
2035 case UnaryOp_kind:
2036 if (e->v.UnaryOp.op == Not)
2037 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2038 /* fallback to general implementation */
2039 break;
2040 case BoolOp_kind: {
2041 asdl_seq *s = e->v.BoolOp.values;
2042 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2043 assert(n >= 0);
2044 int cond2 = e->v.BoolOp.op == Or;
2045 basicblock *next2 = next;
2046 if (!cond2 != !cond) {
2047 next2 = compiler_new_block(c);
2048 if (next2 == NULL)
2049 return 0;
2050 }
2051 for (i = 0; i < n; ++i) {
2052 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2053 return 0;
2054 }
2055 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2056 return 0;
2057 if (next2 != next)
2058 compiler_use_next_block(c, next2);
2059 return 1;
2060 }
2061 case IfExp_kind: {
2062 basicblock *end, *next2;
2063 end = compiler_new_block(c);
2064 if (end == NULL)
2065 return 0;
2066 next2 = compiler_new_block(c);
2067 if (next2 == NULL)
2068 return 0;
2069 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2070 return 0;
2071 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2072 return 0;
2073 ADDOP_JREL(c, JUMP_FORWARD, end);
2074 compiler_use_next_block(c, next2);
2075 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2076 return 0;
2077 compiler_use_next_block(c, end);
2078 return 1;
2079 }
2080 case Compare_kind: {
2081 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2082 if (n > 0) {
2083 basicblock *cleanup = compiler_new_block(c);
2084 if (cleanup == NULL)
2085 return 0;
2086 VISIT(c, expr, e->v.Compare.left);
2087 for (i = 0; i < n; i++) {
2088 VISIT(c, expr,
2089 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2090 ADDOP(c, DUP_TOP);
2091 ADDOP(c, ROT_THREE);
2092 ADDOP_I(c, COMPARE_OP,
2093 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2094 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2095 NEXT_BLOCK(c);
2096 }
2097 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2098 ADDOP_I(c, COMPARE_OP,
2099 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2100 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2101 basicblock *end = compiler_new_block(c);
2102 if (end == NULL)
2103 return 0;
2104 ADDOP_JREL(c, JUMP_FORWARD, end);
2105 compiler_use_next_block(c, cleanup);
2106 ADDOP(c, POP_TOP);
2107 if (!cond) {
2108 ADDOP_JREL(c, JUMP_FORWARD, next);
2109 }
2110 compiler_use_next_block(c, end);
2111 return 1;
2112 }
2113 /* fallback to general implementation */
2114 break;
2115 }
2116 default:
2117 /* fallback to general implementation */
2118 break;
2119 }
2120
2121 /* general implementation */
2122 VISIT(c, expr, e);
2123 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2124 return 1;
2125}
2126
2127static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002128compiler_ifexp(struct compiler *c, expr_ty e)
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 basicblock *end, *next;
2131
2132 assert(e->kind == IfExp_kind);
2133 end = compiler_new_block(c);
2134 if (end == NULL)
2135 return 0;
2136 next = compiler_new_block(c);
2137 if (next == NULL)
2138 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002139 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2140 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 VISIT(c, expr, e->v.IfExp.body);
2142 ADDOP_JREL(c, JUMP_FORWARD, end);
2143 compiler_use_next_block(c, next);
2144 VISIT(c, expr, e->v.IfExp.orelse);
2145 compiler_use_next_block(c, end);
2146 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002147}
2148
2149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150compiler_lambda(struct compiler *c, expr_ty e)
2151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002153 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002155 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 arguments_ty args = e->v.Lambda.args;
2157 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (!name) {
2160 name = PyUnicode_InternFromString("<lambda>");
2161 if (!name)
2162 return 0;
2163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002165 funcflags = compiler_default_arguments(c, args);
2166 if (funcflags == -1) {
2167 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002169
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002170 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002171 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* Make None the first constant, so the lambda can't have a
2175 docstring. */
2176 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2177 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 c->u->u_argcount = asdl_seq_LEN(args->args);
2180 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2181 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2182 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002183 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 }
2185 else {
2186 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002187 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002189 qualname = c->u->u_qualname;
2190 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002192 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002195 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002196 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_DECREF(co);
2198
2199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200}
2201
2202static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203compiler_if(struct compiler *c, stmt_ty s)
2204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 basicblock *end, *next;
2206 int constant;
2207 assert(s->kind == If_kind);
2208 end = compiler_new_block(c);
2209 if (end == NULL)
2210 return 0;
2211
Georg Brandl8334fd92010-12-04 10:26:46 +00002212 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 /* constant = 0: "if 0"
2214 * constant = 1: "if 1", "if 2", ...
2215 * constant = -1: rest */
2216 if (constant == 0) {
2217 if (s->v.If.orelse)
2218 VISIT_SEQ(c, stmt, s->v.If.orelse);
2219 } else if (constant == 1) {
2220 VISIT_SEQ(c, stmt, s->v.If.body);
2221 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002222 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 next = compiler_new_block(c);
2224 if (next == NULL)
2225 return 0;
2226 }
2227 else
2228 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002229 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2230 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002232 if (asdl_seq_LEN(s->v.If.orelse)) {
2233 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 compiler_use_next_block(c, next);
2235 VISIT_SEQ(c, stmt, s->v.If.orelse);
2236 }
2237 }
2238 compiler_use_next_block(c, end);
2239 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240}
2241
2242static int
2243compiler_for(struct compiler *c, stmt_ty s)
2244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 start = compiler_new_block(c);
2248 cleanup = compiler_new_block(c);
2249 end = compiler_new_block(c);
2250 if (start == NULL || end == NULL || cleanup == NULL)
2251 return 0;
2252 ADDOP_JREL(c, SETUP_LOOP, end);
2253 if (!compiler_push_fblock(c, LOOP, start))
2254 return 0;
2255 VISIT(c, expr, s->v.For.iter);
2256 ADDOP(c, GET_ITER);
2257 compiler_use_next_block(c, start);
2258 ADDOP_JREL(c, FOR_ITER, cleanup);
2259 VISIT(c, expr, s->v.For.target);
2260 VISIT_SEQ(c, stmt, s->v.For.body);
2261 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2262 compiler_use_next_block(c, cleanup);
2263 ADDOP(c, POP_BLOCK);
2264 compiler_pop_fblock(c, LOOP, start);
2265 VISIT_SEQ(c, stmt, s->v.For.orelse);
2266 compiler_use_next_block(c, end);
2267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268}
2269
Yury Selivanov75445082015-05-11 22:57:16 -04002270
2271static int
2272compiler_async_for(struct compiler *c, stmt_ty s)
2273{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002274 _Py_IDENTIFIER(StopAsyncIteration);
2275
Yury Selivanov75445082015-05-11 22:57:16 -04002276 basicblock *try, *except, *end, *after_try, *try_cleanup,
2277 *after_loop, *after_loop_else;
2278
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002279 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2280 if (stop_aiter_error == NULL) {
2281 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002282 }
2283
2284 try = compiler_new_block(c);
2285 except = compiler_new_block(c);
2286 end = compiler_new_block(c);
2287 after_try = compiler_new_block(c);
2288 try_cleanup = compiler_new_block(c);
2289 after_loop = compiler_new_block(c);
2290 after_loop_else = compiler_new_block(c);
2291
2292 if (try == NULL || except == NULL || end == NULL
2293 || after_try == NULL || try_cleanup == NULL)
2294 return 0;
2295
2296 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2297 if (!compiler_push_fblock(c, LOOP, try))
2298 return 0;
2299
2300 VISIT(c, expr, s->v.AsyncFor.iter);
2301 ADDOP(c, GET_AITER);
2302 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2303 ADDOP(c, YIELD_FROM);
2304
2305 compiler_use_next_block(c, try);
2306
2307
2308 ADDOP_JREL(c, SETUP_EXCEPT, except);
2309 if (!compiler_push_fblock(c, EXCEPT, try))
2310 return 0;
2311
2312 ADDOP(c, GET_ANEXT);
2313 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2314 ADDOP(c, YIELD_FROM);
2315 VISIT(c, expr, s->v.AsyncFor.target);
2316 ADDOP(c, POP_BLOCK);
2317 compiler_pop_fblock(c, EXCEPT, try);
2318 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2319
2320
2321 compiler_use_next_block(c, except);
2322 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002323 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002324 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2325 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2326
2327 ADDOP(c, POP_TOP);
2328 ADDOP(c, POP_TOP);
2329 ADDOP(c, POP_TOP);
2330 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2331 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2332 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2333
2334
2335 compiler_use_next_block(c, try_cleanup);
2336 ADDOP(c, END_FINALLY);
2337
2338 compiler_use_next_block(c, after_try);
2339 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2340 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2341
2342 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2343 compiler_pop_fblock(c, LOOP, try);
2344
2345 compiler_use_next_block(c, after_loop);
2346 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2347
2348 compiler_use_next_block(c, after_loop_else);
2349 VISIT_SEQ(c, stmt, s->v.For.orelse);
2350
2351 compiler_use_next_block(c, end);
2352
2353 return 1;
2354}
2355
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356static int
2357compiler_while(struct compiler *c, stmt_ty s)
2358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002360 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (constant == 0) {
2363 if (s->v.While.orelse)
2364 VISIT_SEQ(c, stmt, s->v.While.orelse);
2365 return 1;
2366 }
2367 loop = compiler_new_block(c);
2368 end = compiler_new_block(c);
2369 if (constant == -1) {
2370 anchor = compiler_new_block(c);
2371 if (anchor == NULL)
2372 return 0;
2373 }
2374 if (loop == NULL || end == NULL)
2375 return 0;
2376 if (s->v.While.orelse) {
2377 orelse = compiler_new_block(c);
2378 if (orelse == NULL)
2379 return 0;
2380 }
2381 else
2382 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 ADDOP_JREL(c, SETUP_LOOP, end);
2385 compiler_use_next_block(c, loop);
2386 if (!compiler_push_fblock(c, LOOP, loop))
2387 return 0;
2388 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002389 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2390 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 }
2392 VISIT_SEQ(c, stmt, s->v.While.body);
2393 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* XXX should the two POP instructions be in a separate block
2396 if there is no else clause ?
2397 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002399 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002401 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 compiler_pop_fblock(c, LOOP, loop);
2403 if (orelse != NULL) /* what if orelse is just pass? */
2404 VISIT_SEQ(c, stmt, s->v.While.orelse);
2405 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408}
2409
2410static int
2411compiler_continue(struct compiler *c)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2414 static const char IN_FINALLY_ERROR_MSG[] =
2415 "'continue' not supported inside 'finally' clause";
2416 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (!c->u->u_nfblocks)
2419 return compiler_error(c, LOOP_ERROR_MSG);
2420 i = c->u->u_nfblocks - 1;
2421 switch (c->u->u_fblock[i].fb_type) {
2422 case LOOP:
2423 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2424 break;
2425 case EXCEPT:
2426 case FINALLY_TRY:
2427 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2428 /* Prevent continue anywhere under a finally
2429 even if hidden in a sub-try or except. */
2430 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2431 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2432 }
2433 if (i == -1)
2434 return compiler_error(c, LOOP_ERROR_MSG);
2435 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2436 break;
2437 case FINALLY_END:
2438 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442}
2443
2444/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445
2446 SETUP_FINALLY L
2447 <code for body>
2448 POP_BLOCK
2449 LOAD_CONST <None>
2450 L: <code for finalbody>
2451 END_FINALLY
2452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453 The special instructions use the block stack. Each block
2454 stack entry contains the instruction that created it (here
2455 SETUP_FINALLY), the level of the value stack at the time the
2456 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 Pushes the current value stack level and the label
2460 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 Pops en entry from the block stack, and pops the value
2463 stack until its level is the same as indicated on the
2464 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 Pops a variable number of entries from the *value* stack
2467 and re-raises the exception they specify. The number of
2468 entries popped depends on the (pseudo) exception type.
2469
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 The block stack is unwound when an exception is raised:
2471 when a SETUP_FINALLY entry is found, the exception is pushed
2472 onto the value stack (and the exception condition is cleared),
2473 and the interpreter jumps to the label gotten from the block
2474 stack.
2475*/
2476
2477static int
2478compiler_try_finally(struct compiler *c, stmt_ty s)
2479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 basicblock *body, *end;
2481 body = compiler_new_block(c);
2482 end = compiler_new_block(c);
2483 if (body == NULL || end == NULL)
2484 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 ADDOP_JREL(c, SETUP_FINALLY, end);
2487 compiler_use_next_block(c, body);
2488 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2489 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002490 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2491 if (!compiler_try_except(c, s))
2492 return 0;
2493 }
2494 else {
2495 VISIT_SEQ(c, stmt, s->v.Try.body);
2496 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 ADDOP(c, POP_BLOCK);
2498 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2501 compiler_use_next_block(c, end);
2502 if (!compiler_push_fblock(c, FINALLY_END, end))
2503 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002504 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 ADDOP(c, END_FINALLY);
2506 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509}
2510
2511/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002512 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 (The contents of the value stack is shown in [], with the top
2514 at the right; 'tb' is trace-back info, 'val' the exception's
2515 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516
2517 Value stack Label Instruction Argument
2518 [] SETUP_EXCEPT L1
2519 [] <code for S>
2520 [] POP_BLOCK
2521 [] JUMP_FORWARD L0
2522
2523 [tb, val, exc] L1: DUP )
2524 [tb, val, exc, exc] <evaluate E1> )
2525 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2526 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2527 [tb, val, exc] POP
2528 [tb, val] <assign to V1> (or POP if no V1)
2529 [tb] POP
2530 [] <code for S1>
2531 JUMP_FORWARD L0
2532
2533 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 .............................etc.......................
2535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2537
2538 [] L0: <next statement>
2539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 Of course, parts are not generated if Vi or Ei is not present.
2541*/
2542static int
2543compiler_try_except(struct compiler *c, stmt_ty s)
2544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002546 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 body = compiler_new_block(c);
2549 except = compiler_new_block(c);
2550 orelse = compiler_new_block(c);
2551 end = compiler_new_block(c);
2552 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2553 return 0;
2554 ADDOP_JREL(c, SETUP_EXCEPT, except);
2555 compiler_use_next_block(c, body);
2556 if (!compiler_push_fblock(c, EXCEPT, body))
2557 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002558 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 ADDOP(c, POP_BLOCK);
2560 compiler_pop_fblock(c, EXCEPT, body);
2561 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002562 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 compiler_use_next_block(c, except);
2564 for (i = 0; i < n; i++) {
2565 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002566 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 if (!handler->v.ExceptHandler.type && i < n-1)
2568 return compiler_error(c, "default 'except:' must be last");
2569 c->u->u_lineno_set = 0;
2570 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002571 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 except = compiler_new_block(c);
2573 if (except == NULL)
2574 return 0;
2575 if (handler->v.ExceptHandler.type) {
2576 ADDOP(c, DUP_TOP);
2577 VISIT(c, expr, handler->v.ExceptHandler.type);
2578 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2579 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2580 }
2581 ADDOP(c, POP_TOP);
2582 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002583 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002584
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002585 cleanup_end = compiler_new_block(c);
2586 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002587 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002588 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002589
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002590 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2591 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002593 /*
2594 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002595 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002596 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002597 try:
2598 # body
2599 finally:
2600 name = None
2601 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002602 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002604 /* second try: */
2605 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2606 compiler_use_next_block(c, cleanup_body);
2607 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2608 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002610 /* second # body */
2611 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2612 ADDOP(c, POP_BLOCK);
2613 ADDOP(c, POP_EXCEPT);
2614 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002616 /* finally: */
2617 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2618 compiler_use_next_block(c, cleanup_end);
2619 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2620 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002622 /* name = None */
2623 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2624 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002626 /* del name */
2627 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002629 ADDOP(c, END_FINALLY);
2630 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 }
2632 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002633 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002635 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002636 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002637 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638
Guido van Rossumb940e112007-01-10 16:19:56 +00002639 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002640 ADDOP(c, POP_TOP);
2641 compiler_use_next_block(c, cleanup_body);
2642 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2643 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002645 ADDOP(c, POP_EXCEPT);
2646 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 }
2648 ADDOP_JREL(c, JUMP_FORWARD, end);
2649 compiler_use_next_block(c, except);
2650 }
2651 ADDOP(c, END_FINALLY);
2652 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002653 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 compiler_use_next_block(c, end);
2655 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656}
2657
2658static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002659compiler_try(struct compiler *c, stmt_ty s) {
2660 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2661 return compiler_try_finally(c, s);
2662 else
2663 return compiler_try_except(c, s);
2664}
2665
2666
2667static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668compiler_import_as(struct compiler *c, identifier name, identifier asname)
2669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* The IMPORT_NAME opcode was already generated. This function
2671 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002674 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2677 PyUnicode_GET_LENGTH(name), 1);
2678 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002679 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002680 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002682 Py_ssize_t pos = dot + 1;
2683 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002685 dot = PyUnicode_FindChar(name, '.', pos,
2686 PyUnicode_GET_LENGTH(name), 1);
2687 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002688 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 attr = PyUnicode_Substring(name, pos,
2690 (dot != -1) ? dot :
2691 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002693 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002694 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 }
2698 }
2699 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700}
2701
2702static int
2703compiler_import(struct compiler *c, stmt_ty s)
2704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 /* The Import node stores a module name like a.b.c as a single
2706 string. This is convenient for all cases except
2707 import a.b.c as d
2708 where we need to parse that string to extract the individual
2709 module names.
2710 XXX Perhaps change the representation to make this case simpler?
2711 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002712 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 for (i = 0; i < n; i++) {
2715 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2716 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002718 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2720 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 if (alias->asname) {
2723 r = compiler_import_as(c, alias->name, alias->asname);
2724 if (!r)
2725 return r;
2726 }
2727 else {
2728 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002729 Py_ssize_t dot = PyUnicode_FindChar(
2730 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002731 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002733 if (tmp == NULL)
2734 return 0;
2735 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 Py_DECREF(tmp);
2739 }
2740 if (!r)
2741 return r;
2742 }
2743 }
2744 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745}
2746
2747static int
2748compiler_from_import(struct compiler *c, stmt_ty s)
2749{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002750 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 PyObject *names = PyTuple_New(n);
2753 PyObject *level;
2754 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 if (!empty_string) {
2757 empty_string = PyUnicode_FromString("");
2758 if (!empty_string)
2759 return 0;
2760 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 if (!names)
2763 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 level = PyLong_FromLong(s->v.ImportFrom.level);
2766 if (!level) {
2767 Py_DECREF(names);
2768 return 0;
2769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* build up the names */
2772 for (i = 0; i < n; i++) {
2773 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2774 Py_INCREF(alias->name);
2775 PyTuple_SET_ITEM(names, i, alias->name);
2776 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002779 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 Py_DECREF(level);
2781 Py_DECREF(names);
2782 return compiler_error(c, "from __future__ imports must occur "
2783 "at the beginning of the file");
2784 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 ADDOP_O(c, LOAD_CONST, level, consts);
2787 Py_DECREF(level);
2788 ADDOP_O(c, LOAD_CONST, names, consts);
2789 Py_DECREF(names);
2790 if (s->v.ImportFrom.module) {
2791 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2792 }
2793 else {
2794 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2795 }
2796 for (i = 0; i < n; i++) {
2797 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2798 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002800 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 assert(n == 1);
2802 ADDOP(c, IMPORT_STAR);
2803 return 1;
2804 }
2805
2806 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2807 store_name = alias->name;
2808 if (alias->asname)
2809 store_name = alias->asname;
2810
2811 if (!compiler_nameop(c, store_name, Store)) {
2812 Py_DECREF(names);
2813 return 0;
2814 }
2815 }
2816 /* remove imported module */
2817 ADDOP(c, POP_TOP);
2818 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819}
2820
2821static int
2822compiler_assert(struct compiler *c, stmt_ty s)
2823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 static PyObject *assertion_error = NULL;
2825 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002826 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Georg Brandl8334fd92010-12-04 10:26:46 +00002828 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 return 1;
2830 if (assertion_error == NULL) {
2831 assertion_error = PyUnicode_InternFromString("AssertionError");
2832 if (assertion_error == NULL)
2833 return 0;
2834 }
2835 if (s->v.Assert.test->kind == Tuple_kind &&
2836 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002837 msg = PyUnicode_FromString("assertion is always true, "
2838 "perhaps remove parentheses?");
2839 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002841 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2842 c->c_filename, c->u->u_lineno,
2843 NULL, NULL) == -1) {
2844 Py_DECREF(msg);
2845 return 0;
2846 }
2847 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 end = compiler_new_block(c);
2850 if (end == NULL)
2851 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002852 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2853 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2855 if (s->v.Assert.msg) {
2856 VISIT(c, expr, s->v.Assert.msg);
2857 ADDOP_I(c, CALL_FUNCTION, 1);
2858 }
2859 ADDOP_I(c, RAISE_VARARGS, 1);
2860 compiler_use_next_block(c, end);
2861 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862}
2863
2864static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002865compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2866{
2867 if (c->c_interactive && c->c_nestlevel <= 1) {
2868 VISIT(c, expr, value);
2869 ADDOP(c, PRINT_EXPR);
2870 return 1;
2871 }
2872
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002873 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002874 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002875 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002876 }
2877
2878 VISIT(c, expr, value);
2879 ADDOP(c, POP_TOP);
2880 return 1;
2881}
2882
2883static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884compiler_visit_stmt(struct compiler *c, stmt_ty s)
2885{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002886 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 /* Always assign a lineno to the next instruction for a stmt. */
2889 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002890 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 switch (s->kind) {
2894 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002895 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 case ClassDef_kind:
2897 return compiler_class(c, s);
2898 case Return_kind:
2899 if (c->u->u_ste->ste_type != FunctionBlock)
2900 return compiler_error(c, "'return' outside function");
2901 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002902 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2903 return compiler_error(
2904 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 VISIT(c, expr, s->v.Return.value);
2906 }
2907 else
2908 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2909 ADDOP(c, RETURN_VALUE);
2910 break;
2911 case Delete_kind:
2912 VISIT_SEQ(c, expr, s->v.Delete.targets)
2913 break;
2914 case Assign_kind:
2915 n = asdl_seq_LEN(s->v.Assign.targets);
2916 VISIT(c, expr, s->v.Assign.value);
2917 for (i = 0; i < n; i++) {
2918 if (i < n - 1)
2919 ADDOP(c, DUP_TOP);
2920 VISIT(c, expr,
2921 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2922 }
2923 break;
2924 case AugAssign_kind:
2925 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002926 case AnnAssign_kind:
2927 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 case For_kind:
2929 return compiler_for(c, s);
2930 case While_kind:
2931 return compiler_while(c, s);
2932 case If_kind:
2933 return compiler_if(c, s);
2934 case Raise_kind:
2935 n = 0;
2936 if (s->v.Raise.exc) {
2937 VISIT(c, expr, s->v.Raise.exc);
2938 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002939 if (s->v.Raise.cause) {
2940 VISIT(c, expr, s->v.Raise.cause);
2941 n++;
2942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002944 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002946 case Try_kind:
2947 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 case Assert_kind:
2949 return compiler_assert(c, s);
2950 case Import_kind:
2951 return compiler_import(c, s);
2952 case ImportFrom_kind:
2953 return compiler_from_import(c, s);
2954 case Global_kind:
2955 case Nonlocal_kind:
2956 break;
2957 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002958 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 case Pass_kind:
2960 break;
2961 case Break_kind:
2962 if (!compiler_in_loop(c))
2963 return compiler_error(c, "'break' outside loop");
2964 ADDOP(c, BREAK_LOOP);
2965 break;
2966 case Continue_kind:
2967 return compiler_continue(c);
2968 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002969 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002970 case AsyncFunctionDef_kind:
2971 return compiler_function(c, s, 1);
2972 case AsyncWith_kind:
2973 return compiler_async_with(c, s, 0);
2974 case AsyncFor_kind:
2975 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 }
Yury Selivanov75445082015-05-11 22:57:16 -04002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979}
2980
2981static int
2982unaryop(unaryop_ty op)
2983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 switch (op) {
2985 case Invert:
2986 return UNARY_INVERT;
2987 case Not:
2988 return UNARY_NOT;
2989 case UAdd:
2990 return UNARY_POSITIVE;
2991 case USub:
2992 return UNARY_NEGATIVE;
2993 default:
2994 PyErr_Format(PyExc_SystemError,
2995 "unary op %d should not be possible", op);
2996 return 0;
2997 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998}
2999
3000static int
3001binop(struct compiler *c, operator_ty op)
3002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 switch (op) {
3004 case Add:
3005 return BINARY_ADD;
3006 case Sub:
3007 return BINARY_SUBTRACT;
3008 case Mult:
3009 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003010 case MatMult:
3011 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 case Div:
3013 return BINARY_TRUE_DIVIDE;
3014 case Mod:
3015 return BINARY_MODULO;
3016 case Pow:
3017 return BINARY_POWER;
3018 case LShift:
3019 return BINARY_LSHIFT;
3020 case RShift:
3021 return BINARY_RSHIFT;
3022 case BitOr:
3023 return BINARY_OR;
3024 case BitXor:
3025 return BINARY_XOR;
3026 case BitAnd:
3027 return BINARY_AND;
3028 case FloorDiv:
3029 return BINARY_FLOOR_DIVIDE;
3030 default:
3031 PyErr_Format(PyExc_SystemError,
3032 "binary op %d should not be possible", op);
3033 return 0;
3034 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035}
3036
3037static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038inplace_binop(struct compiler *c, operator_ty op)
3039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 switch (op) {
3041 case Add:
3042 return INPLACE_ADD;
3043 case Sub:
3044 return INPLACE_SUBTRACT;
3045 case Mult:
3046 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003047 case MatMult:
3048 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 case Div:
3050 return INPLACE_TRUE_DIVIDE;
3051 case Mod:
3052 return INPLACE_MODULO;
3053 case Pow:
3054 return INPLACE_POWER;
3055 case LShift:
3056 return INPLACE_LSHIFT;
3057 case RShift:
3058 return INPLACE_RSHIFT;
3059 case BitOr:
3060 return INPLACE_OR;
3061 case BitXor:
3062 return INPLACE_XOR;
3063 case BitAnd:
3064 return INPLACE_AND;
3065 case FloorDiv:
3066 return INPLACE_FLOOR_DIVIDE;
3067 default:
3068 PyErr_Format(PyExc_SystemError,
3069 "inplace binary op %d should not be possible", op);
3070 return 0;
3071 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072}
3073
3074static int
3075compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3076{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003077 int op, scope;
3078 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 PyObject *dict = c->u->u_names;
3082 PyObject *mangled;
3083 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 mangled = _Py_Mangle(c->u->u_private, name);
3086 if (!mangled)
3087 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003088
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003089 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3090 !_PyUnicode_EqualToASCIIString(name, "True") &&
3091 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 op = 0;
3094 optype = OP_NAME;
3095 scope = PyST_GetScope(c->u->u_ste, mangled);
3096 switch (scope) {
3097 case FREE:
3098 dict = c->u->u_freevars;
3099 optype = OP_DEREF;
3100 break;
3101 case CELL:
3102 dict = c->u->u_cellvars;
3103 optype = OP_DEREF;
3104 break;
3105 case LOCAL:
3106 if (c->u->u_ste->ste_type == FunctionBlock)
3107 optype = OP_FAST;
3108 break;
3109 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003110 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 optype = OP_GLOBAL;
3112 break;
3113 case GLOBAL_EXPLICIT:
3114 optype = OP_GLOBAL;
3115 break;
3116 default:
3117 /* scope can be 0 */
3118 break;
3119 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003122 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 switch (optype) {
3125 case OP_DEREF:
3126 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003127 case Load:
3128 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3129 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 case Store: op = STORE_DEREF; break;
3131 case AugLoad:
3132 case AugStore:
3133 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003134 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 case Param:
3136 default:
3137 PyErr_SetString(PyExc_SystemError,
3138 "param invalid for deref variable");
3139 return 0;
3140 }
3141 break;
3142 case OP_FAST:
3143 switch (ctx) {
3144 case Load: op = LOAD_FAST; break;
3145 case Store: op = STORE_FAST; break;
3146 case Del: op = DELETE_FAST; break;
3147 case AugLoad:
3148 case AugStore:
3149 break;
3150 case Param:
3151 default:
3152 PyErr_SetString(PyExc_SystemError,
3153 "param invalid for local variable");
3154 return 0;
3155 }
3156 ADDOP_O(c, op, mangled, varnames);
3157 Py_DECREF(mangled);
3158 return 1;
3159 case OP_GLOBAL:
3160 switch (ctx) {
3161 case Load: op = LOAD_GLOBAL; break;
3162 case Store: op = STORE_GLOBAL; break;
3163 case Del: op = DELETE_GLOBAL; break;
3164 case AugLoad:
3165 case AugStore:
3166 break;
3167 case Param:
3168 default:
3169 PyErr_SetString(PyExc_SystemError,
3170 "param invalid for global variable");
3171 return 0;
3172 }
3173 break;
3174 case OP_NAME:
3175 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003176 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 case Store: op = STORE_NAME; break;
3178 case Del: op = DELETE_NAME; break;
3179 case AugLoad:
3180 case AugStore:
3181 break;
3182 case Param:
3183 default:
3184 PyErr_SetString(PyExc_SystemError,
3185 "param invalid for name variable");
3186 return 0;
3187 }
3188 break;
3189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 assert(op);
3192 arg = compiler_add_o(c, dict, mangled);
3193 Py_DECREF(mangled);
3194 if (arg < 0)
3195 return 0;
3196 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197}
3198
3199static int
3200compiler_boolop(struct compiler *c, expr_ty e)
3201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003203 int jumpi;
3204 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 assert(e->kind == BoolOp_kind);
3208 if (e->v.BoolOp.op == And)
3209 jumpi = JUMP_IF_FALSE_OR_POP;
3210 else
3211 jumpi = JUMP_IF_TRUE_OR_POP;
3212 end = compiler_new_block(c);
3213 if (end == NULL)
3214 return 0;
3215 s = e->v.BoolOp.values;
3216 n = asdl_seq_LEN(s) - 1;
3217 assert(n >= 0);
3218 for (i = 0; i < n; ++i) {
3219 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3220 ADDOP_JABS(c, jumpi, end);
3221 }
3222 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3223 compiler_use_next_block(c, end);
3224 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225}
3226
3227static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003228starunpack_helper(struct compiler *c, asdl_seq *elts,
3229 int single_op, int inner_op, int outer_op)
3230{
3231 Py_ssize_t n = asdl_seq_LEN(elts);
3232 Py_ssize_t i, nsubitems = 0, nseen = 0;
3233 for (i = 0; i < n; i++) {
3234 expr_ty elt = asdl_seq_GET(elts, i);
3235 if (elt->kind == Starred_kind) {
3236 if (nseen) {
3237 ADDOP_I(c, inner_op, nseen);
3238 nseen = 0;
3239 nsubitems++;
3240 }
3241 VISIT(c, expr, elt->v.Starred.value);
3242 nsubitems++;
3243 }
3244 else {
3245 VISIT(c, expr, elt);
3246 nseen++;
3247 }
3248 }
3249 if (nsubitems) {
3250 if (nseen) {
3251 ADDOP_I(c, inner_op, nseen);
3252 nsubitems++;
3253 }
3254 ADDOP_I(c, outer_op, nsubitems);
3255 }
3256 else
3257 ADDOP_I(c, single_op, nseen);
3258 return 1;
3259}
3260
3261static int
3262assignment_helper(struct compiler *c, asdl_seq *elts)
3263{
3264 Py_ssize_t n = asdl_seq_LEN(elts);
3265 Py_ssize_t i;
3266 int seen_star = 0;
3267 for (i = 0; i < n; i++) {
3268 expr_ty elt = asdl_seq_GET(elts, i);
3269 if (elt->kind == Starred_kind && !seen_star) {
3270 if ((i >= (1 << 8)) ||
3271 (n-i-1 >= (INT_MAX >> 8)))
3272 return compiler_error(c,
3273 "too many expressions in "
3274 "star-unpacking assignment");
3275 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3276 seen_star = 1;
3277 asdl_seq_SET(elts, i, elt->v.Starred.value);
3278 }
3279 else if (elt->kind == Starred_kind) {
3280 return compiler_error(c,
3281 "two starred expressions in assignment");
3282 }
3283 }
3284 if (!seen_star) {
3285 ADDOP_I(c, UNPACK_SEQUENCE, n);
3286 }
3287 VISIT_SEQ(c, expr, elts);
3288 return 1;
3289}
3290
3291static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292compiler_list(struct compiler *c, expr_ty e)
3293{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003294 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003296 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003298 else if (e->v.List.ctx == Load) {
3299 return starunpack_helper(c, elts,
3300 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003302 else
3303 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305}
3306
3307static int
3308compiler_tuple(struct compiler *c, expr_ty e)
3309{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003310 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003312 return assignment_helper(c, elts);
3313 }
3314 else if (e->v.Tuple.ctx == Load) {
3315 return starunpack_helper(c, elts,
3316 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3317 }
3318 else
3319 VISIT_SEQ(c, expr, elts);
3320 return 1;
3321}
3322
3323static int
3324compiler_set(struct compiler *c, expr_ty e)
3325{
3326 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3327 BUILD_SET, BUILD_SET_UNPACK);
3328}
3329
3330static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003331are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3332{
3333 Py_ssize_t i;
3334 for (i = begin; i < end; i++) {
3335 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3336 if (key == NULL || !is_const(key))
3337 return 0;
3338 }
3339 return 1;
3340}
3341
3342static int
3343compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3344{
3345 Py_ssize_t i, n = end - begin;
3346 PyObject *keys, *key;
3347 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3348 for (i = begin; i < end; i++) {
3349 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3350 }
3351 keys = PyTuple_New(n);
3352 if (keys == NULL) {
3353 return 0;
3354 }
3355 for (i = begin; i < end; i++) {
3356 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3357 Py_INCREF(key);
3358 PyTuple_SET_ITEM(keys, i - begin, key);
3359 }
3360 ADDOP_N(c, LOAD_CONST, keys, consts);
3361 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3362 }
3363 else {
3364 for (i = begin; i < end; i++) {
3365 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3366 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3367 }
3368 ADDOP_I(c, BUILD_MAP, n);
3369 }
3370 return 1;
3371}
3372
3373static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003374compiler_dict(struct compiler *c, expr_ty e)
3375{
Victor Stinner976bb402016-03-23 11:36:19 +01003376 Py_ssize_t i, n, elements;
3377 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003378 int is_unpacking = 0;
3379 n = asdl_seq_LEN(e->v.Dict.values);
3380 containers = 0;
3381 elements = 0;
3382 for (i = 0; i < n; i++) {
3383 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3384 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003385 if (!compiler_subdict(c, e, i - elements, i))
3386 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003387 containers++;
3388 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003390 if (is_unpacking) {
3391 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3392 containers++;
3393 }
3394 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003395 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 }
3397 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003398 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003399 if (!compiler_subdict(c, e, n - elements, n))
3400 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003401 containers++;
3402 }
3403 /* If there is more than one dict, they need to be merged into a new
3404 * dict. If there is one dict and it's an unpacking, then it needs
3405 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003406 if (containers > 1 || is_unpacking) {
3407 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 }
3409 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003410}
3411
3412static int
3413compiler_compare(struct compiler *c, expr_ty e)
3414{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003415 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3419 VISIT(c, expr, e->v.Compare.left);
3420 n = asdl_seq_LEN(e->v.Compare.ops);
3421 assert(n > 0);
3422 if (n > 1) {
3423 cleanup = compiler_new_block(c);
3424 if (cleanup == NULL)
3425 return 0;
3426 VISIT(c, expr,
3427 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3428 }
3429 for (i = 1; i < n; i++) {
3430 ADDOP(c, DUP_TOP);
3431 ADDOP(c, ROT_THREE);
3432 ADDOP_I(c, COMPARE_OP,
3433 cmpop((cmpop_ty)(asdl_seq_GET(
3434 e->v.Compare.ops, i - 1))));
3435 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3436 NEXT_BLOCK(c);
3437 if (i < (n - 1))
3438 VISIT(c, expr,
3439 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3440 }
3441 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3442 ADDOP_I(c, COMPARE_OP,
3443 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3444 if (n > 1) {
3445 basicblock *end = compiler_new_block(c);
3446 if (end == NULL)
3447 return 0;
3448 ADDOP_JREL(c, JUMP_FORWARD, end);
3449 compiler_use_next_block(c, cleanup);
3450 ADDOP(c, ROT_TWO);
3451 ADDOP(c, POP_TOP);
3452 compiler_use_next_block(c, end);
3453 }
3454 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455}
3456
3457static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003458maybe_optimize_method_call(struct compiler *c, expr_ty e)
3459{
3460 Py_ssize_t argsl, i;
3461 expr_ty meth = e->v.Call.func;
3462 asdl_seq *args = e->v.Call.args;
3463
3464 /* Check that the call node is an attribute access, and that
3465 the call doesn't have keyword parameters. */
3466 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3467 asdl_seq_LEN(e->v.Call.keywords))
3468 return -1;
3469
3470 /* Check that there are no *varargs types of arguments. */
3471 argsl = asdl_seq_LEN(args);
3472 for (i = 0; i < argsl; i++) {
3473 expr_ty elt = asdl_seq_GET(args, i);
3474 if (elt->kind == Starred_kind) {
3475 return -1;
3476 }
3477 }
3478
3479 /* Alright, we can optimize the code. */
3480 VISIT(c, expr, meth->v.Attribute.value);
3481 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3482 VISIT_SEQ(c, expr, e->v.Call.args);
3483 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3484 return 1;
3485}
3486
3487static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488compiler_call(struct compiler *c, expr_ty e)
3489{
Yury Selivanovf2392132016-12-13 19:03:51 -05003490 if (maybe_optimize_method_call(c, e) > 0)
3491 return 1;
3492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 VISIT(c, expr, e->v.Call.func);
3494 return compiler_call_helper(c, 0,
3495 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003496 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003497}
3498
Eric V. Smith235a6f02015-09-19 14:51:32 -04003499static int
3500compiler_joined_str(struct compiler *c, expr_ty e)
3501{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003502 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003503 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3504 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003505 return 1;
3506}
3507
Eric V. Smitha78c7952015-11-03 12:45:05 -05003508/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003509static int
3510compiler_formatted_value(struct compiler *c, expr_ty e)
3511{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003512 /* Our oparg encodes 2 pieces of information: the conversion
3513 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003514
Eric V. Smitha78c7952015-11-03 12:45:05 -05003515 Convert the conversion char to 2 bits:
3516 None: 000 0x0 FVC_NONE
3517 !s : 001 0x1 FVC_STR
3518 !r : 010 0x2 FVC_REPR
3519 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003520
Eric V. Smitha78c7952015-11-03 12:45:05 -05003521 next bit is whether or not we have a format spec:
3522 yes : 100 0x4
3523 no : 000 0x0
3524 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003525
Eric V. Smitha78c7952015-11-03 12:45:05 -05003526 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003527
Eric V. Smitha78c7952015-11-03 12:45:05 -05003528 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003529 VISIT(c, expr, e->v.FormattedValue.value);
3530
Eric V. Smitha78c7952015-11-03 12:45:05 -05003531 switch (e->v.FormattedValue.conversion) {
3532 case 's': oparg = FVC_STR; break;
3533 case 'r': oparg = FVC_REPR; break;
3534 case 'a': oparg = FVC_ASCII; break;
3535 case -1: oparg = FVC_NONE; break;
3536 default:
3537 PyErr_SetString(PyExc_SystemError,
3538 "Unrecognized conversion character");
3539 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003540 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003541 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003542 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003543 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003544 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003545 }
3546
Eric V. Smitha78c7952015-11-03 12:45:05 -05003547 /* And push our opcode and oparg */
3548 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003549 return 1;
3550}
3551
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003552static int
3553compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3554{
3555 Py_ssize_t i, n = end - begin;
3556 keyword_ty kw;
3557 PyObject *keys, *key;
3558 assert(n > 0);
3559 if (n > 1) {
3560 for (i = begin; i < end; i++) {
3561 kw = asdl_seq_GET(keywords, i);
3562 VISIT(c, expr, kw->value);
3563 }
3564 keys = PyTuple_New(n);
3565 if (keys == NULL) {
3566 return 0;
3567 }
3568 for (i = begin; i < end; i++) {
3569 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3570 Py_INCREF(key);
3571 PyTuple_SET_ITEM(keys, i - begin, key);
3572 }
3573 ADDOP_N(c, LOAD_CONST, keys, consts);
3574 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3575 }
3576 else {
3577 /* a for loop only executes once */
3578 for (i = begin; i < end; i++) {
3579 kw = asdl_seq_GET(keywords, i);
3580 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3581 VISIT(c, expr, kw->value);
3582 }
3583 ADDOP_I(c, BUILD_MAP, n);
3584 }
3585 return 1;
3586}
3587
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003588/* shared code between compiler_call and compiler_class */
3589static int
3590compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003591 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003592 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003593 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003594{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003595 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003596 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003597
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003598 /* the number of tuples and dictionaries on the stack */
3599 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3600
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003601 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003602 nkwelts = asdl_seq_LEN(keywords);
3603
3604 for (i = 0; i < nkwelts; i++) {
3605 keyword_ty kw = asdl_seq_GET(keywords, i);
3606 if (kw->arg == NULL) {
3607 mustdictunpack = 1;
3608 break;
3609 }
3610 }
3611
3612 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003613 for (i = 0; i < nelts; i++) {
3614 expr_ty elt = asdl_seq_GET(args, i);
3615 if (elt->kind == Starred_kind) {
3616 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003617 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003618 if (nseen) {
3619 ADDOP_I(c, BUILD_TUPLE, nseen);
3620 nseen = 0;
3621 nsubargs++;
3622 }
3623 VISIT(c, expr, elt->v.Starred.value);
3624 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003625 }
3626 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003627 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003628 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003631
3632 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003633 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003634 if (nseen) {
3635 /* Pack up any trailing positional arguments. */
3636 ADDOP_I(c, BUILD_TUPLE, nseen);
3637 nsubargs++;
3638 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003639 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003640 /* If we ended up with more than one stararg, we need
3641 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003642 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003643 }
3644 else if (nsubargs == 0) {
3645 ADDOP_I(c, BUILD_TUPLE, 0);
3646 }
3647 nseen = 0; /* the number of keyword arguments on the stack following */
3648 for (i = 0; i < nkwelts; i++) {
3649 keyword_ty kw = asdl_seq_GET(keywords, i);
3650 if (kw->arg == NULL) {
3651 /* A keyword argument unpacking. */
3652 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003653 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3654 return 0;
3655 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003656 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003657 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003658 VISIT(c, expr, kw->value);
3659 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003660 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003661 else {
3662 nseen++;
3663 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003664 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003665 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003666 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003667 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003668 return 0;
3669 nsubkwargs++;
3670 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003671 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003672 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003673 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003674 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003675 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3676 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003678 else if (nkwelts) {
3679 PyObject *names;
3680 VISIT_SEQ(c, keyword, keywords);
3681 names = PyTuple_New(nkwelts);
3682 if (names == NULL) {
3683 return 0;
3684 }
3685 for (i = 0; i < nkwelts; i++) {
3686 keyword_ty kw = asdl_seq_GET(keywords, i);
3687 Py_INCREF(kw->arg);
3688 PyTuple_SET_ITEM(names, i, kw->arg);
3689 }
3690 ADDOP_N(c, LOAD_CONST, names, consts);
3691 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3692 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003694 else {
3695 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3696 return 1;
3697 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698}
3699
Nick Coghlan650f0d02007-04-15 12:05:43 +00003700
3701/* List and set comprehensions and generator expressions work by creating a
3702 nested function to perform the actual iteration. This means that the
3703 iteration variables don't leak into the current scope.
3704 The defined function is called immediately following its definition, with the
3705 result of that call being the result of the expression.
3706 The LC/SC version returns the populated container, while the GE version is
3707 flagged in symtable.c as a generator, so it returns the generator object
3708 when the function is called.
3709 This code *knows* that the loop cannot contain break, continue, or return,
3710 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3711
3712 Possible cleanups:
3713 - iterate over the generator sequence instead of using recursion
3714*/
3715
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718compiler_comprehension_generator(struct compiler *c,
3719 asdl_seq *generators, int gen_index,
3720 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003722 comprehension_ty gen;
3723 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3724 if (gen->is_async) {
3725 return compiler_async_comprehension_generator(
3726 c, generators, gen_index, elt, val, type);
3727 } else {
3728 return compiler_sync_comprehension_generator(
3729 c, generators, gen_index, elt, val, type);
3730 }
3731}
3732
3733static int
3734compiler_sync_comprehension_generator(struct compiler *c,
3735 asdl_seq *generators, int gen_index,
3736 expr_ty elt, expr_ty val, int type)
3737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 /* generate code for the iterator, then each of the ifs,
3739 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 comprehension_ty gen;
3742 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003743 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 start = compiler_new_block(c);
3746 skip = compiler_new_block(c);
3747 if_cleanup = compiler_new_block(c);
3748 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3751 anchor == NULL)
3752 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 if (gen_index == 0) {
3757 /* Receive outermost iter as an implicit argument */
3758 c->u->u_argcount = 1;
3759 ADDOP_I(c, LOAD_FAST, 0);
3760 }
3761 else {
3762 /* Sub-iter - calculate on the fly */
3763 VISIT(c, expr, gen->iter);
3764 ADDOP(c, GET_ITER);
3765 }
3766 compiler_use_next_block(c, start);
3767 ADDOP_JREL(c, FOR_ITER, anchor);
3768 NEXT_BLOCK(c);
3769 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 /* XXX this needs to be cleaned up...a lot! */
3772 n = asdl_seq_LEN(gen->ifs);
3773 for (i = 0; i < n; i++) {
3774 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003775 if (!compiler_jump_if(c, e, if_cleanup, 0))
3776 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 NEXT_BLOCK(c);
3778 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 if (++gen_index < asdl_seq_LEN(generators))
3781 if (!compiler_comprehension_generator(c,
3782 generators, gen_index,
3783 elt, val, type))
3784 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 /* only append after the last for generator */
3787 if (gen_index >= asdl_seq_LEN(generators)) {
3788 /* comprehension specific code */
3789 switch (type) {
3790 case COMP_GENEXP:
3791 VISIT(c, expr, elt);
3792 ADDOP(c, YIELD_VALUE);
3793 ADDOP(c, POP_TOP);
3794 break;
3795 case COMP_LISTCOMP:
3796 VISIT(c, expr, elt);
3797 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3798 break;
3799 case COMP_SETCOMP:
3800 VISIT(c, expr, elt);
3801 ADDOP_I(c, SET_ADD, gen_index + 1);
3802 break;
3803 case COMP_DICTCOMP:
3804 /* With 'd[k] = v', v is evaluated before k, so we do
3805 the same. */
3806 VISIT(c, expr, val);
3807 VISIT(c, expr, elt);
3808 ADDOP_I(c, MAP_ADD, gen_index + 1);
3809 break;
3810 default:
3811 return 0;
3812 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 compiler_use_next_block(c, skip);
3815 }
3816 compiler_use_next_block(c, if_cleanup);
3817 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3818 compiler_use_next_block(c, anchor);
3819
3820 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821}
3822
3823static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003824compiler_async_comprehension_generator(struct compiler *c,
3825 asdl_seq *generators, int gen_index,
3826 expr_ty elt, expr_ty val, int type)
3827{
3828 _Py_IDENTIFIER(StopAsyncIteration);
3829
3830 comprehension_ty gen;
3831 basicblock *anchor, *skip, *if_cleanup, *try,
3832 *after_try, *except, *try_cleanup;
3833 Py_ssize_t i, n;
3834
3835 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3836 if (stop_aiter_error == NULL) {
3837 return 0;
3838 }
3839
3840 try = compiler_new_block(c);
3841 after_try = compiler_new_block(c);
3842 try_cleanup = compiler_new_block(c);
3843 except = compiler_new_block(c);
3844 skip = compiler_new_block(c);
3845 if_cleanup = compiler_new_block(c);
3846 anchor = compiler_new_block(c);
3847
3848 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3849 try == NULL || after_try == NULL ||
3850 except == NULL || after_try == NULL) {
3851 return 0;
3852 }
3853
3854 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3855
3856 if (gen_index == 0) {
3857 /* Receive outermost iter as an implicit argument */
3858 c->u->u_argcount = 1;
3859 ADDOP_I(c, LOAD_FAST, 0);
3860 }
3861 else {
3862 /* Sub-iter - calculate on the fly */
3863 VISIT(c, expr, gen->iter);
3864 ADDOP(c, GET_AITER);
3865 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3866 ADDOP(c, YIELD_FROM);
3867 }
3868
3869 compiler_use_next_block(c, try);
3870
3871
3872 ADDOP_JREL(c, SETUP_EXCEPT, except);
3873 if (!compiler_push_fblock(c, EXCEPT, try))
3874 return 0;
3875
3876 ADDOP(c, GET_ANEXT);
3877 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3878 ADDOP(c, YIELD_FROM);
3879 VISIT(c, expr, gen->target);
3880 ADDOP(c, POP_BLOCK);
3881 compiler_pop_fblock(c, EXCEPT, try);
3882 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3883
3884
3885 compiler_use_next_block(c, except);
3886 ADDOP(c, DUP_TOP);
3887 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3888 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3889 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3890
3891 ADDOP(c, POP_TOP);
3892 ADDOP(c, POP_TOP);
3893 ADDOP(c, POP_TOP);
3894 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3895 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3896
3897
3898 compiler_use_next_block(c, try_cleanup);
3899 ADDOP(c, END_FINALLY);
3900
3901 compiler_use_next_block(c, after_try);
3902
3903 n = asdl_seq_LEN(gen->ifs);
3904 for (i = 0; i < n; i++) {
3905 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003906 if (!compiler_jump_if(c, e, if_cleanup, 0))
3907 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003908 NEXT_BLOCK(c);
3909 }
3910
3911 if (++gen_index < asdl_seq_LEN(generators))
3912 if (!compiler_comprehension_generator(c,
3913 generators, gen_index,
3914 elt, val, type))
3915 return 0;
3916
3917 /* only append after the last for generator */
3918 if (gen_index >= asdl_seq_LEN(generators)) {
3919 /* comprehension specific code */
3920 switch (type) {
3921 case COMP_GENEXP:
3922 VISIT(c, expr, elt);
3923 ADDOP(c, YIELD_VALUE);
3924 ADDOP(c, POP_TOP);
3925 break;
3926 case COMP_LISTCOMP:
3927 VISIT(c, expr, elt);
3928 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3929 break;
3930 case COMP_SETCOMP:
3931 VISIT(c, expr, elt);
3932 ADDOP_I(c, SET_ADD, gen_index + 1);
3933 break;
3934 case COMP_DICTCOMP:
3935 /* With 'd[k] = v', v is evaluated before k, so we do
3936 the same. */
3937 VISIT(c, expr, val);
3938 VISIT(c, expr, elt);
3939 ADDOP_I(c, MAP_ADD, gen_index + 1);
3940 break;
3941 default:
3942 return 0;
3943 }
3944
3945 compiler_use_next_block(c, skip);
3946 }
3947 compiler_use_next_block(c, if_cleanup);
3948 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3949 compiler_use_next_block(c, anchor);
3950 ADDOP(c, POP_TOP);
3951
3952 return 1;
3953}
3954
3955static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003956compiler_comprehension(struct compiler *c, expr_ty e, int type,
3957 identifier name, asdl_seq *generators, expr_ty elt,
3958 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003961 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003962 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003963 int is_async_function = c->u->u_ste->ste_coroutine;
3964 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003965
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003967
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003968 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3969 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003970 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 }
3973
3974 is_async_generator = c->u->u_ste->ste_coroutine;
3975
3976 if (is_async_generator && !is_async_function) {
3977 if (e->lineno > c->u->u_lineno) {
3978 c->u->u_lineno = e->lineno;
3979 c->u->u_lineno_set = 0;
3980 }
3981 compiler_error(c, "asynchronous comprehension outside of "
3982 "an asynchronous function");
3983 goto error_in_scope;
3984 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 if (type != COMP_GENEXP) {
3987 int op;
3988 switch (type) {
3989 case COMP_LISTCOMP:
3990 op = BUILD_LIST;
3991 break;
3992 case COMP_SETCOMP:
3993 op = BUILD_SET;
3994 break;
3995 case COMP_DICTCOMP:
3996 op = BUILD_MAP;
3997 break;
3998 default:
3999 PyErr_Format(PyExc_SystemError,
4000 "unknown comprehension type %d", type);
4001 goto error_in_scope;
4002 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 ADDOP_I(c, op, 0);
4005 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 if (!compiler_comprehension_generator(c, generators, 0, elt,
4008 val, type))
4009 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 if (type != COMP_GENEXP) {
4012 ADDOP(c, RETURN_VALUE);
4013 }
4014
4015 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004016 qualname = c->u->u_qualname;
4017 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004019 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 goto error;
4021
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004022 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004024 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 Py_DECREF(co);
4026
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004027 VISIT(c, expr, outermost->iter);
4028
4029 if (outermost->is_async) {
4030 ADDOP(c, GET_AITER);
4031 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4032 ADDOP(c, YIELD_FROM);
4033 } else {
4034 ADDOP(c, GET_ITER);
4035 }
4036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004038
4039 if (is_async_generator && type != COMP_GENEXP) {
4040 ADDOP(c, GET_AWAITABLE);
4041 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4042 ADDOP(c, YIELD_FROM);
4043 }
4044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004046error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004048error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004049 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 Py_XDECREF(co);
4051 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004052}
4053
4054static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004055compiler_genexp(struct compiler *c, expr_ty e)
4056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 static identifier name;
4058 if (!name) {
4059 name = PyUnicode_FromString("<genexpr>");
4060 if (!name)
4061 return 0;
4062 }
4063 assert(e->kind == GeneratorExp_kind);
4064 return compiler_comprehension(c, e, COMP_GENEXP, name,
4065 e->v.GeneratorExp.generators,
4066 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067}
4068
4069static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004070compiler_listcomp(struct compiler *c, expr_ty e)
4071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 static identifier name;
4073 if (!name) {
4074 name = PyUnicode_FromString("<listcomp>");
4075 if (!name)
4076 return 0;
4077 }
4078 assert(e->kind == ListComp_kind);
4079 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4080 e->v.ListComp.generators,
4081 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004082}
4083
4084static int
4085compiler_setcomp(struct compiler *c, expr_ty e)
4086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 static identifier name;
4088 if (!name) {
4089 name = PyUnicode_FromString("<setcomp>");
4090 if (!name)
4091 return 0;
4092 }
4093 assert(e->kind == SetComp_kind);
4094 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4095 e->v.SetComp.generators,
4096 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004097}
4098
4099
4100static int
4101compiler_dictcomp(struct compiler *c, expr_ty e)
4102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 static identifier name;
4104 if (!name) {
4105 name = PyUnicode_FromString("<dictcomp>");
4106 if (!name)
4107 return 0;
4108 }
4109 assert(e->kind == DictComp_kind);
4110 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4111 e->v.DictComp.generators,
4112 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004113}
4114
4115
4116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117compiler_visit_keyword(struct compiler *c, keyword_ty k)
4118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 VISIT(c, expr, k->value);
4120 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121}
4122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 whether they are true or false.
4125
4126 Return values: 1 for true, 0 for false, -1 for non-constant.
4127 */
4128
4129static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004130expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004132 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 switch (e->kind) {
4134 case Ellipsis_kind:
4135 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004136 case Constant_kind:
4137 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 case Num_kind:
4139 return PyObject_IsTrue(e->v.Num.n);
4140 case Str_kind:
4141 return PyObject_IsTrue(e->v.Str.s);
4142 case Name_kind:
4143 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004144 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004145 if (id && strcmp(id, "__debug__") == 0)
4146 return !c->c_optimize;
4147 return -1;
4148 case NameConstant_kind: {
4149 PyObject *o = e->v.NameConstant.value;
4150 if (o == Py_None)
4151 return 0;
4152 else if (o == Py_True)
4153 return 1;
4154 else if (o == Py_False)
4155 return 0;
4156 }
Stefan Krahf432a322017-08-21 13:09:59 +02004157 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 default:
4159 return -1;
4160 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161}
4162
Yury Selivanov75445082015-05-11 22:57:16 -04004163
4164/*
4165 Implements the async with statement.
4166
4167 The semantics outlined in that PEP are as follows:
4168
4169 async with EXPR as VAR:
4170 BLOCK
4171
4172 It is implemented roughly as:
4173
4174 context = EXPR
4175 exit = context.__aexit__ # not calling it
4176 value = await context.__aenter__()
4177 try:
4178 VAR = value # if VAR present in the syntax
4179 BLOCK
4180 finally:
4181 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004182 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004183 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004184 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004185 if not (await exit(*exc)):
4186 raise
4187 */
4188static int
4189compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4190{
4191 basicblock *block, *finally;
4192 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4193
4194 assert(s->kind == AsyncWith_kind);
4195
4196 block = compiler_new_block(c);
4197 finally = compiler_new_block(c);
4198 if (!block || !finally)
4199 return 0;
4200
4201 /* Evaluate EXPR */
4202 VISIT(c, expr, item->context_expr);
4203
4204 ADDOP(c, BEFORE_ASYNC_WITH);
4205 ADDOP(c, GET_AWAITABLE);
4206 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4207 ADDOP(c, YIELD_FROM);
4208
4209 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4210
4211 /* SETUP_ASYNC_WITH pushes a finally block. */
4212 compiler_use_next_block(c, block);
4213 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4214 return 0;
4215 }
4216
4217 if (item->optional_vars) {
4218 VISIT(c, expr, item->optional_vars);
4219 }
4220 else {
4221 /* Discard result from context.__aenter__() */
4222 ADDOP(c, POP_TOP);
4223 }
4224
4225 pos++;
4226 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4227 /* BLOCK code */
4228 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4229 else if (!compiler_async_with(c, s, pos))
4230 return 0;
4231
4232 /* End of try block; start the finally block */
4233 ADDOP(c, POP_BLOCK);
4234 compiler_pop_fblock(c, FINALLY_TRY, block);
4235
4236 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4237 compiler_use_next_block(c, finally);
4238 if (!compiler_push_fblock(c, FINALLY_END, finally))
4239 return 0;
4240
4241 /* Finally block starts; context.__exit__ is on the stack under
4242 the exception or return information. Just issue our magic
4243 opcode. */
4244 ADDOP(c, WITH_CLEANUP_START);
4245
4246 ADDOP(c, GET_AWAITABLE);
4247 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4248 ADDOP(c, YIELD_FROM);
4249
4250 ADDOP(c, WITH_CLEANUP_FINISH);
4251
4252 /* Finally block ends. */
4253 ADDOP(c, END_FINALLY);
4254 compiler_pop_fblock(c, FINALLY_END, finally);
4255 return 1;
4256}
4257
4258
Guido van Rossumc2e20742006-02-27 22:32:47 +00004259/*
4260 Implements the with statement from PEP 343.
4261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004263
4264 with EXPR as VAR:
4265 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266
Guido van Rossumc2e20742006-02-27 22:32:47 +00004267 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268
Thomas Wouters477c8d52006-05-27 19:21:47 +00004269 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004270 exit = context.__exit__ # not calling it
4271 value = context.__enter__()
4272 try:
4273 VAR = value # if VAR present in the syntax
4274 BLOCK
4275 finally:
4276 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004277 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004278 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004279 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004280 exit(*exc)
4281 */
4282static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004283compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004284{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004285 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004286 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004287
4288 assert(s->kind == With_kind);
4289
Guido van Rossumc2e20742006-02-27 22:32:47 +00004290 block = compiler_new_block(c);
4291 finally = compiler_new_block(c);
4292 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004293 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004294
Thomas Wouters477c8d52006-05-27 19:21:47 +00004295 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004296 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004297 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004298
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004299 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004300 compiler_use_next_block(c, block);
4301 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004302 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004303 }
4304
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004305 if (item->optional_vars) {
4306 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004307 }
4308 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004310 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004311 }
4312
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004313 pos++;
4314 if (pos == asdl_seq_LEN(s->v.With.items))
4315 /* BLOCK code */
4316 VISIT_SEQ(c, stmt, s->v.With.body)
4317 else if (!compiler_with(c, s, pos))
4318 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004319
4320 /* End of try block; start the finally block */
4321 ADDOP(c, POP_BLOCK);
4322 compiler_pop_fblock(c, FINALLY_TRY, block);
4323
4324 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4325 compiler_use_next_block(c, finally);
4326 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004327 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004328
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004329 /* Finally block starts; context.__exit__ is on the stack under
4330 the exception or return information. Just issue our magic
4331 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004332 ADDOP(c, WITH_CLEANUP_START);
4333 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004334
4335 /* Finally block ends. */
4336 ADDOP(c, END_FINALLY);
4337 compiler_pop_fblock(c, FINALLY_END, finally);
4338 return 1;
4339}
4340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004341static int
4342compiler_visit_expr(struct compiler *c, expr_ty e)
4343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 /* If expr e has a different line number than the last expr/stmt,
4345 set a new line number for the next instruction.
4346 */
4347 if (e->lineno > c->u->u_lineno) {
4348 c->u->u_lineno = e->lineno;
4349 c->u->u_lineno_set = 0;
4350 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004351 /* Updating the column offset is always harmless. */
4352 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 switch (e->kind) {
4354 case BoolOp_kind:
4355 return compiler_boolop(c, e);
4356 case BinOp_kind:
4357 VISIT(c, expr, e->v.BinOp.left);
4358 VISIT(c, expr, e->v.BinOp.right);
4359 ADDOP(c, binop(c, e->v.BinOp.op));
4360 break;
4361 case UnaryOp_kind:
4362 VISIT(c, expr, e->v.UnaryOp.operand);
4363 ADDOP(c, unaryop(e->v.UnaryOp.op));
4364 break;
4365 case Lambda_kind:
4366 return compiler_lambda(c, e);
4367 case IfExp_kind:
4368 return compiler_ifexp(c, e);
4369 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004370 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004372 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 case GeneratorExp_kind:
4374 return compiler_genexp(c, e);
4375 case ListComp_kind:
4376 return compiler_listcomp(c, e);
4377 case SetComp_kind:
4378 return compiler_setcomp(c, e);
4379 case DictComp_kind:
4380 return compiler_dictcomp(c, e);
4381 case Yield_kind:
4382 if (c->u->u_ste->ste_type != FunctionBlock)
4383 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004384 if (e->v.Yield.value) {
4385 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 }
4387 else {
4388 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4389 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004390 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004392 case YieldFrom_kind:
4393 if (c->u->u_ste->ste_type != FunctionBlock)
4394 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004395
4396 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4397 return compiler_error(c, "'yield from' inside async function");
4398
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004399 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004400 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004401 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4402 ADDOP(c, YIELD_FROM);
4403 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004404 case Await_kind:
4405 if (c->u->u_ste->ste_type != FunctionBlock)
4406 return compiler_error(c, "'await' outside function");
4407
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004408 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4409 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004410 return compiler_error(c, "'await' outside async function");
4411
4412 VISIT(c, expr, e->v.Await.value);
4413 ADDOP(c, GET_AWAITABLE);
4414 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4415 ADDOP(c, YIELD_FROM);
4416 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 case Compare_kind:
4418 return compiler_compare(c, e);
4419 case Call_kind:
4420 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004421 case Constant_kind:
4422 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4423 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 case Num_kind:
4425 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4426 break;
4427 case Str_kind:
4428 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4429 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004430 case JoinedStr_kind:
4431 return compiler_joined_str(c, e);
4432 case FormattedValue_kind:
4433 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 case Bytes_kind:
4435 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4436 break;
4437 case Ellipsis_kind:
4438 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4439 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004440 case NameConstant_kind:
4441 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4442 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 /* The following exprs can be assignment targets. */
4444 case Attribute_kind:
4445 if (e->v.Attribute.ctx != AugStore)
4446 VISIT(c, expr, e->v.Attribute.value);
4447 switch (e->v.Attribute.ctx) {
4448 case AugLoad:
4449 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004450 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 case Load:
4452 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4453 break;
4454 case AugStore:
4455 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004456 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 case Store:
4458 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4459 break;
4460 case Del:
4461 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4462 break;
4463 case Param:
4464 default:
4465 PyErr_SetString(PyExc_SystemError,
4466 "param invalid in attribute expression");
4467 return 0;
4468 }
4469 break;
4470 case Subscript_kind:
4471 switch (e->v.Subscript.ctx) {
4472 case AugLoad:
4473 VISIT(c, expr, e->v.Subscript.value);
4474 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4475 break;
4476 case Load:
4477 VISIT(c, expr, e->v.Subscript.value);
4478 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4479 break;
4480 case AugStore:
4481 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4482 break;
4483 case Store:
4484 VISIT(c, expr, e->v.Subscript.value);
4485 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4486 break;
4487 case Del:
4488 VISIT(c, expr, e->v.Subscript.value);
4489 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4490 break;
4491 case Param:
4492 default:
4493 PyErr_SetString(PyExc_SystemError,
4494 "param invalid in subscript expression");
4495 return 0;
4496 }
4497 break;
4498 case Starred_kind:
4499 switch (e->v.Starred.ctx) {
4500 case Store:
4501 /* In all legitimate cases, the Starred node was already replaced
4502 * by compiler_list/compiler_tuple. XXX: is that okay? */
4503 return compiler_error(c,
4504 "starred assignment target must be in a list or tuple");
4505 default:
4506 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004507 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 }
4509 break;
4510 case Name_kind:
4511 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4512 /* child nodes of List and Tuple will have expr_context set */
4513 case List_kind:
4514 return compiler_list(c, e);
4515 case Tuple_kind:
4516 return compiler_tuple(c, e);
4517 }
4518 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004519}
4520
4521static int
4522compiler_augassign(struct compiler *c, stmt_ty s)
4523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 expr_ty e = s->v.AugAssign.target;
4525 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 switch (e->kind) {
4530 case Attribute_kind:
4531 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4532 AugLoad, e->lineno, e->col_offset, c->c_arena);
4533 if (auge == NULL)
4534 return 0;
4535 VISIT(c, expr, auge);
4536 VISIT(c, expr, s->v.AugAssign.value);
4537 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4538 auge->v.Attribute.ctx = AugStore;
4539 VISIT(c, expr, auge);
4540 break;
4541 case Subscript_kind:
4542 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4543 AugLoad, e->lineno, e->col_offset, c->c_arena);
4544 if (auge == NULL)
4545 return 0;
4546 VISIT(c, expr, auge);
4547 VISIT(c, expr, s->v.AugAssign.value);
4548 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4549 auge->v.Subscript.ctx = AugStore;
4550 VISIT(c, expr, auge);
4551 break;
4552 case Name_kind:
4553 if (!compiler_nameop(c, e->v.Name.id, Load))
4554 return 0;
4555 VISIT(c, expr, s->v.AugAssign.value);
4556 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4557 return compiler_nameop(c, e->v.Name.id, Store);
4558 default:
4559 PyErr_Format(PyExc_SystemError,
4560 "invalid node type (%d) for augmented assignment",
4561 e->kind);
4562 return 0;
4563 }
4564 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004565}
4566
4567static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004568check_ann_expr(struct compiler *c, expr_ty e)
4569{
4570 VISIT(c, expr, e);
4571 ADDOP(c, POP_TOP);
4572 return 1;
4573}
4574
4575static int
4576check_annotation(struct compiler *c, stmt_ty s)
4577{
4578 /* Annotations are only evaluated in a module or class. */
4579 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4580 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4581 return check_ann_expr(c, s->v.AnnAssign.annotation);
4582 }
4583 return 1;
4584}
4585
4586static int
4587check_ann_slice(struct compiler *c, slice_ty sl)
4588{
4589 switch(sl->kind) {
4590 case Index_kind:
4591 return check_ann_expr(c, sl->v.Index.value);
4592 case Slice_kind:
4593 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4594 return 0;
4595 }
4596 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4597 return 0;
4598 }
4599 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4600 return 0;
4601 }
4602 break;
4603 default:
4604 PyErr_SetString(PyExc_SystemError,
4605 "unexpected slice kind");
4606 return 0;
4607 }
4608 return 1;
4609}
4610
4611static int
4612check_ann_subscr(struct compiler *c, slice_ty sl)
4613{
4614 /* We check that everything in a subscript is defined at runtime. */
4615 Py_ssize_t i, n;
4616
4617 switch (sl->kind) {
4618 case Index_kind:
4619 case Slice_kind:
4620 if (!check_ann_slice(c, sl)) {
4621 return 0;
4622 }
4623 break;
4624 case ExtSlice_kind:
4625 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4626 for (i = 0; i < n; i++) {
4627 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4628 switch (subsl->kind) {
4629 case Index_kind:
4630 case Slice_kind:
4631 if (!check_ann_slice(c, subsl)) {
4632 return 0;
4633 }
4634 break;
4635 case ExtSlice_kind:
4636 default:
4637 PyErr_SetString(PyExc_SystemError,
4638 "extended slice invalid in nested slice");
4639 return 0;
4640 }
4641 }
4642 break;
4643 default:
4644 PyErr_Format(PyExc_SystemError,
4645 "invalid subscript kind %d", sl->kind);
4646 return 0;
4647 }
4648 return 1;
4649}
4650
4651static int
4652compiler_annassign(struct compiler *c, stmt_ty s)
4653{
4654 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004655 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004656
4657 assert(s->kind == AnnAssign_kind);
4658
4659 /* We perform the actual assignment first. */
4660 if (s->v.AnnAssign.value) {
4661 VISIT(c, expr, s->v.AnnAssign.value);
4662 VISIT(c, expr, targ);
4663 }
4664 switch (targ->kind) {
4665 case Name_kind:
4666 /* If we have a simple name in a module or class, store annotation. */
4667 if (s->v.AnnAssign.simple &&
4668 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4669 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004670 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4671 if (!mangled) {
4672 return 0;
4673 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004674 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004675 /* ADDOP_N decrefs its argument */
4676 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004677 }
4678 break;
4679 case Attribute_kind:
4680 if (!s->v.AnnAssign.value &&
4681 !check_ann_expr(c, targ->v.Attribute.value)) {
4682 return 0;
4683 }
4684 break;
4685 case Subscript_kind:
4686 if (!s->v.AnnAssign.value &&
4687 (!check_ann_expr(c, targ->v.Subscript.value) ||
4688 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4689 return 0;
4690 }
4691 break;
4692 default:
4693 PyErr_Format(PyExc_SystemError,
4694 "invalid node type (%d) for annotated assignment",
4695 targ->kind);
4696 return 0;
4697 }
4698 /* Annotation is evaluated last. */
4699 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4700 return 0;
4701 }
4702 return 1;
4703}
4704
4705static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004706compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 struct fblockinfo *f;
4709 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004710 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 "too many statically nested blocks");
4712 return 0;
4713 }
4714 f = &c->u->u_fblock[c->u->u_nfblocks++];
4715 f->fb_type = t;
4716 f->fb_block = b;
4717 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004718}
4719
4720static void
4721compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 struct compiler_unit *u = c->u;
4724 assert(u->u_nfblocks > 0);
4725 u->u_nfblocks--;
4726 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4727 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004728}
4729
Thomas Wouters89f507f2006-12-13 04:49:30 +00004730static int
4731compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 int i;
4733 struct compiler_unit *u = c->u;
4734 for (i = 0; i < u->u_nfblocks; ++i) {
4735 if (u->u_fblock[i].fb_type == LOOP)
4736 return 1;
4737 }
4738 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004739}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004740/* Raises a SyntaxError and returns 0.
4741 If something goes wrong, a different exception may be raised.
4742*/
4743
4744static int
4745compiler_error(struct compiler *c, const char *errstr)
4746{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004747 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004749
Victor Stinner14e461d2013-08-26 22:28:21 +02004750 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 if (!loc) {
4752 Py_INCREF(Py_None);
4753 loc = Py_None;
4754 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004755 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004756 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 if (!u)
4758 goto exit;
4759 v = Py_BuildValue("(zO)", errstr, u);
4760 if (!v)
4761 goto exit;
4762 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004763 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 Py_DECREF(loc);
4765 Py_XDECREF(u);
4766 Py_XDECREF(v);
4767 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004768}
4769
4770static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771compiler_handle_subscr(struct compiler *c, const char *kind,
4772 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 /* XXX this code is duplicated */
4777 switch (ctx) {
4778 case AugLoad: /* fall through to Load */
4779 case Load: op = BINARY_SUBSCR; break;
4780 case AugStore:/* fall through to Store */
4781 case Store: op = STORE_SUBSCR; break;
4782 case Del: op = DELETE_SUBSCR; break;
4783 case Param:
4784 PyErr_Format(PyExc_SystemError,
4785 "invalid %s kind %d in subscript\n",
4786 kind, ctx);
4787 return 0;
4788 }
4789 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004790 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 }
4792 else if (ctx == AugStore) {
4793 ADDOP(c, ROT_THREE);
4794 }
4795 ADDOP(c, op);
4796 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004797}
4798
4799static int
4800compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 int n = 2;
4803 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 /* only handles the cases where BUILD_SLICE is emitted */
4806 if (s->v.Slice.lower) {
4807 VISIT(c, expr, s->v.Slice.lower);
4808 }
4809 else {
4810 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4811 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 if (s->v.Slice.upper) {
4814 VISIT(c, expr, s->v.Slice.upper);
4815 }
4816 else {
4817 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4818 }
4819
4820 if (s->v.Slice.step) {
4821 n++;
4822 VISIT(c, expr, s->v.Slice.step);
4823 }
4824 ADDOP_I(c, BUILD_SLICE, n);
4825 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004826}
4827
4828static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4830 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 switch (s->kind) {
4833 case Slice_kind:
4834 return compiler_slice(c, s, ctx);
4835 case Index_kind:
4836 VISIT(c, expr, s->v.Index.value);
4837 break;
4838 case ExtSlice_kind:
4839 default:
4840 PyErr_SetString(PyExc_SystemError,
4841 "extended slice invalid in nested slice");
4842 return 0;
4843 }
4844 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004845}
4846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004847static int
4848compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 char * kindname = NULL;
4851 switch (s->kind) {
4852 case Index_kind:
4853 kindname = "index";
4854 if (ctx != AugStore) {
4855 VISIT(c, expr, s->v.Index.value);
4856 }
4857 break;
4858 case Slice_kind:
4859 kindname = "slice";
4860 if (ctx != AugStore) {
4861 if (!compiler_slice(c, s, ctx))
4862 return 0;
4863 }
4864 break;
4865 case ExtSlice_kind:
4866 kindname = "extended slice";
4867 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004868 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 for (i = 0; i < n; i++) {
4870 slice_ty sub = (slice_ty)asdl_seq_GET(
4871 s->v.ExtSlice.dims, i);
4872 if (!compiler_visit_nested_slice(c, sub, ctx))
4873 return 0;
4874 }
4875 ADDOP_I(c, BUILD_TUPLE, n);
4876 }
4877 break;
4878 default:
4879 PyErr_Format(PyExc_SystemError,
4880 "invalid subscript kind %d", s->kind);
4881 return 0;
4882 }
4883 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004884}
4885
Thomas Wouters89f507f2006-12-13 04:49:30 +00004886/* End of the compiler section, beginning of the assembler section */
4887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004888/* do depth-first search of basic block graph, starting with block.
4889 post records the block indices in post-order.
4890
4891 XXX must handle implicit jumps from one block to next
4892*/
4893
Thomas Wouters89f507f2006-12-13 04:49:30 +00004894struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 PyObject *a_bytecode; /* string containing bytecode */
4896 int a_offset; /* offset into bytecode */
4897 int a_nblocks; /* number of reachable blocks */
4898 basicblock **a_postorder; /* list of blocks in dfs postorder */
4899 PyObject *a_lnotab; /* string containing lnotab */
4900 int a_lnotab_off; /* offset into lnotab */
4901 int a_lineno; /* last lineno of emitted instruction */
4902 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004903};
4904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004905static void
4906dfs(struct compiler *c, basicblock *b, struct assembler *a)
4907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 int i;
4909 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 if (b->b_seen)
4912 return;
4913 b->b_seen = 1;
4914 if (b->b_next != NULL)
4915 dfs(c, b->b_next, a);
4916 for (i = 0; i < b->b_iused; i++) {
4917 instr = &b->b_instr[i];
4918 if (instr->i_jrel || instr->i_jabs)
4919 dfs(c, instr->i_target, a);
4920 }
4921 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004922}
4923
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004924static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004925stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4926{
Larry Hastings3a907972013-11-23 14:49:22 -08004927 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 struct instr *instr;
4929 if (b->b_seen || b->b_startdepth >= depth)
4930 return maxdepth;
4931 b->b_seen = 1;
4932 b->b_startdepth = depth;
4933 for (i = 0; i < b->b_iused; i++) {
4934 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004935 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4936 if (effect == PY_INVALID_STACK_EFFECT) {
4937 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4938 Py_FatalError("PyCompile_OpcodeStackEffect()");
4939 }
4940 depth += effect;
4941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 if (depth > maxdepth)
4943 maxdepth = depth;
4944 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4945 if (instr->i_jrel || instr->i_jabs) {
4946 target_depth = depth;
4947 if (instr->i_opcode == FOR_ITER) {
4948 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004949 }
4950 else if (instr->i_opcode == SETUP_FINALLY ||
4951 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 target_depth = depth+3;
4953 if (target_depth > maxdepth)
4954 maxdepth = target_depth;
4955 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004956 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4957 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4958 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004959 maxdepth = stackdepth_walk(c, instr->i_target,
4960 target_depth, maxdepth);
4961 if (instr->i_opcode == JUMP_ABSOLUTE ||
4962 instr->i_opcode == JUMP_FORWARD) {
4963 goto out; /* remaining code is dead */
4964 }
4965 }
4966 }
4967 if (b->b_next)
4968 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004969out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 b->b_seen = 0;
4971 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004972}
4973
4974/* Find the flow path that needs the largest stack. We assume that
4975 * cycles in the flow graph have no net effect on the stack depth.
4976 */
4977static int
4978stackdepth(struct compiler *c)
4979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 basicblock *b, *entryblock;
4981 entryblock = NULL;
4982 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4983 b->b_seen = 0;
4984 b->b_startdepth = INT_MIN;
4985 entryblock = b;
4986 }
4987 if (!entryblock)
4988 return 0;
4989 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004990}
4991
4992static int
4993assemble_init(struct assembler *a, int nblocks, int firstlineno)
4994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 memset(a, 0, sizeof(struct assembler));
4996 a->a_lineno = firstlineno;
4997 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4998 if (!a->a_bytecode)
4999 return 0;
5000 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5001 if (!a->a_lnotab)
5002 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005003 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 PyErr_NoMemory();
5005 return 0;
5006 }
5007 a->a_postorder = (basicblock **)PyObject_Malloc(
5008 sizeof(basicblock *) * nblocks);
5009 if (!a->a_postorder) {
5010 PyErr_NoMemory();
5011 return 0;
5012 }
5013 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005014}
5015
5016static void
5017assemble_free(struct assembler *a)
5018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 Py_XDECREF(a->a_bytecode);
5020 Py_XDECREF(a->a_lnotab);
5021 if (a->a_postorder)
5022 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005023}
5024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005025static int
5026blocksize(basicblock *b)
5027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 int i;
5029 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005032 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005034}
5035
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005036/* Appends a pair to the end of the line number table, a_lnotab, representing
5037 the instruction's bytecode offset and line number. See
5038 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005039
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005040static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005041assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005044 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005046
Serhiy Storchakaab874002016-09-11 13:48:15 +03005047 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 if(d_bytecode == 0 && d_lineno == 0)
5053 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 if (d_bytecode > 255) {
5056 int j, nbytes, ncodes = d_bytecode / 255;
5057 nbytes = a->a_lnotab_off + 2 * ncodes;
5058 len = PyBytes_GET_SIZE(a->a_lnotab);
5059 if (nbytes >= len) {
5060 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5061 len = nbytes;
5062 else if (len <= INT_MAX / 2)
5063 len *= 2;
5064 else {
5065 PyErr_NoMemory();
5066 return 0;
5067 }
5068 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5069 return 0;
5070 }
5071 lnotab = (unsigned char *)
5072 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5073 for (j = 0; j < ncodes; j++) {
5074 *lnotab++ = 255;
5075 *lnotab++ = 0;
5076 }
5077 d_bytecode -= ncodes * 255;
5078 a->a_lnotab_off += ncodes * 2;
5079 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005080 assert(0 <= d_bytecode && d_bytecode <= 255);
5081
5082 if (d_lineno < -128 || 127 < d_lineno) {
5083 int j, nbytes, ncodes, k;
5084 if (d_lineno < 0) {
5085 k = -128;
5086 /* use division on positive numbers */
5087 ncodes = (-d_lineno) / 128;
5088 }
5089 else {
5090 k = 127;
5091 ncodes = d_lineno / 127;
5092 }
5093 d_lineno -= ncodes * k;
5094 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 nbytes = a->a_lnotab_off + 2 * ncodes;
5096 len = PyBytes_GET_SIZE(a->a_lnotab);
5097 if (nbytes >= len) {
5098 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5099 len = nbytes;
5100 else if (len <= INT_MAX / 2)
5101 len *= 2;
5102 else {
5103 PyErr_NoMemory();
5104 return 0;
5105 }
5106 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5107 return 0;
5108 }
5109 lnotab = (unsigned char *)
5110 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5111 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005112 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 d_bytecode = 0;
5114 for (j = 1; j < ncodes; j++) {
5115 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005116 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 a->a_lnotab_off += ncodes * 2;
5119 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005120 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 len = PyBytes_GET_SIZE(a->a_lnotab);
5123 if (a->a_lnotab_off + 2 >= len) {
5124 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5125 return 0;
5126 }
5127 lnotab = (unsigned char *)
5128 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 a->a_lnotab_off += 2;
5131 if (d_bytecode) {
5132 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005133 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 }
5135 else { /* First line of a block; def stmt, etc. */
5136 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005137 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 }
5139 a->a_lineno = i->i_lineno;
5140 a->a_lineno_off = a->a_offset;
5141 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005142}
5143
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005144/* assemble_emit()
5145 Extend the bytecode with a new instruction.
5146 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005147*/
5148
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005150assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005151{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005152 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005154 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005155
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005156 arg = i->i_oparg;
5157 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 if (i->i_lineno && !assemble_lnotab(a, i))
5159 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005160 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 if (len > PY_SSIZE_T_MAX / 2)
5162 return 0;
5163 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5164 return 0;
5165 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005166 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005168 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005170}
5171
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005172static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005173assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005176 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 /* Compute the size of each block and fixup jump args.
5180 Replace block pointer with position in bytecode. */
5181 do {
5182 totsize = 0;
5183 for (i = a->a_nblocks - 1; i >= 0; i--) {
5184 b = a->a_postorder[i];
5185 bsize = blocksize(b);
5186 b->b_offset = totsize;
5187 totsize += bsize;
5188 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005189 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5191 bsize = b->b_offset;
5192 for (i = 0; i < b->b_iused; i++) {
5193 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005194 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 /* Relative jumps are computed relative to
5196 the instruction pointer after fetching
5197 the jump instruction.
5198 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005199 bsize += isize;
5200 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005202 if (instr->i_jrel) {
5203 instr->i_oparg -= bsize;
5204 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005205 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005206 if (instrsize(instr->i_oparg) != isize) {
5207 extended_arg_recompile = 1;
5208 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 }
5211 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 /* XXX: This is an awful hack that could hurt performance, but
5214 on the bright side it should work until we come up
5215 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 The issue is that in the first loop blocksize() is called
5218 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005219 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 So we loop until we stop seeing new EXTENDED_ARGs.
5223 The only EXTENDED_ARGs that could be popping up are
5224 ones in jump instructions. So this should converge
5225 fairly quickly.
5226 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005227 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005228}
5229
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005230static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005231dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005234 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 tuple = PyTuple_New(size);
5237 if (tuple == NULL)
5238 return NULL;
5239 while (PyDict_Next(dict, &pos, &k, &v)) {
5240 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005241 /* The keys of the dictionary are tuples. (see compiler_add_o
5242 * and _PyCode_ConstantKey). The object we want is always second,
5243 * though. */
5244 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 Py_INCREF(k);
5246 assert((i - offset) < size);
5247 assert((i - offset) >= 0);
5248 PyTuple_SET_ITEM(tuple, i - offset, k);
5249 }
5250 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005251}
5252
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005253static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005254compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005257 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005259 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 if (ste->ste_nested)
5261 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005262 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005264 if (!ste->ste_generator && ste->ste_coroutine)
5265 flags |= CO_COROUTINE;
5266 if (ste->ste_generator && ste->ste_coroutine)
5267 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (ste->ste_varargs)
5269 flags |= CO_VARARGS;
5270 if (ste->ste_varkeywords)
5271 flags |= CO_VARKEYWORDS;
5272 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 /* (Only) inherit compilerflags in PyCF_MASK */
5275 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005276
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005277 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5278 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5279 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005283}
5284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005285static PyCodeObject *
5286makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 PyObject *tmp;
5289 PyCodeObject *co = NULL;
5290 PyObject *consts = NULL;
5291 PyObject *names = NULL;
5292 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 PyObject *name = NULL;
5294 PyObject *freevars = NULL;
5295 PyObject *cellvars = NULL;
5296 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005297 Py_ssize_t nlocals;
5298 int nlocals_int;
5299 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005300 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 tmp = dict_keys_inorder(c->u->u_consts, 0);
5303 if (!tmp)
5304 goto error;
5305 consts = PySequence_List(tmp); /* optimize_code requires a list */
5306 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 names = dict_keys_inorder(c->u->u_names, 0);
5309 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5310 if (!consts || !names || !varnames)
5311 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5314 if (!cellvars)
5315 goto error;
5316 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5317 if (!freevars)
5318 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005319
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005320 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005321 assert(nlocals < INT_MAX);
5322 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 flags = compute_code_flags(c);
5325 if (flags < 0)
5326 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5329 if (!bytecode)
5330 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5333 if (!tmp)
5334 goto error;
5335 Py_DECREF(consts);
5336 consts = tmp;
5337
Victor Stinnerf8e32212013-11-19 23:56:34 +01005338 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5339 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5340 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005341 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 bytecode, consts, names, varnames,
5343 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005344 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 c->u->u_firstlineno,
5346 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005347 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 Py_XDECREF(consts);
5349 Py_XDECREF(names);
5350 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 Py_XDECREF(name);
5352 Py_XDECREF(freevars);
5353 Py_XDECREF(cellvars);
5354 Py_XDECREF(bytecode);
5355 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005356}
5357
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005358
5359/* For debugging purposes only */
5360#if 0
5361static void
5362dump_instr(const struct instr *i)
5363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 const char *jrel = i->i_jrel ? "jrel " : "";
5365 const char *jabs = i->i_jabs ? "jabs " : "";
5366 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005369 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5373 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005374}
5375
5376static void
5377dump_basicblock(const basicblock *b)
5378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 const char *seen = b->b_seen ? "seen " : "";
5380 const char *b_return = b->b_return ? "return " : "";
5381 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5382 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5383 if (b->b_instr) {
5384 int i;
5385 for (i = 0; i < b->b_iused; i++) {
5386 fprintf(stderr, " [%02d] ", i);
5387 dump_instr(b->b_instr + i);
5388 }
5389 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005390}
5391#endif
5392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005393static PyCodeObject *
5394assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 basicblock *b, *entryblock;
5397 struct assembler a;
5398 int i, j, nblocks;
5399 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 /* Make sure every block that falls off the end returns None.
5402 XXX NEXT_BLOCK() isn't quite right, because if the last
5403 block ends with a jump or return b_next shouldn't set.
5404 */
5405 if (!c->u->u_curblock->b_return) {
5406 NEXT_BLOCK(c);
5407 if (addNone)
5408 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5409 ADDOP(c, RETURN_VALUE);
5410 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 nblocks = 0;
5413 entryblock = NULL;
5414 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5415 nblocks++;
5416 entryblock = b;
5417 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 /* Set firstlineno if it wasn't explicitly set. */
5420 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005421 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005422 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5423 else
5424 c->u->u_firstlineno = 1;
5425 }
5426 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5427 goto error;
5428 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005430 /* Can't modify the bytecode after computing jump offsets. */
5431 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 /* Emit code in reverse postorder from dfs. */
5434 for (i = a.a_nblocks - 1; i >= 0; i--) {
5435 b = a.a_postorder[i];
5436 for (j = 0; j < b->b_iused; j++)
5437 if (!assemble_emit(&a, &b->b_instr[j]))
5438 goto error;
5439 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5442 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005443 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 assemble_free(&a);
5449 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005450}
Georg Brandl8334fd92010-12-04 10:26:46 +00005451
5452#undef PyAST_Compile
5453PyAPI_FUNC(PyCodeObject *)
5454PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5455 PyArena *arena)
5456{
5457 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5458}