blob: 20fe4bc5b5a28afd4d6c314033544b0d27997f22 [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:
990 case BUILD_SET_UNPACK:
991 case BUILD_MAP_UNPACK:
992 return 1 - oparg;
993 case BUILD_MAP_UNPACK_WITH_CALL:
994 return 1 - (oparg & 0xFF);
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;
Neal Norwitzc1505362006-12-28 06:47:50 +00001041#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case CALL_FUNCTION:
1043 return -NARGS(oparg);
1044 case CALL_FUNCTION_VAR:
1045 case CALL_FUNCTION_KW:
1046 return -NARGS(oparg)-1;
1047 case CALL_FUNCTION_VAR_KW:
1048 return -NARGS(oparg)-2;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001049#undef NARGS
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001050 case MAKE_FUNCTION:
1051 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1052 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 case BUILD_SLICE:
1054 if (oparg == 3)
1055 return -2;
1056 else
1057 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case LOAD_CLOSURE:
1060 return 1;
1061 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001062 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 return 1;
1064 case STORE_DEREF:
1065 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001066 case DELETE_DEREF:
1067 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001068 case GET_AWAITABLE:
1069 return 0;
1070 case SETUP_ASYNC_WITH:
1071 return 6;
1072 case BEFORE_ASYNC_WITH:
1073 return 1;
1074 case GET_AITER:
1075 return 0;
1076 case GET_ANEXT:
1077 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001078 case GET_YIELD_FROM_ITER:
1079 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001080 case FORMAT_VALUE:
1081 /* If there's a fmt_spec on the stack, we go from 2->1,
1082 else 1->1. */
1083 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001085 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
Larry Hastings3a907972013-11-23 14:49:22 -08001087 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088}
1089
1090/* Add an opcode with no argument.
1091 Returns 0 on failure, 1 on success.
1092*/
1093
1094static int
1095compiler_addop(struct compiler *c, int opcode)
1096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 basicblock *b;
1098 struct instr *i;
1099 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001100 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 off = compiler_next_instr(c, c->u->u_curblock);
1102 if (off < 0)
1103 return 0;
1104 b = c->u->u_curblock;
1105 i = &b->b_instr[off];
1106 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001107 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (opcode == RETURN_VALUE)
1109 b->b_return = 1;
1110 compiler_set_lineno(c, off);
1111 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112}
1113
Victor Stinnerf8e32212013-11-19 23:56:34 +01001114static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001115compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyObject *t, *v;
1118 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119
Victor Stinnerefb24132016-01-22 12:33:12 +01001120 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (t == NULL)
1122 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 v = PyDict_GetItem(dict, t);
1125 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001126 if (PyErr_Occurred()) {
1127 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001131 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (!v) {
1133 Py_DECREF(t);
1134 return -1;
1135 }
1136 if (PyDict_SetItem(dict, t, v) < 0) {
1137 Py_DECREF(t);
1138 Py_DECREF(v);
1139 return -1;
1140 }
1141 Py_DECREF(v);
1142 }
1143 else
1144 arg = PyLong_AsLong(v);
1145 Py_DECREF(t);
1146 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
1149static int
1150compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001153 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return compiler_addop_i(c, opcode, arg);
1157}
1158
1159static int
1160compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001163 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1165 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001166 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 arg = compiler_add_o(c, dict, mangled);
1168 Py_DECREF(mangled);
1169 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001170 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171 return compiler_addop_i(c, opcode, arg);
1172}
1173
1174/* Add an opcode with an integer argument.
1175 Returns 0 on failure, 1 on success.
1176*/
1177
1178static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001179compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 struct instr *i;
1182 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001183
Victor Stinner2ad474b2016-03-01 23:34:47 +01001184 /* oparg value is unsigned, but a signed C int is usually used to store
1185 it in the C code (like Python/ceval.c).
1186
1187 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1188
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001189 The argument of a concrete bytecode instruction is limited to 8-bit.
1190 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1191 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001192 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 off = compiler_next_instr(c, c->u->u_curblock);
1195 if (off < 0)
1196 return 0;
1197 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001198 i->i_opcode = opcode;
1199 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 compiler_set_lineno(c, off);
1201 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202}
1203
1204static int
1205compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 struct instr *i;
1208 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001210 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 assert(b != NULL);
1212 off = compiler_next_instr(c, c->u->u_curblock);
1213 if (off < 0)
1214 return 0;
1215 i = &c->u->u_curblock->b_instr[off];
1216 i->i_opcode = opcode;
1217 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 if (absolute)
1219 i->i_jabs = 1;
1220 else
1221 i->i_jrel = 1;
1222 compiler_set_lineno(c, off);
1223 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224}
1225
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001226/* NEXT_BLOCK() creates an implicit jump from the current block
1227 to the new block.
1228
1229 The returns inside this macro make it impossible to decref objects
1230 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001232#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (compiler_next_block((C)) == NULL) \
1234 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (!compiler_addop((C), (OP))) \
1239 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001240}
1241
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001242#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (!compiler_addop((C), (OP))) { \
1244 compiler_exit_scope(c); \
1245 return 0; \
1246 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001247}
1248
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1251 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001254/* Same as ADDOP_O, but steals a reference. */
1255#define ADDOP_N(C, OP, O, TYPE) { \
1256 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1257 Py_DECREF((O)); \
1258 return 0; \
1259 } \
1260 Py_DECREF((O)); \
1261}
1262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!compiler_addop_i((C), (OP), (O))) \
1270 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
1273#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!compiler_addop_j((C), (OP), (O), 1)) \
1275 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_addop_j((C), (OP), (O), 0)) \
1280 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
1283/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1284 the ASDL name to synthesize the name of the C type and the visit function.
1285*/
1286
1287#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (!compiler_visit_ ## TYPE((C), (V))) \
1289 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290}
1291
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001292#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (!compiler_visit_ ## TYPE((C), (V))) { \
1294 compiler_exit_scope(c); \
1295 return 0; \
1296 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001297}
1298
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (!compiler_visit_slice((C), (V), (CTX))) \
1301 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302}
1303
1304#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int _i; \
1306 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1307 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1308 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1309 if (!compiler_visit_ ## TYPE((C), elt)) \
1310 return 0; \
1311 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312}
1313
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001314#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 int _i; \
1316 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1317 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1318 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1319 if (!compiler_visit_ ## TYPE((C), elt)) { \
1320 compiler_exit_scope(c); \
1321 return 0; \
1322 } \
1323 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001324}
1325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326static int
1327compiler_isdocstring(stmt_ty s)
1328{
1329 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001330 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001331 if (s->v.Expr.value->kind == Str_kind)
1332 return 1;
1333 if (s->v.Expr.value->kind == Constant_kind)
1334 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336}
1337
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001338static int
1339is_const(expr_ty e)
1340{
1341 switch (e->kind) {
1342 case Constant_kind:
1343 case Num_kind:
1344 case Str_kind:
1345 case Bytes_kind:
1346 case Ellipsis_kind:
1347 case NameConstant_kind:
1348 return 1;
1349 default:
1350 return 0;
1351 }
1352}
1353
1354static PyObject *
1355get_const_value(expr_ty e)
1356{
1357 switch (e->kind) {
1358 case Constant_kind:
1359 return e->v.Constant.value;
1360 case Num_kind:
1361 return e->v.Num.n;
1362 case Str_kind:
1363 return e->v.Str.s;
1364 case Bytes_kind:
1365 return e->v.Bytes.s;
1366 case Ellipsis_kind:
1367 return Py_Ellipsis;
1368 case NameConstant_kind:
1369 return e->v.NameConstant.value;
1370 default:
1371 assert(!is_const(e));
1372 return NULL;
1373 }
1374}
1375
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001376/* Search if variable annotations are present statically in a block. */
1377
1378static int
1379find_ann(asdl_seq *stmts)
1380{
1381 int i, j, res = 0;
1382 stmt_ty st;
1383
1384 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1385 st = (stmt_ty)asdl_seq_GET(stmts, i);
1386 switch (st->kind) {
1387 case AnnAssign_kind:
1388 return 1;
1389 case For_kind:
1390 res = find_ann(st->v.For.body) ||
1391 find_ann(st->v.For.orelse);
1392 break;
1393 case AsyncFor_kind:
1394 res = find_ann(st->v.AsyncFor.body) ||
1395 find_ann(st->v.AsyncFor.orelse);
1396 break;
1397 case While_kind:
1398 res = find_ann(st->v.While.body) ||
1399 find_ann(st->v.While.orelse);
1400 break;
1401 case If_kind:
1402 res = find_ann(st->v.If.body) ||
1403 find_ann(st->v.If.orelse);
1404 break;
1405 case With_kind:
1406 res = find_ann(st->v.With.body);
1407 break;
1408 case AsyncWith_kind:
1409 res = find_ann(st->v.AsyncWith.body);
1410 break;
1411 case Try_kind:
1412 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1413 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1414 st->v.Try.handlers, j);
1415 if (find_ann(handler->v.ExceptHandler.body)) {
1416 return 1;
1417 }
1418 }
1419 res = find_ann(st->v.Try.body) ||
1420 find_ann(st->v.Try.finalbody) ||
1421 find_ann(st->v.Try.orelse);
1422 break;
1423 default:
1424 res = 0;
1425 }
1426 if (res) {
1427 break;
1428 }
1429 }
1430 return res;
1431}
1432
1433/* Compile a sequence of statements, checking for a docstring
1434 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435
1436static int
1437compiler_body(struct compiler *c, asdl_seq *stmts)
1438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 int i = 0;
1440 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001442 /* Set current line number to the line number of first statement.
1443 This way line number for SETUP_ANNOTATIONS will always
1444 coincide with the line number of first "real" statement in module.
1445 If body is empy, then lineno will be set later in assemble. */
1446 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1447 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
1448 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1449 c->u->u_lineno = st->lineno;
1450 }
1451 /* Every annotated class and module should have __annotations__. */
1452 if (find_ann(stmts)) {
1453 ADDOP(c, SETUP_ANNOTATIONS);
1454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (!asdl_seq_LEN(stmts))
1456 return 1;
1457 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001458 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 /* don't generate docstrings if -OO */
1460 i = 1;
1461 VISIT(c, expr, st->v.Expr.value);
1462 if (!compiler_nameop(c, __doc__, Store))
1463 return 0;
1464 }
1465 for (; i < asdl_seq_LEN(stmts); i++)
1466 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1467 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468}
1469
1470static PyCodeObject *
1471compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyCodeObject *co;
1474 int addNone = 1;
1475 static PyObject *module;
1476 if (!module) {
1477 module = PyUnicode_InternFromString("<module>");
1478 if (!module)
1479 return NULL;
1480 }
1481 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001482 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 return NULL;
1484 switch (mod->kind) {
1485 case Module_kind:
1486 if (!compiler_body(c, mod->v.Module.body)) {
1487 compiler_exit_scope(c);
1488 return 0;
1489 }
1490 break;
1491 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001492 if (find_ann(mod->v.Interactive.body)) {
1493 ADDOP(c, SETUP_ANNOTATIONS);
1494 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 c->c_interactive = 1;
1496 VISIT_SEQ_IN_SCOPE(c, stmt,
1497 mod->v.Interactive.body);
1498 break;
1499 case Expression_kind:
1500 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1501 addNone = 0;
1502 break;
1503 case Suite_kind:
1504 PyErr_SetString(PyExc_SystemError,
1505 "suite should not be possible");
1506 return 0;
1507 default:
1508 PyErr_Format(PyExc_SystemError,
1509 "module kind %d should not be possible",
1510 mod->kind);
1511 return 0;
1512 }
1513 co = assemble(c, addNone);
1514 compiler_exit_scope(c);
1515 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001516}
1517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518/* The test for LOCAL must come before the test for FREE in order to
1519 handle classes where name is both local and free. The local var is
1520 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001521*/
1522
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523static int
1524get_ref_type(struct compiler *c, PyObject *name)
1525{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001526 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001527 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1528 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1529 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001530 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (scope == 0) {
1532 char buf[350];
1533 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001534 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001536 PyUnicode_AsUTF8(name),
1537 PyUnicode_AsUTF8(c->u->u_name),
1538 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1539 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1540 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1541 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 );
1543 Py_FatalError(buf);
1544 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547}
1548
1549static int
1550compiler_lookup_arg(PyObject *dict, PyObject *name)
1551{
1552 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001553 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001554 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001555 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001556 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001557 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001558 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001559 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001560 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561}
1562
1563static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001564compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001566 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001567 if (qualname == NULL)
1568 qualname = co->co_name;
1569
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001570 if (free) {
1571 for (i = 0; i < free; ++i) {
1572 /* Bypass com_addop_varname because it will generate
1573 LOAD_DEREF but LOAD_CLOSURE is needed.
1574 */
1575 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1576 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001578 /* Special case: If a class contains a method with a
1579 free variable that has the same name as a method,
1580 the name will be considered free *and* local in the
1581 class. It should be handled by the closure, as
1582 well as by the normal name loookup logic.
1583 */
1584 reftype = get_ref_type(c, name);
1585 if (reftype == CELL)
1586 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1587 else /* (reftype == FREE) */
1588 arg = compiler_lookup_arg(c->u->u_freevars, name);
1589 if (arg == -1) {
1590 fprintf(stderr,
1591 "lookup %s in %s %d %d\n"
1592 "freevars of %s: %s\n",
1593 PyUnicode_AsUTF8(PyObject_Repr(name)),
1594 PyUnicode_AsUTF8(c->u->u_name),
1595 reftype, arg,
1596 PyUnicode_AsUTF8(co->co_name),
1597 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1598 Py_FatalError("compiler_make_closure()");
1599 }
1600 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001602 flags |= 0x08;
1603 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001606 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001607 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001609}
1610
1611static int
1612compiler_decorators(struct compiler *c, asdl_seq* decos)
1613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (!decos)
1617 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1620 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1621 }
1622 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623}
1624
1625static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001626compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001628{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001629 /* Push a dict of keyword-only default values.
1630
1631 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1632 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001633 int i;
1634 PyObject *keys = NULL;
1635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1637 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1638 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1639 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001640 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001641 if (!mangled) {
1642 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001644 if (keys == NULL) {
1645 keys = PyList_New(1);
1646 if (keys == NULL) {
1647 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001648 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001649 }
1650 PyList_SET_ITEM(keys, 0, mangled);
1651 }
1652 else {
1653 int res = PyList_Append(keys, mangled);
1654 Py_DECREF(mangled);
1655 if (res == -1) {
1656 goto error;
1657 }
1658 }
1659 if (!compiler_visit_expr(c, default_)) {
1660 goto error;
1661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
1663 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001664 if (keys != NULL) {
1665 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1666 PyObject *keys_tuple = PyList_AsTuple(keys);
1667 Py_DECREF(keys);
1668 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001669 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001670 }
1671 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1672 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001673 assert(default_count > 0);
1674 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001675 }
1676 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001677 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001678 }
1679
1680error:
1681 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001682 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001683}
1684
1685static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001686compiler_visit_argannotation(struct compiler *c, identifier id,
1687 expr_ty annotation, PyObject *names)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001690 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001692 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001693 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001694 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001695 if (PyList_Append(names, mangled) < 0) {
1696 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001697 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001698 }
1699 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001701 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001702}
1703
1704static int
1705compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1706 PyObject *names)
1707{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001708 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 for (i = 0; i < asdl_seq_LEN(args); i++) {
1710 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001711 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 c,
1713 arg->arg,
1714 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001715 names))
1716 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001718 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001719}
1720
1721static int
1722compiler_visit_annotations(struct compiler *c, arguments_ty args,
1723 expr_ty returns)
1724{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001725 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001726 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001727
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001728 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 */
1730 static identifier return_str;
1731 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001732 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 names = PyList_New(0);
1734 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001735 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001736
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001737 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001739 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001740 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001741 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001743 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001745 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001746 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001747 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (!return_str) {
1751 return_str = PyUnicode_InternFromString("return");
1752 if (!return_str)
1753 goto error;
1754 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001755 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 goto error;
1757 }
1758
1759 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761 PyObject *keytuple = PyList_AsTuple(names);
1762 Py_DECREF(names);
1763 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001764 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001766 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1767 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001768 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001770 else {
1771 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001772 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001773 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001774
1775error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001777 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001778}
1779
1780static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001781compiler_visit_defaults(struct compiler *c, arguments_ty args)
1782{
1783 VISIT_SEQ(c, expr, args->defaults);
1784 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1785 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786}
1787
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001788static Py_ssize_t
1789compiler_default_arguments(struct compiler *c, arguments_ty args)
1790{
1791 Py_ssize_t funcflags = 0;
1792 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001793 if (!compiler_visit_defaults(c, args))
1794 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001795 funcflags |= 0x01;
1796 }
1797 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001798 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001799 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001800 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001801 return -1;
1802 }
1803 else if (res > 0) {
1804 funcflags |= 0x02;
1805 }
1806 }
1807 return funcflags;
1808}
1809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810static int
Yury Selivanov75445082015-05-11 22:57:16 -04001811compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001814 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001815 arguments_ty args;
1816 expr_ty returns;
1817 identifier name;
1818 asdl_seq* decos;
1819 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001821 Py_ssize_t i, n, funcflags;
1822 int docstring;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001823 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001824 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825
Yury Selivanov75445082015-05-11 22:57:16 -04001826 if (is_async) {
1827 assert(s->kind == AsyncFunctionDef_kind);
1828
1829 args = s->v.AsyncFunctionDef.args;
1830 returns = s->v.AsyncFunctionDef.returns;
1831 decos = s->v.AsyncFunctionDef.decorator_list;
1832 name = s->v.AsyncFunctionDef.name;
1833 body = s->v.AsyncFunctionDef.body;
1834
1835 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1836 } else {
1837 assert(s->kind == FunctionDef_kind);
1838
1839 args = s->v.FunctionDef.args;
1840 returns = s->v.FunctionDef.returns;
1841 decos = s->v.FunctionDef.decorator_list;
1842 name = s->v.FunctionDef.name;
1843 body = s->v.FunctionDef.body;
1844
1845 scope_type = COMPILER_SCOPE_FUNCTION;
1846 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 if (!compiler_decorators(c, decos))
1849 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001850
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001851 funcflags = compiler_default_arguments(c, args);
1852 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001854 }
1855
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001856 annotations = compiler_visit_annotations(c, args, returns);
1857 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001858 return 0;
1859 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001860 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001861 funcflags |= 0x04;
1862 }
1863
1864 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1865 return 0;
1866 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867
Yury Selivanov75445082015-05-11 22:57:16 -04001868 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001870 if (docstring && c->c_optimize < 2) {
1871 if (st->v.Expr.value->kind == Constant_kind)
1872 first_const = st->v.Expr.value->v.Constant.value;
1873 else
1874 first_const = st->v.Expr.value->v.Str.s;
1875 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1877 compiler_exit_scope(c);
1878 return 0;
1879 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 c->u->u_argcount = asdl_seq_LEN(args->args);
1882 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001883 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* if there was a docstring, we need to skip the first statement */
1885 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001886 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 VISIT_IN_SCOPE(c, stmt, st);
1888 }
1889 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001890 qualname = c->u->u_qualname;
1891 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001893 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001894 Py_XDECREF(qualname);
1895 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001897 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001899 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001900 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* decorators */
1904 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1905 ADDOP_I(c, CALL_FUNCTION, 1);
1906 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907
Yury Selivanov75445082015-05-11 22:57:16 -04001908 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
1911static int
1912compiler_class(struct compiler *c, stmt_ty s)
1913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyCodeObject *co;
1915 PyObject *str;
1916 int i;
1917 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (!compiler_decorators(c, decos))
1920 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 /* ultimately generate code for:
1923 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1924 where:
1925 <func> is a function/closure created from the class body;
1926 it has a single argument (__locals__) where the dict
1927 (or MutableSequence) representing the locals is passed
1928 <name> is the class name
1929 <bases> is the positional arguments and *varargs argument
1930 <keywords> is the keyword arguments and **kwds argument
1931 This borrows from compiler_call.
1932 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001935 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1936 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 return 0;
1938 /* this block represents what we do in the new scope */
1939 {
1940 /* use the class name for name mangling */
1941 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001942 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* load (global) __name__ ... */
1944 str = PyUnicode_InternFromString("__name__");
1945 if (!str || !compiler_nameop(c, str, Load)) {
1946 Py_XDECREF(str);
1947 compiler_exit_scope(c);
1948 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 Py_DECREF(str);
1951 /* ... and store it as __module__ */
1952 str = PyUnicode_InternFromString("__module__");
1953 if (!str || !compiler_nameop(c, str, Store)) {
1954 Py_XDECREF(str);
1955 compiler_exit_scope(c);
1956 return 0;
1957 }
1958 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001959 assert(c->u->u_qualname);
1960 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001961 str = PyUnicode_InternFromString("__qualname__");
1962 if (!str || !compiler_nameop(c, str, Store)) {
1963 Py_XDECREF(str);
1964 compiler_exit_scope(c);
1965 return 0;
1966 }
1967 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* compile the body proper */
1969 if (!compiler_body(c, s->v.ClassDef.body)) {
1970 compiler_exit_scope(c);
1971 return 0;
1972 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001973 if (c->u->u_ste->ste_needs_class_closure) {
1974 /* return the (empty) __class__ cell */
1975 str = PyUnicode_InternFromString("__class__");
1976 if (str == NULL) {
1977 compiler_exit_scope(c);
1978 return 0;
1979 }
1980 i = compiler_lookup_arg(c->u->u_cellvars, str);
1981 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001982 if (i < 0) {
1983 compiler_exit_scope(c);
1984 return 0;
1985 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001986 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 /* Return the cell where to store __class__ */
1988 ADDOP_I(c, LOAD_CLOSURE, i);
1989 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001990 else {
1991 assert(PyDict_Size(c->u->u_cellvars) == 0);
1992 /* This happens when nobody references the cell. Return None. */
1993 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1996 /* create the code object */
1997 co = assemble(c, 1);
1998 }
1999 /* leave the new scope */
2000 compiler_exit_scope(c);
2001 if (co == NULL)
2002 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* 2. load the 'build_class' function */
2005 ADDOP(c, LOAD_BUILD_CLASS);
2006
2007 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002008 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 Py_DECREF(co);
2010
2011 /* 4. load class name */
2012 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2013
2014 /* 5. generate the rest of the code for the call */
2015 if (!compiler_call_helper(c, 2,
2016 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002017 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 return 0;
2019
2020 /* 6. apply decorators */
2021 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2022 ADDOP_I(c, CALL_FUNCTION, 1);
2023 }
2024
2025 /* 7. store into <name> */
2026 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2027 return 0;
2028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029}
2030
2031static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002032compiler_ifexp(struct compiler *c, expr_ty e)
2033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 basicblock *end, *next;
2035
2036 assert(e->kind == IfExp_kind);
2037 end = compiler_new_block(c);
2038 if (end == NULL)
2039 return 0;
2040 next = compiler_new_block(c);
2041 if (next == NULL)
2042 return 0;
2043 VISIT(c, expr, e->v.IfExp.test);
2044 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2045 VISIT(c, expr, e->v.IfExp.body);
2046 ADDOP_JREL(c, JUMP_FORWARD, end);
2047 compiler_use_next_block(c, next);
2048 VISIT(c, expr, e->v.IfExp.orelse);
2049 compiler_use_next_block(c, end);
2050 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002051}
2052
2053static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054compiler_lambda(struct compiler *c, expr_ty e)
2055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002057 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002059 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 arguments_ty args = e->v.Lambda.args;
2061 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (!name) {
2064 name = PyUnicode_InternFromString("<lambda>");
2065 if (!name)
2066 return 0;
2067 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002069 funcflags = compiler_default_arguments(c, args);
2070 if (funcflags == -1) {
2071 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002073
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002074 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002075 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* Make None the first constant, so the lambda can't have a
2079 docstring. */
2080 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 c->u->u_argcount = asdl_seq_LEN(args->args);
2084 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2085 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2086 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002087 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 }
2089 else {
2090 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002091 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002093 qualname = c->u->u_qualname;
2094 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002096 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002099 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002100 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 Py_DECREF(co);
2102
2103 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104}
2105
2106static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107compiler_if(struct compiler *c, stmt_ty s)
2108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 basicblock *end, *next;
2110 int constant;
2111 assert(s->kind == If_kind);
2112 end = compiler_new_block(c);
2113 if (end == NULL)
2114 return 0;
2115
Georg Brandl8334fd92010-12-04 10:26:46 +00002116 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 /* constant = 0: "if 0"
2118 * constant = 1: "if 1", "if 2", ...
2119 * constant = -1: rest */
2120 if (constant == 0) {
2121 if (s->v.If.orelse)
2122 VISIT_SEQ(c, stmt, s->v.If.orelse);
2123 } else if (constant == 1) {
2124 VISIT_SEQ(c, stmt, s->v.If.body);
2125 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002126 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 next = compiler_new_block(c);
2128 if (next == NULL)
2129 return 0;
2130 }
2131 else
2132 next = end;
2133 VISIT(c, expr, s->v.If.test);
2134 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2135 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002136 if (asdl_seq_LEN(s->v.If.orelse)) {
2137 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 compiler_use_next_block(c, next);
2139 VISIT_SEQ(c, stmt, s->v.If.orelse);
2140 }
2141 }
2142 compiler_use_next_block(c, end);
2143 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144}
2145
2146static int
2147compiler_for(struct compiler *c, stmt_ty s)
2148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 start = compiler_new_block(c);
2152 cleanup = compiler_new_block(c);
2153 end = compiler_new_block(c);
2154 if (start == NULL || end == NULL || cleanup == NULL)
2155 return 0;
2156 ADDOP_JREL(c, SETUP_LOOP, end);
2157 if (!compiler_push_fblock(c, LOOP, start))
2158 return 0;
2159 VISIT(c, expr, s->v.For.iter);
2160 ADDOP(c, GET_ITER);
2161 compiler_use_next_block(c, start);
2162 ADDOP_JREL(c, FOR_ITER, cleanup);
2163 VISIT(c, expr, s->v.For.target);
2164 VISIT_SEQ(c, stmt, s->v.For.body);
2165 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2166 compiler_use_next_block(c, cleanup);
2167 ADDOP(c, POP_BLOCK);
2168 compiler_pop_fblock(c, LOOP, start);
2169 VISIT_SEQ(c, stmt, s->v.For.orelse);
2170 compiler_use_next_block(c, end);
2171 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172}
2173
Yury Selivanov75445082015-05-11 22:57:16 -04002174
2175static int
2176compiler_async_for(struct compiler *c, stmt_ty s)
2177{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002178 _Py_IDENTIFIER(StopAsyncIteration);
2179
Yury Selivanov75445082015-05-11 22:57:16 -04002180 basicblock *try, *except, *end, *after_try, *try_cleanup,
2181 *after_loop, *after_loop_else;
2182
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002183 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2184 if (stop_aiter_error == NULL) {
2185 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002186 }
2187
2188 try = compiler_new_block(c);
2189 except = compiler_new_block(c);
2190 end = compiler_new_block(c);
2191 after_try = compiler_new_block(c);
2192 try_cleanup = compiler_new_block(c);
2193 after_loop = compiler_new_block(c);
2194 after_loop_else = compiler_new_block(c);
2195
2196 if (try == NULL || except == NULL || end == NULL
2197 || after_try == NULL || try_cleanup == NULL)
2198 return 0;
2199
2200 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2201 if (!compiler_push_fblock(c, LOOP, try))
2202 return 0;
2203
2204 VISIT(c, expr, s->v.AsyncFor.iter);
2205 ADDOP(c, GET_AITER);
2206 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2207 ADDOP(c, YIELD_FROM);
2208
2209 compiler_use_next_block(c, try);
2210
2211
2212 ADDOP_JREL(c, SETUP_EXCEPT, except);
2213 if (!compiler_push_fblock(c, EXCEPT, try))
2214 return 0;
2215
2216 ADDOP(c, GET_ANEXT);
2217 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2218 ADDOP(c, YIELD_FROM);
2219 VISIT(c, expr, s->v.AsyncFor.target);
2220 ADDOP(c, POP_BLOCK);
2221 compiler_pop_fblock(c, EXCEPT, try);
2222 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2223
2224
2225 compiler_use_next_block(c, except);
2226 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002227 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002228 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2229 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2230
2231 ADDOP(c, POP_TOP);
2232 ADDOP(c, POP_TOP);
2233 ADDOP(c, POP_TOP);
2234 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2235 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2236 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2237
2238
2239 compiler_use_next_block(c, try_cleanup);
2240 ADDOP(c, END_FINALLY);
2241
2242 compiler_use_next_block(c, after_try);
2243 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2244 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2245
2246 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2247 compiler_pop_fblock(c, LOOP, try);
2248
2249 compiler_use_next_block(c, after_loop);
2250 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2251
2252 compiler_use_next_block(c, after_loop_else);
2253 VISIT_SEQ(c, stmt, s->v.For.orelse);
2254
2255 compiler_use_next_block(c, end);
2256
2257 return 1;
2258}
2259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260static int
2261compiler_while(struct compiler *c, stmt_ty s)
2262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002264 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (constant == 0) {
2267 if (s->v.While.orelse)
2268 VISIT_SEQ(c, stmt, s->v.While.orelse);
2269 return 1;
2270 }
2271 loop = compiler_new_block(c);
2272 end = compiler_new_block(c);
2273 if (constant == -1) {
2274 anchor = compiler_new_block(c);
2275 if (anchor == NULL)
2276 return 0;
2277 }
2278 if (loop == NULL || end == NULL)
2279 return 0;
2280 if (s->v.While.orelse) {
2281 orelse = compiler_new_block(c);
2282 if (orelse == NULL)
2283 return 0;
2284 }
2285 else
2286 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 ADDOP_JREL(c, SETUP_LOOP, end);
2289 compiler_use_next_block(c, loop);
2290 if (!compiler_push_fblock(c, LOOP, loop))
2291 return 0;
2292 if (constant == -1) {
2293 VISIT(c, expr, s->v.While.test);
2294 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2295 }
2296 VISIT_SEQ(c, stmt, s->v.While.body);
2297 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* XXX should the two POP instructions be in a separate block
2300 if there is no else clause ?
2301 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002303 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002305 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 compiler_pop_fblock(c, LOOP, loop);
2307 if (orelse != NULL) /* what if orelse is just pass? */
2308 VISIT_SEQ(c, stmt, s->v.While.orelse);
2309 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312}
2313
2314static int
2315compiler_continue(struct compiler *c)
2316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2318 static const char IN_FINALLY_ERROR_MSG[] =
2319 "'continue' not supported inside 'finally' clause";
2320 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (!c->u->u_nfblocks)
2323 return compiler_error(c, LOOP_ERROR_MSG);
2324 i = c->u->u_nfblocks - 1;
2325 switch (c->u->u_fblock[i].fb_type) {
2326 case LOOP:
2327 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2328 break;
2329 case EXCEPT:
2330 case FINALLY_TRY:
2331 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2332 /* Prevent continue anywhere under a finally
2333 even if hidden in a sub-try or except. */
2334 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2335 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2336 }
2337 if (i == -1)
2338 return compiler_error(c, LOOP_ERROR_MSG);
2339 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2340 break;
2341 case FINALLY_END:
2342 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346}
2347
2348/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349
2350 SETUP_FINALLY L
2351 <code for body>
2352 POP_BLOCK
2353 LOAD_CONST <None>
2354 L: <code for finalbody>
2355 END_FINALLY
2356
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 The special instructions use the block stack. Each block
2358 stack entry contains the instruction that created it (here
2359 SETUP_FINALLY), the level of the value stack at the time the
2360 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 Pushes the current value stack level and the label
2364 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Pops en entry from the block stack, and pops the value
2367 stack until its level is the same as indicated on the
2368 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 Pops a variable number of entries from the *value* stack
2371 and re-raises the exception they specify. The number of
2372 entries popped depends on the (pseudo) exception type.
2373
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374 The block stack is unwound when an exception is raised:
2375 when a SETUP_FINALLY entry is found, the exception is pushed
2376 onto the value stack (and the exception condition is cleared),
2377 and the interpreter jumps to the label gotten from the block
2378 stack.
2379*/
2380
2381static int
2382compiler_try_finally(struct compiler *c, stmt_ty s)
2383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 basicblock *body, *end;
2385 body = compiler_new_block(c);
2386 end = compiler_new_block(c);
2387 if (body == NULL || end == NULL)
2388 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 ADDOP_JREL(c, SETUP_FINALLY, end);
2391 compiler_use_next_block(c, body);
2392 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2393 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002394 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2395 if (!compiler_try_except(c, s))
2396 return 0;
2397 }
2398 else {
2399 VISIT_SEQ(c, stmt, s->v.Try.body);
2400 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 ADDOP(c, POP_BLOCK);
2402 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2405 compiler_use_next_block(c, end);
2406 if (!compiler_push_fblock(c, FINALLY_END, end))
2407 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002408 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 ADDOP(c, END_FINALLY);
2410 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413}
2414
2415/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002416 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417 (The contents of the value stack is shown in [], with the top
2418 at the right; 'tb' is trace-back info, 'val' the exception's
2419 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420
2421 Value stack Label Instruction Argument
2422 [] SETUP_EXCEPT L1
2423 [] <code for S>
2424 [] POP_BLOCK
2425 [] JUMP_FORWARD L0
2426
2427 [tb, val, exc] L1: DUP )
2428 [tb, val, exc, exc] <evaluate E1> )
2429 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2430 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2431 [tb, val, exc] POP
2432 [tb, val] <assign to V1> (or POP if no V1)
2433 [tb] POP
2434 [] <code for S1>
2435 JUMP_FORWARD L0
2436
2437 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 .............................etc.......................
2439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2441
2442 [] L0: <next statement>
2443
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 Of course, parts are not generated if Vi or Ei is not present.
2445*/
2446static int
2447compiler_try_except(struct compiler *c, stmt_ty s)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002450 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 body = compiler_new_block(c);
2453 except = compiler_new_block(c);
2454 orelse = compiler_new_block(c);
2455 end = compiler_new_block(c);
2456 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2457 return 0;
2458 ADDOP_JREL(c, SETUP_EXCEPT, except);
2459 compiler_use_next_block(c, body);
2460 if (!compiler_push_fblock(c, EXCEPT, body))
2461 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002462 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 ADDOP(c, POP_BLOCK);
2464 compiler_pop_fblock(c, EXCEPT, body);
2465 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002466 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 compiler_use_next_block(c, except);
2468 for (i = 0; i < n; i++) {
2469 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002470 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 if (!handler->v.ExceptHandler.type && i < n-1)
2472 return compiler_error(c, "default 'except:' must be last");
2473 c->u->u_lineno_set = 0;
2474 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002475 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 except = compiler_new_block(c);
2477 if (except == NULL)
2478 return 0;
2479 if (handler->v.ExceptHandler.type) {
2480 ADDOP(c, DUP_TOP);
2481 VISIT(c, expr, handler->v.ExceptHandler.type);
2482 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2483 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2484 }
2485 ADDOP(c, POP_TOP);
2486 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002487 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002488
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002489 cleanup_end = compiler_new_block(c);
2490 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002491 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002492 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002493
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002494 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2495 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002497 /*
2498 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002499 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002500 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002501 try:
2502 # body
2503 finally:
2504 name = None
2505 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002506 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002508 /* second try: */
2509 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2510 compiler_use_next_block(c, cleanup_body);
2511 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2512 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002514 /* second # body */
2515 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2516 ADDOP(c, POP_BLOCK);
2517 ADDOP(c, POP_EXCEPT);
2518 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002520 /* finally: */
2521 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2522 compiler_use_next_block(c, cleanup_end);
2523 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2524 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002526 /* name = None */
2527 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2528 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002530 /* del name */
2531 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002533 ADDOP(c, END_FINALLY);
2534 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 }
2536 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002537 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002539 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002540 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002541 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542
Guido van Rossumb940e112007-01-10 16:19:56 +00002543 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002544 ADDOP(c, POP_TOP);
2545 compiler_use_next_block(c, cleanup_body);
2546 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2547 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002549 ADDOP(c, POP_EXCEPT);
2550 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 }
2552 ADDOP_JREL(c, JUMP_FORWARD, end);
2553 compiler_use_next_block(c, except);
2554 }
2555 ADDOP(c, END_FINALLY);
2556 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002557 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 compiler_use_next_block(c, end);
2559 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560}
2561
2562static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002563compiler_try(struct compiler *c, stmt_ty s) {
2564 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2565 return compiler_try_finally(c, s);
2566 else
2567 return compiler_try_except(c, s);
2568}
2569
2570
2571static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572compiler_import_as(struct compiler *c, identifier name, identifier asname)
2573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* The IMPORT_NAME opcode was already generated. This function
2575 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 If there is a dot in name, we need to split it and emit a
2578 LOAD_ATTR for each name.
2579 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2581 PyUnicode_GET_LENGTH(name), 1);
2582 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002583 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002584 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002586 Py_ssize_t pos = dot + 1;
2587 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 dot = PyUnicode_FindChar(name, '.', pos,
2590 PyUnicode_GET_LENGTH(name), 1);
2591 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002592 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002593 attr = PyUnicode_Substring(name, pos,
2594 (dot != -1) ? dot :
2595 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002597 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 ADDOP_O(c, LOAD_ATTR, attr, names);
2599 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 }
2602 }
2603 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604}
2605
2606static int
2607compiler_import(struct compiler *c, stmt_ty s)
2608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* The Import node stores a module name like a.b.c as a single
2610 string. This is convenient for all cases except
2611 import a.b.c as d
2612 where we need to parse that string to extract the individual
2613 module names.
2614 XXX Perhaps change the representation to make this case simpler?
2615 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002616 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 for (i = 0; i < n; i++) {
2619 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2620 int r;
2621 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 level = PyLong_FromLong(0);
2624 if (level == NULL)
2625 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 ADDOP_O(c, LOAD_CONST, level, consts);
2628 Py_DECREF(level);
2629 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2630 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 if (alias->asname) {
2633 r = compiler_import_as(c, alias->name, alias->asname);
2634 if (!r)
2635 return r;
2636 }
2637 else {
2638 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002639 Py_ssize_t dot = PyUnicode_FindChar(
2640 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002641 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002643 if (tmp == NULL)
2644 return 0;
2645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002647 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 Py_DECREF(tmp);
2649 }
2650 if (!r)
2651 return r;
2652 }
2653 }
2654 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655}
2656
2657static int
2658compiler_from_import(struct compiler *c, stmt_ty s)
2659{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002660 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 PyObject *names = PyTuple_New(n);
2663 PyObject *level;
2664 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 if (!empty_string) {
2667 empty_string = PyUnicode_FromString("");
2668 if (!empty_string)
2669 return 0;
2670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 if (!names)
2673 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 level = PyLong_FromLong(s->v.ImportFrom.level);
2676 if (!level) {
2677 Py_DECREF(names);
2678 return 0;
2679 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 /* build up the names */
2682 for (i = 0; i < n; i++) {
2683 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2684 Py_INCREF(alias->name);
2685 PyTuple_SET_ITEM(names, i, alias->name);
2686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2689 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2690 Py_DECREF(level);
2691 Py_DECREF(names);
2692 return compiler_error(c, "from __future__ imports must occur "
2693 "at the beginning of the file");
2694 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 ADDOP_O(c, LOAD_CONST, level, consts);
2697 Py_DECREF(level);
2698 ADDOP_O(c, LOAD_CONST, names, consts);
2699 Py_DECREF(names);
2700 if (s->v.ImportFrom.module) {
2701 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2702 }
2703 else {
2704 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2705 }
2706 for (i = 0; i < n; i++) {
2707 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2708 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002710 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 assert(n == 1);
2712 ADDOP(c, IMPORT_STAR);
2713 return 1;
2714 }
2715
2716 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2717 store_name = alias->name;
2718 if (alias->asname)
2719 store_name = alias->asname;
2720
2721 if (!compiler_nameop(c, store_name, Store)) {
2722 Py_DECREF(names);
2723 return 0;
2724 }
2725 }
2726 /* remove imported module */
2727 ADDOP(c, POP_TOP);
2728 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729}
2730
2731static int
2732compiler_assert(struct compiler *c, stmt_ty s)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 static PyObject *assertion_error = NULL;
2735 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002736 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Georg Brandl8334fd92010-12-04 10:26:46 +00002738 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return 1;
2740 if (assertion_error == NULL) {
2741 assertion_error = PyUnicode_InternFromString("AssertionError");
2742 if (assertion_error == NULL)
2743 return 0;
2744 }
2745 if (s->v.Assert.test->kind == Tuple_kind &&
2746 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002747 msg = PyUnicode_FromString("assertion is always true, "
2748 "perhaps remove parentheses?");
2749 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002751 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2752 c->c_filename, c->u->u_lineno,
2753 NULL, NULL) == -1) {
2754 Py_DECREF(msg);
2755 return 0;
2756 }
2757 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 }
2759 VISIT(c, expr, s->v.Assert.test);
2760 end = compiler_new_block(c);
2761 if (end == NULL)
2762 return 0;
2763 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2764 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2765 if (s->v.Assert.msg) {
2766 VISIT(c, expr, s->v.Assert.msg);
2767 ADDOP_I(c, CALL_FUNCTION, 1);
2768 }
2769 ADDOP_I(c, RAISE_VARARGS, 1);
2770 compiler_use_next_block(c, end);
2771 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772}
2773
2774static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002775compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2776{
2777 if (c->c_interactive && c->c_nestlevel <= 1) {
2778 VISIT(c, expr, value);
2779 ADDOP(c, PRINT_EXPR);
2780 return 1;
2781 }
2782
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002783 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002784 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002785 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002786 }
2787
2788 VISIT(c, expr, value);
2789 ADDOP(c, POP_TOP);
2790 return 1;
2791}
2792
2793static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794compiler_visit_stmt(struct compiler *c, stmt_ty s)
2795{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002796 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 /* Always assign a lineno to the next instruction for a stmt. */
2799 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002800 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 switch (s->kind) {
2804 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002805 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 case ClassDef_kind:
2807 return compiler_class(c, s);
2808 case Return_kind:
2809 if (c->u->u_ste->ste_type != FunctionBlock)
2810 return compiler_error(c, "'return' outside function");
2811 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002812 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2813 return compiler_error(
2814 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 VISIT(c, expr, s->v.Return.value);
2816 }
2817 else
2818 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2819 ADDOP(c, RETURN_VALUE);
2820 break;
2821 case Delete_kind:
2822 VISIT_SEQ(c, expr, s->v.Delete.targets)
2823 break;
2824 case Assign_kind:
2825 n = asdl_seq_LEN(s->v.Assign.targets);
2826 VISIT(c, expr, s->v.Assign.value);
2827 for (i = 0; i < n; i++) {
2828 if (i < n - 1)
2829 ADDOP(c, DUP_TOP);
2830 VISIT(c, expr,
2831 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2832 }
2833 break;
2834 case AugAssign_kind:
2835 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002836 case AnnAssign_kind:
2837 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 case For_kind:
2839 return compiler_for(c, s);
2840 case While_kind:
2841 return compiler_while(c, s);
2842 case If_kind:
2843 return compiler_if(c, s);
2844 case Raise_kind:
2845 n = 0;
2846 if (s->v.Raise.exc) {
2847 VISIT(c, expr, s->v.Raise.exc);
2848 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002849 if (s->v.Raise.cause) {
2850 VISIT(c, expr, s->v.Raise.cause);
2851 n++;
2852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002854 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002856 case Try_kind:
2857 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 case Assert_kind:
2859 return compiler_assert(c, s);
2860 case Import_kind:
2861 return compiler_import(c, s);
2862 case ImportFrom_kind:
2863 return compiler_from_import(c, s);
2864 case Global_kind:
2865 case Nonlocal_kind:
2866 break;
2867 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002868 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 case Pass_kind:
2870 break;
2871 case Break_kind:
2872 if (!compiler_in_loop(c))
2873 return compiler_error(c, "'break' outside loop");
2874 ADDOP(c, BREAK_LOOP);
2875 break;
2876 case Continue_kind:
2877 return compiler_continue(c);
2878 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002879 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002880 case AsyncFunctionDef_kind:
2881 return compiler_function(c, s, 1);
2882 case AsyncWith_kind:
2883 return compiler_async_with(c, s, 0);
2884 case AsyncFor_kind:
2885 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 }
Yury Selivanov75445082015-05-11 22:57:16 -04002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889}
2890
2891static int
2892unaryop(unaryop_ty op)
2893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 switch (op) {
2895 case Invert:
2896 return UNARY_INVERT;
2897 case Not:
2898 return UNARY_NOT;
2899 case UAdd:
2900 return UNARY_POSITIVE;
2901 case USub:
2902 return UNARY_NEGATIVE;
2903 default:
2904 PyErr_Format(PyExc_SystemError,
2905 "unary op %d should not be possible", op);
2906 return 0;
2907 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908}
2909
2910static int
2911binop(struct compiler *c, operator_ty op)
2912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 switch (op) {
2914 case Add:
2915 return BINARY_ADD;
2916 case Sub:
2917 return BINARY_SUBTRACT;
2918 case Mult:
2919 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002920 case MatMult:
2921 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 case Div:
2923 return BINARY_TRUE_DIVIDE;
2924 case Mod:
2925 return BINARY_MODULO;
2926 case Pow:
2927 return BINARY_POWER;
2928 case LShift:
2929 return BINARY_LSHIFT;
2930 case RShift:
2931 return BINARY_RSHIFT;
2932 case BitOr:
2933 return BINARY_OR;
2934 case BitXor:
2935 return BINARY_XOR;
2936 case BitAnd:
2937 return BINARY_AND;
2938 case FloorDiv:
2939 return BINARY_FLOOR_DIVIDE;
2940 default:
2941 PyErr_Format(PyExc_SystemError,
2942 "binary op %d should not be possible", op);
2943 return 0;
2944 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945}
2946
2947static int
2948cmpop(cmpop_ty op)
2949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 switch (op) {
2951 case Eq:
2952 return PyCmp_EQ;
2953 case NotEq:
2954 return PyCmp_NE;
2955 case Lt:
2956 return PyCmp_LT;
2957 case LtE:
2958 return PyCmp_LE;
2959 case Gt:
2960 return PyCmp_GT;
2961 case GtE:
2962 return PyCmp_GE;
2963 case Is:
2964 return PyCmp_IS;
2965 case IsNot:
2966 return PyCmp_IS_NOT;
2967 case In:
2968 return PyCmp_IN;
2969 case NotIn:
2970 return PyCmp_NOT_IN;
2971 default:
2972 return PyCmp_BAD;
2973 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974}
2975
2976static int
2977inplace_binop(struct compiler *c, operator_ty op)
2978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 switch (op) {
2980 case Add:
2981 return INPLACE_ADD;
2982 case Sub:
2983 return INPLACE_SUBTRACT;
2984 case Mult:
2985 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002986 case MatMult:
2987 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 case Div:
2989 return INPLACE_TRUE_DIVIDE;
2990 case Mod:
2991 return INPLACE_MODULO;
2992 case Pow:
2993 return INPLACE_POWER;
2994 case LShift:
2995 return INPLACE_LSHIFT;
2996 case RShift:
2997 return INPLACE_RSHIFT;
2998 case BitOr:
2999 return INPLACE_OR;
3000 case BitXor:
3001 return INPLACE_XOR;
3002 case BitAnd:
3003 return INPLACE_AND;
3004 case FloorDiv:
3005 return INPLACE_FLOOR_DIVIDE;
3006 default:
3007 PyErr_Format(PyExc_SystemError,
3008 "inplace binary op %d should not be possible", op);
3009 return 0;
3010 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011}
3012
3013static int
3014compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3015{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003016 int op, scope;
3017 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 PyObject *dict = c->u->u_names;
3021 PyObject *mangled;
3022 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 mangled = _Py_Mangle(c->u->u_private, name);
3025 if (!mangled)
3026 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003027
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003028 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
3029 PyUnicode_CompareWithASCIIString(name, "True") &&
3030 PyUnicode_CompareWithASCIIString(name, "False"));
3031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 op = 0;
3033 optype = OP_NAME;
3034 scope = PyST_GetScope(c->u->u_ste, mangled);
3035 switch (scope) {
3036 case FREE:
3037 dict = c->u->u_freevars;
3038 optype = OP_DEREF;
3039 break;
3040 case CELL:
3041 dict = c->u->u_cellvars;
3042 optype = OP_DEREF;
3043 break;
3044 case LOCAL:
3045 if (c->u->u_ste->ste_type == FunctionBlock)
3046 optype = OP_FAST;
3047 break;
3048 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003049 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 optype = OP_GLOBAL;
3051 break;
3052 case GLOBAL_EXPLICIT:
3053 optype = OP_GLOBAL;
3054 break;
3055 default:
3056 /* scope can be 0 */
3057 break;
3058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003061 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 switch (optype) {
3064 case OP_DEREF:
3065 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003066 case Load:
3067 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3068 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 case Store: op = STORE_DEREF; break;
3070 case AugLoad:
3071 case AugStore:
3072 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003073 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 case Param:
3075 default:
3076 PyErr_SetString(PyExc_SystemError,
3077 "param invalid for deref variable");
3078 return 0;
3079 }
3080 break;
3081 case OP_FAST:
3082 switch (ctx) {
3083 case Load: op = LOAD_FAST; break;
3084 case Store: op = STORE_FAST; break;
3085 case Del: op = DELETE_FAST; break;
3086 case AugLoad:
3087 case AugStore:
3088 break;
3089 case Param:
3090 default:
3091 PyErr_SetString(PyExc_SystemError,
3092 "param invalid for local variable");
3093 return 0;
3094 }
3095 ADDOP_O(c, op, mangled, varnames);
3096 Py_DECREF(mangled);
3097 return 1;
3098 case OP_GLOBAL:
3099 switch (ctx) {
3100 case Load: op = LOAD_GLOBAL; break;
3101 case Store: op = STORE_GLOBAL; break;
3102 case Del: op = DELETE_GLOBAL; break;
3103 case AugLoad:
3104 case AugStore:
3105 break;
3106 case Param:
3107 default:
3108 PyErr_SetString(PyExc_SystemError,
3109 "param invalid for global variable");
3110 return 0;
3111 }
3112 break;
3113 case OP_NAME:
3114 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003115 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 case Store: op = STORE_NAME; break;
3117 case Del: op = DELETE_NAME; break;
3118 case AugLoad:
3119 case AugStore:
3120 break;
3121 case Param:
3122 default:
3123 PyErr_SetString(PyExc_SystemError,
3124 "param invalid for name variable");
3125 return 0;
3126 }
3127 break;
3128 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 assert(op);
3131 arg = compiler_add_o(c, dict, mangled);
3132 Py_DECREF(mangled);
3133 if (arg < 0)
3134 return 0;
3135 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136}
3137
3138static int
3139compiler_boolop(struct compiler *c, expr_ty e)
3140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003142 int jumpi;
3143 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 assert(e->kind == BoolOp_kind);
3147 if (e->v.BoolOp.op == And)
3148 jumpi = JUMP_IF_FALSE_OR_POP;
3149 else
3150 jumpi = JUMP_IF_TRUE_OR_POP;
3151 end = compiler_new_block(c);
3152 if (end == NULL)
3153 return 0;
3154 s = e->v.BoolOp.values;
3155 n = asdl_seq_LEN(s) - 1;
3156 assert(n >= 0);
3157 for (i = 0; i < n; ++i) {
3158 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3159 ADDOP_JABS(c, jumpi, end);
3160 }
3161 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3162 compiler_use_next_block(c, end);
3163 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164}
3165
3166static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003167starunpack_helper(struct compiler *c, asdl_seq *elts,
3168 int single_op, int inner_op, int outer_op)
3169{
3170 Py_ssize_t n = asdl_seq_LEN(elts);
3171 Py_ssize_t i, nsubitems = 0, nseen = 0;
3172 for (i = 0; i < n; i++) {
3173 expr_ty elt = asdl_seq_GET(elts, i);
3174 if (elt->kind == Starred_kind) {
3175 if (nseen) {
3176 ADDOP_I(c, inner_op, nseen);
3177 nseen = 0;
3178 nsubitems++;
3179 }
3180 VISIT(c, expr, elt->v.Starred.value);
3181 nsubitems++;
3182 }
3183 else {
3184 VISIT(c, expr, elt);
3185 nseen++;
3186 }
3187 }
3188 if (nsubitems) {
3189 if (nseen) {
3190 ADDOP_I(c, inner_op, nseen);
3191 nsubitems++;
3192 }
3193 ADDOP_I(c, outer_op, nsubitems);
3194 }
3195 else
3196 ADDOP_I(c, single_op, nseen);
3197 return 1;
3198}
3199
3200static int
3201assignment_helper(struct compiler *c, asdl_seq *elts)
3202{
3203 Py_ssize_t n = asdl_seq_LEN(elts);
3204 Py_ssize_t i;
3205 int seen_star = 0;
3206 for (i = 0; i < n; i++) {
3207 expr_ty elt = asdl_seq_GET(elts, i);
3208 if (elt->kind == Starred_kind && !seen_star) {
3209 if ((i >= (1 << 8)) ||
3210 (n-i-1 >= (INT_MAX >> 8)))
3211 return compiler_error(c,
3212 "too many expressions in "
3213 "star-unpacking assignment");
3214 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3215 seen_star = 1;
3216 asdl_seq_SET(elts, i, elt->v.Starred.value);
3217 }
3218 else if (elt->kind == Starred_kind) {
3219 return compiler_error(c,
3220 "two starred expressions in assignment");
3221 }
3222 }
3223 if (!seen_star) {
3224 ADDOP_I(c, UNPACK_SEQUENCE, n);
3225 }
3226 VISIT_SEQ(c, expr, elts);
3227 return 1;
3228}
3229
3230static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003231compiler_list(struct compiler *c, expr_ty e)
3232{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003233 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003235 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003237 else if (e->v.List.ctx == Load) {
3238 return starunpack_helper(c, elts,
3239 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003241 else
3242 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244}
3245
3246static int
3247compiler_tuple(struct compiler *c, expr_ty e)
3248{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003249 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003251 return assignment_helper(c, elts);
3252 }
3253 else if (e->v.Tuple.ctx == Load) {
3254 return starunpack_helper(c, elts,
3255 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3256 }
3257 else
3258 VISIT_SEQ(c, expr, elts);
3259 return 1;
3260}
3261
3262static int
3263compiler_set(struct compiler *c, expr_ty e)
3264{
3265 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3266 BUILD_SET, BUILD_SET_UNPACK);
3267}
3268
3269static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003270are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3271{
3272 Py_ssize_t i;
3273 for (i = begin; i < end; i++) {
3274 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3275 if (key == NULL || !is_const(key))
3276 return 0;
3277 }
3278 return 1;
3279}
3280
3281static int
3282compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3283{
3284 Py_ssize_t i, n = end - begin;
3285 PyObject *keys, *key;
3286 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3287 for (i = begin; i < end; i++) {
3288 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3289 }
3290 keys = PyTuple_New(n);
3291 if (keys == NULL) {
3292 return 0;
3293 }
3294 for (i = begin; i < end; i++) {
3295 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3296 Py_INCREF(key);
3297 PyTuple_SET_ITEM(keys, i - begin, key);
3298 }
3299 ADDOP_N(c, LOAD_CONST, keys, consts);
3300 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3301 }
3302 else {
3303 for (i = begin; i < end; i++) {
3304 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3305 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3306 }
3307 ADDOP_I(c, BUILD_MAP, n);
3308 }
3309 return 1;
3310}
3311
3312static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003313compiler_dict(struct compiler *c, expr_ty e)
3314{
Victor Stinner976bb402016-03-23 11:36:19 +01003315 Py_ssize_t i, n, elements;
3316 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003317 int is_unpacking = 0;
3318 n = asdl_seq_LEN(e->v.Dict.values);
3319 containers = 0;
3320 elements = 0;
3321 for (i = 0; i < n; i++) {
3322 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3323 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003324 if (!compiler_subdict(c, e, i - elements, i))
3325 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003326 containers++;
3327 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003329 if (is_unpacking) {
3330 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3331 containers++;
3332 }
3333 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003334 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 }
3336 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003337 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003338 if (!compiler_subdict(c, e, n - elements, n))
3339 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003340 containers++;
3341 }
3342 /* If there is more than one dict, they need to be merged into a new
3343 * dict. If there is one dict and it's an unpacking, then it needs
3344 * to be copied into a new dict." */
3345 while (containers > 1 || is_unpacking) {
3346 int oparg = containers < 255 ? containers : 255;
3347 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3348 containers -= (oparg - 1);
3349 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 }
3351 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352}
3353
3354static int
3355compiler_compare(struct compiler *c, expr_ty e)
3356{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003357 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3361 VISIT(c, expr, e->v.Compare.left);
3362 n = asdl_seq_LEN(e->v.Compare.ops);
3363 assert(n > 0);
3364 if (n > 1) {
3365 cleanup = compiler_new_block(c);
3366 if (cleanup == NULL)
3367 return 0;
3368 VISIT(c, expr,
3369 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3370 }
3371 for (i = 1; i < n; i++) {
3372 ADDOP(c, DUP_TOP);
3373 ADDOP(c, ROT_THREE);
3374 ADDOP_I(c, COMPARE_OP,
3375 cmpop((cmpop_ty)(asdl_seq_GET(
3376 e->v.Compare.ops, i - 1))));
3377 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3378 NEXT_BLOCK(c);
3379 if (i < (n - 1))
3380 VISIT(c, expr,
3381 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3382 }
3383 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3384 ADDOP_I(c, COMPARE_OP,
3385 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3386 if (n > 1) {
3387 basicblock *end = compiler_new_block(c);
3388 if (end == NULL)
3389 return 0;
3390 ADDOP_JREL(c, JUMP_FORWARD, end);
3391 compiler_use_next_block(c, cleanup);
3392 ADDOP(c, ROT_TWO);
3393 ADDOP(c, POP_TOP);
3394 compiler_use_next_block(c, end);
3395 }
3396 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397}
3398
3399static int
3400compiler_call(struct compiler *c, expr_ty e)
3401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 VISIT(c, expr, e->v.Call.func);
3403 return compiler_call_helper(c, 0,
3404 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003405 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003406}
3407
Eric V. Smith235a6f02015-09-19 14:51:32 -04003408static int
3409compiler_joined_str(struct compiler *c, expr_ty e)
3410{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003411 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03003412 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003413 return 1;
3414}
3415
Eric V. Smitha78c7952015-11-03 12:45:05 -05003416/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003417static int
3418compiler_formatted_value(struct compiler *c, expr_ty e)
3419{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003420 /* Our oparg encodes 2 pieces of information: the conversion
3421 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003422
Eric V. Smitha78c7952015-11-03 12:45:05 -05003423 Convert the conversion char to 2 bits:
3424 None: 000 0x0 FVC_NONE
3425 !s : 001 0x1 FVC_STR
3426 !r : 010 0x2 FVC_REPR
3427 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003428
Eric V. Smitha78c7952015-11-03 12:45:05 -05003429 next bit is whether or not we have a format spec:
3430 yes : 100 0x4
3431 no : 000 0x0
3432 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003433
Eric V. Smitha78c7952015-11-03 12:45:05 -05003434 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003435
Eric V. Smitha78c7952015-11-03 12:45:05 -05003436 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003437 VISIT(c, expr, e->v.FormattedValue.value);
3438
Eric V. Smitha78c7952015-11-03 12:45:05 -05003439 switch (e->v.FormattedValue.conversion) {
3440 case 's': oparg = FVC_STR; break;
3441 case 'r': oparg = FVC_REPR; break;
3442 case 'a': oparg = FVC_ASCII; break;
3443 case -1: oparg = FVC_NONE; break;
3444 default:
3445 PyErr_SetString(PyExc_SystemError,
3446 "Unrecognized conversion character");
3447 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003448 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003449 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003450 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003451 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003452 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003453 }
3454
Eric V. Smitha78c7952015-11-03 12:45:05 -05003455 /* And push our opcode and oparg */
3456 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003457 return 1;
3458}
3459
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003460static int
3461compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3462{
3463 Py_ssize_t i, n = end - begin;
3464 keyword_ty kw;
3465 PyObject *keys, *key;
3466 assert(n > 0);
3467 if (n > 1) {
3468 for (i = begin; i < end; i++) {
3469 kw = asdl_seq_GET(keywords, i);
3470 VISIT(c, expr, kw->value);
3471 }
3472 keys = PyTuple_New(n);
3473 if (keys == NULL) {
3474 return 0;
3475 }
3476 for (i = begin; i < end; i++) {
3477 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3478 Py_INCREF(key);
3479 PyTuple_SET_ITEM(keys, i - begin, key);
3480 }
3481 ADDOP_N(c, LOAD_CONST, keys, consts);
3482 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3483 }
3484 else {
3485 /* a for loop only executes once */
3486 for (i = begin; i < end; i++) {
3487 kw = asdl_seq_GET(keywords, i);
3488 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3489 VISIT(c, expr, kw->value);
3490 }
3491 ADDOP_I(c, BUILD_MAP, n);
3492 }
3493 return 1;
3494}
3495
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003496/* shared code between compiler_call and compiler_class */
3497static int
3498compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003499 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003500 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003501 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 int code = 0;
Victor Stinner976bb402016-03-23 11:36:19 +01003504 Py_ssize_t nelts, i, nseen;
3505 int nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003506
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003507 /* the number of tuples and dictionaries on the stack */
3508 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3509
3510 nkw = 0;
3511 nseen = 0; /* the number of positional arguments on the stack */
3512 nelts = asdl_seq_LEN(args);
3513 for (i = 0; i < nelts; i++) {
3514 expr_ty elt = asdl_seq_GET(args, i);
3515 if (elt->kind == Starred_kind) {
3516 /* A star-arg. If we've seen positional arguments,
3517 pack the positional arguments into a
3518 tuple. */
3519 if (nseen) {
3520 ADDOP_I(c, BUILD_TUPLE, nseen);
3521 nseen = 0;
3522 nsubargs++;
3523 }
3524 VISIT(c, expr, elt->v.Starred.value);
3525 nsubargs++;
3526 }
3527 else if (nsubargs) {
3528 /* We've seen star-args already, so we
3529 count towards items-to-pack-into-tuple. */
3530 VISIT(c, expr, elt);
3531 nseen++;
3532 }
3533 else {
3534 /* Positional arguments before star-arguments
3535 are left on the stack. */
3536 VISIT(c, expr, elt);
3537 n++;
3538 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003540 if (nseen) {
3541 /* Pack up any trailing positional arguments. */
3542 ADDOP_I(c, BUILD_TUPLE, nseen);
3543 nsubargs++;
3544 }
3545 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003547 if (nsubargs > 1) {
3548 /* If we ended up with more than one stararg, we need
3549 to concatenate them into a single sequence. */
3550 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3551 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003553
3554 /* Same dance again for keyword arguments */
3555 nseen = 0; /* the number of keyword arguments on the stack following */
3556 nelts = asdl_seq_LEN(keywords);
3557 for (i = 0; i < nelts; i++) {
3558 keyword_ty kw = asdl_seq_GET(keywords, i);
3559 if (kw->arg == NULL) {
3560 /* A keyword argument unpacking. */
3561 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003562 if (nsubkwargs) {
3563 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3564 return 0;
3565 nsubkwargs++;
3566 }
3567 else {
3568 Py_ssize_t j;
3569 for (j = 0; j < nseen; j++) {
3570 VISIT(c, keyword, asdl_seq_GET(keywords, j));
3571 }
3572 nkw = nseen;
3573 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003574 nseen = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003575 }
3576 VISIT(c, expr, kw->value);
3577 nsubkwargs++;
3578 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003579 else {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003580 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003581 }
3582 }
3583 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003584 if (nsubkwargs) {
3585 /* Pack up any trailing keyword arguments. */
3586 if (!compiler_subkwargs(c, keywords, nelts - nseen, nelts))
3587 return 0;
3588 nsubkwargs++;
3589 }
3590 else {
3591 VISIT_SEQ(c, keyword, keywords);
3592 nkw = nseen;
3593 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003594 }
3595 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003597 if (nsubkwargs > 1) {
3598 /* Pack it all up */
Serhiy Storchaka3c317e72016-06-12 09:22:01 +03003599 int function_pos = n + (code & 1) + 2 * nkw + 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003600 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003603 assert(n < 1<<8);
3604 assert(nkw < 1<<24);
3605 n |= nkw << 8;
3606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 switch (code) {
3608 case 0:
3609 ADDOP_I(c, CALL_FUNCTION, n);
3610 break;
3611 case 1:
3612 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3613 break;
3614 case 2:
3615 ADDOP_I(c, CALL_FUNCTION_KW, n);
3616 break;
3617 case 3:
3618 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3619 break;
3620 }
3621 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622}
3623
Nick Coghlan650f0d02007-04-15 12:05:43 +00003624
3625/* List and set comprehensions and generator expressions work by creating a
3626 nested function to perform the actual iteration. This means that the
3627 iteration variables don't leak into the current scope.
3628 The defined function is called immediately following its definition, with the
3629 result of that call being the result of the expression.
3630 The LC/SC version returns the populated container, while the GE version is
3631 flagged in symtable.c as a generator, so it returns the generator object
3632 when the function is called.
3633 This code *knows* that the loop cannot contain break, continue, or return,
3634 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3635
3636 Possible cleanups:
3637 - iterate over the generator sequence instead of using recursion
3638*/
3639
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003640
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642compiler_comprehension_generator(struct compiler *c,
3643 asdl_seq *generators, int gen_index,
3644 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003646 comprehension_ty gen;
3647 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3648 if (gen->is_async) {
3649 return compiler_async_comprehension_generator(
3650 c, generators, gen_index, elt, val, type);
3651 } else {
3652 return compiler_sync_comprehension_generator(
3653 c, generators, gen_index, elt, val, type);
3654 }
3655}
3656
3657static int
3658compiler_sync_comprehension_generator(struct compiler *c,
3659 asdl_seq *generators, int gen_index,
3660 expr_ty elt, expr_ty val, int type)
3661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* generate code for the iterator, then each of the ifs,
3663 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 comprehension_ty gen;
3666 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003667 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 start = compiler_new_block(c);
3670 skip = compiler_new_block(c);
3671 if_cleanup = compiler_new_block(c);
3672 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3675 anchor == NULL)
3676 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 if (gen_index == 0) {
3681 /* Receive outermost iter as an implicit argument */
3682 c->u->u_argcount = 1;
3683 ADDOP_I(c, LOAD_FAST, 0);
3684 }
3685 else {
3686 /* Sub-iter - calculate on the fly */
3687 VISIT(c, expr, gen->iter);
3688 ADDOP(c, GET_ITER);
3689 }
3690 compiler_use_next_block(c, start);
3691 ADDOP_JREL(c, FOR_ITER, anchor);
3692 NEXT_BLOCK(c);
3693 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 /* XXX this needs to be cleaned up...a lot! */
3696 n = asdl_seq_LEN(gen->ifs);
3697 for (i = 0; i < n; i++) {
3698 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3699 VISIT(c, expr, e);
3700 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3701 NEXT_BLOCK(c);
3702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 if (++gen_index < asdl_seq_LEN(generators))
3705 if (!compiler_comprehension_generator(c,
3706 generators, gen_index,
3707 elt, val, type))
3708 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 /* only append after the last for generator */
3711 if (gen_index >= asdl_seq_LEN(generators)) {
3712 /* comprehension specific code */
3713 switch (type) {
3714 case COMP_GENEXP:
3715 VISIT(c, expr, elt);
3716 ADDOP(c, YIELD_VALUE);
3717 ADDOP(c, POP_TOP);
3718 break;
3719 case COMP_LISTCOMP:
3720 VISIT(c, expr, elt);
3721 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3722 break;
3723 case COMP_SETCOMP:
3724 VISIT(c, expr, elt);
3725 ADDOP_I(c, SET_ADD, gen_index + 1);
3726 break;
3727 case COMP_DICTCOMP:
3728 /* With 'd[k] = v', v is evaluated before k, so we do
3729 the same. */
3730 VISIT(c, expr, val);
3731 VISIT(c, expr, elt);
3732 ADDOP_I(c, MAP_ADD, gen_index + 1);
3733 break;
3734 default:
3735 return 0;
3736 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 compiler_use_next_block(c, skip);
3739 }
3740 compiler_use_next_block(c, if_cleanup);
3741 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3742 compiler_use_next_block(c, anchor);
3743
3744 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745}
3746
3747static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003748compiler_async_comprehension_generator(struct compiler *c,
3749 asdl_seq *generators, int gen_index,
3750 expr_ty elt, expr_ty val, int type)
3751{
3752 _Py_IDENTIFIER(StopAsyncIteration);
3753
3754 comprehension_ty gen;
3755 basicblock *anchor, *skip, *if_cleanup, *try,
3756 *after_try, *except, *try_cleanup;
3757 Py_ssize_t i, n;
3758
3759 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3760 if (stop_aiter_error == NULL) {
3761 return 0;
3762 }
3763
3764 try = compiler_new_block(c);
3765 after_try = compiler_new_block(c);
3766 try_cleanup = compiler_new_block(c);
3767 except = compiler_new_block(c);
3768 skip = compiler_new_block(c);
3769 if_cleanup = compiler_new_block(c);
3770 anchor = compiler_new_block(c);
3771
3772 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3773 try == NULL || after_try == NULL ||
3774 except == NULL || after_try == NULL) {
3775 return 0;
3776 }
3777
3778 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3779
3780 if (gen_index == 0) {
3781 /* Receive outermost iter as an implicit argument */
3782 c->u->u_argcount = 1;
3783 ADDOP_I(c, LOAD_FAST, 0);
3784 }
3785 else {
3786 /* Sub-iter - calculate on the fly */
3787 VISIT(c, expr, gen->iter);
3788 ADDOP(c, GET_AITER);
3789 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3790 ADDOP(c, YIELD_FROM);
3791 }
3792
3793 compiler_use_next_block(c, try);
3794
3795
3796 ADDOP_JREL(c, SETUP_EXCEPT, except);
3797 if (!compiler_push_fblock(c, EXCEPT, try))
3798 return 0;
3799
3800 ADDOP(c, GET_ANEXT);
3801 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3802 ADDOP(c, YIELD_FROM);
3803 VISIT(c, expr, gen->target);
3804 ADDOP(c, POP_BLOCK);
3805 compiler_pop_fblock(c, EXCEPT, try);
3806 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3807
3808
3809 compiler_use_next_block(c, except);
3810 ADDOP(c, DUP_TOP);
3811 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3812 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3813 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3814
3815 ADDOP(c, POP_TOP);
3816 ADDOP(c, POP_TOP);
3817 ADDOP(c, POP_TOP);
3818 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3819 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3820
3821
3822 compiler_use_next_block(c, try_cleanup);
3823 ADDOP(c, END_FINALLY);
3824
3825 compiler_use_next_block(c, after_try);
3826
3827 n = asdl_seq_LEN(gen->ifs);
3828 for (i = 0; i < n; i++) {
3829 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3830 VISIT(c, expr, e);
3831 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3832 NEXT_BLOCK(c);
3833 }
3834
3835 if (++gen_index < asdl_seq_LEN(generators))
3836 if (!compiler_comprehension_generator(c,
3837 generators, gen_index,
3838 elt, val, type))
3839 return 0;
3840
3841 /* only append after the last for generator */
3842 if (gen_index >= asdl_seq_LEN(generators)) {
3843 /* comprehension specific code */
3844 switch (type) {
3845 case COMP_GENEXP:
3846 VISIT(c, expr, elt);
3847 ADDOP(c, YIELD_VALUE);
3848 ADDOP(c, POP_TOP);
3849 break;
3850 case COMP_LISTCOMP:
3851 VISIT(c, expr, elt);
3852 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3853 break;
3854 case COMP_SETCOMP:
3855 VISIT(c, expr, elt);
3856 ADDOP_I(c, SET_ADD, gen_index + 1);
3857 break;
3858 case COMP_DICTCOMP:
3859 /* With 'd[k] = v', v is evaluated before k, so we do
3860 the same. */
3861 VISIT(c, expr, val);
3862 VISIT(c, expr, elt);
3863 ADDOP_I(c, MAP_ADD, gen_index + 1);
3864 break;
3865 default:
3866 return 0;
3867 }
3868
3869 compiler_use_next_block(c, skip);
3870 }
3871 compiler_use_next_block(c, if_cleanup);
3872 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3873 compiler_use_next_block(c, anchor);
3874 ADDOP(c, POP_TOP);
3875
3876 return 1;
3877}
3878
3879static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003880compiler_comprehension(struct compiler *c, expr_ty e, int type,
3881 identifier name, asdl_seq *generators, expr_ty elt,
3882 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003885 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003886 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003887 int is_async_function = c->u->u_ste->ste_coroutine;
3888 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003889
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003890 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003891
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003892 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3893 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003894 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003896 }
3897
3898 is_async_generator = c->u->u_ste->ste_coroutine;
3899
3900 if (is_async_generator && !is_async_function) {
3901 if (e->lineno > c->u->u_lineno) {
3902 c->u->u_lineno = e->lineno;
3903 c->u->u_lineno_set = 0;
3904 }
3905 compiler_error(c, "asynchronous comprehension outside of "
3906 "an asynchronous function");
3907 goto error_in_scope;
3908 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 if (type != COMP_GENEXP) {
3911 int op;
3912 switch (type) {
3913 case COMP_LISTCOMP:
3914 op = BUILD_LIST;
3915 break;
3916 case COMP_SETCOMP:
3917 op = BUILD_SET;
3918 break;
3919 case COMP_DICTCOMP:
3920 op = BUILD_MAP;
3921 break;
3922 default:
3923 PyErr_Format(PyExc_SystemError,
3924 "unknown comprehension type %d", type);
3925 goto error_in_scope;
3926 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 ADDOP_I(c, op, 0);
3929 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 if (!compiler_comprehension_generator(c, generators, 0, elt,
3932 val, type))
3933 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 if (type != COMP_GENEXP) {
3936 ADDOP(c, RETURN_VALUE);
3937 }
3938
3939 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003940 qualname = c->u->u_qualname;
3941 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003943 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 goto error;
3945
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003946 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003948 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 Py_DECREF(co);
3950
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003951 VISIT(c, expr, outermost->iter);
3952
3953 if (outermost->is_async) {
3954 ADDOP(c, GET_AITER);
3955 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3956 ADDOP(c, YIELD_FROM);
3957 } else {
3958 ADDOP(c, GET_ITER);
3959 }
3960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003962
3963 if (is_async_generator && type != COMP_GENEXP) {
3964 ADDOP(c, GET_AWAITABLE);
3965 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3966 ADDOP(c, YIELD_FROM);
3967 }
3968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003970error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003972error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003973 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 Py_XDECREF(co);
3975 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003976}
3977
3978static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003979compiler_genexp(struct compiler *c, expr_ty e)
3980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 static identifier name;
3982 if (!name) {
3983 name = PyUnicode_FromString("<genexpr>");
3984 if (!name)
3985 return 0;
3986 }
3987 assert(e->kind == GeneratorExp_kind);
3988 return compiler_comprehension(c, e, COMP_GENEXP, name,
3989 e->v.GeneratorExp.generators,
3990 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991}
3992
3993static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003994compiler_listcomp(struct compiler *c, expr_ty e)
3995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 static identifier name;
3997 if (!name) {
3998 name = PyUnicode_FromString("<listcomp>");
3999 if (!name)
4000 return 0;
4001 }
4002 assert(e->kind == ListComp_kind);
4003 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4004 e->v.ListComp.generators,
4005 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004006}
4007
4008static int
4009compiler_setcomp(struct compiler *c, expr_ty e)
4010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 static identifier name;
4012 if (!name) {
4013 name = PyUnicode_FromString("<setcomp>");
4014 if (!name)
4015 return 0;
4016 }
4017 assert(e->kind == SetComp_kind);
4018 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4019 e->v.SetComp.generators,
4020 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004021}
4022
4023
4024static int
4025compiler_dictcomp(struct compiler *c, expr_ty e)
4026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 static identifier name;
4028 if (!name) {
4029 name = PyUnicode_FromString("<dictcomp>");
4030 if (!name)
4031 return 0;
4032 }
4033 assert(e->kind == DictComp_kind);
4034 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4035 e->v.DictComp.generators,
4036 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004037}
4038
4039
4040static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004041compiler_visit_keyword(struct compiler *c, keyword_ty k)
4042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 ADDOP_O(c, LOAD_CONST, k->arg, consts);
4044 VISIT(c, expr, k->value);
4045 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004046}
4047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004049 whether they are true or false.
4050
4051 Return values: 1 for true, 0 for false, -1 for non-constant.
4052 */
4053
4054static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004055expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 char *id;
4058 switch (e->kind) {
4059 case Ellipsis_kind:
4060 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004061 case Constant_kind:
4062 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 case Num_kind:
4064 return PyObject_IsTrue(e->v.Num.n);
4065 case Str_kind:
4066 return PyObject_IsTrue(e->v.Str.s);
4067 case Name_kind:
4068 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004069 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004070 if (id && strcmp(id, "__debug__") == 0)
4071 return !c->c_optimize;
4072 return -1;
4073 case NameConstant_kind: {
4074 PyObject *o = e->v.NameConstant.value;
4075 if (o == Py_None)
4076 return 0;
4077 else if (o == Py_True)
4078 return 1;
4079 else if (o == Py_False)
4080 return 0;
4081 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 default:
4083 return -1;
4084 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085}
4086
Yury Selivanov75445082015-05-11 22:57:16 -04004087
4088/*
4089 Implements the async with statement.
4090
4091 The semantics outlined in that PEP are as follows:
4092
4093 async with EXPR as VAR:
4094 BLOCK
4095
4096 It is implemented roughly as:
4097
4098 context = EXPR
4099 exit = context.__aexit__ # not calling it
4100 value = await context.__aenter__()
4101 try:
4102 VAR = value # if VAR present in the syntax
4103 BLOCK
4104 finally:
4105 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004106 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004107 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004108 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004109 if not (await exit(*exc)):
4110 raise
4111 */
4112static int
4113compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4114{
4115 basicblock *block, *finally;
4116 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4117
4118 assert(s->kind == AsyncWith_kind);
4119
4120 block = compiler_new_block(c);
4121 finally = compiler_new_block(c);
4122 if (!block || !finally)
4123 return 0;
4124
4125 /* Evaluate EXPR */
4126 VISIT(c, expr, item->context_expr);
4127
4128 ADDOP(c, BEFORE_ASYNC_WITH);
4129 ADDOP(c, GET_AWAITABLE);
4130 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4131 ADDOP(c, YIELD_FROM);
4132
4133 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4134
4135 /* SETUP_ASYNC_WITH pushes a finally block. */
4136 compiler_use_next_block(c, block);
4137 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4138 return 0;
4139 }
4140
4141 if (item->optional_vars) {
4142 VISIT(c, expr, item->optional_vars);
4143 }
4144 else {
4145 /* Discard result from context.__aenter__() */
4146 ADDOP(c, POP_TOP);
4147 }
4148
4149 pos++;
4150 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4151 /* BLOCK code */
4152 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4153 else if (!compiler_async_with(c, s, pos))
4154 return 0;
4155
4156 /* End of try block; start the finally block */
4157 ADDOP(c, POP_BLOCK);
4158 compiler_pop_fblock(c, FINALLY_TRY, block);
4159
4160 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4161 compiler_use_next_block(c, finally);
4162 if (!compiler_push_fblock(c, FINALLY_END, finally))
4163 return 0;
4164
4165 /* Finally block starts; context.__exit__ is on the stack under
4166 the exception or return information. Just issue our magic
4167 opcode. */
4168 ADDOP(c, WITH_CLEANUP_START);
4169
4170 ADDOP(c, GET_AWAITABLE);
4171 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4172 ADDOP(c, YIELD_FROM);
4173
4174 ADDOP(c, WITH_CLEANUP_FINISH);
4175
4176 /* Finally block ends. */
4177 ADDOP(c, END_FINALLY);
4178 compiler_pop_fblock(c, FINALLY_END, finally);
4179 return 1;
4180}
4181
4182
Guido van Rossumc2e20742006-02-27 22:32:47 +00004183/*
4184 Implements the with statement from PEP 343.
4185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004187
4188 with EXPR as VAR:
4189 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190
Guido van Rossumc2e20742006-02-27 22:32:47 +00004191 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192
Thomas Wouters477c8d52006-05-27 19:21:47 +00004193 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004194 exit = context.__exit__ # not calling it
4195 value = context.__enter__()
4196 try:
4197 VAR = value # if VAR present in the syntax
4198 BLOCK
4199 finally:
4200 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004201 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004202 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004203 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004204 exit(*exc)
4205 */
4206static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004207compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004208{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004209 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004210 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004211
4212 assert(s->kind == With_kind);
4213
Guido van Rossumc2e20742006-02-27 22:32:47 +00004214 block = compiler_new_block(c);
4215 finally = compiler_new_block(c);
4216 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004217 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004218
Thomas Wouters477c8d52006-05-27 19:21:47 +00004219 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004220 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004221 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004222
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004223 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004224 compiler_use_next_block(c, block);
4225 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004226 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004227 }
4228
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004229 if (item->optional_vars) {
4230 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004231 }
4232 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004234 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004235 }
4236
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004237 pos++;
4238 if (pos == asdl_seq_LEN(s->v.With.items))
4239 /* BLOCK code */
4240 VISIT_SEQ(c, stmt, s->v.With.body)
4241 else if (!compiler_with(c, s, pos))
4242 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004243
4244 /* End of try block; start the finally block */
4245 ADDOP(c, POP_BLOCK);
4246 compiler_pop_fblock(c, FINALLY_TRY, block);
4247
4248 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4249 compiler_use_next_block(c, finally);
4250 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004251 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004252
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004253 /* Finally block starts; context.__exit__ is on the stack under
4254 the exception or return information. Just issue our magic
4255 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004256 ADDOP(c, WITH_CLEANUP_START);
4257 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004258
4259 /* Finally block ends. */
4260 ADDOP(c, END_FINALLY);
4261 compiler_pop_fblock(c, FINALLY_END, finally);
4262 return 1;
4263}
4264
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004265static int
4266compiler_visit_expr(struct compiler *c, expr_ty e)
4267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 /* If expr e has a different line number than the last expr/stmt,
4269 set a new line number for the next instruction.
4270 */
4271 if (e->lineno > c->u->u_lineno) {
4272 c->u->u_lineno = e->lineno;
4273 c->u->u_lineno_set = 0;
4274 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004275 /* Updating the column offset is always harmless. */
4276 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 switch (e->kind) {
4278 case BoolOp_kind:
4279 return compiler_boolop(c, e);
4280 case BinOp_kind:
4281 VISIT(c, expr, e->v.BinOp.left);
4282 VISIT(c, expr, e->v.BinOp.right);
4283 ADDOP(c, binop(c, e->v.BinOp.op));
4284 break;
4285 case UnaryOp_kind:
4286 VISIT(c, expr, e->v.UnaryOp.operand);
4287 ADDOP(c, unaryop(e->v.UnaryOp.op));
4288 break;
4289 case Lambda_kind:
4290 return compiler_lambda(c, e);
4291 case IfExp_kind:
4292 return compiler_ifexp(c, e);
4293 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004294 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004296 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 case GeneratorExp_kind:
4298 return compiler_genexp(c, e);
4299 case ListComp_kind:
4300 return compiler_listcomp(c, e);
4301 case SetComp_kind:
4302 return compiler_setcomp(c, e);
4303 case DictComp_kind:
4304 return compiler_dictcomp(c, e);
4305 case Yield_kind:
4306 if (c->u->u_ste->ste_type != FunctionBlock)
4307 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004308 if (e->v.Yield.value) {
4309 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 }
4311 else {
4312 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4313 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004314 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004316 case YieldFrom_kind:
4317 if (c->u->u_ste->ste_type != FunctionBlock)
4318 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004319
4320 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4321 return compiler_error(c, "'yield from' inside async function");
4322
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004323 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004324 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004325 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4326 ADDOP(c, YIELD_FROM);
4327 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004328 case Await_kind:
4329 if (c->u->u_ste->ste_type != FunctionBlock)
4330 return compiler_error(c, "'await' outside function");
4331
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004332 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4333 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004334 return compiler_error(c, "'await' outside async function");
4335
4336 VISIT(c, expr, e->v.Await.value);
4337 ADDOP(c, GET_AWAITABLE);
4338 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4339 ADDOP(c, YIELD_FROM);
4340 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 case Compare_kind:
4342 return compiler_compare(c, e);
4343 case Call_kind:
4344 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004345 case Constant_kind:
4346 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4347 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 case Num_kind:
4349 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4350 break;
4351 case Str_kind:
4352 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4353 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004354 case JoinedStr_kind:
4355 return compiler_joined_str(c, e);
4356 case FormattedValue_kind:
4357 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 case Bytes_kind:
4359 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4360 break;
4361 case Ellipsis_kind:
4362 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4363 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004364 case NameConstant_kind:
4365 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4366 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 /* The following exprs can be assignment targets. */
4368 case Attribute_kind:
4369 if (e->v.Attribute.ctx != AugStore)
4370 VISIT(c, expr, e->v.Attribute.value);
4371 switch (e->v.Attribute.ctx) {
4372 case AugLoad:
4373 ADDOP(c, DUP_TOP);
4374 /* Fall through to load */
4375 case Load:
4376 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4377 break;
4378 case AugStore:
4379 ADDOP(c, ROT_TWO);
4380 /* Fall through to save */
4381 case Store:
4382 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4383 break;
4384 case Del:
4385 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4386 break;
4387 case Param:
4388 default:
4389 PyErr_SetString(PyExc_SystemError,
4390 "param invalid in attribute expression");
4391 return 0;
4392 }
4393 break;
4394 case Subscript_kind:
4395 switch (e->v.Subscript.ctx) {
4396 case AugLoad:
4397 VISIT(c, expr, e->v.Subscript.value);
4398 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4399 break;
4400 case Load:
4401 VISIT(c, expr, e->v.Subscript.value);
4402 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4403 break;
4404 case AugStore:
4405 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4406 break;
4407 case Store:
4408 VISIT(c, expr, e->v.Subscript.value);
4409 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4410 break;
4411 case Del:
4412 VISIT(c, expr, e->v.Subscript.value);
4413 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4414 break;
4415 case Param:
4416 default:
4417 PyErr_SetString(PyExc_SystemError,
4418 "param invalid in subscript expression");
4419 return 0;
4420 }
4421 break;
4422 case Starred_kind:
4423 switch (e->v.Starred.ctx) {
4424 case Store:
4425 /* In all legitimate cases, the Starred node was already replaced
4426 * by compiler_list/compiler_tuple. XXX: is that okay? */
4427 return compiler_error(c,
4428 "starred assignment target must be in a list or tuple");
4429 default:
4430 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004431 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 }
4433 break;
4434 case Name_kind:
4435 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4436 /* child nodes of List and Tuple will have expr_context set */
4437 case List_kind:
4438 return compiler_list(c, e);
4439 case Tuple_kind:
4440 return compiler_tuple(c, e);
4441 }
4442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004443}
4444
4445static int
4446compiler_augassign(struct compiler *c, stmt_ty s)
4447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 expr_ty e = s->v.AugAssign.target;
4449 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 switch (e->kind) {
4454 case Attribute_kind:
4455 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4456 AugLoad, e->lineno, e->col_offset, c->c_arena);
4457 if (auge == NULL)
4458 return 0;
4459 VISIT(c, expr, auge);
4460 VISIT(c, expr, s->v.AugAssign.value);
4461 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4462 auge->v.Attribute.ctx = AugStore;
4463 VISIT(c, expr, auge);
4464 break;
4465 case Subscript_kind:
4466 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4467 AugLoad, e->lineno, e->col_offset, c->c_arena);
4468 if (auge == NULL)
4469 return 0;
4470 VISIT(c, expr, auge);
4471 VISIT(c, expr, s->v.AugAssign.value);
4472 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4473 auge->v.Subscript.ctx = AugStore;
4474 VISIT(c, expr, auge);
4475 break;
4476 case Name_kind:
4477 if (!compiler_nameop(c, e->v.Name.id, Load))
4478 return 0;
4479 VISIT(c, expr, s->v.AugAssign.value);
4480 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4481 return compiler_nameop(c, e->v.Name.id, Store);
4482 default:
4483 PyErr_Format(PyExc_SystemError,
4484 "invalid node type (%d) for augmented assignment",
4485 e->kind);
4486 return 0;
4487 }
4488 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004489}
4490
4491static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004492check_ann_expr(struct compiler *c, expr_ty e)
4493{
4494 VISIT(c, expr, e);
4495 ADDOP(c, POP_TOP);
4496 return 1;
4497}
4498
4499static int
4500check_annotation(struct compiler *c, stmt_ty s)
4501{
4502 /* Annotations are only evaluated in a module or class. */
4503 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4504 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4505 return check_ann_expr(c, s->v.AnnAssign.annotation);
4506 }
4507 return 1;
4508}
4509
4510static int
4511check_ann_slice(struct compiler *c, slice_ty sl)
4512{
4513 switch(sl->kind) {
4514 case Index_kind:
4515 return check_ann_expr(c, sl->v.Index.value);
4516 case Slice_kind:
4517 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4518 return 0;
4519 }
4520 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4521 return 0;
4522 }
4523 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4524 return 0;
4525 }
4526 break;
4527 default:
4528 PyErr_SetString(PyExc_SystemError,
4529 "unexpected slice kind");
4530 return 0;
4531 }
4532 return 1;
4533}
4534
4535static int
4536check_ann_subscr(struct compiler *c, slice_ty sl)
4537{
4538 /* We check that everything in a subscript is defined at runtime. */
4539 Py_ssize_t i, n;
4540
4541 switch (sl->kind) {
4542 case Index_kind:
4543 case Slice_kind:
4544 if (!check_ann_slice(c, sl)) {
4545 return 0;
4546 }
4547 break;
4548 case ExtSlice_kind:
4549 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4550 for (i = 0; i < n; i++) {
4551 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4552 switch (subsl->kind) {
4553 case Index_kind:
4554 case Slice_kind:
4555 if (!check_ann_slice(c, subsl)) {
4556 return 0;
4557 }
4558 break;
4559 case ExtSlice_kind:
4560 default:
4561 PyErr_SetString(PyExc_SystemError,
4562 "extended slice invalid in nested slice");
4563 return 0;
4564 }
4565 }
4566 break;
4567 default:
4568 PyErr_Format(PyExc_SystemError,
4569 "invalid subscript kind %d", sl->kind);
4570 return 0;
4571 }
4572 return 1;
4573}
4574
4575static int
4576compiler_annassign(struct compiler *c, stmt_ty s)
4577{
4578 expr_ty targ = s->v.AnnAssign.target;
4579
4580 assert(s->kind == AnnAssign_kind);
4581
4582 /* We perform the actual assignment first. */
4583 if (s->v.AnnAssign.value) {
4584 VISIT(c, expr, s->v.AnnAssign.value);
4585 VISIT(c, expr, targ);
4586 }
4587 switch (targ->kind) {
4588 case Name_kind:
4589 /* If we have a simple name in a module or class, store annotation. */
4590 if (s->v.AnnAssign.simple &&
4591 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4592 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
4593 VISIT(c, expr, s->v.AnnAssign.annotation);
4594 ADDOP_O(c, STORE_ANNOTATION, targ->v.Name.id, names)
4595 }
4596 break;
4597 case Attribute_kind:
4598 if (!s->v.AnnAssign.value &&
4599 !check_ann_expr(c, targ->v.Attribute.value)) {
4600 return 0;
4601 }
4602 break;
4603 case Subscript_kind:
4604 if (!s->v.AnnAssign.value &&
4605 (!check_ann_expr(c, targ->v.Subscript.value) ||
4606 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4607 return 0;
4608 }
4609 break;
4610 default:
4611 PyErr_Format(PyExc_SystemError,
4612 "invalid node type (%d) for annotated assignment",
4613 targ->kind);
4614 return 0;
4615 }
4616 /* Annotation is evaluated last. */
4617 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4618 return 0;
4619 }
4620 return 1;
4621}
4622
4623static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004624compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 struct fblockinfo *f;
4627 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004628 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 "too many statically nested blocks");
4630 return 0;
4631 }
4632 f = &c->u->u_fblock[c->u->u_nfblocks++];
4633 f->fb_type = t;
4634 f->fb_block = b;
4635 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004636}
4637
4638static void
4639compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 struct compiler_unit *u = c->u;
4642 assert(u->u_nfblocks > 0);
4643 u->u_nfblocks--;
4644 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4645 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004646}
4647
Thomas Wouters89f507f2006-12-13 04:49:30 +00004648static int
4649compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 int i;
4651 struct compiler_unit *u = c->u;
4652 for (i = 0; i < u->u_nfblocks; ++i) {
4653 if (u->u_fblock[i].fb_type == LOOP)
4654 return 1;
4655 }
4656 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004657}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004658/* Raises a SyntaxError and returns 0.
4659 If something goes wrong, a different exception may be raised.
4660*/
4661
4662static int
4663compiler_error(struct compiler *c, const char *errstr)
4664{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004665 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004667
Victor Stinner14e461d2013-08-26 22:28:21 +02004668 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 if (!loc) {
4670 Py_INCREF(Py_None);
4671 loc = Py_None;
4672 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004673 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004674 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 if (!u)
4676 goto exit;
4677 v = Py_BuildValue("(zO)", errstr, u);
4678 if (!v)
4679 goto exit;
4680 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004681 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 Py_DECREF(loc);
4683 Py_XDECREF(u);
4684 Py_XDECREF(v);
4685 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004686}
4687
4688static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689compiler_handle_subscr(struct compiler *c, const char *kind,
4690 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 /* XXX this code is duplicated */
4695 switch (ctx) {
4696 case AugLoad: /* fall through to Load */
4697 case Load: op = BINARY_SUBSCR; break;
4698 case AugStore:/* fall through to Store */
4699 case Store: op = STORE_SUBSCR; break;
4700 case Del: op = DELETE_SUBSCR; break;
4701 case Param:
4702 PyErr_Format(PyExc_SystemError,
4703 "invalid %s kind %d in subscript\n",
4704 kind, ctx);
4705 return 0;
4706 }
4707 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004708 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 }
4710 else if (ctx == AugStore) {
4711 ADDOP(c, ROT_THREE);
4712 }
4713 ADDOP(c, op);
4714 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715}
4716
4717static int
4718compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 int n = 2;
4721 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 /* only handles the cases where BUILD_SLICE is emitted */
4724 if (s->v.Slice.lower) {
4725 VISIT(c, expr, s->v.Slice.lower);
4726 }
4727 else {
4728 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4729 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 if (s->v.Slice.upper) {
4732 VISIT(c, expr, s->v.Slice.upper);
4733 }
4734 else {
4735 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4736 }
4737
4738 if (s->v.Slice.step) {
4739 n++;
4740 VISIT(c, expr, s->v.Slice.step);
4741 }
4742 ADDOP_I(c, BUILD_SLICE, n);
4743 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004744}
4745
4746static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4748 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 switch (s->kind) {
4751 case Slice_kind:
4752 return compiler_slice(c, s, ctx);
4753 case Index_kind:
4754 VISIT(c, expr, s->v.Index.value);
4755 break;
4756 case ExtSlice_kind:
4757 default:
4758 PyErr_SetString(PyExc_SystemError,
4759 "extended slice invalid in nested slice");
4760 return 0;
4761 }
4762 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004763}
4764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004765static int
4766compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 char * kindname = NULL;
4769 switch (s->kind) {
4770 case Index_kind:
4771 kindname = "index";
4772 if (ctx != AugStore) {
4773 VISIT(c, expr, s->v.Index.value);
4774 }
4775 break;
4776 case Slice_kind:
4777 kindname = "slice";
4778 if (ctx != AugStore) {
4779 if (!compiler_slice(c, s, ctx))
4780 return 0;
4781 }
4782 break;
4783 case ExtSlice_kind:
4784 kindname = "extended slice";
4785 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004786 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 for (i = 0; i < n; i++) {
4788 slice_ty sub = (slice_ty)asdl_seq_GET(
4789 s->v.ExtSlice.dims, i);
4790 if (!compiler_visit_nested_slice(c, sub, ctx))
4791 return 0;
4792 }
4793 ADDOP_I(c, BUILD_TUPLE, n);
4794 }
4795 break;
4796 default:
4797 PyErr_Format(PyExc_SystemError,
4798 "invalid subscript kind %d", s->kind);
4799 return 0;
4800 }
4801 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004802}
4803
Thomas Wouters89f507f2006-12-13 04:49:30 +00004804/* End of the compiler section, beginning of the assembler section */
4805
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004806/* do depth-first search of basic block graph, starting with block.
4807 post records the block indices in post-order.
4808
4809 XXX must handle implicit jumps from one block to next
4810*/
4811
Thomas Wouters89f507f2006-12-13 04:49:30 +00004812struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 PyObject *a_bytecode; /* string containing bytecode */
4814 int a_offset; /* offset into bytecode */
4815 int a_nblocks; /* number of reachable blocks */
4816 basicblock **a_postorder; /* list of blocks in dfs postorder */
4817 PyObject *a_lnotab; /* string containing lnotab */
4818 int a_lnotab_off; /* offset into lnotab */
4819 int a_lineno; /* last lineno of emitted instruction */
4820 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004821};
4822
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004823static void
4824dfs(struct compiler *c, basicblock *b, struct assembler *a)
4825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 int i;
4827 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 if (b->b_seen)
4830 return;
4831 b->b_seen = 1;
4832 if (b->b_next != NULL)
4833 dfs(c, b->b_next, a);
4834 for (i = 0; i < b->b_iused; i++) {
4835 instr = &b->b_instr[i];
4836 if (instr->i_jrel || instr->i_jabs)
4837 dfs(c, instr->i_target, a);
4838 }
4839 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004840}
4841
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004842static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004843stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4844{
Larry Hastings3a907972013-11-23 14:49:22 -08004845 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 struct instr *instr;
4847 if (b->b_seen || b->b_startdepth >= depth)
4848 return maxdepth;
4849 b->b_seen = 1;
4850 b->b_startdepth = depth;
4851 for (i = 0; i < b->b_iused; i++) {
4852 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004853 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4854 if (effect == PY_INVALID_STACK_EFFECT) {
4855 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4856 Py_FatalError("PyCompile_OpcodeStackEffect()");
4857 }
4858 depth += effect;
4859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 if (depth > maxdepth)
4861 maxdepth = depth;
4862 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4863 if (instr->i_jrel || instr->i_jabs) {
4864 target_depth = depth;
4865 if (instr->i_opcode == FOR_ITER) {
4866 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004867 }
4868 else if (instr->i_opcode == SETUP_FINALLY ||
4869 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 target_depth = depth+3;
4871 if (target_depth > maxdepth)
4872 maxdepth = target_depth;
4873 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004874 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4875 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4876 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 maxdepth = stackdepth_walk(c, instr->i_target,
4878 target_depth, maxdepth);
4879 if (instr->i_opcode == JUMP_ABSOLUTE ||
4880 instr->i_opcode == JUMP_FORWARD) {
4881 goto out; /* remaining code is dead */
4882 }
4883 }
4884 }
4885 if (b->b_next)
4886 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004887out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 b->b_seen = 0;
4889 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004890}
4891
4892/* Find the flow path that needs the largest stack. We assume that
4893 * cycles in the flow graph have no net effect on the stack depth.
4894 */
4895static int
4896stackdepth(struct compiler *c)
4897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 basicblock *b, *entryblock;
4899 entryblock = NULL;
4900 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4901 b->b_seen = 0;
4902 b->b_startdepth = INT_MIN;
4903 entryblock = b;
4904 }
4905 if (!entryblock)
4906 return 0;
4907 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004908}
4909
4910static int
4911assemble_init(struct assembler *a, int nblocks, int firstlineno)
4912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 memset(a, 0, sizeof(struct assembler));
4914 a->a_lineno = firstlineno;
4915 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4916 if (!a->a_bytecode)
4917 return 0;
4918 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4919 if (!a->a_lnotab)
4920 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004921 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 PyErr_NoMemory();
4923 return 0;
4924 }
4925 a->a_postorder = (basicblock **)PyObject_Malloc(
4926 sizeof(basicblock *) * nblocks);
4927 if (!a->a_postorder) {
4928 PyErr_NoMemory();
4929 return 0;
4930 }
4931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004932}
4933
4934static void
4935assemble_free(struct assembler *a)
4936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004937 Py_XDECREF(a->a_bytecode);
4938 Py_XDECREF(a->a_lnotab);
4939 if (a->a_postorder)
4940 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004941}
4942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004943static int
4944blocksize(basicblock *b)
4945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 int i;
4947 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004950 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004952}
4953
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004954/* Appends a pair to the end of the line number table, a_lnotab, representing
4955 the instruction's bytecode offset and line number. See
4956 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004957
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004958static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004959assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004962 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 d_bytecode = a->a_offset - a->a_lineno_off;
4966 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 if(d_bytecode == 0 && d_lineno == 0)
4971 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 if (d_bytecode > 255) {
4974 int j, nbytes, ncodes = d_bytecode / 255;
4975 nbytes = a->a_lnotab_off + 2 * ncodes;
4976 len = PyBytes_GET_SIZE(a->a_lnotab);
4977 if (nbytes >= len) {
4978 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4979 len = nbytes;
4980 else if (len <= INT_MAX / 2)
4981 len *= 2;
4982 else {
4983 PyErr_NoMemory();
4984 return 0;
4985 }
4986 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4987 return 0;
4988 }
4989 lnotab = (unsigned char *)
4990 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4991 for (j = 0; j < ncodes; j++) {
4992 *lnotab++ = 255;
4993 *lnotab++ = 0;
4994 }
4995 d_bytecode -= ncodes * 255;
4996 a->a_lnotab_off += ncodes * 2;
4997 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004998 assert(0 <= d_bytecode && d_bytecode <= 255);
4999
5000 if (d_lineno < -128 || 127 < d_lineno) {
5001 int j, nbytes, ncodes, k;
5002 if (d_lineno < 0) {
5003 k = -128;
5004 /* use division on positive numbers */
5005 ncodes = (-d_lineno) / 128;
5006 }
5007 else {
5008 k = 127;
5009 ncodes = d_lineno / 127;
5010 }
5011 d_lineno -= ncodes * k;
5012 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 nbytes = a->a_lnotab_off + 2 * ncodes;
5014 len = PyBytes_GET_SIZE(a->a_lnotab);
5015 if (nbytes >= len) {
5016 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5017 len = nbytes;
5018 else if (len <= INT_MAX / 2)
5019 len *= 2;
5020 else {
5021 PyErr_NoMemory();
5022 return 0;
5023 }
5024 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5025 return 0;
5026 }
5027 lnotab = (unsigned char *)
5028 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5029 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005030 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 d_bytecode = 0;
5032 for (j = 1; j < ncodes; j++) {
5033 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005034 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 a->a_lnotab_off += ncodes * 2;
5037 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005038 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 len = PyBytes_GET_SIZE(a->a_lnotab);
5041 if (a->a_lnotab_off + 2 >= len) {
5042 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5043 return 0;
5044 }
5045 lnotab = (unsigned char *)
5046 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 a->a_lnotab_off += 2;
5049 if (d_bytecode) {
5050 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005051 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 }
5053 else { /* First line of a block; def stmt, etc. */
5054 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005055 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 }
5057 a->a_lineno = i->i_lineno;
5058 a->a_lineno_off = a->a_offset;
5059 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005060}
5061
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005062/* assemble_emit()
5063 Extend the bytecode with a new instruction.
5064 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005065*/
5066
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005067static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005068assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005069{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005070 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
5072 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005073
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005074 arg = i->i_oparg;
5075 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 if (i->i_lineno && !assemble_lnotab(a, i))
5077 return 0;
5078 if (a->a_offset + size >= len) {
5079 if (len > PY_SSIZE_T_MAX / 2)
5080 return 0;
5081 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5082 return 0;
5083 }
5084 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
5085 a->a_offset += size;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005086 write_op_arg((unsigned char*)code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005088}
5089
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005090static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005091assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005094 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 /* Compute the size of each block and fixup jump args.
5098 Replace block pointer with position in bytecode. */
5099 do {
5100 totsize = 0;
5101 for (i = a->a_nblocks - 1; i >= 0; i--) {
5102 b = a->a_postorder[i];
5103 bsize = blocksize(b);
5104 b->b_offset = totsize;
5105 totsize += bsize;
5106 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005107 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5109 bsize = b->b_offset;
5110 for (i = 0; i < b->b_iused; i++) {
5111 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005112 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 /* Relative jumps are computed relative to
5114 the instruction pointer after fetching
5115 the jump instruction.
5116 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005117 bsize += isize;
5118 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005120 if (instr->i_jrel) {
5121 instr->i_oparg -= bsize;
5122 }
5123 if (instrsize(instr->i_oparg) != isize) {
5124 extended_arg_recompile = 1;
5125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 }
5128 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 /* XXX: This is an awful hack that could hurt performance, but
5131 on the bright side it should work until we come up
5132 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 The issue is that in the first loop blocksize() is called
5135 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005136 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 So we loop until we stop seeing new EXTENDED_ARGs.
5140 The only EXTENDED_ARGs that could be popping up are
5141 ones in jump instructions. So this should converge
5142 fairly quickly.
5143 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005144 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005145}
5146
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005147static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005148dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 PyObject *tuple, *k, *v;
5151 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 tuple = PyTuple_New(size);
5154 if (tuple == NULL)
5155 return NULL;
5156 while (PyDict_Next(dict, &pos, &k, &v)) {
5157 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005158 /* The keys of the dictionary are tuples. (see compiler_add_o
5159 * and _PyCode_ConstantKey). The object we want is always second,
5160 * though. */
5161 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162 Py_INCREF(k);
5163 assert((i - offset) < size);
5164 assert((i - offset) >= 0);
5165 PyTuple_SET_ITEM(tuple, i - offset, k);
5166 }
5167 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005168}
5169
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005170static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005171compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005174 int flags = 0;
5175 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005177 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 if (ste->ste_nested)
5179 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005180 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005182 if (!ste->ste_generator && ste->ste_coroutine)
5183 flags |= CO_COROUTINE;
5184 if (ste->ste_generator && ste->ste_coroutine)
5185 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 if (ste->ste_varargs)
5187 flags |= CO_VARARGS;
5188 if (ste->ste_varkeywords)
5189 flags |= CO_VARKEYWORDS;
5190 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 /* (Only) inherit compilerflags in PyCF_MASK */
5193 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 n = PyDict_Size(c->u->u_freevars);
5196 if (n < 0)
5197 return -1;
5198 if (n == 0) {
5199 n = PyDict_Size(c->u->u_cellvars);
5200 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01005201 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005203 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 }
5205 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005208}
5209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005210static PyCodeObject *
5211makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 PyObject *tmp;
5214 PyCodeObject *co = NULL;
5215 PyObject *consts = NULL;
5216 PyObject *names = NULL;
5217 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 PyObject *name = NULL;
5219 PyObject *freevars = NULL;
5220 PyObject *cellvars = NULL;
5221 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005222 Py_ssize_t nlocals;
5223 int nlocals_int;
5224 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005225 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 tmp = dict_keys_inorder(c->u->u_consts, 0);
5228 if (!tmp)
5229 goto error;
5230 consts = PySequence_List(tmp); /* optimize_code requires a list */
5231 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 names = dict_keys_inorder(c->u->u_names, 0);
5234 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5235 if (!consts || !names || !varnames)
5236 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5239 if (!cellvars)
5240 goto error;
5241 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5242 if (!freevars)
5243 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005246 assert(nlocals < INT_MAX);
5247 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 flags = compute_code_flags(c);
5250 if (flags < 0)
5251 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5254 if (!bytecode)
5255 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5258 if (!tmp)
5259 goto error;
5260 Py_DECREF(consts);
5261 consts = tmp;
5262
Victor Stinnerf8e32212013-11-19 23:56:34 +01005263 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5264 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5265 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005266 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 bytecode, consts, names, varnames,
5268 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005269 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 c->u->u_firstlineno,
5271 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005272 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 Py_XDECREF(consts);
5274 Py_XDECREF(names);
5275 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 Py_XDECREF(name);
5277 Py_XDECREF(freevars);
5278 Py_XDECREF(cellvars);
5279 Py_XDECREF(bytecode);
5280 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005281}
5282
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005283
5284/* For debugging purposes only */
5285#if 0
5286static void
5287dump_instr(const struct instr *i)
5288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 const char *jrel = i->i_jrel ? "jrel " : "";
5290 const char *jabs = i->i_jabs ? "jabs " : "";
5291 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005294 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5298 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005299}
5300
5301static void
5302dump_basicblock(const basicblock *b)
5303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 const char *seen = b->b_seen ? "seen " : "";
5305 const char *b_return = b->b_return ? "return " : "";
5306 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5307 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5308 if (b->b_instr) {
5309 int i;
5310 for (i = 0; i < b->b_iused; i++) {
5311 fprintf(stderr, " [%02d] ", i);
5312 dump_instr(b->b_instr + i);
5313 }
5314 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005315}
5316#endif
5317
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318static PyCodeObject *
5319assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 basicblock *b, *entryblock;
5322 struct assembler a;
5323 int i, j, nblocks;
5324 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 /* Make sure every block that falls off the end returns None.
5327 XXX NEXT_BLOCK() isn't quite right, because if the last
5328 block ends with a jump or return b_next shouldn't set.
5329 */
5330 if (!c->u->u_curblock->b_return) {
5331 NEXT_BLOCK(c);
5332 if (addNone)
5333 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5334 ADDOP(c, RETURN_VALUE);
5335 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 nblocks = 0;
5338 entryblock = NULL;
5339 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5340 nblocks++;
5341 entryblock = b;
5342 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 /* Set firstlineno if it wasn't explicitly set. */
5345 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005346 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5348 else
5349 c->u->u_firstlineno = 1;
5350 }
5351 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5352 goto error;
5353 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 /* Can't modify the bytecode after computing jump offsets. */
5356 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 /* Emit code in reverse postorder from dfs. */
5359 for (i = a.a_nblocks - 1; i >= 0; i--) {
5360 b = a.a_postorder[i];
5361 for (j = 0; j < b->b_iused; j++)
5362 if (!assemble_emit(&a, &b->b_instr[j]))
5363 goto error;
5364 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5367 goto error;
5368 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
5369 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005372 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 assemble_free(&a);
5374 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005375}
Georg Brandl8334fd92010-12-04 10:26:46 +00005376
5377#undef PyAST_Compile
5378PyAPI_FUNC(PyCodeObject *)
5379PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5380 PyArena *arena)
5381{
5382 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5383}