blob: 1e720eab0d0e909ff86f95286bb7f2e05f6fe72b [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"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
46 unsigned i_hasarg : 1;
47 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 basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static 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 Stinnerad9a0662013-11-19 22:23:20 +0100199static int compiler_call_helper(struct compiler *c, Py_ssize_t 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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205static PyCodeObject *assemble(struct compiler *, int addNone);
206static PyObject *__doc__;
207
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400208#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* Name mangling: __private becomes _classname__private.
214 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200215 PyObject *result;
216 size_t nlen, plen, ipriv;
217 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 PyUnicode_READ_CHAR(ident, 0) != '_' ||
220 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_INCREF(ident);
222 return ident;
223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 nlen = PyUnicode_GET_LENGTH(ident);
225 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 The only time a name with a dot can occur is when
229 we are compiling an import statement that has a
230 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 TODO(jhylton): Decide whether we want to support
233 mangling of the module name, e.g. __M.X.
234 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
236 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
237 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident; /* Don't mangle __whatever__ */
240 }
241 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 ipriv = 0;
243 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
244 ipriv++;
245 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_INCREF(ident);
247 return ident; /* Don't mangle if class is just underscores */
248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000250
Antoine Pitrou55bff892013-04-06 21:21:04 +0200251 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
252 PyErr_SetString(PyExc_OverflowError,
253 "private identifier too large to be mangled");
254 return NULL;
255 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200257 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
258 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
259 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
260
261 result = PyUnicode_New(1 + nlen + plen, maxchar);
262 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
265 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200266 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
267 Py_DECREF(result);
268 return NULL;
269 }
270 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
271 Py_DECREF(result);
272 return NULL;
273 }
Victor Stinner8f825062012-04-27 13:55:39 +0200274 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000276}
277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278static int
279compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 c->c_stack = PyList_New(0);
284 if (!c->c_stack)
285 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288}
289
290PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200291PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
292 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 struct compiler c;
295 PyCodeObject *co = NULL;
296 PyCompilerFlags local_flags;
297 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!__doc__) {
300 __doc__ = PyUnicode_InternFromString("__doc__");
301 if (!__doc__)
302 return NULL;
303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!compiler_init(&c))
306 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200307 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 c.c_filename = filename;
309 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200310 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (c.c_future == NULL)
312 goto finally;
313 if (!flags) {
314 local_flags.cf_flags = 0;
315 flags = &local_flags;
316 }
317 merged = c.c_future->ff_features | flags->cf_flags;
318 c.c_future->ff_features = merged;
319 flags->cf_flags = merged;
320 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000321 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Victor Stinner14e461d2013-08-26 22:28:21 +0200324 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (c.c_st == NULL) {
326 if (!PyErr_Occurred())
327 PyErr_SetString(PyExc_SystemError, "no symtable");
328 goto finally;
329 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Thomas Wouters1175c432006-02-27 22:49:54 +0000333 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 compiler_free(&c);
335 assert(co || PyErr_Occurred());
336 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337}
338
339PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200340PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
341 int optimize, PyArena *arena)
342{
343 PyObject *filename;
344 PyCodeObject *co;
345 filename = PyUnicode_DecodeFSDefault(filename_str);
346 if (filename == NULL)
347 return NULL;
348 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
349 Py_DECREF(filename);
350 return co;
351
352}
353
354PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355PyNode_Compile(struct _node *n, const char *filename)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyCodeObject *co = NULL;
358 mod_ty mod;
359 PyArena *arena = PyArena_New();
360 if (!arena)
361 return NULL;
362 mod = PyAST_FromNode(n, NULL, filename, arena);
363 if (mod)
364 co = PyAST_Compile(mod, filename, NULL, arena);
365 PyArena_Free(arena);
366 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000367}
368
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000369static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (c->c_st)
373 PySymtable_Free(c->c_st);
374 if (c->c_future)
375 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200376 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000378}
379
Guido van Rossum79f25d91997-04-29 20:08:16 +0000380static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_ssize_t i, n;
384 PyObject *v, *k;
385 PyObject *dict = PyDict_New();
386 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 n = PyList_Size(list);
389 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100390 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!v) {
392 Py_DECREF(dict);
393 return NULL;
394 }
395 k = PyList_GET_ITEM(list, i);
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100396 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
398 Py_XDECREF(k);
399 Py_DECREF(v);
400 Py_DECREF(dict);
401 return NULL;
402 }
403 Py_DECREF(k);
404 Py_DECREF(v);
405 }
406 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407}
408
409/* Return new dict containing names from src that match scope(s).
410
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000413values are integers, starting at offset and increasing by one for
414each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415*/
416
417static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100418dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700420 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500422 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 assert(offset >= 0);
425 if (dest == NULL)
426 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427
Meador Inge2ca63152012-07-18 14:20:11 -0500428 /* Sort the keys so that we have a deterministic order on the indexes
429 saved in the returned dictionary. These indexes are used as indexes
430 into the free and cell var storage. Therefore if they aren't
431 deterministic, then the generated bytecode is not deterministic.
432 */
433 sorted_keys = PyDict_Keys(src);
434 if (sorted_keys == NULL)
435 return NULL;
436 if (PyList_Sort(sorted_keys) != 0) {
437 Py_DECREF(sorted_keys);
438 return NULL;
439 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500440 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500441
442 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* XXX this should probably be a macro in symtable.h */
444 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500445 k = PyList_GET_ITEM(sorted_keys, key_i);
446 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 assert(PyLong_Check(v));
448 vi = PyLong_AS_LONG(v);
449 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100452 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500454 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(dest);
456 return NULL;
457 }
458 i++;
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100459 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500461 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 Py_DECREF(item);
463 Py_DECREF(dest);
464 Py_XDECREF(tuple);
465 return NULL;
466 }
467 Py_DECREF(item);
468 Py_DECREF(tuple);
469 }
470 }
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000473}
474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000475static void
476compiler_unit_check(struct compiler_unit *u)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 basicblock *block;
479 for (block = u->u_blocks; block != NULL; block = block->b_list) {
480 assert((void *)block != (void *)0xcbcbcbcb);
481 assert((void *)block != (void *)0xfbfbfbfb);
482 assert((void *)block != (void *)0xdbdbdbdb);
483 if (block->b_instr != NULL) {
484 assert(block->b_ialloc > 0);
485 assert(block->b_iused > 0);
486 assert(block->b_ialloc >= block->b_iused);
487 }
488 else {
489 assert (block->b_iused == 0);
490 assert (block->b_ialloc == 0);
491 }
492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493}
494
495static void
496compiler_unit_free(struct compiler_unit *u)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 compiler_unit_check(u);
501 b = u->u_blocks;
502 while (b != NULL) {
503 if (b->b_instr)
504 PyObject_Free((void *)b->b_instr);
505 next = b->b_list;
506 PyObject_Free((void *)b);
507 b = next;
508 }
509 Py_CLEAR(u->u_ste);
510 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400511 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_CLEAR(u->u_consts);
513 Py_CLEAR(u->u_names);
514 Py_CLEAR(u->u_varnames);
515 Py_CLEAR(u->u_freevars);
516 Py_CLEAR(u->u_cellvars);
517 Py_CLEAR(u->u_private);
518 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519}
520
521static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100522compiler_enter_scope(struct compiler *c, identifier name,
523 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
528 struct compiler_unit));
529 if (!u) {
530 PyErr_NoMemory();
531 return 0;
532 }
533 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100534 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_argcount = 0;
536 u->u_kwonlyargcount = 0;
537 u->u_ste = PySymtable_Lookup(c->c_st, key);
538 if (!u->u_ste) {
539 compiler_unit_free(u);
540 return 0;
541 }
542 Py_INCREF(name);
543 u->u_name = name;
544 u->u_varnames = list2dict(u->u_ste->ste_varnames);
545 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
546 if (!u->u_varnames || !u->u_cellvars) {
547 compiler_unit_free(u);
548 return 0;
549 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500550 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000551 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500552 _Py_IDENTIFIER(__class__);
553 PyObject *tuple, *name, *zero;
554 int res;
555 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
556 assert(PyDict_Size(u->u_cellvars) == 0);
557 name = _PyUnicode_FromId(&PyId___class__);
558 if (!name) {
559 compiler_unit_free(u);
560 return 0;
561 }
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100562 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 if (!tuple) {
564 compiler_unit_free(u);
565 return 0;
566 }
567 zero = PyLong_FromLong(0);
568 if (!zero) {
569 Py_DECREF(tuple);
570 compiler_unit_free(u);
571 return 0;
572 }
573 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
574 Py_DECREF(tuple);
575 Py_DECREF(zero);
576 if (res < 0) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
583 PyDict_Size(u->u_cellvars));
584 if (!u->u_freevars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_blocks = NULL;
590 u->u_nfblocks = 0;
591 u->u_firstlineno = lineno;
592 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000593 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_lineno_set = 0;
595 u->u_consts = PyDict_New();
596 if (!u->u_consts) {
597 compiler_unit_free(u);
598 return 0;
599 }
600 u->u_names = PyDict_New();
601 if (!u->u_names) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Push the old compiler_unit on the stack. */
609 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400610 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
612 Py_XDECREF(capsule);
613 compiler_unit_free(u);
614 return 0;
615 }
616 Py_DECREF(capsule);
617 u->u_private = c->u->u_private;
618 Py_XINCREF(u->u_private);
619 }
620 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 c->c_nestlevel++;
623 if (compiler_use_new_block(c) == NULL)
624 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400626 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
627 if (!compiler_set_qualname(c))
628 return 0;
629 }
630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632}
633
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000634static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635compiler_exit_scope(struct compiler *c)
636{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100637 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 c->c_nestlevel--;
641 compiler_unit_free(c->u);
642 /* Restore c->u to the parent unit. */
643 n = PyList_GET_SIZE(c->c_stack) - 1;
644 if (n >= 0) {
645 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400646 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 assert(c->u);
648 /* we are deleting from a list so this really shouldn't fail */
649 if (PySequence_DelItem(c->c_stack, n) < 0)
650 Py_FatalError("compiler_exit_scope()");
651 compiler_unit_check(c->u);
652 }
653 else
654 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400658static int
659compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100661 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400662 _Py_static_string(dot_locals, ".<locals>");
663 Py_ssize_t stack_size;
664 struct compiler_unit *u = c->u;
665 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400669 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 if (stack_size > 1) {
671 int scope, force_global = 0;
672 struct compiler_unit *parent;
673 PyObject *mangled, *capsule;
674
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400675 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400676 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 assert(parent);
678
Yury Selivanov75445082015-05-11 22:57:16 -0400679 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
680 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
681 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 assert(u->u_name);
683 mangled = _Py_Mangle(parent->u_private, u->u_name);
684 if (!mangled)
685 return 0;
686 scope = PyST_GetScope(parent->u_ste, mangled);
687 Py_DECREF(mangled);
688 assert(scope != GLOBAL_IMPLICIT);
689 if (scope == GLOBAL_EXPLICIT)
690 force_global = 1;
691 }
692
693 if (!force_global) {
694 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400695 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
697 dot_locals_str = _PyUnicode_FromId(&dot_locals);
698 if (dot_locals_str == NULL)
699 return 0;
700 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
701 if (base == NULL)
702 return 0;
703 }
704 else {
705 Py_INCREF(parent->u_qualname);
706 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400707 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100708 }
709 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400711 if (base != NULL) {
712 dot_str = _PyUnicode_FromId(&dot);
713 if (dot_str == NULL) {
714 Py_DECREF(base);
715 return 0;
716 }
717 name = PyUnicode_Concat(base, dot_str);
718 Py_DECREF(base);
719 if (name == NULL)
720 return 0;
721 PyUnicode_Append(&name, u->u_name);
722 if (name == NULL)
723 return 0;
724 }
725 else {
726 Py_INCREF(u->u_name);
727 name = u->u_name;
728 }
729 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100732}
733
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734/* Allocate a new block and return a pointer to it.
735 Returns NULL on error.
736*/
737
738static basicblock *
739compiler_new_block(struct compiler *c)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 basicblock *b;
742 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 u = c->u;
745 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
746 if (b == NULL) {
747 PyErr_NoMemory();
748 return NULL;
749 }
750 memset((void *)b, 0, sizeof(basicblock));
751 /* Extend the singly linked list of blocks with new block. */
752 b->b_list = u->u_blocks;
753 u->u_blocks = b;
754 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755}
756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757static basicblock *
758compiler_use_new_block(struct compiler *c)
759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 basicblock *block = compiler_new_block(c);
761 if (block == NULL)
762 return NULL;
763 c->u->u_curblock = block;
764 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
767static basicblock *
768compiler_next_block(struct compiler *c)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 basicblock *block = compiler_new_block(c);
771 if (block == NULL)
772 return NULL;
773 c->u->u_curblock->b_next = block;
774 c->u->u_curblock = block;
775 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
778static basicblock *
779compiler_use_next_block(struct compiler *c, basicblock *block)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 assert(block != NULL);
782 c->u->u_curblock->b_next = block;
783 c->u->u_curblock = block;
784 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785}
786
787/* Returns the offset of the next instruction in the current block's
788 b_instr array. Resizes the b_instr as necessary.
789 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000790*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791
792static int
793compiler_next_instr(struct compiler *c, basicblock *b)
794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(b != NULL);
796 if (b->b_instr == NULL) {
797 b->b_instr = (struct instr *)PyObject_Malloc(
798 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
799 if (b->b_instr == NULL) {
800 PyErr_NoMemory();
801 return -1;
802 }
803 b->b_ialloc = DEFAULT_BLOCK_SIZE;
804 memset((char *)b->b_instr, 0,
805 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
806 }
807 else if (b->b_iused == b->b_ialloc) {
808 struct instr *tmp;
809 size_t oldsize, newsize;
810 oldsize = b->b_ialloc * sizeof(struct instr);
811 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (oldsize > (PY_SIZE_MAX >> 1)) {
814 PyErr_NoMemory();
815 return -1;
816 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (newsize == 0) {
819 PyErr_NoMemory();
820 return -1;
821 }
822 b->b_ialloc <<= 1;
823 tmp = (struct instr *)PyObject_Realloc(
824 (void *)b->b_instr, newsize);
825 if (tmp == NULL) {
826 PyErr_NoMemory();
827 return -1;
828 }
829 b->b_instr = tmp;
830 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
831 }
832 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833}
834
Christian Heimes2202f872008-02-06 14:31:34 +0000835/* Set the i_lineno member of the instruction at offset off if the
836 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 already been set. If it has been set, the call has no effect.
838
Christian Heimes2202f872008-02-06 14:31:34 +0000839 The line number is reset in the following cases:
840 - when entering a new scope
841 - on each statement
842 - on each expression that start a new line
843 - before the "except" clause
844 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000845*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847static void
848compiler_set_lineno(struct compiler *c, int off)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 basicblock *b;
851 if (c->u->u_lineno_set)
852 return;
853 c->u->u_lineno_set = 1;
854 b = c->u->u_curblock;
855 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856}
857
Larry Hastings3a907972013-11-23 14:49:22 -0800858int
859PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 switch (opcode) {
862 case POP_TOP:
863 return -1;
864 case ROT_TWO:
865 case ROT_THREE:
866 return 0;
867 case DUP_TOP:
868 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000869 case DUP_TOP_TWO:
870 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case UNARY_POSITIVE:
873 case UNARY_NEGATIVE:
874 case UNARY_NOT:
875 case UNARY_INVERT:
876 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case SET_ADD:
879 case LIST_APPEND:
880 return -1;
881 case MAP_ADD:
882 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 case BINARY_POWER:
885 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400886 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 case BINARY_MODULO:
888 case BINARY_ADD:
889 case BINARY_SUBTRACT:
890 case BINARY_SUBSCR:
891 case BINARY_FLOOR_DIVIDE:
892 case BINARY_TRUE_DIVIDE:
893 return -1;
894 case INPLACE_FLOOR_DIVIDE:
895 case INPLACE_TRUE_DIVIDE:
896 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case INPLACE_ADD:
899 case INPLACE_SUBTRACT:
900 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400901 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case INPLACE_MODULO:
903 return -1;
904 case STORE_SUBSCR:
905 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case DELETE_SUBSCR:
907 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 case BINARY_LSHIFT:
910 case BINARY_RSHIFT:
911 case BINARY_AND:
912 case BINARY_XOR:
913 case BINARY_OR:
914 return -1;
915 case INPLACE_POWER:
916 return -1;
917 case GET_ITER:
918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case PRINT_EXPR:
921 return -1;
922 case LOAD_BUILD_CLASS:
923 return 1;
924 case INPLACE_LSHIFT:
925 case INPLACE_RSHIFT:
926 case INPLACE_AND:
927 case INPLACE_XOR:
928 case INPLACE_OR:
929 return -1;
930 case BREAK_LOOP:
931 return 0;
932 case SETUP_WITH:
933 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400934 case WITH_CLEANUP_START:
935 return 1;
936 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case RETURN_VALUE:
939 return -1;
940 case IMPORT_STAR:
941 return -1;
942 case YIELD_VALUE:
943 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500944 case YIELD_FROM:
945 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case POP_BLOCK:
947 return 0;
948 case POP_EXCEPT:
949 return 0; /* -3 except if bad bytecode */
950 case END_FINALLY:
951 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case STORE_NAME:
954 return -1;
955 case DELETE_NAME:
956 return 0;
957 case UNPACK_SEQUENCE:
958 return oparg-1;
959 case UNPACK_EX:
960 return (oparg&0xFF) + (oparg>>8);
961 case FOR_ITER:
962 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case STORE_ATTR:
965 return -2;
966 case DELETE_ATTR:
967 return -1;
968 case STORE_GLOBAL:
969 return -1;
970 case DELETE_GLOBAL:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case LOAD_CONST:
973 return 1;
974 case LOAD_NAME:
975 return 1;
976 case BUILD_TUPLE:
977 case BUILD_LIST:
978 case BUILD_SET:
979 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400980 case BUILD_LIST_UNPACK:
981 case BUILD_TUPLE_UNPACK:
982 case BUILD_SET_UNPACK:
983 case BUILD_MAP_UNPACK:
984 return 1 - oparg;
985 case BUILD_MAP_UNPACK_WITH_CALL:
986 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700988 return 1 - 2*oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case LOAD_ATTR:
990 return 0;
991 case COMPARE_OP:
992 return -1;
993 case IMPORT_NAME:
994 return -1;
995 case IMPORT_FROM:
996 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case JUMP_FORWARD:
999 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1000 case JUMP_IF_FALSE_OR_POP: /* "" */
1001 case JUMP_ABSOLUTE:
1002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case POP_JUMP_IF_FALSE:
1005 case POP_JUMP_IF_TRUE:
1006 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case LOAD_GLOBAL:
1009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case CONTINUE_LOOP:
1012 return 0;
1013 case SETUP_LOOP:
1014 return 0;
1015 case SETUP_EXCEPT:
1016 case SETUP_FINALLY:
1017 return 6; /* can push 3 values for the new exception
1018 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_FAST:
1021 return 1;
1022 case STORE_FAST:
1023 return -1;
1024 case DELETE_FAST:
1025 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case RAISE_VARARGS:
1028 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001029#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case CALL_FUNCTION:
1031 return -NARGS(oparg);
1032 case CALL_FUNCTION_VAR:
1033 case CALL_FUNCTION_KW:
1034 return -NARGS(oparg)-1;
1035 case CALL_FUNCTION_VAR_KW:
1036 return -NARGS(oparg)-2;
1037 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001038 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001040 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001041#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case BUILD_SLICE:
1043 if (oparg == 3)
1044 return -2;
1045 else
1046 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 case LOAD_CLOSURE:
1049 return 1;
1050 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001051 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 return 1;
1053 case STORE_DEREF:
1054 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001055 case DELETE_DEREF:
1056 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001057 case GET_AWAITABLE:
1058 return 0;
1059 case SETUP_ASYNC_WITH:
1060 return 6;
1061 case BEFORE_ASYNC_WITH:
1062 return 1;
1063 case GET_AITER:
1064 return 0;
1065 case GET_ANEXT:
1066 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001067 case GET_YIELD_FROM_ITER:
1068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001070 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
Larry Hastings3a907972013-11-23 14:49:22 -08001072 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
1075/* Add an opcode with no argument.
1076 Returns 0 on failure, 1 on success.
1077*/
1078
1079static int
1080compiler_addop(struct compiler *c, int opcode)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 basicblock *b;
1083 struct instr *i;
1084 int off;
1085 off = compiler_next_instr(c, c->u->u_curblock);
1086 if (off < 0)
1087 return 0;
1088 b = c->u->u_curblock;
1089 i = &b->b_instr[off];
1090 i->i_opcode = opcode;
1091 i->i_hasarg = 0;
1092 if (opcode == RETURN_VALUE)
1093 b->b_return = 1;
1094 compiler_set_lineno(c, off);
1095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096}
1097
Victor Stinnerf8e32212013-11-19 23:56:34 +01001098static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *t, *v;
1102 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Victor Stinner3cdd5fb2016-01-22 12:33:12 +01001104 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (t == NULL)
1106 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 v = PyDict_GetItem(dict, t);
1109 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001110 if (PyErr_Occurred()) {
1111 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001115 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!v) {
1117 Py_DECREF(t);
1118 return -1;
1119 }
1120 if (PyDict_SetItem(dict, t, v) < 0) {
1121 Py_DECREF(t);
1122 Py_DECREF(v);
1123 return -1;
1124 }
1125 Py_DECREF(v);
1126 }
1127 else
1128 arg = PyLong_AsLong(v);
1129 Py_DECREF(t);
1130 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131}
1132
1133static int
1134compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001137 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001139 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return compiler_addop_i(c, opcode, arg);
1141}
1142
1143static int
1144compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001147 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1149 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001150 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 arg = compiler_add_o(c, dict, mangled);
1152 Py_DECREF(mangled);
1153 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001154 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 return compiler_addop_i(c, opcode, arg);
1156}
1157
1158/* Add an opcode with an integer argument.
1159 Returns 0 on failure, 1 on success.
1160*/
1161
1162static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001163compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 struct instr *i;
1166 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001167
1168 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1169 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001170 assert((-2147483647-1) <= oparg);
1171 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 off = compiler_next_instr(c, c->u->u_curblock);
1174 if (off < 0)
1175 return 0;
1176 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177 i->i_opcode = opcode;
1178 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 i->i_hasarg = 1;
1180 compiler_set_lineno(c, off);
1181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182}
1183
1184static int
1185compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 struct instr *i;
1188 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 assert(b != NULL);
1191 off = compiler_next_instr(c, c->u->u_curblock);
1192 if (off < 0)
1193 return 0;
1194 i = &c->u->u_curblock->b_instr[off];
1195 i->i_opcode = opcode;
1196 i->i_target = b;
1197 i->i_hasarg = 1;
1198 if (absolute)
1199 i->i_jabs = 1;
1200 else
1201 i->i_jrel = 1;
1202 compiler_set_lineno(c, off);
1203 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204}
1205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1207 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 it as the current block. NEXT_BLOCK() also creates an implicit jump
1209 from the current block to the new block.
1210*/
1211
Thomas Wouters89f507f2006-12-13 04:49:30 +00001212/* The returns inside these macros make it impossible to decref objects
1213 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214*/
1215
1216
1217#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 if (compiler_use_new_block((C)) == NULL) \
1219 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220}
1221
1222#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (compiler_next_block((C)) == NULL) \
1224 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
1227#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!compiler_addop((C), (OP))) \
1229 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230}
1231
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001232#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (!compiler_addop((C), (OP))) { \
1234 compiler_exit_scope(c); \
1235 return 0; \
1236 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001237}
1238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1241 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242}
1243
1244#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1246 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247}
1248
1249#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (!compiler_addop_i((C), (OP), (O))) \
1251 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (!compiler_addop_j((C), (OP), (O), 1)) \
1256 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (!compiler_addop_j((C), (OP), (O), 0)) \
1261 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262}
1263
1264/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1265 the ASDL name to synthesize the name of the C type and the visit function.
1266*/
1267
1268#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!compiler_visit_ ## TYPE((C), (V))) \
1270 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001273#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!compiler_visit_ ## TYPE((C), (V))) { \
1275 compiler_exit_scope(c); \
1276 return 0; \
1277 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001278}
1279
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (!compiler_visit_slice((C), (V), (CTX))) \
1282 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283}
1284
1285#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 int _i; \
1287 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1288 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1289 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1290 if (!compiler_visit_ ## TYPE((C), elt)) \
1291 return 0; \
1292 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293}
1294
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001295#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 int _i; \
1297 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1298 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1299 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1300 if (!compiler_visit_ ## TYPE((C), elt)) { \
1301 compiler_exit_scope(c); \
1302 return 0; \
1303 } \
1304 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001305}
1306
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307static int
1308compiler_isdocstring(stmt_ty s)
1309{
1310 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 return s->v.Expr.value->kind == Str_kind;
1313}
1314
1315/* Compile a sequence of statements, checking for a docstring. */
1316
1317static int
1318compiler_body(struct compiler *c, asdl_seq *stmts)
1319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 int i = 0;
1321 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (!asdl_seq_LEN(stmts))
1324 return 1;
1325 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001326 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 /* don't generate docstrings if -OO */
1328 i = 1;
1329 VISIT(c, expr, st->v.Expr.value);
1330 if (!compiler_nameop(c, __doc__, Store))
1331 return 0;
1332 }
1333 for (; i < asdl_seq_LEN(stmts); i++)
1334 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1335 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336}
1337
1338static PyCodeObject *
1339compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 PyCodeObject *co;
1342 int addNone = 1;
1343 static PyObject *module;
1344 if (!module) {
1345 module = PyUnicode_InternFromString("<module>");
1346 if (!module)
1347 return NULL;
1348 }
1349 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001350 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 return NULL;
1352 switch (mod->kind) {
1353 case Module_kind:
1354 if (!compiler_body(c, mod->v.Module.body)) {
1355 compiler_exit_scope(c);
1356 return 0;
1357 }
1358 break;
1359 case Interactive_kind:
1360 c->c_interactive = 1;
1361 VISIT_SEQ_IN_SCOPE(c, stmt,
1362 mod->v.Interactive.body);
1363 break;
1364 case Expression_kind:
1365 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1366 addNone = 0;
1367 break;
1368 case Suite_kind:
1369 PyErr_SetString(PyExc_SystemError,
1370 "suite should not be possible");
1371 return 0;
1372 default:
1373 PyErr_Format(PyExc_SystemError,
1374 "module kind %d should not be possible",
1375 mod->kind);
1376 return 0;
1377 }
1378 co = assemble(c, addNone);
1379 compiler_exit_scope(c);
1380 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001381}
1382
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383/* The test for LOCAL must come before the test for FREE in order to
1384 handle classes where name is both local and free. The local var is
1385 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001386*/
1387
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388static int
1389get_ref_type(struct compiler *c, PyObject *name)
1390{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001391 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001392 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1393 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1394 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001395 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (scope == 0) {
1397 char buf[350];
1398 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001399 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001401 PyUnicode_AsUTF8(name),
1402 PyUnicode_AsUTF8(c->u->u_name),
1403 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1404 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1405 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1406 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 );
1408 Py_FatalError(buf);
1409 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412}
1413
1414static int
1415compiler_lookup_arg(PyObject *dict, PyObject *name)
1416{
1417 PyObject *k, *v;
Victor Stinner3cdd5fb2016-01-22 12:33:12 +01001418 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001420 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001422 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001424 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001425 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426}
1427
1428static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001429compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001431 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001432 if (qualname == NULL)
1433 qualname = co->co_name;
1434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (free == 0) {
1436 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001437 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 ADDOP_I(c, MAKE_FUNCTION, args);
1439 return 1;
1440 }
1441 for (i = 0; i < free; ++i) {
1442 /* Bypass com_addop_varname because it will generate
1443 LOAD_DEREF but LOAD_CLOSURE is needed.
1444 */
1445 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1446 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 /* Special case: If a class contains a method with a
1449 free variable that has the same name as a method,
1450 the name will be considered free *and* local in the
1451 class. It should be handled by the closure, as
1452 well as by the normal name loookup logic.
1453 */
1454 reftype = get_ref_type(c, name);
1455 if (reftype == CELL)
1456 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1457 else /* (reftype == FREE) */
1458 arg = compiler_lookup_arg(c->u->u_freevars, name);
1459 if (arg == -1) {
1460 fprintf(stderr,
1461 "lookup %s in %s %d %d\n"
1462 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001463 PyUnicode_AsUTF8(PyObject_Repr(name)),
1464 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001466 PyUnicode_AsUTF8(co->co_name),
1467 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 Py_FatalError("compiler_make_closure()");
1469 }
1470 ADDOP_I(c, LOAD_CLOSURE, arg);
1471 }
1472 ADDOP_I(c, BUILD_TUPLE, free);
1473 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001474 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 ADDOP_I(c, MAKE_CLOSURE, args);
1476 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477}
1478
1479static int
1480compiler_decorators(struct compiler *c, asdl_seq* decos)
1481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (!decos)
1485 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1488 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1489 }
1490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491}
1492
1493static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001494compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 int i, default_count = 0;
1498 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1499 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1500 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1501 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001502 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1503 if (!mangled)
1504 return -1;
1505 ADDOP_O(c, LOAD_CONST, mangled, consts);
1506 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (!compiler_visit_expr(c, default_)) {
1508 return -1;
1509 }
1510 default_count++;
1511 }
1512 }
1513 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001514}
1515
1516static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001517compiler_visit_argannotation(struct compiler *c, identifier id,
1518 expr_ty annotation, PyObject *names)
1519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001521 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001523 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001524 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001525 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001526 if (PyList_Append(names, mangled) < 0) {
1527 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001528 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001529 }
1530 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001532 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001533}
1534
1535static int
1536compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1537 PyObject *names)
1538{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001539 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 for (i = 0; i < asdl_seq_LEN(args); i++) {
1541 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001542 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 c,
1544 arg->arg,
1545 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001546 names))
1547 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001549 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001550}
1551
1552static int
1553compiler_visit_annotations(struct compiler *c, arguments_ty args,
1554 expr_ty returns)
1555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 /* Push arg annotations and a list of the argument names. Return the #
1557 of items pushed. The expressions are evaluated out-of-order wrt the
1558 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1561 */
1562 static identifier return_str;
1563 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001564 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 names = PyList_New(0);
1566 if (!names)
1567 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001568
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001569 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001571 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001572 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001573 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001575 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001577 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001578 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001579 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (!return_str) {
1583 return_str = PyUnicode_InternFromString("return");
1584 if (!return_str)
1585 goto error;
1586 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001587 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 goto error;
1589 }
1590
1591 len = PyList_GET_SIZE(names);
1592 if (len > 65534) {
1593 /* len must fit in 16 bits, and len is incremented below */
1594 PyErr_SetString(PyExc_SyntaxError,
1595 "too many annotations");
1596 goto error;
1597 }
1598 if (len) {
1599 /* convert names to a tuple and place on stack */
1600 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001601 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 PyObject *s = PyTuple_New(len);
1603 if (!s)
1604 goto error;
1605 for (i = 0; i < len; i++) {
1606 elt = PyList_GET_ITEM(names, i);
1607 Py_INCREF(elt);
1608 PyTuple_SET_ITEM(s, i, elt);
1609 }
1610 ADDOP_O(c, LOAD_CONST, s, consts);
1611 Py_DECREF(s);
1612 len++; /* include the just-pushed tuple */
1613 }
1614 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001615
1616 /* We just checked that len <= 65535, see above */
1617 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001618
1619error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 Py_DECREF(names);
1621 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001622}
1623
1624static int
Yury Selivanov75445082015-05-11 22:57:16 -04001625compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001628 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001629 arguments_ty args;
1630 expr_ty returns;
1631 identifier name;
1632 asdl_seq* decos;
1633 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001635 Py_ssize_t i, n, arglength;
1636 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001638 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639
Yury Selivanov75445082015-05-11 22:57:16 -04001640
1641 if (is_async) {
1642 assert(s->kind == AsyncFunctionDef_kind);
1643
1644 args = s->v.AsyncFunctionDef.args;
1645 returns = s->v.AsyncFunctionDef.returns;
1646 decos = s->v.AsyncFunctionDef.decorator_list;
1647 name = s->v.AsyncFunctionDef.name;
1648 body = s->v.AsyncFunctionDef.body;
1649
1650 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1651 } else {
1652 assert(s->kind == FunctionDef_kind);
1653
1654 args = s->v.FunctionDef.args;
1655 returns = s->v.FunctionDef.returns;
1656 decos = s->v.FunctionDef.decorator_list;
1657 name = s->v.FunctionDef.name;
1658 body = s->v.FunctionDef.body;
1659
1660 scope_type = COMPILER_SCOPE_FUNCTION;
1661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (!compiler_decorators(c, decos))
1664 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001665 if (args->defaults)
1666 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (args->kwonlyargs) {
1668 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1669 args->kw_defaults);
1670 if (res < 0)
1671 return 0;
1672 kw_default_count = res;
1673 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 num_annotations = compiler_visit_annotations(c, args, returns);
1675 if (num_annotations < 0)
1676 return 0;
1677 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001678
Yury Selivanov75445082015-05-11 22:57:16 -04001679 if (!compiler_enter_scope(c, name,
1680 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 s->lineno))
1682 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683
Yury Selivanov75445082015-05-11 22:57:16 -04001684 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001686 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 first_const = st->v.Expr.value->v.Str.s;
1688 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1689 compiler_exit_scope(c);
1690 return 0;
1691 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 c->u->u_argcount = asdl_seq_LEN(args->args);
1694 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001695 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* if there was a docstring, we need to skip the first statement */
1697 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001698 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 VISIT_IN_SCOPE(c, stmt, st);
1700 }
1701 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001702 qualname = c->u->u_qualname;
1703 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001705 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001706 Py_XDECREF(qualname);
1707 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001709 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 arglength = asdl_seq_LEN(args->defaults);
1712 arglength |= kw_default_count << 8;
1713 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001714 if (is_async)
1715 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001716 compiler_make_closure(c, co, arglength, qualname);
1717 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 /* decorators */
1721 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1722 ADDOP_I(c, CALL_FUNCTION, 1);
1723 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724
Yury Selivanov75445082015-05-11 22:57:16 -04001725 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726}
1727
1728static int
1729compiler_class(struct compiler *c, stmt_ty s)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyCodeObject *co;
1732 PyObject *str;
1733 int i;
1734 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (!compiler_decorators(c, decos))
1737 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* ultimately generate code for:
1740 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1741 where:
1742 <func> is a function/closure created from the class body;
1743 it has a single argument (__locals__) where the dict
1744 (or MutableSequence) representing the locals is passed
1745 <name> is the class name
1746 <bases> is the positional arguments and *varargs argument
1747 <keywords> is the keyword arguments and **kwds argument
1748 This borrows from compiler_call.
1749 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001752 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1753 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 return 0;
1755 /* this block represents what we do in the new scope */
1756 {
1757 /* use the class name for name mangling */
1758 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001759 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 /* load (global) __name__ ... */
1761 str = PyUnicode_InternFromString("__name__");
1762 if (!str || !compiler_nameop(c, str, Load)) {
1763 Py_XDECREF(str);
1764 compiler_exit_scope(c);
1765 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 Py_DECREF(str);
1768 /* ... and store it as __module__ */
1769 str = PyUnicode_InternFromString("__module__");
1770 if (!str || !compiler_nameop(c, str, Store)) {
1771 Py_XDECREF(str);
1772 compiler_exit_scope(c);
1773 return 0;
1774 }
1775 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001776 assert(c->u->u_qualname);
1777 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001778 str = PyUnicode_InternFromString("__qualname__");
1779 if (!str || !compiler_nameop(c, str, Store)) {
1780 Py_XDECREF(str);
1781 compiler_exit_scope(c);
1782 return 0;
1783 }
1784 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* compile the body proper */
1786 if (!compiler_body(c, s->v.ClassDef.body)) {
1787 compiler_exit_scope(c);
1788 return 0;
1789 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001790 if (c->u->u_ste->ste_needs_class_closure) {
1791 /* return the (empty) __class__ cell */
1792 str = PyUnicode_InternFromString("__class__");
1793 if (str == NULL) {
1794 compiler_exit_scope(c);
1795 return 0;
1796 }
1797 i = compiler_lookup_arg(c->u->u_cellvars, str);
1798 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001799 if (i < 0) {
1800 compiler_exit_scope(c);
1801 return 0;
1802 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001803 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Return the cell where to store __class__ */
1805 ADDOP_I(c, LOAD_CLOSURE, i);
1806 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001807 else {
1808 assert(PyDict_Size(c->u->u_cellvars) == 0);
1809 /* This happens when nobody references the cell. Return None. */
1810 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1813 /* create the code object */
1814 co = assemble(c, 1);
1815 }
1816 /* leave the new scope */
1817 compiler_exit_scope(c);
1818 if (co == NULL)
1819 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 /* 2. load the 'build_class' function */
1822 ADDOP(c, LOAD_BUILD_CLASS);
1823
1824 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001825 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 Py_DECREF(co);
1827
1828 /* 4. load class name */
1829 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1830
1831 /* 5. generate the rest of the code for the call */
1832 if (!compiler_call_helper(c, 2,
1833 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001834 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return 0;
1836
1837 /* 6. apply decorators */
1838 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1839 ADDOP_I(c, CALL_FUNCTION, 1);
1840 }
1841
1842 /* 7. store into <name> */
1843 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1844 return 0;
1845 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846}
1847
1848static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001849compiler_ifexp(struct compiler *c, expr_ty e)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 basicblock *end, *next;
1852
1853 assert(e->kind == IfExp_kind);
1854 end = compiler_new_block(c);
1855 if (end == NULL)
1856 return 0;
1857 next = compiler_new_block(c);
1858 if (next == NULL)
1859 return 0;
1860 VISIT(c, expr, e->v.IfExp.test);
1861 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1862 VISIT(c, expr, e->v.IfExp.body);
1863 ADDOP_JREL(c, JUMP_FORWARD, end);
1864 compiler_use_next_block(c, next);
1865 VISIT(c, expr, e->v.IfExp.orelse);
1866 compiler_use_next_block(c, end);
1867 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001868}
1869
1870static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871compiler_lambda(struct compiler *c, expr_ty e)
1872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001874 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001876 int kw_default_count = 0;
1877 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 arguments_ty args = e->v.Lambda.args;
1879 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (!name) {
1882 name = PyUnicode_InternFromString("<lambda>");
1883 if (!name)
1884 return 0;
1885 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001887 if (args->defaults)
1888 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (args->kwonlyargs) {
1890 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1891 args->kw_defaults);
1892 if (res < 0) return 0;
1893 kw_default_count = res;
1894 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001895 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001896 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Make None the first constant, so the lambda can't have a
1900 docstring. */
1901 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 c->u->u_argcount = asdl_seq_LEN(args->args);
1905 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1906 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1907 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001908 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
1910 else {
1911 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001912 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001914 qualname = c->u->u_qualname;
1915 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001917 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 arglength = asdl_seq_LEN(args->defaults);
1921 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001922 compiler_make_closure(c, co, arglength, qualname);
1923 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 Py_DECREF(co);
1925
1926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927}
1928
1929static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930compiler_if(struct compiler *c, stmt_ty s)
1931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 basicblock *end, *next;
1933 int constant;
1934 assert(s->kind == If_kind);
1935 end = compiler_new_block(c);
1936 if (end == NULL)
1937 return 0;
1938
Georg Brandl8334fd92010-12-04 10:26:46 +00001939 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* constant = 0: "if 0"
1941 * constant = 1: "if 1", "if 2", ...
1942 * constant = -1: rest */
1943 if (constant == 0) {
1944 if (s->v.If.orelse)
1945 VISIT_SEQ(c, stmt, s->v.If.orelse);
1946 } else if (constant == 1) {
1947 VISIT_SEQ(c, stmt, s->v.If.body);
1948 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001949 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 next = compiler_new_block(c);
1951 if (next == NULL)
1952 return 0;
1953 }
1954 else
1955 next = end;
1956 VISIT(c, expr, s->v.If.test);
1957 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1958 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001959 if (asdl_seq_LEN(s->v.If.orelse)) {
1960 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 compiler_use_next_block(c, next);
1962 VISIT_SEQ(c, stmt, s->v.If.orelse);
1963 }
1964 }
1965 compiler_use_next_block(c, end);
1966 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967}
1968
1969static int
1970compiler_for(struct compiler *c, stmt_ty s)
1971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 start = compiler_new_block(c);
1975 cleanup = compiler_new_block(c);
1976 end = compiler_new_block(c);
1977 if (start == NULL || end == NULL || cleanup == NULL)
1978 return 0;
1979 ADDOP_JREL(c, SETUP_LOOP, end);
1980 if (!compiler_push_fblock(c, LOOP, start))
1981 return 0;
1982 VISIT(c, expr, s->v.For.iter);
1983 ADDOP(c, GET_ITER);
1984 compiler_use_next_block(c, start);
1985 ADDOP_JREL(c, FOR_ITER, cleanup);
1986 VISIT(c, expr, s->v.For.target);
1987 VISIT_SEQ(c, stmt, s->v.For.body);
1988 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1989 compiler_use_next_block(c, cleanup);
1990 ADDOP(c, POP_BLOCK);
1991 compiler_pop_fblock(c, LOOP, start);
1992 VISIT_SEQ(c, stmt, s->v.For.orelse);
1993 compiler_use_next_block(c, end);
1994 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995}
1996
Yury Selivanov75445082015-05-11 22:57:16 -04001997
1998static int
1999compiler_async_for(struct compiler *c, stmt_ty s)
2000{
2001 static PyObject *stopiter_error = NULL;
2002 basicblock *try, *except, *end, *after_try, *try_cleanup,
2003 *after_loop, *after_loop_else;
2004
2005 if (stopiter_error == NULL) {
2006 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2007 if (stopiter_error == NULL)
2008 return 0;
2009 }
2010
2011 try = compiler_new_block(c);
2012 except = compiler_new_block(c);
2013 end = compiler_new_block(c);
2014 after_try = compiler_new_block(c);
2015 try_cleanup = compiler_new_block(c);
2016 after_loop = compiler_new_block(c);
2017 after_loop_else = compiler_new_block(c);
2018
2019 if (try == NULL || except == NULL || end == NULL
2020 || after_try == NULL || try_cleanup == NULL)
2021 return 0;
2022
2023 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2024 if (!compiler_push_fblock(c, LOOP, try))
2025 return 0;
2026
2027 VISIT(c, expr, s->v.AsyncFor.iter);
2028 ADDOP(c, GET_AITER);
2029 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2030 ADDOP(c, YIELD_FROM);
2031
2032 compiler_use_next_block(c, try);
2033
2034
2035 ADDOP_JREL(c, SETUP_EXCEPT, except);
2036 if (!compiler_push_fblock(c, EXCEPT, try))
2037 return 0;
2038
2039 ADDOP(c, GET_ANEXT);
2040 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2041 ADDOP(c, YIELD_FROM);
2042 VISIT(c, expr, s->v.AsyncFor.target);
2043 ADDOP(c, POP_BLOCK);
2044 compiler_pop_fblock(c, EXCEPT, try);
2045 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2046
2047
2048 compiler_use_next_block(c, except);
2049 ADDOP(c, DUP_TOP);
2050 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2051 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2052 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2053
2054 ADDOP(c, POP_TOP);
2055 ADDOP(c, POP_TOP);
2056 ADDOP(c, POP_TOP);
2057 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2058 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2059 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2060
2061
2062 compiler_use_next_block(c, try_cleanup);
2063 ADDOP(c, END_FINALLY);
2064
2065 compiler_use_next_block(c, after_try);
2066 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2067 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2068
2069 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2070 compiler_pop_fblock(c, LOOP, try);
2071
2072 compiler_use_next_block(c, after_loop);
2073 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2074
2075 compiler_use_next_block(c, after_loop_else);
2076 VISIT_SEQ(c, stmt, s->v.For.orelse);
2077
2078 compiler_use_next_block(c, end);
2079
2080 return 1;
2081}
2082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083static int
2084compiler_while(struct compiler *c, stmt_ty s)
2085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002087 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (constant == 0) {
2090 if (s->v.While.orelse)
2091 VISIT_SEQ(c, stmt, s->v.While.orelse);
2092 return 1;
2093 }
2094 loop = compiler_new_block(c);
2095 end = compiler_new_block(c);
2096 if (constant == -1) {
2097 anchor = compiler_new_block(c);
2098 if (anchor == NULL)
2099 return 0;
2100 }
2101 if (loop == NULL || end == NULL)
2102 return 0;
2103 if (s->v.While.orelse) {
2104 orelse = compiler_new_block(c);
2105 if (orelse == NULL)
2106 return 0;
2107 }
2108 else
2109 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 ADDOP_JREL(c, SETUP_LOOP, end);
2112 compiler_use_next_block(c, loop);
2113 if (!compiler_push_fblock(c, LOOP, loop))
2114 return 0;
2115 if (constant == -1) {
2116 VISIT(c, expr, s->v.While.test);
2117 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2118 }
2119 VISIT_SEQ(c, stmt, s->v.While.body);
2120 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 /* XXX should the two POP instructions be in a separate block
2123 if there is no else clause ?
2124 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002126 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002128 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 compiler_pop_fblock(c, LOOP, loop);
2130 if (orelse != NULL) /* what if orelse is just pass? */
2131 VISIT_SEQ(c, stmt, s->v.While.orelse);
2132 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135}
2136
2137static int
2138compiler_continue(struct compiler *c)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2141 static const char IN_FINALLY_ERROR_MSG[] =
2142 "'continue' not supported inside 'finally' clause";
2143 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (!c->u->u_nfblocks)
2146 return compiler_error(c, LOOP_ERROR_MSG);
2147 i = c->u->u_nfblocks - 1;
2148 switch (c->u->u_fblock[i].fb_type) {
2149 case LOOP:
2150 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2151 break;
2152 case EXCEPT:
2153 case FINALLY_TRY:
2154 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2155 /* Prevent continue anywhere under a finally
2156 even if hidden in a sub-try or except. */
2157 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2158 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2159 }
2160 if (i == -1)
2161 return compiler_error(c, LOOP_ERROR_MSG);
2162 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2163 break;
2164 case FINALLY_END:
2165 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169}
2170
2171/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172
2173 SETUP_FINALLY L
2174 <code for body>
2175 POP_BLOCK
2176 LOAD_CONST <None>
2177 L: <code for finalbody>
2178 END_FINALLY
2179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 The special instructions use the block stack. Each block
2181 stack entry contains the instruction that created it (here
2182 SETUP_FINALLY), the level of the value stack at the time the
2183 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 Pushes the current value stack level and the label
2187 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 Pops en entry from the block stack, and pops the value
2190 stack until its level is the same as indicated on the
2191 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 Pops a variable number of entries from the *value* stack
2194 and re-raises the exception they specify. The number of
2195 entries popped depends on the (pseudo) exception type.
2196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 The block stack is unwound when an exception is raised:
2198 when a SETUP_FINALLY entry is found, the exception is pushed
2199 onto the value stack (and the exception condition is cleared),
2200 and the interpreter jumps to the label gotten from the block
2201 stack.
2202*/
2203
2204static int
2205compiler_try_finally(struct compiler *c, stmt_ty s)
2206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 basicblock *body, *end;
2208 body = compiler_new_block(c);
2209 end = compiler_new_block(c);
2210 if (body == NULL || end == NULL)
2211 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 ADDOP_JREL(c, SETUP_FINALLY, end);
2214 compiler_use_next_block(c, body);
2215 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2216 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002217 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2218 if (!compiler_try_except(c, s))
2219 return 0;
2220 }
2221 else {
2222 VISIT_SEQ(c, stmt, s->v.Try.body);
2223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 ADDOP(c, POP_BLOCK);
2225 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2228 compiler_use_next_block(c, end);
2229 if (!compiler_push_fblock(c, FINALLY_END, end))
2230 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002231 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 ADDOP(c, END_FINALLY);
2233 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236}
2237
2238/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002239 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 (The contents of the value stack is shown in [], with the top
2241 at the right; 'tb' is trace-back info, 'val' the exception's
2242 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243
2244 Value stack Label Instruction Argument
2245 [] SETUP_EXCEPT L1
2246 [] <code for S>
2247 [] POP_BLOCK
2248 [] JUMP_FORWARD L0
2249
2250 [tb, val, exc] L1: DUP )
2251 [tb, val, exc, exc] <evaluate E1> )
2252 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2253 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2254 [tb, val, exc] POP
2255 [tb, val] <assign to V1> (or POP if no V1)
2256 [tb] POP
2257 [] <code for S1>
2258 JUMP_FORWARD L0
2259
2260 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 .............................etc.......................
2262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2264
2265 [] L0: <next statement>
2266
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 Of course, parts are not generated if Vi or Ei is not present.
2268*/
2269static int
2270compiler_try_except(struct compiler *c, stmt_ty s)
2271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002273 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 body = compiler_new_block(c);
2276 except = compiler_new_block(c);
2277 orelse = compiler_new_block(c);
2278 end = compiler_new_block(c);
2279 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2280 return 0;
2281 ADDOP_JREL(c, SETUP_EXCEPT, except);
2282 compiler_use_next_block(c, body);
2283 if (!compiler_push_fblock(c, EXCEPT, body))
2284 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002285 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 ADDOP(c, POP_BLOCK);
2287 compiler_pop_fblock(c, EXCEPT, body);
2288 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002289 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_use_next_block(c, except);
2291 for (i = 0; i < n; i++) {
2292 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002293 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (!handler->v.ExceptHandler.type && i < n-1)
2295 return compiler_error(c, "default 'except:' must be last");
2296 c->u->u_lineno_set = 0;
2297 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002298 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 except = compiler_new_block(c);
2300 if (except == NULL)
2301 return 0;
2302 if (handler->v.ExceptHandler.type) {
2303 ADDOP(c, DUP_TOP);
2304 VISIT(c, expr, handler->v.ExceptHandler.type);
2305 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2306 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2307 }
2308 ADDOP(c, POP_TOP);
2309 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002310 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002311
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002312 cleanup_end = compiler_new_block(c);
2313 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002314 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002315 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002316
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002317 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2318 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002320 /*
2321 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002322 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002323 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002324 try:
2325 # body
2326 finally:
2327 name = None
2328 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002329 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002331 /* second try: */
2332 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2333 compiler_use_next_block(c, cleanup_body);
2334 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2335 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002337 /* second # body */
2338 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2339 ADDOP(c, POP_BLOCK);
2340 ADDOP(c, POP_EXCEPT);
2341 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002343 /* finally: */
2344 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2345 compiler_use_next_block(c, cleanup_end);
2346 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2347 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002349 /* name = None */
2350 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2351 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002353 /* del name */
2354 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002356 ADDOP(c, END_FINALLY);
2357 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 }
2359 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002360 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002362 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002363 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002364 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365
Guido van Rossumb940e112007-01-10 16:19:56 +00002366 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002367 ADDOP(c, POP_TOP);
2368 compiler_use_next_block(c, cleanup_body);
2369 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2370 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002372 ADDOP(c, POP_EXCEPT);
2373 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 }
2375 ADDOP_JREL(c, JUMP_FORWARD, end);
2376 compiler_use_next_block(c, except);
2377 }
2378 ADDOP(c, END_FINALLY);
2379 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002380 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 compiler_use_next_block(c, end);
2382 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383}
2384
2385static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002386compiler_try(struct compiler *c, stmt_ty s) {
2387 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2388 return compiler_try_finally(c, s);
2389 else
2390 return compiler_try_except(c, s);
2391}
2392
2393
2394static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395compiler_import_as(struct compiler *c, identifier name, identifier asname)
2396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* The IMPORT_NAME opcode was already generated. This function
2398 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 If there is a dot in name, we need to split it and emit a
2401 LOAD_ATTR for each name.
2402 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2404 PyUnicode_GET_LENGTH(name), 1);
2405 if (dot == -2)
2406 return -1;
2407 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002409 Py_ssize_t pos = dot + 1;
2410 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 dot = PyUnicode_FindChar(name, '.', pos,
2413 PyUnicode_GET_LENGTH(name), 1);
2414 if (dot == -2)
2415 return -1;
2416 attr = PyUnicode_Substring(name, pos,
2417 (dot != -1) ? dot :
2418 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (!attr)
2420 return -1;
2421 ADDOP_O(c, LOAD_ATTR, attr, names);
2422 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002423 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 }
2425 }
2426 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427}
2428
2429static int
2430compiler_import(struct compiler *c, stmt_ty s)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 /* The Import node stores a module name like a.b.c as a single
2433 string. This is convenient for all cases except
2434 import a.b.c as d
2435 where we need to parse that string to extract the individual
2436 module names.
2437 XXX Perhaps change the representation to make this case simpler?
2438 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002439 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 for (i = 0; i < n; i++) {
2442 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2443 int r;
2444 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 level = PyLong_FromLong(0);
2447 if (level == NULL)
2448 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 ADDOP_O(c, LOAD_CONST, level, consts);
2451 Py_DECREF(level);
2452 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2453 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (alias->asname) {
2456 r = compiler_import_as(c, alias->name, alias->asname);
2457 if (!r)
2458 return r;
2459 }
2460 else {
2461 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 Py_ssize_t dot = PyUnicode_FindChar(
2463 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002464 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002465 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002466 if (tmp == NULL)
2467 return 0;
2468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 Py_DECREF(tmp);
2472 }
2473 if (!r)
2474 return r;
2475 }
2476 }
2477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478}
2479
2480static int
2481compiler_from_import(struct compiler *c, stmt_ty s)
2482{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002483 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 PyObject *names = PyTuple_New(n);
2486 PyObject *level;
2487 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (!empty_string) {
2490 empty_string = PyUnicode_FromString("");
2491 if (!empty_string)
2492 return 0;
2493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (!names)
2496 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 level = PyLong_FromLong(s->v.ImportFrom.level);
2499 if (!level) {
2500 Py_DECREF(names);
2501 return 0;
2502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* build up the names */
2505 for (i = 0; i < n; i++) {
2506 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2507 Py_INCREF(alias->name);
2508 PyTuple_SET_ITEM(names, i, alias->name);
2509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2512 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2513 Py_DECREF(level);
2514 Py_DECREF(names);
2515 return compiler_error(c, "from __future__ imports must occur "
2516 "at the beginning of the file");
2517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 ADDOP_O(c, LOAD_CONST, level, consts);
2520 Py_DECREF(level);
2521 ADDOP_O(c, LOAD_CONST, names, consts);
2522 Py_DECREF(names);
2523 if (s->v.ImportFrom.module) {
2524 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2525 }
2526 else {
2527 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2528 }
2529 for (i = 0; i < n; i++) {
2530 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2531 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002533 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 assert(n == 1);
2535 ADDOP(c, IMPORT_STAR);
2536 return 1;
2537 }
2538
2539 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2540 store_name = alias->name;
2541 if (alias->asname)
2542 store_name = alias->asname;
2543
2544 if (!compiler_nameop(c, store_name, Store)) {
2545 Py_DECREF(names);
2546 return 0;
2547 }
2548 }
2549 /* remove imported module */
2550 ADDOP(c, POP_TOP);
2551 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552}
2553
2554static int
2555compiler_assert(struct compiler *c, stmt_ty s)
2556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 static PyObject *assertion_error = NULL;
2558 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002559 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560
Georg Brandl8334fd92010-12-04 10:26:46 +00002561 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return 1;
2563 if (assertion_error == NULL) {
2564 assertion_error = PyUnicode_InternFromString("AssertionError");
2565 if (assertion_error == NULL)
2566 return 0;
2567 }
2568 if (s->v.Assert.test->kind == Tuple_kind &&
2569 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002570 msg = PyUnicode_FromString("assertion is always true, "
2571 "perhaps remove parentheses?");
2572 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002574 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2575 c->c_filename, c->u->u_lineno,
2576 NULL, NULL) == -1) {
2577 Py_DECREF(msg);
2578 return 0;
2579 }
2580 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 }
2582 VISIT(c, expr, s->v.Assert.test);
2583 end = compiler_new_block(c);
2584 if (end == NULL)
2585 return 0;
2586 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2587 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2588 if (s->v.Assert.msg) {
2589 VISIT(c, expr, s->v.Assert.msg);
2590 ADDOP_I(c, CALL_FUNCTION, 1);
2591 }
2592 ADDOP_I(c, RAISE_VARARGS, 1);
2593 compiler_use_next_block(c, end);
2594 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595}
2596
2597static int
2598compiler_visit_stmt(struct compiler *c, stmt_ty s)
2599{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002600 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* Always assign a lineno to the next instruction for a stmt. */
2603 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002604 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 switch (s->kind) {
2608 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002609 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 case ClassDef_kind:
2611 return compiler_class(c, s);
2612 case Return_kind:
2613 if (c->u->u_ste->ste_type != FunctionBlock)
2614 return compiler_error(c, "'return' outside function");
2615 if (s->v.Return.value) {
2616 VISIT(c, expr, s->v.Return.value);
2617 }
2618 else
2619 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2620 ADDOP(c, RETURN_VALUE);
2621 break;
2622 case Delete_kind:
2623 VISIT_SEQ(c, expr, s->v.Delete.targets)
2624 break;
2625 case Assign_kind:
2626 n = asdl_seq_LEN(s->v.Assign.targets);
2627 VISIT(c, expr, s->v.Assign.value);
2628 for (i = 0; i < n; i++) {
2629 if (i < n - 1)
2630 ADDOP(c, DUP_TOP);
2631 VISIT(c, expr,
2632 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2633 }
2634 break;
2635 case AugAssign_kind:
2636 return compiler_augassign(c, s);
2637 case For_kind:
2638 return compiler_for(c, s);
2639 case While_kind:
2640 return compiler_while(c, s);
2641 case If_kind:
2642 return compiler_if(c, s);
2643 case Raise_kind:
2644 n = 0;
2645 if (s->v.Raise.exc) {
2646 VISIT(c, expr, s->v.Raise.exc);
2647 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002648 if (s->v.Raise.cause) {
2649 VISIT(c, expr, s->v.Raise.cause);
2650 n++;
2651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002653 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002655 case Try_kind:
2656 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 case Assert_kind:
2658 return compiler_assert(c, s);
2659 case Import_kind:
2660 return compiler_import(c, s);
2661 case ImportFrom_kind:
2662 return compiler_from_import(c, s);
2663 case Global_kind:
2664 case Nonlocal_kind:
2665 break;
2666 case Expr_kind:
2667 if (c->c_interactive && c->c_nestlevel <= 1) {
2668 VISIT(c, expr, s->v.Expr.value);
2669 ADDOP(c, PRINT_EXPR);
2670 }
2671 else if (s->v.Expr.value->kind != Str_kind &&
2672 s->v.Expr.value->kind != Num_kind) {
2673 VISIT(c, expr, s->v.Expr.value);
2674 ADDOP(c, POP_TOP);
2675 }
2676 break;
2677 case Pass_kind:
2678 break;
2679 case Break_kind:
2680 if (!compiler_in_loop(c))
2681 return compiler_error(c, "'break' outside loop");
2682 ADDOP(c, BREAK_LOOP);
2683 break;
2684 case Continue_kind:
2685 return compiler_continue(c);
2686 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002687 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002688 case AsyncFunctionDef_kind:
2689 return compiler_function(c, s, 1);
2690 case AsyncWith_kind:
2691 return compiler_async_with(c, s, 0);
2692 case AsyncFor_kind:
2693 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
Yury Selivanov75445082015-05-11 22:57:16 -04002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697}
2698
2699static int
2700unaryop(unaryop_ty op)
2701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 switch (op) {
2703 case Invert:
2704 return UNARY_INVERT;
2705 case Not:
2706 return UNARY_NOT;
2707 case UAdd:
2708 return UNARY_POSITIVE;
2709 case USub:
2710 return UNARY_NEGATIVE;
2711 default:
2712 PyErr_Format(PyExc_SystemError,
2713 "unary op %d should not be possible", op);
2714 return 0;
2715 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716}
2717
2718static int
2719binop(struct compiler *c, operator_ty op)
2720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 switch (op) {
2722 case Add:
2723 return BINARY_ADD;
2724 case Sub:
2725 return BINARY_SUBTRACT;
2726 case Mult:
2727 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002728 case MatMult:
2729 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 case Div:
2731 return BINARY_TRUE_DIVIDE;
2732 case Mod:
2733 return BINARY_MODULO;
2734 case Pow:
2735 return BINARY_POWER;
2736 case LShift:
2737 return BINARY_LSHIFT;
2738 case RShift:
2739 return BINARY_RSHIFT;
2740 case BitOr:
2741 return BINARY_OR;
2742 case BitXor:
2743 return BINARY_XOR;
2744 case BitAnd:
2745 return BINARY_AND;
2746 case FloorDiv:
2747 return BINARY_FLOOR_DIVIDE;
2748 default:
2749 PyErr_Format(PyExc_SystemError,
2750 "binary op %d should not be possible", op);
2751 return 0;
2752 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753}
2754
2755static int
2756cmpop(cmpop_ty op)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 switch (op) {
2759 case Eq:
2760 return PyCmp_EQ;
2761 case NotEq:
2762 return PyCmp_NE;
2763 case Lt:
2764 return PyCmp_LT;
2765 case LtE:
2766 return PyCmp_LE;
2767 case Gt:
2768 return PyCmp_GT;
2769 case GtE:
2770 return PyCmp_GE;
2771 case Is:
2772 return PyCmp_IS;
2773 case IsNot:
2774 return PyCmp_IS_NOT;
2775 case In:
2776 return PyCmp_IN;
2777 case NotIn:
2778 return PyCmp_NOT_IN;
2779 default:
2780 return PyCmp_BAD;
2781 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782}
2783
2784static int
2785inplace_binop(struct compiler *c, operator_ty op)
2786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 switch (op) {
2788 case Add:
2789 return INPLACE_ADD;
2790 case Sub:
2791 return INPLACE_SUBTRACT;
2792 case Mult:
2793 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002794 case MatMult:
2795 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 case Div:
2797 return INPLACE_TRUE_DIVIDE;
2798 case Mod:
2799 return INPLACE_MODULO;
2800 case Pow:
2801 return INPLACE_POWER;
2802 case LShift:
2803 return INPLACE_LSHIFT;
2804 case RShift:
2805 return INPLACE_RSHIFT;
2806 case BitOr:
2807 return INPLACE_OR;
2808 case BitXor:
2809 return INPLACE_XOR;
2810 case BitAnd:
2811 return INPLACE_AND;
2812 case FloorDiv:
2813 return INPLACE_FLOOR_DIVIDE;
2814 default:
2815 PyErr_Format(PyExc_SystemError,
2816 "inplace binary op %d should not be possible", op);
2817 return 0;
2818 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819}
2820
2821static int
2822compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2823{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002824 int op, scope;
2825 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 PyObject *dict = c->u->u_names;
2829 PyObject *mangled;
2830 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 mangled = _Py_Mangle(c->u->u_private, name);
2833 if (!mangled)
2834 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002835
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002836 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2837 PyUnicode_CompareWithASCIIString(name, "True") &&
2838 PyUnicode_CompareWithASCIIString(name, "False"));
2839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 op = 0;
2841 optype = OP_NAME;
2842 scope = PyST_GetScope(c->u->u_ste, mangled);
2843 switch (scope) {
2844 case FREE:
2845 dict = c->u->u_freevars;
2846 optype = OP_DEREF;
2847 break;
2848 case CELL:
2849 dict = c->u->u_cellvars;
2850 optype = OP_DEREF;
2851 break;
2852 case LOCAL:
2853 if (c->u->u_ste->ste_type == FunctionBlock)
2854 optype = OP_FAST;
2855 break;
2856 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002857 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 optype = OP_GLOBAL;
2859 break;
2860 case GLOBAL_EXPLICIT:
2861 optype = OP_GLOBAL;
2862 break;
2863 default:
2864 /* scope can be 0 */
2865 break;
2866 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002869 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 switch (optype) {
2872 case OP_DEREF:
2873 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002874 case Load:
2875 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2876 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 case Store: op = STORE_DEREF; break;
2878 case AugLoad:
2879 case AugStore:
2880 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002881 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 case Param:
2883 default:
2884 PyErr_SetString(PyExc_SystemError,
2885 "param invalid for deref variable");
2886 return 0;
2887 }
2888 break;
2889 case OP_FAST:
2890 switch (ctx) {
2891 case Load: op = LOAD_FAST; break;
2892 case Store: op = STORE_FAST; break;
2893 case Del: op = DELETE_FAST; break;
2894 case AugLoad:
2895 case AugStore:
2896 break;
2897 case Param:
2898 default:
2899 PyErr_SetString(PyExc_SystemError,
2900 "param invalid for local variable");
2901 return 0;
2902 }
2903 ADDOP_O(c, op, mangled, varnames);
2904 Py_DECREF(mangled);
2905 return 1;
2906 case OP_GLOBAL:
2907 switch (ctx) {
2908 case Load: op = LOAD_GLOBAL; break;
2909 case Store: op = STORE_GLOBAL; break;
2910 case Del: op = DELETE_GLOBAL; break;
2911 case AugLoad:
2912 case AugStore:
2913 break;
2914 case Param:
2915 default:
2916 PyErr_SetString(PyExc_SystemError,
2917 "param invalid for global variable");
2918 return 0;
2919 }
2920 break;
2921 case OP_NAME:
2922 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002923 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 case Store: op = STORE_NAME; break;
2925 case Del: op = DELETE_NAME; break;
2926 case AugLoad:
2927 case AugStore:
2928 break;
2929 case Param:
2930 default:
2931 PyErr_SetString(PyExc_SystemError,
2932 "param invalid for name variable");
2933 return 0;
2934 }
2935 break;
2936 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 assert(op);
2939 arg = compiler_add_o(c, dict, mangled);
2940 Py_DECREF(mangled);
2941 if (arg < 0)
2942 return 0;
2943 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944}
2945
2946static int
2947compiler_boolop(struct compiler *c, expr_ty e)
2948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002950 int jumpi;
2951 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 assert(e->kind == BoolOp_kind);
2955 if (e->v.BoolOp.op == And)
2956 jumpi = JUMP_IF_FALSE_OR_POP;
2957 else
2958 jumpi = JUMP_IF_TRUE_OR_POP;
2959 end = compiler_new_block(c);
2960 if (end == NULL)
2961 return 0;
2962 s = e->v.BoolOp.values;
2963 n = asdl_seq_LEN(s) - 1;
2964 assert(n >= 0);
2965 for (i = 0; i < n; ++i) {
2966 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2967 ADDOP_JABS(c, jumpi, end);
2968 }
2969 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2970 compiler_use_next_block(c, end);
2971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972}
2973
2974static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002975starunpack_helper(struct compiler *c, asdl_seq *elts,
2976 int single_op, int inner_op, int outer_op)
2977{
2978 Py_ssize_t n = asdl_seq_LEN(elts);
2979 Py_ssize_t i, nsubitems = 0, nseen = 0;
2980 for (i = 0; i < n; i++) {
2981 expr_ty elt = asdl_seq_GET(elts, i);
2982 if (elt->kind == Starred_kind) {
2983 if (nseen) {
2984 ADDOP_I(c, inner_op, nseen);
2985 nseen = 0;
2986 nsubitems++;
2987 }
2988 VISIT(c, expr, elt->v.Starred.value);
2989 nsubitems++;
2990 }
2991 else {
2992 VISIT(c, expr, elt);
2993 nseen++;
2994 }
2995 }
2996 if (nsubitems) {
2997 if (nseen) {
2998 ADDOP_I(c, inner_op, nseen);
2999 nsubitems++;
3000 }
3001 ADDOP_I(c, outer_op, nsubitems);
3002 }
3003 else
3004 ADDOP_I(c, single_op, nseen);
3005 return 1;
3006}
3007
3008static int
3009assignment_helper(struct compiler *c, asdl_seq *elts)
3010{
3011 Py_ssize_t n = asdl_seq_LEN(elts);
3012 Py_ssize_t i;
3013 int seen_star = 0;
3014 for (i = 0; i < n; i++) {
3015 expr_ty elt = asdl_seq_GET(elts, i);
3016 if (elt->kind == Starred_kind && !seen_star) {
3017 if ((i >= (1 << 8)) ||
3018 (n-i-1 >= (INT_MAX >> 8)))
3019 return compiler_error(c,
3020 "too many expressions in "
3021 "star-unpacking assignment");
3022 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3023 seen_star = 1;
3024 asdl_seq_SET(elts, i, elt->v.Starred.value);
3025 }
3026 else if (elt->kind == Starred_kind) {
3027 return compiler_error(c,
3028 "two starred expressions in assignment");
3029 }
3030 }
3031 if (!seen_star) {
3032 ADDOP_I(c, UNPACK_SEQUENCE, n);
3033 }
3034 VISIT_SEQ(c, expr, elts);
3035 return 1;
3036}
3037
3038static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039compiler_list(struct compiler *c, expr_ty e)
3040{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003041 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003043 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003045 else if (e->v.List.ctx == Load) {
3046 return starunpack_helper(c, elts,
3047 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003049 else
3050 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052}
3053
3054static int
3055compiler_tuple(struct compiler *c, expr_ty e)
3056{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003057 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003059 return assignment_helper(c, elts);
3060 }
3061 else if (e->v.Tuple.ctx == Load) {
3062 return starunpack_helper(c, elts,
3063 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3064 }
3065 else
3066 VISIT_SEQ(c, expr, elts);
3067 return 1;
3068}
3069
3070static int
3071compiler_set(struct compiler *c, expr_ty e)
3072{
3073 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3074 BUILD_SET, BUILD_SET_UNPACK);
3075}
3076
3077static int
3078compiler_dict(struct compiler *c, expr_ty e)
3079{
3080 Py_ssize_t i, n, containers, elements;
3081 int is_unpacking = 0;
3082 n = asdl_seq_LEN(e->v.Dict.values);
3083 containers = 0;
3084 elements = 0;
3085 for (i = 0; i < n; i++) {
3086 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3087 if (elements == 0xFFFF || (elements && is_unpacking)) {
3088 ADDOP_I(c, BUILD_MAP, elements);
3089 containers++;
3090 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003092 if (is_unpacking) {
3093 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3094 containers++;
3095 }
3096 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003097 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003098 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003099 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 }
3101 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003102 if (elements || containers == 0) {
3103 ADDOP_I(c, BUILD_MAP, elements);
3104 containers++;
3105 }
3106 /* If there is more than one dict, they need to be merged into a new
3107 * dict. If there is one dict and it's an unpacking, then it needs
3108 * to be copied into a new dict." */
3109 while (containers > 1 || is_unpacking) {
3110 int oparg = containers < 255 ? containers : 255;
3111 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3112 containers -= (oparg - 1);
3113 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 }
3115 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003116}
3117
3118static int
3119compiler_compare(struct compiler *c, expr_ty e)
3120{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003121 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3125 VISIT(c, expr, e->v.Compare.left);
3126 n = asdl_seq_LEN(e->v.Compare.ops);
3127 assert(n > 0);
3128 if (n > 1) {
3129 cleanup = compiler_new_block(c);
3130 if (cleanup == NULL)
3131 return 0;
3132 VISIT(c, expr,
3133 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3134 }
3135 for (i = 1; i < n; i++) {
3136 ADDOP(c, DUP_TOP);
3137 ADDOP(c, ROT_THREE);
3138 ADDOP_I(c, COMPARE_OP,
3139 cmpop((cmpop_ty)(asdl_seq_GET(
3140 e->v.Compare.ops, i - 1))));
3141 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3142 NEXT_BLOCK(c);
3143 if (i < (n - 1))
3144 VISIT(c, expr,
3145 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3146 }
3147 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3148 ADDOP_I(c, COMPARE_OP,
3149 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3150 if (n > 1) {
3151 basicblock *end = compiler_new_block(c);
3152 if (end == NULL)
3153 return 0;
3154 ADDOP_JREL(c, JUMP_FORWARD, end);
3155 compiler_use_next_block(c, cleanup);
3156 ADDOP(c, ROT_TWO);
3157 ADDOP(c, POP_TOP);
3158 compiler_use_next_block(c, end);
3159 }
3160 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161}
3162
3163static int
3164compiler_call(struct compiler *c, expr_ty e)
3165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 VISIT(c, expr, e->v.Call.func);
3167 return compiler_call_helper(c, 0,
3168 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003169 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003170}
3171
3172/* shared code between compiler_call and compiler_class */
3173static int
3174compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003175 Py_ssize_t n, /* Args already pushed */
3176 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003177 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003180 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003181
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003182 /* the number of tuples and dictionaries on the stack */
3183 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3184
3185 nkw = 0;
3186 nseen = 0; /* the number of positional arguments on the stack */
3187 nelts = asdl_seq_LEN(args);
3188 for (i = 0; i < nelts; i++) {
3189 expr_ty elt = asdl_seq_GET(args, i);
3190 if (elt->kind == Starred_kind) {
3191 /* A star-arg. If we've seen positional arguments,
3192 pack the positional arguments into a
3193 tuple. */
3194 if (nseen) {
3195 ADDOP_I(c, BUILD_TUPLE, nseen);
3196 nseen = 0;
3197 nsubargs++;
3198 }
3199 VISIT(c, expr, elt->v.Starred.value);
3200 nsubargs++;
3201 }
3202 else if (nsubargs) {
3203 /* We've seen star-args already, so we
3204 count towards items-to-pack-into-tuple. */
3205 VISIT(c, expr, elt);
3206 nseen++;
3207 }
3208 else {
3209 /* Positional arguments before star-arguments
3210 are left on the stack. */
3211 VISIT(c, expr, elt);
3212 n++;
3213 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003215 if (nseen) {
3216 /* Pack up any trailing positional arguments. */
3217 ADDOP_I(c, BUILD_TUPLE, nseen);
3218 nsubargs++;
3219 }
3220 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003222 if (nsubargs > 1) {
3223 /* If we ended up with more than one stararg, we need
3224 to concatenate them into a single sequence. */
3225 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003228
3229 /* Same dance again for keyword arguments */
3230 nseen = 0; /* the number of keyword arguments on the stack following */
3231 nelts = asdl_seq_LEN(keywords);
3232 for (i = 0; i < nelts; i++) {
3233 keyword_ty kw = asdl_seq_GET(keywords, i);
3234 if (kw->arg == NULL) {
3235 /* A keyword argument unpacking. */
3236 if (nseen) {
3237 ADDOP_I(c, BUILD_MAP, nseen);
3238 nseen = 0;
3239 nsubkwargs++;
3240 }
3241 VISIT(c, expr, kw->value);
3242 nsubkwargs++;
3243 }
3244 else if (nsubkwargs) {
3245 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003246 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003247 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003248 nseen++;
3249 }
3250 else {
3251 /* keyword argument */
3252 VISIT(c, keyword, kw)
3253 nkw++;
3254 }
3255 }
3256 if (nseen) {
3257 /* Pack up any trailing keyword arguments. */
3258 ADDOP_I(c, BUILD_MAP, nseen);
3259 nsubkwargs++;
3260 }
3261 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003263 if (nsubkwargs > 1) {
3264 /* Pack it all up */
3265 int function_pos = n + (code & 1) + nkw + 1;
3266 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003269 assert(n < 1<<8);
3270 assert(nkw < 1<<24);
3271 n |= nkw << 8;
3272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 switch (code) {
3274 case 0:
3275 ADDOP_I(c, CALL_FUNCTION, n);
3276 break;
3277 case 1:
3278 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3279 break;
3280 case 2:
3281 ADDOP_I(c, CALL_FUNCTION_KW, n);
3282 break;
3283 case 3:
3284 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3285 break;
3286 }
3287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288}
3289
Nick Coghlan650f0d02007-04-15 12:05:43 +00003290
3291/* List and set comprehensions and generator expressions work by creating a
3292 nested function to perform the actual iteration. This means that the
3293 iteration variables don't leak into the current scope.
3294 The defined function is called immediately following its definition, with the
3295 result of that call being the result of the expression.
3296 The LC/SC version returns the populated container, while the GE version is
3297 flagged in symtable.c as a generator, so it returns the generator object
3298 when the function is called.
3299 This code *knows* that the loop cannot contain break, continue, or return,
3300 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3301
3302 Possible cleanups:
3303 - iterate over the generator sequence instead of using recursion
3304*/
3305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307compiler_comprehension_generator(struct compiler *c,
3308 asdl_seq *generators, int gen_index,
3309 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 /* generate code for the iterator, then each of the ifs,
3312 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 comprehension_ty gen;
3315 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003316 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 start = compiler_new_block(c);
3319 skip = compiler_new_block(c);
3320 if_cleanup = compiler_new_block(c);
3321 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3324 anchor == NULL)
3325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 if (gen_index == 0) {
3330 /* Receive outermost iter as an implicit argument */
3331 c->u->u_argcount = 1;
3332 ADDOP_I(c, LOAD_FAST, 0);
3333 }
3334 else {
3335 /* Sub-iter - calculate on the fly */
3336 VISIT(c, expr, gen->iter);
3337 ADDOP(c, GET_ITER);
3338 }
3339 compiler_use_next_block(c, start);
3340 ADDOP_JREL(c, FOR_ITER, anchor);
3341 NEXT_BLOCK(c);
3342 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 /* XXX this needs to be cleaned up...a lot! */
3345 n = asdl_seq_LEN(gen->ifs);
3346 for (i = 0; i < n; i++) {
3347 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3348 VISIT(c, expr, e);
3349 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3350 NEXT_BLOCK(c);
3351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 if (++gen_index < asdl_seq_LEN(generators))
3354 if (!compiler_comprehension_generator(c,
3355 generators, gen_index,
3356 elt, val, type))
3357 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 /* only append after the last for generator */
3360 if (gen_index >= asdl_seq_LEN(generators)) {
3361 /* comprehension specific code */
3362 switch (type) {
3363 case COMP_GENEXP:
3364 VISIT(c, expr, elt);
3365 ADDOP(c, YIELD_VALUE);
3366 ADDOP(c, POP_TOP);
3367 break;
3368 case COMP_LISTCOMP:
3369 VISIT(c, expr, elt);
3370 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3371 break;
3372 case COMP_SETCOMP:
3373 VISIT(c, expr, elt);
3374 ADDOP_I(c, SET_ADD, gen_index + 1);
3375 break;
3376 case COMP_DICTCOMP:
3377 /* With 'd[k] = v', v is evaluated before k, so we do
3378 the same. */
3379 VISIT(c, expr, val);
3380 VISIT(c, expr, elt);
3381 ADDOP_I(c, MAP_ADD, gen_index + 1);
3382 break;
3383 default:
3384 return 0;
3385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 compiler_use_next_block(c, skip);
3388 }
3389 compiler_use_next_block(c, if_cleanup);
3390 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3391 compiler_use_next_block(c, anchor);
3392
3393 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394}
3395
3396static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003397compiler_comprehension(struct compiler *c, expr_ty e, int type,
3398 identifier name, asdl_seq *generators, expr_ty elt,
3399 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 PyCodeObject *co = NULL;
3402 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003403 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 outermost_iter = ((comprehension_ty)
3406 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003407
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003408 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3409 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 if (type != COMP_GENEXP) {
3413 int op;
3414 switch (type) {
3415 case COMP_LISTCOMP:
3416 op = BUILD_LIST;
3417 break;
3418 case COMP_SETCOMP:
3419 op = BUILD_SET;
3420 break;
3421 case COMP_DICTCOMP:
3422 op = BUILD_MAP;
3423 break;
3424 default:
3425 PyErr_Format(PyExc_SystemError,
3426 "unknown comprehension type %d", type);
3427 goto error_in_scope;
3428 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 ADDOP_I(c, op, 0);
3431 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 if (!compiler_comprehension_generator(c, generators, 0, elt,
3434 val, type))
3435 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 if (type != COMP_GENEXP) {
3438 ADDOP(c, RETURN_VALUE);
3439 }
3440
3441 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003442 qualname = c->u->u_qualname;
3443 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003445 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 goto error;
3447
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003448 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003450 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 Py_DECREF(co);
3452
3453 VISIT(c, expr, outermost_iter);
3454 ADDOP(c, GET_ITER);
3455 ADDOP_I(c, CALL_FUNCTION, 1);
3456 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003457error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003459error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003460 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 Py_XDECREF(co);
3462 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003463}
3464
3465static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466compiler_genexp(struct compiler *c, expr_ty e)
3467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 static identifier name;
3469 if (!name) {
3470 name = PyUnicode_FromString("<genexpr>");
3471 if (!name)
3472 return 0;
3473 }
3474 assert(e->kind == GeneratorExp_kind);
3475 return compiler_comprehension(c, e, COMP_GENEXP, name,
3476 e->v.GeneratorExp.generators,
3477 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003481compiler_listcomp(struct compiler *c, expr_ty e)
3482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 static identifier name;
3484 if (!name) {
3485 name = PyUnicode_FromString("<listcomp>");
3486 if (!name)
3487 return 0;
3488 }
3489 assert(e->kind == ListComp_kind);
3490 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3491 e->v.ListComp.generators,
3492 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003493}
3494
3495static int
3496compiler_setcomp(struct compiler *c, expr_ty e)
3497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 static identifier name;
3499 if (!name) {
3500 name = PyUnicode_FromString("<setcomp>");
3501 if (!name)
3502 return 0;
3503 }
3504 assert(e->kind == SetComp_kind);
3505 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3506 e->v.SetComp.generators,
3507 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003508}
3509
3510
3511static int
3512compiler_dictcomp(struct compiler *c, expr_ty e)
3513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 static identifier name;
3515 if (!name) {
3516 name = PyUnicode_FromString("<dictcomp>");
3517 if (!name)
3518 return 0;
3519 }
3520 assert(e->kind == DictComp_kind);
3521 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3522 e->v.DictComp.generators,
3523 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003524}
3525
3526
3527static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528compiler_visit_keyword(struct compiler *c, keyword_ty k)
3529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3531 VISIT(c, expr, k->value);
3532 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533}
3534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536 whether they are true or false.
3537
3538 Return values: 1 for true, 0 for false, -1 for non-constant.
3539 */
3540
3541static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003542expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 char *id;
3545 switch (e->kind) {
3546 case Ellipsis_kind:
3547 return 1;
3548 case Num_kind:
3549 return PyObject_IsTrue(e->v.Num.n);
3550 case Str_kind:
3551 return PyObject_IsTrue(e->v.Str.s);
3552 case Name_kind:
3553 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003554 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003555 if (id && strcmp(id, "__debug__") == 0)
3556 return !c->c_optimize;
3557 return -1;
3558 case NameConstant_kind: {
3559 PyObject *o = e->v.NameConstant.value;
3560 if (o == Py_None)
3561 return 0;
3562 else if (o == Py_True)
3563 return 1;
3564 else if (o == Py_False)
3565 return 0;
3566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 default:
3568 return -1;
3569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570}
3571
Yury Selivanov75445082015-05-11 22:57:16 -04003572
3573/*
3574 Implements the async with statement.
3575
3576 The semantics outlined in that PEP are as follows:
3577
3578 async with EXPR as VAR:
3579 BLOCK
3580
3581 It is implemented roughly as:
3582
3583 context = EXPR
3584 exit = context.__aexit__ # not calling it
3585 value = await context.__aenter__()
3586 try:
3587 VAR = value # if VAR present in the syntax
3588 BLOCK
3589 finally:
3590 if an exception was raised:
3591 exc = copy of (exception, instance, traceback)
3592 else:
3593 exc = (None, None, None)
3594 if not (await exit(*exc)):
3595 raise
3596 */
3597static int
3598compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3599{
3600 basicblock *block, *finally;
3601 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3602
3603 assert(s->kind == AsyncWith_kind);
3604
3605 block = compiler_new_block(c);
3606 finally = compiler_new_block(c);
3607 if (!block || !finally)
3608 return 0;
3609
3610 /* Evaluate EXPR */
3611 VISIT(c, expr, item->context_expr);
3612
3613 ADDOP(c, BEFORE_ASYNC_WITH);
3614 ADDOP(c, GET_AWAITABLE);
3615 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3616 ADDOP(c, YIELD_FROM);
3617
3618 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3619
3620 /* SETUP_ASYNC_WITH pushes a finally block. */
3621 compiler_use_next_block(c, block);
3622 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3623 return 0;
3624 }
3625
3626 if (item->optional_vars) {
3627 VISIT(c, expr, item->optional_vars);
3628 }
3629 else {
3630 /* Discard result from context.__aenter__() */
3631 ADDOP(c, POP_TOP);
3632 }
3633
3634 pos++;
3635 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3636 /* BLOCK code */
3637 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3638 else if (!compiler_async_with(c, s, pos))
3639 return 0;
3640
3641 /* End of try block; start the finally block */
3642 ADDOP(c, POP_BLOCK);
3643 compiler_pop_fblock(c, FINALLY_TRY, block);
3644
3645 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3646 compiler_use_next_block(c, finally);
3647 if (!compiler_push_fblock(c, FINALLY_END, finally))
3648 return 0;
3649
3650 /* Finally block starts; context.__exit__ is on the stack under
3651 the exception or return information. Just issue our magic
3652 opcode. */
3653 ADDOP(c, WITH_CLEANUP_START);
3654
3655 ADDOP(c, GET_AWAITABLE);
3656 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3657 ADDOP(c, YIELD_FROM);
3658
3659 ADDOP(c, WITH_CLEANUP_FINISH);
3660
3661 /* Finally block ends. */
3662 ADDOP(c, END_FINALLY);
3663 compiler_pop_fblock(c, FINALLY_END, finally);
3664 return 1;
3665}
3666
3667
Guido van Rossumc2e20742006-02-27 22:32:47 +00003668/*
3669 Implements the with statement from PEP 343.
3670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003672
3673 with EXPR as VAR:
3674 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675
Guido van Rossumc2e20742006-02-27 22:32:47 +00003676 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677
Thomas Wouters477c8d52006-05-27 19:21:47 +00003678 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003679 exit = context.__exit__ # not calling it
3680 value = context.__enter__()
3681 try:
3682 VAR = value # if VAR present in the syntax
3683 BLOCK
3684 finally:
3685 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003686 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003687 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003688 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003689 exit(*exc)
3690 */
3691static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003692compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003693{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003694 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003695 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003696
3697 assert(s->kind == With_kind);
3698
Guido van Rossumc2e20742006-02-27 22:32:47 +00003699 block = compiler_new_block(c);
3700 finally = compiler_new_block(c);
3701 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003702 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003703
Thomas Wouters477c8d52006-05-27 19:21:47 +00003704 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003705 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003706 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003707
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003708 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003709 compiler_use_next_block(c, block);
3710 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003711 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003712 }
3713
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003714 if (item->optional_vars) {
3715 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003716 }
3717 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003719 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003720 }
3721
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003722 pos++;
3723 if (pos == asdl_seq_LEN(s->v.With.items))
3724 /* BLOCK code */
3725 VISIT_SEQ(c, stmt, s->v.With.body)
3726 else if (!compiler_with(c, s, pos))
3727 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003728
3729 /* End of try block; start the finally block */
3730 ADDOP(c, POP_BLOCK);
3731 compiler_pop_fblock(c, FINALLY_TRY, block);
3732
3733 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3734 compiler_use_next_block(c, finally);
3735 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003736 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003737
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003738 /* Finally block starts; context.__exit__ is on the stack under
3739 the exception or return information. Just issue our magic
3740 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003741 ADDOP(c, WITH_CLEANUP_START);
3742 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003743
3744 /* Finally block ends. */
3745 ADDOP(c, END_FINALLY);
3746 compiler_pop_fblock(c, FINALLY_END, finally);
3747 return 1;
3748}
3749
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750static int
3751compiler_visit_expr(struct compiler *c, expr_ty e)
3752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 /* If expr e has a different line number than the last expr/stmt,
3754 set a new line number for the next instruction.
3755 */
3756 if (e->lineno > c->u->u_lineno) {
3757 c->u->u_lineno = e->lineno;
3758 c->u->u_lineno_set = 0;
3759 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003760 /* Updating the column offset is always harmless. */
3761 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 switch (e->kind) {
3763 case BoolOp_kind:
3764 return compiler_boolop(c, e);
3765 case BinOp_kind:
3766 VISIT(c, expr, e->v.BinOp.left);
3767 VISIT(c, expr, e->v.BinOp.right);
3768 ADDOP(c, binop(c, e->v.BinOp.op));
3769 break;
3770 case UnaryOp_kind:
3771 VISIT(c, expr, e->v.UnaryOp.operand);
3772 ADDOP(c, unaryop(e->v.UnaryOp.op));
3773 break;
3774 case Lambda_kind:
3775 return compiler_lambda(c, e);
3776 case IfExp_kind:
3777 return compiler_ifexp(c, e);
3778 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003779 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 case GeneratorExp_kind:
3783 return compiler_genexp(c, e);
3784 case ListComp_kind:
3785 return compiler_listcomp(c, e);
3786 case SetComp_kind:
3787 return compiler_setcomp(c, e);
3788 case DictComp_kind:
3789 return compiler_dictcomp(c, e);
3790 case Yield_kind:
3791 if (c->u->u_ste->ste_type != FunctionBlock)
3792 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003793 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3794 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003795 if (e->v.Yield.value) {
3796 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 }
3798 else {
3799 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3800 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003801 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003803 case YieldFrom_kind:
3804 if (c->u->u_ste->ste_type != FunctionBlock)
3805 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003806
3807 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3808 return compiler_error(c, "'yield from' inside async function");
3809
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003810 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003811 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003812 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3813 ADDOP(c, YIELD_FROM);
3814 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003815 case Await_kind:
3816 if (c->u->u_ste->ste_type != FunctionBlock)
3817 return compiler_error(c, "'await' outside function");
3818
Yury Selivanov9dec0352015-06-30 12:49:04 -04003819 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3820 return compiler_error(
3821 c, "'await' expressions in comprehensions are not supported");
3822
Yury Selivanov75445082015-05-11 22:57:16 -04003823 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3824 return compiler_error(c, "'await' outside async function");
3825
3826 VISIT(c, expr, e->v.Await.value);
3827 ADDOP(c, GET_AWAITABLE);
3828 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3829 ADDOP(c, YIELD_FROM);
3830 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 case Compare_kind:
3832 return compiler_compare(c, e);
3833 case Call_kind:
3834 return compiler_call(c, e);
3835 case Num_kind:
3836 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3837 break;
3838 case Str_kind:
3839 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3840 break;
3841 case Bytes_kind:
3842 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3843 break;
3844 case Ellipsis_kind:
3845 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3846 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003847 case NameConstant_kind:
3848 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3849 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 /* The following exprs can be assignment targets. */
3851 case Attribute_kind:
3852 if (e->v.Attribute.ctx != AugStore)
3853 VISIT(c, expr, e->v.Attribute.value);
3854 switch (e->v.Attribute.ctx) {
3855 case AugLoad:
3856 ADDOP(c, DUP_TOP);
3857 /* Fall through to load */
3858 case Load:
3859 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3860 break;
3861 case AugStore:
3862 ADDOP(c, ROT_TWO);
3863 /* Fall through to save */
3864 case Store:
3865 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3866 break;
3867 case Del:
3868 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3869 break;
3870 case Param:
3871 default:
3872 PyErr_SetString(PyExc_SystemError,
3873 "param invalid in attribute expression");
3874 return 0;
3875 }
3876 break;
3877 case Subscript_kind:
3878 switch (e->v.Subscript.ctx) {
3879 case AugLoad:
3880 VISIT(c, expr, e->v.Subscript.value);
3881 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3882 break;
3883 case Load:
3884 VISIT(c, expr, e->v.Subscript.value);
3885 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3886 break;
3887 case AugStore:
3888 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3889 break;
3890 case Store:
3891 VISIT(c, expr, e->v.Subscript.value);
3892 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3893 break;
3894 case Del:
3895 VISIT(c, expr, e->v.Subscript.value);
3896 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3897 break;
3898 case Param:
3899 default:
3900 PyErr_SetString(PyExc_SystemError,
3901 "param invalid in subscript expression");
3902 return 0;
3903 }
3904 break;
3905 case Starred_kind:
3906 switch (e->v.Starred.ctx) {
3907 case Store:
3908 /* In all legitimate cases, the Starred node was already replaced
3909 * by compiler_list/compiler_tuple. XXX: is that okay? */
3910 return compiler_error(c,
3911 "starred assignment target must be in a list or tuple");
3912 default:
3913 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003914 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 }
3916 break;
3917 case Name_kind:
3918 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3919 /* child nodes of List and Tuple will have expr_context set */
3920 case List_kind:
3921 return compiler_list(c, e);
3922 case Tuple_kind:
3923 return compiler_tuple(c, e);
3924 }
3925 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003926}
3927
3928static int
3929compiler_augassign(struct compiler *c, stmt_ty s)
3930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 expr_ty e = s->v.AugAssign.target;
3932 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 switch (e->kind) {
3937 case Attribute_kind:
3938 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3939 AugLoad, e->lineno, e->col_offset, c->c_arena);
3940 if (auge == NULL)
3941 return 0;
3942 VISIT(c, expr, auge);
3943 VISIT(c, expr, s->v.AugAssign.value);
3944 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3945 auge->v.Attribute.ctx = AugStore;
3946 VISIT(c, expr, auge);
3947 break;
3948 case Subscript_kind:
3949 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3950 AugLoad, e->lineno, e->col_offset, c->c_arena);
3951 if (auge == NULL)
3952 return 0;
3953 VISIT(c, expr, auge);
3954 VISIT(c, expr, s->v.AugAssign.value);
3955 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3956 auge->v.Subscript.ctx = AugStore;
3957 VISIT(c, expr, auge);
3958 break;
3959 case Name_kind:
3960 if (!compiler_nameop(c, e->v.Name.id, Load))
3961 return 0;
3962 VISIT(c, expr, s->v.AugAssign.value);
3963 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3964 return compiler_nameop(c, e->v.Name.id, Store);
3965 default:
3966 PyErr_Format(PyExc_SystemError,
3967 "invalid node type (%d) for augmented assignment",
3968 e->kind);
3969 return 0;
3970 }
3971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972}
3973
3974static int
3975compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 struct fblockinfo *f;
3978 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3979 PyErr_SetString(PyExc_SystemError,
3980 "too many statically nested blocks");
3981 return 0;
3982 }
3983 f = &c->u->u_fblock[c->u->u_nfblocks++];
3984 f->fb_type = t;
3985 f->fb_block = b;
3986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003987}
3988
3989static void
3990compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 struct compiler_unit *u = c->u;
3993 assert(u->u_nfblocks > 0);
3994 u->u_nfblocks--;
3995 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3996 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003997}
3998
Thomas Wouters89f507f2006-12-13 04:49:30 +00003999static int
4000compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 int i;
4002 struct compiler_unit *u = c->u;
4003 for (i = 0; i < u->u_nfblocks; ++i) {
4004 if (u->u_fblock[i].fb_type == LOOP)
4005 return 1;
4006 }
4007 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004008}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009/* Raises a SyntaxError and returns 0.
4010 If something goes wrong, a different exception may be raised.
4011*/
4012
4013static int
4014compiler_error(struct compiler *c, const char *errstr)
4015{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004016 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004018
Victor Stinner14e461d2013-08-26 22:28:21 +02004019 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 if (!loc) {
4021 Py_INCREF(Py_None);
4022 loc = Py_None;
4023 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004024 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004025 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 if (!u)
4027 goto exit;
4028 v = Py_BuildValue("(zO)", errstr, u);
4029 if (!v)
4030 goto exit;
4031 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 Py_DECREF(loc);
4034 Py_XDECREF(u);
4035 Py_XDECREF(v);
4036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004037}
4038
4039static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040compiler_handle_subscr(struct compiler *c, const char *kind,
4041 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 /* XXX this code is duplicated */
4046 switch (ctx) {
4047 case AugLoad: /* fall through to Load */
4048 case Load: op = BINARY_SUBSCR; break;
4049 case AugStore:/* fall through to Store */
4050 case Store: op = STORE_SUBSCR; break;
4051 case Del: op = DELETE_SUBSCR; break;
4052 case Param:
4053 PyErr_Format(PyExc_SystemError,
4054 "invalid %s kind %d in subscript\n",
4055 kind, ctx);
4056 return 0;
4057 }
4058 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004059 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 }
4061 else if (ctx == AugStore) {
4062 ADDOP(c, ROT_THREE);
4063 }
4064 ADDOP(c, op);
4065 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066}
4067
4068static int
4069compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 int n = 2;
4072 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 /* only handles the cases where BUILD_SLICE is emitted */
4075 if (s->v.Slice.lower) {
4076 VISIT(c, expr, s->v.Slice.lower);
4077 }
4078 else {
4079 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4080 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 if (s->v.Slice.upper) {
4083 VISIT(c, expr, s->v.Slice.upper);
4084 }
4085 else {
4086 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4087 }
4088
4089 if (s->v.Slice.step) {
4090 n++;
4091 VISIT(c, expr, s->v.Slice.step);
4092 }
4093 ADDOP_I(c, BUILD_SLICE, n);
4094 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004095}
4096
4097static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4099 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 switch (s->kind) {
4102 case Slice_kind:
4103 return compiler_slice(c, s, ctx);
4104 case Index_kind:
4105 VISIT(c, expr, s->v.Index.value);
4106 break;
4107 case ExtSlice_kind:
4108 default:
4109 PyErr_SetString(PyExc_SystemError,
4110 "extended slice invalid in nested slice");
4111 return 0;
4112 }
4113 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114}
4115
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116static int
4117compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 char * kindname = NULL;
4120 switch (s->kind) {
4121 case Index_kind:
4122 kindname = "index";
4123 if (ctx != AugStore) {
4124 VISIT(c, expr, s->v.Index.value);
4125 }
4126 break;
4127 case Slice_kind:
4128 kindname = "slice";
4129 if (ctx != AugStore) {
4130 if (!compiler_slice(c, s, ctx))
4131 return 0;
4132 }
4133 break;
4134 case ExtSlice_kind:
4135 kindname = "extended slice";
4136 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004137 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 for (i = 0; i < n; i++) {
4139 slice_ty sub = (slice_ty)asdl_seq_GET(
4140 s->v.ExtSlice.dims, i);
4141 if (!compiler_visit_nested_slice(c, sub, ctx))
4142 return 0;
4143 }
4144 ADDOP_I(c, BUILD_TUPLE, n);
4145 }
4146 break;
4147 default:
4148 PyErr_Format(PyExc_SystemError,
4149 "invalid subscript kind %d", s->kind);
4150 return 0;
4151 }
4152 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153}
4154
Thomas Wouters89f507f2006-12-13 04:49:30 +00004155/* End of the compiler section, beginning of the assembler section */
4156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157/* do depth-first search of basic block graph, starting with block.
4158 post records the block indices in post-order.
4159
4160 XXX must handle implicit jumps from one block to next
4161*/
4162
Thomas Wouters89f507f2006-12-13 04:49:30 +00004163struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 PyObject *a_bytecode; /* string containing bytecode */
4165 int a_offset; /* offset into bytecode */
4166 int a_nblocks; /* number of reachable blocks */
4167 basicblock **a_postorder; /* list of blocks in dfs postorder */
4168 PyObject *a_lnotab; /* string containing lnotab */
4169 int a_lnotab_off; /* offset into lnotab */
4170 int a_lineno; /* last lineno of emitted instruction */
4171 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004172};
4173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174static void
4175dfs(struct compiler *c, basicblock *b, struct assembler *a)
4176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 int i;
4178 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 if (b->b_seen)
4181 return;
4182 b->b_seen = 1;
4183 if (b->b_next != NULL)
4184 dfs(c, b->b_next, a);
4185 for (i = 0; i < b->b_iused; i++) {
4186 instr = &b->b_instr[i];
4187 if (instr->i_jrel || instr->i_jabs)
4188 dfs(c, instr->i_target, a);
4189 }
4190 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191}
4192
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004193static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4195{
Larry Hastings3a907972013-11-23 14:49:22 -08004196 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 struct instr *instr;
4198 if (b->b_seen || b->b_startdepth >= depth)
4199 return maxdepth;
4200 b->b_seen = 1;
4201 b->b_startdepth = depth;
4202 for (i = 0; i < b->b_iused; i++) {
4203 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004204 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4205 if (effect == PY_INVALID_STACK_EFFECT) {
4206 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4207 Py_FatalError("PyCompile_OpcodeStackEffect()");
4208 }
4209 depth += effect;
4210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 if (depth > maxdepth)
4212 maxdepth = depth;
4213 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4214 if (instr->i_jrel || instr->i_jabs) {
4215 target_depth = depth;
4216 if (instr->i_opcode == FOR_ITER) {
4217 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004218 }
4219 else if (instr->i_opcode == SETUP_FINALLY ||
4220 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 target_depth = depth+3;
4222 if (target_depth > maxdepth)
4223 maxdepth = target_depth;
4224 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004225 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4226 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4227 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 maxdepth = stackdepth_walk(c, instr->i_target,
4229 target_depth, maxdepth);
4230 if (instr->i_opcode == JUMP_ABSOLUTE ||
4231 instr->i_opcode == JUMP_FORWARD) {
4232 goto out; /* remaining code is dead */
4233 }
4234 }
4235 }
4236 if (b->b_next)
4237 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004238out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 b->b_seen = 0;
4240 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004241}
4242
4243/* Find the flow path that needs the largest stack. We assume that
4244 * cycles in the flow graph have no net effect on the stack depth.
4245 */
4246static int
4247stackdepth(struct compiler *c)
4248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 basicblock *b, *entryblock;
4250 entryblock = NULL;
4251 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4252 b->b_seen = 0;
4253 b->b_startdepth = INT_MIN;
4254 entryblock = b;
4255 }
4256 if (!entryblock)
4257 return 0;
4258 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004259}
4260
4261static int
4262assemble_init(struct assembler *a, int nblocks, int firstlineno)
4263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 memset(a, 0, sizeof(struct assembler));
4265 a->a_lineno = firstlineno;
4266 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4267 if (!a->a_bytecode)
4268 return 0;
4269 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4270 if (!a->a_lnotab)
4271 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004272 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 PyErr_NoMemory();
4274 return 0;
4275 }
4276 a->a_postorder = (basicblock **)PyObject_Malloc(
4277 sizeof(basicblock *) * nblocks);
4278 if (!a->a_postorder) {
4279 PyErr_NoMemory();
4280 return 0;
4281 }
4282 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004283}
4284
4285static void
4286assemble_free(struct assembler *a)
4287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 Py_XDECREF(a->a_bytecode);
4289 Py_XDECREF(a->a_lnotab);
4290 if (a->a_postorder)
4291 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292}
4293
4294/* Return the size of a basic block in bytes. */
4295
4296static int
4297instrsize(struct instr *instr)
4298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 if (!instr->i_hasarg)
4300 return 1; /* 1 byte for the opcode*/
4301 if (instr->i_oparg > 0xffff)
4302 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4303 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004304}
4305
4306static int
4307blocksize(basicblock *b)
4308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 int i;
4310 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 for (i = 0; i < b->b_iused; i++)
4313 size += instrsize(&b->b_instr[i]);
4314 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004315}
4316
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004317/* Appends a pair to the end of the line number table, a_lnotab, representing
4318 the instruction's bytecode offset and line number. See
4319 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004320
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004321static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004322assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004325 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 d_bytecode = a->a_offset - a->a_lineno_off;
4329 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 assert(d_bytecode >= 0);
4332 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 if(d_bytecode == 0 && d_lineno == 0)
4335 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 if (d_bytecode > 255) {
4338 int j, nbytes, ncodes = d_bytecode / 255;
4339 nbytes = a->a_lnotab_off + 2 * ncodes;
4340 len = PyBytes_GET_SIZE(a->a_lnotab);
4341 if (nbytes >= len) {
4342 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4343 len = nbytes;
4344 else if (len <= INT_MAX / 2)
4345 len *= 2;
4346 else {
4347 PyErr_NoMemory();
4348 return 0;
4349 }
4350 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4351 return 0;
4352 }
4353 lnotab = (unsigned char *)
4354 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4355 for (j = 0; j < ncodes; j++) {
4356 *lnotab++ = 255;
4357 *lnotab++ = 0;
4358 }
4359 d_bytecode -= ncodes * 255;
4360 a->a_lnotab_off += ncodes * 2;
4361 }
4362 assert(d_bytecode <= 255);
4363 if (d_lineno > 255) {
4364 int j, nbytes, ncodes = d_lineno / 255;
4365 nbytes = a->a_lnotab_off + 2 * ncodes;
4366 len = PyBytes_GET_SIZE(a->a_lnotab);
4367 if (nbytes >= len) {
4368 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4369 len = nbytes;
4370 else if (len <= INT_MAX / 2)
4371 len *= 2;
4372 else {
4373 PyErr_NoMemory();
4374 return 0;
4375 }
4376 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4377 return 0;
4378 }
4379 lnotab = (unsigned char *)
4380 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4381 *lnotab++ = d_bytecode;
4382 *lnotab++ = 255;
4383 d_bytecode = 0;
4384 for (j = 1; j < ncodes; j++) {
4385 *lnotab++ = 0;
4386 *lnotab++ = 255;
4387 }
4388 d_lineno -= ncodes * 255;
4389 a->a_lnotab_off += ncodes * 2;
4390 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 len = PyBytes_GET_SIZE(a->a_lnotab);
4393 if (a->a_lnotab_off + 2 >= len) {
4394 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4395 return 0;
4396 }
4397 lnotab = (unsigned char *)
4398 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 a->a_lnotab_off += 2;
4401 if (d_bytecode) {
4402 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004403 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 }
4405 else { /* First line of a block; def stmt, etc. */
4406 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004407 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 }
4409 a->a_lineno = i->i_lineno;
4410 a->a_lineno_off = a->a_offset;
4411 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004412}
4413
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004414/* assemble_emit()
4415 Extend the bytecode with a new instruction.
4416 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004417*/
4418
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004419static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004420assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 int size, arg = 0, ext = 0;
4423 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4424 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 size = instrsize(i);
4427 if (i->i_hasarg) {
4428 arg = i->i_oparg;
4429 ext = arg >> 16;
4430 }
4431 if (i->i_lineno && !assemble_lnotab(a, i))
4432 return 0;
4433 if (a->a_offset + size >= len) {
4434 if (len > PY_SSIZE_T_MAX / 2)
4435 return 0;
4436 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4437 return 0;
4438 }
4439 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4440 a->a_offset += size;
4441 if (size == 6) {
4442 assert(i->i_hasarg);
4443 *code++ = (char)EXTENDED_ARG;
4444 *code++ = ext & 0xff;
4445 *code++ = ext >> 8;
4446 arg &= 0xffff;
4447 }
4448 *code++ = i->i_opcode;
4449 if (i->i_hasarg) {
4450 assert(size == 3 || size == 6);
4451 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004452 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 }
4454 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004455}
4456
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004457static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004458assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 basicblock *b;
4461 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4462 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 /* Compute the size of each block and fixup jump args.
4465 Replace block pointer with position in bytecode. */
4466 do {
4467 totsize = 0;
4468 for (i = a->a_nblocks - 1; i >= 0; i--) {
4469 b = a->a_postorder[i];
4470 bsize = blocksize(b);
4471 b->b_offset = totsize;
4472 totsize += bsize;
4473 }
4474 last_extended_arg_count = extended_arg_count;
4475 extended_arg_count = 0;
4476 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4477 bsize = b->b_offset;
4478 for (i = 0; i < b->b_iused; i++) {
4479 struct instr *instr = &b->b_instr[i];
4480 /* Relative jumps are computed relative to
4481 the instruction pointer after fetching
4482 the jump instruction.
4483 */
4484 bsize += instrsize(instr);
4485 if (instr->i_jabs)
4486 instr->i_oparg = instr->i_target->b_offset;
4487 else if (instr->i_jrel) {
4488 int delta = instr->i_target->b_offset - bsize;
4489 instr->i_oparg = delta;
4490 }
4491 else
4492 continue;
4493 if (instr->i_oparg > 0xffff)
4494 extended_arg_count++;
4495 }
4496 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 /* XXX: This is an awful hack that could hurt performance, but
4499 on the bright side it should work until we come up
4500 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 The issue is that in the first loop blocksize() is called
4503 which calls instrsize() which requires i_oparg be set
4504 appropriately. There is a bootstrap problem because
4505 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 So we loop until we stop seeing new EXTENDED_ARGs.
4508 The only EXTENDED_ARGs that could be popping up are
4509 ones in jump instructions. So this should converge
4510 fairly quickly.
4511 */
4512 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004513}
4514
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004515static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004516dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 PyObject *tuple, *k, *v;
4519 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 tuple = PyTuple_New(size);
4522 if (tuple == NULL)
4523 return NULL;
4524 while (PyDict_Next(dict, &pos, &k, &v)) {
4525 i = PyLong_AS_LONG(v);
Victor Stinner3cdd5fb2016-01-22 12:33:12 +01004526 /* The keys of the dictionary are tuples. (see compiler_add_o
4527 * and _PyCode_ConstantKey). The object we want is always second,
4528 * though. */
4529 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 Py_INCREF(k);
4531 assert((i - offset) < size);
4532 assert((i - offset) >= 0);
4533 PyTuple_SET_ITEM(tuple, i - offset, k);
4534 }
4535 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004536}
4537
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004538static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004539compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004542 int flags = 0;
4543 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004545 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 if (ste->ste_nested)
4547 flags |= CO_NESTED;
4548 if (ste->ste_generator)
4549 flags |= CO_GENERATOR;
4550 if (ste->ste_varargs)
4551 flags |= CO_VARARGS;
4552 if (ste->ste_varkeywords)
4553 flags |= CO_VARKEYWORDS;
4554 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 /* (Only) inherit compilerflags in PyCF_MASK */
4557 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 n = PyDict_Size(c->u->u_freevars);
4560 if (n < 0)
4561 return -1;
4562 if (n == 0) {
4563 n = PyDict_Size(c->u->u_cellvars);
4564 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004565 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004567 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 }
4569 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004572}
4573
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004574static PyCodeObject *
4575makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 PyObject *tmp;
4578 PyCodeObject *co = NULL;
4579 PyObject *consts = NULL;
4580 PyObject *names = NULL;
4581 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 PyObject *name = NULL;
4583 PyObject *freevars = NULL;
4584 PyObject *cellvars = NULL;
4585 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004586 Py_ssize_t nlocals;
4587 int nlocals_int;
4588 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004589 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 tmp = dict_keys_inorder(c->u->u_consts, 0);
4592 if (!tmp)
4593 goto error;
4594 consts = PySequence_List(tmp); /* optimize_code requires a list */
4595 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 names = dict_keys_inorder(c->u->u_names, 0);
4598 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4599 if (!consts || !names || !varnames)
4600 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4603 if (!cellvars)
4604 goto error;
4605 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4606 if (!freevars)
4607 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004610 assert(nlocals < INT_MAX);
4611 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 flags = compute_code_flags(c);
4614 if (flags < 0)
4615 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4618 if (!bytecode)
4619 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4622 if (!tmp)
4623 goto error;
4624 Py_DECREF(consts);
4625 consts = tmp;
4626
Victor Stinnerf8e32212013-11-19 23:56:34 +01004627 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4628 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4629 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004630 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 bytecode, consts, names, varnames,
4632 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004633 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 c->u->u_firstlineno,
4635 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004636 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 Py_XDECREF(consts);
4638 Py_XDECREF(names);
4639 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 Py_XDECREF(name);
4641 Py_XDECREF(freevars);
4642 Py_XDECREF(cellvars);
4643 Py_XDECREF(bytecode);
4644 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004645}
4646
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004647
4648/* For debugging purposes only */
4649#if 0
4650static void
4651dump_instr(const struct instr *i)
4652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 const char *jrel = i->i_jrel ? "jrel " : "";
4654 const char *jabs = i->i_jabs ? "jabs " : "";
4655 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 *arg = '\0';
4658 if (i->i_hasarg)
4659 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4662 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004663}
4664
4665static void
4666dump_basicblock(const basicblock *b)
4667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 const char *seen = b->b_seen ? "seen " : "";
4669 const char *b_return = b->b_return ? "return " : "";
4670 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4671 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4672 if (b->b_instr) {
4673 int i;
4674 for (i = 0; i < b->b_iused; i++) {
4675 fprintf(stderr, " [%02d] ", i);
4676 dump_instr(b->b_instr + i);
4677 }
4678 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004679}
4680#endif
4681
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004682static PyCodeObject *
4683assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 basicblock *b, *entryblock;
4686 struct assembler a;
4687 int i, j, nblocks;
4688 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 /* Make sure every block that falls off the end returns None.
4691 XXX NEXT_BLOCK() isn't quite right, because if the last
4692 block ends with a jump or return b_next shouldn't set.
4693 */
4694 if (!c->u->u_curblock->b_return) {
4695 NEXT_BLOCK(c);
4696 if (addNone)
4697 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4698 ADDOP(c, RETURN_VALUE);
4699 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 nblocks = 0;
4702 entryblock = NULL;
4703 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4704 nblocks++;
4705 entryblock = b;
4706 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 /* Set firstlineno if it wasn't explicitly set. */
4709 if (!c->u->u_firstlineno) {
4710 if (entryblock && entryblock->b_instr)
4711 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4712 else
4713 c->u->u_firstlineno = 1;
4714 }
4715 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4716 goto error;
4717 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 /* Can't modify the bytecode after computing jump offsets. */
4720 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 /* Emit code in reverse postorder from dfs. */
4723 for (i = a.a_nblocks - 1; i >= 0; i--) {
4724 b = a.a_postorder[i];
4725 for (j = 0; j < b->b_iused; j++)
4726 if (!assemble_emit(&a, &b->b_instr[j]))
4727 goto error;
4728 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4731 goto error;
4732 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4733 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004736 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 assemble_free(&a);
4738 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004739}
Georg Brandl8334fd92010-12-04 10:26:46 +00004740
4741#undef PyAST_Compile
4742PyAPI_FUNC(PyCodeObject *)
4743PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4744 PyArena *arena)
4745{
4746 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4747}
4748