blob: 064364ea28cb111522f4caca4430a43e81adb1ad [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__);
564 PyObject *tuple, *name, *zero;
565 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 }
578 zero = PyLong_FromLong(0);
579 if (!zero) {
580 Py_DECREF(tuple);
581 compiler_unit_free(u);
582 return 0;
583 }
584 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
585 Py_DECREF(tuple);
586 Py_DECREF(zero);
587 if (res < 0) {
588 compiler_unit_free(u);
589 return 0;
590 }
591 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200594 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (!u->u_freevars) {
596 compiler_unit_free(u);
597 return 0;
598 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 u->u_blocks = NULL;
601 u->u_nfblocks = 0;
602 u->u_firstlineno = lineno;
603 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000604 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_lineno_set = 0;
606 u->u_consts = PyDict_New();
607 if (!u->u_consts) {
608 compiler_unit_free(u);
609 return 0;
610 }
611 u->u_names = PyDict_New();
612 if (!u->u_names) {
613 compiler_unit_free(u);
614 return 0;
615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Push the old compiler_unit on the stack. */
620 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400621 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
623 Py_XDECREF(capsule);
624 compiler_unit_free(u);
625 return 0;
626 }
627 Py_DECREF(capsule);
628 u->u_private = c->u->u_private;
629 Py_XINCREF(u->u_private);
630 }
631 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100634
635 block = compiler_new_block(c);
636 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100638 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400640 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
641 if (!compiler_set_qualname(c))
642 return 0;
643 }
644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646}
647
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000648static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649compiler_exit_scope(struct compiler *c)
650{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100651 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 c->c_nestlevel--;
655 compiler_unit_free(c->u);
656 /* Restore c->u to the parent unit. */
657 n = PyList_GET_SIZE(c->c_stack) - 1;
658 if (n >= 0) {
659 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400660 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 assert(c->u);
662 /* we are deleting from a list so this really shouldn't fail */
663 if (PySequence_DelItem(c->c_stack, n) < 0)
664 Py_FatalError("compiler_exit_scope()");
665 compiler_unit_check(c->u);
666 }
667 else
668 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400672static int
673compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400676 _Py_static_string(dot_locals, ".<locals>");
677 Py_ssize_t stack_size;
678 struct compiler_unit *u = c->u;
679 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100682 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400683 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 if (stack_size > 1) {
685 int scope, force_global = 0;
686 struct compiler_unit *parent;
687 PyObject *mangled, *capsule;
688
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400689 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400690 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 assert(parent);
692
Yury Selivanov75445082015-05-11 22:57:16 -0400693 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
694 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
695 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 assert(u->u_name);
697 mangled = _Py_Mangle(parent->u_private, u->u_name);
698 if (!mangled)
699 return 0;
700 scope = PyST_GetScope(parent->u_ste, mangled);
701 Py_DECREF(mangled);
702 assert(scope != GLOBAL_IMPLICIT);
703 if (scope == GLOBAL_EXPLICIT)
704 force_global = 1;
705 }
706
707 if (!force_global) {
708 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400709 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400710 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
711 dot_locals_str = _PyUnicode_FromId(&dot_locals);
712 if (dot_locals_str == NULL)
713 return 0;
714 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
715 if (base == NULL)
716 return 0;
717 }
718 else {
719 Py_INCREF(parent->u_qualname);
720 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400721 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100722 }
723 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400724
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400725 if (base != NULL) {
726 dot_str = _PyUnicode_FromId(&dot);
727 if (dot_str == NULL) {
728 Py_DECREF(base);
729 return 0;
730 }
731 name = PyUnicode_Concat(base, dot_str);
732 Py_DECREF(base);
733 if (name == NULL)
734 return 0;
735 PyUnicode_Append(&name, u->u_name);
736 if (name == NULL)
737 return 0;
738 }
739 else {
740 Py_INCREF(u->u_name);
741 name = u->u_name;
742 }
743 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100744
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400745 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100746}
747
Eric V. Smith235a6f02015-09-19 14:51:32 -0400748
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749/* Allocate a new block and return a pointer to it.
750 Returns NULL on error.
751*/
752
753static basicblock *
754compiler_new_block(struct compiler *c)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 basicblock *b;
757 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 u = c->u;
760 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
761 if (b == NULL) {
762 PyErr_NoMemory();
763 return NULL;
764 }
765 memset((void *)b, 0, sizeof(basicblock));
766 /* Extend the singly linked list of blocks with new block. */
767 b->b_list = u->u_blocks;
768 u->u_blocks = b;
769 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773compiler_next_block(struct compiler *c)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 basicblock *block = compiler_new_block(c);
776 if (block == NULL)
777 return NULL;
778 c->u->u_curblock->b_next = block;
779 c->u->u_curblock = block;
780 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781}
782
783static basicblock *
784compiler_use_next_block(struct compiler *c, basicblock *block)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 assert(block != NULL);
787 c->u->u_curblock->b_next = block;
788 c->u->u_curblock = block;
789 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790}
791
792/* Returns the offset of the next instruction in the current block's
793 b_instr array. Resizes the b_instr as necessary.
794 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000795*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796
797static int
798compiler_next_instr(struct compiler *c, basicblock *b)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 assert(b != NULL);
801 if (b->b_instr == NULL) {
802 b->b_instr = (struct instr *)PyObject_Malloc(
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 if (b->b_instr == NULL) {
805 PyErr_NoMemory();
806 return -1;
807 }
808 b->b_ialloc = DEFAULT_BLOCK_SIZE;
809 memset((char *)b->b_instr, 0,
810 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
811 }
812 else if (b->b_iused == b->b_ialloc) {
813 struct instr *tmp;
814 size_t oldsize, newsize;
815 oldsize = b->b_ialloc * sizeof(struct instr);
816 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000817
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700818 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyErr_NoMemory();
820 return -1;
821 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (newsize == 0) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_ialloc <<= 1;
828 tmp = (struct instr *)PyObject_Realloc(
829 (void *)b->b_instr, newsize);
830 if (tmp == NULL) {
831 PyErr_NoMemory();
832 return -1;
833 }
834 b->b_instr = tmp;
835 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
836 }
837 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838}
839
Christian Heimes2202f872008-02-06 14:31:34 +0000840/* Set the i_lineno member of the instruction at offset off if the
841 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000842 already been set. If it has been set, the call has no effect.
843
Christian Heimes2202f872008-02-06 14:31:34 +0000844 The line number is reset in the following cases:
845 - when entering a new scope
846 - on each statement
847 - on each expression that start a new line
848 - before the "except" clause
849 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000850*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852static void
853compiler_set_lineno(struct compiler *c, int off)
854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 basicblock *b;
856 if (c->u->u_lineno_set)
857 return;
858 c->u->u_lineno_set = 1;
859 b = c->u->u_curblock;
860 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861}
862
Larry Hastings3a907972013-11-23 14:49:22 -0800863int
864PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 switch (opcode) {
867 case POP_TOP:
868 return -1;
869 case ROT_TWO:
870 case ROT_THREE:
871 return 0;
872 case DUP_TOP:
873 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000874 case DUP_TOP_TWO:
875 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 case UNARY_POSITIVE:
878 case UNARY_NEGATIVE:
879 case UNARY_NOT:
880 case UNARY_INVERT:
881 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 case SET_ADD:
884 case LIST_APPEND:
885 return -1;
886 case MAP_ADD:
887 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case BINARY_POWER:
890 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400891 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case BINARY_MODULO:
893 case BINARY_ADD:
894 case BINARY_SUBTRACT:
895 case BINARY_SUBSCR:
896 case BINARY_FLOOR_DIVIDE:
897 case BINARY_TRUE_DIVIDE:
898 return -1;
899 case INPLACE_FLOOR_DIVIDE:
900 case INPLACE_TRUE_DIVIDE:
901 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case INPLACE_ADD:
904 case INPLACE_SUBTRACT:
905 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400906 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case INPLACE_MODULO:
908 return -1;
909 case STORE_SUBSCR:
910 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case DELETE_SUBSCR:
912 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_LSHIFT:
915 case BINARY_RSHIFT:
916 case BINARY_AND:
917 case BINARY_XOR:
918 case BINARY_OR:
919 return -1;
920 case INPLACE_POWER:
921 return -1;
922 case GET_ITER:
923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case PRINT_EXPR:
926 return -1;
927 case LOAD_BUILD_CLASS:
928 return 1;
929 case INPLACE_LSHIFT:
930 case INPLACE_RSHIFT:
931 case INPLACE_AND:
932 case INPLACE_XOR:
933 case INPLACE_OR:
934 return -1;
935 case BREAK_LOOP:
936 return 0;
937 case SETUP_WITH:
938 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400939 case WITH_CLEANUP_START:
940 return 1;
941 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 case RETURN_VALUE:
944 return -1;
945 case IMPORT_STAR:
946 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700947 case SETUP_ANNOTATIONS:
948 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case YIELD_VALUE:
950 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500951 case YIELD_FROM:
952 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case POP_BLOCK:
954 return 0;
955 case POP_EXCEPT:
956 return 0; /* -3 except if bad bytecode */
957 case END_FINALLY:
958 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case STORE_NAME:
961 return -1;
962 case DELETE_NAME:
963 return 0;
964 case UNPACK_SEQUENCE:
965 return oparg-1;
966 case UNPACK_EX:
967 return (oparg&0xFF) + (oparg>>8);
968 case FOR_ITER:
969 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case STORE_ATTR:
972 return -2;
973 case DELETE_ATTR:
974 return -1;
975 case STORE_GLOBAL:
976 return -1;
977 case DELETE_GLOBAL:
978 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case LOAD_CONST:
980 return 1;
981 case LOAD_NAME:
982 return 1;
983 case BUILD_TUPLE:
984 case BUILD_LIST:
985 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300986 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400988 case BUILD_LIST_UNPACK:
989 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300990 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400991 case BUILD_SET_UNPACK:
992 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400993 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700994 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700996 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300997 case BUILD_CONST_KEY_MAP:
998 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_ATTR:
1000 return 0;
1001 case COMPARE_OP:
1002 return -1;
1003 case IMPORT_NAME:
1004 return -1;
1005 case IMPORT_FROM:
1006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case JUMP_FORWARD:
1009 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1010 case JUMP_IF_FALSE_OR_POP: /* "" */
1011 case JUMP_ABSOLUTE:
1012 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case POP_JUMP_IF_FALSE:
1015 case POP_JUMP_IF_TRUE:
1016 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case LOAD_GLOBAL:
1019 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case CONTINUE_LOOP:
1022 return 0;
1023 case SETUP_LOOP:
1024 return 0;
1025 case SETUP_EXCEPT:
1026 case SETUP_FINALLY:
1027 return 6; /* can push 3 values for the new exception
1028 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case LOAD_FAST:
1031 return 1;
1032 case STORE_FAST:
1033 return -1;
1034 case DELETE_FAST:
1035 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001036 case STORE_ANNOTATION:
1037 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case RAISE_VARARGS:
1040 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001042 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001043 case CALL_METHOD:
1044 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001046 return -oparg-1;
1047 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001048 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001049 case MAKE_FUNCTION:
1050 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1051 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 case BUILD_SLICE:
1053 if (oparg == 3)
1054 return -2;
1055 else
1056 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_CLOSURE:
1059 return 1;
1060 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001061 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return 1;
1063 case STORE_DEREF:
1064 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001065 case DELETE_DEREF:
1066 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001067 case GET_AWAITABLE:
1068 return 0;
1069 case SETUP_ASYNC_WITH:
1070 return 6;
1071 case BEFORE_ASYNC_WITH:
1072 return 1;
1073 case GET_AITER:
1074 return 0;
1075 case GET_ANEXT:
1076 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001077 case GET_YIELD_FROM_ITER:
1078 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001079 case FORMAT_VALUE:
1080 /* If there's a fmt_spec on the stack, we go from 2->1,
1081 else 1->1. */
1082 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001083 case LOAD_METHOD:
1084 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001086 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
Larry Hastings3a907972013-11-23 14:49:22 -08001088 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089}
1090
1091/* Add an opcode with no argument.
1092 Returns 0 on failure, 1 on success.
1093*/
1094
1095static int
1096compiler_addop(struct compiler *c, int opcode)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 basicblock *b;
1099 struct instr *i;
1100 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001101 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 off = compiler_next_instr(c, c->u->u_curblock);
1103 if (off < 0)
1104 return 0;
1105 b = c->u->u_curblock;
1106 i = &b->b_instr[off];
1107 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001108 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (opcode == RETURN_VALUE)
1110 b->b_return = 1;
1111 compiler_set_lineno(c, off);
1112 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113}
1114
Victor Stinnerf8e32212013-11-19 23:56:34 +01001115static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject *t, *v;
1119 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120
Victor Stinnerefb24132016-01-22 12:33:12 +01001121 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (t == NULL)
1123 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 v = PyDict_GetItem(dict, t);
1126 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001127 if (PyErr_Occurred()) {
1128 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001130 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001131 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001132 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (!v) {
1134 Py_DECREF(t);
1135 return -1;
1136 }
1137 if (PyDict_SetItem(dict, t, v) < 0) {
1138 Py_DECREF(t);
1139 Py_DECREF(v);
1140 return -1;
1141 }
1142 Py_DECREF(v);
1143 }
1144 else
1145 arg = PyLong_AsLong(v);
1146 Py_DECREF(t);
1147 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148}
1149
1150static int
1151compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001154 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001156 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 return compiler_addop_i(c, opcode, arg);
1158}
1159
1160static int
1161compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001164 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1166 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001167 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 arg = compiler_add_o(c, dict, mangled);
1169 Py_DECREF(mangled);
1170 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001171 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 return compiler_addop_i(c, opcode, arg);
1173}
1174
1175/* Add an opcode with an integer argument.
1176 Returns 0 on failure, 1 on success.
1177*/
1178
1179static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001180compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 struct instr *i;
1183 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001184
Victor Stinner2ad474b2016-03-01 23:34:47 +01001185 /* oparg value is unsigned, but a signed C int is usually used to store
1186 it in the C code (like Python/ceval.c).
1187
1188 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1189
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001190 The argument of a concrete bytecode instruction is limited to 8-bit.
1191 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1192 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001193 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 off = compiler_next_instr(c, c->u->u_curblock);
1196 if (off < 0)
1197 return 0;
1198 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001199 i->i_opcode = opcode;
1200 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 compiler_set_lineno(c, off);
1202 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203}
1204
1205static int
1206compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 struct instr *i;
1209 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001211 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 assert(b != NULL);
1213 off = compiler_next_instr(c, c->u->u_curblock);
1214 if (off < 0)
1215 return 0;
1216 i = &c->u->u_curblock->b_instr[off];
1217 i->i_opcode = opcode;
1218 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (absolute)
1220 i->i_jabs = 1;
1221 else
1222 i->i_jrel = 1;
1223 compiler_set_lineno(c, off);
1224 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001227/* NEXT_BLOCK() creates an implicit jump from the current block
1228 to the new block.
1229
1230 The returns inside this macro make it impossible to decref objects
1231 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001232*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (compiler_next_block((C)) == NULL) \
1235 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
1238#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (!compiler_addop((C), (OP))) \
1240 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241}
1242
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001243#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop((C), (OP))) { \
1245 compiler_exit_scope(c); \
1246 return 0; \
1247 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001248}
1249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1252 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253}
1254
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001255/* Same as ADDOP_O, but steals a reference. */
1256#define ADDOP_N(C, OP, O, TYPE) { \
1257 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1258 Py_DECREF((O)); \
1259 return 0; \
1260 } \
1261 Py_DECREF((O)); \
1262}
1263
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1266 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
1269#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!compiler_addop_i((C), (OP), (O))) \
1271 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272}
1273
1274#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (!compiler_addop_j((C), (OP), (O), 1)) \
1276 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (!compiler_addop_j((C), (OP), (O), 0)) \
1281 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
1284/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1285 the ASDL name to synthesize the name of the C type and the visit function.
1286*/
1287
1288#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!compiler_visit_ ## TYPE((C), (V))) \
1290 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291}
1292
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001293#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_visit_ ## TYPE((C), (V))) { \
1295 compiler_exit_scope(c); \
1296 return 0; \
1297 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001298}
1299
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 if (!compiler_visit_slice((C), (V), (CTX))) \
1302 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303}
1304
1305#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 int _i; \
1307 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1308 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1309 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1310 if (!compiler_visit_ ## TYPE((C), elt)) \
1311 return 0; \
1312 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001315#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 int _i; \
1317 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1318 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1319 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1320 if (!compiler_visit_ ## TYPE((C), elt)) { \
1321 compiler_exit_scope(c); \
1322 return 0; \
1323 } \
1324 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001325}
1326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001328is_const(expr_ty e)
1329{
1330 switch (e->kind) {
1331 case Constant_kind:
1332 case Num_kind:
1333 case Str_kind:
1334 case Bytes_kind:
1335 case Ellipsis_kind:
1336 case NameConstant_kind:
1337 return 1;
1338 default:
1339 return 0;
1340 }
1341}
1342
1343static PyObject *
1344get_const_value(expr_ty e)
1345{
1346 switch (e->kind) {
1347 case Constant_kind:
1348 return e->v.Constant.value;
1349 case Num_kind:
1350 return e->v.Num.n;
1351 case Str_kind:
1352 return e->v.Str.s;
1353 case Bytes_kind:
1354 return e->v.Bytes.s;
1355 case Ellipsis_kind:
1356 return Py_Ellipsis;
1357 case NameConstant_kind:
1358 return e->v.NameConstant.value;
1359 default:
1360 assert(!is_const(e));
1361 return NULL;
1362 }
1363}
1364
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001365/* Search if variable annotations are present statically in a block. */
1366
1367static int
1368find_ann(asdl_seq *stmts)
1369{
1370 int i, j, res = 0;
1371 stmt_ty st;
1372
1373 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1374 st = (stmt_ty)asdl_seq_GET(stmts, i);
1375 switch (st->kind) {
1376 case AnnAssign_kind:
1377 return 1;
1378 case For_kind:
1379 res = find_ann(st->v.For.body) ||
1380 find_ann(st->v.For.orelse);
1381 break;
1382 case AsyncFor_kind:
1383 res = find_ann(st->v.AsyncFor.body) ||
1384 find_ann(st->v.AsyncFor.orelse);
1385 break;
1386 case While_kind:
1387 res = find_ann(st->v.While.body) ||
1388 find_ann(st->v.While.orelse);
1389 break;
1390 case If_kind:
1391 res = find_ann(st->v.If.body) ||
1392 find_ann(st->v.If.orelse);
1393 break;
1394 case With_kind:
1395 res = find_ann(st->v.With.body);
1396 break;
1397 case AsyncWith_kind:
1398 res = find_ann(st->v.AsyncWith.body);
1399 break;
1400 case Try_kind:
1401 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1402 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1403 st->v.Try.handlers, j);
1404 if (find_ann(handler->v.ExceptHandler.body)) {
1405 return 1;
1406 }
1407 }
1408 res = find_ann(st->v.Try.body) ||
1409 find_ann(st->v.Try.finalbody) ||
1410 find_ann(st->v.Try.orelse);
1411 break;
1412 default:
1413 res = 0;
1414 }
1415 if (res) {
1416 break;
1417 }
1418 }
1419 return res;
1420}
1421
1422/* Compile a sequence of statements, checking for a docstring
1423 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424
1425static int
INADA Naokicb41b272017-02-23 00:31:59 +09001426compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001428 /* Set current line number to the line number of first statement.
1429 This way line number for SETUP_ANNOTATIONS will always
1430 coincide with the line number of first "real" statement in module.
1431 If body is empy, then lineno will be set later in assemble. */
1432 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1433 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001434 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001435 c->u->u_lineno = st->lineno;
1436 }
1437 /* Every annotated class and module should have __annotations__. */
1438 if (find_ann(stmts)) {
1439 ADDOP(c, SETUP_ANNOTATIONS);
1440 }
INADA Naokicb41b272017-02-23 00:31:59 +09001441 /* if not -OO mode, set docstring */
1442 if (c->c_optimize < 2 && docstring) {
1443 ADDOP_O(c, LOAD_CONST, docstring, consts);
1444 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 }
INADA Naokicb41b272017-02-23 00:31:59 +09001446 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448}
1449
1450static PyCodeObject *
1451compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyCodeObject *co;
1454 int addNone = 1;
1455 static PyObject *module;
1456 if (!module) {
1457 module = PyUnicode_InternFromString("<module>");
1458 if (!module)
1459 return NULL;
1460 }
1461 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001462 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return NULL;
1464 switch (mod->kind) {
1465 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001466 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 compiler_exit_scope(c);
1468 return 0;
1469 }
1470 break;
1471 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001472 if (find_ann(mod->v.Interactive.body)) {
1473 ADDOP(c, SETUP_ANNOTATIONS);
1474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 c->c_interactive = 1;
1476 VISIT_SEQ_IN_SCOPE(c, stmt,
1477 mod->v.Interactive.body);
1478 break;
1479 case Expression_kind:
1480 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1481 addNone = 0;
1482 break;
1483 case Suite_kind:
1484 PyErr_SetString(PyExc_SystemError,
1485 "suite should not be possible");
1486 return 0;
1487 default:
1488 PyErr_Format(PyExc_SystemError,
1489 "module kind %d should not be possible",
1490 mod->kind);
1491 return 0;
1492 }
1493 co = assemble(c, addNone);
1494 compiler_exit_scope(c);
1495 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001496}
1497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498/* The test for LOCAL must come before the test for FREE in order to
1499 handle classes where name is both local and free. The local var is
1500 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001501*/
1502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503static int
1504get_ref_type(struct compiler *c, PyObject *name)
1505{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001506 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001507 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001508 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001509 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001510 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (scope == 0) {
1512 char buf[350];
1513 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001514 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001516 PyUnicode_AsUTF8(name),
1517 PyUnicode_AsUTF8(c->u->u_name),
1518 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1519 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1520 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1521 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 );
1523 Py_FatalError(buf);
1524 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527}
1528
1529static int
1530compiler_lookup_arg(PyObject *dict, PyObject *name)
1531{
1532 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001533 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001535 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001537 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001539 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001540 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001541}
1542
1543static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001544compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001546 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001547 if (qualname == NULL)
1548 qualname = co->co_name;
1549
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001550 if (free) {
1551 for (i = 0; i < free; ++i) {
1552 /* Bypass com_addop_varname because it will generate
1553 LOAD_DEREF but LOAD_CLOSURE is needed.
1554 */
1555 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1556 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001558 /* Special case: If a class contains a method with a
1559 free variable that has the same name as a method,
1560 the name will be considered free *and* local in the
1561 class. It should be handled by the closure, as
1562 well as by the normal name loookup logic.
1563 */
1564 reftype = get_ref_type(c, name);
1565 if (reftype == CELL)
1566 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1567 else /* (reftype == FREE) */
1568 arg = compiler_lookup_arg(c->u->u_freevars, name);
1569 if (arg == -1) {
1570 fprintf(stderr,
1571 "lookup %s in %s %d %d\n"
1572 "freevars of %s: %s\n",
1573 PyUnicode_AsUTF8(PyObject_Repr(name)),
1574 PyUnicode_AsUTF8(c->u->u_name),
1575 reftype, arg,
1576 PyUnicode_AsUTF8(co->co_name),
1577 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1578 Py_FatalError("compiler_make_closure()");
1579 }
1580 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001582 flags |= 0x08;
1583 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001586 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001587 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589}
1590
1591static int
1592compiler_decorators(struct compiler *c, asdl_seq* decos)
1593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 if (!decos)
1597 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1600 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1601 }
1602 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603}
1604
1605static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001606compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001608{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001609 /* Push a dict of keyword-only default values.
1610
1611 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1612 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001613 int i;
1614 PyObject *keys = NULL;
1615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1617 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1618 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1619 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001620 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001621 if (!mangled) {
1622 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001624 if (keys == NULL) {
1625 keys = PyList_New(1);
1626 if (keys == NULL) {
1627 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001628 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001629 }
1630 PyList_SET_ITEM(keys, 0, mangled);
1631 }
1632 else {
1633 int res = PyList_Append(keys, mangled);
1634 Py_DECREF(mangled);
1635 if (res == -1) {
1636 goto error;
1637 }
1638 }
1639 if (!compiler_visit_expr(c, default_)) {
1640 goto error;
1641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 }
1643 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001644 if (keys != NULL) {
1645 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1646 PyObject *keys_tuple = PyList_AsTuple(keys);
1647 Py_DECREF(keys);
1648 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001649 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001650 }
1651 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1652 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001653 assert(default_count > 0);
1654 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001655 }
1656 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001657 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001658 }
1659
1660error:
1661 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001662 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001663}
1664
1665static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001666compiler_visit_argannotation(struct compiler *c, identifier id,
1667 expr_ty annotation, PyObject *names)
1668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001670 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001672 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001673 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001674 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001675 if (PyList_Append(names, mangled) < 0) {
1676 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001677 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001678 }
1679 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001681 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001682}
1683
1684static int
1685compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1686 PyObject *names)
1687{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001688 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 for (i = 0; i < asdl_seq_LEN(args); i++) {
1690 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 c,
1693 arg->arg,
1694 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001695 names))
1696 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001698 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001699}
1700
1701static int
1702compiler_visit_annotations(struct compiler *c, arguments_ty args,
1703 expr_ty returns)
1704{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001705 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001706 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001707
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001708 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 */
1710 static identifier return_str;
1711 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001712 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 names = PyList_New(0);
1714 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001715 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001716
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001717 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001719 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001720 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001721 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001723 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001725 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001726 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001727 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (!return_str) {
1731 return_str = PyUnicode_InternFromString("return");
1732 if (!return_str)
1733 goto error;
1734 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001735 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 goto error;
1737 }
1738
1739 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001741 PyObject *keytuple = PyList_AsTuple(names);
1742 Py_DECREF(names);
1743 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001744 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001746 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1747 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001748 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001750 else {
1751 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001752 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001753 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001754
1755error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001757 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001758}
1759
1760static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001761compiler_visit_defaults(struct compiler *c, arguments_ty args)
1762{
1763 VISIT_SEQ(c, expr, args->defaults);
1764 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1765 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766}
1767
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768static Py_ssize_t
1769compiler_default_arguments(struct compiler *c, arguments_ty args)
1770{
1771 Py_ssize_t funcflags = 0;
1772 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001773 if (!compiler_visit_defaults(c, args))
1774 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001775 funcflags |= 0x01;
1776 }
1777 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001778 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001779 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001780 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001781 return -1;
1782 }
1783 else if (res > 0) {
1784 funcflags |= 0x02;
1785 }
1786 }
1787 return funcflags;
1788}
1789
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790static int
Yury Selivanov75445082015-05-11 22:57:16 -04001791compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001794 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001795 arguments_ty args;
1796 expr_ty returns;
1797 identifier name;
1798 asdl_seq* decos;
1799 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001800 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001801 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001802 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803
Yury Selivanov75445082015-05-11 22:57:16 -04001804 if (is_async) {
1805 assert(s->kind == AsyncFunctionDef_kind);
1806
1807 args = s->v.AsyncFunctionDef.args;
1808 returns = s->v.AsyncFunctionDef.returns;
1809 decos = s->v.AsyncFunctionDef.decorator_list;
1810 name = s->v.AsyncFunctionDef.name;
1811 body = s->v.AsyncFunctionDef.body;
1812
1813 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1814 } else {
1815 assert(s->kind == FunctionDef_kind);
1816
1817 args = s->v.FunctionDef.args;
1818 returns = s->v.FunctionDef.returns;
1819 decos = s->v.FunctionDef.decorator_list;
1820 name = s->v.FunctionDef.name;
1821 body = s->v.FunctionDef.body;
1822
1823 scope_type = COMPILER_SCOPE_FUNCTION;
1824 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (!compiler_decorators(c, decos))
1827 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001828
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001829 funcflags = compiler_default_arguments(c, args);
1830 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001832 }
1833
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001834 annotations = compiler_visit_annotations(c, args, returns);
1835 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001836 return 0;
1837 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001838 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001839 funcflags |= 0x04;
1840 }
1841
1842 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1843 return 0;
1844 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845
INADA Naokicb41b272017-02-23 00:31:59 +09001846 /* if not -OO mode, add docstring */
1847 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1848 docstring = s->v.FunctionDef.docstring;
1849 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 compiler_exit_scope(c);
1851 return 0;
1852 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 c->u->u_argcount = asdl_seq_LEN(args->args);
1855 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001857 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001859 qualname = c->u->u_qualname;
1860 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001862 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001863 Py_XDECREF(qualname);
1864 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001866 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001868 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001869 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 /* decorators */
1873 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1874 ADDOP_I(c, CALL_FUNCTION, 1);
1875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876
Yury Selivanov75445082015-05-11 22:57:16 -04001877 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878}
1879
1880static int
1881compiler_class(struct compiler *c, stmt_ty s)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 PyCodeObject *co;
1884 PyObject *str;
1885 int i;
1886 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (!compiler_decorators(c, decos))
1889 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* ultimately generate code for:
1892 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1893 where:
1894 <func> is a function/closure created from the class body;
1895 it has a single argument (__locals__) where the dict
1896 (or MutableSequence) representing the locals is passed
1897 <name> is the class name
1898 <bases> is the positional arguments and *varargs argument
1899 <keywords> is the keyword arguments and **kwds argument
1900 This borrows from compiler_call.
1901 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001904 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1905 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return 0;
1907 /* this block represents what we do in the new scope */
1908 {
1909 /* use the class name for name mangling */
1910 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001911 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* load (global) __name__ ... */
1913 str = PyUnicode_InternFromString("__name__");
1914 if (!str || !compiler_nameop(c, str, Load)) {
1915 Py_XDECREF(str);
1916 compiler_exit_scope(c);
1917 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 Py_DECREF(str);
1920 /* ... and store it as __module__ */
1921 str = PyUnicode_InternFromString("__module__");
1922 if (!str || !compiler_nameop(c, str, Store)) {
1923 Py_XDECREF(str);
1924 compiler_exit_scope(c);
1925 return 0;
1926 }
1927 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001928 assert(c->u->u_qualname);
1929 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001930 str = PyUnicode_InternFromString("__qualname__");
1931 if (!str || !compiler_nameop(c, str, Store)) {
1932 Py_XDECREF(str);
1933 compiler_exit_scope(c);
1934 return 0;
1935 }
1936 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001938 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 compiler_exit_scope(c);
1940 return 0;
1941 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001942 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001943 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001944 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001945 str = PyUnicode_InternFromString("__class__");
1946 if (str == NULL) {
1947 compiler_exit_scope(c);
1948 return 0;
1949 }
1950 i = compiler_lookup_arg(c->u->u_cellvars, str);
1951 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001952 if (i < 0) {
1953 compiler_exit_scope(c);
1954 return 0;
1955 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001956 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001959 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001960 str = PyUnicode_InternFromString("__classcell__");
1961 if (!str || !compiler_nameop(c, str, Store)) {
1962 Py_XDECREF(str);
1963 compiler_exit_scope(c);
1964 return 0;
1965 }
1966 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001968 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001969 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001970 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001971 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001972 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001973 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* create the code object */
1975 co = assemble(c, 1);
1976 }
1977 /* leave the new scope */
1978 compiler_exit_scope(c);
1979 if (co == NULL)
1980 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* 2. load the 'build_class' function */
1983 ADDOP(c, LOAD_BUILD_CLASS);
1984
1985 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001986 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 Py_DECREF(co);
1988
1989 /* 4. load class name */
1990 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1991
1992 /* 5. generate the rest of the code for the call */
1993 if (!compiler_call_helper(c, 2,
1994 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001995 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 return 0;
1997
1998 /* 6. apply decorators */
1999 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2000 ADDOP_I(c, CALL_FUNCTION, 1);
2001 }
2002
2003 /* 7. store into <name> */
2004 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2005 return 0;
2006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007}
2008
2009static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002010compiler_ifexp(struct compiler *c, expr_ty e)
2011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 basicblock *end, *next;
2013
2014 assert(e->kind == IfExp_kind);
2015 end = compiler_new_block(c);
2016 if (end == NULL)
2017 return 0;
2018 next = compiler_new_block(c);
2019 if (next == NULL)
2020 return 0;
2021 VISIT(c, expr, e->v.IfExp.test);
2022 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2023 VISIT(c, expr, e->v.IfExp.body);
2024 ADDOP_JREL(c, JUMP_FORWARD, end);
2025 compiler_use_next_block(c, next);
2026 VISIT(c, expr, e->v.IfExp.orelse);
2027 compiler_use_next_block(c, end);
2028 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002029}
2030
2031static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032compiler_lambda(struct compiler *c, expr_ty e)
2033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002035 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002037 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 arguments_ty args = e->v.Lambda.args;
2039 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 if (!name) {
2042 name = PyUnicode_InternFromString("<lambda>");
2043 if (!name)
2044 return 0;
2045 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002047 funcflags = compiler_default_arguments(c, args);
2048 if (funcflags == -1) {
2049 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002051
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002052 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002053 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* Make None the first constant, so the lambda can't have a
2057 docstring. */
2058 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2059 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 c->u->u_argcount = asdl_seq_LEN(args->args);
2062 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2063 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2064 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002065 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
2067 else {
2068 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002069 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002071 qualname = c->u->u_qualname;
2072 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002074 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002077 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002078 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 Py_DECREF(co);
2080
2081 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082}
2083
2084static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085compiler_if(struct compiler *c, stmt_ty s)
2086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 basicblock *end, *next;
2088 int constant;
2089 assert(s->kind == If_kind);
2090 end = compiler_new_block(c);
2091 if (end == NULL)
2092 return 0;
2093
Georg Brandl8334fd92010-12-04 10:26:46 +00002094 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 /* constant = 0: "if 0"
2096 * constant = 1: "if 1", "if 2", ...
2097 * constant = -1: rest */
2098 if (constant == 0) {
2099 if (s->v.If.orelse)
2100 VISIT_SEQ(c, stmt, s->v.If.orelse);
2101 } else if (constant == 1) {
2102 VISIT_SEQ(c, stmt, s->v.If.body);
2103 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002104 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 next = compiler_new_block(c);
2106 if (next == NULL)
2107 return 0;
2108 }
2109 else
2110 next = end;
2111 VISIT(c, expr, s->v.If.test);
2112 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2113 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002114 if (asdl_seq_LEN(s->v.If.orelse)) {
2115 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 compiler_use_next_block(c, next);
2117 VISIT_SEQ(c, stmt, s->v.If.orelse);
2118 }
2119 }
2120 compiler_use_next_block(c, end);
2121 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122}
2123
2124static int
2125compiler_for(struct compiler *c, stmt_ty s)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 start = compiler_new_block(c);
2130 cleanup = compiler_new_block(c);
2131 end = compiler_new_block(c);
2132 if (start == NULL || end == NULL || cleanup == NULL)
2133 return 0;
2134 ADDOP_JREL(c, SETUP_LOOP, end);
2135 if (!compiler_push_fblock(c, LOOP, start))
2136 return 0;
2137 VISIT(c, expr, s->v.For.iter);
2138 ADDOP(c, GET_ITER);
2139 compiler_use_next_block(c, start);
2140 ADDOP_JREL(c, FOR_ITER, cleanup);
2141 VISIT(c, expr, s->v.For.target);
2142 VISIT_SEQ(c, stmt, s->v.For.body);
2143 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2144 compiler_use_next_block(c, cleanup);
2145 ADDOP(c, POP_BLOCK);
2146 compiler_pop_fblock(c, LOOP, start);
2147 VISIT_SEQ(c, stmt, s->v.For.orelse);
2148 compiler_use_next_block(c, end);
2149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150}
2151
Yury Selivanov75445082015-05-11 22:57:16 -04002152
2153static int
2154compiler_async_for(struct compiler *c, stmt_ty s)
2155{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002156 _Py_IDENTIFIER(StopAsyncIteration);
2157
Yury Selivanov75445082015-05-11 22:57:16 -04002158 basicblock *try, *except, *end, *after_try, *try_cleanup,
2159 *after_loop, *after_loop_else;
2160
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002161 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2162 if (stop_aiter_error == NULL) {
2163 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002164 }
2165
2166 try = compiler_new_block(c);
2167 except = compiler_new_block(c);
2168 end = compiler_new_block(c);
2169 after_try = compiler_new_block(c);
2170 try_cleanup = compiler_new_block(c);
2171 after_loop = compiler_new_block(c);
2172 after_loop_else = compiler_new_block(c);
2173
2174 if (try == NULL || except == NULL || end == NULL
2175 || after_try == NULL || try_cleanup == NULL)
2176 return 0;
2177
2178 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2179 if (!compiler_push_fblock(c, LOOP, try))
2180 return 0;
2181
2182 VISIT(c, expr, s->v.AsyncFor.iter);
2183 ADDOP(c, GET_AITER);
2184 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2185 ADDOP(c, YIELD_FROM);
2186
2187 compiler_use_next_block(c, try);
2188
2189
2190 ADDOP_JREL(c, SETUP_EXCEPT, except);
2191 if (!compiler_push_fblock(c, EXCEPT, try))
2192 return 0;
2193
2194 ADDOP(c, GET_ANEXT);
2195 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2196 ADDOP(c, YIELD_FROM);
2197 VISIT(c, expr, s->v.AsyncFor.target);
2198 ADDOP(c, POP_BLOCK);
2199 compiler_pop_fblock(c, EXCEPT, try);
2200 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2201
2202
2203 compiler_use_next_block(c, except);
2204 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002205 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002206 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2207 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2208
2209 ADDOP(c, POP_TOP);
2210 ADDOP(c, POP_TOP);
2211 ADDOP(c, POP_TOP);
2212 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2213 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2214 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2215
2216
2217 compiler_use_next_block(c, try_cleanup);
2218 ADDOP(c, END_FINALLY);
2219
2220 compiler_use_next_block(c, after_try);
2221 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2222 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2223
2224 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2225 compiler_pop_fblock(c, LOOP, try);
2226
2227 compiler_use_next_block(c, after_loop);
2228 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2229
2230 compiler_use_next_block(c, after_loop_else);
2231 VISIT_SEQ(c, stmt, s->v.For.orelse);
2232
2233 compiler_use_next_block(c, end);
2234
2235 return 1;
2236}
2237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238static int
2239compiler_while(struct compiler *c, stmt_ty s)
2240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002242 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 if (constant == 0) {
2245 if (s->v.While.orelse)
2246 VISIT_SEQ(c, stmt, s->v.While.orelse);
2247 return 1;
2248 }
2249 loop = compiler_new_block(c);
2250 end = compiler_new_block(c);
2251 if (constant == -1) {
2252 anchor = compiler_new_block(c);
2253 if (anchor == NULL)
2254 return 0;
2255 }
2256 if (loop == NULL || end == NULL)
2257 return 0;
2258 if (s->v.While.orelse) {
2259 orelse = compiler_new_block(c);
2260 if (orelse == NULL)
2261 return 0;
2262 }
2263 else
2264 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 ADDOP_JREL(c, SETUP_LOOP, end);
2267 compiler_use_next_block(c, loop);
2268 if (!compiler_push_fblock(c, LOOP, loop))
2269 return 0;
2270 if (constant == -1) {
2271 VISIT(c, expr, s->v.While.test);
2272 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2273 }
2274 VISIT_SEQ(c, stmt, s->v.While.body);
2275 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* XXX should the two POP instructions be in a separate block
2278 if there is no else clause ?
2279 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002281 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002283 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 compiler_pop_fblock(c, LOOP, loop);
2285 if (orelse != NULL) /* what if orelse is just pass? */
2286 VISIT_SEQ(c, stmt, s->v.While.orelse);
2287 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290}
2291
2292static int
2293compiler_continue(struct compiler *c)
2294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2296 static const char IN_FINALLY_ERROR_MSG[] =
2297 "'continue' not supported inside 'finally' clause";
2298 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (!c->u->u_nfblocks)
2301 return compiler_error(c, LOOP_ERROR_MSG);
2302 i = c->u->u_nfblocks - 1;
2303 switch (c->u->u_fblock[i].fb_type) {
2304 case LOOP:
2305 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2306 break;
2307 case EXCEPT:
2308 case FINALLY_TRY:
2309 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2310 /* Prevent continue anywhere under a finally
2311 even if hidden in a sub-try or except. */
2312 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2313 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2314 }
2315 if (i == -1)
2316 return compiler_error(c, LOOP_ERROR_MSG);
2317 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2318 break;
2319 case FINALLY_END:
2320 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2321 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324}
2325
2326/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327
2328 SETUP_FINALLY L
2329 <code for body>
2330 POP_BLOCK
2331 LOAD_CONST <None>
2332 L: <code for finalbody>
2333 END_FINALLY
2334
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 The special instructions use the block stack. Each block
2336 stack entry contains the instruction that created it (here
2337 SETUP_FINALLY), the level of the value stack at the time the
2338 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 Pushes the current value stack level and the label
2342 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 Pops en entry from the block stack, and pops the value
2345 stack until its level is the same as indicated on the
2346 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 Pops a variable number of entries from the *value* stack
2349 and re-raises the exception they specify. The number of
2350 entries popped depends on the (pseudo) exception type.
2351
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 The block stack is unwound when an exception is raised:
2353 when a SETUP_FINALLY entry is found, the exception is pushed
2354 onto the value stack (and the exception condition is cleared),
2355 and the interpreter jumps to the label gotten from the block
2356 stack.
2357*/
2358
2359static int
2360compiler_try_finally(struct compiler *c, stmt_ty s)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 basicblock *body, *end;
2363 body = compiler_new_block(c);
2364 end = compiler_new_block(c);
2365 if (body == NULL || end == NULL)
2366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 ADDOP_JREL(c, SETUP_FINALLY, end);
2369 compiler_use_next_block(c, body);
2370 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2371 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002372 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2373 if (!compiler_try_except(c, s))
2374 return 0;
2375 }
2376 else {
2377 VISIT_SEQ(c, stmt, s->v.Try.body);
2378 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 ADDOP(c, POP_BLOCK);
2380 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2383 compiler_use_next_block(c, end);
2384 if (!compiler_push_fblock(c, FINALLY_END, end))
2385 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002386 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 ADDOP(c, END_FINALLY);
2388 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391}
2392
2393/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002394 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395 (The contents of the value stack is shown in [], with the top
2396 at the right; 'tb' is trace-back info, 'val' the exception's
2397 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398
2399 Value stack Label Instruction Argument
2400 [] SETUP_EXCEPT L1
2401 [] <code for S>
2402 [] POP_BLOCK
2403 [] JUMP_FORWARD L0
2404
2405 [tb, val, exc] L1: DUP )
2406 [tb, val, exc, exc] <evaluate E1> )
2407 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2408 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2409 [tb, val, exc] POP
2410 [tb, val] <assign to V1> (or POP if no V1)
2411 [tb] POP
2412 [] <code for S1>
2413 JUMP_FORWARD L0
2414
2415 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416 .............................etc.......................
2417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2419
2420 [] L0: <next statement>
2421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422 Of course, parts are not generated if Vi or Ei is not present.
2423*/
2424static int
2425compiler_try_except(struct compiler *c, stmt_ty s)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002428 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 body = compiler_new_block(c);
2431 except = compiler_new_block(c);
2432 orelse = compiler_new_block(c);
2433 end = compiler_new_block(c);
2434 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2435 return 0;
2436 ADDOP_JREL(c, SETUP_EXCEPT, except);
2437 compiler_use_next_block(c, body);
2438 if (!compiler_push_fblock(c, EXCEPT, body))
2439 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002440 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 ADDOP(c, POP_BLOCK);
2442 compiler_pop_fblock(c, EXCEPT, body);
2443 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002444 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 compiler_use_next_block(c, except);
2446 for (i = 0; i < n; i++) {
2447 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002448 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 if (!handler->v.ExceptHandler.type && i < n-1)
2450 return compiler_error(c, "default 'except:' must be last");
2451 c->u->u_lineno_set = 0;
2452 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002453 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 except = compiler_new_block(c);
2455 if (except == NULL)
2456 return 0;
2457 if (handler->v.ExceptHandler.type) {
2458 ADDOP(c, DUP_TOP);
2459 VISIT(c, expr, handler->v.ExceptHandler.type);
2460 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2461 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2462 }
2463 ADDOP(c, POP_TOP);
2464 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002465 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002466
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002467 cleanup_end = compiler_new_block(c);
2468 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002469 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002470 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002471
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002472 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2473 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002475 /*
2476 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002477 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002478 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002479 try:
2480 # body
2481 finally:
2482 name = None
2483 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002484 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002486 /* second try: */
2487 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2488 compiler_use_next_block(c, cleanup_body);
2489 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2490 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002492 /* second # body */
2493 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2494 ADDOP(c, POP_BLOCK);
2495 ADDOP(c, POP_EXCEPT);
2496 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002498 /* finally: */
2499 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2500 compiler_use_next_block(c, cleanup_end);
2501 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2502 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002504 /* name = None */
2505 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2506 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002508 /* del name */
2509 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002511 ADDOP(c, END_FINALLY);
2512 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 }
2514 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002515 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002517 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002518 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002519 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520
Guido van Rossumb940e112007-01-10 16:19:56 +00002521 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002522 ADDOP(c, POP_TOP);
2523 compiler_use_next_block(c, cleanup_body);
2524 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2525 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002527 ADDOP(c, POP_EXCEPT);
2528 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 }
2530 ADDOP_JREL(c, JUMP_FORWARD, end);
2531 compiler_use_next_block(c, except);
2532 }
2533 ADDOP(c, END_FINALLY);
2534 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002535 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 compiler_use_next_block(c, end);
2537 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538}
2539
2540static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002541compiler_try(struct compiler *c, stmt_ty s) {
2542 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2543 return compiler_try_finally(c, s);
2544 else
2545 return compiler_try_except(c, s);
2546}
2547
2548
2549static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550compiler_import_as(struct compiler *c, identifier name, identifier asname)
2551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 /* The IMPORT_NAME opcode was already generated. This function
2553 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 If there is a dot in name, we need to split it and emit a
2556 LOAD_ATTR for each name.
2557 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002558 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2559 PyUnicode_GET_LENGTH(name), 1);
2560 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002561 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002562 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 Py_ssize_t pos = dot + 1;
2565 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002567 dot = PyUnicode_FindChar(name, '.', pos,
2568 PyUnicode_GET_LENGTH(name), 1);
2569 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002570 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002571 attr = PyUnicode_Substring(name, pos,
2572 (dot != -1) ? dot :
2573 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002575 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 ADDOP_O(c, LOAD_ATTR, attr, names);
2577 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 }
2580 }
2581 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582}
2583
2584static int
2585compiler_import(struct compiler *c, stmt_ty s)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 /* The Import node stores a module name like a.b.c as a single
2588 string. This is convenient for all cases except
2589 import a.b.c as d
2590 where we need to parse that string to extract the individual
2591 module names.
2592 XXX Perhaps change the representation to make this case simpler?
2593 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002594 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 for (i = 0; i < n; i++) {
2597 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2598 int r;
2599 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 level = PyLong_FromLong(0);
2602 if (level == NULL)
2603 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 ADDOP_O(c, LOAD_CONST, level, consts);
2606 Py_DECREF(level);
2607 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2608 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 if (alias->asname) {
2611 r = compiler_import_as(c, alias->name, alias->asname);
2612 if (!r)
2613 return r;
2614 }
2615 else {
2616 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002617 Py_ssize_t dot = PyUnicode_FindChar(
2618 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002619 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002621 if (tmp == NULL)
2622 return 0;
2623 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002625 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 Py_DECREF(tmp);
2627 }
2628 if (!r)
2629 return r;
2630 }
2631 }
2632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633}
2634
2635static int
2636compiler_from_import(struct compiler *c, stmt_ty s)
2637{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002638 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 PyObject *names = PyTuple_New(n);
2641 PyObject *level;
2642 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 if (!empty_string) {
2645 empty_string = PyUnicode_FromString("");
2646 if (!empty_string)
2647 return 0;
2648 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 if (!names)
2651 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 level = PyLong_FromLong(s->v.ImportFrom.level);
2654 if (!level) {
2655 Py_DECREF(names);
2656 return 0;
2657 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 /* build up the names */
2660 for (i = 0; i < n; i++) {
2661 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2662 Py_INCREF(alias->name);
2663 PyTuple_SET_ITEM(names, i, alias->name);
2664 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002667 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 Py_DECREF(level);
2669 Py_DECREF(names);
2670 return compiler_error(c, "from __future__ imports must occur "
2671 "at the beginning of the file");
2672 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 ADDOP_O(c, LOAD_CONST, level, consts);
2675 Py_DECREF(level);
2676 ADDOP_O(c, LOAD_CONST, names, consts);
2677 Py_DECREF(names);
2678 if (s->v.ImportFrom.module) {
2679 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2680 }
2681 else {
2682 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2683 }
2684 for (i = 0; i < n; i++) {
2685 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2686 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002688 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 assert(n == 1);
2690 ADDOP(c, IMPORT_STAR);
2691 return 1;
2692 }
2693
2694 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2695 store_name = alias->name;
2696 if (alias->asname)
2697 store_name = alias->asname;
2698
2699 if (!compiler_nameop(c, store_name, Store)) {
2700 Py_DECREF(names);
2701 return 0;
2702 }
2703 }
2704 /* remove imported module */
2705 ADDOP(c, POP_TOP);
2706 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707}
2708
2709static int
2710compiler_assert(struct compiler *c, stmt_ty s)
2711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 static PyObject *assertion_error = NULL;
2713 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002714 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715
Georg Brandl8334fd92010-12-04 10:26:46 +00002716 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 return 1;
2718 if (assertion_error == NULL) {
2719 assertion_error = PyUnicode_InternFromString("AssertionError");
2720 if (assertion_error == NULL)
2721 return 0;
2722 }
2723 if (s->v.Assert.test->kind == Tuple_kind &&
2724 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002725 msg = PyUnicode_FromString("assertion is always true, "
2726 "perhaps remove parentheses?");
2727 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002729 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2730 c->c_filename, c->u->u_lineno,
2731 NULL, NULL) == -1) {
2732 Py_DECREF(msg);
2733 return 0;
2734 }
2735 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 }
2737 VISIT(c, expr, s->v.Assert.test);
2738 end = compiler_new_block(c);
2739 if (end == NULL)
2740 return 0;
2741 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2742 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2743 if (s->v.Assert.msg) {
2744 VISIT(c, expr, s->v.Assert.msg);
2745 ADDOP_I(c, CALL_FUNCTION, 1);
2746 }
2747 ADDOP_I(c, RAISE_VARARGS, 1);
2748 compiler_use_next_block(c, end);
2749 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750}
2751
2752static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002753compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2754{
2755 if (c->c_interactive && c->c_nestlevel <= 1) {
2756 VISIT(c, expr, value);
2757 ADDOP(c, PRINT_EXPR);
2758 return 1;
2759 }
2760
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002761 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002762 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002763 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002764 }
2765
2766 VISIT(c, expr, value);
2767 ADDOP(c, POP_TOP);
2768 return 1;
2769}
2770
2771static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772compiler_visit_stmt(struct compiler *c, stmt_ty s)
2773{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002774 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 /* Always assign a lineno to the next instruction for a stmt. */
2777 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002778 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 switch (s->kind) {
2782 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002783 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 case ClassDef_kind:
2785 return compiler_class(c, s);
2786 case Return_kind:
2787 if (c->u->u_ste->ste_type != FunctionBlock)
2788 return compiler_error(c, "'return' outside function");
2789 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002790 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2791 return compiler_error(
2792 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 VISIT(c, expr, s->v.Return.value);
2794 }
2795 else
2796 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2797 ADDOP(c, RETURN_VALUE);
2798 break;
2799 case Delete_kind:
2800 VISIT_SEQ(c, expr, s->v.Delete.targets)
2801 break;
2802 case Assign_kind:
2803 n = asdl_seq_LEN(s->v.Assign.targets);
2804 VISIT(c, expr, s->v.Assign.value);
2805 for (i = 0; i < n; i++) {
2806 if (i < n - 1)
2807 ADDOP(c, DUP_TOP);
2808 VISIT(c, expr,
2809 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2810 }
2811 break;
2812 case AugAssign_kind:
2813 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002814 case AnnAssign_kind:
2815 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 case For_kind:
2817 return compiler_for(c, s);
2818 case While_kind:
2819 return compiler_while(c, s);
2820 case If_kind:
2821 return compiler_if(c, s);
2822 case Raise_kind:
2823 n = 0;
2824 if (s->v.Raise.exc) {
2825 VISIT(c, expr, s->v.Raise.exc);
2826 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002827 if (s->v.Raise.cause) {
2828 VISIT(c, expr, s->v.Raise.cause);
2829 n++;
2830 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002832 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002834 case Try_kind:
2835 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 case Assert_kind:
2837 return compiler_assert(c, s);
2838 case Import_kind:
2839 return compiler_import(c, s);
2840 case ImportFrom_kind:
2841 return compiler_from_import(c, s);
2842 case Global_kind:
2843 case Nonlocal_kind:
2844 break;
2845 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002846 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 case Pass_kind:
2848 break;
2849 case Break_kind:
2850 if (!compiler_in_loop(c))
2851 return compiler_error(c, "'break' outside loop");
2852 ADDOP(c, BREAK_LOOP);
2853 break;
2854 case Continue_kind:
2855 return compiler_continue(c);
2856 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002857 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002858 case AsyncFunctionDef_kind:
2859 return compiler_function(c, s, 1);
2860 case AsyncWith_kind:
2861 return compiler_async_with(c, s, 0);
2862 case AsyncFor_kind:
2863 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 }
Yury Selivanov75445082015-05-11 22:57:16 -04002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867}
2868
2869static int
2870unaryop(unaryop_ty op)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 switch (op) {
2873 case Invert:
2874 return UNARY_INVERT;
2875 case Not:
2876 return UNARY_NOT;
2877 case UAdd:
2878 return UNARY_POSITIVE;
2879 case USub:
2880 return UNARY_NEGATIVE;
2881 default:
2882 PyErr_Format(PyExc_SystemError,
2883 "unary op %d should not be possible", op);
2884 return 0;
2885 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886}
2887
2888static int
2889binop(struct compiler *c, operator_ty op)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 switch (op) {
2892 case Add:
2893 return BINARY_ADD;
2894 case Sub:
2895 return BINARY_SUBTRACT;
2896 case Mult:
2897 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002898 case MatMult:
2899 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 case Div:
2901 return BINARY_TRUE_DIVIDE;
2902 case Mod:
2903 return BINARY_MODULO;
2904 case Pow:
2905 return BINARY_POWER;
2906 case LShift:
2907 return BINARY_LSHIFT;
2908 case RShift:
2909 return BINARY_RSHIFT;
2910 case BitOr:
2911 return BINARY_OR;
2912 case BitXor:
2913 return BINARY_XOR;
2914 case BitAnd:
2915 return BINARY_AND;
2916 case FloorDiv:
2917 return BINARY_FLOOR_DIVIDE;
2918 default:
2919 PyErr_Format(PyExc_SystemError,
2920 "binary op %d should not be possible", op);
2921 return 0;
2922 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923}
2924
2925static int
2926cmpop(cmpop_ty op)
2927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 switch (op) {
2929 case Eq:
2930 return PyCmp_EQ;
2931 case NotEq:
2932 return PyCmp_NE;
2933 case Lt:
2934 return PyCmp_LT;
2935 case LtE:
2936 return PyCmp_LE;
2937 case Gt:
2938 return PyCmp_GT;
2939 case GtE:
2940 return PyCmp_GE;
2941 case Is:
2942 return PyCmp_IS;
2943 case IsNot:
2944 return PyCmp_IS_NOT;
2945 case In:
2946 return PyCmp_IN;
2947 case NotIn:
2948 return PyCmp_NOT_IN;
2949 default:
2950 return PyCmp_BAD;
2951 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952}
2953
2954static int
2955inplace_binop(struct compiler *c, operator_ty op)
2956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 switch (op) {
2958 case Add:
2959 return INPLACE_ADD;
2960 case Sub:
2961 return INPLACE_SUBTRACT;
2962 case Mult:
2963 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002964 case MatMult:
2965 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 case Div:
2967 return INPLACE_TRUE_DIVIDE;
2968 case Mod:
2969 return INPLACE_MODULO;
2970 case Pow:
2971 return INPLACE_POWER;
2972 case LShift:
2973 return INPLACE_LSHIFT;
2974 case RShift:
2975 return INPLACE_RSHIFT;
2976 case BitOr:
2977 return INPLACE_OR;
2978 case BitXor:
2979 return INPLACE_XOR;
2980 case BitAnd:
2981 return INPLACE_AND;
2982 case FloorDiv:
2983 return INPLACE_FLOOR_DIVIDE;
2984 default:
2985 PyErr_Format(PyExc_SystemError,
2986 "inplace binary op %d should not be possible", op);
2987 return 0;
2988 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989}
2990
2991static int
2992compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2993{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002994 int op, scope;
2995 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 PyObject *dict = c->u->u_names;
2999 PyObject *mangled;
3000 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 mangled = _Py_Mangle(c->u->u_private, name);
3003 if (!mangled)
3004 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003005
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003006 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3007 !_PyUnicode_EqualToASCIIString(name, "True") &&
3008 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 op = 0;
3011 optype = OP_NAME;
3012 scope = PyST_GetScope(c->u->u_ste, mangled);
3013 switch (scope) {
3014 case FREE:
3015 dict = c->u->u_freevars;
3016 optype = OP_DEREF;
3017 break;
3018 case CELL:
3019 dict = c->u->u_cellvars;
3020 optype = OP_DEREF;
3021 break;
3022 case LOCAL:
3023 if (c->u->u_ste->ste_type == FunctionBlock)
3024 optype = OP_FAST;
3025 break;
3026 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003027 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 optype = OP_GLOBAL;
3029 break;
3030 case GLOBAL_EXPLICIT:
3031 optype = OP_GLOBAL;
3032 break;
3033 default:
3034 /* scope can be 0 */
3035 break;
3036 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003039 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 switch (optype) {
3042 case OP_DEREF:
3043 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003044 case Load:
3045 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3046 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 case Store: op = STORE_DEREF; break;
3048 case AugLoad:
3049 case AugStore:
3050 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003051 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 case Param:
3053 default:
3054 PyErr_SetString(PyExc_SystemError,
3055 "param invalid for deref variable");
3056 return 0;
3057 }
3058 break;
3059 case OP_FAST:
3060 switch (ctx) {
3061 case Load: op = LOAD_FAST; break;
3062 case Store: op = STORE_FAST; break;
3063 case Del: op = DELETE_FAST; break;
3064 case AugLoad:
3065 case AugStore:
3066 break;
3067 case Param:
3068 default:
3069 PyErr_SetString(PyExc_SystemError,
3070 "param invalid for local variable");
3071 return 0;
3072 }
3073 ADDOP_O(c, op, mangled, varnames);
3074 Py_DECREF(mangled);
3075 return 1;
3076 case OP_GLOBAL:
3077 switch (ctx) {
3078 case Load: op = LOAD_GLOBAL; break;
3079 case Store: op = STORE_GLOBAL; break;
3080 case Del: op = DELETE_GLOBAL; break;
3081 case AugLoad:
3082 case AugStore:
3083 break;
3084 case Param:
3085 default:
3086 PyErr_SetString(PyExc_SystemError,
3087 "param invalid for global variable");
3088 return 0;
3089 }
3090 break;
3091 case OP_NAME:
3092 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003093 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 case Store: op = STORE_NAME; break;
3095 case Del: op = DELETE_NAME; break;
3096 case AugLoad:
3097 case AugStore:
3098 break;
3099 case Param:
3100 default:
3101 PyErr_SetString(PyExc_SystemError,
3102 "param invalid for name variable");
3103 return 0;
3104 }
3105 break;
3106 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 assert(op);
3109 arg = compiler_add_o(c, dict, mangled);
3110 Py_DECREF(mangled);
3111 if (arg < 0)
3112 return 0;
3113 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003114}
3115
3116static int
3117compiler_boolop(struct compiler *c, expr_ty e)
3118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003120 int jumpi;
3121 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 assert(e->kind == BoolOp_kind);
3125 if (e->v.BoolOp.op == And)
3126 jumpi = JUMP_IF_FALSE_OR_POP;
3127 else
3128 jumpi = JUMP_IF_TRUE_OR_POP;
3129 end = compiler_new_block(c);
3130 if (end == NULL)
3131 return 0;
3132 s = e->v.BoolOp.values;
3133 n = asdl_seq_LEN(s) - 1;
3134 assert(n >= 0);
3135 for (i = 0; i < n; ++i) {
3136 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3137 ADDOP_JABS(c, jumpi, end);
3138 }
3139 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3140 compiler_use_next_block(c, end);
3141 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142}
3143
3144static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003145starunpack_helper(struct compiler *c, asdl_seq *elts,
3146 int single_op, int inner_op, int outer_op)
3147{
3148 Py_ssize_t n = asdl_seq_LEN(elts);
3149 Py_ssize_t i, nsubitems = 0, nseen = 0;
3150 for (i = 0; i < n; i++) {
3151 expr_ty elt = asdl_seq_GET(elts, i);
3152 if (elt->kind == Starred_kind) {
3153 if (nseen) {
3154 ADDOP_I(c, inner_op, nseen);
3155 nseen = 0;
3156 nsubitems++;
3157 }
3158 VISIT(c, expr, elt->v.Starred.value);
3159 nsubitems++;
3160 }
3161 else {
3162 VISIT(c, expr, elt);
3163 nseen++;
3164 }
3165 }
3166 if (nsubitems) {
3167 if (nseen) {
3168 ADDOP_I(c, inner_op, nseen);
3169 nsubitems++;
3170 }
3171 ADDOP_I(c, outer_op, nsubitems);
3172 }
3173 else
3174 ADDOP_I(c, single_op, nseen);
3175 return 1;
3176}
3177
3178static int
3179assignment_helper(struct compiler *c, asdl_seq *elts)
3180{
3181 Py_ssize_t n = asdl_seq_LEN(elts);
3182 Py_ssize_t i;
3183 int seen_star = 0;
3184 for (i = 0; i < n; i++) {
3185 expr_ty elt = asdl_seq_GET(elts, i);
3186 if (elt->kind == Starred_kind && !seen_star) {
3187 if ((i >= (1 << 8)) ||
3188 (n-i-1 >= (INT_MAX >> 8)))
3189 return compiler_error(c,
3190 "too many expressions in "
3191 "star-unpacking assignment");
3192 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3193 seen_star = 1;
3194 asdl_seq_SET(elts, i, elt->v.Starred.value);
3195 }
3196 else if (elt->kind == Starred_kind) {
3197 return compiler_error(c,
3198 "two starred expressions in assignment");
3199 }
3200 }
3201 if (!seen_star) {
3202 ADDOP_I(c, UNPACK_SEQUENCE, n);
3203 }
3204 VISIT_SEQ(c, expr, elts);
3205 return 1;
3206}
3207
3208static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209compiler_list(struct compiler *c, expr_ty e)
3210{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003211 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003213 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003215 else if (e->v.List.ctx == Load) {
3216 return starunpack_helper(c, elts,
3217 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003219 else
3220 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222}
3223
3224static int
3225compiler_tuple(struct compiler *c, expr_ty e)
3226{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003227 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003229 return assignment_helper(c, elts);
3230 }
3231 else if (e->v.Tuple.ctx == Load) {
3232 return starunpack_helper(c, elts,
3233 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3234 }
3235 else
3236 VISIT_SEQ(c, expr, elts);
3237 return 1;
3238}
3239
3240static int
3241compiler_set(struct compiler *c, expr_ty e)
3242{
3243 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3244 BUILD_SET, BUILD_SET_UNPACK);
3245}
3246
3247static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003248are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3249{
3250 Py_ssize_t i;
3251 for (i = begin; i < end; i++) {
3252 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3253 if (key == NULL || !is_const(key))
3254 return 0;
3255 }
3256 return 1;
3257}
3258
3259static int
3260compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3261{
3262 Py_ssize_t i, n = end - begin;
3263 PyObject *keys, *key;
3264 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3265 for (i = begin; i < end; i++) {
3266 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3267 }
3268 keys = PyTuple_New(n);
3269 if (keys == NULL) {
3270 return 0;
3271 }
3272 for (i = begin; i < end; i++) {
3273 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3274 Py_INCREF(key);
3275 PyTuple_SET_ITEM(keys, i - begin, key);
3276 }
3277 ADDOP_N(c, LOAD_CONST, keys, consts);
3278 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3279 }
3280 else {
3281 for (i = begin; i < end; i++) {
3282 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3283 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3284 }
3285 ADDOP_I(c, BUILD_MAP, n);
3286 }
3287 return 1;
3288}
3289
3290static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003291compiler_dict(struct compiler *c, expr_ty e)
3292{
Victor Stinner976bb402016-03-23 11:36:19 +01003293 Py_ssize_t i, n, elements;
3294 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003295 int is_unpacking = 0;
3296 n = asdl_seq_LEN(e->v.Dict.values);
3297 containers = 0;
3298 elements = 0;
3299 for (i = 0; i < n; i++) {
3300 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3301 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003302 if (!compiler_subdict(c, e, i - elements, i))
3303 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003304 containers++;
3305 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003307 if (is_unpacking) {
3308 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3309 containers++;
3310 }
3311 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003312 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 }
3314 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003315 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003316 if (!compiler_subdict(c, e, n - elements, n))
3317 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003318 containers++;
3319 }
3320 /* If there is more than one dict, they need to be merged into a new
3321 * dict. If there is one dict and it's an unpacking, then it needs
3322 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003323 if (containers > 1 || is_unpacking) {
3324 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 }
3326 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327}
3328
3329static int
3330compiler_compare(struct compiler *c, expr_ty e)
3331{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003332 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3336 VISIT(c, expr, e->v.Compare.left);
3337 n = asdl_seq_LEN(e->v.Compare.ops);
3338 assert(n > 0);
3339 if (n > 1) {
3340 cleanup = compiler_new_block(c);
3341 if (cleanup == NULL)
3342 return 0;
3343 VISIT(c, expr,
3344 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3345 }
3346 for (i = 1; i < n; i++) {
3347 ADDOP(c, DUP_TOP);
3348 ADDOP(c, ROT_THREE);
3349 ADDOP_I(c, COMPARE_OP,
3350 cmpop((cmpop_ty)(asdl_seq_GET(
3351 e->v.Compare.ops, i - 1))));
3352 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3353 NEXT_BLOCK(c);
3354 if (i < (n - 1))
3355 VISIT(c, expr,
3356 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3357 }
3358 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3359 ADDOP_I(c, COMPARE_OP,
3360 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3361 if (n > 1) {
3362 basicblock *end = compiler_new_block(c);
3363 if (end == NULL)
3364 return 0;
3365 ADDOP_JREL(c, JUMP_FORWARD, end);
3366 compiler_use_next_block(c, cleanup);
3367 ADDOP(c, ROT_TWO);
3368 ADDOP(c, POP_TOP);
3369 compiler_use_next_block(c, end);
3370 }
3371 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372}
3373
3374static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003375maybe_optimize_method_call(struct compiler *c, expr_ty e)
3376{
3377 Py_ssize_t argsl, i;
3378 expr_ty meth = e->v.Call.func;
3379 asdl_seq *args = e->v.Call.args;
3380
3381 /* Check that the call node is an attribute access, and that
3382 the call doesn't have keyword parameters. */
3383 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3384 asdl_seq_LEN(e->v.Call.keywords))
3385 return -1;
3386
3387 /* Check that there are no *varargs types of arguments. */
3388 argsl = asdl_seq_LEN(args);
3389 for (i = 0; i < argsl; i++) {
3390 expr_ty elt = asdl_seq_GET(args, i);
3391 if (elt->kind == Starred_kind) {
3392 return -1;
3393 }
3394 }
3395
3396 /* Alright, we can optimize the code. */
3397 VISIT(c, expr, meth->v.Attribute.value);
3398 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3399 VISIT_SEQ(c, expr, e->v.Call.args);
3400 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3401 return 1;
3402}
3403
3404static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405compiler_call(struct compiler *c, expr_ty e)
3406{
Yury Selivanovf2392132016-12-13 19:03:51 -05003407 if (maybe_optimize_method_call(c, e) > 0)
3408 return 1;
3409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 VISIT(c, expr, e->v.Call.func);
3411 return compiler_call_helper(c, 0,
3412 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003413 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003414}
3415
Eric V. Smith235a6f02015-09-19 14:51:32 -04003416static int
3417compiler_joined_str(struct compiler *c, expr_ty e)
3418{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003419 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003420 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3421 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003422 return 1;
3423}
3424
Eric V. Smitha78c7952015-11-03 12:45:05 -05003425/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003426static int
3427compiler_formatted_value(struct compiler *c, expr_ty e)
3428{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003429 /* Our oparg encodes 2 pieces of information: the conversion
3430 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003431
Eric V. Smitha78c7952015-11-03 12:45:05 -05003432 Convert the conversion char to 2 bits:
3433 None: 000 0x0 FVC_NONE
3434 !s : 001 0x1 FVC_STR
3435 !r : 010 0x2 FVC_REPR
3436 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003437
Eric V. Smitha78c7952015-11-03 12:45:05 -05003438 next bit is whether or not we have a format spec:
3439 yes : 100 0x4
3440 no : 000 0x0
3441 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003442
Eric V. Smitha78c7952015-11-03 12:45:05 -05003443 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003444
Eric V. Smitha78c7952015-11-03 12:45:05 -05003445 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003446 VISIT(c, expr, e->v.FormattedValue.value);
3447
Eric V. Smitha78c7952015-11-03 12:45:05 -05003448 switch (e->v.FormattedValue.conversion) {
3449 case 's': oparg = FVC_STR; break;
3450 case 'r': oparg = FVC_REPR; break;
3451 case 'a': oparg = FVC_ASCII; break;
3452 case -1: oparg = FVC_NONE; break;
3453 default:
3454 PyErr_SetString(PyExc_SystemError,
3455 "Unrecognized conversion character");
3456 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003457 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003458 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003459 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003460 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003461 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003462 }
3463
Eric V. Smitha78c7952015-11-03 12:45:05 -05003464 /* And push our opcode and oparg */
3465 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003466 return 1;
3467}
3468
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003469static int
3470compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3471{
3472 Py_ssize_t i, n = end - begin;
3473 keyword_ty kw;
3474 PyObject *keys, *key;
3475 assert(n > 0);
3476 if (n > 1) {
3477 for (i = begin; i < end; i++) {
3478 kw = asdl_seq_GET(keywords, i);
3479 VISIT(c, expr, kw->value);
3480 }
3481 keys = PyTuple_New(n);
3482 if (keys == NULL) {
3483 return 0;
3484 }
3485 for (i = begin; i < end; i++) {
3486 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3487 Py_INCREF(key);
3488 PyTuple_SET_ITEM(keys, i - begin, key);
3489 }
3490 ADDOP_N(c, LOAD_CONST, keys, consts);
3491 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3492 }
3493 else {
3494 /* a for loop only executes once */
3495 for (i = begin; i < end; i++) {
3496 kw = asdl_seq_GET(keywords, i);
3497 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3498 VISIT(c, expr, kw->value);
3499 }
3500 ADDOP_I(c, BUILD_MAP, n);
3501 }
3502 return 1;
3503}
3504
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003505/* shared code between compiler_call and compiler_class */
3506static int
3507compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003508 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003509 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003510 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003511{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003512 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003513 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003514
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003515 /* the number of tuples and dictionaries on the stack */
3516 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3517
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003518 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003519 nkwelts = asdl_seq_LEN(keywords);
3520
3521 for (i = 0; i < nkwelts; i++) {
3522 keyword_ty kw = asdl_seq_GET(keywords, i);
3523 if (kw->arg == NULL) {
3524 mustdictunpack = 1;
3525 break;
3526 }
3527 }
3528
3529 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003530 for (i = 0; i < nelts; i++) {
3531 expr_ty elt = asdl_seq_GET(args, i);
3532 if (elt->kind == Starred_kind) {
3533 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003534 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003535 if (nseen) {
3536 ADDOP_I(c, BUILD_TUPLE, nseen);
3537 nseen = 0;
3538 nsubargs++;
3539 }
3540 VISIT(c, expr, elt->v.Starred.value);
3541 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003542 }
3543 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003544 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003545 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003546 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003548
3549 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003550 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003551 if (nseen) {
3552 /* Pack up any trailing positional arguments. */
3553 ADDOP_I(c, BUILD_TUPLE, nseen);
3554 nsubargs++;
3555 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003556 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003557 /* If we ended up with more than one stararg, we need
3558 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003559 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003560 }
3561 else if (nsubargs == 0) {
3562 ADDOP_I(c, BUILD_TUPLE, 0);
3563 }
3564 nseen = 0; /* the number of keyword arguments on the stack following */
3565 for (i = 0; i < nkwelts; i++) {
3566 keyword_ty kw = asdl_seq_GET(keywords, i);
3567 if (kw->arg == NULL) {
3568 /* A keyword argument unpacking. */
3569 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003570 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3571 return 0;
3572 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003573 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003574 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003575 VISIT(c, expr, kw->value);
3576 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003577 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003578 else {
3579 nseen++;
3580 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003581 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003582 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003583 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003584 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003585 return 0;
3586 nsubkwargs++;
3587 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003588 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003589 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003590 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003591 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003592 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3593 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003595 else if (nkwelts) {
3596 PyObject *names;
3597 VISIT_SEQ(c, keyword, keywords);
3598 names = PyTuple_New(nkwelts);
3599 if (names == NULL) {
3600 return 0;
3601 }
3602 for (i = 0; i < nkwelts; i++) {
3603 keyword_ty kw = asdl_seq_GET(keywords, i);
3604 Py_INCREF(kw->arg);
3605 PyTuple_SET_ITEM(names, i, kw->arg);
3606 }
3607 ADDOP_N(c, LOAD_CONST, names, consts);
3608 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3609 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003611 else {
3612 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3613 return 1;
3614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615}
3616
Nick Coghlan650f0d02007-04-15 12:05:43 +00003617
3618/* List and set comprehensions and generator expressions work by creating a
3619 nested function to perform the actual iteration. This means that the
3620 iteration variables don't leak into the current scope.
3621 The defined function is called immediately following its definition, with the
3622 result of that call being the result of the expression.
3623 The LC/SC version returns the populated container, while the GE version is
3624 flagged in symtable.c as a generator, so it returns the generator object
3625 when the function is called.
3626 This code *knows* that the loop cannot contain break, continue, or return,
3627 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3628
3629 Possible cleanups:
3630 - iterate over the generator sequence instead of using recursion
3631*/
3632
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003633
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635compiler_comprehension_generator(struct compiler *c,
3636 asdl_seq *generators, int gen_index,
3637 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003639 comprehension_ty gen;
3640 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3641 if (gen->is_async) {
3642 return compiler_async_comprehension_generator(
3643 c, generators, gen_index, elt, val, type);
3644 } else {
3645 return compiler_sync_comprehension_generator(
3646 c, generators, gen_index, elt, val, type);
3647 }
3648}
3649
3650static int
3651compiler_sync_comprehension_generator(struct compiler *c,
3652 asdl_seq *generators, int gen_index,
3653 expr_ty elt, expr_ty val, int type)
3654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 /* generate code for the iterator, then each of the ifs,
3656 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 comprehension_ty gen;
3659 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003660 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 start = compiler_new_block(c);
3663 skip = compiler_new_block(c);
3664 if_cleanup = compiler_new_block(c);
3665 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3668 anchor == NULL)
3669 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 if (gen_index == 0) {
3674 /* Receive outermost iter as an implicit argument */
3675 c->u->u_argcount = 1;
3676 ADDOP_I(c, LOAD_FAST, 0);
3677 }
3678 else {
3679 /* Sub-iter - calculate on the fly */
3680 VISIT(c, expr, gen->iter);
3681 ADDOP(c, GET_ITER);
3682 }
3683 compiler_use_next_block(c, start);
3684 ADDOP_JREL(c, FOR_ITER, anchor);
3685 NEXT_BLOCK(c);
3686 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 /* XXX this needs to be cleaned up...a lot! */
3689 n = asdl_seq_LEN(gen->ifs);
3690 for (i = 0; i < n; i++) {
3691 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3692 VISIT(c, expr, e);
3693 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3694 NEXT_BLOCK(c);
3695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 if (++gen_index < asdl_seq_LEN(generators))
3698 if (!compiler_comprehension_generator(c,
3699 generators, gen_index,
3700 elt, val, type))
3701 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 /* only append after the last for generator */
3704 if (gen_index >= asdl_seq_LEN(generators)) {
3705 /* comprehension specific code */
3706 switch (type) {
3707 case COMP_GENEXP:
3708 VISIT(c, expr, elt);
3709 ADDOP(c, YIELD_VALUE);
3710 ADDOP(c, POP_TOP);
3711 break;
3712 case COMP_LISTCOMP:
3713 VISIT(c, expr, elt);
3714 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3715 break;
3716 case COMP_SETCOMP:
3717 VISIT(c, expr, elt);
3718 ADDOP_I(c, SET_ADD, gen_index + 1);
3719 break;
3720 case COMP_DICTCOMP:
3721 /* With 'd[k] = v', v is evaluated before k, so we do
3722 the same. */
3723 VISIT(c, expr, val);
3724 VISIT(c, expr, elt);
3725 ADDOP_I(c, MAP_ADD, gen_index + 1);
3726 break;
3727 default:
3728 return 0;
3729 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 compiler_use_next_block(c, skip);
3732 }
3733 compiler_use_next_block(c, if_cleanup);
3734 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3735 compiler_use_next_block(c, anchor);
3736
3737 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738}
3739
3740static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003741compiler_async_comprehension_generator(struct compiler *c,
3742 asdl_seq *generators, int gen_index,
3743 expr_ty elt, expr_ty val, int type)
3744{
3745 _Py_IDENTIFIER(StopAsyncIteration);
3746
3747 comprehension_ty gen;
3748 basicblock *anchor, *skip, *if_cleanup, *try,
3749 *after_try, *except, *try_cleanup;
3750 Py_ssize_t i, n;
3751
3752 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3753 if (stop_aiter_error == NULL) {
3754 return 0;
3755 }
3756
3757 try = compiler_new_block(c);
3758 after_try = compiler_new_block(c);
3759 try_cleanup = compiler_new_block(c);
3760 except = compiler_new_block(c);
3761 skip = compiler_new_block(c);
3762 if_cleanup = compiler_new_block(c);
3763 anchor = compiler_new_block(c);
3764
3765 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3766 try == NULL || after_try == NULL ||
3767 except == NULL || after_try == NULL) {
3768 return 0;
3769 }
3770
3771 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3772
3773 if (gen_index == 0) {
3774 /* Receive outermost iter as an implicit argument */
3775 c->u->u_argcount = 1;
3776 ADDOP_I(c, LOAD_FAST, 0);
3777 }
3778 else {
3779 /* Sub-iter - calculate on the fly */
3780 VISIT(c, expr, gen->iter);
3781 ADDOP(c, GET_AITER);
3782 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3783 ADDOP(c, YIELD_FROM);
3784 }
3785
3786 compiler_use_next_block(c, try);
3787
3788
3789 ADDOP_JREL(c, SETUP_EXCEPT, except);
3790 if (!compiler_push_fblock(c, EXCEPT, try))
3791 return 0;
3792
3793 ADDOP(c, GET_ANEXT);
3794 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3795 ADDOP(c, YIELD_FROM);
3796 VISIT(c, expr, gen->target);
3797 ADDOP(c, POP_BLOCK);
3798 compiler_pop_fblock(c, EXCEPT, try);
3799 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3800
3801
3802 compiler_use_next_block(c, except);
3803 ADDOP(c, DUP_TOP);
3804 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3805 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3806 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3807
3808 ADDOP(c, POP_TOP);
3809 ADDOP(c, POP_TOP);
3810 ADDOP(c, POP_TOP);
3811 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3812 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3813
3814
3815 compiler_use_next_block(c, try_cleanup);
3816 ADDOP(c, END_FINALLY);
3817
3818 compiler_use_next_block(c, after_try);
3819
3820 n = asdl_seq_LEN(gen->ifs);
3821 for (i = 0; i < n; i++) {
3822 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3823 VISIT(c, expr, e);
3824 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3825 NEXT_BLOCK(c);
3826 }
3827
3828 if (++gen_index < asdl_seq_LEN(generators))
3829 if (!compiler_comprehension_generator(c,
3830 generators, gen_index,
3831 elt, val, type))
3832 return 0;
3833
3834 /* only append after the last for generator */
3835 if (gen_index >= asdl_seq_LEN(generators)) {
3836 /* comprehension specific code */
3837 switch (type) {
3838 case COMP_GENEXP:
3839 VISIT(c, expr, elt);
3840 ADDOP(c, YIELD_VALUE);
3841 ADDOP(c, POP_TOP);
3842 break;
3843 case COMP_LISTCOMP:
3844 VISIT(c, expr, elt);
3845 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3846 break;
3847 case COMP_SETCOMP:
3848 VISIT(c, expr, elt);
3849 ADDOP_I(c, SET_ADD, gen_index + 1);
3850 break;
3851 case COMP_DICTCOMP:
3852 /* With 'd[k] = v', v is evaluated before k, so we do
3853 the same. */
3854 VISIT(c, expr, val);
3855 VISIT(c, expr, elt);
3856 ADDOP_I(c, MAP_ADD, gen_index + 1);
3857 break;
3858 default:
3859 return 0;
3860 }
3861
3862 compiler_use_next_block(c, skip);
3863 }
3864 compiler_use_next_block(c, if_cleanup);
3865 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3866 compiler_use_next_block(c, anchor);
3867 ADDOP(c, POP_TOP);
3868
3869 return 1;
3870}
3871
3872static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873compiler_comprehension(struct compiler *c, expr_ty e, int type,
3874 identifier name, asdl_seq *generators, expr_ty elt,
3875 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003878 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003879 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003880 int is_async_function = c->u->u_ste->ste_coroutine;
3881 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003882
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003883 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003884
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003885 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3886 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003887 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003889 }
3890
3891 is_async_generator = c->u->u_ste->ste_coroutine;
3892
3893 if (is_async_generator && !is_async_function) {
3894 if (e->lineno > c->u->u_lineno) {
3895 c->u->u_lineno = e->lineno;
3896 c->u->u_lineno_set = 0;
3897 }
3898 compiler_error(c, "asynchronous comprehension outside of "
3899 "an asynchronous function");
3900 goto error_in_scope;
3901 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (type != COMP_GENEXP) {
3904 int op;
3905 switch (type) {
3906 case COMP_LISTCOMP:
3907 op = BUILD_LIST;
3908 break;
3909 case COMP_SETCOMP:
3910 op = BUILD_SET;
3911 break;
3912 case COMP_DICTCOMP:
3913 op = BUILD_MAP;
3914 break;
3915 default:
3916 PyErr_Format(PyExc_SystemError,
3917 "unknown comprehension type %d", type);
3918 goto error_in_scope;
3919 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 ADDOP_I(c, op, 0);
3922 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 if (!compiler_comprehension_generator(c, generators, 0, elt,
3925 val, type))
3926 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 if (type != COMP_GENEXP) {
3929 ADDOP(c, RETURN_VALUE);
3930 }
3931
3932 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003933 qualname = c->u->u_qualname;
3934 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003936 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 goto error;
3938
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003939 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003941 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 Py_DECREF(co);
3943
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003944 VISIT(c, expr, outermost->iter);
3945
3946 if (outermost->is_async) {
3947 ADDOP(c, GET_AITER);
3948 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3949 ADDOP(c, YIELD_FROM);
3950 } else {
3951 ADDOP(c, GET_ITER);
3952 }
3953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003955
3956 if (is_async_generator && type != COMP_GENEXP) {
3957 ADDOP(c, GET_AWAITABLE);
3958 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3959 ADDOP(c, YIELD_FROM);
3960 }
3961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003963error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003965error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003966 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 Py_XDECREF(co);
3968 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003969}
3970
3971static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972compiler_genexp(struct compiler *c, expr_ty e)
3973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 static identifier name;
3975 if (!name) {
3976 name = PyUnicode_FromString("<genexpr>");
3977 if (!name)
3978 return 0;
3979 }
3980 assert(e->kind == GeneratorExp_kind);
3981 return compiler_comprehension(c, e, COMP_GENEXP, name,
3982 e->v.GeneratorExp.generators,
3983 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984}
3985
3986static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003987compiler_listcomp(struct compiler *c, expr_ty e)
3988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 static identifier name;
3990 if (!name) {
3991 name = PyUnicode_FromString("<listcomp>");
3992 if (!name)
3993 return 0;
3994 }
3995 assert(e->kind == ListComp_kind);
3996 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3997 e->v.ListComp.generators,
3998 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003999}
4000
4001static int
4002compiler_setcomp(struct compiler *c, expr_ty e)
4003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 static identifier name;
4005 if (!name) {
4006 name = PyUnicode_FromString("<setcomp>");
4007 if (!name)
4008 return 0;
4009 }
4010 assert(e->kind == SetComp_kind);
4011 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4012 e->v.SetComp.generators,
4013 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004014}
4015
4016
4017static int
4018compiler_dictcomp(struct compiler *c, expr_ty e)
4019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 static identifier name;
4021 if (!name) {
4022 name = PyUnicode_FromString("<dictcomp>");
4023 if (!name)
4024 return 0;
4025 }
4026 assert(e->kind == DictComp_kind);
4027 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4028 e->v.DictComp.generators,
4029 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004030}
4031
4032
4033static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004034compiler_visit_keyword(struct compiler *c, keyword_ty k)
4035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 VISIT(c, expr, k->value);
4037 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004038}
4039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004041 whether they are true or false.
4042
4043 Return values: 1 for true, 0 for false, -1 for non-constant.
4044 */
4045
4046static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004047expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004049 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 switch (e->kind) {
4051 case Ellipsis_kind:
4052 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004053 case Constant_kind:
4054 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 case Num_kind:
4056 return PyObject_IsTrue(e->v.Num.n);
4057 case Str_kind:
4058 return PyObject_IsTrue(e->v.Str.s);
4059 case Name_kind:
4060 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004061 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004062 if (id && strcmp(id, "__debug__") == 0)
4063 return !c->c_optimize;
4064 return -1;
4065 case NameConstant_kind: {
4066 PyObject *o = e->v.NameConstant.value;
4067 if (o == Py_None)
4068 return 0;
4069 else if (o == Py_True)
4070 return 1;
4071 else if (o == Py_False)
4072 return 0;
4073 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 default:
4075 return -1;
4076 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077}
4078
Yury Selivanov75445082015-05-11 22:57:16 -04004079
4080/*
4081 Implements the async with statement.
4082
4083 The semantics outlined in that PEP are as follows:
4084
4085 async with EXPR as VAR:
4086 BLOCK
4087
4088 It is implemented roughly as:
4089
4090 context = EXPR
4091 exit = context.__aexit__ # not calling it
4092 value = await context.__aenter__()
4093 try:
4094 VAR = value # if VAR present in the syntax
4095 BLOCK
4096 finally:
4097 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004098 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004099 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004100 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004101 if not (await exit(*exc)):
4102 raise
4103 */
4104static int
4105compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4106{
4107 basicblock *block, *finally;
4108 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4109
4110 assert(s->kind == AsyncWith_kind);
4111
4112 block = compiler_new_block(c);
4113 finally = compiler_new_block(c);
4114 if (!block || !finally)
4115 return 0;
4116
4117 /* Evaluate EXPR */
4118 VISIT(c, expr, item->context_expr);
4119
4120 ADDOP(c, BEFORE_ASYNC_WITH);
4121 ADDOP(c, GET_AWAITABLE);
4122 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4123 ADDOP(c, YIELD_FROM);
4124
4125 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4126
4127 /* SETUP_ASYNC_WITH pushes a finally block. */
4128 compiler_use_next_block(c, block);
4129 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4130 return 0;
4131 }
4132
4133 if (item->optional_vars) {
4134 VISIT(c, expr, item->optional_vars);
4135 }
4136 else {
4137 /* Discard result from context.__aenter__() */
4138 ADDOP(c, POP_TOP);
4139 }
4140
4141 pos++;
4142 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4143 /* BLOCK code */
4144 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4145 else if (!compiler_async_with(c, s, pos))
4146 return 0;
4147
4148 /* End of try block; start the finally block */
4149 ADDOP(c, POP_BLOCK);
4150 compiler_pop_fblock(c, FINALLY_TRY, block);
4151
4152 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4153 compiler_use_next_block(c, finally);
4154 if (!compiler_push_fblock(c, FINALLY_END, finally))
4155 return 0;
4156
4157 /* Finally block starts; context.__exit__ is on the stack under
4158 the exception or return information. Just issue our magic
4159 opcode. */
4160 ADDOP(c, WITH_CLEANUP_START);
4161
4162 ADDOP(c, GET_AWAITABLE);
4163 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4164 ADDOP(c, YIELD_FROM);
4165
4166 ADDOP(c, WITH_CLEANUP_FINISH);
4167
4168 /* Finally block ends. */
4169 ADDOP(c, END_FINALLY);
4170 compiler_pop_fblock(c, FINALLY_END, finally);
4171 return 1;
4172}
4173
4174
Guido van Rossumc2e20742006-02-27 22:32:47 +00004175/*
4176 Implements the with statement from PEP 343.
4177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004179
4180 with EXPR as VAR:
4181 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182
Guido van Rossumc2e20742006-02-27 22:32:47 +00004183 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184
Thomas Wouters477c8d52006-05-27 19:21:47 +00004185 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004186 exit = context.__exit__ # not calling it
4187 value = context.__enter__()
4188 try:
4189 VAR = value # if VAR present in the syntax
4190 BLOCK
4191 finally:
4192 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004193 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004194 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004195 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004196 exit(*exc)
4197 */
4198static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004199compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004200{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004201 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004202 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004203
4204 assert(s->kind == With_kind);
4205
Guido van Rossumc2e20742006-02-27 22:32:47 +00004206 block = compiler_new_block(c);
4207 finally = compiler_new_block(c);
4208 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004209 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004210
Thomas Wouters477c8d52006-05-27 19:21:47 +00004211 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004212 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004213 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004214
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004215 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004216 compiler_use_next_block(c, block);
4217 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004218 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004219 }
4220
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004221 if (item->optional_vars) {
4222 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004223 }
4224 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004226 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004227 }
4228
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004229 pos++;
4230 if (pos == asdl_seq_LEN(s->v.With.items))
4231 /* BLOCK code */
4232 VISIT_SEQ(c, stmt, s->v.With.body)
4233 else if (!compiler_with(c, s, pos))
4234 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004235
4236 /* End of try block; start the finally block */
4237 ADDOP(c, POP_BLOCK);
4238 compiler_pop_fblock(c, FINALLY_TRY, block);
4239
4240 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4241 compiler_use_next_block(c, finally);
4242 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004243 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004244
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004245 /* Finally block starts; context.__exit__ is on the stack under
4246 the exception or return information. Just issue our magic
4247 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004248 ADDOP(c, WITH_CLEANUP_START);
4249 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004250
4251 /* Finally block ends. */
4252 ADDOP(c, END_FINALLY);
4253 compiler_pop_fblock(c, FINALLY_END, finally);
4254 return 1;
4255}
4256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257static int
4258compiler_visit_expr(struct compiler *c, expr_ty e)
4259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 /* If expr e has a different line number than the last expr/stmt,
4261 set a new line number for the next instruction.
4262 */
4263 if (e->lineno > c->u->u_lineno) {
4264 c->u->u_lineno = e->lineno;
4265 c->u->u_lineno_set = 0;
4266 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004267 /* Updating the column offset is always harmless. */
4268 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 switch (e->kind) {
4270 case BoolOp_kind:
4271 return compiler_boolop(c, e);
4272 case BinOp_kind:
4273 VISIT(c, expr, e->v.BinOp.left);
4274 VISIT(c, expr, e->v.BinOp.right);
4275 ADDOP(c, binop(c, e->v.BinOp.op));
4276 break;
4277 case UnaryOp_kind:
4278 VISIT(c, expr, e->v.UnaryOp.operand);
4279 ADDOP(c, unaryop(e->v.UnaryOp.op));
4280 break;
4281 case Lambda_kind:
4282 return compiler_lambda(c, e);
4283 case IfExp_kind:
4284 return compiler_ifexp(c, e);
4285 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004286 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004288 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 case GeneratorExp_kind:
4290 return compiler_genexp(c, e);
4291 case ListComp_kind:
4292 return compiler_listcomp(c, e);
4293 case SetComp_kind:
4294 return compiler_setcomp(c, e);
4295 case DictComp_kind:
4296 return compiler_dictcomp(c, e);
4297 case Yield_kind:
4298 if (c->u->u_ste->ste_type != FunctionBlock)
4299 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004300 if (e->v.Yield.value) {
4301 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 }
4303 else {
4304 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4305 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004306 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004308 case YieldFrom_kind:
4309 if (c->u->u_ste->ste_type != FunctionBlock)
4310 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004311
4312 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4313 return compiler_error(c, "'yield from' inside async function");
4314
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004315 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004316 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004317 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4318 ADDOP(c, YIELD_FROM);
4319 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004320 case Await_kind:
4321 if (c->u->u_ste->ste_type != FunctionBlock)
4322 return compiler_error(c, "'await' outside function");
4323
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004324 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4325 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004326 return compiler_error(c, "'await' outside async function");
4327
4328 VISIT(c, expr, e->v.Await.value);
4329 ADDOP(c, GET_AWAITABLE);
4330 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4331 ADDOP(c, YIELD_FROM);
4332 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 case Compare_kind:
4334 return compiler_compare(c, e);
4335 case Call_kind:
4336 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004337 case Constant_kind:
4338 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4339 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 case Num_kind:
4341 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4342 break;
4343 case Str_kind:
4344 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4345 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004346 case JoinedStr_kind:
4347 return compiler_joined_str(c, e);
4348 case FormattedValue_kind:
4349 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 case Bytes_kind:
4351 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4352 break;
4353 case Ellipsis_kind:
4354 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4355 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004356 case NameConstant_kind:
4357 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4358 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 /* The following exprs can be assignment targets. */
4360 case Attribute_kind:
4361 if (e->v.Attribute.ctx != AugStore)
4362 VISIT(c, expr, e->v.Attribute.value);
4363 switch (e->v.Attribute.ctx) {
4364 case AugLoad:
4365 ADDOP(c, DUP_TOP);
4366 /* Fall through to load */
4367 case Load:
4368 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4369 break;
4370 case AugStore:
4371 ADDOP(c, ROT_TWO);
4372 /* Fall through to save */
4373 case Store:
4374 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4375 break;
4376 case Del:
4377 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4378 break;
4379 case Param:
4380 default:
4381 PyErr_SetString(PyExc_SystemError,
4382 "param invalid in attribute expression");
4383 return 0;
4384 }
4385 break;
4386 case Subscript_kind:
4387 switch (e->v.Subscript.ctx) {
4388 case AugLoad:
4389 VISIT(c, expr, e->v.Subscript.value);
4390 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4391 break;
4392 case Load:
4393 VISIT(c, expr, e->v.Subscript.value);
4394 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4395 break;
4396 case AugStore:
4397 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4398 break;
4399 case Store:
4400 VISIT(c, expr, e->v.Subscript.value);
4401 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4402 break;
4403 case Del:
4404 VISIT(c, expr, e->v.Subscript.value);
4405 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4406 break;
4407 case Param:
4408 default:
4409 PyErr_SetString(PyExc_SystemError,
4410 "param invalid in subscript expression");
4411 return 0;
4412 }
4413 break;
4414 case Starred_kind:
4415 switch (e->v.Starred.ctx) {
4416 case Store:
4417 /* In all legitimate cases, the Starred node was already replaced
4418 * by compiler_list/compiler_tuple. XXX: is that okay? */
4419 return compiler_error(c,
4420 "starred assignment target must be in a list or tuple");
4421 default:
4422 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004423 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 }
4425 break;
4426 case Name_kind:
4427 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4428 /* child nodes of List and Tuple will have expr_context set */
4429 case List_kind:
4430 return compiler_list(c, e);
4431 case Tuple_kind:
4432 return compiler_tuple(c, e);
4433 }
4434 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004435}
4436
4437static int
4438compiler_augassign(struct compiler *c, stmt_ty s)
4439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 expr_ty e = s->v.AugAssign.target;
4441 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 switch (e->kind) {
4446 case Attribute_kind:
4447 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4448 AugLoad, e->lineno, e->col_offset, c->c_arena);
4449 if (auge == NULL)
4450 return 0;
4451 VISIT(c, expr, auge);
4452 VISIT(c, expr, s->v.AugAssign.value);
4453 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4454 auge->v.Attribute.ctx = AugStore;
4455 VISIT(c, expr, auge);
4456 break;
4457 case Subscript_kind:
4458 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4459 AugLoad, e->lineno, e->col_offset, c->c_arena);
4460 if (auge == NULL)
4461 return 0;
4462 VISIT(c, expr, auge);
4463 VISIT(c, expr, s->v.AugAssign.value);
4464 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4465 auge->v.Subscript.ctx = AugStore;
4466 VISIT(c, expr, auge);
4467 break;
4468 case Name_kind:
4469 if (!compiler_nameop(c, e->v.Name.id, Load))
4470 return 0;
4471 VISIT(c, expr, s->v.AugAssign.value);
4472 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4473 return compiler_nameop(c, e->v.Name.id, Store);
4474 default:
4475 PyErr_Format(PyExc_SystemError,
4476 "invalid node type (%d) for augmented assignment",
4477 e->kind);
4478 return 0;
4479 }
4480 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004481}
4482
4483static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004484check_ann_expr(struct compiler *c, expr_ty e)
4485{
4486 VISIT(c, expr, e);
4487 ADDOP(c, POP_TOP);
4488 return 1;
4489}
4490
4491static int
4492check_annotation(struct compiler *c, stmt_ty s)
4493{
4494 /* Annotations are only evaluated in a module or class. */
4495 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4496 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4497 return check_ann_expr(c, s->v.AnnAssign.annotation);
4498 }
4499 return 1;
4500}
4501
4502static int
4503check_ann_slice(struct compiler *c, slice_ty sl)
4504{
4505 switch(sl->kind) {
4506 case Index_kind:
4507 return check_ann_expr(c, sl->v.Index.value);
4508 case Slice_kind:
4509 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4510 return 0;
4511 }
4512 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4513 return 0;
4514 }
4515 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4516 return 0;
4517 }
4518 break;
4519 default:
4520 PyErr_SetString(PyExc_SystemError,
4521 "unexpected slice kind");
4522 return 0;
4523 }
4524 return 1;
4525}
4526
4527static int
4528check_ann_subscr(struct compiler *c, slice_ty sl)
4529{
4530 /* We check that everything in a subscript is defined at runtime. */
4531 Py_ssize_t i, n;
4532
4533 switch (sl->kind) {
4534 case Index_kind:
4535 case Slice_kind:
4536 if (!check_ann_slice(c, sl)) {
4537 return 0;
4538 }
4539 break;
4540 case ExtSlice_kind:
4541 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4542 for (i = 0; i < n; i++) {
4543 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4544 switch (subsl->kind) {
4545 case Index_kind:
4546 case Slice_kind:
4547 if (!check_ann_slice(c, subsl)) {
4548 return 0;
4549 }
4550 break;
4551 case ExtSlice_kind:
4552 default:
4553 PyErr_SetString(PyExc_SystemError,
4554 "extended slice invalid in nested slice");
4555 return 0;
4556 }
4557 }
4558 break;
4559 default:
4560 PyErr_Format(PyExc_SystemError,
4561 "invalid subscript kind %d", sl->kind);
4562 return 0;
4563 }
4564 return 1;
4565}
4566
4567static int
4568compiler_annassign(struct compiler *c, stmt_ty s)
4569{
4570 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004571 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004572
4573 assert(s->kind == AnnAssign_kind);
4574
4575 /* We perform the actual assignment first. */
4576 if (s->v.AnnAssign.value) {
4577 VISIT(c, expr, s->v.AnnAssign.value);
4578 VISIT(c, expr, targ);
4579 }
4580 switch (targ->kind) {
4581 case Name_kind:
4582 /* If we have a simple name in a module or class, store annotation. */
4583 if (s->v.AnnAssign.simple &&
4584 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4585 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004586 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4587 if (!mangled) {
4588 return 0;
4589 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004590 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004591 /* ADDOP_N decrefs its argument */
4592 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004593 }
4594 break;
4595 case Attribute_kind:
4596 if (!s->v.AnnAssign.value &&
4597 !check_ann_expr(c, targ->v.Attribute.value)) {
4598 return 0;
4599 }
4600 break;
4601 case Subscript_kind:
4602 if (!s->v.AnnAssign.value &&
4603 (!check_ann_expr(c, targ->v.Subscript.value) ||
4604 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4605 return 0;
4606 }
4607 break;
4608 default:
4609 PyErr_Format(PyExc_SystemError,
4610 "invalid node type (%d) for annotated assignment",
4611 targ->kind);
4612 return 0;
4613 }
4614 /* Annotation is evaluated last. */
4615 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4616 return 0;
4617 }
4618 return 1;
4619}
4620
4621static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004622compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 struct fblockinfo *f;
4625 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004626 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 "too many statically nested blocks");
4628 return 0;
4629 }
4630 f = &c->u->u_fblock[c->u->u_nfblocks++];
4631 f->fb_type = t;
4632 f->fb_block = b;
4633 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004634}
4635
4636static void
4637compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 struct compiler_unit *u = c->u;
4640 assert(u->u_nfblocks > 0);
4641 u->u_nfblocks--;
4642 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4643 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004644}
4645
Thomas Wouters89f507f2006-12-13 04:49:30 +00004646static int
4647compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 int i;
4649 struct compiler_unit *u = c->u;
4650 for (i = 0; i < u->u_nfblocks; ++i) {
4651 if (u->u_fblock[i].fb_type == LOOP)
4652 return 1;
4653 }
4654 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004655}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004656/* Raises a SyntaxError and returns 0.
4657 If something goes wrong, a different exception may be raised.
4658*/
4659
4660static int
4661compiler_error(struct compiler *c, const char *errstr)
4662{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004663 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004665
Victor Stinner14e461d2013-08-26 22:28:21 +02004666 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 if (!loc) {
4668 Py_INCREF(Py_None);
4669 loc = Py_None;
4670 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004671 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004672 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 if (!u)
4674 goto exit;
4675 v = Py_BuildValue("(zO)", errstr, u);
4676 if (!v)
4677 goto exit;
4678 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004679 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 Py_DECREF(loc);
4681 Py_XDECREF(u);
4682 Py_XDECREF(v);
4683 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004684}
4685
4686static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687compiler_handle_subscr(struct compiler *c, const char *kind,
4688 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 /* XXX this code is duplicated */
4693 switch (ctx) {
4694 case AugLoad: /* fall through to Load */
4695 case Load: op = BINARY_SUBSCR; break;
4696 case AugStore:/* fall through to Store */
4697 case Store: op = STORE_SUBSCR; break;
4698 case Del: op = DELETE_SUBSCR; break;
4699 case Param:
4700 PyErr_Format(PyExc_SystemError,
4701 "invalid %s kind %d in subscript\n",
4702 kind, ctx);
4703 return 0;
4704 }
4705 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004706 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 }
4708 else if (ctx == AugStore) {
4709 ADDOP(c, ROT_THREE);
4710 }
4711 ADDOP(c, op);
4712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004713}
4714
4715static int
4716compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 int n = 2;
4719 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 /* only handles the cases where BUILD_SLICE is emitted */
4722 if (s->v.Slice.lower) {
4723 VISIT(c, expr, s->v.Slice.lower);
4724 }
4725 else {
4726 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 if (s->v.Slice.upper) {
4730 VISIT(c, expr, s->v.Slice.upper);
4731 }
4732 else {
4733 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4734 }
4735
4736 if (s->v.Slice.step) {
4737 n++;
4738 VISIT(c, expr, s->v.Slice.step);
4739 }
4740 ADDOP_I(c, BUILD_SLICE, n);
4741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004742}
4743
4744static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4746 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 switch (s->kind) {
4749 case Slice_kind:
4750 return compiler_slice(c, s, ctx);
4751 case Index_kind:
4752 VISIT(c, expr, s->v.Index.value);
4753 break;
4754 case ExtSlice_kind:
4755 default:
4756 PyErr_SetString(PyExc_SystemError,
4757 "extended slice invalid in nested slice");
4758 return 0;
4759 }
4760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004761}
4762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004763static int
4764compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004766 char * kindname = NULL;
4767 switch (s->kind) {
4768 case Index_kind:
4769 kindname = "index";
4770 if (ctx != AugStore) {
4771 VISIT(c, expr, s->v.Index.value);
4772 }
4773 break;
4774 case Slice_kind:
4775 kindname = "slice";
4776 if (ctx != AugStore) {
4777 if (!compiler_slice(c, s, ctx))
4778 return 0;
4779 }
4780 break;
4781 case ExtSlice_kind:
4782 kindname = "extended slice";
4783 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004784 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 for (i = 0; i < n; i++) {
4786 slice_ty sub = (slice_ty)asdl_seq_GET(
4787 s->v.ExtSlice.dims, i);
4788 if (!compiler_visit_nested_slice(c, sub, ctx))
4789 return 0;
4790 }
4791 ADDOP_I(c, BUILD_TUPLE, n);
4792 }
4793 break;
4794 default:
4795 PyErr_Format(PyExc_SystemError,
4796 "invalid subscript kind %d", s->kind);
4797 return 0;
4798 }
4799 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004800}
4801
Thomas Wouters89f507f2006-12-13 04:49:30 +00004802/* End of the compiler section, beginning of the assembler section */
4803
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004804/* do depth-first search of basic block graph, starting with block.
4805 post records the block indices in post-order.
4806
4807 XXX must handle implicit jumps from one block to next
4808*/
4809
Thomas Wouters89f507f2006-12-13 04:49:30 +00004810struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 PyObject *a_bytecode; /* string containing bytecode */
4812 int a_offset; /* offset into bytecode */
4813 int a_nblocks; /* number of reachable blocks */
4814 basicblock **a_postorder; /* list of blocks in dfs postorder */
4815 PyObject *a_lnotab; /* string containing lnotab */
4816 int a_lnotab_off; /* offset into lnotab */
4817 int a_lineno; /* last lineno of emitted instruction */
4818 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004819};
4820
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004821static void
4822dfs(struct compiler *c, basicblock *b, struct assembler *a)
4823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 int i;
4825 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 if (b->b_seen)
4828 return;
4829 b->b_seen = 1;
4830 if (b->b_next != NULL)
4831 dfs(c, b->b_next, a);
4832 for (i = 0; i < b->b_iused; i++) {
4833 instr = &b->b_instr[i];
4834 if (instr->i_jrel || instr->i_jabs)
4835 dfs(c, instr->i_target, a);
4836 }
4837 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004838}
4839
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004840static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004841stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4842{
Larry Hastings3a907972013-11-23 14:49:22 -08004843 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 struct instr *instr;
4845 if (b->b_seen || b->b_startdepth >= depth)
4846 return maxdepth;
4847 b->b_seen = 1;
4848 b->b_startdepth = depth;
4849 for (i = 0; i < b->b_iused; i++) {
4850 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004851 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4852 if (effect == PY_INVALID_STACK_EFFECT) {
4853 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4854 Py_FatalError("PyCompile_OpcodeStackEffect()");
4855 }
4856 depth += effect;
4857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 if (depth > maxdepth)
4859 maxdepth = depth;
4860 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4861 if (instr->i_jrel || instr->i_jabs) {
4862 target_depth = depth;
4863 if (instr->i_opcode == FOR_ITER) {
4864 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004865 }
4866 else if (instr->i_opcode == SETUP_FINALLY ||
4867 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 target_depth = depth+3;
4869 if (target_depth > maxdepth)
4870 maxdepth = target_depth;
4871 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004872 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4873 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4874 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 maxdepth = stackdepth_walk(c, instr->i_target,
4876 target_depth, maxdepth);
4877 if (instr->i_opcode == JUMP_ABSOLUTE ||
4878 instr->i_opcode == JUMP_FORWARD) {
4879 goto out; /* remaining code is dead */
4880 }
4881 }
4882 }
4883 if (b->b_next)
4884 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004885out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 b->b_seen = 0;
4887 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004888}
4889
4890/* Find the flow path that needs the largest stack. We assume that
4891 * cycles in the flow graph have no net effect on the stack depth.
4892 */
4893static int
4894stackdepth(struct compiler *c)
4895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 basicblock *b, *entryblock;
4897 entryblock = NULL;
4898 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4899 b->b_seen = 0;
4900 b->b_startdepth = INT_MIN;
4901 entryblock = b;
4902 }
4903 if (!entryblock)
4904 return 0;
4905 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004906}
4907
4908static int
4909assemble_init(struct assembler *a, int nblocks, int firstlineno)
4910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 memset(a, 0, sizeof(struct assembler));
4912 a->a_lineno = firstlineno;
4913 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4914 if (!a->a_bytecode)
4915 return 0;
4916 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4917 if (!a->a_lnotab)
4918 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004919 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 PyErr_NoMemory();
4921 return 0;
4922 }
4923 a->a_postorder = (basicblock **)PyObject_Malloc(
4924 sizeof(basicblock *) * nblocks);
4925 if (!a->a_postorder) {
4926 PyErr_NoMemory();
4927 return 0;
4928 }
4929 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004930}
4931
4932static void
4933assemble_free(struct assembler *a)
4934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 Py_XDECREF(a->a_bytecode);
4936 Py_XDECREF(a->a_lnotab);
4937 if (a->a_postorder)
4938 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004939}
4940
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004941static int
4942blocksize(basicblock *b)
4943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 int i;
4945 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004948 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004950}
4951
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004952/* Appends a pair to the end of the line number table, a_lnotab, representing
4953 the instruction's bytecode offset and line number. See
4954 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004955
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004956static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004957assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004959 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004960 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004962
Serhiy Storchakaab874002016-09-11 13:48:15 +03004963 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 if(d_bytecode == 0 && d_lineno == 0)
4969 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 if (d_bytecode > 255) {
4972 int j, nbytes, ncodes = d_bytecode / 255;
4973 nbytes = a->a_lnotab_off + 2 * ncodes;
4974 len = PyBytes_GET_SIZE(a->a_lnotab);
4975 if (nbytes >= len) {
4976 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4977 len = nbytes;
4978 else if (len <= INT_MAX / 2)
4979 len *= 2;
4980 else {
4981 PyErr_NoMemory();
4982 return 0;
4983 }
4984 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4985 return 0;
4986 }
4987 lnotab = (unsigned char *)
4988 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4989 for (j = 0; j < ncodes; j++) {
4990 *lnotab++ = 255;
4991 *lnotab++ = 0;
4992 }
4993 d_bytecode -= ncodes * 255;
4994 a->a_lnotab_off += ncodes * 2;
4995 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004996 assert(0 <= d_bytecode && d_bytecode <= 255);
4997
4998 if (d_lineno < -128 || 127 < d_lineno) {
4999 int j, nbytes, ncodes, k;
5000 if (d_lineno < 0) {
5001 k = -128;
5002 /* use division on positive numbers */
5003 ncodes = (-d_lineno) / 128;
5004 }
5005 else {
5006 k = 127;
5007 ncodes = d_lineno / 127;
5008 }
5009 d_lineno -= ncodes * k;
5010 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 nbytes = a->a_lnotab_off + 2 * ncodes;
5012 len = PyBytes_GET_SIZE(a->a_lnotab);
5013 if (nbytes >= len) {
5014 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5015 len = nbytes;
5016 else if (len <= INT_MAX / 2)
5017 len *= 2;
5018 else {
5019 PyErr_NoMemory();
5020 return 0;
5021 }
5022 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5023 return 0;
5024 }
5025 lnotab = (unsigned char *)
5026 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5027 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005028 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 d_bytecode = 0;
5030 for (j = 1; j < ncodes; j++) {
5031 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005032 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 a->a_lnotab_off += ncodes * 2;
5035 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005036 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 len = PyBytes_GET_SIZE(a->a_lnotab);
5039 if (a->a_lnotab_off + 2 >= len) {
5040 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5041 return 0;
5042 }
5043 lnotab = (unsigned char *)
5044 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 a->a_lnotab_off += 2;
5047 if (d_bytecode) {
5048 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005049 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 }
5051 else { /* First line of a block; def stmt, etc. */
5052 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005053 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 }
5055 a->a_lineno = i->i_lineno;
5056 a->a_lineno_off = a->a_offset;
5057 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005058}
5059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005060/* assemble_emit()
5061 Extend the bytecode with a new instruction.
5062 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005063*/
5064
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005065static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005066assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005067{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005068 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005070 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005071
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005072 arg = i->i_oparg;
5073 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 if (i->i_lineno && !assemble_lnotab(a, i))
5075 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005076 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 if (len > PY_SSIZE_T_MAX / 2)
5078 return 0;
5079 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5080 return 0;
5081 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005082 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005084 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005086}
5087
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005088static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005089assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005092 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 /* Compute the size of each block and fixup jump args.
5096 Replace block pointer with position in bytecode. */
5097 do {
5098 totsize = 0;
5099 for (i = a->a_nblocks - 1; i >= 0; i--) {
5100 b = a->a_postorder[i];
5101 bsize = blocksize(b);
5102 b->b_offset = totsize;
5103 totsize += bsize;
5104 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005105 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5107 bsize = b->b_offset;
5108 for (i = 0; i < b->b_iused; i++) {
5109 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005110 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 /* Relative jumps are computed relative to
5112 the instruction pointer after fetching
5113 the jump instruction.
5114 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005115 bsize += isize;
5116 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005118 if (instr->i_jrel) {
5119 instr->i_oparg -= bsize;
5120 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005121 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005122 if (instrsize(instr->i_oparg) != isize) {
5123 extended_arg_recompile = 1;
5124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 }
5127 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 /* XXX: This is an awful hack that could hurt performance, but
5130 on the bright side it should work until we come up
5131 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 The issue is that in the first loop blocksize() is called
5134 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005135 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 So we loop until we stop seeing new EXTENDED_ARGs.
5139 The only EXTENDED_ARGs that could be popping up are
5140 ones in jump instructions. So this should converge
5141 fairly quickly.
5142 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005143 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005144}
5145
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005146static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005147dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005150 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 tuple = PyTuple_New(size);
5153 if (tuple == NULL)
5154 return NULL;
5155 while (PyDict_Next(dict, &pos, &k, &v)) {
5156 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005157 /* The keys of the dictionary are tuples. (see compiler_add_o
5158 * and _PyCode_ConstantKey). The object we want is always second,
5159 * though. */
5160 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 Py_INCREF(k);
5162 assert((i - offset) < size);
5163 assert((i - offset) >= 0);
5164 PyTuple_SET_ITEM(tuple, i - offset, k);
5165 }
5166 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005167}
5168
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005169static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005170compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005173 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005175 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 if (ste->ste_nested)
5177 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005178 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005180 if (!ste->ste_generator && ste->ste_coroutine)
5181 flags |= CO_COROUTINE;
5182 if (ste->ste_generator && ste->ste_coroutine)
5183 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 if (ste->ste_varargs)
5185 flags |= CO_VARARGS;
5186 if (ste->ste_varkeywords)
5187 flags |= CO_VARKEYWORDS;
5188 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 /* (Only) inherit compilerflags in PyCF_MASK */
5191 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005192
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005193 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5194 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5195 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005199}
5200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005201static PyCodeObject *
5202makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 PyObject *tmp;
5205 PyCodeObject *co = NULL;
5206 PyObject *consts = NULL;
5207 PyObject *names = NULL;
5208 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 PyObject *name = NULL;
5210 PyObject *freevars = NULL;
5211 PyObject *cellvars = NULL;
5212 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005213 Py_ssize_t nlocals;
5214 int nlocals_int;
5215 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005216 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 tmp = dict_keys_inorder(c->u->u_consts, 0);
5219 if (!tmp)
5220 goto error;
5221 consts = PySequence_List(tmp); /* optimize_code requires a list */
5222 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 names = dict_keys_inorder(c->u->u_names, 0);
5225 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5226 if (!consts || !names || !varnames)
5227 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5230 if (!cellvars)
5231 goto error;
5232 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5233 if (!freevars)
5234 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005235
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005236 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005237 assert(nlocals < INT_MAX);
5238 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 flags = compute_code_flags(c);
5241 if (flags < 0)
5242 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5245 if (!bytecode)
5246 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5249 if (!tmp)
5250 goto error;
5251 Py_DECREF(consts);
5252 consts = tmp;
5253
Victor Stinnerf8e32212013-11-19 23:56:34 +01005254 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5255 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5256 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005257 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 bytecode, consts, names, varnames,
5259 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005260 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 c->u->u_firstlineno,
5262 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005263 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 Py_XDECREF(consts);
5265 Py_XDECREF(names);
5266 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 Py_XDECREF(name);
5268 Py_XDECREF(freevars);
5269 Py_XDECREF(cellvars);
5270 Py_XDECREF(bytecode);
5271 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005272}
5273
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005274
5275/* For debugging purposes only */
5276#if 0
5277static void
5278dump_instr(const struct instr *i)
5279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 const char *jrel = i->i_jrel ? "jrel " : "";
5281 const char *jabs = i->i_jabs ? "jabs " : "";
5282 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005285 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005287 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5289 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005290}
5291
5292static void
5293dump_basicblock(const basicblock *b)
5294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 const char *seen = b->b_seen ? "seen " : "";
5296 const char *b_return = b->b_return ? "return " : "";
5297 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5298 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5299 if (b->b_instr) {
5300 int i;
5301 for (i = 0; i < b->b_iused; i++) {
5302 fprintf(stderr, " [%02d] ", i);
5303 dump_instr(b->b_instr + i);
5304 }
5305 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005306}
5307#endif
5308
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005309static PyCodeObject *
5310assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 basicblock *b, *entryblock;
5313 struct assembler a;
5314 int i, j, nblocks;
5315 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 /* Make sure every block that falls off the end returns None.
5318 XXX NEXT_BLOCK() isn't quite right, because if the last
5319 block ends with a jump or return b_next shouldn't set.
5320 */
5321 if (!c->u->u_curblock->b_return) {
5322 NEXT_BLOCK(c);
5323 if (addNone)
5324 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5325 ADDOP(c, RETURN_VALUE);
5326 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 nblocks = 0;
5329 entryblock = NULL;
5330 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5331 nblocks++;
5332 entryblock = b;
5333 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 /* Set firstlineno if it wasn't explicitly set. */
5336 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005337 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5339 else
5340 c->u->u_firstlineno = 1;
5341 }
5342 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5343 goto error;
5344 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 /* Can't modify the bytecode after computing jump offsets. */
5347 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 /* Emit code in reverse postorder from dfs. */
5350 for (i = a.a_nblocks - 1; i >= 0; i--) {
5351 b = a.a_postorder[i];
5352 for (j = 0; j < b->b_iused; j++)
5353 if (!assemble_emit(&a, &b->b_instr[j]))
5354 goto error;
5355 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5358 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005359 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005363 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 assemble_free(&a);
5365 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005366}
Georg Brandl8334fd92010-12-04 10:26:46 +00005367
5368#undef PyAST_Compile
5369PyAPI_FUNC(PyCodeObject *)
5370PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5371 PyArena *arena)
5372{
5373 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5374}