blob: 797a1840e6a7f23e3a9c076c684aec8a2d8239aa [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);
567 assert(PyDict_Size(u->u_cellvars) == 0);
568 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,
594 PyDict_Size(u->u_cellvars));
595 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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001044 return -oparg-1;
1045 case CALL_FUNCTION_EX:
INADA Naoki3ab24bd2017-02-22 02:33:24 +09001046 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001047 case MAKE_FUNCTION:
1048 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1049 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case BUILD_SLICE:
1051 if (oparg == 3)
1052 return -2;
1053 else
1054 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case LOAD_CLOSURE:
1057 return 1;
1058 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001059 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 return 1;
1061 case STORE_DEREF:
1062 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001063 case DELETE_DEREF:
1064 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001065 case GET_AWAITABLE:
1066 return 0;
1067 case SETUP_ASYNC_WITH:
1068 return 6;
1069 case BEFORE_ASYNC_WITH:
1070 return 1;
1071 case GET_AITER:
1072 return 0;
1073 case GET_ANEXT:
1074 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001075 case GET_YIELD_FROM_ITER:
1076 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001077 case FORMAT_VALUE:
1078 /* If there's a fmt_spec on the stack, we go from 2->1,
1079 else 1->1. */
1080 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001082 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
Larry Hastings3a907972013-11-23 14:49:22 -08001084 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085}
1086
1087/* Add an opcode with no argument.
1088 Returns 0 on failure, 1 on success.
1089*/
1090
1091static int
1092compiler_addop(struct compiler *c, int opcode)
1093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 basicblock *b;
1095 struct instr *i;
1096 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001097 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 off = compiler_next_instr(c, c->u->u_curblock);
1099 if (off < 0)
1100 return 0;
1101 b = c->u->u_curblock;
1102 i = &b->b_instr[off];
1103 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001104 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (opcode == RETURN_VALUE)
1106 b->b_return = 1;
1107 compiler_set_lineno(c, off);
1108 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109}
1110
Victor Stinnerf8e32212013-11-19 23:56:34 +01001111static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyObject *t, *v;
1115 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116
Victor Stinnerefb24132016-01-22 12:33:12 +01001117 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (t == NULL)
1119 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 v = PyDict_GetItem(dict, t);
1122 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001123 if (PyErr_Occurred()) {
1124 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001128 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (!v) {
1130 Py_DECREF(t);
1131 return -1;
1132 }
1133 if (PyDict_SetItem(dict, t, v) < 0) {
1134 Py_DECREF(t);
1135 Py_DECREF(v);
1136 return -1;
1137 }
1138 Py_DECREF(v);
1139 }
1140 else
1141 arg = PyLong_AsLong(v);
1142 Py_DECREF(t);
1143 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144}
1145
1146static int
1147compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001150 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001152 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 return compiler_addop_i(c, opcode, arg);
1154}
1155
1156static int
1157compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001160 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1162 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001163 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 arg = compiler_add_o(c, dict, mangled);
1165 Py_DECREF(mangled);
1166 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001167 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 return compiler_addop_i(c, opcode, arg);
1169}
1170
1171/* Add an opcode with an integer argument.
1172 Returns 0 on failure, 1 on success.
1173*/
1174
1175static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001176compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 struct instr *i;
1179 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001180
Victor Stinner2ad474b2016-03-01 23:34:47 +01001181 /* oparg value is unsigned, but a signed C int is usually used to store
1182 it in the C code (like Python/ceval.c).
1183
1184 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1185
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001186 The argument of a concrete bytecode instruction is limited to 8-bit.
1187 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1188 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001189 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 off = compiler_next_instr(c, c->u->u_curblock);
1192 if (off < 0)
1193 return 0;
1194 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001195 i->i_opcode = opcode;
1196 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 compiler_set_lineno(c, off);
1198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199}
1200
1201static int
1202compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 struct instr *i;
1205 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001207 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 assert(b != NULL);
1209 off = compiler_next_instr(c, c->u->u_curblock);
1210 if (off < 0)
1211 return 0;
1212 i = &c->u->u_curblock->b_instr[off];
1213 i->i_opcode = opcode;
1214 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (absolute)
1216 i->i_jabs = 1;
1217 else
1218 i->i_jrel = 1;
1219 compiler_set_lineno(c, off);
1220 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221}
1222
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001223/* NEXT_BLOCK() creates an implicit jump from the current block
1224 to the new block.
1225
1226 The returns inside this macro make it impossible to decref objects
1227 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (compiler_next_block((C)) == NULL) \
1231 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001232}
1233
1234#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (!compiler_addop((C), (OP))) \
1236 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237}
1238
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001239#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (!compiler_addop((C), (OP))) { \
1241 compiler_exit_scope(c); \
1242 return 0; \
1243 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001244}
1245
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1248 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001251/* Same as ADDOP_O, but steals a reference. */
1252#define ADDOP_N(C, OP, O, TYPE) { \
1253 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1254 Py_DECREF((O)); \
1255 return 0; \
1256 } \
1257 Py_DECREF((O)); \
1258}
1259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1262 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
1265#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (!compiler_addop_i((C), (OP), (O))) \
1267 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268}
1269
1270#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 if (!compiler_addop_j((C), (OP), (O), 1)) \
1272 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273}
1274
1275#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (!compiler_addop_j((C), (OP), (O), 0)) \
1277 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278}
1279
1280/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1281 the ASDL name to synthesize the name of the C type and the visit function.
1282*/
1283
1284#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_visit_ ## TYPE((C), (V))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001289#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!compiler_visit_ ## TYPE((C), (V))) { \
1291 compiler_exit_scope(c); \
1292 return 0; \
1293 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001294}
1295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (!compiler_visit_slice((C), (V), (CTX))) \
1298 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299}
1300
1301#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 int _i; \
1303 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1304 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1305 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1306 if (!compiler_visit_ ## TYPE((C), elt)) \
1307 return 0; \
1308 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001311#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 int _i; \
1313 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1314 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1315 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1316 if (!compiler_visit_ ## TYPE((C), elt)) { \
1317 compiler_exit_scope(c); \
1318 return 0; \
1319 } \
1320 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001321}
1322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323static int
1324compiler_isdocstring(stmt_ty s)
1325{
1326 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001327 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001328 if (s->v.Expr.value->kind == Str_kind)
1329 return 1;
1330 if (s->v.Expr.value->kind == Constant_kind)
1331 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1332 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333}
1334
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001335static int
1336is_const(expr_ty e)
1337{
1338 switch (e->kind) {
1339 case Constant_kind:
1340 case Num_kind:
1341 case Str_kind:
1342 case Bytes_kind:
1343 case Ellipsis_kind:
1344 case NameConstant_kind:
1345 return 1;
1346 default:
1347 return 0;
1348 }
1349}
1350
1351static PyObject *
1352get_const_value(expr_ty e)
1353{
1354 switch (e->kind) {
1355 case Constant_kind:
1356 return e->v.Constant.value;
1357 case Num_kind:
1358 return e->v.Num.n;
1359 case Str_kind:
1360 return e->v.Str.s;
1361 case Bytes_kind:
1362 return e->v.Bytes.s;
1363 case Ellipsis_kind:
1364 return Py_Ellipsis;
1365 case NameConstant_kind:
1366 return e->v.NameConstant.value;
1367 default:
1368 assert(!is_const(e));
1369 return NULL;
1370 }
1371}
1372
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001373/* Search if variable annotations are present statically in a block. */
1374
1375static int
1376find_ann(asdl_seq *stmts)
1377{
1378 int i, j, res = 0;
1379 stmt_ty st;
1380
1381 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1382 st = (stmt_ty)asdl_seq_GET(stmts, i);
1383 switch (st->kind) {
1384 case AnnAssign_kind:
1385 return 1;
1386 case For_kind:
1387 res = find_ann(st->v.For.body) ||
1388 find_ann(st->v.For.orelse);
1389 break;
1390 case AsyncFor_kind:
1391 res = find_ann(st->v.AsyncFor.body) ||
1392 find_ann(st->v.AsyncFor.orelse);
1393 break;
1394 case While_kind:
1395 res = find_ann(st->v.While.body) ||
1396 find_ann(st->v.While.orelse);
1397 break;
1398 case If_kind:
1399 res = find_ann(st->v.If.body) ||
1400 find_ann(st->v.If.orelse);
1401 break;
1402 case With_kind:
1403 res = find_ann(st->v.With.body);
1404 break;
1405 case AsyncWith_kind:
1406 res = find_ann(st->v.AsyncWith.body);
1407 break;
1408 case Try_kind:
1409 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1410 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1411 st->v.Try.handlers, j);
1412 if (find_ann(handler->v.ExceptHandler.body)) {
1413 return 1;
1414 }
1415 }
1416 res = find_ann(st->v.Try.body) ||
1417 find_ann(st->v.Try.finalbody) ||
1418 find_ann(st->v.Try.orelse);
1419 break;
1420 default:
1421 res = 0;
1422 }
1423 if (res) {
1424 break;
1425 }
1426 }
1427 return res;
1428}
1429
1430/* Compile a sequence of statements, checking for a docstring
1431 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432
1433static int
1434compiler_body(struct compiler *c, asdl_seq *stmts)
1435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 int i = 0;
1437 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001439 /* Set current line number to the line number of first statement.
1440 This way line number for SETUP_ANNOTATIONS will always
1441 coincide with the line number of first "real" statement in module.
1442 If body is empy, then lineno will be set later in assemble. */
1443 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1444 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
1445 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1446 c->u->u_lineno = st->lineno;
1447 }
1448 /* Every annotated class and module should have __annotations__. */
1449 if (find_ann(stmts)) {
1450 ADDOP(c, SETUP_ANNOTATIONS);
1451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!asdl_seq_LEN(stmts))
1453 return 1;
1454 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001455 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* don't generate docstrings if -OO */
1457 i = 1;
1458 VISIT(c, expr, st->v.Expr.value);
1459 if (!compiler_nameop(c, __doc__, Store))
1460 return 0;
1461 }
1462 for (; i < asdl_seq_LEN(stmts); i++)
1463 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1464 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465}
1466
1467static PyCodeObject *
1468compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyCodeObject *co;
1471 int addNone = 1;
1472 static PyObject *module;
1473 if (!module) {
1474 module = PyUnicode_InternFromString("<module>");
1475 if (!module)
1476 return NULL;
1477 }
1478 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001479 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 return NULL;
1481 switch (mod->kind) {
1482 case Module_kind:
1483 if (!compiler_body(c, mod->v.Module.body)) {
1484 compiler_exit_scope(c);
1485 return 0;
1486 }
1487 break;
1488 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001489 if (find_ann(mod->v.Interactive.body)) {
1490 ADDOP(c, SETUP_ANNOTATIONS);
1491 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 c->c_interactive = 1;
1493 VISIT_SEQ_IN_SCOPE(c, stmt,
1494 mod->v.Interactive.body);
1495 break;
1496 case Expression_kind:
1497 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1498 addNone = 0;
1499 break;
1500 case Suite_kind:
1501 PyErr_SetString(PyExc_SystemError,
1502 "suite should not be possible");
1503 return 0;
1504 default:
1505 PyErr_Format(PyExc_SystemError,
1506 "module kind %d should not be possible",
1507 mod->kind);
1508 return 0;
1509 }
1510 co = assemble(c, addNone);
1511 compiler_exit_scope(c);
1512 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001513}
1514
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515/* The test for LOCAL must come before the test for FREE in order to
1516 handle classes where name is both local and free. The local var is
1517 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001518*/
1519
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520static int
1521get_ref_type(struct compiler *c, PyObject *name)
1522{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001523 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001524 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001525 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001526 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001527 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (scope == 0) {
1529 char buf[350];
1530 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001531 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001533 PyUnicode_AsUTF8(name),
1534 PyUnicode_AsUTF8(c->u->u_name),
1535 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1536 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1537 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1538 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 );
1540 Py_FatalError(buf);
1541 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544}
1545
1546static int
1547compiler_lookup_arg(PyObject *dict, PyObject *name)
1548{
1549 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001550 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001552 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001553 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001554 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001556 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001557 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001558}
1559
1560static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001561compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001563 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001564 if (qualname == NULL)
1565 qualname = co->co_name;
1566
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001567 if (free) {
1568 for (i = 0; i < free; ++i) {
1569 /* Bypass com_addop_varname because it will generate
1570 LOAD_DEREF but LOAD_CLOSURE is needed.
1571 */
1572 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1573 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001574
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001575 /* Special case: If a class contains a method with a
1576 free variable that has the same name as a method,
1577 the name will be considered free *and* local in the
1578 class. It should be handled by the closure, as
1579 well as by the normal name loookup logic.
1580 */
1581 reftype = get_ref_type(c, name);
1582 if (reftype == CELL)
1583 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1584 else /* (reftype == FREE) */
1585 arg = compiler_lookup_arg(c->u->u_freevars, name);
1586 if (arg == -1) {
1587 fprintf(stderr,
1588 "lookup %s in %s %d %d\n"
1589 "freevars of %s: %s\n",
1590 PyUnicode_AsUTF8(PyObject_Repr(name)),
1591 PyUnicode_AsUTF8(c->u->u_name),
1592 reftype, arg,
1593 PyUnicode_AsUTF8(co->co_name),
1594 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1595 Py_FatalError("compiler_make_closure()");
1596 }
1597 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001599 flags |= 0x08;
1600 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001603 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001604 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001606}
1607
1608static int
1609compiler_decorators(struct compiler *c, asdl_seq* decos)
1610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (!decos)
1614 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1617 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1618 }
1619 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001620}
1621
1622static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001623compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001625{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001626 /* Push a dict of keyword-only default values.
1627
1628 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1629 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001630 int i;
1631 PyObject *keys = NULL;
1632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1634 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1635 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1636 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001637 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001638 if (!mangled) {
1639 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001641 if (keys == NULL) {
1642 keys = PyList_New(1);
1643 if (keys == NULL) {
1644 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001645 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001646 }
1647 PyList_SET_ITEM(keys, 0, mangled);
1648 }
1649 else {
1650 int res = PyList_Append(keys, mangled);
1651 Py_DECREF(mangled);
1652 if (res == -1) {
1653 goto error;
1654 }
1655 }
1656 if (!compiler_visit_expr(c, default_)) {
1657 goto error;
1658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 }
1660 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001661 if (keys != NULL) {
1662 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1663 PyObject *keys_tuple = PyList_AsTuple(keys);
1664 Py_DECREF(keys);
1665 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001666 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001667 }
1668 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1669 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001670 assert(default_count > 0);
1671 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001672 }
1673 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001674 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001675 }
1676
1677error:
1678 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001679 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001680}
1681
1682static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001683compiler_visit_argannotation(struct compiler *c, identifier id,
1684 expr_ty annotation, PyObject *names)
1685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001687 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001689 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001690 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001692 if (PyList_Append(names, mangled) < 0) {
1693 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001694 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001695 }
1696 Py_DECREF(mangled);
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_argannotations(struct compiler *c, asdl_seq* args,
1703 PyObject *names)
1704{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001705 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 for (i = 0; i < asdl_seq_LEN(args); i++) {
1707 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001708 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 c,
1710 arg->arg,
1711 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001712 names))
1713 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001715 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001716}
1717
1718static int
1719compiler_visit_annotations(struct compiler *c, arguments_ty args,
1720 expr_ty returns)
1721{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001722 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001723 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001724
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001725 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 */
1727 static identifier return_str;
1728 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001729 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 names = PyList_New(0);
1731 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001732 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001733
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001734 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001736 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001737 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001738 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001740 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001742 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001743 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001744 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (!return_str) {
1748 return_str = PyUnicode_InternFromString("return");
1749 if (!return_str)
1750 goto error;
1751 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001752 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 goto error;
1754 }
1755
1756 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001758 PyObject *keytuple = PyList_AsTuple(names);
1759 Py_DECREF(names);
1760 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001761 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001763 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1764 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001765 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001767 else {
1768 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001769 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001770 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001771
1772error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001774 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001775}
1776
1777static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001778compiler_visit_defaults(struct compiler *c, arguments_ty args)
1779{
1780 VISIT_SEQ(c, expr, args->defaults);
1781 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1782 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783}
1784
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001785static Py_ssize_t
1786compiler_default_arguments(struct compiler *c, arguments_ty args)
1787{
1788 Py_ssize_t funcflags = 0;
1789 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001790 if (!compiler_visit_defaults(c, args))
1791 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001792 funcflags |= 0x01;
1793 }
1794 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001795 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001796 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001797 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001798 return -1;
1799 }
1800 else if (res > 0) {
1801 funcflags |= 0x02;
1802 }
1803 }
1804 return funcflags;
1805}
1806
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807static int
Yury Selivanov75445082015-05-11 22:57:16 -04001808compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001811 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001812 arguments_ty args;
1813 expr_ty returns;
1814 identifier name;
1815 asdl_seq* decos;
1816 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001818 Py_ssize_t i, n, funcflags;
1819 int docstring;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001820 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001821 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822
Yury Selivanov75445082015-05-11 22:57:16 -04001823 if (is_async) {
1824 assert(s->kind == AsyncFunctionDef_kind);
1825
1826 args = s->v.AsyncFunctionDef.args;
1827 returns = s->v.AsyncFunctionDef.returns;
1828 decos = s->v.AsyncFunctionDef.decorator_list;
1829 name = s->v.AsyncFunctionDef.name;
1830 body = s->v.AsyncFunctionDef.body;
1831
1832 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1833 } else {
1834 assert(s->kind == FunctionDef_kind);
1835
1836 args = s->v.FunctionDef.args;
1837 returns = s->v.FunctionDef.returns;
1838 decos = s->v.FunctionDef.decorator_list;
1839 name = s->v.FunctionDef.name;
1840 body = s->v.FunctionDef.body;
1841
1842 scope_type = COMPILER_SCOPE_FUNCTION;
1843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (!compiler_decorators(c, decos))
1846 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001847
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001848 funcflags = compiler_default_arguments(c, args);
1849 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001851 }
1852
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001853 annotations = compiler_visit_annotations(c, args, returns);
1854 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001855 return 0;
1856 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001857 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001858 funcflags |= 0x04;
1859 }
1860
1861 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1862 return 0;
1863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864
Yury Selivanov75445082015-05-11 22:57:16 -04001865 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001867 if (docstring && c->c_optimize < 2) {
1868 if (st->v.Expr.value->kind == Constant_kind)
1869 first_const = st->v.Expr.value->v.Constant.value;
1870 else
1871 first_const = st->v.Expr.value->v.Str.s;
1872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1874 compiler_exit_scope(c);
1875 return 0;
1876 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 c->u->u_argcount = asdl_seq_LEN(args->args);
1879 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001880 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* if there was a docstring, we need to skip the first statement */
1882 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001883 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 VISIT_IN_SCOPE(c, stmt, st);
1885 }
1886 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001887 qualname = c->u->u_qualname;
1888 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001890 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001891 Py_XDECREF(qualname);
1892 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001894 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001896 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001897 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* decorators */
1901 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1902 ADDOP_I(c, CALL_FUNCTION, 1);
1903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904
Yury Selivanov75445082015-05-11 22:57:16 -04001905 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906}
1907
1908static int
1909compiler_class(struct compiler *c, stmt_ty s)
1910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyCodeObject *co;
1912 PyObject *str;
1913 int i;
1914 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (!compiler_decorators(c, decos))
1917 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 /* ultimately generate code for:
1920 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1921 where:
1922 <func> is a function/closure created from the class body;
1923 it has a single argument (__locals__) where the dict
1924 (or MutableSequence) representing the locals is passed
1925 <name> is the class name
1926 <bases> is the positional arguments and *varargs argument
1927 <keywords> is the keyword arguments and **kwds argument
1928 This borrows from compiler_call.
1929 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001932 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1933 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 return 0;
1935 /* this block represents what we do in the new scope */
1936 {
1937 /* use the class name for name mangling */
1938 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001939 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* load (global) __name__ ... */
1941 str = PyUnicode_InternFromString("__name__");
1942 if (!str || !compiler_nameop(c, str, Load)) {
1943 Py_XDECREF(str);
1944 compiler_exit_scope(c);
1945 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001946 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 Py_DECREF(str);
1948 /* ... and store it as __module__ */
1949 str = PyUnicode_InternFromString("__module__");
1950 if (!str || !compiler_nameop(c, str, Store)) {
1951 Py_XDECREF(str);
1952 compiler_exit_scope(c);
1953 return 0;
1954 }
1955 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001956 assert(c->u->u_qualname);
1957 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001958 str = PyUnicode_InternFromString("__qualname__");
1959 if (!str || !compiler_nameop(c, str, Store)) {
1960 Py_XDECREF(str);
1961 compiler_exit_scope(c);
1962 return 0;
1963 }
1964 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 /* compile the body proper */
1966 if (!compiler_body(c, s->v.ClassDef.body)) {
1967 compiler_exit_scope(c);
1968 return 0;
1969 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001970 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001971 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001972 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001973 str = PyUnicode_InternFromString("__class__");
1974 if (str == NULL) {
1975 compiler_exit_scope(c);
1976 return 0;
1977 }
1978 i = compiler_lookup_arg(c->u->u_cellvars, str);
1979 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001980 if (i < 0) {
1981 compiler_exit_scope(c);
1982 return 0;
1983 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001984 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001987 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001988 str = PyUnicode_InternFromString("__classcell__");
1989 if (!str || !compiler_nameop(c, str, Store)) {
1990 Py_XDECREF(str);
1991 compiler_exit_scope(c);
1992 return 0;
1993 }
1994 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001996 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001997 /* No methods referenced __class__, so just return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001998 assert(PyDict_Size(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001999 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002000 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002001 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* create the code object */
2003 co = assemble(c, 1);
2004 }
2005 /* leave the new scope */
2006 compiler_exit_scope(c);
2007 if (co == NULL)
2008 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* 2. load the 'build_class' function */
2011 ADDOP(c, LOAD_BUILD_CLASS);
2012
2013 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002014 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 Py_DECREF(co);
2016
2017 /* 4. load class name */
2018 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2019
2020 /* 5. generate the rest of the code for the call */
2021 if (!compiler_call_helper(c, 2,
2022 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002023 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return 0;
2025
2026 /* 6. apply decorators */
2027 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2028 ADDOP_I(c, CALL_FUNCTION, 1);
2029 }
2030
2031 /* 7. store into <name> */
2032 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2033 return 0;
2034 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035}
2036
2037static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002038compiler_ifexp(struct compiler *c, expr_ty e)
2039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 basicblock *end, *next;
2041
2042 assert(e->kind == IfExp_kind);
2043 end = compiler_new_block(c);
2044 if (end == NULL)
2045 return 0;
2046 next = compiler_new_block(c);
2047 if (next == NULL)
2048 return 0;
2049 VISIT(c, expr, e->v.IfExp.test);
2050 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2051 VISIT(c, expr, e->v.IfExp.body);
2052 ADDOP_JREL(c, JUMP_FORWARD, end);
2053 compiler_use_next_block(c, next);
2054 VISIT(c, expr, e->v.IfExp.orelse);
2055 compiler_use_next_block(c, end);
2056 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002057}
2058
2059static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060compiler_lambda(struct compiler *c, expr_ty e)
2061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002063 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002065 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 arguments_ty args = e->v.Lambda.args;
2067 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (!name) {
2070 name = PyUnicode_InternFromString("<lambda>");
2071 if (!name)
2072 return 0;
2073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002075 funcflags = compiler_default_arguments(c, args);
2076 if (funcflags == -1) {
2077 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002079
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002080 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002081 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Make None the first constant, so the lambda can't have a
2085 docstring. */
2086 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 c->u->u_argcount = asdl_seq_LEN(args->args);
2090 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2091 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2092 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002093 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 }
2095 else {
2096 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002097 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002099 qualname = c->u->u_qualname;
2100 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002102 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002106 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 Py_DECREF(co);
2108
2109 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110}
2111
2112static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113compiler_if(struct compiler *c, stmt_ty s)
2114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 basicblock *end, *next;
2116 int constant;
2117 assert(s->kind == If_kind);
2118 end = compiler_new_block(c);
2119 if (end == NULL)
2120 return 0;
2121
Georg Brandl8334fd92010-12-04 10:26:46 +00002122 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* constant = 0: "if 0"
2124 * constant = 1: "if 1", "if 2", ...
2125 * constant = -1: rest */
2126 if (constant == 0) {
2127 if (s->v.If.orelse)
2128 VISIT_SEQ(c, stmt, s->v.If.orelse);
2129 } else if (constant == 1) {
2130 VISIT_SEQ(c, stmt, s->v.If.body);
2131 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002132 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 next = compiler_new_block(c);
2134 if (next == NULL)
2135 return 0;
2136 }
2137 else
2138 next = end;
2139 VISIT(c, expr, s->v.If.test);
2140 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2141 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002142 if (asdl_seq_LEN(s->v.If.orelse)) {
2143 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 compiler_use_next_block(c, next);
2145 VISIT_SEQ(c, stmt, s->v.If.orelse);
2146 }
2147 }
2148 compiler_use_next_block(c, end);
2149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150}
2151
2152static int
2153compiler_for(struct compiler *c, stmt_ty s)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 start = compiler_new_block(c);
2158 cleanup = compiler_new_block(c);
2159 end = compiler_new_block(c);
2160 if (start == NULL || end == NULL || cleanup == NULL)
2161 return 0;
2162 ADDOP_JREL(c, SETUP_LOOP, end);
2163 if (!compiler_push_fblock(c, LOOP, start))
2164 return 0;
2165 VISIT(c, expr, s->v.For.iter);
2166 ADDOP(c, GET_ITER);
2167 compiler_use_next_block(c, start);
2168 ADDOP_JREL(c, FOR_ITER, cleanup);
2169 VISIT(c, expr, s->v.For.target);
2170 VISIT_SEQ(c, stmt, s->v.For.body);
2171 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2172 compiler_use_next_block(c, cleanup);
2173 ADDOP(c, POP_BLOCK);
2174 compiler_pop_fblock(c, LOOP, start);
2175 VISIT_SEQ(c, stmt, s->v.For.orelse);
2176 compiler_use_next_block(c, end);
2177 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178}
2179
Yury Selivanov75445082015-05-11 22:57:16 -04002180
2181static int
2182compiler_async_for(struct compiler *c, stmt_ty s)
2183{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002184 _Py_IDENTIFIER(StopAsyncIteration);
2185
Yury Selivanov75445082015-05-11 22:57:16 -04002186 basicblock *try, *except, *end, *after_try, *try_cleanup,
2187 *after_loop, *after_loop_else;
2188
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002189 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2190 if (stop_aiter_error == NULL) {
2191 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002192 }
2193
2194 try = compiler_new_block(c);
2195 except = compiler_new_block(c);
2196 end = compiler_new_block(c);
2197 after_try = compiler_new_block(c);
2198 try_cleanup = compiler_new_block(c);
2199 after_loop = compiler_new_block(c);
2200 after_loop_else = compiler_new_block(c);
2201
2202 if (try == NULL || except == NULL || end == NULL
2203 || after_try == NULL || try_cleanup == NULL)
2204 return 0;
2205
2206 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2207 if (!compiler_push_fblock(c, LOOP, try))
2208 return 0;
2209
2210 VISIT(c, expr, s->v.AsyncFor.iter);
2211 ADDOP(c, GET_AITER);
2212 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2213 ADDOP(c, YIELD_FROM);
2214
2215 compiler_use_next_block(c, try);
2216
2217
2218 ADDOP_JREL(c, SETUP_EXCEPT, except);
2219 if (!compiler_push_fblock(c, EXCEPT, try))
2220 return 0;
2221
2222 ADDOP(c, GET_ANEXT);
2223 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2224 ADDOP(c, YIELD_FROM);
2225 VISIT(c, expr, s->v.AsyncFor.target);
2226 ADDOP(c, POP_BLOCK);
2227 compiler_pop_fblock(c, EXCEPT, try);
2228 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2229
2230
2231 compiler_use_next_block(c, except);
2232 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002233 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002234 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2235 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2236
2237 ADDOP(c, POP_TOP);
2238 ADDOP(c, POP_TOP);
2239 ADDOP(c, POP_TOP);
2240 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2241 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2242 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2243
2244
2245 compiler_use_next_block(c, try_cleanup);
2246 ADDOP(c, END_FINALLY);
2247
2248 compiler_use_next_block(c, after_try);
2249 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2250 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2251
2252 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2253 compiler_pop_fblock(c, LOOP, try);
2254
2255 compiler_use_next_block(c, after_loop);
2256 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2257
2258 compiler_use_next_block(c, after_loop_else);
2259 VISIT_SEQ(c, stmt, s->v.For.orelse);
2260
2261 compiler_use_next_block(c, end);
2262
2263 return 1;
2264}
2265
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266static int
2267compiler_while(struct compiler *c, stmt_ty s)
2268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002270 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (constant == 0) {
2273 if (s->v.While.orelse)
2274 VISIT_SEQ(c, stmt, s->v.While.orelse);
2275 return 1;
2276 }
2277 loop = compiler_new_block(c);
2278 end = compiler_new_block(c);
2279 if (constant == -1) {
2280 anchor = compiler_new_block(c);
2281 if (anchor == NULL)
2282 return 0;
2283 }
2284 if (loop == NULL || end == NULL)
2285 return 0;
2286 if (s->v.While.orelse) {
2287 orelse = compiler_new_block(c);
2288 if (orelse == NULL)
2289 return 0;
2290 }
2291 else
2292 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 ADDOP_JREL(c, SETUP_LOOP, end);
2295 compiler_use_next_block(c, loop);
2296 if (!compiler_push_fblock(c, LOOP, loop))
2297 return 0;
2298 if (constant == -1) {
2299 VISIT(c, expr, s->v.While.test);
2300 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2301 }
2302 VISIT_SEQ(c, stmt, s->v.While.body);
2303 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* XXX should the two POP instructions be in a separate block
2306 if there is no else clause ?
2307 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002309 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002311 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 compiler_pop_fblock(c, LOOP, loop);
2313 if (orelse != NULL) /* what if orelse is just pass? */
2314 VISIT_SEQ(c, stmt, s->v.While.orelse);
2315 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318}
2319
2320static int
2321compiler_continue(struct compiler *c)
2322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2324 static const char IN_FINALLY_ERROR_MSG[] =
2325 "'continue' not supported inside 'finally' clause";
2326 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (!c->u->u_nfblocks)
2329 return compiler_error(c, LOOP_ERROR_MSG);
2330 i = c->u->u_nfblocks - 1;
2331 switch (c->u->u_fblock[i].fb_type) {
2332 case LOOP:
2333 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2334 break;
2335 case EXCEPT:
2336 case FINALLY_TRY:
2337 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2338 /* Prevent continue anywhere under a finally
2339 even if hidden in a sub-try or except. */
2340 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2341 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2342 }
2343 if (i == -1)
2344 return compiler_error(c, LOOP_ERROR_MSG);
2345 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2346 break;
2347 case FINALLY_END:
2348 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2349 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352}
2353
2354/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355
2356 SETUP_FINALLY L
2357 <code for body>
2358 POP_BLOCK
2359 LOAD_CONST <None>
2360 L: <code for finalbody>
2361 END_FINALLY
2362
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363 The special instructions use the block stack. Each block
2364 stack entry contains the instruction that created it (here
2365 SETUP_FINALLY), the level of the value stack at the time the
2366 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 Pushes the current value stack level and the label
2370 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 Pops en entry from the block stack, and pops the value
2373 stack until its level is the same as indicated on the
2374 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Pops a variable number of entries from the *value* stack
2377 and re-raises the exception they specify. The number of
2378 entries popped depends on the (pseudo) exception type.
2379
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380 The block stack is unwound when an exception is raised:
2381 when a SETUP_FINALLY entry is found, the exception is pushed
2382 onto the value stack (and the exception condition is cleared),
2383 and the interpreter jumps to the label gotten from the block
2384 stack.
2385*/
2386
2387static int
2388compiler_try_finally(struct compiler *c, stmt_ty s)
2389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 basicblock *body, *end;
2391 body = compiler_new_block(c);
2392 end = compiler_new_block(c);
2393 if (body == NULL || end == NULL)
2394 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 ADDOP_JREL(c, SETUP_FINALLY, end);
2397 compiler_use_next_block(c, body);
2398 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2399 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002400 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2401 if (!compiler_try_except(c, s))
2402 return 0;
2403 }
2404 else {
2405 VISIT_SEQ(c, stmt, s->v.Try.body);
2406 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 ADDOP(c, POP_BLOCK);
2408 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2411 compiler_use_next_block(c, end);
2412 if (!compiler_push_fblock(c, FINALLY_END, end))
2413 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002414 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 ADDOP(c, END_FINALLY);
2416 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419}
2420
2421/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002422 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423 (The contents of the value stack is shown in [], with the top
2424 at the right; 'tb' is trace-back info, 'val' the exception's
2425 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426
2427 Value stack Label Instruction Argument
2428 [] SETUP_EXCEPT L1
2429 [] <code for S>
2430 [] POP_BLOCK
2431 [] JUMP_FORWARD L0
2432
2433 [tb, val, exc] L1: DUP )
2434 [tb, val, exc, exc] <evaluate E1> )
2435 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2436 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2437 [tb, val, exc] POP
2438 [tb, val] <assign to V1> (or POP if no V1)
2439 [tb] POP
2440 [] <code for S1>
2441 JUMP_FORWARD L0
2442
2443 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 .............................etc.......................
2445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2447
2448 [] L0: <next statement>
2449
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 Of course, parts are not generated if Vi or Ei is not present.
2451*/
2452static int
2453compiler_try_except(struct compiler *c, stmt_ty s)
2454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002456 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 body = compiler_new_block(c);
2459 except = compiler_new_block(c);
2460 orelse = compiler_new_block(c);
2461 end = compiler_new_block(c);
2462 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2463 return 0;
2464 ADDOP_JREL(c, SETUP_EXCEPT, except);
2465 compiler_use_next_block(c, body);
2466 if (!compiler_push_fblock(c, EXCEPT, body))
2467 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002468 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 ADDOP(c, POP_BLOCK);
2470 compiler_pop_fblock(c, EXCEPT, body);
2471 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002472 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 compiler_use_next_block(c, except);
2474 for (i = 0; i < n; i++) {
2475 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002476 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (!handler->v.ExceptHandler.type && i < n-1)
2478 return compiler_error(c, "default 'except:' must be last");
2479 c->u->u_lineno_set = 0;
2480 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002481 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 except = compiler_new_block(c);
2483 if (except == NULL)
2484 return 0;
2485 if (handler->v.ExceptHandler.type) {
2486 ADDOP(c, DUP_TOP);
2487 VISIT(c, expr, handler->v.ExceptHandler.type);
2488 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2489 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2490 }
2491 ADDOP(c, POP_TOP);
2492 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002493 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002494
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002495 cleanup_end = compiler_new_block(c);
2496 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002497 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002498 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002499
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002500 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2501 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002503 /*
2504 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002505 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002506 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002507 try:
2508 # body
2509 finally:
2510 name = None
2511 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002512 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002514 /* second try: */
2515 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2516 compiler_use_next_block(c, cleanup_body);
2517 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2518 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002520 /* second # body */
2521 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2522 ADDOP(c, POP_BLOCK);
2523 ADDOP(c, POP_EXCEPT);
2524 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002526 /* finally: */
2527 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2528 compiler_use_next_block(c, cleanup_end);
2529 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2530 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002532 /* name = None */
2533 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2534 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002536 /* del name */
2537 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002539 ADDOP(c, END_FINALLY);
2540 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 }
2542 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002543 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002545 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002546 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002547 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548
Guido van Rossumb940e112007-01-10 16:19:56 +00002549 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002550 ADDOP(c, POP_TOP);
2551 compiler_use_next_block(c, cleanup_body);
2552 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2553 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002555 ADDOP(c, POP_EXCEPT);
2556 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 }
2558 ADDOP_JREL(c, JUMP_FORWARD, end);
2559 compiler_use_next_block(c, except);
2560 }
2561 ADDOP(c, END_FINALLY);
2562 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002563 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 compiler_use_next_block(c, end);
2565 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566}
2567
2568static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002569compiler_try(struct compiler *c, stmt_ty s) {
2570 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2571 return compiler_try_finally(c, s);
2572 else
2573 return compiler_try_except(c, s);
2574}
2575
2576
2577static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578compiler_import_as(struct compiler *c, identifier name, identifier asname)
2579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* The IMPORT_NAME opcode was already generated. This function
2581 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 If there is a dot in name, we need to split it and emit a
2584 LOAD_ATTR for each name.
2585 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002586 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2587 PyUnicode_GET_LENGTH(name), 1);
2588 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002589 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 Py_ssize_t pos = dot + 1;
2593 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 dot = PyUnicode_FindChar(name, '.', pos,
2596 PyUnicode_GET_LENGTH(name), 1);
2597 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002598 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002599 attr = PyUnicode_Substring(name, pos,
2600 (dot != -1) ? dot :
2601 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002603 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 ADDOP_O(c, LOAD_ATTR, attr, names);
2605 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002606 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 }
2608 }
2609 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610}
2611
2612static int
2613compiler_import(struct compiler *c, stmt_ty s)
2614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 /* The Import node stores a module name like a.b.c as a single
2616 string. This is convenient for all cases except
2617 import a.b.c as d
2618 where we need to parse that string to extract the individual
2619 module names.
2620 XXX Perhaps change the representation to make this case simpler?
2621 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002622 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 for (i = 0; i < n; i++) {
2625 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2626 int r;
2627 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 level = PyLong_FromLong(0);
2630 if (level == NULL)
2631 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 ADDOP_O(c, LOAD_CONST, level, consts);
2634 Py_DECREF(level);
2635 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2636 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 if (alias->asname) {
2639 r = compiler_import_as(c, alias->name, alias->asname);
2640 if (!r)
2641 return r;
2642 }
2643 else {
2644 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 Py_ssize_t dot = PyUnicode_FindChar(
2646 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002647 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002648 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002649 if (tmp == NULL)
2650 return 0;
2651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002653 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 Py_DECREF(tmp);
2655 }
2656 if (!r)
2657 return r;
2658 }
2659 }
2660 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661}
2662
2663static int
2664compiler_from_import(struct compiler *c, stmt_ty s)
2665{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002666 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 PyObject *names = PyTuple_New(n);
2669 PyObject *level;
2670 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 if (!empty_string) {
2673 empty_string = PyUnicode_FromString("");
2674 if (!empty_string)
2675 return 0;
2676 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 if (!names)
2679 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 level = PyLong_FromLong(s->v.ImportFrom.level);
2682 if (!level) {
2683 Py_DECREF(names);
2684 return 0;
2685 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* build up the names */
2688 for (i = 0; i < n; i++) {
2689 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2690 Py_INCREF(alias->name);
2691 PyTuple_SET_ITEM(names, i, alias->name);
2692 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002695 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_DECREF(level);
2697 Py_DECREF(names);
2698 return compiler_error(c, "from __future__ imports must occur "
2699 "at the beginning of the file");
2700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 ADDOP_O(c, LOAD_CONST, level, consts);
2703 Py_DECREF(level);
2704 ADDOP_O(c, LOAD_CONST, names, consts);
2705 Py_DECREF(names);
2706 if (s->v.ImportFrom.module) {
2707 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2708 }
2709 else {
2710 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2711 }
2712 for (i = 0; i < n; i++) {
2713 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2714 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002716 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 assert(n == 1);
2718 ADDOP(c, IMPORT_STAR);
2719 return 1;
2720 }
2721
2722 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2723 store_name = alias->name;
2724 if (alias->asname)
2725 store_name = alias->asname;
2726
2727 if (!compiler_nameop(c, store_name, Store)) {
2728 Py_DECREF(names);
2729 return 0;
2730 }
2731 }
2732 /* remove imported module */
2733 ADDOP(c, POP_TOP);
2734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735}
2736
2737static int
2738compiler_assert(struct compiler *c, stmt_ty s)
2739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 static PyObject *assertion_error = NULL;
2741 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002742 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743
Georg Brandl8334fd92010-12-04 10:26:46 +00002744 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 return 1;
2746 if (assertion_error == NULL) {
2747 assertion_error = PyUnicode_InternFromString("AssertionError");
2748 if (assertion_error == NULL)
2749 return 0;
2750 }
2751 if (s->v.Assert.test->kind == Tuple_kind &&
2752 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002753 msg = PyUnicode_FromString("assertion is always true, "
2754 "perhaps remove parentheses?");
2755 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002757 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2758 c->c_filename, c->u->u_lineno,
2759 NULL, NULL) == -1) {
2760 Py_DECREF(msg);
2761 return 0;
2762 }
2763 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 }
2765 VISIT(c, expr, s->v.Assert.test);
2766 end = compiler_new_block(c);
2767 if (end == NULL)
2768 return 0;
2769 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2770 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2771 if (s->v.Assert.msg) {
2772 VISIT(c, expr, s->v.Assert.msg);
2773 ADDOP_I(c, CALL_FUNCTION, 1);
2774 }
2775 ADDOP_I(c, RAISE_VARARGS, 1);
2776 compiler_use_next_block(c, end);
2777 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778}
2779
2780static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002781compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2782{
2783 if (c->c_interactive && c->c_nestlevel <= 1) {
2784 VISIT(c, expr, value);
2785 ADDOP(c, PRINT_EXPR);
2786 return 1;
2787 }
2788
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002789 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002790 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002791 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002792 }
2793
2794 VISIT(c, expr, value);
2795 ADDOP(c, POP_TOP);
2796 return 1;
2797}
2798
2799static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800compiler_visit_stmt(struct compiler *c, stmt_ty s)
2801{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002802 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* Always assign a lineno to the next instruction for a stmt. */
2805 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002806 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 switch (s->kind) {
2810 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002811 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 case ClassDef_kind:
2813 return compiler_class(c, s);
2814 case Return_kind:
2815 if (c->u->u_ste->ste_type != FunctionBlock)
2816 return compiler_error(c, "'return' outside function");
2817 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002818 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2819 return compiler_error(
2820 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 VISIT(c, expr, s->v.Return.value);
2822 }
2823 else
2824 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2825 ADDOP(c, RETURN_VALUE);
2826 break;
2827 case Delete_kind:
2828 VISIT_SEQ(c, expr, s->v.Delete.targets)
2829 break;
2830 case Assign_kind:
2831 n = asdl_seq_LEN(s->v.Assign.targets);
2832 VISIT(c, expr, s->v.Assign.value);
2833 for (i = 0; i < n; i++) {
2834 if (i < n - 1)
2835 ADDOP(c, DUP_TOP);
2836 VISIT(c, expr,
2837 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2838 }
2839 break;
2840 case AugAssign_kind:
2841 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002842 case AnnAssign_kind:
2843 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 case For_kind:
2845 return compiler_for(c, s);
2846 case While_kind:
2847 return compiler_while(c, s);
2848 case If_kind:
2849 return compiler_if(c, s);
2850 case Raise_kind:
2851 n = 0;
2852 if (s->v.Raise.exc) {
2853 VISIT(c, expr, s->v.Raise.exc);
2854 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002855 if (s->v.Raise.cause) {
2856 VISIT(c, expr, s->v.Raise.cause);
2857 n++;
2858 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002860 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002862 case Try_kind:
2863 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 case Assert_kind:
2865 return compiler_assert(c, s);
2866 case Import_kind:
2867 return compiler_import(c, s);
2868 case ImportFrom_kind:
2869 return compiler_from_import(c, s);
2870 case Global_kind:
2871 case Nonlocal_kind:
2872 break;
2873 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002874 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 case Pass_kind:
2876 break;
2877 case Break_kind:
2878 if (!compiler_in_loop(c))
2879 return compiler_error(c, "'break' outside loop");
2880 ADDOP(c, BREAK_LOOP);
2881 break;
2882 case Continue_kind:
2883 return compiler_continue(c);
2884 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002885 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002886 case AsyncFunctionDef_kind:
2887 return compiler_function(c, s, 1);
2888 case AsyncWith_kind:
2889 return compiler_async_with(c, s, 0);
2890 case AsyncFor_kind:
2891 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 }
Yury Selivanov75445082015-05-11 22:57:16 -04002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895}
2896
2897static int
2898unaryop(unaryop_ty op)
2899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 switch (op) {
2901 case Invert:
2902 return UNARY_INVERT;
2903 case Not:
2904 return UNARY_NOT;
2905 case UAdd:
2906 return UNARY_POSITIVE;
2907 case USub:
2908 return UNARY_NEGATIVE;
2909 default:
2910 PyErr_Format(PyExc_SystemError,
2911 "unary op %d should not be possible", op);
2912 return 0;
2913 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914}
2915
2916static int
2917binop(struct compiler *c, operator_ty op)
2918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 switch (op) {
2920 case Add:
2921 return BINARY_ADD;
2922 case Sub:
2923 return BINARY_SUBTRACT;
2924 case Mult:
2925 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002926 case MatMult:
2927 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 case Div:
2929 return BINARY_TRUE_DIVIDE;
2930 case Mod:
2931 return BINARY_MODULO;
2932 case Pow:
2933 return BINARY_POWER;
2934 case LShift:
2935 return BINARY_LSHIFT;
2936 case RShift:
2937 return BINARY_RSHIFT;
2938 case BitOr:
2939 return BINARY_OR;
2940 case BitXor:
2941 return BINARY_XOR;
2942 case BitAnd:
2943 return BINARY_AND;
2944 case FloorDiv:
2945 return BINARY_FLOOR_DIVIDE;
2946 default:
2947 PyErr_Format(PyExc_SystemError,
2948 "binary op %d should not be possible", op);
2949 return 0;
2950 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951}
2952
2953static int
2954cmpop(cmpop_ty op)
2955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 switch (op) {
2957 case Eq:
2958 return PyCmp_EQ;
2959 case NotEq:
2960 return PyCmp_NE;
2961 case Lt:
2962 return PyCmp_LT;
2963 case LtE:
2964 return PyCmp_LE;
2965 case Gt:
2966 return PyCmp_GT;
2967 case GtE:
2968 return PyCmp_GE;
2969 case Is:
2970 return PyCmp_IS;
2971 case IsNot:
2972 return PyCmp_IS_NOT;
2973 case In:
2974 return PyCmp_IN;
2975 case NotIn:
2976 return PyCmp_NOT_IN;
2977 default:
2978 return PyCmp_BAD;
2979 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980}
2981
2982static int
2983inplace_binop(struct compiler *c, operator_ty op)
2984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 switch (op) {
2986 case Add:
2987 return INPLACE_ADD;
2988 case Sub:
2989 return INPLACE_SUBTRACT;
2990 case Mult:
2991 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002992 case MatMult:
2993 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 case Div:
2995 return INPLACE_TRUE_DIVIDE;
2996 case Mod:
2997 return INPLACE_MODULO;
2998 case Pow:
2999 return INPLACE_POWER;
3000 case LShift:
3001 return INPLACE_LSHIFT;
3002 case RShift:
3003 return INPLACE_RSHIFT;
3004 case BitOr:
3005 return INPLACE_OR;
3006 case BitXor:
3007 return INPLACE_XOR;
3008 case BitAnd:
3009 return INPLACE_AND;
3010 case FloorDiv:
3011 return INPLACE_FLOOR_DIVIDE;
3012 default:
3013 PyErr_Format(PyExc_SystemError,
3014 "inplace binary op %d should not be possible", op);
3015 return 0;
3016 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017}
3018
3019static int
3020compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3021{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003022 int op, scope;
3023 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 PyObject *dict = c->u->u_names;
3027 PyObject *mangled;
3028 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 mangled = _Py_Mangle(c->u->u_private, name);
3031 if (!mangled)
3032 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003033
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003034 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3035 !_PyUnicode_EqualToASCIIString(name, "True") &&
3036 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 op = 0;
3039 optype = OP_NAME;
3040 scope = PyST_GetScope(c->u->u_ste, mangled);
3041 switch (scope) {
3042 case FREE:
3043 dict = c->u->u_freevars;
3044 optype = OP_DEREF;
3045 break;
3046 case CELL:
3047 dict = c->u->u_cellvars;
3048 optype = OP_DEREF;
3049 break;
3050 case LOCAL:
3051 if (c->u->u_ste->ste_type == FunctionBlock)
3052 optype = OP_FAST;
3053 break;
3054 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003055 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 optype = OP_GLOBAL;
3057 break;
3058 case GLOBAL_EXPLICIT:
3059 optype = OP_GLOBAL;
3060 break;
3061 default:
3062 /* scope can be 0 */
3063 break;
3064 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003067 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 switch (optype) {
3070 case OP_DEREF:
3071 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003072 case Load:
3073 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3074 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 case Store: op = STORE_DEREF; break;
3076 case AugLoad:
3077 case AugStore:
3078 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003079 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 case Param:
3081 default:
3082 PyErr_SetString(PyExc_SystemError,
3083 "param invalid for deref variable");
3084 return 0;
3085 }
3086 break;
3087 case OP_FAST:
3088 switch (ctx) {
3089 case Load: op = LOAD_FAST; break;
3090 case Store: op = STORE_FAST; break;
3091 case Del: op = DELETE_FAST; break;
3092 case AugLoad:
3093 case AugStore:
3094 break;
3095 case Param:
3096 default:
3097 PyErr_SetString(PyExc_SystemError,
3098 "param invalid for local variable");
3099 return 0;
3100 }
3101 ADDOP_O(c, op, mangled, varnames);
3102 Py_DECREF(mangled);
3103 return 1;
3104 case OP_GLOBAL:
3105 switch (ctx) {
3106 case Load: op = LOAD_GLOBAL; break;
3107 case Store: op = STORE_GLOBAL; break;
3108 case Del: op = DELETE_GLOBAL; break;
3109 case AugLoad:
3110 case AugStore:
3111 break;
3112 case Param:
3113 default:
3114 PyErr_SetString(PyExc_SystemError,
3115 "param invalid for global variable");
3116 return 0;
3117 }
3118 break;
3119 case OP_NAME:
3120 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003121 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 case Store: op = STORE_NAME; break;
3123 case Del: op = DELETE_NAME; break;
3124 case AugLoad:
3125 case AugStore:
3126 break;
3127 case Param:
3128 default:
3129 PyErr_SetString(PyExc_SystemError,
3130 "param invalid for name variable");
3131 return 0;
3132 }
3133 break;
3134 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 assert(op);
3137 arg = compiler_add_o(c, dict, mangled);
3138 Py_DECREF(mangled);
3139 if (arg < 0)
3140 return 0;
3141 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142}
3143
3144static int
3145compiler_boolop(struct compiler *c, expr_ty e)
3146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003148 int jumpi;
3149 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 assert(e->kind == BoolOp_kind);
3153 if (e->v.BoolOp.op == And)
3154 jumpi = JUMP_IF_FALSE_OR_POP;
3155 else
3156 jumpi = JUMP_IF_TRUE_OR_POP;
3157 end = compiler_new_block(c);
3158 if (end == NULL)
3159 return 0;
3160 s = e->v.BoolOp.values;
3161 n = asdl_seq_LEN(s) - 1;
3162 assert(n >= 0);
3163 for (i = 0; i < n; ++i) {
3164 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3165 ADDOP_JABS(c, jumpi, end);
3166 }
3167 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3168 compiler_use_next_block(c, end);
3169 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170}
3171
3172static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003173starunpack_helper(struct compiler *c, asdl_seq *elts,
3174 int single_op, int inner_op, int outer_op)
3175{
3176 Py_ssize_t n = asdl_seq_LEN(elts);
3177 Py_ssize_t i, nsubitems = 0, nseen = 0;
3178 for (i = 0; i < n; i++) {
3179 expr_ty elt = asdl_seq_GET(elts, i);
3180 if (elt->kind == Starred_kind) {
3181 if (nseen) {
3182 ADDOP_I(c, inner_op, nseen);
3183 nseen = 0;
3184 nsubitems++;
3185 }
3186 VISIT(c, expr, elt->v.Starred.value);
3187 nsubitems++;
3188 }
3189 else {
3190 VISIT(c, expr, elt);
3191 nseen++;
3192 }
3193 }
3194 if (nsubitems) {
3195 if (nseen) {
3196 ADDOP_I(c, inner_op, nseen);
3197 nsubitems++;
3198 }
3199 ADDOP_I(c, outer_op, nsubitems);
3200 }
3201 else
3202 ADDOP_I(c, single_op, nseen);
3203 return 1;
3204}
3205
3206static int
3207assignment_helper(struct compiler *c, asdl_seq *elts)
3208{
3209 Py_ssize_t n = asdl_seq_LEN(elts);
3210 Py_ssize_t i;
3211 int seen_star = 0;
3212 for (i = 0; i < n; i++) {
3213 expr_ty elt = asdl_seq_GET(elts, i);
3214 if (elt->kind == Starred_kind && !seen_star) {
3215 if ((i >= (1 << 8)) ||
3216 (n-i-1 >= (INT_MAX >> 8)))
3217 return compiler_error(c,
3218 "too many expressions in "
3219 "star-unpacking assignment");
3220 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3221 seen_star = 1;
3222 asdl_seq_SET(elts, i, elt->v.Starred.value);
3223 }
3224 else if (elt->kind == Starred_kind) {
3225 return compiler_error(c,
3226 "two starred expressions in assignment");
3227 }
3228 }
3229 if (!seen_star) {
3230 ADDOP_I(c, UNPACK_SEQUENCE, n);
3231 }
3232 VISIT_SEQ(c, expr, elts);
3233 return 1;
3234}
3235
3236static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237compiler_list(struct compiler *c, expr_ty e)
3238{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003239 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003241 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003243 else if (e->v.List.ctx == Load) {
3244 return starunpack_helper(c, elts,
3245 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003247 else
3248 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250}
3251
3252static int
3253compiler_tuple(struct compiler *c, expr_ty e)
3254{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003255 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003257 return assignment_helper(c, elts);
3258 }
3259 else if (e->v.Tuple.ctx == Load) {
3260 return starunpack_helper(c, elts,
3261 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3262 }
3263 else
3264 VISIT_SEQ(c, expr, elts);
3265 return 1;
3266}
3267
3268static int
3269compiler_set(struct compiler *c, expr_ty e)
3270{
3271 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3272 BUILD_SET, BUILD_SET_UNPACK);
3273}
3274
3275static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003276are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3277{
3278 Py_ssize_t i;
3279 for (i = begin; i < end; i++) {
3280 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3281 if (key == NULL || !is_const(key))
3282 return 0;
3283 }
3284 return 1;
3285}
3286
3287static int
3288compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3289{
3290 Py_ssize_t i, n = end - begin;
3291 PyObject *keys, *key;
3292 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3293 for (i = begin; i < end; i++) {
3294 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3295 }
3296 keys = PyTuple_New(n);
3297 if (keys == NULL) {
3298 return 0;
3299 }
3300 for (i = begin; i < end; i++) {
3301 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3302 Py_INCREF(key);
3303 PyTuple_SET_ITEM(keys, i - begin, key);
3304 }
3305 ADDOP_N(c, LOAD_CONST, keys, consts);
3306 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3307 }
3308 else {
3309 for (i = begin; i < end; i++) {
3310 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3311 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3312 }
3313 ADDOP_I(c, BUILD_MAP, n);
3314 }
3315 return 1;
3316}
3317
3318static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003319compiler_dict(struct compiler *c, expr_ty e)
3320{
Victor Stinner976bb402016-03-23 11:36:19 +01003321 Py_ssize_t i, n, elements;
3322 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003323 int is_unpacking = 0;
3324 n = asdl_seq_LEN(e->v.Dict.values);
3325 containers = 0;
3326 elements = 0;
3327 for (i = 0; i < n; i++) {
3328 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3329 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003330 if (!compiler_subdict(c, e, i - elements, i))
3331 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003332 containers++;
3333 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003335 if (is_unpacking) {
3336 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3337 containers++;
3338 }
3339 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003340 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 }
3342 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003343 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003344 if (!compiler_subdict(c, e, n - elements, n))
3345 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003346 containers++;
3347 }
3348 /* If there is more than one dict, they need to be merged into a new
3349 * dict. If there is one dict and it's an unpacking, then it needs
3350 * to be copied into a new dict." */
3351 while (containers > 1 || is_unpacking) {
3352 int oparg = containers < 255 ? containers : 255;
3353 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3354 containers -= (oparg - 1);
3355 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 }
3357 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358}
3359
3360static int
3361compiler_compare(struct compiler *c, expr_ty e)
3362{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003363 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3367 VISIT(c, expr, e->v.Compare.left);
3368 n = asdl_seq_LEN(e->v.Compare.ops);
3369 assert(n > 0);
3370 if (n > 1) {
3371 cleanup = compiler_new_block(c);
3372 if (cleanup == NULL)
3373 return 0;
3374 VISIT(c, expr,
3375 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3376 }
3377 for (i = 1; i < n; i++) {
3378 ADDOP(c, DUP_TOP);
3379 ADDOP(c, ROT_THREE);
3380 ADDOP_I(c, COMPARE_OP,
3381 cmpop((cmpop_ty)(asdl_seq_GET(
3382 e->v.Compare.ops, i - 1))));
3383 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3384 NEXT_BLOCK(c);
3385 if (i < (n - 1))
3386 VISIT(c, expr,
3387 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3388 }
3389 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3390 ADDOP_I(c, COMPARE_OP,
3391 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3392 if (n > 1) {
3393 basicblock *end = compiler_new_block(c);
3394 if (end == NULL)
3395 return 0;
3396 ADDOP_JREL(c, JUMP_FORWARD, end);
3397 compiler_use_next_block(c, cleanup);
3398 ADDOP(c, ROT_TWO);
3399 ADDOP(c, POP_TOP);
3400 compiler_use_next_block(c, end);
3401 }
3402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403}
3404
3405static int
3406compiler_call(struct compiler *c, expr_ty e)
3407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 VISIT(c, expr, e->v.Call.func);
3409 return compiler_call_helper(c, 0,
3410 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003411 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003412}
3413
Eric V. Smith235a6f02015-09-19 14:51:32 -04003414static int
3415compiler_joined_str(struct compiler *c, expr_ty e)
3416{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003417 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003418 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3419 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003420 return 1;
3421}
3422
Eric V. Smitha78c7952015-11-03 12:45:05 -05003423/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003424static int
3425compiler_formatted_value(struct compiler *c, expr_ty e)
3426{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003427 /* Our oparg encodes 2 pieces of information: the conversion
3428 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003429
Eric V. Smitha78c7952015-11-03 12:45:05 -05003430 Convert the conversion char to 2 bits:
3431 None: 000 0x0 FVC_NONE
3432 !s : 001 0x1 FVC_STR
3433 !r : 010 0x2 FVC_REPR
3434 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003435
Eric V. Smitha78c7952015-11-03 12:45:05 -05003436 next bit is whether or not we have a format spec:
3437 yes : 100 0x4
3438 no : 000 0x0
3439 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003440
Eric V. Smitha78c7952015-11-03 12:45:05 -05003441 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003442
Eric V. Smitha78c7952015-11-03 12:45:05 -05003443 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003444 VISIT(c, expr, e->v.FormattedValue.value);
3445
Eric V. Smitha78c7952015-11-03 12:45:05 -05003446 switch (e->v.FormattedValue.conversion) {
3447 case 's': oparg = FVC_STR; break;
3448 case 'r': oparg = FVC_REPR; break;
3449 case 'a': oparg = FVC_ASCII; break;
3450 case -1: oparg = FVC_NONE; break;
3451 default:
3452 PyErr_SetString(PyExc_SystemError,
3453 "Unrecognized conversion character");
3454 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003455 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003456 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003457 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003458 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003459 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003460 }
3461
Eric V. Smitha78c7952015-11-03 12:45:05 -05003462 /* And push our opcode and oparg */
3463 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003464 return 1;
3465}
3466
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003467static int
3468compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3469{
3470 Py_ssize_t i, n = end - begin;
3471 keyword_ty kw;
3472 PyObject *keys, *key;
3473 assert(n > 0);
3474 if (n > 1) {
3475 for (i = begin; i < end; i++) {
3476 kw = asdl_seq_GET(keywords, i);
3477 VISIT(c, expr, kw->value);
3478 }
3479 keys = PyTuple_New(n);
3480 if (keys == NULL) {
3481 return 0;
3482 }
3483 for (i = begin; i < end; i++) {
3484 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3485 Py_INCREF(key);
3486 PyTuple_SET_ITEM(keys, i - begin, key);
3487 }
3488 ADDOP_N(c, LOAD_CONST, keys, consts);
3489 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3490 }
3491 else {
3492 /* a for loop only executes once */
3493 for (i = begin; i < end; i++) {
3494 kw = asdl_seq_GET(keywords, i);
3495 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3496 VISIT(c, expr, kw->value);
3497 }
3498 ADDOP_I(c, BUILD_MAP, n);
3499 }
3500 return 1;
3501}
3502
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003503/* shared code between compiler_call and compiler_class */
3504static int
3505compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003506 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003507 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003508 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003509{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003510 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003511 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003512
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003513 /* the number of tuples and dictionaries on the stack */
3514 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3515
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003516 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003517 nkwelts = asdl_seq_LEN(keywords);
3518
3519 for (i = 0; i < nkwelts; i++) {
3520 keyword_ty kw = asdl_seq_GET(keywords, i);
3521 if (kw->arg == NULL) {
3522 mustdictunpack = 1;
3523 break;
3524 }
3525 }
3526
3527 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003528 for (i = 0; i < nelts; i++) {
3529 expr_ty elt = asdl_seq_GET(args, i);
3530 if (elt->kind == Starred_kind) {
3531 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003532 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003533 if (nseen) {
3534 ADDOP_I(c, BUILD_TUPLE, nseen);
3535 nseen = 0;
3536 nsubargs++;
3537 }
3538 VISIT(c, expr, elt->v.Starred.value);
3539 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003540 }
3541 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003542 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003543 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003544 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003546
3547 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003548 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003549 if (nseen) {
3550 /* Pack up any trailing positional arguments. */
3551 ADDOP_I(c, BUILD_TUPLE, nseen);
3552 nsubargs++;
3553 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003554 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003555 /* If we ended up with more than one stararg, we need
3556 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003557 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003558 }
3559 else if (nsubargs == 0) {
3560 ADDOP_I(c, BUILD_TUPLE, 0);
3561 }
3562 nseen = 0; /* the number of keyword arguments on the stack following */
3563 for (i = 0; i < nkwelts; i++) {
3564 keyword_ty kw = asdl_seq_GET(keywords, i);
3565 if (kw->arg == NULL) {
3566 /* A keyword argument unpacking. */
3567 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003568 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3569 return 0;
3570 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003571 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003572 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003573 VISIT(c, expr, kw->value);
3574 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003575 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003576 else {
3577 nseen++;
3578 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003579 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003580 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003581 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003582 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003583 return 0;
3584 nsubkwargs++;
3585 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003586 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003587 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003588 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003589 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003590 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3591 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003593 else if (nkwelts) {
3594 PyObject *names;
3595 VISIT_SEQ(c, keyword, keywords);
3596 names = PyTuple_New(nkwelts);
3597 if (names == NULL) {
3598 return 0;
3599 }
3600 for (i = 0; i < nkwelts; i++) {
3601 keyword_ty kw = asdl_seq_GET(keywords, i);
3602 Py_INCREF(kw->arg);
3603 PyTuple_SET_ITEM(names, i, kw->arg);
3604 }
3605 ADDOP_N(c, LOAD_CONST, names, consts);
3606 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3607 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003609 else {
3610 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3611 return 1;
3612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613}
3614
Nick Coghlan650f0d02007-04-15 12:05:43 +00003615
3616/* List and set comprehensions and generator expressions work by creating a
3617 nested function to perform the actual iteration. This means that the
3618 iteration variables don't leak into the current scope.
3619 The defined function is called immediately following its definition, with the
3620 result of that call being the result of the expression.
3621 The LC/SC version returns the populated container, while the GE version is
3622 flagged in symtable.c as a generator, so it returns the generator object
3623 when the function is called.
3624 This code *knows* that the loop cannot contain break, continue, or return,
3625 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3626
3627 Possible cleanups:
3628 - iterate over the generator sequence instead of using recursion
3629*/
3630
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003631
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633compiler_comprehension_generator(struct compiler *c,
3634 asdl_seq *generators, int gen_index,
3635 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003637 comprehension_ty gen;
3638 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3639 if (gen->is_async) {
3640 return compiler_async_comprehension_generator(
3641 c, generators, gen_index, elt, val, type);
3642 } else {
3643 return compiler_sync_comprehension_generator(
3644 c, generators, gen_index, elt, val, type);
3645 }
3646}
3647
3648static int
3649compiler_sync_comprehension_generator(struct compiler *c,
3650 asdl_seq *generators, int gen_index,
3651 expr_ty elt, expr_ty val, int type)
3652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* generate code for the iterator, then each of the ifs,
3654 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 comprehension_ty gen;
3657 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003658 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 start = compiler_new_block(c);
3661 skip = compiler_new_block(c);
3662 if_cleanup = compiler_new_block(c);
3663 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3666 anchor == NULL)
3667 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 if (gen_index == 0) {
3672 /* Receive outermost iter as an implicit argument */
3673 c->u->u_argcount = 1;
3674 ADDOP_I(c, LOAD_FAST, 0);
3675 }
3676 else {
3677 /* Sub-iter - calculate on the fly */
3678 VISIT(c, expr, gen->iter);
3679 ADDOP(c, GET_ITER);
3680 }
3681 compiler_use_next_block(c, start);
3682 ADDOP_JREL(c, FOR_ITER, anchor);
3683 NEXT_BLOCK(c);
3684 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 /* XXX this needs to be cleaned up...a lot! */
3687 n = asdl_seq_LEN(gen->ifs);
3688 for (i = 0; i < n; i++) {
3689 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3690 VISIT(c, expr, e);
3691 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3692 NEXT_BLOCK(c);
3693 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 if (++gen_index < asdl_seq_LEN(generators))
3696 if (!compiler_comprehension_generator(c,
3697 generators, gen_index,
3698 elt, val, type))
3699 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 /* only append after the last for generator */
3702 if (gen_index >= asdl_seq_LEN(generators)) {
3703 /* comprehension specific code */
3704 switch (type) {
3705 case COMP_GENEXP:
3706 VISIT(c, expr, elt);
3707 ADDOP(c, YIELD_VALUE);
3708 ADDOP(c, POP_TOP);
3709 break;
3710 case COMP_LISTCOMP:
3711 VISIT(c, expr, elt);
3712 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3713 break;
3714 case COMP_SETCOMP:
3715 VISIT(c, expr, elt);
3716 ADDOP_I(c, SET_ADD, gen_index + 1);
3717 break;
3718 case COMP_DICTCOMP:
3719 /* With 'd[k] = v', v is evaluated before k, so we do
3720 the same. */
3721 VISIT(c, expr, val);
3722 VISIT(c, expr, elt);
3723 ADDOP_I(c, MAP_ADD, gen_index + 1);
3724 break;
3725 default:
3726 return 0;
3727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 compiler_use_next_block(c, skip);
3730 }
3731 compiler_use_next_block(c, if_cleanup);
3732 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3733 compiler_use_next_block(c, anchor);
3734
3735 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736}
3737
3738static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003739compiler_async_comprehension_generator(struct compiler *c,
3740 asdl_seq *generators, int gen_index,
3741 expr_ty elt, expr_ty val, int type)
3742{
3743 _Py_IDENTIFIER(StopAsyncIteration);
3744
3745 comprehension_ty gen;
3746 basicblock *anchor, *skip, *if_cleanup, *try,
3747 *after_try, *except, *try_cleanup;
3748 Py_ssize_t i, n;
3749
3750 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3751 if (stop_aiter_error == NULL) {
3752 return 0;
3753 }
3754
3755 try = compiler_new_block(c);
3756 after_try = compiler_new_block(c);
3757 try_cleanup = compiler_new_block(c);
3758 except = compiler_new_block(c);
3759 skip = compiler_new_block(c);
3760 if_cleanup = compiler_new_block(c);
3761 anchor = compiler_new_block(c);
3762
3763 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3764 try == NULL || after_try == NULL ||
3765 except == NULL || after_try == NULL) {
3766 return 0;
3767 }
3768
3769 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3770
3771 if (gen_index == 0) {
3772 /* Receive outermost iter as an implicit argument */
3773 c->u->u_argcount = 1;
3774 ADDOP_I(c, LOAD_FAST, 0);
3775 }
3776 else {
3777 /* Sub-iter - calculate on the fly */
3778 VISIT(c, expr, gen->iter);
3779 ADDOP(c, GET_AITER);
3780 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3781 ADDOP(c, YIELD_FROM);
3782 }
3783
3784 compiler_use_next_block(c, try);
3785
3786
3787 ADDOP_JREL(c, SETUP_EXCEPT, except);
3788 if (!compiler_push_fblock(c, EXCEPT, try))
3789 return 0;
3790
3791 ADDOP(c, GET_ANEXT);
3792 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3793 ADDOP(c, YIELD_FROM);
3794 VISIT(c, expr, gen->target);
3795 ADDOP(c, POP_BLOCK);
3796 compiler_pop_fblock(c, EXCEPT, try);
3797 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3798
3799
3800 compiler_use_next_block(c, except);
3801 ADDOP(c, DUP_TOP);
3802 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3803 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3804 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3805
3806 ADDOP(c, POP_TOP);
3807 ADDOP(c, POP_TOP);
3808 ADDOP(c, POP_TOP);
3809 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3810 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3811
3812
3813 compiler_use_next_block(c, try_cleanup);
3814 ADDOP(c, END_FINALLY);
3815
3816 compiler_use_next_block(c, after_try);
3817
3818 n = asdl_seq_LEN(gen->ifs);
3819 for (i = 0; i < n; i++) {
3820 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3821 VISIT(c, expr, e);
3822 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3823 NEXT_BLOCK(c);
3824 }
3825
3826 if (++gen_index < asdl_seq_LEN(generators))
3827 if (!compiler_comprehension_generator(c,
3828 generators, gen_index,
3829 elt, val, type))
3830 return 0;
3831
3832 /* only append after the last for generator */
3833 if (gen_index >= asdl_seq_LEN(generators)) {
3834 /* comprehension specific code */
3835 switch (type) {
3836 case COMP_GENEXP:
3837 VISIT(c, expr, elt);
3838 ADDOP(c, YIELD_VALUE);
3839 ADDOP(c, POP_TOP);
3840 break;
3841 case COMP_LISTCOMP:
3842 VISIT(c, expr, elt);
3843 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3844 break;
3845 case COMP_SETCOMP:
3846 VISIT(c, expr, elt);
3847 ADDOP_I(c, SET_ADD, gen_index + 1);
3848 break;
3849 case COMP_DICTCOMP:
3850 /* With 'd[k] = v', v is evaluated before k, so we do
3851 the same. */
3852 VISIT(c, expr, val);
3853 VISIT(c, expr, elt);
3854 ADDOP_I(c, MAP_ADD, gen_index + 1);
3855 break;
3856 default:
3857 return 0;
3858 }
3859
3860 compiler_use_next_block(c, skip);
3861 }
3862 compiler_use_next_block(c, if_cleanup);
3863 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3864 compiler_use_next_block(c, anchor);
3865 ADDOP(c, POP_TOP);
3866
3867 return 1;
3868}
3869
3870static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003871compiler_comprehension(struct compiler *c, expr_ty e, int type,
3872 identifier name, asdl_seq *generators, expr_ty elt,
3873 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003876 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003877 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003878 int is_async_function = c->u->u_ste->ste_coroutine;
3879 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003880
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003881 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003882
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003883 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3884 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003885 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003887 }
3888
3889 is_async_generator = c->u->u_ste->ste_coroutine;
3890
3891 if (is_async_generator && !is_async_function) {
3892 if (e->lineno > c->u->u_lineno) {
3893 c->u->u_lineno = e->lineno;
3894 c->u->u_lineno_set = 0;
3895 }
3896 compiler_error(c, "asynchronous comprehension outside of "
3897 "an asynchronous function");
3898 goto error_in_scope;
3899 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 if (type != COMP_GENEXP) {
3902 int op;
3903 switch (type) {
3904 case COMP_LISTCOMP:
3905 op = BUILD_LIST;
3906 break;
3907 case COMP_SETCOMP:
3908 op = BUILD_SET;
3909 break;
3910 case COMP_DICTCOMP:
3911 op = BUILD_MAP;
3912 break;
3913 default:
3914 PyErr_Format(PyExc_SystemError,
3915 "unknown comprehension type %d", type);
3916 goto error_in_scope;
3917 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 ADDOP_I(c, op, 0);
3920 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 if (!compiler_comprehension_generator(c, generators, 0, elt,
3923 val, type))
3924 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 if (type != COMP_GENEXP) {
3927 ADDOP(c, RETURN_VALUE);
3928 }
3929
3930 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003931 qualname = c->u->u_qualname;
3932 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003934 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 goto error;
3936
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003937 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003939 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 Py_DECREF(co);
3941
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003942 VISIT(c, expr, outermost->iter);
3943
3944 if (outermost->is_async) {
3945 ADDOP(c, GET_AITER);
3946 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3947 ADDOP(c, YIELD_FROM);
3948 } else {
3949 ADDOP(c, GET_ITER);
3950 }
3951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003953
3954 if (is_async_generator && type != COMP_GENEXP) {
3955 ADDOP(c, GET_AWAITABLE);
3956 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3957 ADDOP(c, YIELD_FROM);
3958 }
3959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003961error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003963error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003964 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 Py_XDECREF(co);
3966 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003967}
3968
3969static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003970compiler_genexp(struct compiler *c, expr_ty e)
3971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 static identifier name;
3973 if (!name) {
3974 name = PyUnicode_FromString("<genexpr>");
3975 if (!name)
3976 return 0;
3977 }
3978 assert(e->kind == GeneratorExp_kind);
3979 return compiler_comprehension(c, e, COMP_GENEXP, name,
3980 e->v.GeneratorExp.generators,
3981 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003982}
3983
3984static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003985compiler_listcomp(struct compiler *c, expr_ty e)
3986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 static identifier name;
3988 if (!name) {
3989 name = PyUnicode_FromString("<listcomp>");
3990 if (!name)
3991 return 0;
3992 }
3993 assert(e->kind == ListComp_kind);
3994 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3995 e->v.ListComp.generators,
3996 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003997}
3998
3999static int
4000compiler_setcomp(struct compiler *c, expr_ty e)
4001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 static identifier name;
4003 if (!name) {
4004 name = PyUnicode_FromString("<setcomp>");
4005 if (!name)
4006 return 0;
4007 }
4008 assert(e->kind == SetComp_kind);
4009 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4010 e->v.SetComp.generators,
4011 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004012}
4013
4014
4015static int
4016compiler_dictcomp(struct compiler *c, expr_ty e)
4017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 static identifier name;
4019 if (!name) {
4020 name = PyUnicode_FromString("<dictcomp>");
4021 if (!name)
4022 return 0;
4023 }
4024 assert(e->kind == DictComp_kind);
4025 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4026 e->v.DictComp.generators,
4027 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004028}
4029
4030
4031static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032compiler_visit_keyword(struct compiler *c, keyword_ty k)
4033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 VISIT(c, expr, k->value);
4035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004036}
4037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004039 whether they are true or false.
4040
4041 Return values: 1 for true, 0 for false, -1 for non-constant.
4042 */
4043
4044static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004045expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 char *id;
4048 switch (e->kind) {
4049 case Ellipsis_kind:
4050 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004051 case Constant_kind:
4052 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 case Num_kind:
4054 return PyObject_IsTrue(e->v.Num.n);
4055 case Str_kind:
4056 return PyObject_IsTrue(e->v.Str.s);
4057 case Name_kind:
4058 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004059 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004060 if (id && strcmp(id, "__debug__") == 0)
4061 return !c->c_optimize;
4062 return -1;
4063 case NameConstant_kind: {
4064 PyObject *o = e->v.NameConstant.value;
4065 if (o == Py_None)
4066 return 0;
4067 else if (o == Py_True)
4068 return 1;
4069 else if (o == Py_False)
4070 return 0;
4071 }
Victor Stinnerc0e77362017-09-12 16:09:44 -07004072 /* fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 default:
4074 return -1;
4075 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004076}
4077
Yury Selivanov75445082015-05-11 22:57:16 -04004078
4079/*
4080 Implements the async with statement.
4081
4082 The semantics outlined in that PEP are as follows:
4083
4084 async with EXPR as VAR:
4085 BLOCK
4086
4087 It is implemented roughly as:
4088
4089 context = EXPR
4090 exit = context.__aexit__ # not calling it
4091 value = await context.__aenter__()
4092 try:
4093 VAR = value # if VAR present in the syntax
4094 BLOCK
4095 finally:
4096 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004097 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004098 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004099 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004100 if not (await exit(*exc)):
4101 raise
4102 */
4103static int
4104compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4105{
4106 basicblock *block, *finally;
4107 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4108
4109 assert(s->kind == AsyncWith_kind);
4110
4111 block = compiler_new_block(c);
4112 finally = compiler_new_block(c);
4113 if (!block || !finally)
4114 return 0;
4115
4116 /* Evaluate EXPR */
4117 VISIT(c, expr, item->context_expr);
4118
4119 ADDOP(c, BEFORE_ASYNC_WITH);
4120 ADDOP(c, GET_AWAITABLE);
4121 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4122 ADDOP(c, YIELD_FROM);
4123
4124 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4125
4126 /* SETUP_ASYNC_WITH pushes a finally block. */
4127 compiler_use_next_block(c, block);
4128 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4129 return 0;
4130 }
4131
4132 if (item->optional_vars) {
4133 VISIT(c, expr, item->optional_vars);
4134 }
4135 else {
4136 /* Discard result from context.__aenter__() */
4137 ADDOP(c, POP_TOP);
4138 }
4139
4140 pos++;
4141 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4142 /* BLOCK code */
4143 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4144 else if (!compiler_async_with(c, s, pos))
4145 return 0;
4146
4147 /* End of try block; start the finally block */
4148 ADDOP(c, POP_BLOCK);
4149 compiler_pop_fblock(c, FINALLY_TRY, block);
4150
4151 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4152 compiler_use_next_block(c, finally);
4153 if (!compiler_push_fblock(c, FINALLY_END, finally))
4154 return 0;
4155
4156 /* Finally block starts; context.__exit__ is on the stack under
4157 the exception or return information. Just issue our magic
4158 opcode. */
4159 ADDOP(c, WITH_CLEANUP_START);
4160
4161 ADDOP(c, GET_AWAITABLE);
4162 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4163 ADDOP(c, YIELD_FROM);
4164
4165 ADDOP(c, WITH_CLEANUP_FINISH);
4166
4167 /* Finally block ends. */
4168 ADDOP(c, END_FINALLY);
4169 compiler_pop_fblock(c, FINALLY_END, finally);
4170 return 1;
4171}
4172
4173
Guido van Rossumc2e20742006-02-27 22:32:47 +00004174/*
4175 Implements the with statement from PEP 343.
4176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004178
4179 with EXPR as VAR:
4180 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181
Guido van Rossumc2e20742006-02-27 22:32:47 +00004182 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183
Thomas Wouters477c8d52006-05-27 19:21:47 +00004184 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004185 exit = context.__exit__ # not calling it
4186 value = context.__enter__()
4187 try:
4188 VAR = value # if VAR present in the syntax
4189 BLOCK
4190 finally:
4191 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004192 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004193 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004194 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004195 exit(*exc)
4196 */
4197static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004198compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004199{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004200 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004201 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004202
4203 assert(s->kind == With_kind);
4204
Guido van Rossumc2e20742006-02-27 22:32:47 +00004205 block = compiler_new_block(c);
4206 finally = compiler_new_block(c);
4207 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004208 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004209
Thomas Wouters477c8d52006-05-27 19:21:47 +00004210 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004211 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004212 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004213
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004214 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004215 compiler_use_next_block(c, block);
4216 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004217 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004218 }
4219
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004220 if (item->optional_vars) {
4221 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004222 }
4223 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004225 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004226 }
4227
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004228 pos++;
4229 if (pos == asdl_seq_LEN(s->v.With.items))
4230 /* BLOCK code */
4231 VISIT_SEQ(c, stmt, s->v.With.body)
4232 else if (!compiler_with(c, s, pos))
4233 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004234
4235 /* End of try block; start the finally block */
4236 ADDOP(c, POP_BLOCK);
4237 compiler_pop_fblock(c, FINALLY_TRY, block);
4238
4239 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4240 compiler_use_next_block(c, finally);
4241 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004242 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004243
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004244 /* Finally block starts; context.__exit__ is on the stack under
4245 the exception or return information. Just issue our magic
4246 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004247 ADDOP(c, WITH_CLEANUP_START);
4248 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004249
4250 /* Finally block ends. */
4251 ADDOP(c, END_FINALLY);
4252 compiler_pop_fblock(c, FINALLY_END, finally);
4253 return 1;
4254}
4255
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004256static int
4257compiler_visit_expr(struct compiler *c, expr_ty e)
4258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 /* If expr e has a different line number than the last expr/stmt,
4260 set a new line number for the next instruction.
4261 */
4262 if (e->lineno > c->u->u_lineno) {
4263 c->u->u_lineno = e->lineno;
4264 c->u->u_lineno_set = 0;
4265 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004266 /* Updating the column offset is always harmless. */
4267 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 switch (e->kind) {
4269 case BoolOp_kind:
4270 return compiler_boolop(c, e);
4271 case BinOp_kind:
4272 VISIT(c, expr, e->v.BinOp.left);
4273 VISIT(c, expr, e->v.BinOp.right);
4274 ADDOP(c, binop(c, e->v.BinOp.op));
4275 break;
4276 case UnaryOp_kind:
4277 VISIT(c, expr, e->v.UnaryOp.operand);
4278 ADDOP(c, unaryop(e->v.UnaryOp.op));
4279 break;
4280 case Lambda_kind:
4281 return compiler_lambda(c, e);
4282 case IfExp_kind:
4283 return compiler_ifexp(c, e);
4284 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004285 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004287 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 case GeneratorExp_kind:
4289 return compiler_genexp(c, e);
4290 case ListComp_kind:
4291 return compiler_listcomp(c, e);
4292 case SetComp_kind:
4293 return compiler_setcomp(c, e);
4294 case DictComp_kind:
4295 return compiler_dictcomp(c, e);
4296 case Yield_kind:
4297 if (c->u->u_ste->ste_type != FunctionBlock)
4298 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004299 if (e->v.Yield.value) {
4300 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 }
4302 else {
4303 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4304 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004305 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004307 case YieldFrom_kind:
4308 if (c->u->u_ste->ste_type != FunctionBlock)
4309 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004310
4311 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4312 return compiler_error(c, "'yield from' inside async function");
4313
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004314 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004315 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004316 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4317 ADDOP(c, YIELD_FROM);
4318 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004319 case Await_kind:
4320 if (c->u->u_ste->ste_type != FunctionBlock)
4321 return compiler_error(c, "'await' outside function");
4322
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004323 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4324 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004325 return compiler_error(c, "'await' outside async function");
4326
4327 VISIT(c, expr, e->v.Await.value);
4328 ADDOP(c, GET_AWAITABLE);
4329 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4330 ADDOP(c, YIELD_FROM);
4331 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 case Compare_kind:
4333 return compiler_compare(c, e);
4334 case Call_kind:
4335 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004336 case Constant_kind:
4337 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4338 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 case Num_kind:
4340 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4341 break;
4342 case Str_kind:
4343 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4344 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004345 case JoinedStr_kind:
4346 return compiler_joined_str(c, e);
4347 case FormattedValue_kind:
4348 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 case Bytes_kind:
4350 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4351 break;
4352 case Ellipsis_kind:
4353 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4354 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004355 case NameConstant_kind:
4356 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4357 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 /* The following exprs can be assignment targets. */
4359 case Attribute_kind:
4360 if (e->v.Attribute.ctx != AugStore)
4361 VISIT(c, expr, e->v.Attribute.value);
4362 switch (e->v.Attribute.ctx) {
4363 case AugLoad:
4364 ADDOP(c, DUP_TOP);
Victor Stinnerc0e77362017-09-12 16:09:44 -07004365 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 case Load:
4367 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4368 break;
4369 case AugStore:
4370 ADDOP(c, ROT_TWO);
Victor Stinnerc0e77362017-09-12 16:09:44 -07004371 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 case Store:
4373 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4374 break;
4375 case Del:
4376 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4377 break;
4378 case Param:
4379 default:
4380 PyErr_SetString(PyExc_SystemError,
4381 "param invalid in attribute expression");
4382 return 0;
4383 }
4384 break;
4385 case Subscript_kind:
4386 switch (e->v.Subscript.ctx) {
4387 case AugLoad:
4388 VISIT(c, expr, e->v.Subscript.value);
4389 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4390 break;
4391 case Load:
4392 VISIT(c, expr, e->v.Subscript.value);
4393 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4394 break;
4395 case AugStore:
4396 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4397 break;
4398 case Store:
4399 VISIT(c, expr, e->v.Subscript.value);
4400 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4401 break;
4402 case Del:
4403 VISIT(c, expr, e->v.Subscript.value);
4404 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4405 break;
4406 case Param:
4407 default:
4408 PyErr_SetString(PyExc_SystemError,
4409 "param invalid in subscript expression");
4410 return 0;
4411 }
4412 break;
4413 case Starred_kind:
4414 switch (e->v.Starred.ctx) {
4415 case Store:
4416 /* In all legitimate cases, the Starred node was already replaced
4417 * by compiler_list/compiler_tuple. XXX: is that okay? */
4418 return compiler_error(c,
4419 "starred assignment target must be in a list or tuple");
4420 default:
4421 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004422 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 }
4424 break;
4425 case Name_kind:
4426 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4427 /* child nodes of List and Tuple will have expr_context set */
4428 case List_kind:
4429 return compiler_list(c, e);
4430 case Tuple_kind:
4431 return compiler_tuple(c, e);
4432 }
4433 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434}
4435
4436static int
4437compiler_augassign(struct compiler *c, stmt_ty s)
4438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 expr_ty e = s->v.AugAssign.target;
4440 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 switch (e->kind) {
4445 case Attribute_kind:
4446 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4447 AugLoad, e->lineno, e->col_offset, c->c_arena);
4448 if (auge == NULL)
4449 return 0;
4450 VISIT(c, expr, auge);
4451 VISIT(c, expr, s->v.AugAssign.value);
4452 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4453 auge->v.Attribute.ctx = AugStore;
4454 VISIT(c, expr, auge);
4455 break;
4456 case Subscript_kind:
4457 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4458 AugLoad, e->lineno, e->col_offset, c->c_arena);
4459 if (auge == NULL)
4460 return 0;
4461 VISIT(c, expr, auge);
4462 VISIT(c, expr, s->v.AugAssign.value);
4463 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4464 auge->v.Subscript.ctx = AugStore;
4465 VISIT(c, expr, auge);
4466 break;
4467 case Name_kind:
4468 if (!compiler_nameop(c, e->v.Name.id, Load))
4469 return 0;
4470 VISIT(c, expr, s->v.AugAssign.value);
4471 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4472 return compiler_nameop(c, e->v.Name.id, Store);
4473 default:
4474 PyErr_Format(PyExc_SystemError,
4475 "invalid node type (%d) for augmented assignment",
4476 e->kind);
4477 return 0;
4478 }
4479 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004480}
4481
4482static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004483check_ann_expr(struct compiler *c, expr_ty e)
4484{
4485 VISIT(c, expr, e);
4486 ADDOP(c, POP_TOP);
4487 return 1;
4488}
4489
4490static int
4491check_annotation(struct compiler *c, stmt_ty s)
4492{
4493 /* Annotations are only evaluated in a module or class. */
4494 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4495 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4496 return check_ann_expr(c, s->v.AnnAssign.annotation);
4497 }
4498 return 1;
4499}
4500
4501static int
4502check_ann_slice(struct compiler *c, slice_ty sl)
4503{
4504 switch(sl->kind) {
4505 case Index_kind:
4506 return check_ann_expr(c, sl->v.Index.value);
4507 case Slice_kind:
4508 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4509 return 0;
4510 }
4511 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4512 return 0;
4513 }
4514 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4515 return 0;
4516 }
4517 break;
4518 default:
4519 PyErr_SetString(PyExc_SystemError,
4520 "unexpected slice kind");
4521 return 0;
4522 }
4523 return 1;
4524}
4525
4526static int
4527check_ann_subscr(struct compiler *c, slice_ty sl)
4528{
4529 /* We check that everything in a subscript is defined at runtime. */
4530 Py_ssize_t i, n;
4531
4532 switch (sl->kind) {
4533 case Index_kind:
4534 case Slice_kind:
4535 if (!check_ann_slice(c, sl)) {
4536 return 0;
4537 }
4538 break;
4539 case ExtSlice_kind:
4540 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4541 for (i = 0; i < n; i++) {
4542 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4543 switch (subsl->kind) {
4544 case Index_kind:
4545 case Slice_kind:
4546 if (!check_ann_slice(c, subsl)) {
4547 return 0;
4548 }
4549 break;
4550 case ExtSlice_kind:
4551 default:
4552 PyErr_SetString(PyExc_SystemError,
4553 "extended slice invalid in nested slice");
4554 return 0;
4555 }
4556 }
4557 break;
4558 default:
4559 PyErr_Format(PyExc_SystemError,
4560 "invalid subscript kind %d", sl->kind);
4561 return 0;
4562 }
4563 return 1;
4564}
4565
4566static int
4567compiler_annassign(struct compiler *c, stmt_ty s)
4568{
4569 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004570 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004571
4572 assert(s->kind == AnnAssign_kind);
4573
4574 /* We perform the actual assignment first. */
4575 if (s->v.AnnAssign.value) {
4576 VISIT(c, expr, s->v.AnnAssign.value);
4577 VISIT(c, expr, targ);
4578 }
4579 switch (targ->kind) {
4580 case Name_kind:
4581 /* If we have a simple name in a module or class, store annotation. */
4582 if (s->v.AnnAssign.simple &&
4583 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4584 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004585 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4586 if (!mangled) {
4587 return 0;
4588 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004589 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004590 /* ADDOP_N decrefs its argument */
4591 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004592 }
4593 break;
4594 case Attribute_kind:
4595 if (!s->v.AnnAssign.value &&
4596 !check_ann_expr(c, targ->v.Attribute.value)) {
4597 return 0;
4598 }
4599 break;
4600 case Subscript_kind:
4601 if (!s->v.AnnAssign.value &&
4602 (!check_ann_expr(c, targ->v.Subscript.value) ||
4603 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4604 return 0;
4605 }
4606 break;
4607 default:
4608 PyErr_Format(PyExc_SystemError,
4609 "invalid node type (%d) for annotated assignment",
4610 targ->kind);
4611 return 0;
4612 }
4613 /* Annotation is evaluated last. */
4614 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4615 return 0;
4616 }
4617 return 1;
4618}
4619
4620static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004621compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 struct fblockinfo *f;
4624 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004625 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 "too many statically nested blocks");
4627 return 0;
4628 }
4629 f = &c->u->u_fblock[c->u->u_nfblocks++];
4630 f->fb_type = t;
4631 f->fb_block = b;
4632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004633}
4634
4635static void
4636compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 struct compiler_unit *u = c->u;
4639 assert(u->u_nfblocks > 0);
4640 u->u_nfblocks--;
4641 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4642 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004643}
4644
Thomas Wouters89f507f2006-12-13 04:49:30 +00004645static int
4646compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 int i;
4648 struct compiler_unit *u = c->u;
4649 for (i = 0; i < u->u_nfblocks; ++i) {
4650 if (u->u_fblock[i].fb_type == LOOP)
4651 return 1;
4652 }
4653 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004654}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004655/* Raises a SyntaxError and returns 0.
4656 If something goes wrong, a different exception may be raised.
4657*/
4658
4659static int
4660compiler_error(struct compiler *c, const char *errstr)
4661{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004662 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004664
Victor Stinner14e461d2013-08-26 22:28:21 +02004665 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 if (!loc) {
4667 Py_INCREF(Py_None);
4668 loc = Py_None;
4669 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004670 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004671 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 if (!u)
4673 goto exit;
4674 v = Py_BuildValue("(zO)", errstr, u);
4675 if (!v)
4676 goto exit;
4677 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004678 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 Py_DECREF(loc);
4680 Py_XDECREF(u);
4681 Py_XDECREF(v);
4682 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004683}
4684
4685static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686compiler_handle_subscr(struct compiler *c, const char *kind,
4687 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 /* XXX this code is duplicated */
4692 switch (ctx) {
4693 case AugLoad: /* fall through to Load */
4694 case Load: op = BINARY_SUBSCR; break;
4695 case AugStore:/* fall through to Store */
4696 case Store: op = STORE_SUBSCR; break;
4697 case Del: op = DELETE_SUBSCR; break;
4698 case Param:
4699 PyErr_Format(PyExc_SystemError,
4700 "invalid %s kind %d in subscript\n",
4701 kind, ctx);
4702 return 0;
4703 }
4704 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004705 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 }
4707 else if (ctx == AugStore) {
4708 ADDOP(c, ROT_THREE);
4709 }
4710 ADDOP(c, op);
4711 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004712}
4713
4714static int
4715compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 int n = 2;
4718 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 /* only handles the cases where BUILD_SLICE is emitted */
4721 if (s->v.Slice.lower) {
4722 VISIT(c, expr, s->v.Slice.lower);
4723 }
4724 else {
4725 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4726 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 if (s->v.Slice.upper) {
4729 VISIT(c, expr, s->v.Slice.upper);
4730 }
4731 else {
4732 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4733 }
4734
4735 if (s->v.Slice.step) {
4736 n++;
4737 VISIT(c, expr, s->v.Slice.step);
4738 }
4739 ADDOP_I(c, BUILD_SLICE, n);
4740 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004741}
4742
4743static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4745 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 switch (s->kind) {
4748 case Slice_kind:
4749 return compiler_slice(c, s, ctx);
4750 case Index_kind:
4751 VISIT(c, expr, s->v.Index.value);
4752 break;
4753 case ExtSlice_kind:
4754 default:
4755 PyErr_SetString(PyExc_SystemError,
4756 "extended slice invalid in nested slice");
4757 return 0;
4758 }
4759 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004760}
4761
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004762static int
4763compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 char * kindname = NULL;
4766 switch (s->kind) {
4767 case Index_kind:
4768 kindname = "index";
4769 if (ctx != AugStore) {
4770 VISIT(c, expr, s->v.Index.value);
4771 }
4772 break;
4773 case Slice_kind:
4774 kindname = "slice";
4775 if (ctx != AugStore) {
4776 if (!compiler_slice(c, s, ctx))
4777 return 0;
4778 }
4779 break;
4780 case ExtSlice_kind:
4781 kindname = "extended slice";
4782 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004783 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 for (i = 0; i < n; i++) {
4785 slice_ty sub = (slice_ty)asdl_seq_GET(
4786 s->v.ExtSlice.dims, i);
4787 if (!compiler_visit_nested_slice(c, sub, ctx))
4788 return 0;
4789 }
4790 ADDOP_I(c, BUILD_TUPLE, n);
4791 }
4792 break;
4793 default:
4794 PyErr_Format(PyExc_SystemError,
4795 "invalid subscript kind %d", s->kind);
4796 return 0;
4797 }
4798 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004799}
4800
Thomas Wouters89f507f2006-12-13 04:49:30 +00004801/* End of the compiler section, beginning of the assembler section */
4802
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004803/* do depth-first search of basic block graph, starting with block.
4804 post records the block indices in post-order.
4805
4806 XXX must handle implicit jumps from one block to next
4807*/
4808
Thomas Wouters89f507f2006-12-13 04:49:30 +00004809struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 PyObject *a_bytecode; /* string containing bytecode */
4811 int a_offset; /* offset into bytecode */
4812 int a_nblocks; /* number of reachable blocks */
4813 basicblock **a_postorder; /* list of blocks in dfs postorder */
4814 PyObject *a_lnotab; /* string containing lnotab */
4815 int a_lnotab_off; /* offset into lnotab */
4816 int a_lineno; /* last lineno of emitted instruction */
4817 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004818};
4819
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004820static void
4821dfs(struct compiler *c, basicblock *b, struct assembler *a)
4822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 int i;
4824 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 if (b->b_seen)
4827 return;
4828 b->b_seen = 1;
4829 if (b->b_next != NULL)
4830 dfs(c, b->b_next, a);
4831 for (i = 0; i < b->b_iused; i++) {
4832 instr = &b->b_instr[i];
4833 if (instr->i_jrel || instr->i_jabs)
4834 dfs(c, instr->i_target, a);
4835 }
4836 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004837}
4838
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004839static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004840stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4841{
Larry Hastings3a907972013-11-23 14:49:22 -08004842 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004843 struct instr *instr;
4844 if (b->b_seen || b->b_startdepth >= depth)
4845 return maxdepth;
4846 b->b_seen = 1;
4847 b->b_startdepth = depth;
4848 for (i = 0; i < b->b_iused; i++) {
4849 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004850 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4851 if (effect == PY_INVALID_STACK_EFFECT) {
4852 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4853 Py_FatalError("PyCompile_OpcodeStackEffect()");
4854 }
4855 depth += effect;
4856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 if (depth > maxdepth)
4858 maxdepth = depth;
4859 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4860 if (instr->i_jrel || instr->i_jabs) {
4861 target_depth = depth;
4862 if (instr->i_opcode == FOR_ITER) {
4863 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004864 }
4865 else if (instr->i_opcode == SETUP_FINALLY ||
4866 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 target_depth = depth+3;
4868 if (target_depth > maxdepth)
4869 maxdepth = target_depth;
4870 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004871 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4872 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4873 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 maxdepth = stackdepth_walk(c, instr->i_target,
4875 target_depth, maxdepth);
4876 if (instr->i_opcode == JUMP_ABSOLUTE ||
4877 instr->i_opcode == JUMP_FORWARD) {
4878 goto out; /* remaining code is dead */
4879 }
4880 }
4881 }
4882 if (b->b_next)
4883 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004884out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 b->b_seen = 0;
4886 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004887}
4888
4889/* Find the flow path that needs the largest stack. We assume that
4890 * cycles in the flow graph have no net effect on the stack depth.
4891 */
4892static int
4893stackdepth(struct compiler *c)
4894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 basicblock *b, *entryblock;
4896 entryblock = NULL;
4897 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4898 b->b_seen = 0;
4899 b->b_startdepth = INT_MIN;
4900 entryblock = b;
4901 }
4902 if (!entryblock)
4903 return 0;
4904 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004905}
4906
4907static int
4908assemble_init(struct assembler *a, int nblocks, int firstlineno)
4909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 memset(a, 0, sizeof(struct assembler));
4911 a->a_lineno = firstlineno;
4912 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4913 if (!a->a_bytecode)
4914 return 0;
4915 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4916 if (!a->a_lnotab)
4917 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004918 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 PyErr_NoMemory();
4920 return 0;
4921 }
4922 a->a_postorder = (basicblock **)PyObject_Malloc(
4923 sizeof(basicblock *) * nblocks);
4924 if (!a->a_postorder) {
4925 PyErr_NoMemory();
4926 return 0;
4927 }
4928 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004929}
4930
4931static void
4932assemble_free(struct assembler *a)
4933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 Py_XDECREF(a->a_bytecode);
4935 Py_XDECREF(a->a_lnotab);
4936 if (a->a_postorder)
4937 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004938}
4939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004940static int
4941blocksize(basicblock *b)
4942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 int i;
4944 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004947 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004949}
4950
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004951/* Appends a pair to the end of the line number table, a_lnotab, representing
4952 the instruction's bytecode offset and line number. See
4953 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004954
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004955static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004956assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004959 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004961
Serhiy Storchakaab874002016-09-11 13:48:15 +03004962 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 if(d_bytecode == 0 && d_lineno == 0)
4968 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 if (d_bytecode > 255) {
4971 int j, nbytes, ncodes = d_bytecode / 255;
4972 nbytes = a->a_lnotab_off + 2 * ncodes;
4973 len = PyBytes_GET_SIZE(a->a_lnotab);
4974 if (nbytes >= len) {
4975 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4976 len = nbytes;
4977 else if (len <= INT_MAX / 2)
4978 len *= 2;
4979 else {
4980 PyErr_NoMemory();
4981 return 0;
4982 }
4983 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4984 return 0;
4985 }
4986 lnotab = (unsigned char *)
4987 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4988 for (j = 0; j < ncodes; j++) {
4989 *lnotab++ = 255;
4990 *lnotab++ = 0;
4991 }
4992 d_bytecode -= ncodes * 255;
4993 a->a_lnotab_off += ncodes * 2;
4994 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004995 assert(0 <= d_bytecode && d_bytecode <= 255);
4996
4997 if (d_lineno < -128 || 127 < d_lineno) {
4998 int j, nbytes, ncodes, k;
4999 if (d_lineno < 0) {
5000 k = -128;
5001 /* use division on positive numbers */
5002 ncodes = (-d_lineno) / 128;
5003 }
5004 else {
5005 k = 127;
5006 ncodes = d_lineno / 127;
5007 }
5008 d_lineno -= ncodes * k;
5009 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 nbytes = a->a_lnotab_off + 2 * ncodes;
5011 len = PyBytes_GET_SIZE(a->a_lnotab);
5012 if (nbytes >= len) {
5013 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5014 len = nbytes;
5015 else if (len <= INT_MAX / 2)
5016 len *= 2;
5017 else {
5018 PyErr_NoMemory();
5019 return 0;
5020 }
5021 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5022 return 0;
5023 }
5024 lnotab = (unsigned char *)
5025 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5026 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005027 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 d_bytecode = 0;
5029 for (j = 1; j < ncodes; j++) {
5030 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005031 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 a->a_lnotab_off += ncodes * 2;
5034 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005035 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 len = PyBytes_GET_SIZE(a->a_lnotab);
5038 if (a->a_lnotab_off + 2 >= len) {
5039 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5040 return 0;
5041 }
5042 lnotab = (unsigned char *)
5043 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 a->a_lnotab_off += 2;
5046 if (d_bytecode) {
5047 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005048 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 }
5050 else { /* First line of a block; def stmt, etc. */
5051 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005052 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 }
5054 a->a_lineno = i->i_lineno;
5055 a->a_lineno_off = a->a_offset;
5056 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005057}
5058
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005059/* assemble_emit()
5060 Extend the bytecode with a new instruction.
5061 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005062*/
5063
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005064static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005065assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005066{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005067 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005069 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005070
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005071 arg = i->i_oparg;
5072 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 if (i->i_lineno && !assemble_lnotab(a, i))
5074 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005075 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 if (len > PY_SSIZE_T_MAX / 2)
5077 return 0;
5078 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5079 return 0;
5080 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005081 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005083 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005085}
5086
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005087static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005088assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005091 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 /* Compute the size of each block and fixup jump args.
5095 Replace block pointer with position in bytecode. */
5096 do {
5097 totsize = 0;
5098 for (i = a->a_nblocks - 1; i >= 0; i--) {
5099 b = a->a_postorder[i];
5100 bsize = blocksize(b);
5101 b->b_offset = totsize;
5102 totsize += bsize;
5103 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005104 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5106 bsize = b->b_offset;
5107 for (i = 0; i < b->b_iused; i++) {
5108 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005109 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 /* Relative jumps are computed relative to
5111 the instruction pointer after fetching
5112 the jump instruction.
5113 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005114 bsize += isize;
5115 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005117 if (instr->i_jrel) {
5118 instr->i_oparg -= bsize;
5119 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005120 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005121 if (instrsize(instr->i_oparg) != isize) {
5122 extended_arg_recompile = 1;
5123 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 }
5126 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 /* XXX: This is an awful hack that could hurt performance, but
5129 on the bright side it should work until we come up
5130 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 The issue is that in the first loop blocksize() is called
5133 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005134 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 So we loop until we stop seeing new EXTENDED_ARGs.
5138 The only EXTENDED_ARGs that could be popping up are
5139 ones in jump instructions. So this should converge
5140 fairly quickly.
5141 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005142 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005143}
5144
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005145static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005146dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 PyObject *tuple, *k, *v;
5149 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 tuple = PyTuple_New(size);
5152 if (tuple == NULL)
5153 return NULL;
5154 while (PyDict_Next(dict, &pos, &k, &v)) {
5155 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005156 /* The keys of the dictionary are tuples. (see compiler_add_o
5157 * and _PyCode_ConstantKey). The object we want is always second,
5158 * though. */
5159 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 Py_INCREF(k);
5161 assert((i - offset) < size);
5162 assert((i - offset) >= 0);
5163 PyTuple_SET_ITEM(tuple, i - offset, k);
5164 }
5165 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005166}
5167
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005168static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005169compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005172 int flags = 0;
5173 Py_ssize_t n;
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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 n = PyDict_Size(c->u->u_freevars);
5194 if (n < 0)
5195 return -1;
5196 if (n == 0) {
5197 n = PyDict_Size(c->u->u_cellvars);
5198 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01005199 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005201 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 }
5203 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005206}
5207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005208static PyCodeObject *
5209makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 PyObject *tmp;
5212 PyCodeObject *co = NULL;
5213 PyObject *consts = NULL;
5214 PyObject *names = NULL;
5215 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 PyObject *name = NULL;
5217 PyObject *freevars = NULL;
5218 PyObject *cellvars = NULL;
5219 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005220 Py_ssize_t nlocals;
5221 int nlocals_int;
5222 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005223 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 tmp = dict_keys_inorder(c->u->u_consts, 0);
5226 if (!tmp)
5227 goto error;
5228 consts = PySequence_List(tmp); /* optimize_code requires a list */
5229 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 names = dict_keys_inorder(c->u->u_names, 0);
5232 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5233 if (!consts || !names || !varnames)
5234 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5237 if (!cellvars)
5238 goto error;
5239 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5240 if (!freevars)
5241 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005244 assert(nlocals < INT_MAX);
5245 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 flags = compute_code_flags(c);
5248 if (flags < 0)
5249 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5252 if (!bytecode)
5253 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5256 if (!tmp)
5257 goto error;
5258 Py_DECREF(consts);
5259 consts = tmp;
5260
Victor Stinnerf8e32212013-11-19 23:56:34 +01005261 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5262 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5263 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005264 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 bytecode, consts, names, varnames,
5266 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005267 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 c->u->u_firstlineno,
5269 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005270 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 Py_XDECREF(consts);
5272 Py_XDECREF(names);
5273 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 Py_XDECREF(name);
5275 Py_XDECREF(freevars);
5276 Py_XDECREF(cellvars);
5277 Py_XDECREF(bytecode);
5278 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005279}
5280
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005281
5282/* For debugging purposes only */
5283#if 0
5284static void
5285dump_instr(const struct instr *i)
5286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 const char *jrel = i->i_jrel ? "jrel " : "";
5288 const char *jabs = i->i_jabs ? "jabs " : "";
5289 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005292 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5296 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005297}
5298
5299static void
5300dump_basicblock(const basicblock *b)
5301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 const char *seen = b->b_seen ? "seen " : "";
5303 const char *b_return = b->b_return ? "return " : "";
5304 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5305 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5306 if (b->b_instr) {
5307 int i;
5308 for (i = 0; i < b->b_iused; i++) {
5309 fprintf(stderr, " [%02d] ", i);
5310 dump_instr(b->b_instr + i);
5311 }
5312 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005313}
5314#endif
5315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005316static PyCodeObject *
5317assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 basicblock *b, *entryblock;
5320 struct assembler a;
5321 int i, j, nblocks;
5322 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 /* Make sure every block that falls off the end returns None.
5325 XXX NEXT_BLOCK() isn't quite right, because if the last
5326 block ends with a jump or return b_next shouldn't set.
5327 */
5328 if (!c->u->u_curblock->b_return) {
5329 NEXT_BLOCK(c);
5330 if (addNone)
5331 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5332 ADDOP(c, RETURN_VALUE);
5333 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 nblocks = 0;
5336 entryblock = NULL;
5337 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5338 nblocks++;
5339 entryblock = b;
5340 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 /* Set firstlineno if it wasn't explicitly set. */
5343 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005344 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5346 else
5347 c->u->u_firstlineno = 1;
5348 }
5349 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5350 goto error;
5351 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 /* Can't modify the bytecode after computing jump offsets. */
5354 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 /* Emit code in reverse postorder from dfs. */
5357 for (i = a.a_nblocks - 1; i >= 0; i--) {
5358 b = a.a_postorder[i];
5359 for (j = 0; j < b->b_iused; j++)
5360 if (!assemble_emit(&a, &b->b_instr[j]))
5361 goto error;
5362 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5365 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005366 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005370 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 assemble_free(&a);
5372 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005373}
Georg Brandl8334fd92010-12-04 10:26:46 +00005374
5375#undef PyAST_Compile
5376PyAPI_FUNC(PyCodeObject *)
5377PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5378 PyArena *arena)
5379{
5380 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5381}