blob: a710e82693e7a25de5d67848c361e11b6c55cbb3 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
46 unsigned i_hasarg : 1;
47 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinnerad9a0662013-11-19 22:23:20 +0100199static int compiler_call_helper(struct compiler *c, Py_ssize_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205static PyCodeObject *assemble(struct compiler *, int addNone);
206static PyObject *__doc__;
207
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400208#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* Name mangling: __private becomes _classname__private.
214 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200215 PyObject *result;
216 size_t nlen, plen, ipriv;
217 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 PyUnicode_READ_CHAR(ident, 0) != '_' ||
220 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_INCREF(ident);
222 return ident;
223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 nlen = PyUnicode_GET_LENGTH(ident);
225 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 The only time a name with a dot can occur is when
229 we are compiling an import statement that has a
230 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 TODO(jhylton): Decide whether we want to support
233 mangling of the module name, e.g. __M.X.
234 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
236 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
237 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident; /* Don't mangle __whatever__ */
240 }
241 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 ipriv = 0;
243 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
244 ipriv++;
245 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_INCREF(ident);
247 return ident; /* Don't mangle if class is just underscores */
248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000250
Antoine Pitrou55bff892013-04-06 21:21:04 +0200251 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
252 PyErr_SetString(PyExc_OverflowError,
253 "private identifier too large to be mangled");
254 return NULL;
255 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200257 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
258 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
259 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
260
261 result = PyUnicode_New(1 + nlen + plen, maxchar);
262 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
265 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200266 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
267 Py_DECREF(result);
268 return NULL;
269 }
270 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
271 Py_DECREF(result);
272 return NULL;
273 }
Victor Stinner8f825062012-04-27 13:55:39 +0200274 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000276}
277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278static int
279compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 c->c_stack = PyList_New(0);
284 if (!c->c_stack)
285 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288}
289
290PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200291PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
292 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 struct compiler c;
295 PyCodeObject *co = NULL;
296 PyCompilerFlags local_flags;
297 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!__doc__) {
300 __doc__ = PyUnicode_InternFromString("__doc__");
301 if (!__doc__)
302 return NULL;
303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!compiler_init(&c))
306 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200307 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 c.c_filename = filename;
309 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200310 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (c.c_future == NULL)
312 goto finally;
313 if (!flags) {
314 local_flags.cf_flags = 0;
315 flags = &local_flags;
316 }
317 merged = c.c_future->ff_features | flags->cf_flags;
318 c.c_future->ff_features = merged;
319 flags->cf_flags = merged;
320 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000321 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Victor Stinner14e461d2013-08-26 22:28:21 +0200324 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (c.c_st == NULL) {
326 if (!PyErr_Occurred())
327 PyErr_SetString(PyExc_SystemError, "no symtable");
328 goto finally;
329 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Thomas Wouters1175c432006-02-27 22:49:54 +0000333 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 compiler_free(&c);
335 assert(co || PyErr_Occurred());
336 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337}
338
339PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200340PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
341 int optimize, PyArena *arena)
342{
343 PyObject *filename;
344 PyCodeObject *co;
345 filename = PyUnicode_DecodeFSDefault(filename_str);
346 if (filename == NULL)
347 return NULL;
348 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
349 Py_DECREF(filename);
350 return co;
351
352}
353
354PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355PyNode_Compile(struct _node *n, const char *filename)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyCodeObject *co = NULL;
358 mod_ty mod;
359 PyArena *arena = PyArena_New();
360 if (!arena)
361 return NULL;
362 mod = PyAST_FromNode(n, NULL, filename, arena);
363 if (mod)
364 co = PyAST_Compile(mod, filename, NULL, arena);
365 PyArena_Free(arena);
366 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000367}
368
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000369static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (c->c_st)
373 PySymtable_Free(c->c_st);
374 if (c->c_future)
375 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200376 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000378}
379
Guido van Rossum79f25d91997-04-29 20:08:16 +0000380static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_ssize_t i, n;
384 PyObject *v, *k;
385 PyObject *dict = PyDict_New();
386 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 n = PyList_Size(list);
389 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100390 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!v) {
392 Py_DECREF(dict);
393 return NULL;
394 }
395 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100396 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
398 Py_XDECREF(k);
399 Py_DECREF(v);
400 Py_DECREF(dict);
401 return NULL;
402 }
403 Py_DECREF(k);
404 Py_DECREF(v);
405 }
406 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407}
408
409/* Return new dict containing names from src that match scope(s).
410
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000413values are integers, starting at offset and increasing by one for
414each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415*/
416
417static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100418dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700420 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500422 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 assert(offset >= 0);
425 if (dest == NULL)
426 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427
Meador Inge2ca63152012-07-18 14:20:11 -0500428 /* Sort the keys so that we have a deterministic order on the indexes
429 saved in the returned dictionary. These indexes are used as indexes
430 into the free and cell var storage. Therefore if they aren't
431 deterministic, then the generated bytecode is not deterministic.
432 */
433 sorted_keys = PyDict_Keys(src);
434 if (sorted_keys == NULL)
435 return NULL;
436 if (PyList_Sort(sorted_keys) != 0) {
437 Py_DECREF(sorted_keys);
438 return NULL;
439 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500440 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500441
442 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* XXX this should probably be a macro in symtable.h */
444 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500445 k = PyList_GET_ITEM(sorted_keys, key_i);
446 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 assert(PyLong_Check(v));
448 vi = PyLong_AS_LONG(v);
449 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100452 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500454 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(dest);
456 return NULL;
457 }
458 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100459 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500461 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 Py_DECREF(item);
463 Py_DECREF(dest);
464 Py_XDECREF(tuple);
465 return NULL;
466 }
467 Py_DECREF(item);
468 Py_DECREF(tuple);
469 }
470 }
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000473}
474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000475static void
476compiler_unit_check(struct compiler_unit *u)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 basicblock *block;
479 for (block = u->u_blocks; block != NULL; block = block->b_list) {
480 assert((void *)block != (void *)0xcbcbcbcb);
481 assert((void *)block != (void *)0xfbfbfbfb);
482 assert((void *)block != (void *)0xdbdbdbdb);
483 if (block->b_instr != NULL) {
484 assert(block->b_ialloc > 0);
485 assert(block->b_iused > 0);
486 assert(block->b_ialloc >= block->b_iused);
487 }
488 else {
489 assert (block->b_iused == 0);
490 assert (block->b_ialloc == 0);
491 }
492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493}
494
495static void
496compiler_unit_free(struct compiler_unit *u)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 compiler_unit_check(u);
501 b = u->u_blocks;
502 while (b != NULL) {
503 if (b->b_instr)
504 PyObject_Free((void *)b->b_instr);
505 next = b->b_list;
506 PyObject_Free((void *)b);
507 b = next;
508 }
509 Py_CLEAR(u->u_ste);
510 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400511 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_CLEAR(u->u_consts);
513 Py_CLEAR(u->u_names);
514 Py_CLEAR(u->u_varnames);
515 Py_CLEAR(u->u_freevars);
516 Py_CLEAR(u->u_cellvars);
517 Py_CLEAR(u->u_private);
518 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519}
520
521static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100522compiler_enter_scope(struct compiler *c, identifier name,
523 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
528 struct compiler_unit));
529 if (!u) {
530 PyErr_NoMemory();
531 return 0;
532 }
533 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100534 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_argcount = 0;
536 u->u_kwonlyargcount = 0;
537 u->u_ste = PySymtable_Lookup(c->c_st, key);
538 if (!u->u_ste) {
539 compiler_unit_free(u);
540 return 0;
541 }
542 Py_INCREF(name);
543 u->u_name = name;
544 u->u_varnames = list2dict(u->u_ste->ste_varnames);
545 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
546 if (!u->u_varnames || !u->u_cellvars) {
547 compiler_unit_free(u);
548 return 0;
549 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500550 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000551 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500552 _Py_IDENTIFIER(__class__);
553 PyObject *tuple, *name, *zero;
554 int res;
555 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
556 assert(PyDict_Size(u->u_cellvars) == 0);
557 name = _PyUnicode_FromId(&PyId___class__);
558 if (!name) {
559 compiler_unit_free(u);
560 return 0;
561 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100562 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 if (!tuple) {
564 compiler_unit_free(u);
565 return 0;
566 }
567 zero = PyLong_FromLong(0);
568 if (!zero) {
569 Py_DECREF(tuple);
570 compiler_unit_free(u);
571 return 0;
572 }
573 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
574 Py_DECREF(tuple);
575 Py_DECREF(zero);
576 if (res < 0) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
583 PyDict_Size(u->u_cellvars));
584 if (!u->u_freevars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_blocks = NULL;
590 u->u_nfblocks = 0;
591 u->u_firstlineno = lineno;
592 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000593 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_lineno_set = 0;
595 u->u_consts = PyDict_New();
596 if (!u->u_consts) {
597 compiler_unit_free(u);
598 return 0;
599 }
600 u->u_names = PyDict_New();
601 if (!u->u_names) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Push the old compiler_unit on the stack. */
609 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400610 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
612 Py_XDECREF(capsule);
613 compiler_unit_free(u);
614 return 0;
615 }
616 Py_DECREF(capsule);
617 u->u_private = c->u->u_private;
618 Py_XINCREF(u->u_private);
619 }
620 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 c->c_nestlevel++;
623 if (compiler_use_new_block(c) == NULL)
624 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400626 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
627 if (!compiler_set_qualname(c))
628 return 0;
629 }
630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632}
633
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000634static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635compiler_exit_scope(struct compiler *c)
636{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100637 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 c->c_nestlevel--;
641 compiler_unit_free(c->u);
642 /* Restore c->u to the parent unit. */
643 n = PyList_GET_SIZE(c->c_stack) - 1;
644 if (n >= 0) {
645 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400646 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 assert(c->u);
648 /* we are deleting from a list so this really shouldn't fail */
649 if (PySequence_DelItem(c->c_stack, n) < 0)
650 Py_FatalError("compiler_exit_scope()");
651 compiler_unit_check(c->u);
652 }
653 else
654 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400658static int
659compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100661 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400662 _Py_static_string(dot_locals, ".<locals>");
663 Py_ssize_t stack_size;
664 struct compiler_unit *u = c->u;
665 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400669 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 if (stack_size > 1) {
671 int scope, force_global = 0;
672 struct compiler_unit *parent;
673 PyObject *mangled, *capsule;
674
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400675 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400676 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 assert(parent);
678
Yury Selivanov75445082015-05-11 22:57:16 -0400679 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
680 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
681 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 assert(u->u_name);
683 mangled = _Py_Mangle(parent->u_private, u->u_name);
684 if (!mangled)
685 return 0;
686 scope = PyST_GetScope(parent->u_ste, mangled);
687 Py_DECREF(mangled);
688 assert(scope != GLOBAL_IMPLICIT);
689 if (scope == GLOBAL_EXPLICIT)
690 force_global = 1;
691 }
692
693 if (!force_global) {
694 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400695 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
697 dot_locals_str = _PyUnicode_FromId(&dot_locals);
698 if (dot_locals_str == NULL)
699 return 0;
700 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
701 if (base == NULL)
702 return 0;
703 }
704 else {
705 Py_INCREF(parent->u_qualname);
706 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400707 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100708 }
709 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400711 if (base != NULL) {
712 dot_str = _PyUnicode_FromId(&dot);
713 if (dot_str == NULL) {
714 Py_DECREF(base);
715 return 0;
716 }
717 name = PyUnicode_Concat(base, dot_str);
718 Py_DECREF(base);
719 if (name == NULL)
720 return 0;
721 PyUnicode_Append(&name, u->u_name);
722 if (name == NULL)
723 return 0;
724 }
725 else {
726 Py_INCREF(u->u_name);
727 name = u->u_name;
728 }
729 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100732}
733
Eric V. Smith235a6f02015-09-19 14:51:32 -0400734
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735/* Allocate a new block and return a pointer to it.
736 Returns NULL on error.
737*/
738
739static basicblock *
740compiler_new_block(struct compiler *c)
741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 basicblock *b;
743 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 u = c->u;
746 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
747 if (b == NULL) {
748 PyErr_NoMemory();
749 return NULL;
750 }
751 memset((void *)b, 0, sizeof(basicblock));
752 /* Extend the singly linked list of blocks with new block. */
753 b->b_list = u->u_blocks;
754 u->u_blocks = b;
755 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756}
757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758static basicblock *
759compiler_use_new_block(struct compiler *c)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 basicblock *block = compiler_new_block(c);
762 if (block == NULL)
763 return NULL;
764 c->u->u_curblock = block;
765 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766}
767
768static basicblock *
769compiler_next_block(struct compiler *c)
770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 basicblock *block = compiler_new_block(c);
772 if (block == NULL)
773 return NULL;
774 c->u->u_curblock->b_next = block;
775 c->u->u_curblock = block;
776 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777}
778
779static basicblock *
780compiler_use_next_block(struct compiler *c, basicblock *block)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 assert(block != NULL);
783 c->u->u_curblock->b_next = block;
784 c->u->u_curblock = block;
785 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000786}
787
788/* Returns the offset of the next instruction in the current block's
789 b_instr array. Resizes the b_instr as necessary.
790 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000791*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000792
793static int
794compiler_next_instr(struct compiler *c, basicblock *b)
795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 assert(b != NULL);
797 if (b->b_instr == NULL) {
798 b->b_instr = (struct instr *)PyObject_Malloc(
799 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
800 if (b->b_instr == NULL) {
801 PyErr_NoMemory();
802 return -1;
803 }
804 b->b_ialloc = DEFAULT_BLOCK_SIZE;
805 memset((char *)b->b_instr, 0,
806 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
807 }
808 else if (b->b_iused == b->b_ialloc) {
809 struct instr *tmp;
810 size_t oldsize, newsize;
811 oldsize = b->b_ialloc * sizeof(struct instr);
812 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (oldsize > (PY_SIZE_MAX >> 1)) {
815 PyErr_NoMemory();
816 return -1;
817 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (newsize == 0) {
820 PyErr_NoMemory();
821 return -1;
822 }
823 b->b_ialloc <<= 1;
824 tmp = (struct instr *)PyObject_Realloc(
825 (void *)b->b_instr, newsize);
826 if (tmp == NULL) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 b->b_instr = tmp;
831 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
832 }
833 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000834}
835
Christian Heimes2202f872008-02-06 14:31:34 +0000836/* Set the i_lineno member of the instruction at offset off if the
837 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838 already been set. If it has been set, the call has no effect.
839
Christian Heimes2202f872008-02-06 14:31:34 +0000840 The line number is reset in the following cases:
841 - when entering a new scope
842 - on each statement
843 - on each expression that start a new line
844 - before the "except" clause
845 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000846*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848static void
849compiler_set_lineno(struct compiler *c, int off)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 basicblock *b;
852 if (c->u->u_lineno_set)
853 return;
854 c->u->u_lineno_set = 1;
855 b = c->u->u_curblock;
856 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000857}
858
Larry Hastings3a907972013-11-23 14:49:22 -0800859int
860PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 switch (opcode) {
863 case POP_TOP:
864 return -1;
865 case ROT_TWO:
866 case ROT_THREE:
867 return 0;
868 case DUP_TOP:
869 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000870 case DUP_TOP_TWO:
871 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 case UNARY_POSITIVE:
874 case UNARY_NEGATIVE:
875 case UNARY_NOT:
876 case UNARY_INVERT:
877 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 case SET_ADD:
880 case LIST_APPEND:
881 return -1;
882 case MAP_ADD:
883 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_POWER:
886 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400887 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case BINARY_MODULO:
889 case BINARY_ADD:
890 case BINARY_SUBTRACT:
891 case BINARY_SUBSCR:
892 case BINARY_FLOOR_DIVIDE:
893 case BINARY_TRUE_DIVIDE:
894 return -1;
895 case INPLACE_FLOOR_DIVIDE:
896 case INPLACE_TRUE_DIVIDE:
897 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 case INPLACE_ADD:
900 case INPLACE_SUBTRACT:
901 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400902 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case INPLACE_MODULO:
904 return -1;
905 case STORE_SUBSCR:
906 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case DELETE_SUBSCR:
908 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case BINARY_LSHIFT:
911 case BINARY_RSHIFT:
912 case BINARY_AND:
913 case BINARY_XOR:
914 case BINARY_OR:
915 return -1;
916 case INPLACE_POWER:
917 return -1;
918 case GET_ITER:
919 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case PRINT_EXPR:
922 return -1;
923 case LOAD_BUILD_CLASS:
924 return 1;
925 case INPLACE_LSHIFT:
926 case INPLACE_RSHIFT:
927 case INPLACE_AND:
928 case INPLACE_XOR:
929 case INPLACE_OR:
930 return -1;
931 case BREAK_LOOP:
932 return 0;
933 case SETUP_WITH:
934 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400935 case WITH_CLEANUP_START:
936 return 1;
937 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case RETURN_VALUE:
940 return -1;
941 case IMPORT_STAR:
942 return -1;
943 case YIELD_VALUE:
944 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500945 case YIELD_FROM:
946 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case POP_BLOCK:
948 return 0;
949 case POP_EXCEPT:
950 return 0; /* -3 except if bad bytecode */
951 case END_FINALLY:
952 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 case STORE_NAME:
955 return -1;
956 case DELETE_NAME:
957 return 0;
958 case UNPACK_SEQUENCE:
959 return oparg-1;
960 case UNPACK_EX:
961 return (oparg&0xFF) + (oparg>>8);
962 case FOR_ITER:
963 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case STORE_ATTR:
966 return -2;
967 case DELETE_ATTR:
968 return -1;
969 case STORE_GLOBAL:
970 return -1;
971 case DELETE_GLOBAL:
972 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case LOAD_CONST:
974 return 1;
975 case LOAD_NAME:
976 return 1;
977 case BUILD_TUPLE:
978 case BUILD_LIST:
979 case BUILD_SET:
980 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400981 case BUILD_LIST_UNPACK:
982 case BUILD_TUPLE_UNPACK:
983 case BUILD_SET_UNPACK:
984 case BUILD_MAP_UNPACK:
985 return 1 - oparg;
986 case BUILD_MAP_UNPACK_WITH_CALL:
987 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700989 return 1 - 2*oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case LOAD_ATTR:
991 return 0;
992 case COMPARE_OP:
993 return -1;
994 case IMPORT_NAME:
995 return -1;
996 case IMPORT_FROM:
997 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case JUMP_FORWARD:
1000 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1001 case JUMP_IF_FALSE_OR_POP: /* "" */
1002 case JUMP_ABSOLUTE:
1003 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case POP_JUMP_IF_FALSE:
1006 case POP_JUMP_IF_TRUE:
1007 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_GLOBAL:
1010 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 case CONTINUE_LOOP:
1013 return 0;
1014 case SETUP_LOOP:
1015 return 0;
1016 case SETUP_EXCEPT:
1017 case SETUP_FINALLY:
1018 return 6; /* can push 3 values for the new exception
1019 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case LOAD_FAST:
1022 return 1;
1023 case STORE_FAST:
1024 return -1;
1025 case DELETE_FAST:
1026 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case RAISE_VARARGS:
1029 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001030#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case CALL_FUNCTION:
1032 return -NARGS(oparg);
1033 case CALL_FUNCTION_VAR:
1034 case CALL_FUNCTION_KW:
1035 return -NARGS(oparg)-1;
1036 case CALL_FUNCTION_VAR_KW:
1037 return -NARGS(oparg)-2;
1038 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001039 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001041 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001042#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case BUILD_SLICE:
1044 if (oparg == 3)
1045 return -2;
1046 else
1047 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case LOAD_CLOSURE:
1050 return 1;
1051 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001052 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return 1;
1054 case STORE_DEREF:
1055 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001056 case DELETE_DEREF:
1057 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001058 case GET_AWAITABLE:
1059 return 0;
1060 case SETUP_ASYNC_WITH:
1061 return 6;
1062 case BEFORE_ASYNC_WITH:
1063 return 1;
1064 case GET_AITER:
1065 return 0;
1066 case GET_ANEXT:
1067 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001068 case GET_YIELD_FROM_ITER:
1069 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001070 case FORMAT_VALUE:
1071 /* If there's a fmt_spec on the stack, we go from 2->1,
1072 else 1->1. */
1073 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001075 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 }
Larry Hastings3a907972013-11-23 14:49:22 -08001077 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078}
1079
1080/* Add an opcode with no argument.
1081 Returns 0 on failure, 1 on success.
1082*/
1083
1084static int
1085compiler_addop(struct compiler *c, int opcode)
1086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 basicblock *b;
1088 struct instr *i;
1089 int off;
1090 off = compiler_next_instr(c, c->u->u_curblock);
1091 if (off < 0)
1092 return 0;
1093 b = c->u->u_curblock;
1094 i = &b->b_instr[off];
1095 i->i_opcode = opcode;
1096 i->i_hasarg = 0;
1097 if (opcode == RETURN_VALUE)
1098 b->b_return = 1;
1099 compiler_set_lineno(c, off);
1100 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001101}
1102
Victor Stinnerf8e32212013-11-19 23:56:34 +01001103static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 PyObject *t, *v;
1107 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108
Victor Stinnerefb24132016-01-22 12:33:12 +01001109 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (t == NULL)
1111 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 v = PyDict_GetItem(dict, t);
1114 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001115 if (PyErr_Occurred()) {
1116 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001120 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (!v) {
1122 Py_DECREF(t);
1123 return -1;
1124 }
1125 if (PyDict_SetItem(dict, t, v) < 0) {
1126 Py_DECREF(t);
1127 Py_DECREF(v);
1128 return -1;
1129 }
1130 Py_DECREF(v);
1131 }
1132 else
1133 arg = PyLong_AsLong(v);
1134 Py_DECREF(t);
1135 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136}
1137
1138static int
1139compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001142 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001144 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 return compiler_addop_i(c, opcode, arg);
1146}
1147
1148static int
1149compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001152 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1154 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 arg = compiler_add_o(c, dict, mangled);
1157 Py_DECREF(mangled);
1158 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001159 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160 return compiler_addop_i(c, opcode, arg);
1161}
1162
1163/* Add an opcode with an integer argument.
1164 Returns 0 on failure, 1 on success.
1165*/
1166
1167static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001168compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 struct instr *i;
1171 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001172
1173 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1174 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001175 assert((-2147483647-1) <= oparg);
1176 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 off = compiler_next_instr(c, c->u->u_curblock);
1179 if (off < 0)
1180 return 0;
1181 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001182 i->i_opcode = opcode;
1183 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 i->i_hasarg = 1;
1185 compiler_set_lineno(c, off);
1186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187}
1188
1189static int
1190compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 struct instr *i;
1193 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 assert(b != NULL);
1196 off = compiler_next_instr(c, c->u->u_curblock);
1197 if (off < 0)
1198 return 0;
1199 i = &c->u->u_curblock->b_instr[off];
1200 i->i_opcode = opcode;
1201 i->i_target = b;
1202 i->i_hasarg = 1;
1203 if (absolute)
1204 i->i_jabs = 1;
1205 else
1206 i->i_jrel = 1;
1207 compiler_set_lineno(c, off);
1208 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209}
1210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1212 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 it as the current block. NEXT_BLOCK() also creates an implicit jump
1214 from the current block to the new block.
1215*/
1216
Thomas Wouters89f507f2006-12-13 04:49:30 +00001217/* The returns inside these macros make it impossible to decref objects
1218 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219*/
1220
1221
1222#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (compiler_use_new_block((C)) == NULL) \
1224 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
1227#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (compiler_next_block((C)) == NULL) \
1229 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230}
1231
1232#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (!compiler_addop((C), (OP))) \
1234 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001237#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (!compiler_addop((C), (OP))) { \
1239 compiler_exit_scope(c); \
1240 return 0; \
1241 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001242}
1243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1246 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247}
1248
1249#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1251 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (!compiler_addop_i((C), (OP), (O))) \
1256 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (!compiler_addop_j((C), (OP), (O), 1)) \
1261 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262}
1263
1264#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!compiler_addop_j((C), (OP), (O), 0)) \
1266 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
1269/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1270 the ASDL name to synthesize the name of the C type and the visit function.
1271*/
1272
1273#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!compiler_visit_ ## TYPE((C), (V))) \
1275 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001278#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_visit_ ## TYPE((C), (V))) { \
1280 compiler_exit_scope(c); \
1281 return 0; \
1282 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001283}
1284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (!compiler_visit_slice((C), (V), (CTX))) \
1287 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288}
1289
1290#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 int _i; \
1292 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1293 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1294 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1295 if (!compiler_visit_ ## TYPE((C), elt)) \
1296 return 0; \
1297 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298}
1299
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001300#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int _i; \
1302 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1303 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1304 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1305 if (!compiler_visit_ ## TYPE((C), elt)) { \
1306 compiler_exit_scope(c); \
1307 return 0; \
1308 } \
1309 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001310}
1311
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312static int
1313compiler_isdocstring(stmt_ty s)
1314{
1315 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001316 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317 return s->v.Expr.value->kind == Str_kind;
1318}
1319
1320/* Compile a sequence of statements, checking for a docstring. */
1321
1322static int
1323compiler_body(struct compiler *c, asdl_seq *stmts)
1324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 int i = 0;
1326 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (!asdl_seq_LEN(stmts))
1329 return 1;
1330 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001331 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* don't generate docstrings if -OO */
1333 i = 1;
1334 VISIT(c, expr, st->v.Expr.value);
1335 if (!compiler_nameop(c, __doc__, Store))
1336 return 0;
1337 }
1338 for (; i < asdl_seq_LEN(stmts); i++)
1339 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1340 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341}
1342
1343static PyCodeObject *
1344compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 PyCodeObject *co;
1347 int addNone = 1;
1348 static PyObject *module;
1349 if (!module) {
1350 module = PyUnicode_InternFromString("<module>");
1351 if (!module)
1352 return NULL;
1353 }
1354 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001355 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 return NULL;
1357 switch (mod->kind) {
1358 case Module_kind:
1359 if (!compiler_body(c, mod->v.Module.body)) {
1360 compiler_exit_scope(c);
1361 return 0;
1362 }
1363 break;
1364 case Interactive_kind:
1365 c->c_interactive = 1;
1366 VISIT_SEQ_IN_SCOPE(c, stmt,
1367 mod->v.Interactive.body);
1368 break;
1369 case Expression_kind:
1370 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1371 addNone = 0;
1372 break;
1373 case Suite_kind:
1374 PyErr_SetString(PyExc_SystemError,
1375 "suite should not be possible");
1376 return 0;
1377 default:
1378 PyErr_Format(PyExc_SystemError,
1379 "module kind %d should not be possible",
1380 mod->kind);
1381 return 0;
1382 }
1383 co = assemble(c, addNone);
1384 compiler_exit_scope(c);
1385 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001386}
1387
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388/* The test for LOCAL must come before the test for FREE in order to
1389 handle classes where name is both local and free. The local var is
1390 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001391*/
1392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393static int
1394get_ref_type(struct compiler *c, PyObject *name)
1395{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001396 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001397 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1398 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1399 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001400 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (scope == 0) {
1402 char buf[350];
1403 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001404 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001406 PyUnicode_AsUTF8(name),
1407 PyUnicode_AsUTF8(c->u->u_name),
1408 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1409 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1410 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1411 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 );
1413 Py_FatalError(buf);
1414 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417}
1418
1419static int
1420compiler_lookup_arg(PyObject *dict, PyObject *name)
1421{
1422 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001423 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001425 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001427 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001429 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001430 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431}
1432
1433static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001434compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001436 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001437 if (qualname == NULL)
1438 qualname = co->co_name;
1439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (free == 0) {
1441 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001442 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 ADDOP_I(c, MAKE_FUNCTION, args);
1444 return 1;
1445 }
1446 for (i = 0; i < free; ++i) {
1447 /* Bypass com_addop_varname because it will generate
1448 LOAD_DEREF but LOAD_CLOSURE is needed.
1449 */
1450 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1451 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* Special case: If a class contains a method with a
1454 free variable that has the same name as a method,
1455 the name will be considered free *and* local in the
1456 class. It should be handled by the closure, as
1457 well as by the normal name loookup logic.
1458 */
1459 reftype = get_ref_type(c, name);
1460 if (reftype == CELL)
1461 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1462 else /* (reftype == FREE) */
1463 arg = compiler_lookup_arg(c->u->u_freevars, name);
1464 if (arg == -1) {
1465 fprintf(stderr,
1466 "lookup %s in %s %d %d\n"
1467 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001468 PyUnicode_AsUTF8(PyObject_Repr(name)),
1469 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001471 PyUnicode_AsUTF8(co->co_name),
1472 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 Py_FatalError("compiler_make_closure()");
1474 }
1475 ADDOP_I(c, LOAD_CLOSURE, arg);
1476 }
1477 ADDOP_I(c, BUILD_TUPLE, free);
1478 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001479 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 ADDOP_I(c, MAKE_CLOSURE, args);
1481 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482}
1483
1484static int
1485compiler_decorators(struct compiler *c, asdl_seq* decos)
1486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (!decos)
1490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1493 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1494 }
1495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001499compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 int i, default_count = 0;
1503 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1504 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1505 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1506 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001507 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1508 if (!mangled)
1509 return -1;
1510 ADDOP_O(c, LOAD_CONST, mangled, consts);
1511 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (!compiler_visit_expr(c, default_)) {
1513 return -1;
1514 }
1515 default_count++;
1516 }
1517 }
1518 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001519}
1520
1521static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001522compiler_visit_argannotation(struct compiler *c, identifier id,
1523 expr_ty annotation, PyObject *names)
1524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001526 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001528 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001529 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001530 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001531 if (PyList_Append(names, mangled) < 0) {
1532 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001533 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001534 }
1535 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001537 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001538}
1539
1540static int
1541compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1542 PyObject *names)
1543{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001544 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 for (i = 0; i < asdl_seq_LEN(args); i++) {
1546 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001547 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 c,
1549 arg->arg,
1550 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001551 names))
1552 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001554 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001555}
1556
1557static int
1558compiler_visit_annotations(struct compiler *c, arguments_ty args,
1559 expr_ty returns)
1560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* Push arg annotations and a list of the argument names. Return the #
1562 of items pushed. The expressions are evaluated out-of-order wrt the
1563 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1566 */
1567 static identifier return_str;
1568 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001569 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 names = PyList_New(0);
1571 if (!names)
1572 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001573
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001574 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001576 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001577 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001578 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001580 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001582 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001583 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001584 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if (!return_str) {
1588 return_str = PyUnicode_InternFromString("return");
1589 if (!return_str)
1590 goto error;
1591 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001592 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 goto error;
1594 }
1595
1596 len = PyList_GET_SIZE(names);
1597 if (len > 65534) {
1598 /* len must fit in 16 bits, and len is incremented below */
1599 PyErr_SetString(PyExc_SyntaxError,
1600 "too many annotations");
1601 goto error;
1602 }
1603 if (len) {
1604 /* convert names to a tuple and place on stack */
1605 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001606 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyObject *s = PyTuple_New(len);
1608 if (!s)
1609 goto error;
1610 for (i = 0; i < len; i++) {
1611 elt = PyList_GET_ITEM(names, i);
1612 Py_INCREF(elt);
1613 PyTuple_SET_ITEM(s, i, elt);
1614 }
1615 ADDOP_O(c, LOAD_CONST, s, consts);
1616 Py_DECREF(s);
1617 len++; /* include the just-pushed tuple */
1618 }
1619 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001620
1621 /* We just checked that len <= 65535, see above */
1622 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001623
1624error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 Py_DECREF(names);
1626 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001627}
1628
1629static int
Yury Selivanov75445082015-05-11 22:57:16 -04001630compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001633 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001634 arguments_ty args;
1635 expr_ty returns;
1636 identifier name;
1637 asdl_seq* decos;
1638 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001640 Py_ssize_t i, n, arglength;
1641 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001643 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644
Yury Selivanov75445082015-05-11 22:57:16 -04001645
1646 if (is_async) {
1647 assert(s->kind == AsyncFunctionDef_kind);
1648
1649 args = s->v.AsyncFunctionDef.args;
1650 returns = s->v.AsyncFunctionDef.returns;
1651 decos = s->v.AsyncFunctionDef.decorator_list;
1652 name = s->v.AsyncFunctionDef.name;
1653 body = s->v.AsyncFunctionDef.body;
1654
1655 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1656 } else {
1657 assert(s->kind == FunctionDef_kind);
1658
1659 args = s->v.FunctionDef.args;
1660 returns = s->v.FunctionDef.returns;
1661 decos = s->v.FunctionDef.decorator_list;
1662 name = s->v.FunctionDef.name;
1663 body = s->v.FunctionDef.body;
1664
1665 scope_type = COMPILER_SCOPE_FUNCTION;
1666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (!compiler_decorators(c, decos))
1669 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001670 if (args->defaults)
1671 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (args->kwonlyargs) {
1673 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1674 args->kw_defaults);
1675 if (res < 0)
1676 return 0;
1677 kw_default_count = res;
1678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 num_annotations = compiler_visit_annotations(c, args, returns);
1680 if (num_annotations < 0)
1681 return 0;
1682 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001683
Yury Selivanov75445082015-05-11 22:57:16 -04001684 if (!compiler_enter_scope(c, name,
1685 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 s->lineno))
1687 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688
Yury Selivanov75445082015-05-11 22:57:16 -04001689 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001691 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 first_const = st->v.Expr.value->v.Str.s;
1693 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1694 compiler_exit_scope(c);
1695 return 0;
1696 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 c->u->u_argcount = asdl_seq_LEN(args->args);
1699 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001700 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* if there was a docstring, we need to skip the first statement */
1702 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001703 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 VISIT_IN_SCOPE(c, stmt, st);
1705 }
1706 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001707 qualname = c->u->u_qualname;
1708 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001710 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001711 Py_XDECREF(qualname);
1712 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001714 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 arglength = asdl_seq_LEN(args->defaults);
1717 arglength |= kw_default_count << 8;
1718 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001719 if (is_async)
1720 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001721 compiler_make_closure(c, co, arglength, qualname);
1722 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* decorators */
1726 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1727 ADDOP_I(c, CALL_FUNCTION, 1);
1728 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001729
Yury Selivanov75445082015-05-11 22:57:16 -04001730 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731}
1732
1733static int
1734compiler_class(struct compiler *c, stmt_ty s)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyCodeObject *co;
1737 PyObject *str;
1738 int i;
1739 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (!compiler_decorators(c, decos))
1742 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* ultimately generate code for:
1745 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1746 where:
1747 <func> is a function/closure created from the class body;
1748 it has a single argument (__locals__) where the dict
1749 (or MutableSequence) representing the locals is passed
1750 <name> is the class name
1751 <bases> is the positional arguments and *varargs argument
1752 <keywords> is the keyword arguments and **kwds argument
1753 This borrows from compiler_call.
1754 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001757 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1758 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 return 0;
1760 /* this block represents what we do in the new scope */
1761 {
1762 /* use the class name for name mangling */
1763 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001764 Py_SETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 /* load (global) __name__ ... */
1766 str = PyUnicode_InternFromString("__name__");
1767 if (!str || !compiler_nameop(c, str, Load)) {
1768 Py_XDECREF(str);
1769 compiler_exit_scope(c);
1770 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 Py_DECREF(str);
1773 /* ... and store it as __module__ */
1774 str = PyUnicode_InternFromString("__module__");
1775 if (!str || !compiler_nameop(c, str, Store)) {
1776 Py_XDECREF(str);
1777 compiler_exit_scope(c);
1778 return 0;
1779 }
1780 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001781 assert(c->u->u_qualname);
1782 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001783 str = PyUnicode_InternFromString("__qualname__");
1784 if (!str || !compiler_nameop(c, str, Store)) {
1785 Py_XDECREF(str);
1786 compiler_exit_scope(c);
1787 return 0;
1788 }
1789 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* compile the body proper */
1791 if (!compiler_body(c, s->v.ClassDef.body)) {
1792 compiler_exit_scope(c);
1793 return 0;
1794 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001795 if (c->u->u_ste->ste_needs_class_closure) {
1796 /* return the (empty) __class__ cell */
1797 str = PyUnicode_InternFromString("__class__");
1798 if (str == NULL) {
1799 compiler_exit_scope(c);
1800 return 0;
1801 }
1802 i = compiler_lookup_arg(c->u->u_cellvars, str);
1803 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001804 if (i < 0) {
1805 compiler_exit_scope(c);
1806 return 0;
1807 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001808 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* Return the cell where to store __class__ */
1810 ADDOP_I(c, LOAD_CLOSURE, i);
1811 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001812 else {
1813 assert(PyDict_Size(c->u->u_cellvars) == 0);
1814 /* This happens when nobody references the cell. Return None. */
1815 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1818 /* create the code object */
1819 co = assemble(c, 1);
1820 }
1821 /* leave the new scope */
1822 compiler_exit_scope(c);
1823 if (co == NULL)
1824 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 /* 2. load the 'build_class' function */
1827 ADDOP(c, LOAD_BUILD_CLASS);
1828
1829 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001830 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 Py_DECREF(co);
1832
1833 /* 4. load class name */
1834 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1835
1836 /* 5. generate the rest of the code for the call */
1837 if (!compiler_call_helper(c, 2,
1838 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001839 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 return 0;
1841
1842 /* 6. apply decorators */
1843 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1844 ADDOP_I(c, CALL_FUNCTION, 1);
1845 }
1846
1847 /* 7. store into <name> */
1848 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1849 return 0;
1850 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
1853static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001854compiler_ifexp(struct compiler *c, expr_ty e)
1855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 basicblock *end, *next;
1857
1858 assert(e->kind == IfExp_kind);
1859 end = compiler_new_block(c);
1860 if (end == NULL)
1861 return 0;
1862 next = compiler_new_block(c);
1863 if (next == NULL)
1864 return 0;
1865 VISIT(c, expr, e->v.IfExp.test);
1866 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1867 VISIT(c, expr, e->v.IfExp.body);
1868 ADDOP_JREL(c, JUMP_FORWARD, end);
1869 compiler_use_next_block(c, next);
1870 VISIT(c, expr, e->v.IfExp.orelse);
1871 compiler_use_next_block(c, end);
1872 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001873}
1874
1875static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876compiler_lambda(struct compiler *c, expr_ty e)
1877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001879 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001881 int kw_default_count = 0;
1882 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 arguments_ty args = e->v.Lambda.args;
1884 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (!name) {
1887 name = PyUnicode_InternFromString("<lambda>");
1888 if (!name)
1889 return 0;
1890 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001892 if (args->defaults)
1893 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (args->kwonlyargs) {
1895 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1896 args->kw_defaults);
1897 if (res < 0) return 0;
1898 kw_default_count = res;
1899 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001900 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001901 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* Make None the first constant, so the lambda can't have a
1905 docstring. */
1906 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1907 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 c->u->u_argcount = asdl_seq_LEN(args->args);
1910 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1911 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1912 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001913 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 }
1915 else {
1916 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001917 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001919 qualname = c->u->u_qualname;
1920 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001922 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 arglength = asdl_seq_LEN(args->defaults);
1926 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001927 compiler_make_closure(c, co, arglength, qualname);
1928 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 Py_DECREF(co);
1930
1931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932}
1933
1934static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935compiler_if(struct compiler *c, stmt_ty s)
1936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 basicblock *end, *next;
1938 int constant;
1939 assert(s->kind == If_kind);
1940 end = compiler_new_block(c);
1941 if (end == NULL)
1942 return 0;
1943
Georg Brandl8334fd92010-12-04 10:26:46 +00001944 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* constant = 0: "if 0"
1946 * constant = 1: "if 1", "if 2", ...
1947 * constant = -1: rest */
1948 if (constant == 0) {
1949 if (s->v.If.orelse)
1950 VISIT_SEQ(c, stmt, s->v.If.orelse);
1951 } else if (constant == 1) {
1952 VISIT_SEQ(c, stmt, s->v.If.body);
1953 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001954 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 next = compiler_new_block(c);
1956 if (next == NULL)
1957 return 0;
1958 }
1959 else
1960 next = end;
1961 VISIT(c, expr, s->v.If.test);
1962 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1963 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001964 if (asdl_seq_LEN(s->v.If.orelse)) {
1965 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 compiler_use_next_block(c, next);
1967 VISIT_SEQ(c, stmt, s->v.If.orelse);
1968 }
1969 }
1970 compiler_use_next_block(c, end);
1971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972}
1973
1974static int
1975compiler_for(struct compiler *c, stmt_ty s)
1976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 start = compiler_new_block(c);
1980 cleanup = compiler_new_block(c);
1981 end = compiler_new_block(c);
1982 if (start == NULL || end == NULL || cleanup == NULL)
1983 return 0;
1984 ADDOP_JREL(c, SETUP_LOOP, end);
1985 if (!compiler_push_fblock(c, LOOP, start))
1986 return 0;
1987 VISIT(c, expr, s->v.For.iter);
1988 ADDOP(c, GET_ITER);
1989 compiler_use_next_block(c, start);
1990 ADDOP_JREL(c, FOR_ITER, cleanup);
1991 VISIT(c, expr, s->v.For.target);
1992 VISIT_SEQ(c, stmt, s->v.For.body);
1993 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1994 compiler_use_next_block(c, cleanup);
1995 ADDOP(c, POP_BLOCK);
1996 compiler_pop_fblock(c, LOOP, start);
1997 VISIT_SEQ(c, stmt, s->v.For.orelse);
1998 compiler_use_next_block(c, end);
1999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000}
2001
Yury Selivanov75445082015-05-11 22:57:16 -04002002
2003static int
2004compiler_async_for(struct compiler *c, stmt_ty s)
2005{
2006 static PyObject *stopiter_error = NULL;
2007 basicblock *try, *except, *end, *after_try, *try_cleanup,
2008 *after_loop, *after_loop_else;
2009
2010 if (stopiter_error == NULL) {
2011 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2012 if (stopiter_error == NULL)
2013 return 0;
2014 }
2015
2016 try = compiler_new_block(c);
2017 except = compiler_new_block(c);
2018 end = compiler_new_block(c);
2019 after_try = compiler_new_block(c);
2020 try_cleanup = compiler_new_block(c);
2021 after_loop = compiler_new_block(c);
2022 after_loop_else = compiler_new_block(c);
2023
2024 if (try == NULL || except == NULL || end == NULL
2025 || after_try == NULL || try_cleanup == NULL)
2026 return 0;
2027
2028 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2029 if (!compiler_push_fblock(c, LOOP, try))
2030 return 0;
2031
2032 VISIT(c, expr, s->v.AsyncFor.iter);
2033 ADDOP(c, GET_AITER);
2034 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2035 ADDOP(c, YIELD_FROM);
2036
2037 compiler_use_next_block(c, try);
2038
2039
2040 ADDOP_JREL(c, SETUP_EXCEPT, except);
2041 if (!compiler_push_fblock(c, EXCEPT, try))
2042 return 0;
2043
2044 ADDOP(c, GET_ANEXT);
2045 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2046 ADDOP(c, YIELD_FROM);
2047 VISIT(c, expr, s->v.AsyncFor.target);
2048 ADDOP(c, POP_BLOCK);
2049 compiler_pop_fblock(c, EXCEPT, try);
2050 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2051
2052
2053 compiler_use_next_block(c, except);
2054 ADDOP(c, DUP_TOP);
2055 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2056 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2057 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2058
2059 ADDOP(c, POP_TOP);
2060 ADDOP(c, POP_TOP);
2061 ADDOP(c, POP_TOP);
2062 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2063 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2064 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2065
2066
2067 compiler_use_next_block(c, try_cleanup);
2068 ADDOP(c, END_FINALLY);
2069
2070 compiler_use_next_block(c, after_try);
2071 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2072 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2073
2074 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2075 compiler_pop_fblock(c, LOOP, try);
2076
2077 compiler_use_next_block(c, after_loop);
2078 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2079
2080 compiler_use_next_block(c, after_loop_else);
2081 VISIT_SEQ(c, stmt, s->v.For.orelse);
2082
2083 compiler_use_next_block(c, end);
2084
2085 return 1;
2086}
2087
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088static int
2089compiler_while(struct compiler *c, stmt_ty s)
2090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002092 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (constant == 0) {
2095 if (s->v.While.orelse)
2096 VISIT_SEQ(c, stmt, s->v.While.orelse);
2097 return 1;
2098 }
2099 loop = compiler_new_block(c);
2100 end = compiler_new_block(c);
2101 if (constant == -1) {
2102 anchor = compiler_new_block(c);
2103 if (anchor == NULL)
2104 return 0;
2105 }
2106 if (loop == NULL || end == NULL)
2107 return 0;
2108 if (s->v.While.orelse) {
2109 orelse = compiler_new_block(c);
2110 if (orelse == NULL)
2111 return 0;
2112 }
2113 else
2114 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 ADDOP_JREL(c, SETUP_LOOP, end);
2117 compiler_use_next_block(c, loop);
2118 if (!compiler_push_fblock(c, LOOP, loop))
2119 return 0;
2120 if (constant == -1) {
2121 VISIT(c, expr, s->v.While.test);
2122 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2123 }
2124 VISIT_SEQ(c, stmt, s->v.While.body);
2125 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 /* XXX should the two POP instructions be in a separate block
2128 if there is no else clause ?
2129 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002131 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002133 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 compiler_pop_fblock(c, LOOP, loop);
2135 if (orelse != NULL) /* what if orelse is just pass? */
2136 VISIT_SEQ(c, stmt, s->v.While.orelse);
2137 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140}
2141
2142static int
2143compiler_continue(struct compiler *c)
2144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2146 static const char IN_FINALLY_ERROR_MSG[] =
2147 "'continue' not supported inside 'finally' clause";
2148 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (!c->u->u_nfblocks)
2151 return compiler_error(c, LOOP_ERROR_MSG);
2152 i = c->u->u_nfblocks - 1;
2153 switch (c->u->u_fblock[i].fb_type) {
2154 case LOOP:
2155 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2156 break;
2157 case EXCEPT:
2158 case FINALLY_TRY:
2159 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2160 /* Prevent continue anywhere under a finally
2161 even if hidden in a sub-try or except. */
2162 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2163 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2164 }
2165 if (i == -1)
2166 return compiler_error(c, LOOP_ERROR_MSG);
2167 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2168 break;
2169 case FINALLY_END:
2170 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2171 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174}
2175
2176/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177
2178 SETUP_FINALLY L
2179 <code for body>
2180 POP_BLOCK
2181 LOAD_CONST <None>
2182 L: <code for finalbody>
2183 END_FINALLY
2184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 The special instructions use the block stack. Each block
2186 stack entry contains the instruction that created it (here
2187 SETUP_FINALLY), the level of the value stack at the time the
2188 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Pushes the current value stack level and the label
2192 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 Pops en entry from the block stack, and pops the value
2195 stack until its level is the same as indicated on the
2196 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 Pops a variable number of entries from the *value* stack
2199 and re-raises the exception they specify. The number of
2200 entries popped depends on the (pseudo) exception type.
2201
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202 The block stack is unwound when an exception is raised:
2203 when a SETUP_FINALLY entry is found, the exception is pushed
2204 onto the value stack (and the exception condition is cleared),
2205 and the interpreter jumps to the label gotten from the block
2206 stack.
2207*/
2208
2209static int
2210compiler_try_finally(struct compiler *c, stmt_ty s)
2211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 basicblock *body, *end;
2213 body = compiler_new_block(c);
2214 end = compiler_new_block(c);
2215 if (body == NULL || end == NULL)
2216 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 ADDOP_JREL(c, SETUP_FINALLY, end);
2219 compiler_use_next_block(c, body);
2220 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2221 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002222 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2223 if (!compiler_try_except(c, s))
2224 return 0;
2225 }
2226 else {
2227 VISIT_SEQ(c, stmt, s->v.Try.body);
2228 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 ADDOP(c, POP_BLOCK);
2230 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2233 compiler_use_next_block(c, end);
2234 if (!compiler_push_fblock(c, FINALLY_END, end))
2235 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002236 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 ADDOP(c, END_FINALLY);
2238 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002241}
2242
2243/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002244 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 (The contents of the value stack is shown in [], with the top
2246 at the right; 'tb' is trace-back info, 'val' the exception's
2247 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248
2249 Value stack Label Instruction Argument
2250 [] SETUP_EXCEPT L1
2251 [] <code for S>
2252 [] POP_BLOCK
2253 [] JUMP_FORWARD L0
2254
2255 [tb, val, exc] L1: DUP )
2256 [tb, val, exc, exc] <evaluate E1> )
2257 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2258 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2259 [tb, val, exc] POP
2260 [tb, val] <assign to V1> (or POP if no V1)
2261 [tb] POP
2262 [] <code for S1>
2263 JUMP_FORWARD L0
2264
2265 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 .............................etc.......................
2267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2269
2270 [] L0: <next statement>
2271
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272 Of course, parts are not generated if Vi or Ei is not present.
2273*/
2274static int
2275compiler_try_except(struct compiler *c, stmt_ty s)
2276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002278 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 body = compiler_new_block(c);
2281 except = compiler_new_block(c);
2282 orelse = compiler_new_block(c);
2283 end = compiler_new_block(c);
2284 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2285 return 0;
2286 ADDOP_JREL(c, SETUP_EXCEPT, except);
2287 compiler_use_next_block(c, body);
2288 if (!compiler_push_fblock(c, EXCEPT, body))
2289 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002290 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 ADDOP(c, POP_BLOCK);
2292 compiler_pop_fblock(c, EXCEPT, body);
2293 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002294 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 compiler_use_next_block(c, except);
2296 for (i = 0; i < n; i++) {
2297 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002298 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (!handler->v.ExceptHandler.type && i < n-1)
2300 return compiler_error(c, "default 'except:' must be last");
2301 c->u->u_lineno_set = 0;
2302 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002303 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 except = compiler_new_block(c);
2305 if (except == NULL)
2306 return 0;
2307 if (handler->v.ExceptHandler.type) {
2308 ADDOP(c, DUP_TOP);
2309 VISIT(c, expr, handler->v.ExceptHandler.type);
2310 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2311 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2312 }
2313 ADDOP(c, POP_TOP);
2314 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002315 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002316
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002317 cleanup_end = compiler_new_block(c);
2318 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002319 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002320 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002321
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002322 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2323 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002325 /*
2326 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002327 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002328 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002329 try:
2330 # body
2331 finally:
2332 name = None
2333 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002334 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002336 /* second try: */
2337 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2338 compiler_use_next_block(c, cleanup_body);
2339 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2340 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002342 /* second # body */
2343 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2344 ADDOP(c, POP_BLOCK);
2345 ADDOP(c, POP_EXCEPT);
2346 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002348 /* finally: */
2349 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2350 compiler_use_next_block(c, cleanup_end);
2351 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2352 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002354 /* name = None */
2355 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2356 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002358 /* del name */
2359 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002361 ADDOP(c, END_FINALLY);
2362 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 }
2364 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002365 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002367 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002368 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002369 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370
Guido van Rossumb940e112007-01-10 16:19:56 +00002371 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002372 ADDOP(c, POP_TOP);
2373 compiler_use_next_block(c, cleanup_body);
2374 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2375 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002377 ADDOP(c, POP_EXCEPT);
2378 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 }
2380 ADDOP_JREL(c, JUMP_FORWARD, end);
2381 compiler_use_next_block(c, except);
2382 }
2383 ADDOP(c, END_FINALLY);
2384 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002385 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 compiler_use_next_block(c, end);
2387 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002388}
2389
2390static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002391compiler_try(struct compiler *c, stmt_ty s) {
2392 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2393 return compiler_try_finally(c, s);
2394 else
2395 return compiler_try_except(c, s);
2396}
2397
2398
2399static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400compiler_import_as(struct compiler *c, identifier name, identifier asname)
2401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* The IMPORT_NAME opcode was already generated. This function
2403 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 If there is a dot in name, we need to split it and emit a
2406 LOAD_ATTR for each name.
2407 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2409 PyUnicode_GET_LENGTH(name), 1);
2410 if (dot == -2)
2411 return -1;
2412 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 Py_ssize_t pos = dot + 1;
2415 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 dot = PyUnicode_FindChar(name, '.', pos,
2418 PyUnicode_GET_LENGTH(name), 1);
2419 if (dot == -2)
2420 return -1;
2421 attr = PyUnicode_Substring(name, pos,
2422 (dot != -1) ? dot :
2423 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 if (!attr)
2425 return -1;
2426 ADDOP_O(c, LOAD_ATTR, attr, names);
2427 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 }
2430 }
2431 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432}
2433
2434static int
2435compiler_import(struct compiler *c, stmt_ty s)
2436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* The Import node stores a module name like a.b.c as a single
2438 string. This is convenient for all cases except
2439 import a.b.c as d
2440 where we need to parse that string to extract the individual
2441 module names.
2442 XXX Perhaps change the representation to make this case simpler?
2443 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002444 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 for (i = 0; i < n; i++) {
2447 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2448 int r;
2449 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 level = PyLong_FromLong(0);
2452 if (level == NULL)
2453 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 ADDOP_O(c, LOAD_CONST, level, consts);
2456 Py_DECREF(level);
2457 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2458 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (alias->asname) {
2461 r = compiler_import_as(c, alias->name, alias->asname);
2462 if (!r)
2463 return r;
2464 }
2465 else {
2466 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002467 Py_ssize_t dot = PyUnicode_FindChar(
2468 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002469 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002471 if (tmp == NULL)
2472 return 0;
2473 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 Py_DECREF(tmp);
2477 }
2478 if (!r)
2479 return r;
2480 }
2481 }
2482 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483}
2484
2485static int
2486compiler_from_import(struct compiler *c, stmt_ty s)
2487{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002488 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 PyObject *names = PyTuple_New(n);
2491 PyObject *level;
2492 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (!empty_string) {
2495 empty_string = PyUnicode_FromString("");
2496 if (!empty_string)
2497 return 0;
2498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (!names)
2501 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 level = PyLong_FromLong(s->v.ImportFrom.level);
2504 if (!level) {
2505 Py_DECREF(names);
2506 return 0;
2507 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 /* build up the names */
2510 for (i = 0; i < n; i++) {
2511 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2512 Py_INCREF(alias->name);
2513 PyTuple_SET_ITEM(names, i, alias->name);
2514 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2517 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2518 Py_DECREF(level);
2519 Py_DECREF(names);
2520 return compiler_error(c, "from __future__ imports must occur "
2521 "at the beginning of the file");
2522 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 ADDOP_O(c, LOAD_CONST, level, consts);
2525 Py_DECREF(level);
2526 ADDOP_O(c, LOAD_CONST, names, consts);
2527 Py_DECREF(names);
2528 if (s->v.ImportFrom.module) {
2529 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2530 }
2531 else {
2532 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2533 }
2534 for (i = 0; i < n; i++) {
2535 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2536 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002538 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 assert(n == 1);
2540 ADDOP(c, IMPORT_STAR);
2541 return 1;
2542 }
2543
2544 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2545 store_name = alias->name;
2546 if (alias->asname)
2547 store_name = alias->asname;
2548
2549 if (!compiler_nameop(c, store_name, Store)) {
2550 Py_DECREF(names);
2551 return 0;
2552 }
2553 }
2554 /* remove imported module */
2555 ADDOP(c, POP_TOP);
2556 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557}
2558
2559static int
2560compiler_assert(struct compiler *c, stmt_ty s)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 static PyObject *assertion_error = NULL;
2563 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002564 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565
Georg Brandl8334fd92010-12-04 10:26:46 +00002566 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 return 1;
2568 if (assertion_error == NULL) {
2569 assertion_error = PyUnicode_InternFromString("AssertionError");
2570 if (assertion_error == NULL)
2571 return 0;
2572 }
2573 if (s->v.Assert.test->kind == Tuple_kind &&
2574 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002575 msg = PyUnicode_FromString("assertion is always true, "
2576 "perhaps remove parentheses?");
2577 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002579 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2580 c->c_filename, c->u->u_lineno,
2581 NULL, NULL) == -1) {
2582 Py_DECREF(msg);
2583 return 0;
2584 }
2585 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 }
2587 VISIT(c, expr, s->v.Assert.test);
2588 end = compiler_new_block(c);
2589 if (end == NULL)
2590 return 0;
2591 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2592 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2593 if (s->v.Assert.msg) {
2594 VISIT(c, expr, s->v.Assert.msg);
2595 ADDOP_I(c, CALL_FUNCTION, 1);
2596 }
2597 ADDOP_I(c, RAISE_VARARGS, 1);
2598 compiler_use_next_block(c, end);
2599 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600}
2601
2602static int
2603compiler_visit_stmt(struct compiler *c, stmt_ty s)
2604{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002605 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* Always assign a lineno to the next instruction for a stmt. */
2608 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002609 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 switch (s->kind) {
2613 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002614 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 case ClassDef_kind:
2616 return compiler_class(c, s);
2617 case Return_kind:
2618 if (c->u->u_ste->ste_type != FunctionBlock)
2619 return compiler_error(c, "'return' outside function");
2620 if (s->v.Return.value) {
2621 VISIT(c, expr, s->v.Return.value);
2622 }
2623 else
2624 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2625 ADDOP(c, RETURN_VALUE);
2626 break;
2627 case Delete_kind:
2628 VISIT_SEQ(c, expr, s->v.Delete.targets)
2629 break;
2630 case Assign_kind:
2631 n = asdl_seq_LEN(s->v.Assign.targets);
2632 VISIT(c, expr, s->v.Assign.value);
2633 for (i = 0; i < n; i++) {
2634 if (i < n - 1)
2635 ADDOP(c, DUP_TOP);
2636 VISIT(c, expr,
2637 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2638 }
2639 break;
2640 case AugAssign_kind:
2641 return compiler_augassign(c, s);
2642 case For_kind:
2643 return compiler_for(c, s);
2644 case While_kind:
2645 return compiler_while(c, s);
2646 case If_kind:
2647 return compiler_if(c, s);
2648 case Raise_kind:
2649 n = 0;
2650 if (s->v.Raise.exc) {
2651 VISIT(c, expr, s->v.Raise.exc);
2652 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002653 if (s->v.Raise.cause) {
2654 VISIT(c, expr, s->v.Raise.cause);
2655 n++;
2656 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002658 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002660 case Try_kind:
2661 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 case Assert_kind:
2663 return compiler_assert(c, s);
2664 case Import_kind:
2665 return compiler_import(c, s);
2666 case ImportFrom_kind:
2667 return compiler_from_import(c, s);
2668 case Global_kind:
2669 case Nonlocal_kind:
2670 break;
2671 case Expr_kind:
2672 if (c->c_interactive && c->c_nestlevel <= 1) {
2673 VISIT(c, expr, s->v.Expr.value);
2674 ADDOP(c, PRINT_EXPR);
2675 }
2676 else if (s->v.Expr.value->kind != Str_kind &&
2677 s->v.Expr.value->kind != Num_kind) {
2678 VISIT(c, expr, s->v.Expr.value);
2679 ADDOP(c, POP_TOP);
2680 }
2681 break;
2682 case Pass_kind:
2683 break;
2684 case Break_kind:
2685 if (!compiler_in_loop(c))
2686 return compiler_error(c, "'break' outside loop");
2687 ADDOP(c, BREAK_LOOP);
2688 break;
2689 case Continue_kind:
2690 return compiler_continue(c);
2691 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002692 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002693 case AsyncFunctionDef_kind:
2694 return compiler_function(c, s, 1);
2695 case AsyncWith_kind:
2696 return compiler_async_with(c, s, 0);
2697 case AsyncFor_kind:
2698 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 }
Yury Selivanov75445082015-05-11 22:57:16 -04002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702}
2703
2704static int
2705unaryop(unaryop_ty op)
2706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 switch (op) {
2708 case Invert:
2709 return UNARY_INVERT;
2710 case Not:
2711 return UNARY_NOT;
2712 case UAdd:
2713 return UNARY_POSITIVE;
2714 case USub:
2715 return UNARY_NEGATIVE;
2716 default:
2717 PyErr_Format(PyExc_SystemError,
2718 "unary op %d should not be possible", op);
2719 return 0;
2720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721}
2722
2723static int
2724binop(struct compiler *c, operator_ty op)
2725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 switch (op) {
2727 case Add:
2728 return BINARY_ADD;
2729 case Sub:
2730 return BINARY_SUBTRACT;
2731 case Mult:
2732 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002733 case MatMult:
2734 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 case Div:
2736 return BINARY_TRUE_DIVIDE;
2737 case Mod:
2738 return BINARY_MODULO;
2739 case Pow:
2740 return BINARY_POWER;
2741 case LShift:
2742 return BINARY_LSHIFT;
2743 case RShift:
2744 return BINARY_RSHIFT;
2745 case BitOr:
2746 return BINARY_OR;
2747 case BitXor:
2748 return BINARY_XOR;
2749 case BitAnd:
2750 return BINARY_AND;
2751 case FloorDiv:
2752 return BINARY_FLOOR_DIVIDE;
2753 default:
2754 PyErr_Format(PyExc_SystemError,
2755 "binary op %d should not be possible", op);
2756 return 0;
2757 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758}
2759
2760static int
2761cmpop(cmpop_ty op)
2762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 switch (op) {
2764 case Eq:
2765 return PyCmp_EQ;
2766 case NotEq:
2767 return PyCmp_NE;
2768 case Lt:
2769 return PyCmp_LT;
2770 case LtE:
2771 return PyCmp_LE;
2772 case Gt:
2773 return PyCmp_GT;
2774 case GtE:
2775 return PyCmp_GE;
2776 case Is:
2777 return PyCmp_IS;
2778 case IsNot:
2779 return PyCmp_IS_NOT;
2780 case In:
2781 return PyCmp_IN;
2782 case NotIn:
2783 return PyCmp_NOT_IN;
2784 default:
2785 return PyCmp_BAD;
2786 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787}
2788
2789static int
2790inplace_binop(struct compiler *c, operator_ty op)
2791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 switch (op) {
2793 case Add:
2794 return INPLACE_ADD;
2795 case Sub:
2796 return INPLACE_SUBTRACT;
2797 case Mult:
2798 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002799 case MatMult:
2800 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 case Div:
2802 return INPLACE_TRUE_DIVIDE;
2803 case Mod:
2804 return INPLACE_MODULO;
2805 case Pow:
2806 return INPLACE_POWER;
2807 case LShift:
2808 return INPLACE_LSHIFT;
2809 case RShift:
2810 return INPLACE_RSHIFT;
2811 case BitOr:
2812 return INPLACE_OR;
2813 case BitXor:
2814 return INPLACE_XOR;
2815 case BitAnd:
2816 return INPLACE_AND;
2817 case FloorDiv:
2818 return INPLACE_FLOOR_DIVIDE;
2819 default:
2820 PyErr_Format(PyExc_SystemError,
2821 "inplace binary op %d should not be possible", op);
2822 return 0;
2823 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824}
2825
2826static int
2827compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2828{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002829 int op, scope;
2830 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 PyObject *dict = c->u->u_names;
2834 PyObject *mangled;
2835 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 mangled = _Py_Mangle(c->u->u_private, name);
2838 if (!mangled)
2839 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002840
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002841 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2842 PyUnicode_CompareWithASCIIString(name, "True") &&
2843 PyUnicode_CompareWithASCIIString(name, "False"));
2844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 op = 0;
2846 optype = OP_NAME;
2847 scope = PyST_GetScope(c->u->u_ste, mangled);
2848 switch (scope) {
2849 case FREE:
2850 dict = c->u->u_freevars;
2851 optype = OP_DEREF;
2852 break;
2853 case CELL:
2854 dict = c->u->u_cellvars;
2855 optype = OP_DEREF;
2856 break;
2857 case LOCAL:
2858 if (c->u->u_ste->ste_type == FunctionBlock)
2859 optype = OP_FAST;
2860 break;
2861 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002862 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 optype = OP_GLOBAL;
2864 break;
2865 case GLOBAL_EXPLICIT:
2866 optype = OP_GLOBAL;
2867 break;
2868 default:
2869 /* scope can be 0 */
2870 break;
2871 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002874 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 switch (optype) {
2877 case OP_DEREF:
2878 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002879 case Load:
2880 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2881 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 case Store: op = STORE_DEREF; break;
2883 case AugLoad:
2884 case AugStore:
2885 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002886 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 case Param:
2888 default:
2889 PyErr_SetString(PyExc_SystemError,
2890 "param invalid for deref variable");
2891 return 0;
2892 }
2893 break;
2894 case OP_FAST:
2895 switch (ctx) {
2896 case Load: op = LOAD_FAST; break;
2897 case Store: op = STORE_FAST; break;
2898 case Del: op = DELETE_FAST; break;
2899 case AugLoad:
2900 case AugStore:
2901 break;
2902 case Param:
2903 default:
2904 PyErr_SetString(PyExc_SystemError,
2905 "param invalid for local variable");
2906 return 0;
2907 }
2908 ADDOP_O(c, op, mangled, varnames);
2909 Py_DECREF(mangled);
2910 return 1;
2911 case OP_GLOBAL:
2912 switch (ctx) {
2913 case Load: op = LOAD_GLOBAL; break;
2914 case Store: op = STORE_GLOBAL; break;
2915 case Del: op = DELETE_GLOBAL; break;
2916 case AugLoad:
2917 case AugStore:
2918 break;
2919 case Param:
2920 default:
2921 PyErr_SetString(PyExc_SystemError,
2922 "param invalid for global variable");
2923 return 0;
2924 }
2925 break;
2926 case OP_NAME:
2927 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002928 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 case Store: op = STORE_NAME; break;
2930 case Del: op = DELETE_NAME; break;
2931 case AugLoad:
2932 case AugStore:
2933 break;
2934 case Param:
2935 default:
2936 PyErr_SetString(PyExc_SystemError,
2937 "param invalid for name variable");
2938 return 0;
2939 }
2940 break;
2941 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 assert(op);
2944 arg = compiler_add_o(c, dict, mangled);
2945 Py_DECREF(mangled);
2946 if (arg < 0)
2947 return 0;
2948 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949}
2950
2951static int
2952compiler_boolop(struct compiler *c, expr_ty e)
2953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002955 int jumpi;
2956 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 assert(e->kind == BoolOp_kind);
2960 if (e->v.BoolOp.op == And)
2961 jumpi = JUMP_IF_FALSE_OR_POP;
2962 else
2963 jumpi = JUMP_IF_TRUE_OR_POP;
2964 end = compiler_new_block(c);
2965 if (end == NULL)
2966 return 0;
2967 s = e->v.BoolOp.values;
2968 n = asdl_seq_LEN(s) - 1;
2969 assert(n >= 0);
2970 for (i = 0; i < n; ++i) {
2971 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2972 ADDOP_JABS(c, jumpi, end);
2973 }
2974 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2975 compiler_use_next_block(c, end);
2976 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977}
2978
2979static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002980starunpack_helper(struct compiler *c, asdl_seq *elts,
2981 int single_op, int inner_op, int outer_op)
2982{
2983 Py_ssize_t n = asdl_seq_LEN(elts);
2984 Py_ssize_t i, nsubitems = 0, nseen = 0;
2985 for (i = 0; i < n; i++) {
2986 expr_ty elt = asdl_seq_GET(elts, i);
2987 if (elt->kind == Starred_kind) {
2988 if (nseen) {
2989 ADDOP_I(c, inner_op, nseen);
2990 nseen = 0;
2991 nsubitems++;
2992 }
2993 VISIT(c, expr, elt->v.Starred.value);
2994 nsubitems++;
2995 }
2996 else {
2997 VISIT(c, expr, elt);
2998 nseen++;
2999 }
3000 }
3001 if (nsubitems) {
3002 if (nseen) {
3003 ADDOP_I(c, inner_op, nseen);
3004 nsubitems++;
3005 }
3006 ADDOP_I(c, outer_op, nsubitems);
3007 }
3008 else
3009 ADDOP_I(c, single_op, nseen);
3010 return 1;
3011}
3012
3013static int
3014assignment_helper(struct compiler *c, asdl_seq *elts)
3015{
3016 Py_ssize_t n = asdl_seq_LEN(elts);
3017 Py_ssize_t i;
3018 int seen_star = 0;
3019 for (i = 0; i < n; i++) {
3020 expr_ty elt = asdl_seq_GET(elts, i);
3021 if (elt->kind == Starred_kind && !seen_star) {
3022 if ((i >= (1 << 8)) ||
3023 (n-i-1 >= (INT_MAX >> 8)))
3024 return compiler_error(c,
3025 "too many expressions in "
3026 "star-unpacking assignment");
3027 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3028 seen_star = 1;
3029 asdl_seq_SET(elts, i, elt->v.Starred.value);
3030 }
3031 else if (elt->kind == Starred_kind) {
3032 return compiler_error(c,
3033 "two starred expressions in assignment");
3034 }
3035 }
3036 if (!seen_star) {
3037 ADDOP_I(c, UNPACK_SEQUENCE, n);
3038 }
3039 VISIT_SEQ(c, expr, elts);
3040 return 1;
3041}
3042
3043static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044compiler_list(struct compiler *c, expr_ty e)
3045{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003046 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003048 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003050 else if (e->v.List.ctx == Load) {
3051 return starunpack_helper(c, elts,
3052 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003054 else
3055 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057}
3058
3059static int
3060compiler_tuple(struct compiler *c, expr_ty e)
3061{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003062 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003064 return assignment_helper(c, elts);
3065 }
3066 else if (e->v.Tuple.ctx == Load) {
3067 return starunpack_helper(c, elts,
3068 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3069 }
3070 else
3071 VISIT_SEQ(c, expr, elts);
3072 return 1;
3073}
3074
3075static int
3076compiler_set(struct compiler *c, expr_ty e)
3077{
3078 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3079 BUILD_SET, BUILD_SET_UNPACK);
3080}
3081
3082static int
3083compiler_dict(struct compiler *c, expr_ty e)
3084{
3085 Py_ssize_t i, n, containers, elements;
3086 int is_unpacking = 0;
3087 n = asdl_seq_LEN(e->v.Dict.values);
3088 containers = 0;
3089 elements = 0;
3090 for (i = 0; i < n; i++) {
3091 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3092 if (elements == 0xFFFF || (elements && is_unpacking)) {
3093 ADDOP_I(c, BUILD_MAP, elements);
3094 containers++;
3095 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003097 if (is_unpacking) {
3098 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3099 containers++;
3100 }
3101 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003102 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003103 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003104 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 }
3106 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003107 if (elements || containers == 0) {
3108 ADDOP_I(c, BUILD_MAP, elements);
3109 containers++;
3110 }
3111 /* If there is more than one dict, they need to be merged into a new
3112 * dict. If there is one dict and it's an unpacking, then it needs
3113 * to be copied into a new dict." */
3114 while (containers > 1 || is_unpacking) {
3115 int oparg = containers < 255 ? containers : 255;
3116 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3117 containers -= (oparg - 1);
3118 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
3120 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121}
3122
3123static int
3124compiler_compare(struct compiler *c, expr_ty e)
3125{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003126 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3130 VISIT(c, expr, e->v.Compare.left);
3131 n = asdl_seq_LEN(e->v.Compare.ops);
3132 assert(n > 0);
3133 if (n > 1) {
3134 cleanup = compiler_new_block(c);
3135 if (cleanup == NULL)
3136 return 0;
3137 VISIT(c, expr,
3138 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3139 }
3140 for (i = 1; i < n; i++) {
3141 ADDOP(c, DUP_TOP);
3142 ADDOP(c, ROT_THREE);
3143 ADDOP_I(c, COMPARE_OP,
3144 cmpop((cmpop_ty)(asdl_seq_GET(
3145 e->v.Compare.ops, i - 1))));
3146 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3147 NEXT_BLOCK(c);
3148 if (i < (n - 1))
3149 VISIT(c, expr,
3150 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3151 }
3152 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3153 ADDOP_I(c, COMPARE_OP,
3154 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3155 if (n > 1) {
3156 basicblock *end = compiler_new_block(c);
3157 if (end == NULL)
3158 return 0;
3159 ADDOP_JREL(c, JUMP_FORWARD, end);
3160 compiler_use_next_block(c, cleanup);
3161 ADDOP(c, ROT_TWO);
3162 ADDOP(c, POP_TOP);
3163 compiler_use_next_block(c, end);
3164 }
3165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166}
3167
3168static int
3169compiler_call(struct compiler *c, expr_ty e)
3170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 VISIT(c, expr, e->v.Call.func);
3172 return compiler_call_helper(c, 0,
3173 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003174 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003175}
3176
Eric V. Smith235a6f02015-09-19 14:51:32 -04003177static int
3178compiler_joined_str(struct compiler *c, expr_ty e)
3179{
3180 /* Concatenate parts of a string using ''.join(parts). There are
3181 probably better ways of doing this.
3182
3183 This is used for constructs like "'x=' f'{42}'", which have to
3184 be evaluated at compile time. */
3185
3186 static PyObject *empty_string;
3187 static PyObject *join_string;
3188
3189 if (!empty_string) {
3190 empty_string = PyUnicode_FromString("");
3191 if (!empty_string)
3192 return 0;
3193 }
3194 if (!join_string) {
3195 join_string = PyUnicode_FromString("join");
3196 if (!join_string)
3197 return 0;
3198 }
3199
3200 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3201 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3202 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3203 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3204 ADDOP_I(c, CALL_FUNCTION, 1);
3205 return 1;
3206}
3207
Eric V. Smitha78c7952015-11-03 12:45:05 -05003208/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003209static int
3210compiler_formatted_value(struct compiler *c, expr_ty e)
3211{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003212 /* Our oparg encodes 2 pieces of information: the conversion
3213 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003214
Eric V. Smitha78c7952015-11-03 12:45:05 -05003215 Convert the conversion char to 2 bits:
3216 None: 000 0x0 FVC_NONE
3217 !s : 001 0x1 FVC_STR
3218 !r : 010 0x2 FVC_REPR
3219 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003220
Eric V. Smitha78c7952015-11-03 12:45:05 -05003221 next bit is whether or not we have a format spec:
3222 yes : 100 0x4
3223 no : 000 0x0
3224 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003225
Eric V. Smitha78c7952015-11-03 12:45:05 -05003226 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003227
Eric V. Smitha78c7952015-11-03 12:45:05 -05003228 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003229 VISIT(c, expr, e->v.FormattedValue.value);
3230
Eric V. Smitha78c7952015-11-03 12:45:05 -05003231 switch (e->v.FormattedValue.conversion) {
3232 case 's': oparg = FVC_STR; break;
3233 case 'r': oparg = FVC_REPR; break;
3234 case 'a': oparg = FVC_ASCII; break;
3235 case -1: oparg = FVC_NONE; break;
3236 default:
3237 PyErr_SetString(PyExc_SystemError,
3238 "Unrecognized conversion character");
3239 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003240 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003241 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003242 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003243 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003244 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003245 }
3246
Eric V. Smitha78c7952015-11-03 12:45:05 -05003247 /* And push our opcode and oparg */
3248 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003249 return 1;
3250}
3251
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003252/* shared code between compiler_call and compiler_class */
3253static int
3254compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003255 Py_ssize_t n, /* Args already pushed */
3256 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003257 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003260 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003261
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003262 /* the number of tuples and dictionaries on the stack */
3263 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3264
3265 nkw = 0;
3266 nseen = 0; /* the number of positional arguments on the stack */
3267 nelts = asdl_seq_LEN(args);
3268 for (i = 0; i < nelts; i++) {
3269 expr_ty elt = asdl_seq_GET(args, i);
3270 if (elt->kind == Starred_kind) {
3271 /* A star-arg. If we've seen positional arguments,
3272 pack the positional arguments into a
3273 tuple. */
3274 if (nseen) {
3275 ADDOP_I(c, BUILD_TUPLE, nseen);
3276 nseen = 0;
3277 nsubargs++;
3278 }
3279 VISIT(c, expr, elt->v.Starred.value);
3280 nsubargs++;
3281 }
3282 else if (nsubargs) {
3283 /* We've seen star-args already, so we
3284 count towards items-to-pack-into-tuple. */
3285 VISIT(c, expr, elt);
3286 nseen++;
3287 }
3288 else {
3289 /* Positional arguments before star-arguments
3290 are left on the stack. */
3291 VISIT(c, expr, elt);
3292 n++;
3293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003295 if (nseen) {
3296 /* Pack up any trailing positional arguments. */
3297 ADDOP_I(c, BUILD_TUPLE, nseen);
3298 nsubargs++;
3299 }
3300 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003302 if (nsubargs > 1) {
3303 /* If we ended up with more than one stararg, we need
3304 to concatenate them into a single sequence. */
3305 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003308
3309 /* Same dance again for keyword arguments */
3310 nseen = 0; /* the number of keyword arguments on the stack following */
3311 nelts = asdl_seq_LEN(keywords);
3312 for (i = 0; i < nelts; i++) {
3313 keyword_ty kw = asdl_seq_GET(keywords, i);
3314 if (kw->arg == NULL) {
3315 /* A keyword argument unpacking. */
3316 if (nseen) {
3317 ADDOP_I(c, BUILD_MAP, nseen);
3318 nseen = 0;
3319 nsubkwargs++;
3320 }
3321 VISIT(c, expr, kw->value);
3322 nsubkwargs++;
3323 }
3324 else if (nsubkwargs) {
3325 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003326 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003327 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003328 nseen++;
3329 }
3330 else {
3331 /* keyword argument */
3332 VISIT(c, keyword, kw)
3333 nkw++;
3334 }
3335 }
3336 if (nseen) {
3337 /* Pack up any trailing keyword arguments. */
3338 ADDOP_I(c, BUILD_MAP, nseen);
3339 nsubkwargs++;
3340 }
3341 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003343 if (nsubkwargs > 1) {
3344 /* Pack it all up */
3345 int function_pos = n + (code & 1) + nkw + 1;
3346 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003349 assert(n < 1<<8);
3350 assert(nkw < 1<<24);
3351 n |= nkw << 8;
3352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 switch (code) {
3354 case 0:
3355 ADDOP_I(c, CALL_FUNCTION, n);
3356 break;
3357 case 1:
3358 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3359 break;
3360 case 2:
3361 ADDOP_I(c, CALL_FUNCTION_KW, n);
3362 break;
3363 case 3:
3364 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3365 break;
3366 }
3367 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368}
3369
Nick Coghlan650f0d02007-04-15 12:05:43 +00003370
3371/* List and set comprehensions and generator expressions work by creating a
3372 nested function to perform the actual iteration. This means that the
3373 iteration variables don't leak into the current scope.
3374 The defined function is called immediately following its definition, with the
3375 result of that call being the result of the expression.
3376 The LC/SC version returns the populated container, while the GE version is
3377 flagged in symtable.c as a generator, so it returns the generator object
3378 when the function is called.
3379 This code *knows* that the loop cannot contain break, continue, or return,
3380 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3381
3382 Possible cleanups:
3383 - iterate over the generator sequence instead of using recursion
3384*/
3385
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387compiler_comprehension_generator(struct compiler *c,
3388 asdl_seq *generators, int gen_index,
3389 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 /* generate code for the iterator, then each of the ifs,
3392 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 comprehension_ty gen;
3395 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003396 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 start = compiler_new_block(c);
3399 skip = compiler_new_block(c);
3400 if_cleanup = compiler_new_block(c);
3401 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3404 anchor == NULL)
3405 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 if (gen_index == 0) {
3410 /* Receive outermost iter as an implicit argument */
3411 c->u->u_argcount = 1;
3412 ADDOP_I(c, LOAD_FAST, 0);
3413 }
3414 else {
3415 /* Sub-iter - calculate on the fly */
3416 VISIT(c, expr, gen->iter);
3417 ADDOP(c, GET_ITER);
3418 }
3419 compiler_use_next_block(c, start);
3420 ADDOP_JREL(c, FOR_ITER, anchor);
3421 NEXT_BLOCK(c);
3422 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 /* XXX this needs to be cleaned up...a lot! */
3425 n = asdl_seq_LEN(gen->ifs);
3426 for (i = 0; i < n; i++) {
3427 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3428 VISIT(c, expr, e);
3429 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3430 NEXT_BLOCK(c);
3431 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 if (++gen_index < asdl_seq_LEN(generators))
3434 if (!compiler_comprehension_generator(c,
3435 generators, gen_index,
3436 elt, val, type))
3437 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 /* only append after the last for generator */
3440 if (gen_index >= asdl_seq_LEN(generators)) {
3441 /* comprehension specific code */
3442 switch (type) {
3443 case COMP_GENEXP:
3444 VISIT(c, expr, elt);
3445 ADDOP(c, YIELD_VALUE);
3446 ADDOP(c, POP_TOP);
3447 break;
3448 case COMP_LISTCOMP:
3449 VISIT(c, expr, elt);
3450 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3451 break;
3452 case COMP_SETCOMP:
3453 VISIT(c, expr, elt);
3454 ADDOP_I(c, SET_ADD, gen_index + 1);
3455 break;
3456 case COMP_DICTCOMP:
3457 /* With 'd[k] = v', v is evaluated before k, so we do
3458 the same. */
3459 VISIT(c, expr, val);
3460 VISIT(c, expr, elt);
3461 ADDOP_I(c, MAP_ADD, gen_index + 1);
3462 break;
3463 default:
3464 return 0;
3465 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 compiler_use_next_block(c, skip);
3468 }
3469 compiler_use_next_block(c, if_cleanup);
3470 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3471 compiler_use_next_block(c, anchor);
3472
3473 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474}
3475
3476static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003477compiler_comprehension(struct compiler *c, expr_ty e, int type,
3478 identifier name, asdl_seq *generators, expr_ty elt,
3479 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 PyCodeObject *co = NULL;
3482 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003483 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 outermost_iter = ((comprehension_ty)
3486 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003487
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003488 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3489 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 if (type != COMP_GENEXP) {
3493 int op;
3494 switch (type) {
3495 case COMP_LISTCOMP:
3496 op = BUILD_LIST;
3497 break;
3498 case COMP_SETCOMP:
3499 op = BUILD_SET;
3500 break;
3501 case COMP_DICTCOMP:
3502 op = BUILD_MAP;
3503 break;
3504 default:
3505 PyErr_Format(PyExc_SystemError,
3506 "unknown comprehension type %d", type);
3507 goto error_in_scope;
3508 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 ADDOP_I(c, op, 0);
3511 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 if (!compiler_comprehension_generator(c, generators, 0, elt,
3514 val, type))
3515 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 if (type != COMP_GENEXP) {
3518 ADDOP(c, RETURN_VALUE);
3519 }
3520
3521 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003522 qualname = c->u->u_qualname;
3523 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003525 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 goto error;
3527
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003528 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003530 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 Py_DECREF(co);
3532
3533 VISIT(c, expr, outermost_iter);
3534 ADDOP(c, GET_ITER);
3535 ADDOP_I(c, CALL_FUNCTION, 1);
3536 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003537error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003539error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003540 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 Py_XDECREF(co);
3542 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003543}
3544
3545static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546compiler_genexp(struct compiler *c, expr_ty e)
3547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 static identifier name;
3549 if (!name) {
3550 name = PyUnicode_FromString("<genexpr>");
3551 if (!name)
3552 return 0;
3553 }
3554 assert(e->kind == GeneratorExp_kind);
3555 return compiler_comprehension(c, e, COMP_GENEXP, name,
3556 e->v.GeneratorExp.generators,
3557 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558}
3559
3560static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003561compiler_listcomp(struct compiler *c, expr_ty e)
3562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 static identifier name;
3564 if (!name) {
3565 name = PyUnicode_FromString("<listcomp>");
3566 if (!name)
3567 return 0;
3568 }
3569 assert(e->kind == ListComp_kind);
3570 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3571 e->v.ListComp.generators,
3572 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003573}
3574
3575static int
3576compiler_setcomp(struct compiler *c, expr_ty e)
3577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 static identifier name;
3579 if (!name) {
3580 name = PyUnicode_FromString("<setcomp>");
3581 if (!name)
3582 return 0;
3583 }
3584 assert(e->kind == SetComp_kind);
3585 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3586 e->v.SetComp.generators,
3587 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003588}
3589
3590
3591static int
3592compiler_dictcomp(struct compiler *c, expr_ty e)
3593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 static identifier name;
3595 if (!name) {
3596 name = PyUnicode_FromString("<dictcomp>");
3597 if (!name)
3598 return 0;
3599 }
3600 assert(e->kind == DictComp_kind);
3601 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3602 e->v.DictComp.generators,
3603 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003604}
3605
3606
3607static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608compiler_visit_keyword(struct compiler *c, keyword_ty k)
3609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3611 VISIT(c, expr, k->value);
3612 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613}
3614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 whether they are true or false.
3617
3618 Return values: 1 for true, 0 for false, -1 for non-constant.
3619 */
3620
3621static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003622expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 char *id;
3625 switch (e->kind) {
3626 case Ellipsis_kind:
3627 return 1;
3628 case Num_kind:
3629 return PyObject_IsTrue(e->v.Num.n);
3630 case Str_kind:
3631 return PyObject_IsTrue(e->v.Str.s);
3632 case Name_kind:
3633 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003634 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003635 if (id && strcmp(id, "__debug__") == 0)
3636 return !c->c_optimize;
3637 return -1;
3638 case NameConstant_kind: {
3639 PyObject *o = e->v.NameConstant.value;
3640 if (o == Py_None)
3641 return 0;
3642 else if (o == Py_True)
3643 return 1;
3644 else if (o == Py_False)
3645 return 0;
3646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 default:
3648 return -1;
3649 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650}
3651
Yury Selivanov75445082015-05-11 22:57:16 -04003652
3653/*
3654 Implements the async with statement.
3655
3656 The semantics outlined in that PEP are as follows:
3657
3658 async with EXPR as VAR:
3659 BLOCK
3660
3661 It is implemented roughly as:
3662
3663 context = EXPR
3664 exit = context.__aexit__ # not calling it
3665 value = await context.__aenter__()
3666 try:
3667 VAR = value # if VAR present in the syntax
3668 BLOCK
3669 finally:
3670 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003671 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003672 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003673 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003674 if not (await exit(*exc)):
3675 raise
3676 */
3677static int
3678compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3679{
3680 basicblock *block, *finally;
3681 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3682
3683 assert(s->kind == AsyncWith_kind);
3684
3685 block = compiler_new_block(c);
3686 finally = compiler_new_block(c);
3687 if (!block || !finally)
3688 return 0;
3689
3690 /* Evaluate EXPR */
3691 VISIT(c, expr, item->context_expr);
3692
3693 ADDOP(c, BEFORE_ASYNC_WITH);
3694 ADDOP(c, GET_AWAITABLE);
3695 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3696 ADDOP(c, YIELD_FROM);
3697
3698 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3699
3700 /* SETUP_ASYNC_WITH pushes a finally block. */
3701 compiler_use_next_block(c, block);
3702 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3703 return 0;
3704 }
3705
3706 if (item->optional_vars) {
3707 VISIT(c, expr, item->optional_vars);
3708 }
3709 else {
3710 /* Discard result from context.__aenter__() */
3711 ADDOP(c, POP_TOP);
3712 }
3713
3714 pos++;
3715 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3716 /* BLOCK code */
3717 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3718 else if (!compiler_async_with(c, s, pos))
3719 return 0;
3720
3721 /* End of try block; start the finally block */
3722 ADDOP(c, POP_BLOCK);
3723 compiler_pop_fblock(c, FINALLY_TRY, block);
3724
3725 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3726 compiler_use_next_block(c, finally);
3727 if (!compiler_push_fblock(c, FINALLY_END, finally))
3728 return 0;
3729
3730 /* Finally block starts; context.__exit__ is on the stack under
3731 the exception or return information. Just issue our magic
3732 opcode. */
3733 ADDOP(c, WITH_CLEANUP_START);
3734
3735 ADDOP(c, GET_AWAITABLE);
3736 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3737 ADDOP(c, YIELD_FROM);
3738
3739 ADDOP(c, WITH_CLEANUP_FINISH);
3740
3741 /* Finally block ends. */
3742 ADDOP(c, END_FINALLY);
3743 compiler_pop_fblock(c, FINALLY_END, finally);
3744 return 1;
3745}
3746
3747
Guido van Rossumc2e20742006-02-27 22:32:47 +00003748/*
3749 Implements the with statement from PEP 343.
3750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003752
3753 with EXPR as VAR:
3754 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755
Guido van Rossumc2e20742006-02-27 22:32:47 +00003756 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757
Thomas Wouters477c8d52006-05-27 19:21:47 +00003758 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003759 exit = context.__exit__ # not calling it
3760 value = context.__enter__()
3761 try:
3762 VAR = value # if VAR present in the syntax
3763 BLOCK
3764 finally:
3765 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003766 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003767 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003768 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003769 exit(*exc)
3770 */
3771static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003772compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003773{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003774 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003775 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003776
3777 assert(s->kind == With_kind);
3778
Guido van Rossumc2e20742006-02-27 22:32:47 +00003779 block = compiler_new_block(c);
3780 finally = compiler_new_block(c);
3781 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003782 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003783
Thomas Wouters477c8d52006-05-27 19:21:47 +00003784 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003785 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003786 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003787
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003788 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003789 compiler_use_next_block(c, block);
3790 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003791 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003792 }
3793
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003794 if (item->optional_vars) {
3795 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003796 }
3797 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003799 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003800 }
3801
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003802 pos++;
3803 if (pos == asdl_seq_LEN(s->v.With.items))
3804 /* BLOCK code */
3805 VISIT_SEQ(c, stmt, s->v.With.body)
3806 else if (!compiler_with(c, s, pos))
3807 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003808
3809 /* End of try block; start the finally block */
3810 ADDOP(c, POP_BLOCK);
3811 compiler_pop_fblock(c, FINALLY_TRY, block);
3812
3813 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3814 compiler_use_next_block(c, finally);
3815 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003816 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003817
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003818 /* Finally block starts; context.__exit__ is on the stack under
3819 the exception or return information. Just issue our magic
3820 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003821 ADDOP(c, WITH_CLEANUP_START);
3822 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003823
3824 /* Finally block ends. */
3825 ADDOP(c, END_FINALLY);
3826 compiler_pop_fblock(c, FINALLY_END, finally);
3827 return 1;
3828}
3829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830static int
3831compiler_visit_expr(struct compiler *c, expr_ty e)
3832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 /* If expr e has a different line number than the last expr/stmt,
3834 set a new line number for the next instruction.
3835 */
3836 if (e->lineno > c->u->u_lineno) {
3837 c->u->u_lineno = e->lineno;
3838 c->u->u_lineno_set = 0;
3839 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003840 /* Updating the column offset is always harmless. */
3841 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 switch (e->kind) {
3843 case BoolOp_kind:
3844 return compiler_boolop(c, e);
3845 case BinOp_kind:
3846 VISIT(c, expr, e->v.BinOp.left);
3847 VISIT(c, expr, e->v.BinOp.right);
3848 ADDOP(c, binop(c, e->v.BinOp.op));
3849 break;
3850 case UnaryOp_kind:
3851 VISIT(c, expr, e->v.UnaryOp.operand);
3852 ADDOP(c, unaryop(e->v.UnaryOp.op));
3853 break;
3854 case Lambda_kind:
3855 return compiler_lambda(c, e);
3856 case IfExp_kind:
3857 return compiler_ifexp(c, e);
3858 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003859 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003861 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 case GeneratorExp_kind:
3863 return compiler_genexp(c, e);
3864 case ListComp_kind:
3865 return compiler_listcomp(c, e);
3866 case SetComp_kind:
3867 return compiler_setcomp(c, e);
3868 case DictComp_kind:
3869 return compiler_dictcomp(c, e);
3870 case Yield_kind:
3871 if (c->u->u_ste->ste_type != FunctionBlock)
3872 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003873 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3874 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003875 if (e->v.Yield.value) {
3876 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 }
3878 else {
3879 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3880 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003881 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003883 case YieldFrom_kind:
3884 if (c->u->u_ste->ste_type != FunctionBlock)
3885 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003886
3887 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3888 return compiler_error(c, "'yield from' inside async function");
3889
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003890 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003891 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003892 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3893 ADDOP(c, YIELD_FROM);
3894 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003895 case Await_kind:
3896 if (c->u->u_ste->ste_type != FunctionBlock)
3897 return compiler_error(c, "'await' outside function");
3898
Yury Selivanov9dec0352015-06-30 12:49:04 -04003899 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3900 return compiler_error(
3901 c, "'await' expressions in comprehensions are not supported");
3902
Yury Selivanov75445082015-05-11 22:57:16 -04003903 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3904 return compiler_error(c, "'await' outside async function");
3905
3906 VISIT(c, expr, e->v.Await.value);
3907 ADDOP(c, GET_AWAITABLE);
3908 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3909 ADDOP(c, YIELD_FROM);
3910 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 case Compare_kind:
3912 return compiler_compare(c, e);
3913 case Call_kind:
3914 return compiler_call(c, e);
3915 case Num_kind:
3916 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3917 break;
3918 case Str_kind:
3919 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3920 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003921 case JoinedStr_kind:
3922 return compiler_joined_str(c, e);
3923 case FormattedValue_kind:
3924 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 case Bytes_kind:
3926 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3927 break;
3928 case Ellipsis_kind:
3929 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3930 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003931 case NameConstant_kind:
3932 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3933 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 /* The following exprs can be assignment targets. */
3935 case Attribute_kind:
3936 if (e->v.Attribute.ctx != AugStore)
3937 VISIT(c, expr, e->v.Attribute.value);
3938 switch (e->v.Attribute.ctx) {
3939 case AugLoad:
3940 ADDOP(c, DUP_TOP);
3941 /* Fall through to load */
3942 case Load:
3943 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3944 break;
3945 case AugStore:
3946 ADDOP(c, ROT_TWO);
3947 /* Fall through to save */
3948 case Store:
3949 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3950 break;
3951 case Del:
3952 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3953 break;
3954 case Param:
3955 default:
3956 PyErr_SetString(PyExc_SystemError,
3957 "param invalid in attribute expression");
3958 return 0;
3959 }
3960 break;
3961 case Subscript_kind:
3962 switch (e->v.Subscript.ctx) {
3963 case AugLoad:
3964 VISIT(c, expr, e->v.Subscript.value);
3965 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3966 break;
3967 case Load:
3968 VISIT(c, expr, e->v.Subscript.value);
3969 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3970 break;
3971 case AugStore:
3972 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3973 break;
3974 case Store:
3975 VISIT(c, expr, e->v.Subscript.value);
3976 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3977 break;
3978 case Del:
3979 VISIT(c, expr, e->v.Subscript.value);
3980 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3981 break;
3982 case Param:
3983 default:
3984 PyErr_SetString(PyExc_SystemError,
3985 "param invalid in subscript expression");
3986 return 0;
3987 }
3988 break;
3989 case Starred_kind:
3990 switch (e->v.Starred.ctx) {
3991 case Store:
3992 /* In all legitimate cases, the Starred node was already replaced
3993 * by compiler_list/compiler_tuple. XXX: is that okay? */
3994 return compiler_error(c,
3995 "starred assignment target must be in a list or tuple");
3996 default:
3997 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003998 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 }
4000 break;
4001 case Name_kind:
4002 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4003 /* child nodes of List and Tuple will have expr_context set */
4004 case List_kind:
4005 return compiler_list(c, e);
4006 case Tuple_kind:
4007 return compiler_tuple(c, e);
4008 }
4009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010}
4011
4012static int
4013compiler_augassign(struct compiler *c, stmt_ty s)
4014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 expr_ty e = s->v.AugAssign.target;
4016 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 switch (e->kind) {
4021 case Attribute_kind:
4022 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4023 AugLoad, e->lineno, e->col_offset, c->c_arena);
4024 if (auge == NULL)
4025 return 0;
4026 VISIT(c, expr, auge);
4027 VISIT(c, expr, s->v.AugAssign.value);
4028 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4029 auge->v.Attribute.ctx = AugStore;
4030 VISIT(c, expr, auge);
4031 break;
4032 case Subscript_kind:
4033 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4034 AugLoad, e->lineno, e->col_offset, c->c_arena);
4035 if (auge == NULL)
4036 return 0;
4037 VISIT(c, expr, auge);
4038 VISIT(c, expr, s->v.AugAssign.value);
4039 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4040 auge->v.Subscript.ctx = AugStore;
4041 VISIT(c, expr, auge);
4042 break;
4043 case Name_kind:
4044 if (!compiler_nameop(c, e->v.Name.id, Load))
4045 return 0;
4046 VISIT(c, expr, s->v.AugAssign.value);
4047 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4048 return compiler_nameop(c, e->v.Name.id, Store);
4049 default:
4050 PyErr_Format(PyExc_SystemError,
4051 "invalid node type (%d) for augmented assignment",
4052 e->kind);
4053 return 0;
4054 }
4055 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004056}
4057
4058static int
4059compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 struct fblockinfo *f;
4062 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4063 PyErr_SetString(PyExc_SystemError,
4064 "too many statically nested blocks");
4065 return 0;
4066 }
4067 f = &c->u->u_fblock[c->u->u_nfblocks++];
4068 f->fb_type = t;
4069 f->fb_block = b;
4070 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004071}
4072
4073static void
4074compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 struct compiler_unit *u = c->u;
4077 assert(u->u_nfblocks > 0);
4078 u->u_nfblocks--;
4079 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4080 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081}
4082
Thomas Wouters89f507f2006-12-13 04:49:30 +00004083static int
4084compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 int i;
4086 struct compiler_unit *u = c->u;
4087 for (i = 0; i < u->u_nfblocks; ++i) {
4088 if (u->u_fblock[i].fb_type == LOOP)
4089 return 1;
4090 }
4091 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004092}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093/* Raises a SyntaxError and returns 0.
4094 If something goes wrong, a different exception may be raised.
4095*/
4096
4097static int
4098compiler_error(struct compiler *c, const char *errstr)
4099{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004100 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004102
Victor Stinner14e461d2013-08-26 22:28:21 +02004103 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 if (!loc) {
4105 Py_INCREF(Py_None);
4106 loc = Py_None;
4107 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004108 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004109 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 if (!u)
4111 goto exit;
4112 v = Py_BuildValue("(zO)", errstr, u);
4113 if (!v)
4114 goto exit;
4115 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 Py_DECREF(loc);
4118 Py_XDECREF(u);
4119 Py_XDECREF(v);
4120 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121}
4122
4123static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124compiler_handle_subscr(struct compiler *c, const char *kind,
4125 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 /* XXX this code is duplicated */
4130 switch (ctx) {
4131 case AugLoad: /* fall through to Load */
4132 case Load: op = BINARY_SUBSCR; break;
4133 case AugStore:/* fall through to Store */
4134 case Store: op = STORE_SUBSCR; break;
4135 case Del: op = DELETE_SUBSCR; break;
4136 case Param:
4137 PyErr_Format(PyExc_SystemError,
4138 "invalid %s kind %d in subscript\n",
4139 kind, ctx);
4140 return 0;
4141 }
4142 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004143 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 }
4145 else if (ctx == AugStore) {
4146 ADDOP(c, ROT_THREE);
4147 }
4148 ADDOP(c, op);
4149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150}
4151
4152static int
4153compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 int n = 2;
4156 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 /* only handles the cases where BUILD_SLICE is emitted */
4159 if (s->v.Slice.lower) {
4160 VISIT(c, expr, s->v.Slice.lower);
4161 }
4162 else {
4163 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4164 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 if (s->v.Slice.upper) {
4167 VISIT(c, expr, s->v.Slice.upper);
4168 }
4169 else {
4170 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4171 }
4172
4173 if (s->v.Slice.step) {
4174 n++;
4175 VISIT(c, expr, s->v.Slice.step);
4176 }
4177 ADDOP_I(c, BUILD_SLICE, n);
4178 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179}
4180
4181static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4183 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 switch (s->kind) {
4186 case Slice_kind:
4187 return compiler_slice(c, s, ctx);
4188 case Index_kind:
4189 VISIT(c, expr, s->v.Index.value);
4190 break;
4191 case ExtSlice_kind:
4192 default:
4193 PyErr_SetString(PyExc_SystemError,
4194 "extended slice invalid in nested slice");
4195 return 0;
4196 }
4197 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198}
4199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200static int
4201compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 char * kindname = NULL;
4204 switch (s->kind) {
4205 case Index_kind:
4206 kindname = "index";
4207 if (ctx != AugStore) {
4208 VISIT(c, expr, s->v.Index.value);
4209 }
4210 break;
4211 case Slice_kind:
4212 kindname = "slice";
4213 if (ctx != AugStore) {
4214 if (!compiler_slice(c, s, ctx))
4215 return 0;
4216 }
4217 break;
4218 case ExtSlice_kind:
4219 kindname = "extended slice";
4220 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004221 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 for (i = 0; i < n; i++) {
4223 slice_ty sub = (slice_ty)asdl_seq_GET(
4224 s->v.ExtSlice.dims, i);
4225 if (!compiler_visit_nested_slice(c, sub, ctx))
4226 return 0;
4227 }
4228 ADDOP_I(c, BUILD_TUPLE, n);
4229 }
4230 break;
4231 default:
4232 PyErr_Format(PyExc_SystemError,
4233 "invalid subscript kind %d", s->kind);
4234 return 0;
4235 }
4236 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004237}
4238
Thomas Wouters89f507f2006-12-13 04:49:30 +00004239/* End of the compiler section, beginning of the assembler section */
4240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004241/* do depth-first search of basic block graph, starting with block.
4242 post records the block indices in post-order.
4243
4244 XXX must handle implicit jumps from one block to next
4245*/
4246
Thomas Wouters89f507f2006-12-13 04:49:30 +00004247struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 PyObject *a_bytecode; /* string containing bytecode */
4249 int a_offset; /* offset into bytecode */
4250 int a_nblocks; /* number of reachable blocks */
4251 basicblock **a_postorder; /* list of blocks in dfs postorder */
4252 PyObject *a_lnotab; /* string containing lnotab */
4253 int a_lnotab_off; /* offset into lnotab */
4254 int a_lineno; /* last lineno of emitted instruction */
4255 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004256};
4257
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004258static void
4259dfs(struct compiler *c, basicblock *b, struct assembler *a)
4260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 int i;
4262 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 if (b->b_seen)
4265 return;
4266 b->b_seen = 1;
4267 if (b->b_next != NULL)
4268 dfs(c, b->b_next, a);
4269 for (i = 0; i < b->b_iused; i++) {
4270 instr = &b->b_instr[i];
4271 if (instr->i_jrel || instr->i_jabs)
4272 dfs(c, instr->i_target, a);
4273 }
4274 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004275}
4276
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004277static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004278stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4279{
Larry Hastings3a907972013-11-23 14:49:22 -08004280 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 struct instr *instr;
4282 if (b->b_seen || b->b_startdepth >= depth)
4283 return maxdepth;
4284 b->b_seen = 1;
4285 b->b_startdepth = depth;
4286 for (i = 0; i < b->b_iused; i++) {
4287 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004288 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4289 if (effect == PY_INVALID_STACK_EFFECT) {
4290 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4291 Py_FatalError("PyCompile_OpcodeStackEffect()");
4292 }
4293 depth += effect;
4294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 if (depth > maxdepth)
4296 maxdepth = depth;
4297 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4298 if (instr->i_jrel || instr->i_jabs) {
4299 target_depth = depth;
4300 if (instr->i_opcode == FOR_ITER) {
4301 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004302 }
4303 else if (instr->i_opcode == SETUP_FINALLY ||
4304 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 target_depth = depth+3;
4306 if (target_depth > maxdepth)
4307 maxdepth = target_depth;
4308 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004309 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4310 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4311 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 maxdepth = stackdepth_walk(c, instr->i_target,
4313 target_depth, maxdepth);
4314 if (instr->i_opcode == JUMP_ABSOLUTE ||
4315 instr->i_opcode == JUMP_FORWARD) {
4316 goto out; /* remaining code is dead */
4317 }
4318 }
4319 }
4320 if (b->b_next)
4321 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004322out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 b->b_seen = 0;
4324 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325}
4326
4327/* Find the flow path that needs the largest stack. We assume that
4328 * cycles in the flow graph have no net effect on the stack depth.
4329 */
4330static int
4331stackdepth(struct compiler *c)
4332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 basicblock *b, *entryblock;
4334 entryblock = NULL;
4335 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4336 b->b_seen = 0;
4337 b->b_startdepth = INT_MIN;
4338 entryblock = b;
4339 }
4340 if (!entryblock)
4341 return 0;
4342 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004343}
4344
4345static int
4346assemble_init(struct assembler *a, int nblocks, int firstlineno)
4347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 memset(a, 0, sizeof(struct assembler));
4349 a->a_lineno = firstlineno;
4350 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4351 if (!a->a_bytecode)
4352 return 0;
4353 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4354 if (!a->a_lnotab)
4355 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004356 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 PyErr_NoMemory();
4358 return 0;
4359 }
4360 a->a_postorder = (basicblock **)PyObject_Malloc(
4361 sizeof(basicblock *) * nblocks);
4362 if (!a->a_postorder) {
4363 PyErr_NoMemory();
4364 return 0;
4365 }
4366 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004367}
4368
4369static void
4370assemble_free(struct assembler *a)
4371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 Py_XDECREF(a->a_bytecode);
4373 Py_XDECREF(a->a_lnotab);
4374 if (a->a_postorder)
4375 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004376}
4377
4378/* Return the size of a basic block in bytes. */
4379
4380static int
4381instrsize(struct instr *instr)
4382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 if (!instr->i_hasarg)
4384 return 1; /* 1 byte for the opcode*/
4385 if (instr->i_oparg > 0xffff)
4386 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4387 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004388}
4389
4390static int
4391blocksize(basicblock *b)
4392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 int i;
4394 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 for (i = 0; i < b->b_iused; i++)
4397 size += instrsize(&b->b_instr[i]);
4398 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004399}
4400
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004401/* Appends a pair to the end of the line number table, a_lnotab, representing
4402 the instruction's bytecode offset and line number. See
4403 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004404
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004405static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004406assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004409 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 d_bytecode = a->a_offset - a->a_lineno_off;
4413 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 if(d_bytecode == 0 && d_lineno == 0)
4418 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 if (d_bytecode > 255) {
4421 int j, nbytes, ncodes = d_bytecode / 255;
4422 nbytes = a->a_lnotab_off + 2 * ncodes;
4423 len = PyBytes_GET_SIZE(a->a_lnotab);
4424 if (nbytes >= len) {
4425 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4426 len = nbytes;
4427 else if (len <= INT_MAX / 2)
4428 len *= 2;
4429 else {
4430 PyErr_NoMemory();
4431 return 0;
4432 }
4433 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4434 return 0;
4435 }
4436 lnotab = (unsigned char *)
4437 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4438 for (j = 0; j < ncodes; j++) {
4439 *lnotab++ = 255;
4440 *lnotab++ = 0;
4441 }
4442 d_bytecode -= ncodes * 255;
4443 a->a_lnotab_off += ncodes * 2;
4444 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004445 assert(0 <= d_bytecode && d_bytecode <= 255);
4446
4447 if (d_lineno < -128 || 127 < d_lineno) {
4448 int j, nbytes, ncodes, k;
4449 if (d_lineno < 0) {
4450 k = -128;
4451 /* use division on positive numbers */
4452 ncodes = (-d_lineno) / 128;
4453 }
4454 else {
4455 k = 127;
4456 ncodes = d_lineno / 127;
4457 }
4458 d_lineno -= ncodes * k;
4459 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 nbytes = a->a_lnotab_off + 2 * ncodes;
4461 len = PyBytes_GET_SIZE(a->a_lnotab);
4462 if (nbytes >= len) {
4463 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4464 len = nbytes;
4465 else if (len <= INT_MAX / 2)
4466 len *= 2;
4467 else {
4468 PyErr_NoMemory();
4469 return 0;
4470 }
4471 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4472 return 0;
4473 }
4474 lnotab = (unsigned char *)
4475 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4476 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004477 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 d_bytecode = 0;
4479 for (j = 1; j < ncodes; j++) {
4480 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004481 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 a->a_lnotab_off += ncodes * 2;
4484 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004485 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 len = PyBytes_GET_SIZE(a->a_lnotab);
4488 if (a->a_lnotab_off + 2 >= len) {
4489 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4490 return 0;
4491 }
4492 lnotab = (unsigned char *)
4493 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 a->a_lnotab_off += 2;
4496 if (d_bytecode) {
4497 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004498 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 }
4500 else { /* First line of a block; def stmt, etc. */
4501 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004502 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 }
4504 a->a_lineno = i->i_lineno;
4505 a->a_lineno_off = a->a_offset;
4506 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004507}
4508
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004509/* assemble_emit()
4510 Extend the bytecode with a new instruction.
4511 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004512*/
4513
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004514static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004515assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 int size, arg = 0, ext = 0;
4518 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4519 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 size = instrsize(i);
4522 if (i->i_hasarg) {
4523 arg = i->i_oparg;
4524 ext = arg >> 16;
4525 }
4526 if (i->i_lineno && !assemble_lnotab(a, i))
4527 return 0;
4528 if (a->a_offset + size >= len) {
4529 if (len > PY_SSIZE_T_MAX / 2)
4530 return 0;
4531 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4532 return 0;
4533 }
4534 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4535 a->a_offset += size;
4536 if (size == 6) {
4537 assert(i->i_hasarg);
4538 *code++ = (char)EXTENDED_ARG;
4539 *code++ = ext & 0xff;
4540 *code++ = ext >> 8;
4541 arg &= 0xffff;
4542 }
4543 *code++ = i->i_opcode;
4544 if (i->i_hasarg) {
4545 assert(size == 3 || size == 6);
4546 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004547 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 }
4549 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004550}
4551
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004552static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 basicblock *b;
4556 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4557 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 /* Compute the size of each block and fixup jump args.
4560 Replace block pointer with position in bytecode. */
4561 do {
4562 totsize = 0;
4563 for (i = a->a_nblocks - 1; i >= 0; i--) {
4564 b = a->a_postorder[i];
4565 bsize = blocksize(b);
4566 b->b_offset = totsize;
4567 totsize += bsize;
4568 }
4569 last_extended_arg_count = extended_arg_count;
4570 extended_arg_count = 0;
4571 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4572 bsize = b->b_offset;
4573 for (i = 0; i < b->b_iused; i++) {
4574 struct instr *instr = &b->b_instr[i];
4575 /* Relative jumps are computed relative to
4576 the instruction pointer after fetching
4577 the jump instruction.
4578 */
4579 bsize += instrsize(instr);
4580 if (instr->i_jabs)
4581 instr->i_oparg = instr->i_target->b_offset;
4582 else if (instr->i_jrel) {
4583 int delta = instr->i_target->b_offset - bsize;
4584 instr->i_oparg = delta;
4585 }
4586 else
4587 continue;
4588 if (instr->i_oparg > 0xffff)
4589 extended_arg_count++;
4590 }
4591 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 /* XXX: This is an awful hack that could hurt performance, but
4594 on the bright side it should work until we come up
4595 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 The issue is that in the first loop blocksize() is called
4598 which calls instrsize() which requires i_oparg be set
4599 appropriately. There is a bootstrap problem because
4600 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 So we loop until we stop seeing new EXTENDED_ARGs.
4603 The only EXTENDED_ARGs that could be popping up are
4604 ones in jump instructions. So this should converge
4605 fairly quickly.
4606 */
4607 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004608}
4609
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004610static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004611dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 PyObject *tuple, *k, *v;
4614 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 tuple = PyTuple_New(size);
4617 if (tuple == NULL)
4618 return NULL;
4619 while (PyDict_Next(dict, &pos, &k, &v)) {
4620 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004621 /* The keys of the dictionary are tuples. (see compiler_add_o
4622 * and _PyCode_ConstantKey). The object we want is always second,
4623 * though. */
4624 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 Py_INCREF(k);
4626 assert((i - offset) < size);
4627 assert((i - offset) >= 0);
4628 PyTuple_SET_ITEM(tuple, i - offset, k);
4629 }
4630 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004631}
4632
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004633static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004634compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004637 int flags = 0;
4638 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004640 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 if (ste->ste_nested)
4642 flags |= CO_NESTED;
4643 if (ste->ste_generator)
4644 flags |= CO_GENERATOR;
4645 if (ste->ste_varargs)
4646 flags |= CO_VARARGS;
4647 if (ste->ste_varkeywords)
4648 flags |= CO_VARKEYWORDS;
4649 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 /* (Only) inherit compilerflags in PyCF_MASK */
4652 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 n = PyDict_Size(c->u->u_freevars);
4655 if (n < 0)
4656 return -1;
4657 if (n == 0) {
4658 n = PyDict_Size(c->u->u_cellvars);
4659 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004660 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004662 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 }
4664 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004667}
4668
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004669static PyCodeObject *
4670makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 PyObject *tmp;
4673 PyCodeObject *co = NULL;
4674 PyObject *consts = NULL;
4675 PyObject *names = NULL;
4676 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 PyObject *name = NULL;
4678 PyObject *freevars = NULL;
4679 PyObject *cellvars = NULL;
4680 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004681 Py_ssize_t nlocals;
4682 int nlocals_int;
4683 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004684 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 tmp = dict_keys_inorder(c->u->u_consts, 0);
4687 if (!tmp)
4688 goto error;
4689 consts = PySequence_List(tmp); /* optimize_code requires a list */
4690 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 names = dict_keys_inorder(c->u->u_names, 0);
4693 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4694 if (!consts || !names || !varnames)
4695 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4698 if (!cellvars)
4699 goto error;
4700 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4701 if (!freevars)
4702 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004705 assert(nlocals < INT_MAX);
4706 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 flags = compute_code_flags(c);
4709 if (flags < 0)
4710 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4713 if (!bytecode)
4714 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4717 if (!tmp)
4718 goto error;
4719 Py_DECREF(consts);
4720 consts = tmp;
4721
Victor Stinnerf8e32212013-11-19 23:56:34 +01004722 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4723 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4724 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004725 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 bytecode, consts, names, varnames,
4727 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004728 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 c->u->u_firstlineno,
4730 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004731 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 Py_XDECREF(consts);
4733 Py_XDECREF(names);
4734 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 Py_XDECREF(name);
4736 Py_XDECREF(freevars);
4737 Py_XDECREF(cellvars);
4738 Py_XDECREF(bytecode);
4739 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004740}
4741
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004742
4743/* For debugging purposes only */
4744#if 0
4745static void
4746dump_instr(const struct instr *i)
4747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 const char *jrel = i->i_jrel ? "jrel " : "";
4749 const char *jabs = i->i_jabs ? "jabs " : "";
4750 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 *arg = '\0';
4753 if (i->i_hasarg)
4754 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4757 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004758}
4759
4760static void
4761dump_basicblock(const basicblock *b)
4762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 const char *seen = b->b_seen ? "seen " : "";
4764 const char *b_return = b->b_return ? "return " : "";
4765 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4766 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4767 if (b->b_instr) {
4768 int i;
4769 for (i = 0; i < b->b_iused; i++) {
4770 fprintf(stderr, " [%02d] ", i);
4771 dump_instr(b->b_instr + i);
4772 }
4773 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004774}
4775#endif
4776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004777static PyCodeObject *
4778assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 basicblock *b, *entryblock;
4781 struct assembler a;
4782 int i, j, nblocks;
4783 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 /* Make sure every block that falls off the end returns None.
4786 XXX NEXT_BLOCK() isn't quite right, because if the last
4787 block ends with a jump or return b_next shouldn't set.
4788 */
4789 if (!c->u->u_curblock->b_return) {
4790 NEXT_BLOCK(c);
4791 if (addNone)
4792 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4793 ADDOP(c, RETURN_VALUE);
4794 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 nblocks = 0;
4797 entryblock = NULL;
4798 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4799 nblocks++;
4800 entryblock = b;
4801 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 /* Set firstlineno if it wasn't explicitly set. */
4804 if (!c->u->u_firstlineno) {
4805 if (entryblock && entryblock->b_instr)
4806 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4807 else
4808 c->u->u_firstlineno = 1;
4809 }
4810 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4811 goto error;
4812 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 /* Can't modify the bytecode after computing jump offsets. */
4815 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 /* Emit code in reverse postorder from dfs. */
4818 for (i = a.a_nblocks - 1; i >= 0; i--) {
4819 b = a.a_postorder[i];
4820 for (j = 0; j < b->b_iused; j++)
4821 if (!assemble_emit(&a, &b->b_instr[j]))
4822 goto error;
4823 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4826 goto error;
4827 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4828 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004831 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 assemble_free(&a);
4833 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004834}
Georg Brandl8334fd92010-12-04 10:26:46 +00004835
4836#undef PyAST_Compile
4837PyAPI_FUNC(PyCodeObject *)
4838PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4839 PyArena *arena)
4840{
4841 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4842}