blob: 027e3abe6813f481c23710297b91bd6e7185717e [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);
396 k = PyTuple_Pack(2, k, k->ob_type);
397 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++;
459 tuple = PyTuple_Pack(2, k, k->ob_type);
460 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) {
551 /* Cook up a implicit __class__ cell. */
552 _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 }
562 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
563 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:
988 return 1;
989 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;
1103 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104
Serhiy Storchaka95949422013-08-27 19:40:23 +03001105 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1107 if (PyFloat_Check(o)) {
1108 d = PyFloat_AS_DOUBLE(o);
1109 /* all we need is to make the tuple different in either the 0.0
1110 * or -0.0 case from all others, just to avoid the "coercion".
1111 */
1112 if (d == 0.0 && copysign(1.0, d) < 0.0)
1113 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1114 else
1115 t = PyTuple_Pack(2, o, o->ob_type);
1116 }
1117 else if (PyComplex_Check(o)) {
1118 Py_complex z;
1119 int real_negzero, imag_negzero;
1120 /* For the complex case we must make complex(x, 0.)
1121 different from complex(x, -0.) and complex(0., y)
1122 different from complex(-0., y), for any x and y.
1123 All four complex zeros must be distinguished.*/
1124 z = PyComplex_AsCComplex(o);
1125 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1126 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1127 if (real_negzero && imag_negzero) {
1128 t = PyTuple_Pack(5, o, o->ob_type,
1129 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 else if (imag_negzero) {
1132 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 else if (real_negzero) {
1135 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1136 }
1137 else {
1138 t = PyTuple_Pack(2, o, o->ob_type);
1139 }
1140 }
1141 else {
1142 t = PyTuple_Pack(2, o, o->ob_type);
1143 }
1144 if (t == NULL)
1145 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 v = PyDict_GetItem(dict, t);
1148 if (!v) {
1149 if (PyErr_Occurred())
1150 return -1;
1151 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001152 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (!v) {
1154 Py_DECREF(t);
1155 return -1;
1156 }
1157 if (PyDict_SetItem(dict, t, v) < 0) {
1158 Py_DECREF(t);
1159 Py_DECREF(v);
1160 return -1;
1161 }
1162 Py_DECREF(v);
1163 }
1164 else
1165 arg = PyLong_AsLong(v);
1166 Py_DECREF(t);
1167 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168}
1169
1170static int
1171compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001174 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001176 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 return compiler_addop_i(c, opcode, arg);
1178}
1179
1180static int
1181compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001184 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1186 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001187 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188 arg = compiler_add_o(c, dict, mangled);
1189 Py_DECREF(mangled);
1190 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001191 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 return compiler_addop_i(c, opcode, arg);
1193}
1194
1195/* Add an opcode with an integer argument.
1196 Returns 0 on failure, 1 on success.
1197*/
1198
1199static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001200compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 struct instr *i;
1203 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001204
1205 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1206 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001207 assert((-2147483647-1) <= oparg);
1208 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 off = compiler_next_instr(c, c->u->u_curblock);
1211 if (off < 0)
1212 return 0;
1213 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001214 i->i_opcode = opcode;
1215 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 i->i_hasarg = 1;
1217 compiler_set_lineno(c, off);
1218 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219}
1220
1221static int
1222compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 struct instr *i;
1225 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 assert(b != NULL);
1228 off = compiler_next_instr(c, c->u->u_curblock);
1229 if (off < 0)
1230 return 0;
1231 i = &c->u->u_curblock->b_instr[off];
1232 i->i_opcode = opcode;
1233 i->i_target = b;
1234 i->i_hasarg = 1;
1235 if (absolute)
1236 i->i_jabs = 1;
1237 else
1238 i->i_jrel = 1;
1239 compiler_set_lineno(c, off);
1240 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241}
1242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1244 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 it as the current block. NEXT_BLOCK() also creates an implicit jump
1246 from the current block to the new block.
1247*/
1248
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249/* The returns inside these macros make it impossible to decref objects
1250 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251*/
1252
1253
1254#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (compiler_use_new_block((C)) == NULL) \
1256 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (compiler_next_block((C)) == NULL) \
1261 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262}
1263
1264#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!compiler_addop((C), (OP))) \
1266 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001269#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!compiler_addop((C), (OP))) { \
1271 compiler_exit_scope(c); \
1272 return 0; \
1273 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001274}
1275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1278 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1283 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
1286#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!compiler_addop_i((C), (OP), (O))) \
1288 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289}
1290
1291#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (!compiler_addop_j((C), (OP), (O), 1)) \
1293 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294}
1295
1296#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (!compiler_addop_j((C), (OP), (O), 0)) \
1298 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299}
1300
1301/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1302 the ASDL name to synthesize the name of the C type and the visit function.
1303*/
1304
1305#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (!compiler_visit_ ## TYPE((C), (V))) \
1307 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308}
1309
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001310#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (!compiler_visit_ ## TYPE((C), (V))) { \
1312 compiler_exit_scope(c); \
1313 return 0; \
1314 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001315}
1316
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (!compiler_visit_slice((C), (V), (CTX))) \
1319 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320}
1321
1322#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 int _i; \
1324 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1325 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1326 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1327 if (!compiler_visit_ ## TYPE((C), elt)) \
1328 return 0; \
1329 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330}
1331
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001332#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 int _i; \
1334 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1335 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1336 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1337 if (!compiler_visit_ ## TYPE((C), elt)) { \
1338 compiler_exit_scope(c); \
1339 return 0; \
1340 } \
1341 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001342}
1343
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344static int
1345compiler_isdocstring(stmt_ty s)
1346{
1347 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001348 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 return s->v.Expr.value->kind == Str_kind;
1350}
1351
1352/* Compile a sequence of statements, checking for a docstring. */
1353
1354static int
1355compiler_body(struct compiler *c, asdl_seq *stmts)
1356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 int i = 0;
1358 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (!asdl_seq_LEN(stmts))
1361 return 1;
1362 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001363 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 /* don't generate docstrings if -OO */
1365 i = 1;
1366 VISIT(c, expr, st->v.Expr.value);
1367 if (!compiler_nameop(c, __doc__, Store))
1368 return 0;
1369 }
1370 for (; i < asdl_seq_LEN(stmts); i++)
1371 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373}
1374
1375static PyCodeObject *
1376compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 PyCodeObject *co;
1379 int addNone = 1;
1380 static PyObject *module;
1381 if (!module) {
1382 module = PyUnicode_InternFromString("<module>");
1383 if (!module)
1384 return NULL;
1385 }
1386 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001387 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 return NULL;
1389 switch (mod->kind) {
1390 case Module_kind:
1391 if (!compiler_body(c, mod->v.Module.body)) {
1392 compiler_exit_scope(c);
1393 return 0;
1394 }
1395 break;
1396 case Interactive_kind:
1397 c->c_interactive = 1;
1398 VISIT_SEQ_IN_SCOPE(c, stmt,
1399 mod->v.Interactive.body);
1400 break;
1401 case Expression_kind:
1402 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1403 addNone = 0;
1404 break;
1405 case Suite_kind:
1406 PyErr_SetString(PyExc_SystemError,
1407 "suite should not be possible");
1408 return 0;
1409 default:
1410 PyErr_Format(PyExc_SystemError,
1411 "module kind %d should not be possible",
1412 mod->kind);
1413 return 0;
1414 }
1415 co = assemble(c, addNone);
1416 compiler_exit_scope(c);
1417 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001418}
1419
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420/* The test for LOCAL must come before the test for FREE in order to
1421 handle classes where name is both local and free. The local var is
1422 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001423*/
1424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425static int
1426get_ref_type(struct compiler *c, PyObject *name)
1427{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001428 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001429 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1430 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1431 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001432 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (scope == 0) {
1434 char buf[350];
1435 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001436 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001438 PyUnicode_AsUTF8(name),
1439 PyUnicode_AsUTF8(c->u->u_name),
1440 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1441 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1442 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1443 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 );
1445 Py_FatalError(buf);
1446 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
1451static int
1452compiler_lookup_arg(PyObject *dict, PyObject *name)
1453{
1454 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001455 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001457 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001459 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001461 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001462 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463}
1464
1465static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001466compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001468 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001469 if (qualname == NULL)
1470 qualname = co->co_name;
1471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (free == 0) {
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_FUNCTION, args);
1476 return 1;
1477 }
1478 for (i = 0; i < free; ++i) {
1479 /* Bypass com_addop_varname because it will generate
1480 LOAD_DEREF but LOAD_CLOSURE is needed.
1481 */
1482 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1483 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 /* Special case: If a class contains a method with a
1486 free variable that has the same name as a method,
1487 the name will be considered free *and* local in the
1488 class. It should be handled by the closure, as
1489 well as by the normal name loookup logic.
1490 */
1491 reftype = get_ref_type(c, name);
1492 if (reftype == CELL)
1493 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1494 else /* (reftype == FREE) */
1495 arg = compiler_lookup_arg(c->u->u_freevars, name);
1496 if (arg == -1) {
1497 fprintf(stderr,
1498 "lookup %s in %s %d %d\n"
1499 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001500 PyUnicode_AsUTF8(PyObject_Repr(name)),
1501 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001503 PyUnicode_AsUTF8(co->co_name),
1504 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_FatalError("compiler_make_closure()");
1506 }
1507 ADDOP_I(c, LOAD_CLOSURE, arg);
1508 }
1509 ADDOP_I(c, BUILD_TUPLE, free);
1510 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001511 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 ADDOP_I(c, MAKE_CLOSURE, args);
1513 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514}
1515
1516static int
1517compiler_decorators(struct compiler *c, asdl_seq* decos)
1518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!decos)
1522 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1525 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1526 }
1527 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528}
1529
1530static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001531compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 int i, default_count = 0;
1535 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1536 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1537 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1538 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001539 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1540 if (!mangled)
1541 return -1;
1542 ADDOP_O(c, LOAD_CONST, mangled, consts);
1543 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if (!compiler_visit_expr(c, default_)) {
1545 return -1;
1546 }
1547 default_count++;
1548 }
1549 }
1550 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001551}
1552
1553static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001554compiler_visit_argannotation(struct compiler *c, identifier id,
1555 expr_ty annotation, PyObject *names)
1556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001558 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001560 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001561 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001562 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001563 if (PyList_Append(names, mangled) < 0) {
1564 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001565 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001566 }
1567 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001569 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001570}
1571
1572static int
1573compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1574 PyObject *names)
1575{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001576 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 for (i = 0; i < asdl_seq_LEN(args); i++) {
1578 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001579 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 c,
1581 arg->arg,
1582 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001583 names))
1584 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001586 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001587}
1588
1589static int
1590compiler_visit_annotations(struct compiler *c, arguments_ty args,
1591 expr_ty returns)
1592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* Push arg annotations and a list of the argument names. Return the #
1594 of items pushed. The expressions are evaluated out-of-order wrt the
1595 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1598 */
1599 static identifier return_str;
1600 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001601 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 names = PyList_New(0);
1603 if (!names)
1604 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001605
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001606 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001608 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001609 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001610 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001612 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001614 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001615 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001616 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (!return_str) {
1620 return_str = PyUnicode_InternFromString("return");
1621 if (!return_str)
1622 goto error;
1623 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001624 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 goto error;
1626 }
1627
1628 len = PyList_GET_SIZE(names);
1629 if (len > 65534) {
1630 /* len must fit in 16 bits, and len is incremented below */
1631 PyErr_SetString(PyExc_SyntaxError,
1632 "too many annotations");
1633 goto error;
1634 }
1635 if (len) {
1636 /* convert names to a tuple and place on stack */
1637 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001638 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 PyObject *s = PyTuple_New(len);
1640 if (!s)
1641 goto error;
1642 for (i = 0; i < len; i++) {
1643 elt = PyList_GET_ITEM(names, i);
1644 Py_INCREF(elt);
1645 PyTuple_SET_ITEM(s, i, elt);
1646 }
1647 ADDOP_O(c, LOAD_CONST, s, consts);
1648 Py_DECREF(s);
1649 len++; /* include the just-pushed tuple */
1650 }
1651 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001652
1653 /* We just checked that len <= 65535, see above */
1654 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001655
1656error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 Py_DECREF(names);
1658 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001659}
1660
1661static int
Yury Selivanov75445082015-05-11 22:57:16 -04001662compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001665 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001666 arguments_ty args;
1667 expr_ty returns;
1668 identifier name;
1669 asdl_seq* decos;
1670 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001672 Py_ssize_t i, n, arglength;
1673 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001675 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676
Yury Selivanov75445082015-05-11 22:57:16 -04001677
1678 if (is_async) {
1679 assert(s->kind == AsyncFunctionDef_kind);
1680
1681 args = s->v.AsyncFunctionDef.args;
1682 returns = s->v.AsyncFunctionDef.returns;
1683 decos = s->v.AsyncFunctionDef.decorator_list;
1684 name = s->v.AsyncFunctionDef.name;
1685 body = s->v.AsyncFunctionDef.body;
1686
1687 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1688 } else {
1689 assert(s->kind == FunctionDef_kind);
1690
1691 args = s->v.FunctionDef.args;
1692 returns = s->v.FunctionDef.returns;
1693 decos = s->v.FunctionDef.decorator_list;
1694 name = s->v.FunctionDef.name;
1695 body = s->v.FunctionDef.body;
1696
1697 scope_type = COMPILER_SCOPE_FUNCTION;
1698 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 if (!compiler_decorators(c, decos))
1701 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001702 if (args->defaults)
1703 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (args->kwonlyargs) {
1705 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1706 args->kw_defaults);
1707 if (res < 0)
1708 return 0;
1709 kw_default_count = res;
1710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 num_annotations = compiler_visit_annotations(c, args, returns);
1712 if (num_annotations < 0)
1713 return 0;
1714 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001715
Yury Selivanov75445082015-05-11 22:57:16 -04001716 if (!compiler_enter_scope(c, name,
1717 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 s->lineno))
1719 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720
Yury Selivanov75445082015-05-11 22:57:16 -04001721 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001723 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 first_const = st->v.Expr.value->v.Str.s;
1725 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1726 compiler_exit_scope(c);
1727 return 0;
1728 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 c->u->u_argcount = asdl_seq_LEN(args->args);
1731 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001732 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* if there was a docstring, we need to skip the first statement */
1734 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001735 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 VISIT_IN_SCOPE(c, stmt, st);
1737 }
1738 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001739 qualname = c->u->u_qualname;
1740 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001742 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001743 Py_XDECREF(qualname);
1744 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001746 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 arglength = asdl_seq_LEN(args->defaults);
1749 arglength |= kw_default_count << 8;
1750 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001751 if (is_async)
1752 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001753 compiler_make_closure(c, co, arglength, qualname);
1754 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* decorators */
1758 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1759 ADDOP_I(c, CALL_FUNCTION, 1);
1760 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761
Yury Selivanov75445082015-05-11 22:57:16 -04001762 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763}
1764
1765static int
1766compiler_class(struct compiler *c, stmt_ty s)
1767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 PyCodeObject *co;
1769 PyObject *str;
1770 int i;
1771 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 if (!compiler_decorators(c, decos))
1774 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* ultimately generate code for:
1777 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1778 where:
1779 <func> is a function/closure created from the class body;
1780 it has a single argument (__locals__) where the dict
1781 (or MutableSequence) representing the locals is passed
1782 <name> is the class name
1783 <bases> is the positional arguments and *varargs argument
1784 <keywords> is the keyword arguments and **kwds argument
1785 This borrows from compiler_call.
1786 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001789 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1790 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return 0;
1792 /* this block represents what we do in the new scope */
1793 {
1794 /* use the class name for name mangling */
1795 Py_INCREF(s->v.ClassDef.name);
1796 Py_XDECREF(c->u->u_private);
1797 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* load (global) __name__ ... */
1799 str = PyUnicode_InternFromString("__name__");
1800 if (!str || !compiler_nameop(c, str, Load)) {
1801 Py_XDECREF(str);
1802 compiler_exit_scope(c);
1803 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 Py_DECREF(str);
1806 /* ... and store it as __module__ */
1807 str = PyUnicode_InternFromString("__module__");
1808 if (!str || !compiler_nameop(c, str, Store)) {
1809 Py_XDECREF(str);
1810 compiler_exit_scope(c);
1811 return 0;
1812 }
1813 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001814 assert(c->u->u_qualname);
1815 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001816 str = PyUnicode_InternFromString("__qualname__");
1817 if (!str || !compiler_nameop(c, str, Store)) {
1818 Py_XDECREF(str);
1819 compiler_exit_scope(c);
1820 return 0;
1821 }
1822 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 /* compile the body proper */
1824 if (!compiler_body(c, s->v.ClassDef.body)) {
1825 compiler_exit_scope(c);
1826 return 0;
1827 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001828 if (c->u->u_ste->ste_needs_class_closure) {
1829 /* return the (empty) __class__ cell */
1830 str = PyUnicode_InternFromString("__class__");
1831 if (str == NULL) {
1832 compiler_exit_scope(c);
1833 return 0;
1834 }
1835 i = compiler_lookup_arg(c->u->u_cellvars, str);
1836 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001837 if (i < 0) {
1838 compiler_exit_scope(c);
1839 return 0;
1840 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001841 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 /* Return the cell where to store __class__ */
1843 ADDOP_I(c, LOAD_CLOSURE, i);
1844 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001845 else {
1846 assert(PyDict_Size(c->u->u_cellvars) == 0);
1847 /* This happens when nobody references the cell. Return None. */
1848 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1851 /* create the code object */
1852 co = assemble(c, 1);
1853 }
1854 /* leave the new scope */
1855 compiler_exit_scope(c);
1856 if (co == NULL)
1857 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* 2. load the 'build_class' function */
1860 ADDOP(c, LOAD_BUILD_CLASS);
1861
1862 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001863 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 Py_DECREF(co);
1865
1866 /* 4. load class name */
1867 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1868
1869 /* 5. generate the rest of the code for the call */
1870 if (!compiler_call_helper(c, 2,
1871 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001872 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 return 0;
1874
1875 /* 6. apply decorators */
1876 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1877 ADDOP_I(c, CALL_FUNCTION, 1);
1878 }
1879
1880 /* 7. store into <name> */
1881 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1882 return 0;
1883 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884}
1885
1886static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001887compiler_ifexp(struct compiler *c, expr_ty e)
1888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 basicblock *end, *next;
1890
1891 assert(e->kind == IfExp_kind);
1892 end = compiler_new_block(c);
1893 if (end == NULL)
1894 return 0;
1895 next = compiler_new_block(c);
1896 if (next == NULL)
1897 return 0;
1898 VISIT(c, expr, e->v.IfExp.test);
1899 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1900 VISIT(c, expr, e->v.IfExp.body);
1901 ADDOP_JREL(c, JUMP_FORWARD, end);
1902 compiler_use_next_block(c, next);
1903 VISIT(c, expr, e->v.IfExp.orelse);
1904 compiler_use_next_block(c, end);
1905 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001906}
1907
1908static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909compiler_lambda(struct compiler *c, expr_ty e)
1910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001912 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001914 int kw_default_count = 0;
1915 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 arguments_ty args = e->v.Lambda.args;
1917 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (!name) {
1920 name = PyUnicode_InternFromString("<lambda>");
1921 if (!name)
1922 return 0;
1923 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001925 if (args->defaults)
1926 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 if (args->kwonlyargs) {
1928 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1929 args->kw_defaults);
1930 if (res < 0) return 0;
1931 kw_default_count = res;
1932 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001933 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001934 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 /* Make None the first constant, so the lambda can't have a
1938 docstring. */
1939 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1940 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 c->u->u_argcount = asdl_seq_LEN(args->args);
1943 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1944 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1945 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001946 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 }
1948 else {
1949 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001950 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001952 qualname = c->u->u_qualname;
1953 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001955 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 arglength = asdl_seq_LEN(args->defaults);
1959 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001960 compiler_make_closure(c, co, arglength, qualname);
1961 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 Py_DECREF(co);
1963
1964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965}
1966
1967static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968compiler_if(struct compiler *c, stmt_ty s)
1969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 basicblock *end, *next;
1971 int constant;
1972 assert(s->kind == If_kind);
1973 end = compiler_new_block(c);
1974 if (end == NULL)
1975 return 0;
1976
Georg Brandl8334fd92010-12-04 10:26:46 +00001977 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* constant = 0: "if 0"
1979 * constant = 1: "if 1", "if 2", ...
1980 * constant = -1: rest */
1981 if (constant == 0) {
1982 if (s->v.If.orelse)
1983 VISIT_SEQ(c, stmt, s->v.If.orelse);
1984 } else if (constant == 1) {
1985 VISIT_SEQ(c, stmt, s->v.If.body);
1986 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001987 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 next = compiler_new_block(c);
1989 if (next == NULL)
1990 return 0;
1991 }
1992 else
1993 next = end;
1994 VISIT(c, expr, s->v.If.test);
1995 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1996 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001997 if (asdl_seq_LEN(s->v.If.orelse)) {
1998 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 compiler_use_next_block(c, next);
2000 VISIT_SEQ(c, stmt, s->v.If.orelse);
2001 }
2002 }
2003 compiler_use_next_block(c, end);
2004 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005}
2006
2007static int
2008compiler_for(struct compiler *c, stmt_ty s)
2009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 start = compiler_new_block(c);
2013 cleanup = compiler_new_block(c);
2014 end = compiler_new_block(c);
2015 if (start == NULL || end == NULL || cleanup == NULL)
2016 return 0;
2017 ADDOP_JREL(c, SETUP_LOOP, end);
2018 if (!compiler_push_fblock(c, LOOP, start))
2019 return 0;
2020 VISIT(c, expr, s->v.For.iter);
2021 ADDOP(c, GET_ITER);
2022 compiler_use_next_block(c, start);
2023 ADDOP_JREL(c, FOR_ITER, cleanup);
2024 VISIT(c, expr, s->v.For.target);
2025 VISIT_SEQ(c, stmt, s->v.For.body);
2026 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2027 compiler_use_next_block(c, cleanup);
2028 ADDOP(c, POP_BLOCK);
2029 compiler_pop_fblock(c, LOOP, start);
2030 VISIT_SEQ(c, stmt, s->v.For.orelse);
2031 compiler_use_next_block(c, end);
2032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033}
2034
Yury Selivanov75445082015-05-11 22:57:16 -04002035
2036static int
2037compiler_async_for(struct compiler *c, stmt_ty s)
2038{
2039 static PyObject *stopiter_error = NULL;
2040 basicblock *try, *except, *end, *after_try, *try_cleanup,
2041 *after_loop, *after_loop_else;
2042
2043 if (stopiter_error == NULL) {
2044 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2045 if (stopiter_error == NULL)
2046 return 0;
2047 }
2048
2049 try = compiler_new_block(c);
2050 except = compiler_new_block(c);
2051 end = compiler_new_block(c);
2052 after_try = compiler_new_block(c);
2053 try_cleanup = compiler_new_block(c);
2054 after_loop = compiler_new_block(c);
2055 after_loop_else = compiler_new_block(c);
2056
2057 if (try == NULL || except == NULL || end == NULL
2058 || after_try == NULL || try_cleanup == NULL)
2059 return 0;
2060
2061 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2062 if (!compiler_push_fblock(c, LOOP, try))
2063 return 0;
2064
2065 VISIT(c, expr, s->v.AsyncFor.iter);
2066 ADDOP(c, GET_AITER);
2067 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2068 ADDOP(c, YIELD_FROM);
2069
2070 compiler_use_next_block(c, try);
2071
2072
2073 ADDOP_JREL(c, SETUP_EXCEPT, except);
2074 if (!compiler_push_fblock(c, EXCEPT, try))
2075 return 0;
2076
2077 ADDOP(c, GET_ANEXT);
2078 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2079 ADDOP(c, YIELD_FROM);
2080 VISIT(c, expr, s->v.AsyncFor.target);
2081 ADDOP(c, POP_BLOCK);
2082 compiler_pop_fblock(c, EXCEPT, try);
2083 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2084
2085
2086 compiler_use_next_block(c, except);
2087 ADDOP(c, DUP_TOP);
2088 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2089 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2090 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2091
2092 ADDOP(c, POP_TOP);
2093 ADDOP(c, POP_TOP);
2094 ADDOP(c, POP_TOP);
2095 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2096 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2097 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2098
2099
2100 compiler_use_next_block(c, try_cleanup);
2101 ADDOP(c, END_FINALLY);
2102
2103 compiler_use_next_block(c, after_try);
2104 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2105 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2106
2107 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2108 compiler_pop_fblock(c, LOOP, try);
2109
2110 compiler_use_next_block(c, after_loop);
2111 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2112
2113 compiler_use_next_block(c, after_loop_else);
2114 VISIT_SEQ(c, stmt, s->v.For.orelse);
2115
2116 compiler_use_next_block(c, end);
2117
2118 return 1;
2119}
2120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121static int
2122compiler_while(struct compiler *c, stmt_ty s)
2123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002125 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (constant == 0) {
2128 if (s->v.While.orelse)
2129 VISIT_SEQ(c, stmt, s->v.While.orelse);
2130 return 1;
2131 }
2132 loop = compiler_new_block(c);
2133 end = compiler_new_block(c);
2134 if (constant == -1) {
2135 anchor = compiler_new_block(c);
2136 if (anchor == NULL)
2137 return 0;
2138 }
2139 if (loop == NULL || end == NULL)
2140 return 0;
2141 if (s->v.While.orelse) {
2142 orelse = compiler_new_block(c);
2143 if (orelse == NULL)
2144 return 0;
2145 }
2146 else
2147 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 ADDOP_JREL(c, SETUP_LOOP, end);
2150 compiler_use_next_block(c, loop);
2151 if (!compiler_push_fblock(c, LOOP, loop))
2152 return 0;
2153 if (constant == -1) {
2154 VISIT(c, expr, s->v.While.test);
2155 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2156 }
2157 VISIT_SEQ(c, stmt, s->v.While.body);
2158 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* XXX should the two POP instructions be in a separate block
2161 if there is no else clause ?
2162 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002164 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002166 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 compiler_pop_fblock(c, LOOP, loop);
2168 if (orelse != NULL) /* what if orelse is just pass? */
2169 VISIT_SEQ(c, stmt, s->v.While.orelse);
2170 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173}
2174
2175static int
2176compiler_continue(struct compiler *c)
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2179 static const char IN_FINALLY_ERROR_MSG[] =
2180 "'continue' not supported inside 'finally' clause";
2181 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (!c->u->u_nfblocks)
2184 return compiler_error(c, LOOP_ERROR_MSG);
2185 i = c->u->u_nfblocks - 1;
2186 switch (c->u->u_fblock[i].fb_type) {
2187 case LOOP:
2188 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2189 break;
2190 case EXCEPT:
2191 case FINALLY_TRY:
2192 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2193 /* Prevent continue anywhere under a finally
2194 even if hidden in a sub-try or except. */
2195 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2196 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2197 }
2198 if (i == -1)
2199 return compiler_error(c, LOOP_ERROR_MSG);
2200 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2201 break;
2202 case FINALLY_END:
2203 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2204 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207}
2208
2209/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210
2211 SETUP_FINALLY L
2212 <code for body>
2213 POP_BLOCK
2214 LOAD_CONST <None>
2215 L: <code for finalbody>
2216 END_FINALLY
2217
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218 The special instructions use the block stack. Each block
2219 stack entry contains the instruction that created it (here
2220 SETUP_FINALLY), the level of the value stack at the time the
2221 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 Pushes the current value stack level and the label
2225 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 Pops en entry from the block stack, and pops the value
2228 stack until its level is the same as indicated on the
2229 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002230 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 Pops a variable number of entries from the *value* stack
2232 and re-raises the exception they specify. The number of
2233 entries popped depends on the (pseudo) exception type.
2234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235 The block stack is unwound when an exception is raised:
2236 when a SETUP_FINALLY entry is found, the exception is pushed
2237 onto the value stack (and the exception condition is cleared),
2238 and the interpreter jumps to the label gotten from the block
2239 stack.
2240*/
2241
2242static int
2243compiler_try_finally(struct compiler *c, stmt_ty s)
2244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 basicblock *body, *end;
2246 body = compiler_new_block(c);
2247 end = compiler_new_block(c);
2248 if (body == NULL || end == NULL)
2249 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 ADDOP_JREL(c, SETUP_FINALLY, end);
2252 compiler_use_next_block(c, body);
2253 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2254 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002255 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2256 if (!compiler_try_except(c, s))
2257 return 0;
2258 }
2259 else {
2260 VISIT_SEQ(c, stmt, s->v.Try.body);
2261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 ADDOP(c, POP_BLOCK);
2263 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2266 compiler_use_next_block(c, end);
2267 if (!compiler_push_fblock(c, FINALLY_END, end))
2268 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002269 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 ADDOP(c, END_FINALLY);
2271 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274}
2275
2276/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002277 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 (The contents of the value stack is shown in [], with the top
2279 at the right; 'tb' is trace-back info, 'val' the exception's
2280 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281
2282 Value stack Label Instruction Argument
2283 [] SETUP_EXCEPT L1
2284 [] <code for S>
2285 [] POP_BLOCK
2286 [] JUMP_FORWARD L0
2287
2288 [tb, val, exc] L1: DUP )
2289 [tb, val, exc, exc] <evaluate E1> )
2290 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2291 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2292 [tb, val, exc] POP
2293 [tb, val] <assign to V1> (or POP if no V1)
2294 [tb] POP
2295 [] <code for S1>
2296 JUMP_FORWARD L0
2297
2298 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299 .............................etc.......................
2300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2302
2303 [] L0: <next statement>
2304
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 Of course, parts are not generated if Vi or Ei is not present.
2306*/
2307static int
2308compiler_try_except(struct compiler *c, stmt_ty s)
2309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002311 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 body = compiler_new_block(c);
2314 except = compiler_new_block(c);
2315 orelse = compiler_new_block(c);
2316 end = compiler_new_block(c);
2317 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2318 return 0;
2319 ADDOP_JREL(c, SETUP_EXCEPT, except);
2320 compiler_use_next_block(c, body);
2321 if (!compiler_push_fblock(c, EXCEPT, body))
2322 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002323 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 ADDOP(c, POP_BLOCK);
2325 compiler_pop_fblock(c, EXCEPT, body);
2326 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002327 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 compiler_use_next_block(c, except);
2329 for (i = 0; i < n; i++) {
2330 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002331 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (!handler->v.ExceptHandler.type && i < n-1)
2333 return compiler_error(c, "default 'except:' must be last");
2334 c->u->u_lineno_set = 0;
2335 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002336 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 except = compiler_new_block(c);
2338 if (except == NULL)
2339 return 0;
2340 if (handler->v.ExceptHandler.type) {
2341 ADDOP(c, DUP_TOP);
2342 VISIT(c, expr, handler->v.ExceptHandler.type);
2343 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2344 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2345 }
2346 ADDOP(c, POP_TOP);
2347 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002348 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002349
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002350 cleanup_end = compiler_new_block(c);
2351 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002352 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002353 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002354
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002355 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2356 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002358 /*
2359 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002360 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002361 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002362 try:
2363 # body
2364 finally:
2365 name = None
2366 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002367 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002369 /* second try: */
2370 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2371 compiler_use_next_block(c, cleanup_body);
2372 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2373 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002375 /* second # body */
2376 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2377 ADDOP(c, POP_BLOCK);
2378 ADDOP(c, POP_EXCEPT);
2379 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002381 /* finally: */
2382 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2383 compiler_use_next_block(c, cleanup_end);
2384 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2385 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002387 /* name = None */
2388 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2389 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002391 /* del name */
2392 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002394 ADDOP(c, END_FINALLY);
2395 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 }
2397 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002398 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002400 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002401 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002402 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403
Guido van Rossumb940e112007-01-10 16:19:56 +00002404 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002405 ADDOP(c, POP_TOP);
2406 compiler_use_next_block(c, cleanup_body);
2407 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2408 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002410 ADDOP(c, POP_EXCEPT);
2411 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 }
2413 ADDOP_JREL(c, JUMP_FORWARD, end);
2414 compiler_use_next_block(c, except);
2415 }
2416 ADDOP(c, END_FINALLY);
2417 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002418 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 compiler_use_next_block(c, end);
2420 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421}
2422
2423static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002424compiler_try(struct compiler *c, stmt_ty s) {
2425 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2426 return compiler_try_finally(c, s);
2427 else
2428 return compiler_try_except(c, s);
2429}
2430
2431
2432static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433compiler_import_as(struct compiler *c, identifier name, identifier asname)
2434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* The IMPORT_NAME opcode was already generated. This function
2436 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 If there is a dot in name, we need to split it and emit a
2439 LOAD_ATTR for each name.
2440 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002441 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2442 PyUnicode_GET_LENGTH(name), 1);
2443 if (dot == -2)
2444 return -1;
2445 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002447 Py_ssize_t pos = dot + 1;
2448 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 dot = PyUnicode_FindChar(name, '.', pos,
2451 PyUnicode_GET_LENGTH(name), 1);
2452 if (dot == -2)
2453 return -1;
2454 attr = PyUnicode_Substring(name, pos,
2455 (dot != -1) ? dot :
2456 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 if (!attr)
2458 return -1;
2459 ADDOP_O(c, LOAD_ATTR, attr, names);
2460 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 }
2463 }
2464 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465}
2466
2467static int
2468compiler_import(struct compiler *c, stmt_ty s)
2469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* The Import node stores a module name like a.b.c as a single
2471 string. This is convenient for all cases except
2472 import a.b.c as d
2473 where we need to parse that string to extract the individual
2474 module names.
2475 XXX Perhaps change the representation to make this case simpler?
2476 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002477 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 for (i = 0; i < n; i++) {
2480 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2481 int r;
2482 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 level = PyLong_FromLong(0);
2485 if (level == NULL)
2486 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 ADDOP_O(c, LOAD_CONST, level, consts);
2489 Py_DECREF(level);
2490 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2491 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 if (alias->asname) {
2494 r = compiler_import_as(c, alias->name, alias->asname);
2495 if (!r)
2496 return r;
2497 }
2498 else {
2499 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 Py_ssize_t dot = PyUnicode_FindChar(
2501 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002502 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002504 if (tmp == NULL)
2505 return 0;
2506 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 Py_DECREF(tmp);
2510 }
2511 if (!r)
2512 return r;
2513 }
2514 }
2515 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516}
2517
2518static int
2519compiler_from_import(struct compiler *c, stmt_ty s)
2520{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002521 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyObject *names = PyTuple_New(n);
2524 PyObject *level;
2525 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 if (!empty_string) {
2528 empty_string = PyUnicode_FromString("");
2529 if (!empty_string)
2530 return 0;
2531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (!names)
2534 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 level = PyLong_FromLong(s->v.ImportFrom.level);
2537 if (!level) {
2538 Py_DECREF(names);
2539 return 0;
2540 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* build up the names */
2543 for (i = 0; i < n; i++) {
2544 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2545 Py_INCREF(alias->name);
2546 PyTuple_SET_ITEM(names, i, alias->name);
2547 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2550 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2551 Py_DECREF(level);
2552 Py_DECREF(names);
2553 return compiler_error(c, "from __future__ imports must occur "
2554 "at the beginning of the file");
2555 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 ADDOP_O(c, LOAD_CONST, level, consts);
2558 Py_DECREF(level);
2559 ADDOP_O(c, LOAD_CONST, names, consts);
2560 Py_DECREF(names);
2561 if (s->v.ImportFrom.module) {
2562 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2563 }
2564 else {
2565 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2566 }
2567 for (i = 0; i < n; i++) {
2568 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2569 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002571 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 assert(n == 1);
2573 ADDOP(c, IMPORT_STAR);
2574 return 1;
2575 }
2576
2577 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2578 store_name = alias->name;
2579 if (alias->asname)
2580 store_name = alias->asname;
2581
2582 if (!compiler_nameop(c, store_name, Store)) {
2583 Py_DECREF(names);
2584 return 0;
2585 }
2586 }
2587 /* remove imported module */
2588 ADDOP(c, POP_TOP);
2589 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590}
2591
2592static int
2593compiler_assert(struct compiler *c, stmt_ty s)
2594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 static PyObject *assertion_error = NULL;
2596 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002597 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598
Georg Brandl8334fd92010-12-04 10:26:46 +00002599 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 return 1;
2601 if (assertion_error == NULL) {
2602 assertion_error = PyUnicode_InternFromString("AssertionError");
2603 if (assertion_error == NULL)
2604 return 0;
2605 }
2606 if (s->v.Assert.test->kind == Tuple_kind &&
2607 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002608 msg = PyUnicode_FromString("assertion is always true, "
2609 "perhaps remove parentheses?");
2610 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002612 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2613 c->c_filename, c->u->u_lineno,
2614 NULL, NULL) == -1) {
2615 Py_DECREF(msg);
2616 return 0;
2617 }
2618 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 }
2620 VISIT(c, expr, s->v.Assert.test);
2621 end = compiler_new_block(c);
2622 if (end == NULL)
2623 return 0;
2624 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2625 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2626 if (s->v.Assert.msg) {
2627 VISIT(c, expr, s->v.Assert.msg);
2628 ADDOP_I(c, CALL_FUNCTION, 1);
2629 }
2630 ADDOP_I(c, RAISE_VARARGS, 1);
2631 compiler_use_next_block(c, end);
2632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633}
2634
2635static int
2636compiler_visit_stmt(struct compiler *c, stmt_ty s)
2637{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002638 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 /* Always assign a lineno to the next instruction for a stmt. */
2641 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002642 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 switch (s->kind) {
2646 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002647 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 case ClassDef_kind:
2649 return compiler_class(c, s);
2650 case Return_kind:
2651 if (c->u->u_ste->ste_type != FunctionBlock)
2652 return compiler_error(c, "'return' outside function");
2653 if (s->v.Return.value) {
2654 VISIT(c, expr, s->v.Return.value);
2655 }
2656 else
2657 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2658 ADDOP(c, RETURN_VALUE);
2659 break;
2660 case Delete_kind:
2661 VISIT_SEQ(c, expr, s->v.Delete.targets)
2662 break;
2663 case Assign_kind:
2664 n = asdl_seq_LEN(s->v.Assign.targets);
2665 VISIT(c, expr, s->v.Assign.value);
2666 for (i = 0; i < n; i++) {
2667 if (i < n - 1)
2668 ADDOP(c, DUP_TOP);
2669 VISIT(c, expr,
2670 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2671 }
2672 break;
2673 case AugAssign_kind:
2674 return compiler_augassign(c, s);
2675 case For_kind:
2676 return compiler_for(c, s);
2677 case While_kind:
2678 return compiler_while(c, s);
2679 case If_kind:
2680 return compiler_if(c, s);
2681 case Raise_kind:
2682 n = 0;
2683 if (s->v.Raise.exc) {
2684 VISIT(c, expr, s->v.Raise.exc);
2685 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002686 if (s->v.Raise.cause) {
2687 VISIT(c, expr, s->v.Raise.cause);
2688 n++;
2689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002691 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002693 case Try_kind:
2694 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 case Assert_kind:
2696 return compiler_assert(c, s);
2697 case Import_kind:
2698 return compiler_import(c, s);
2699 case ImportFrom_kind:
2700 return compiler_from_import(c, s);
2701 case Global_kind:
2702 case Nonlocal_kind:
2703 break;
2704 case Expr_kind:
2705 if (c->c_interactive && c->c_nestlevel <= 1) {
2706 VISIT(c, expr, s->v.Expr.value);
2707 ADDOP(c, PRINT_EXPR);
2708 }
2709 else if (s->v.Expr.value->kind != Str_kind &&
2710 s->v.Expr.value->kind != Num_kind) {
2711 VISIT(c, expr, s->v.Expr.value);
2712 ADDOP(c, POP_TOP);
2713 }
2714 break;
2715 case Pass_kind:
2716 break;
2717 case Break_kind:
2718 if (!compiler_in_loop(c))
2719 return compiler_error(c, "'break' outside loop");
2720 ADDOP(c, BREAK_LOOP);
2721 break;
2722 case Continue_kind:
2723 return compiler_continue(c);
2724 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002725 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002726 case AsyncFunctionDef_kind:
2727 return compiler_function(c, s, 1);
2728 case AsyncWith_kind:
2729 return compiler_async_with(c, s, 0);
2730 case AsyncFor_kind:
2731 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 }
Yury Selivanov75445082015-05-11 22:57:16 -04002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735}
2736
2737static int
2738unaryop(unaryop_ty op)
2739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 switch (op) {
2741 case Invert:
2742 return UNARY_INVERT;
2743 case Not:
2744 return UNARY_NOT;
2745 case UAdd:
2746 return UNARY_POSITIVE;
2747 case USub:
2748 return UNARY_NEGATIVE;
2749 default:
2750 PyErr_Format(PyExc_SystemError,
2751 "unary op %d should not be possible", op);
2752 return 0;
2753 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754}
2755
2756static int
2757binop(struct compiler *c, operator_ty op)
2758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 switch (op) {
2760 case Add:
2761 return BINARY_ADD;
2762 case Sub:
2763 return BINARY_SUBTRACT;
2764 case Mult:
2765 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002766 case MatMult:
2767 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 case Div:
2769 return BINARY_TRUE_DIVIDE;
2770 case Mod:
2771 return BINARY_MODULO;
2772 case Pow:
2773 return BINARY_POWER;
2774 case LShift:
2775 return BINARY_LSHIFT;
2776 case RShift:
2777 return BINARY_RSHIFT;
2778 case BitOr:
2779 return BINARY_OR;
2780 case BitXor:
2781 return BINARY_XOR;
2782 case BitAnd:
2783 return BINARY_AND;
2784 case FloorDiv:
2785 return BINARY_FLOOR_DIVIDE;
2786 default:
2787 PyErr_Format(PyExc_SystemError,
2788 "binary op %d should not be possible", op);
2789 return 0;
2790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791}
2792
2793static int
2794cmpop(cmpop_ty op)
2795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 switch (op) {
2797 case Eq:
2798 return PyCmp_EQ;
2799 case NotEq:
2800 return PyCmp_NE;
2801 case Lt:
2802 return PyCmp_LT;
2803 case LtE:
2804 return PyCmp_LE;
2805 case Gt:
2806 return PyCmp_GT;
2807 case GtE:
2808 return PyCmp_GE;
2809 case Is:
2810 return PyCmp_IS;
2811 case IsNot:
2812 return PyCmp_IS_NOT;
2813 case In:
2814 return PyCmp_IN;
2815 case NotIn:
2816 return PyCmp_NOT_IN;
2817 default:
2818 return PyCmp_BAD;
2819 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820}
2821
2822static int
2823inplace_binop(struct compiler *c, operator_ty op)
2824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 switch (op) {
2826 case Add:
2827 return INPLACE_ADD;
2828 case Sub:
2829 return INPLACE_SUBTRACT;
2830 case Mult:
2831 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002832 case MatMult:
2833 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 case Div:
2835 return INPLACE_TRUE_DIVIDE;
2836 case Mod:
2837 return INPLACE_MODULO;
2838 case Pow:
2839 return INPLACE_POWER;
2840 case LShift:
2841 return INPLACE_LSHIFT;
2842 case RShift:
2843 return INPLACE_RSHIFT;
2844 case BitOr:
2845 return INPLACE_OR;
2846 case BitXor:
2847 return INPLACE_XOR;
2848 case BitAnd:
2849 return INPLACE_AND;
2850 case FloorDiv:
2851 return INPLACE_FLOOR_DIVIDE;
2852 default:
2853 PyErr_Format(PyExc_SystemError,
2854 "inplace binary op %d should not be possible", op);
2855 return 0;
2856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857}
2858
2859static int
2860compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2861{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002862 int op, scope;
2863 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 PyObject *dict = c->u->u_names;
2867 PyObject *mangled;
2868 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 mangled = _Py_Mangle(c->u->u_private, name);
2871 if (!mangled)
2872 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002873
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002874 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2875 PyUnicode_CompareWithASCIIString(name, "True") &&
2876 PyUnicode_CompareWithASCIIString(name, "False"));
2877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 op = 0;
2879 optype = OP_NAME;
2880 scope = PyST_GetScope(c->u->u_ste, mangled);
2881 switch (scope) {
2882 case FREE:
2883 dict = c->u->u_freevars;
2884 optype = OP_DEREF;
2885 break;
2886 case CELL:
2887 dict = c->u->u_cellvars;
2888 optype = OP_DEREF;
2889 break;
2890 case LOCAL:
2891 if (c->u->u_ste->ste_type == FunctionBlock)
2892 optype = OP_FAST;
2893 break;
2894 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002895 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 optype = OP_GLOBAL;
2897 break;
2898 case GLOBAL_EXPLICIT:
2899 optype = OP_GLOBAL;
2900 break;
2901 default:
2902 /* scope can be 0 */
2903 break;
2904 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002907 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 switch (optype) {
2910 case OP_DEREF:
2911 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002912 case Load:
2913 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2914 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 case Store: op = STORE_DEREF; break;
2916 case AugLoad:
2917 case AugStore:
2918 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002919 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 case Param:
2921 default:
2922 PyErr_SetString(PyExc_SystemError,
2923 "param invalid for deref variable");
2924 return 0;
2925 }
2926 break;
2927 case OP_FAST:
2928 switch (ctx) {
2929 case Load: op = LOAD_FAST; break;
2930 case Store: op = STORE_FAST; break;
2931 case Del: op = DELETE_FAST; break;
2932 case AugLoad:
2933 case AugStore:
2934 break;
2935 case Param:
2936 default:
2937 PyErr_SetString(PyExc_SystemError,
2938 "param invalid for local variable");
2939 return 0;
2940 }
2941 ADDOP_O(c, op, mangled, varnames);
2942 Py_DECREF(mangled);
2943 return 1;
2944 case OP_GLOBAL:
2945 switch (ctx) {
2946 case Load: op = LOAD_GLOBAL; break;
2947 case Store: op = STORE_GLOBAL; break;
2948 case Del: op = DELETE_GLOBAL; break;
2949 case AugLoad:
2950 case AugStore:
2951 break;
2952 case Param:
2953 default:
2954 PyErr_SetString(PyExc_SystemError,
2955 "param invalid for global variable");
2956 return 0;
2957 }
2958 break;
2959 case OP_NAME:
2960 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002961 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 case Store: op = STORE_NAME; break;
2963 case Del: op = DELETE_NAME; break;
2964 case AugLoad:
2965 case AugStore:
2966 break;
2967 case Param:
2968 default:
2969 PyErr_SetString(PyExc_SystemError,
2970 "param invalid for name variable");
2971 return 0;
2972 }
2973 break;
2974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 assert(op);
2977 arg = compiler_add_o(c, dict, mangled);
2978 Py_DECREF(mangled);
2979 if (arg < 0)
2980 return 0;
2981 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982}
2983
2984static int
2985compiler_boolop(struct compiler *c, expr_ty e)
2986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002988 int jumpi;
2989 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 assert(e->kind == BoolOp_kind);
2993 if (e->v.BoolOp.op == And)
2994 jumpi = JUMP_IF_FALSE_OR_POP;
2995 else
2996 jumpi = JUMP_IF_TRUE_OR_POP;
2997 end = compiler_new_block(c);
2998 if (end == NULL)
2999 return 0;
3000 s = e->v.BoolOp.values;
3001 n = asdl_seq_LEN(s) - 1;
3002 assert(n >= 0);
3003 for (i = 0; i < n; ++i) {
3004 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3005 ADDOP_JABS(c, jumpi, end);
3006 }
3007 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3008 compiler_use_next_block(c, end);
3009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010}
3011
3012static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003013starunpack_helper(struct compiler *c, asdl_seq *elts,
3014 int single_op, int inner_op, int outer_op)
3015{
3016 Py_ssize_t n = asdl_seq_LEN(elts);
3017 Py_ssize_t i, nsubitems = 0, nseen = 0;
3018 for (i = 0; i < n; i++) {
3019 expr_ty elt = asdl_seq_GET(elts, i);
3020 if (elt->kind == Starred_kind) {
3021 if (nseen) {
3022 ADDOP_I(c, inner_op, nseen);
3023 nseen = 0;
3024 nsubitems++;
3025 }
3026 VISIT(c, expr, elt->v.Starred.value);
3027 nsubitems++;
3028 }
3029 else {
3030 VISIT(c, expr, elt);
3031 nseen++;
3032 }
3033 }
3034 if (nsubitems) {
3035 if (nseen) {
3036 ADDOP_I(c, inner_op, nseen);
3037 nsubitems++;
3038 }
3039 ADDOP_I(c, outer_op, nsubitems);
3040 }
3041 else
3042 ADDOP_I(c, single_op, nseen);
3043 return 1;
3044}
3045
3046static int
3047assignment_helper(struct compiler *c, asdl_seq *elts)
3048{
3049 Py_ssize_t n = asdl_seq_LEN(elts);
3050 Py_ssize_t i;
3051 int seen_star = 0;
3052 for (i = 0; i < n; i++) {
3053 expr_ty elt = asdl_seq_GET(elts, i);
3054 if (elt->kind == Starred_kind && !seen_star) {
3055 if ((i >= (1 << 8)) ||
3056 (n-i-1 >= (INT_MAX >> 8)))
3057 return compiler_error(c,
3058 "too many expressions in "
3059 "star-unpacking assignment");
3060 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3061 seen_star = 1;
3062 asdl_seq_SET(elts, i, elt->v.Starred.value);
3063 }
3064 else if (elt->kind == Starred_kind) {
3065 return compiler_error(c,
3066 "two starred expressions in assignment");
3067 }
3068 }
3069 if (!seen_star) {
3070 ADDOP_I(c, UNPACK_SEQUENCE, n);
3071 }
3072 VISIT_SEQ(c, expr, elts);
3073 return 1;
3074}
3075
3076static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077compiler_list(struct compiler *c, expr_ty e)
3078{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003079 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003081 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003083 else if (e->v.List.ctx == Load) {
3084 return starunpack_helper(c, elts,
3085 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003087 else
3088 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090}
3091
3092static int
3093compiler_tuple(struct compiler *c, expr_ty e)
3094{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003095 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003097 return assignment_helper(c, elts);
3098 }
3099 else if (e->v.Tuple.ctx == Load) {
3100 return starunpack_helper(c, elts,
3101 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3102 }
3103 else
3104 VISIT_SEQ(c, expr, elts);
3105 return 1;
3106}
3107
3108static int
3109compiler_set(struct compiler *c, expr_ty e)
3110{
3111 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3112 BUILD_SET, BUILD_SET_UNPACK);
3113}
3114
3115static int
3116compiler_dict(struct compiler *c, expr_ty e)
3117{
3118 Py_ssize_t i, n, containers, elements;
3119 int is_unpacking = 0;
3120 n = asdl_seq_LEN(e->v.Dict.values);
3121 containers = 0;
3122 elements = 0;
3123 for (i = 0; i < n; i++) {
3124 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3125 if (elements == 0xFFFF || (elements && is_unpacking)) {
3126 ADDOP_I(c, BUILD_MAP, elements);
3127 containers++;
3128 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003130 if (is_unpacking) {
3131 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3132 containers++;
3133 }
3134 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003135 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003136 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003137 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 }
3139 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003140 if (elements || containers == 0) {
3141 ADDOP_I(c, BUILD_MAP, elements);
3142 containers++;
3143 }
3144 /* If there is more than one dict, they need to be merged into a new
3145 * dict. If there is one dict and it's an unpacking, then it needs
3146 * to be copied into a new dict." */
3147 while (containers > 1 || is_unpacking) {
3148 int oparg = containers < 255 ? containers : 255;
3149 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3150 containers -= (oparg - 1);
3151 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 }
3153 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154}
3155
3156static int
3157compiler_compare(struct compiler *c, expr_ty e)
3158{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003159 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3163 VISIT(c, expr, e->v.Compare.left);
3164 n = asdl_seq_LEN(e->v.Compare.ops);
3165 assert(n > 0);
3166 if (n > 1) {
3167 cleanup = compiler_new_block(c);
3168 if (cleanup == NULL)
3169 return 0;
3170 VISIT(c, expr,
3171 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3172 }
3173 for (i = 1; i < n; i++) {
3174 ADDOP(c, DUP_TOP);
3175 ADDOP(c, ROT_THREE);
3176 ADDOP_I(c, COMPARE_OP,
3177 cmpop((cmpop_ty)(asdl_seq_GET(
3178 e->v.Compare.ops, i - 1))));
3179 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3180 NEXT_BLOCK(c);
3181 if (i < (n - 1))
3182 VISIT(c, expr,
3183 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3184 }
3185 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3186 ADDOP_I(c, COMPARE_OP,
3187 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3188 if (n > 1) {
3189 basicblock *end = compiler_new_block(c);
3190 if (end == NULL)
3191 return 0;
3192 ADDOP_JREL(c, JUMP_FORWARD, end);
3193 compiler_use_next_block(c, cleanup);
3194 ADDOP(c, ROT_TWO);
3195 ADDOP(c, POP_TOP);
3196 compiler_use_next_block(c, end);
3197 }
3198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199}
3200
3201static int
3202compiler_call(struct compiler *c, expr_ty e)
3203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 VISIT(c, expr, e->v.Call.func);
3205 return compiler_call_helper(c, 0,
3206 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003207 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003208}
3209
3210/* shared code between compiler_call and compiler_class */
3211static int
3212compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003213 Py_ssize_t n, /* Args already pushed */
3214 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003215 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003218 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003219
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003220 /* the number of tuples and dictionaries on the stack */
3221 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3222
3223 nkw = 0;
3224 nseen = 0; /* the number of positional arguments on the stack */
3225 nelts = asdl_seq_LEN(args);
3226 for (i = 0; i < nelts; i++) {
3227 expr_ty elt = asdl_seq_GET(args, i);
3228 if (elt->kind == Starred_kind) {
3229 /* A star-arg. If we've seen positional arguments,
3230 pack the positional arguments into a
3231 tuple. */
3232 if (nseen) {
3233 ADDOP_I(c, BUILD_TUPLE, nseen);
3234 nseen = 0;
3235 nsubargs++;
3236 }
3237 VISIT(c, expr, elt->v.Starred.value);
3238 nsubargs++;
3239 }
3240 else if (nsubargs) {
3241 /* We've seen star-args already, so we
3242 count towards items-to-pack-into-tuple. */
3243 VISIT(c, expr, elt);
3244 nseen++;
3245 }
3246 else {
3247 /* Positional arguments before star-arguments
3248 are left on the stack. */
3249 VISIT(c, expr, elt);
3250 n++;
3251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003253 if (nseen) {
3254 /* Pack up any trailing positional arguments. */
3255 ADDOP_I(c, BUILD_TUPLE, nseen);
3256 nsubargs++;
3257 }
3258 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003260 if (nsubargs > 1) {
3261 /* If we ended up with more than one stararg, we need
3262 to concatenate them into a single sequence. */
3263 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003266
3267 /* Same dance again for keyword arguments */
3268 nseen = 0; /* the number of keyword arguments on the stack following */
3269 nelts = asdl_seq_LEN(keywords);
3270 for (i = 0; i < nelts; i++) {
3271 keyword_ty kw = asdl_seq_GET(keywords, i);
3272 if (kw->arg == NULL) {
3273 /* A keyword argument unpacking. */
3274 if (nseen) {
3275 ADDOP_I(c, BUILD_MAP, nseen);
3276 nseen = 0;
3277 nsubkwargs++;
3278 }
3279 VISIT(c, expr, kw->value);
3280 nsubkwargs++;
3281 }
3282 else if (nsubkwargs) {
3283 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003284 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003285 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003286 nseen++;
3287 }
3288 else {
3289 /* keyword argument */
3290 VISIT(c, keyword, kw)
3291 nkw++;
3292 }
3293 }
3294 if (nseen) {
3295 /* Pack up any trailing keyword arguments. */
3296 ADDOP_I(c, BUILD_MAP, nseen);
3297 nsubkwargs++;
3298 }
3299 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003301 if (nsubkwargs > 1) {
3302 /* Pack it all up */
3303 int function_pos = n + (code & 1) + nkw + 1;
3304 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003307 assert(n < 1<<8);
3308 assert(nkw < 1<<24);
3309 n |= nkw << 8;
3310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 switch (code) {
3312 case 0:
3313 ADDOP_I(c, CALL_FUNCTION, n);
3314 break;
3315 case 1:
3316 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3317 break;
3318 case 2:
3319 ADDOP_I(c, CALL_FUNCTION_KW, n);
3320 break;
3321 case 3:
3322 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3323 break;
3324 }
3325 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326}
3327
Nick Coghlan650f0d02007-04-15 12:05:43 +00003328
3329/* List and set comprehensions and generator expressions work by creating a
3330 nested function to perform the actual iteration. This means that the
3331 iteration variables don't leak into the current scope.
3332 The defined function is called immediately following its definition, with the
3333 result of that call being the result of the expression.
3334 The LC/SC version returns the populated container, while the GE version is
3335 flagged in symtable.c as a generator, so it returns the generator object
3336 when the function is called.
3337 This code *knows* that the loop cannot contain break, continue, or return,
3338 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3339
3340 Possible cleanups:
3341 - iterate over the generator sequence instead of using recursion
3342*/
3343
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345compiler_comprehension_generator(struct compiler *c,
3346 asdl_seq *generators, int gen_index,
3347 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 /* generate code for the iterator, then each of the ifs,
3350 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 comprehension_ty gen;
3353 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003354 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 start = compiler_new_block(c);
3357 skip = compiler_new_block(c);
3358 if_cleanup = compiler_new_block(c);
3359 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3362 anchor == NULL)
3363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 if (gen_index == 0) {
3368 /* Receive outermost iter as an implicit argument */
3369 c->u->u_argcount = 1;
3370 ADDOP_I(c, LOAD_FAST, 0);
3371 }
3372 else {
3373 /* Sub-iter - calculate on the fly */
3374 VISIT(c, expr, gen->iter);
3375 ADDOP(c, GET_ITER);
3376 }
3377 compiler_use_next_block(c, start);
3378 ADDOP_JREL(c, FOR_ITER, anchor);
3379 NEXT_BLOCK(c);
3380 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 /* XXX this needs to be cleaned up...a lot! */
3383 n = asdl_seq_LEN(gen->ifs);
3384 for (i = 0; i < n; i++) {
3385 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3386 VISIT(c, expr, e);
3387 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3388 NEXT_BLOCK(c);
3389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 if (++gen_index < asdl_seq_LEN(generators))
3392 if (!compiler_comprehension_generator(c,
3393 generators, gen_index,
3394 elt, val, type))
3395 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 /* only append after the last for generator */
3398 if (gen_index >= asdl_seq_LEN(generators)) {
3399 /* comprehension specific code */
3400 switch (type) {
3401 case COMP_GENEXP:
3402 VISIT(c, expr, elt);
3403 ADDOP(c, YIELD_VALUE);
3404 ADDOP(c, POP_TOP);
3405 break;
3406 case COMP_LISTCOMP:
3407 VISIT(c, expr, elt);
3408 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3409 break;
3410 case COMP_SETCOMP:
3411 VISIT(c, expr, elt);
3412 ADDOP_I(c, SET_ADD, gen_index + 1);
3413 break;
3414 case COMP_DICTCOMP:
3415 /* With 'd[k] = v', v is evaluated before k, so we do
3416 the same. */
3417 VISIT(c, expr, val);
3418 VISIT(c, expr, elt);
3419 ADDOP_I(c, MAP_ADD, gen_index + 1);
3420 break;
3421 default:
3422 return 0;
3423 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 compiler_use_next_block(c, skip);
3426 }
3427 compiler_use_next_block(c, if_cleanup);
3428 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3429 compiler_use_next_block(c, anchor);
3430
3431 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432}
3433
3434static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003435compiler_comprehension(struct compiler *c, expr_ty e, int type,
3436 identifier name, asdl_seq *generators, expr_ty elt,
3437 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 PyCodeObject *co = NULL;
3440 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003441 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 outermost_iter = ((comprehension_ty)
3444 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003445
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003446 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3447 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 if (type != COMP_GENEXP) {
3451 int op;
3452 switch (type) {
3453 case COMP_LISTCOMP:
3454 op = BUILD_LIST;
3455 break;
3456 case COMP_SETCOMP:
3457 op = BUILD_SET;
3458 break;
3459 case COMP_DICTCOMP:
3460 op = BUILD_MAP;
3461 break;
3462 default:
3463 PyErr_Format(PyExc_SystemError,
3464 "unknown comprehension type %d", type);
3465 goto error_in_scope;
3466 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 ADDOP_I(c, op, 0);
3469 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 if (!compiler_comprehension_generator(c, generators, 0, elt,
3472 val, type))
3473 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 if (type != COMP_GENEXP) {
3476 ADDOP(c, RETURN_VALUE);
3477 }
3478
3479 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003480 qualname = c->u->u_qualname;
3481 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003483 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 goto error;
3485
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003486 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003488 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 Py_DECREF(co);
3490
3491 VISIT(c, expr, outermost_iter);
3492 ADDOP(c, GET_ITER);
3493 ADDOP_I(c, CALL_FUNCTION, 1);
3494 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003495error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003497error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003498 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 Py_XDECREF(co);
3500 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003501}
3502
3503static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504compiler_genexp(struct compiler *c, expr_ty e)
3505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 static identifier name;
3507 if (!name) {
3508 name = PyUnicode_FromString("<genexpr>");
3509 if (!name)
3510 return 0;
3511 }
3512 assert(e->kind == GeneratorExp_kind);
3513 return compiler_comprehension(c, e, COMP_GENEXP, name,
3514 e->v.GeneratorExp.generators,
3515 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516}
3517
3518static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003519compiler_listcomp(struct compiler *c, expr_ty e)
3520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 static identifier name;
3522 if (!name) {
3523 name = PyUnicode_FromString("<listcomp>");
3524 if (!name)
3525 return 0;
3526 }
3527 assert(e->kind == ListComp_kind);
3528 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3529 e->v.ListComp.generators,
3530 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003531}
3532
3533static int
3534compiler_setcomp(struct compiler *c, expr_ty e)
3535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 static identifier name;
3537 if (!name) {
3538 name = PyUnicode_FromString("<setcomp>");
3539 if (!name)
3540 return 0;
3541 }
3542 assert(e->kind == SetComp_kind);
3543 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3544 e->v.SetComp.generators,
3545 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003546}
3547
3548
3549static int
3550compiler_dictcomp(struct compiler *c, expr_ty e)
3551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 static identifier name;
3553 if (!name) {
3554 name = PyUnicode_FromString("<dictcomp>");
3555 if (!name)
3556 return 0;
3557 }
3558 assert(e->kind == DictComp_kind);
3559 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3560 e->v.DictComp.generators,
3561 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003562}
3563
3564
3565static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566compiler_visit_keyword(struct compiler *c, keyword_ty k)
3567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3569 VISIT(c, expr, k->value);
3570 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571}
3572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 whether they are true or false.
3575
3576 Return values: 1 for true, 0 for false, -1 for non-constant.
3577 */
3578
3579static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003580expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 char *id;
3583 switch (e->kind) {
3584 case Ellipsis_kind:
3585 return 1;
3586 case Num_kind:
3587 return PyObject_IsTrue(e->v.Num.n);
3588 case Str_kind:
3589 return PyObject_IsTrue(e->v.Str.s);
3590 case Name_kind:
3591 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003592 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003593 if (id && strcmp(id, "__debug__") == 0)
3594 return !c->c_optimize;
3595 return -1;
3596 case NameConstant_kind: {
3597 PyObject *o = e->v.NameConstant.value;
3598 if (o == Py_None)
3599 return 0;
3600 else if (o == Py_True)
3601 return 1;
3602 else if (o == Py_False)
3603 return 0;
3604 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 default:
3606 return -1;
3607 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608}
3609
Yury Selivanov75445082015-05-11 22:57:16 -04003610
3611/*
3612 Implements the async with statement.
3613
3614 The semantics outlined in that PEP are as follows:
3615
3616 async with EXPR as VAR:
3617 BLOCK
3618
3619 It is implemented roughly as:
3620
3621 context = EXPR
3622 exit = context.__aexit__ # not calling it
3623 value = await context.__aenter__()
3624 try:
3625 VAR = value # if VAR present in the syntax
3626 BLOCK
3627 finally:
3628 if an exception was raised:
3629 exc = copy of (exception, instance, traceback)
3630 else:
3631 exc = (None, None, None)
3632 if not (await exit(*exc)):
3633 raise
3634 */
3635static int
3636compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3637{
3638 basicblock *block, *finally;
3639 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3640
3641 assert(s->kind == AsyncWith_kind);
3642
3643 block = compiler_new_block(c);
3644 finally = compiler_new_block(c);
3645 if (!block || !finally)
3646 return 0;
3647
3648 /* Evaluate EXPR */
3649 VISIT(c, expr, item->context_expr);
3650
3651 ADDOP(c, BEFORE_ASYNC_WITH);
3652 ADDOP(c, GET_AWAITABLE);
3653 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3654 ADDOP(c, YIELD_FROM);
3655
3656 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3657
3658 /* SETUP_ASYNC_WITH pushes a finally block. */
3659 compiler_use_next_block(c, block);
3660 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3661 return 0;
3662 }
3663
3664 if (item->optional_vars) {
3665 VISIT(c, expr, item->optional_vars);
3666 }
3667 else {
3668 /* Discard result from context.__aenter__() */
3669 ADDOP(c, POP_TOP);
3670 }
3671
3672 pos++;
3673 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3674 /* BLOCK code */
3675 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3676 else if (!compiler_async_with(c, s, pos))
3677 return 0;
3678
3679 /* End of try block; start the finally block */
3680 ADDOP(c, POP_BLOCK);
3681 compiler_pop_fblock(c, FINALLY_TRY, block);
3682
3683 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3684 compiler_use_next_block(c, finally);
3685 if (!compiler_push_fblock(c, FINALLY_END, finally))
3686 return 0;
3687
3688 /* Finally block starts; context.__exit__ is on the stack under
3689 the exception or return information. Just issue our magic
3690 opcode. */
3691 ADDOP(c, WITH_CLEANUP_START);
3692
3693 ADDOP(c, GET_AWAITABLE);
3694 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3695 ADDOP(c, YIELD_FROM);
3696
3697 ADDOP(c, WITH_CLEANUP_FINISH);
3698
3699 /* Finally block ends. */
3700 ADDOP(c, END_FINALLY);
3701 compiler_pop_fblock(c, FINALLY_END, finally);
3702 return 1;
3703}
3704
3705
Guido van Rossumc2e20742006-02-27 22:32:47 +00003706/*
3707 Implements the with statement from PEP 343.
3708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003710
3711 with EXPR as VAR:
3712 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713
Guido van Rossumc2e20742006-02-27 22:32:47 +00003714 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715
Thomas Wouters477c8d52006-05-27 19:21:47 +00003716 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003717 exit = context.__exit__ # not calling it
3718 value = context.__enter__()
3719 try:
3720 VAR = value # if VAR present in the syntax
3721 BLOCK
3722 finally:
3723 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003724 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003725 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003726 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003727 exit(*exc)
3728 */
3729static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003730compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003731{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003732 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003733 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003734
3735 assert(s->kind == With_kind);
3736
Guido van Rossumc2e20742006-02-27 22:32:47 +00003737 block = compiler_new_block(c);
3738 finally = compiler_new_block(c);
3739 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003740 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003741
Thomas Wouters477c8d52006-05-27 19:21:47 +00003742 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003743 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003744 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003745
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003746 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003747 compiler_use_next_block(c, block);
3748 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003749 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003750 }
3751
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003752 if (item->optional_vars) {
3753 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003754 }
3755 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003757 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003758 }
3759
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003760 pos++;
3761 if (pos == asdl_seq_LEN(s->v.With.items))
3762 /* BLOCK code */
3763 VISIT_SEQ(c, stmt, s->v.With.body)
3764 else if (!compiler_with(c, s, pos))
3765 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003766
3767 /* End of try block; start the finally block */
3768 ADDOP(c, POP_BLOCK);
3769 compiler_pop_fblock(c, FINALLY_TRY, block);
3770
3771 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3772 compiler_use_next_block(c, finally);
3773 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003774 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003775
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003776 /* Finally block starts; context.__exit__ is on the stack under
3777 the exception or return information. Just issue our magic
3778 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003779 ADDOP(c, WITH_CLEANUP_START);
3780 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003781
3782 /* Finally block ends. */
3783 ADDOP(c, END_FINALLY);
3784 compiler_pop_fblock(c, FINALLY_END, finally);
3785 return 1;
3786}
3787
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788static int
3789compiler_visit_expr(struct compiler *c, expr_ty e)
3790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 /* If expr e has a different line number than the last expr/stmt,
3792 set a new line number for the next instruction.
3793 */
3794 if (e->lineno > c->u->u_lineno) {
3795 c->u->u_lineno = e->lineno;
3796 c->u->u_lineno_set = 0;
3797 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003798 /* Updating the column offset is always harmless. */
3799 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 switch (e->kind) {
3801 case BoolOp_kind:
3802 return compiler_boolop(c, e);
3803 case BinOp_kind:
3804 VISIT(c, expr, e->v.BinOp.left);
3805 VISIT(c, expr, e->v.BinOp.right);
3806 ADDOP(c, binop(c, e->v.BinOp.op));
3807 break;
3808 case UnaryOp_kind:
3809 VISIT(c, expr, e->v.UnaryOp.operand);
3810 ADDOP(c, unaryop(e->v.UnaryOp.op));
3811 break;
3812 case Lambda_kind:
3813 return compiler_lambda(c, e);
3814 case IfExp_kind:
3815 return compiler_ifexp(c, e);
3816 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003817 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003819 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 case GeneratorExp_kind:
3821 return compiler_genexp(c, e);
3822 case ListComp_kind:
3823 return compiler_listcomp(c, e);
3824 case SetComp_kind:
3825 return compiler_setcomp(c, e);
3826 case DictComp_kind:
3827 return compiler_dictcomp(c, e);
3828 case Yield_kind:
3829 if (c->u->u_ste->ste_type != FunctionBlock)
3830 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003831 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3832 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003833 if (e->v.Yield.value) {
3834 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 }
3836 else {
3837 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3838 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003839 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003841 case YieldFrom_kind:
3842 if (c->u->u_ste->ste_type != FunctionBlock)
3843 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003844
3845 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3846 return compiler_error(c, "'yield from' inside async function");
3847
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003848 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003849 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003850 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3851 ADDOP(c, YIELD_FROM);
3852 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003853 case Await_kind:
3854 if (c->u->u_ste->ste_type != FunctionBlock)
3855 return compiler_error(c, "'await' outside function");
3856
Yury Selivanov9dec0352015-06-30 12:49:04 -04003857 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3858 return compiler_error(
3859 c, "'await' expressions in comprehensions are not supported");
3860
Yury Selivanov75445082015-05-11 22:57:16 -04003861 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3862 return compiler_error(c, "'await' outside async function");
3863
3864 VISIT(c, expr, e->v.Await.value);
3865 ADDOP(c, GET_AWAITABLE);
3866 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3867 ADDOP(c, YIELD_FROM);
3868 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 case Compare_kind:
3870 return compiler_compare(c, e);
3871 case Call_kind:
3872 return compiler_call(c, e);
3873 case Num_kind:
3874 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3875 break;
3876 case Str_kind:
3877 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3878 break;
3879 case Bytes_kind:
3880 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3881 break;
3882 case Ellipsis_kind:
3883 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3884 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003885 case NameConstant_kind:
3886 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3887 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 /* The following exprs can be assignment targets. */
3889 case Attribute_kind:
3890 if (e->v.Attribute.ctx != AugStore)
3891 VISIT(c, expr, e->v.Attribute.value);
3892 switch (e->v.Attribute.ctx) {
3893 case AugLoad:
3894 ADDOP(c, DUP_TOP);
3895 /* Fall through to load */
3896 case Load:
3897 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3898 break;
3899 case AugStore:
3900 ADDOP(c, ROT_TWO);
3901 /* Fall through to save */
3902 case Store:
3903 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3904 break;
3905 case Del:
3906 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3907 break;
3908 case Param:
3909 default:
3910 PyErr_SetString(PyExc_SystemError,
3911 "param invalid in attribute expression");
3912 return 0;
3913 }
3914 break;
3915 case Subscript_kind:
3916 switch (e->v.Subscript.ctx) {
3917 case AugLoad:
3918 VISIT(c, expr, e->v.Subscript.value);
3919 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3920 break;
3921 case Load:
3922 VISIT(c, expr, e->v.Subscript.value);
3923 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3924 break;
3925 case AugStore:
3926 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3927 break;
3928 case Store:
3929 VISIT(c, expr, e->v.Subscript.value);
3930 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3931 break;
3932 case Del:
3933 VISIT(c, expr, e->v.Subscript.value);
3934 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3935 break;
3936 case Param:
3937 default:
3938 PyErr_SetString(PyExc_SystemError,
3939 "param invalid in subscript expression");
3940 return 0;
3941 }
3942 break;
3943 case Starred_kind:
3944 switch (e->v.Starred.ctx) {
3945 case Store:
3946 /* In all legitimate cases, the Starred node was already replaced
3947 * by compiler_list/compiler_tuple. XXX: is that okay? */
3948 return compiler_error(c,
3949 "starred assignment target must be in a list or tuple");
3950 default:
3951 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003952 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 }
3954 break;
3955 case Name_kind:
3956 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3957 /* child nodes of List and Tuple will have expr_context set */
3958 case List_kind:
3959 return compiler_list(c, e);
3960 case Tuple_kind:
3961 return compiler_tuple(c, e);
3962 }
3963 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964}
3965
3966static int
3967compiler_augassign(struct compiler *c, stmt_ty s)
3968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 expr_ty e = s->v.AugAssign.target;
3970 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 switch (e->kind) {
3975 case Attribute_kind:
3976 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3977 AugLoad, e->lineno, e->col_offset, c->c_arena);
3978 if (auge == NULL)
3979 return 0;
3980 VISIT(c, expr, auge);
3981 VISIT(c, expr, s->v.AugAssign.value);
3982 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3983 auge->v.Attribute.ctx = AugStore;
3984 VISIT(c, expr, auge);
3985 break;
3986 case Subscript_kind:
3987 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3988 AugLoad, e->lineno, e->col_offset, c->c_arena);
3989 if (auge == NULL)
3990 return 0;
3991 VISIT(c, expr, auge);
3992 VISIT(c, expr, s->v.AugAssign.value);
3993 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3994 auge->v.Subscript.ctx = AugStore;
3995 VISIT(c, expr, auge);
3996 break;
3997 case Name_kind:
3998 if (!compiler_nameop(c, e->v.Name.id, Load))
3999 return 0;
4000 VISIT(c, expr, s->v.AugAssign.value);
4001 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4002 return compiler_nameop(c, e->v.Name.id, Store);
4003 default:
4004 PyErr_Format(PyExc_SystemError,
4005 "invalid node type (%d) for augmented assignment",
4006 e->kind);
4007 return 0;
4008 }
4009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010}
4011
4012static int
4013compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 struct fblockinfo *f;
4016 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4017 PyErr_SetString(PyExc_SystemError,
4018 "too many statically nested blocks");
4019 return 0;
4020 }
4021 f = &c->u->u_fblock[c->u->u_nfblocks++];
4022 f->fb_type = t;
4023 f->fb_block = b;
4024 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025}
4026
4027static void
4028compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 struct compiler_unit *u = c->u;
4031 assert(u->u_nfblocks > 0);
4032 u->u_nfblocks--;
4033 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4034 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004035}
4036
Thomas Wouters89f507f2006-12-13 04:49:30 +00004037static int
4038compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 int i;
4040 struct compiler_unit *u = c->u;
4041 for (i = 0; i < u->u_nfblocks; ++i) {
4042 if (u->u_fblock[i].fb_type == LOOP)
4043 return 1;
4044 }
4045 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004046}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004047/* Raises a SyntaxError and returns 0.
4048 If something goes wrong, a different exception may be raised.
4049*/
4050
4051static int
4052compiler_error(struct compiler *c, const char *errstr)
4053{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004054 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004056
Victor Stinner14e461d2013-08-26 22:28:21 +02004057 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 if (!loc) {
4059 Py_INCREF(Py_None);
4060 loc = Py_None;
4061 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004062 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004063 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 if (!u)
4065 goto exit;
4066 v = Py_BuildValue("(zO)", errstr, u);
4067 if (!v)
4068 goto exit;
4069 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 Py_DECREF(loc);
4072 Py_XDECREF(u);
4073 Py_XDECREF(v);
4074 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004075}
4076
4077static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078compiler_handle_subscr(struct compiler *c, const char *kind,
4079 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 /* XXX this code is duplicated */
4084 switch (ctx) {
4085 case AugLoad: /* fall through to Load */
4086 case Load: op = BINARY_SUBSCR; break;
4087 case AugStore:/* fall through to Store */
4088 case Store: op = STORE_SUBSCR; break;
4089 case Del: op = DELETE_SUBSCR; break;
4090 case Param:
4091 PyErr_Format(PyExc_SystemError,
4092 "invalid %s kind %d in subscript\n",
4093 kind, ctx);
4094 return 0;
4095 }
4096 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004097 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 }
4099 else if (ctx == AugStore) {
4100 ADDOP(c, ROT_THREE);
4101 }
4102 ADDOP(c, op);
4103 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004104}
4105
4106static int
4107compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 int n = 2;
4110 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 /* only handles the cases where BUILD_SLICE is emitted */
4113 if (s->v.Slice.lower) {
4114 VISIT(c, expr, s->v.Slice.lower);
4115 }
4116 else {
4117 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 if (s->v.Slice.upper) {
4121 VISIT(c, expr, s->v.Slice.upper);
4122 }
4123 else {
4124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4125 }
4126
4127 if (s->v.Slice.step) {
4128 n++;
4129 VISIT(c, expr, s->v.Slice.step);
4130 }
4131 ADDOP_I(c, BUILD_SLICE, n);
4132 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133}
4134
4135static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4137 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 switch (s->kind) {
4140 case Slice_kind:
4141 return compiler_slice(c, s, ctx);
4142 case Index_kind:
4143 VISIT(c, expr, s->v.Index.value);
4144 break;
4145 case ExtSlice_kind:
4146 default:
4147 PyErr_SetString(PyExc_SystemError,
4148 "extended slice invalid in nested slice");
4149 return 0;
4150 }
4151 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152}
4153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154static int
4155compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 char * kindname = NULL;
4158 switch (s->kind) {
4159 case Index_kind:
4160 kindname = "index";
4161 if (ctx != AugStore) {
4162 VISIT(c, expr, s->v.Index.value);
4163 }
4164 break;
4165 case Slice_kind:
4166 kindname = "slice";
4167 if (ctx != AugStore) {
4168 if (!compiler_slice(c, s, ctx))
4169 return 0;
4170 }
4171 break;
4172 case ExtSlice_kind:
4173 kindname = "extended slice";
4174 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004175 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 for (i = 0; i < n; i++) {
4177 slice_ty sub = (slice_ty)asdl_seq_GET(
4178 s->v.ExtSlice.dims, i);
4179 if (!compiler_visit_nested_slice(c, sub, ctx))
4180 return 0;
4181 }
4182 ADDOP_I(c, BUILD_TUPLE, n);
4183 }
4184 break;
4185 default:
4186 PyErr_Format(PyExc_SystemError,
4187 "invalid subscript kind %d", s->kind);
4188 return 0;
4189 }
4190 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191}
4192
Thomas Wouters89f507f2006-12-13 04:49:30 +00004193/* End of the compiler section, beginning of the assembler section */
4194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195/* do depth-first search of basic block graph, starting with block.
4196 post records the block indices in post-order.
4197
4198 XXX must handle implicit jumps from one block to next
4199*/
4200
Thomas Wouters89f507f2006-12-13 04:49:30 +00004201struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 PyObject *a_bytecode; /* string containing bytecode */
4203 int a_offset; /* offset into bytecode */
4204 int a_nblocks; /* number of reachable blocks */
4205 basicblock **a_postorder; /* list of blocks in dfs postorder */
4206 PyObject *a_lnotab; /* string containing lnotab */
4207 int a_lnotab_off; /* offset into lnotab */
4208 int a_lineno; /* last lineno of emitted instruction */
4209 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004210};
4211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212static void
4213dfs(struct compiler *c, basicblock *b, struct assembler *a)
4214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 int i;
4216 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (b->b_seen)
4219 return;
4220 b->b_seen = 1;
4221 if (b->b_next != NULL)
4222 dfs(c, b->b_next, a);
4223 for (i = 0; i < b->b_iused; i++) {
4224 instr = &b->b_instr[i];
4225 if (instr->i_jrel || instr->i_jabs)
4226 dfs(c, instr->i_target, a);
4227 }
4228 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004229}
4230
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004231static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004232stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4233{
Larry Hastings3a907972013-11-23 14:49:22 -08004234 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 struct instr *instr;
4236 if (b->b_seen || b->b_startdepth >= depth)
4237 return maxdepth;
4238 b->b_seen = 1;
4239 b->b_startdepth = depth;
4240 for (i = 0; i < b->b_iused; i++) {
4241 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004242 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4243 if (effect == PY_INVALID_STACK_EFFECT) {
4244 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4245 Py_FatalError("PyCompile_OpcodeStackEffect()");
4246 }
4247 depth += effect;
4248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 if (depth > maxdepth)
4250 maxdepth = depth;
4251 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4252 if (instr->i_jrel || instr->i_jabs) {
4253 target_depth = depth;
4254 if (instr->i_opcode == FOR_ITER) {
4255 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004256 }
4257 else if (instr->i_opcode == SETUP_FINALLY ||
4258 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 target_depth = depth+3;
4260 if (target_depth > maxdepth)
4261 maxdepth = target_depth;
4262 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004263 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4264 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4265 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 maxdepth = stackdepth_walk(c, instr->i_target,
4267 target_depth, maxdepth);
4268 if (instr->i_opcode == JUMP_ABSOLUTE ||
4269 instr->i_opcode == JUMP_FORWARD) {
4270 goto out; /* remaining code is dead */
4271 }
4272 }
4273 }
4274 if (b->b_next)
4275 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004276out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 b->b_seen = 0;
4278 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004279}
4280
4281/* Find the flow path that needs the largest stack. We assume that
4282 * cycles in the flow graph have no net effect on the stack depth.
4283 */
4284static int
4285stackdepth(struct compiler *c)
4286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 basicblock *b, *entryblock;
4288 entryblock = NULL;
4289 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4290 b->b_seen = 0;
4291 b->b_startdepth = INT_MIN;
4292 entryblock = b;
4293 }
4294 if (!entryblock)
4295 return 0;
4296 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004297}
4298
4299static int
4300assemble_init(struct assembler *a, int nblocks, int firstlineno)
4301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 memset(a, 0, sizeof(struct assembler));
4303 a->a_lineno = firstlineno;
4304 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4305 if (!a->a_bytecode)
4306 return 0;
4307 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4308 if (!a->a_lnotab)
4309 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004310 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 PyErr_NoMemory();
4312 return 0;
4313 }
4314 a->a_postorder = (basicblock **)PyObject_Malloc(
4315 sizeof(basicblock *) * nblocks);
4316 if (!a->a_postorder) {
4317 PyErr_NoMemory();
4318 return 0;
4319 }
4320 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321}
4322
4323static void
4324assemble_free(struct assembler *a)
4325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 Py_XDECREF(a->a_bytecode);
4327 Py_XDECREF(a->a_lnotab);
4328 if (a->a_postorder)
4329 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004330}
4331
4332/* Return the size of a basic block in bytes. */
4333
4334static int
4335instrsize(struct instr *instr)
4336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 if (!instr->i_hasarg)
4338 return 1; /* 1 byte for the opcode*/
4339 if (instr->i_oparg > 0xffff)
4340 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4341 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342}
4343
4344static int
4345blocksize(basicblock *b)
4346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 int i;
4348 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 for (i = 0; i < b->b_iused; i++)
4351 size += instrsize(&b->b_instr[i]);
4352 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004353}
4354
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004355/* Appends a pair to the end of the line number table, a_lnotab, representing
4356 the instruction's bytecode offset and line number. See
4357 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004358
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004359static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004360assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004363 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 d_bytecode = a->a_offset - a->a_lineno_off;
4367 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 assert(d_bytecode >= 0);
4370 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 if(d_bytecode == 0 && d_lineno == 0)
4373 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 if (d_bytecode > 255) {
4376 int j, nbytes, ncodes = d_bytecode / 255;
4377 nbytes = a->a_lnotab_off + 2 * ncodes;
4378 len = PyBytes_GET_SIZE(a->a_lnotab);
4379 if (nbytes >= len) {
4380 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4381 len = nbytes;
4382 else if (len <= INT_MAX / 2)
4383 len *= 2;
4384 else {
4385 PyErr_NoMemory();
4386 return 0;
4387 }
4388 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4389 return 0;
4390 }
4391 lnotab = (unsigned char *)
4392 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4393 for (j = 0; j < ncodes; j++) {
4394 *lnotab++ = 255;
4395 *lnotab++ = 0;
4396 }
4397 d_bytecode -= ncodes * 255;
4398 a->a_lnotab_off += ncodes * 2;
4399 }
4400 assert(d_bytecode <= 255);
4401 if (d_lineno > 255) {
4402 int j, nbytes, ncodes = d_lineno / 255;
4403 nbytes = a->a_lnotab_off + 2 * ncodes;
4404 len = PyBytes_GET_SIZE(a->a_lnotab);
4405 if (nbytes >= len) {
4406 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4407 len = nbytes;
4408 else if (len <= INT_MAX / 2)
4409 len *= 2;
4410 else {
4411 PyErr_NoMemory();
4412 return 0;
4413 }
4414 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4415 return 0;
4416 }
4417 lnotab = (unsigned char *)
4418 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4419 *lnotab++ = d_bytecode;
4420 *lnotab++ = 255;
4421 d_bytecode = 0;
4422 for (j = 1; j < ncodes; j++) {
4423 *lnotab++ = 0;
4424 *lnotab++ = 255;
4425 }
4426 d_lineno -= ncodes * 255;
4427 a->a_lnotab_off += ncodes * 2;
4428 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 len = PyBytes_GET_SIZE(a->a_lnotab);
4431 if (a->a_lnotab_off + 2 >= len) {
4432 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4433 return 0;
4434 }
4435 lnotab = (unsigned char *)
4436 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 a->a_lnotab_off += 2;
4439 if (d_bytecode) {
4440 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004441 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 }
4443 else { /* First line of a block; def stmt, etc. */
4444 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004445 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 }
4447 a->a_lineno = i->i_lineno;
4448 a->a_lineno_off = a->a_offset;
4449 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004450}
4451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004452/* assemble_emit()
4453 Extend the bytecode with a new instruction.
4454 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004455*/
4456
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004457static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004458assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 int size, arg = 0, ext = 0;
4461 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4462 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 size = instrsize(i);
4465 if (i->i_hasarg) {
4466 arg = i->i_oparg;
4467 ext = arg >> 16;
4468 }
4469 if (i->i_lineno && !assemble_lnotab(a, i))
4470 return 0;
4471 if (a->a_offset + size >= len) {
4472 if (len > PY_SSIZE_T_MAX / 2)
4473 return 0;
4474 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4475 return 0;
4476 }
4477 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4478 a->a_offset += size;
4479 if (size == 6) {
4480 assert(i->i_hasarg);
4481 *code++ = (char)EXTENDED_ARG;
4482 *code++ = ext & 0xff;
4483 *code++ = ext >> 8;
4484 arg &= 0xffff;
4485 }
4486 *code++ = i->i_opcode;
4487 if (i->i_hasarg) {
4488 assert(size == 3 || size == 6);
4489 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004490 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 }
4492 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004493}
4494
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004495static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004496assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 basicblock *b;
4499 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4500 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 /* Compute the size of each block and fixup jump args.
4503 Replace block pointer with position in bytecode. */
4504 do {
4505 totsize = 0;
4506 for (i = a->a_nblocks - 1; i >= 0; i--) {
4507 b = a->a_postorder[i];
4508 bsize = blocksize(b);
4509 b->b_offset = totsize;
4510 totsize += bsize;
4511 }
4512 last_extended_arg_count = extended_arg_count;
4513 extended_arg_count = 0;
4514 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4515 bsize = b->b_offset;
4516 for (i = 0; i < b->b_iused; i++) {
4517 struct instr *instr = &b->b_instr[i];
4518 /* Relative jumps are computed relative to
4519 the instruction pointer after fetching
4520 the jump instruction.
4521 */
4522 bsize += instrsize(instr);
4523 if (instr->i_jabs)
4524 instr->i_oparg = instr->i_target->b_offset;
4525 else if (instr->i_jrel) {
4526 int delta = instr->i_target->b_offset - bsize;
4527 instr->i_oparg = delta;
4528 }
4529 else
4530 continue;
4531 if (instr->i_oparg > 0xffff)
4532 extended_arg_count++;
4533 }
4534 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 /* XXX: This is an awful hack that could hurt performance, but
4537 on the bright side it should work until we come up
4538 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 The issue is that in the first loop blocksize() is called
4541 which calls instrsize() which requires i_oparg be set
4542 appropriately. There is a bootstrap problem because
4543 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 So we loop until we stop seeing new EXTENDED_ARGs.
4546 The only EXTENDED_ARGs that could be popping up are
4547 ones in jump instructions. So this should converge
4548 fairly quickly.
4549 */
4550 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004551}
4552
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004553static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004554dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 PyObject *tuple, *k, *v;
4557 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 tuple = PyTuple_New(size);
4560 if (tuple == NULL)
4561 return NULL;
4562 while (PyDict_Next(dict, &pos, &k, &v)) {
4563 i = PyLong_AS_LONG(v);
4564 /* The keys of the dictionary are tuples. (see compiler_add_o)
4565 The object we want is always first, though. */
4566 k = PyTuple_GET_ITEM(k, 0);
4567 Py_INCREF(k);
4568 assert((i - offset) < size);
4569 assert((i - offset) >= 0);
4570 PyTuple_SET_ITEM(tuple, i - offset, k);
4571 }
4572 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004573}
4574
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004575static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004576compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004579 int flags = 0;
4580 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004582 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (ste->ste_nested)
4584 flags |= CO_NESTED;
4585 if (ste->ste_generator)
4586 flags |= CO_GENERATOR;
4587 if (ste->ste_varargs)
4588 flags |= CO_VARARGS;
4589 if (ste->ste_varkeywords)
4590 flags |= CO_VARKEYWORDS;
4591 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 /* (Only) inherit compilerflags in PyCF_MASK */
4594 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 n = PyDict_Size(c->u->u_freevars);
4597 if (n < 0)
4598 return -1;
4599 if (n == 0) {
4600 n = PyDict_Size(c->u->u_cellvars);
4601 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004602 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004604 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 }
4606 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004609}
4610
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004611static PyCodeObject *
4612makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 PyObject *tmp;
4615 PyCodeObject *co = NULL;
4616 PyObject *consts = NULL;
4617 PyObject *names = NULL;
4618 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 PyObject *name = NULL;
4620 PyObject *freevars = NULL;
4621 PyObject *cellvars = NULL;
4622 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004623 Py_ssize_t nlocals;
4624 int nlocals_int;
4625 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004626 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 tmp = dict_keys_inorder(c->u->u_consts, 0);
4629 if (!tmp)
4630 goto error;
4631 consts = PySequence_List(tmp); /* optimize_code requires a list */
4632 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 names = dict_keys_inorder(c->u->u_names, 0);
4635 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4636 if (!consts || !names || !varnames)
4637 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4640 if (!cellvars)
4641 goto error;
4642 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4643 if (!freevars)
4644 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004647 assert(nlocals < INT_MAX);
4648 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 flags = compute_code_flags(c);
4651 if (flags < 0)
4652 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4655 if (!bytecode)
4656 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4659 if (!tmp)
4660 goto error;
4661 Py_DECREF(consts);
4662 consts = tmp;
4663
Victor Stinnerf8e32212013-11-19 23:56:34 +01004664 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4665 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4666 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004667 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 bytecode, consts, names, varnames,
4669 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004670 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 c->u->u_firstlineno,
4672 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004673 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 Py_XDECREF(consts);
4675 Py_XDECREF(names);
4676 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 Py_XDECREF(name);
4678 Py_XDECREF(freevars);
4679 Py_XDECREF(cellvars);
4680 Py_XDECREF(bytecode);
4681 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004682}
4683
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004684
4685/* For debugging purposes only */
4686#if 0
4687static void
4688dump_instr(const struct instr *i)
4689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 const char *jrel = i->i_jrel ? "jrel " : "";
4691 const char *jabs = i->i_jabs ? "jabs " : "";
4692 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 *arg = '\0';
4695 if (i->i_hasarg)
4696 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4699 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004700}
4701
4702static void
4703dump_basicblock(const basicblock *b)
4704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 const char *seen = b->b_seen ? "seen " : "";
4706 const char *b_return = b->b_return ? "return " : "";
4707 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4708 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4709 if (b->b_instr) {
4710 int i;
4711 for (i = 0; i < b->b_iused; i++) {
4712 fprintf(stderr, " [%02d] ", i);
4713 dump_instr(b->b_instr + i);
4714 }
4715 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004716}
4717#endif
4718
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004719static PyCodeObject *
4720assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 basicblock *b, *entryblock;
4723 struct assembler a;
4724 int i, j, nblocks;
4725 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 /* Make sure every block that falls off the end returns None.
4728 XXX NEXT_BLOCK() isn't quite right, because if the last
4729 block ends with a jump or return b_next shouldn't set.
4730 */
4731 if (!c->u->u_curblock->b_return) {
4732 NEXT_BLOCK(c);
4733 if (addNone)
4734 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4735 ADDOP(c, RETURN_VALUE);
4736 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 nblocks = 0;
4739 entryblock = NULL;
4740 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4741 nblocks++;
4742 entryblock = b;
4743 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 /* Set firstlineno if it wasn't explicitly set. */
4746 if (!c->u->u_firstlineno) {
4747 if (entryblock && entryblock->b_instr)
4748 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4749 else
4750 c->u->u_firstlineno = 1;
4751 }
4752 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4753 goto error;
4754 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 /* Can't modify the bytecode after computing jump offsets. */
4757 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 /* Emit code in reverse postorder from dfs. */
4760 for (i = a.a_nblocks - 1; i >= 0; i--) {
4761 b = a.a_postorder[i];
4762 for (j = 0; j < b->b_iused; j++)
4763 if (!assemble_emit(&a, &b->b_instr[j]))
4764 goto error;
4765 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4768 goto error;
4769 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4770 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 assemble_free(&a);
4775 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004776}
Georg Brandl8334fd92010-12-04 10:26:46 +00004777
4778#undef PyAST_Compile
4779PyAPI_FUNC(PyCodeObject *)
4780PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4781 PyArena *arena)
4782{
4783 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4784}
4785