blob: ca1d8656c731ecac3c415ee3ef90d922bf148773 [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;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001317 if (s->v.Expr.value->kind == Str_kind)
1318 return 1;
1319 if (s->v.Expr.value->kind == Constant_kind)
1320 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1321 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324/* Compile a sequence of statements, checking for a docstring. */
1325
1326static int
1327compiler_body(struct compiler *c, asdl_seq *stmts)
1328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 int i = 0;
1330 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (!asdl_seq_LEN(stmts))
1333 return 1;
1334 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001335 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* don't generate docstrings if -OO */
1337 i = 1;
1338 VISIT(c, expr, st->v.Expr.value);
1339 if (!compiler_nameop(c, __doc__, Store))
1340 return 0;
1341 }
1342 for (; i < asdl_seq_LEN(stmts); i++)
1343 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1344 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345}
1346
1347static PyCodeObject *
1348compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 PyCodeObject *co;
1351 int addNone = 1;
1352 static PyObject *module;
1353 if (!module) {
1354 module = PyUnicode_InternFromString("<module>");
1355 if (!module)
1356 return NULL;
1357 }
1358 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001359 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 return NULL;
1361 switch (mod->kind) {
1362 case Module_kind:
1363 if (!compiler_body(c, mod->v.Module.body)) {
1364 compiler_exit_scope(c);
1365 return 0;
1366 }
1367 break;
1368 case Interactive_kind:
1369 c->c_interactive = 1;
1370 VISIT_SEQ_IN_SCOPE(c, stmt,
1371 mod->v.Interactive.body);
1372 break;
1373 case Expression_kind:
1374 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1375 addNone = 0;
1376 break;
1377 case Suite_kind:
1378 PyErr_SetString(PyExc_SystemError,
1379 "suite should not be possible");
1380 return 0;
1381 default:
1382 PyErr_Format(PyExc_SystemError,
1383 "module kind %d should not be possible",
1384 mod->kind);
1385 return 0;
1386 }
1387 co = assemble(c, addNone);
1388 compiler_exit_scope(c);
1389 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001390}
1391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392/* The test for LOCAL must come before the test for FREE in order to
1393 handle classes where name is both local and free. The local var is
1394 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001395*/
1396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397static int
1398get_ref_type(struct compiler *c, PyObject *name)
1399{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001400 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001401 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1402 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1403 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001404 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (scope == 0) {
1406 char buf[350];
1407 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001408 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001410 PyUnicode_AsUTF8(name),
1411 PyUnicode_AsUTF8(c->u->u_name),
1412 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1413 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1414 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1415 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 );
1417 Py_FatalError(buf);
1418 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421}
1422
1423static int
1424compiler_lookup_arg(PyObject *dict, PyObject *name)
1425{
1426 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001427 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001429 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001431 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001433 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001434 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435}
1436
1437static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001438compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001440 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001441 if (qualname == NULL)
1442 qualname = co->co_name;
1443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (free == 0) {
1445 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001446 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 ADDOP_I(c, MAKE_FUNCTION, args);
1448 return 1;
1449 }
1450 for (i = 0; i < free; ++i) {
1451 /* Bypass com_addop_varname because it will generate
1452 LOAD_DEREF but LOAD_CLOSURE is needed.
1453 */
1454 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1455 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /* Special case: If a class contains a method with a
1458 free variable that has the same name as a method,
1459 the name will be considered free *and* local in the
1460 class. It should be handled by the closure, as
1461 well as by the normal name loookup logic.
1462 */
1463 reftype = get_ref_type(c, name);
1464 if (reftype == CELL)
1465 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1466 else /* (reftype == FREE) */
1467 arg = compiler_lookup_arg(c->u->u_freevars, name);
1468 if (arg == -1) {
1469 fprintf(stderr,
1470 "lookup %s in %s %d %d\n"
1471 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001472 PyUnicode_AsUTF8(PyObject_Repr(name)),
1473 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001475 PyUnicode_AsUTF8(co->co_name),
1476 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 Py_FatalError("compiler_make_closure()");
1478 }
1479 ADDOP_I(c, LOAD_CLOSURE, arg);
1480 }
1481 ADDOP_I(c, BUILD_TUPLE, free);
1482 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001483 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 ADDOP_I(c, MAKE_CLOSURE, args);
1485 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486}
1487
1488static int
1489compiler_decorators(struct compiler *c, asdl_seq* decos)
1490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (!decos)
1494 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1497 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1498 }
1499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
1502static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001503compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 int i, default_count = 0;
1507 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1508 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1509 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1510 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001511 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1512 if (!mangled)
1513 return -1;
1514 ADDOP_O(c, LOAD_CONST, mangled, consts);
1515 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (!compiler_visit_expr(c, default_)) {
1517 return -1;
1518 }
1519 default_count++;
1520 }
1521 }
1522 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001523}
1524
1525static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001526compiler_visit_argannotation(struct compiler *c, identifier id,
1527 expr_ty annotation, PyObject *names)
1528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001530 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001532 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001533 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001534 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001535 if (PyList_Append(names, mangled) < 0) {
1536 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001537 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001538 }
1539 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001541 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001542}
1543
1544static int
1545compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1546 PyObject *names)
1547{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001548 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 for (i = 0; i < asdl_seq_LEN(args); i++) {
1550 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001551 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 c,
1553 arg->arg,
1554 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001555 names))
1556 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001558 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001559}
1560
1561static int
1562compiler_visit_annotations(struct compiler *c, arguments_ty args,
1563 expr_ty returns)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 /* Push arg annotations and a list of the argument names. Return the #
1566 of items pushed. The expressions are evaluated out-of-order wrt the
1567 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1570 */
1571 static identifier return_str;
1572 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001573 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 names = PyList_New(0);
1575 if (!names)
1576 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001577
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001578 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001580 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001581 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001582 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001584 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001586 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001587 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001588 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (!return_str) {
1592 return_str = PyUnicode_InternFromString("return");
1593 if (!return_str)
1594 goto error;
1595 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001596 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 goto error;
1598 }
1599
1600 len = PyList_GET_SIZE(names);
1601 if (len > 65534) {
1602 /* len must fit in 16 bits, and len is incremented below */
1603 PyErr_SetString(PyExc_SyntaxError,
1604 "too many annotations");
1605 goto error;
1606 }
1607 if (len) {
1608 /* convert names to a tuple and place on stack */
1609 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001610 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 PyObject *s = PyTuple_New(len);
1612 if (!s)
1613 goto error;
1614 for (i = 0; i < len; i++) {
1615 elt = PyList_GET_ITEM(names, i);
1616 Py_INCREF(elt);
1617 PyTuple_SET_ITEM(s, i, elt);
1618 }
1619 ADDOP_O(c, LOAD_CONST, s, consts);
1620 Py_DECREF(s);
1621 len++; /* include the just-pushed tuple */
1622 }
1623 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001624
1625 /* We just checked that len <= 65535, see above */
1626 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001627
1628error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 Py_DECREF(names);
1630 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001631}
1632
1633static int
Yury Selivanov75445082015-05-11 22:57:16 -04001634compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001637 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001638 arguments_ty args;
1639 expr_ty returns;
1640 identifier name;
1641 asdl_seq* decos;
1642 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001644 Py_ssize_t i, n, arglength;
1645 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001647 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001648
Yury Selivanov75445082015-05-11 22:57:16 -04001649
1650 if (is_async) {
1651 assert(s->kind == AsyncFunctionDef_kind);
1652
1653 args = s->v.AsyncFunctionDef.args;
1654 returns = s->v.AsyncFunctionDef.returns;
1655 decos = s->v.AsyncFunctionDef.decorator_list;
1656 name = s->v.AsyncFunctionDef.name;
1657 body = s->v.AsyncFunctionDef.body;
1658
1659 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1660 } else {
1661 assert(s->kind == FunctionDef_kind);
1662
1663 args = s->v.FunctionDef.args;
1664 returns = s->v.FunctionDef.returns;
1665 decos = s->v.FunctionDef.decorator_list;
1666 name = s->v.FunctionDef.name;
1667 body = s->v.FunctionDef.body;
1668
1669 scope_type = COMPILER_SCOPE_FUNCTION;
1670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (!compiler_decorators(c, decos))
1673 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001674 if (args->defaults)
1675 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 if (args->kwonlyargs) {
1677 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1678 args->kw_defaults);
1679 if (res < 0)
1680 return 0;
1681 kw_default_count = res;
1682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 num_annotations = compiler_visit_annotations(c, args, returns);
1684 if (num_annotations < 0)
1685 return 0;
1686 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001687
Yury Selivanov75445082015-05-11 22:57:16 -04001688 if (!compiler_enter_scope(c, name,
1689 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 s->lineno))
1691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Yury Selivanov75445082015-05-11 22:57:16 -04001693 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001695 if (docstring && c->c_optimize < 2) {
1696 if (st->v.Expr.value->kind == Constant_kind)
1697 first_const = st->v.Expr.value->v.Constant.value;
1698 else
1699 first_const = st->v.Expr.value->v.Str.s;
1700 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1702 compiler_exit_scope(c);
1703 return 0;
1704 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 c->u->u_argcount = asdl_seq_LEN(args->args);
1707 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001708 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 /* if there was a docstring, we need to skip the first statement */
1710 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001711 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 VISIT_IN_SCOPE(c, stmt, st);
1713 }
1714 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001715 qualname = c->u->u_qualname;
1716 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001718 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001719 Py_XDECREF(qualname);
1720 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001722 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 arglength = asdl_seq_LEN(args->defaults);
1725 arglength |= kw_default_count << 8;
1726 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001727 if (is_async)
1728 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001729 compiler_make_closure(c, co, arglength, qualname);
1730 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* decorators */
1734 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1735 ADDOP_I(c, CALL_FUNCTION, 1);
1736 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737
Yury Selivanov75445082015-05-11 22:57:16 -04001738 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001739}
1740
1741static int
1742compiler_class(struct compiler *c, stmt_ty s)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyCodeObject *co;
1745 PyObject *str;
1746 int i;
1747 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (!compiler_decorators(c, decos))
1750 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 /* ultimately generate code for:
1753 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1754 where:
1755 <func> is a function/closure created from the class body;
1756 it has a single argument (__locals__) where the dict
1757 (or MutableSequence) representing the locals is passed
1758 <name> is the class name
1759 <bases> is the positional arguments and *varargs argument
1760 <keywords> is the keyword arguments and **kwds argument
1761 This borrows from compiler_call.
1762 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001765 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1766 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 return 0;
1768 /* this block represents what we do in the new scope */
1769 {
1770 /* use the class name for name mangling */
1771 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001772 Py_SETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 /* load (global) __name__ ... */
1774 str = PyUnicode_InternFromString("__name__");
1775 if (!str || !compiler_nameop(c, str, Load)) {
1776 Py_XDECREF(str);
1777 compiler_exit_scope(c);
1778 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001779 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 Py_DECREF(str);
1781 /* ... and store it as __module__ */
1782 str = PyUnicode_InternFromString("__module__");
1783 if (!str || !compiler_nameop(c, str, Store)) {
1784 Py_XDECREF(str);
1785 compiler_exit_scope(c);
1786 return 0;
1787 }
1788 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001789 assert(c->u->u_qualname);
1790 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001791 str = PyUnicode_InternFromString("__qualname__");
1792 if (!str || !compiler_nameop(c, str, Store)) {
1793 Py_XDECREF(str);
1794 compiler_exit_scope(c);
1795 return 0;
1796 }
1797 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* compile the body proper */
1799 if (!compiler_body(c, s->v.ClassDef.body)) {
1800 compiler_exit_scope(c);
1801 return 0;
1802 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001803 if (c->u->u_ste->ste_needs_class_closure) {
1804 /* return the (empty) __class__ cell */
1805 str = PyUnicode_InternFromString("__class__");
1806 if (str == NULL) {
1807 compiler_exit_scope(c);
1808 return 0;
1809 }
1810 i = compiler_lookup_arg(c->u->u_cellvars, str);
1811 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001812 if (i < 0) {
1813 compiler_exit_scope(c);
1814 return 0;
1815 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001816 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* Return the cell where to store __class__ */
1818 ADDOP_I(c, LOAD_CLOSURE, i);
1819 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001820 else {
1821 assert(PyDict_Size(c->u->u_cellvars) == 0);
1822 /* This happens when nobody references the cell. Return None. */
1823 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1826 /* create the code object */
1827 co = assemble(c, 1);
1828 }
1829 /* leave the new scope */
1830 compiler_exit_scope(c);
1831 if (co == NULL)
1832 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* 2. load the 'build_class' function */
1835 ADDOP(c, LOAD_BUILD_CLASS);
1836
1837 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001838 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 Py_DECREF(co);
1840
1841 /* 4. load class name */
1842 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1843
1844 /* 5. generate the rest of the code for the call */
1845 if (!compiler_call_helper(c, 2,
1846 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001847 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 return 0;
1849
1850 /* 6. apply decorators */
1851 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1852 ADDOP_I(c, CALL_FUNCTION, 1);
1853 }
1854
1855 /* 7. store into <name> */
1856 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1857 return 0;
1858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859}
1860
1861static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001862compiler_ifexp(struct compiler *c, expr_ty e)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 basicblock *end, *next;
1865
1866 assert(e->kind == IfExp_kind);
1867 end = compiler_new_block(c);
1868 if (end == NULL)
1869 return 0;
1870 next = compiler_new_block(c);
1871 if (next == NULL)
1872 return 0;
1873 VISIT(c, expr, e->v.IfExp.test);
1874 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1875 VISIT(c, expr, e->v.IfExp.body);
1876 ADDOP_JREL(c, JUMP_FORWARD, end);
1877 compiler_use_next_block(c, next);
1878 VISIT(c, expr, e->v.IfExp.orelse);
1879 compiler_use_next_block(c, end);
1880 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001881}
1882
1883static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884compiler_lambda(struct compiler *c, expr_ty e)
1885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001887 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001889 int kw_default_count = 0;
1890 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 arguments_ty args = e->v.Lambda.args;
1892 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (!name) {
1895 name = PyUnicode_InternFromString("<lambda>");
1896 if (!name)
1897 return 0;
1898 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001900 if (args->defaults)
1901 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 if (args->kwonlyargs) {
1903 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1904 args->kw_defaults);
1905 if (res < 0) return 0;
1906 kw_default_count = res;
1907 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001908 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001909 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* Make None the first constant, so the lambda can't have a
1913 docstring. */
1914 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1915 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 c->u->u_argcount = asdl_seq_LEN(args->args);
1918 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1919 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1920 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001921 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
1923 else {
1924 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001925 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001927 qualname = c->u->u_qualname;
1928 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001930 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 arglength = asdl_seq_LEN(args->defaults);
1934 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001935 compiler_make_closure(c, co, arglength, qualname);
1936 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 Py_DECREF(co);
1938
1939 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940}
1941
1942static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943compiler_if(struct compiler *c, stmt_ty s)
1944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 basicblock *end, *next;
1946 int constant;
1947 assert(s->kind == If_kind);
1948 end = compiler_new_block(c);
1949 if (end == NULL)
1950 return 0;
1951
Georg Brandl8334fd92010-12-04 10:26:46 +00001952 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 /* constant = 0: "if 0"
1954 * constant = 1: "if 1", "if 2", ...
1955 * constant = -1: rest */
1956 if (constant == 0) {
1957 if (s->v.If.orelse)
1958 VISIT_SEQ(c, stmt, s->v.If.orelse);
1959 } else if (constant == 1) {
1960 VISIT_SEQ(c, stmt, s->v.If.body);
1961 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001962 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 next = compiler_new_block(c);
1964 if (next == NULL)
1965 return 0;
1966 }
1967 else
1968 next = end;
1969 VISIT(c, expr, s->v.If.test);
1970 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1971 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001972 if (asdl_seq_LEN(s->v.If.orelse)) {
1973 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 compiler_use_next_block(c, next);
1975 VISIT_SEQ(c, stmt, s->v.If.orelse);
1976 }
1977 }
1978 compiler_use_next_block(c, end);
1979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980}
1981
1982static int
1983compiler_for(struct compiler *c, stmt_ty s)
1984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 start = compiler_new_block(c);
1988 cleanup = compiler_new_block(c);
1989 end = compiler_new_block(c);
1990 if (start == NULL || end == NULL || cleanup == NULL)
1991 return 0;
1992 ADDOP_JREL(c, SETUP_LOOP, end);
1993 if (!compiler_push_fblock(c, LOOP, start))
1994 return 0;
1995 VISIT(c, expr, s->v.For.iter);
1996 ADDOP(c, GET_ITER);
1997 compiler_use_next_block(c, start);
1998 ADDOP_JREL(c, FOR_ITER, cleanup);
1999 VISIT(c, expr, s->v.For.target);
2000 VISIT_SEQ(c, stmt, s->v.For.body);
2001 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2002 compiler_use_next_block(c, cleanup);
2003 ADDOP(c, POP_BLOCK);
2004 compiler_pop_fblock(c, LOOP, start);
2005 VISIT_SEQ(c, stmt, s->v.For.orelse);
2006 compiler_use_next_block(c, end);
2007 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008}
2009
Yury Selivanov75445082015-05-11 22:57:16 -04002010
2011static int
2012compiler_async_for(struct compiler *c, stmt_ty s)
2013{
2014 static PyObject *stopiter_error = NULL;
2015 basicblock *try, *except, *end, *after_try, *try_cleanup,
2016 *after_loop, *after_loop_else;
2017
2018 if (stopiter_error == NULL) {
2019 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2020 if (stopiter_error == NULL)
2021 return 0;
2022 }
2023
2024 try = compiler_new_block(c);
2025 except = compiler_new_block(c);
2026 end = compiler_new_block(c);
2027 after_try = compiler_new_block(c);
2028 try_cleanup = compiler_new_block(c);
2029 after_loop = compiler_new_block(c);
2030 after_loop_else = compiler_new_block(c);
2031
2032 if (try == NULL || except == NULL || end == NULL
2033 || after_try == NULL || try_cleanup == NULL)
2034 return 0;
2035
2036 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2037 if (!compiler_push_fblock(c, LOOP, try))
2038 return 0;
2039
2040 VISIT(c, expr, s->v.AsyncFor.iter);
2041 ADDOP(c, GET_AITER);
2042 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2043 ADDOP(c, YIELD_FROM);
2044
2045 compiler_use_next_block(c, try);
2046
2047
2048 ADDOP_JREL(c, SETUP_EXCEPT, except);
2049 if (!compiler_push_fblock(c, EXCEPT, try))
2050 return 0;
2051
2052 ADDOP(c, GET_ANEXT);
2053 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2054 ADDOP(c, YIELD_FROM);
2055 VISIT(c, expr, s->v.AsyncFor.target);
2056 ADDOP(c, POP_BLOCK);
2057 compiler_pop_fblock(c, EXCEPT, try);
2058 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2059
2060
2061 compiler_use_next_block(c, except);
2062 ADDOP(c, DUP_TOP);
2063 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2064 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2065 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2066
2067 ADDOP(c, POP_TOP);
2068 ADDOP(c, POP_TOP);
2069 ADDOP(c, POP_TOP);
2070 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2071 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2072 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2073
2074
2075 compiler_use_next_block(c, try_cleanup);
2076 ADDOP(c, END_FINALLY);
2077
2078 compiler_use_next_block(c, after_try);
2079 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2080 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2081
2082 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2083 compiler_pop_fblock(c, LOOP, try);
2084
2085 compiler_use_next_block(c, after_loop);
2086 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2087
2088 compiler_use_next_block(c, after_loop_else);
2089 VISIT_SEQ(c, stmt, s->v.For.orelse);
2090
2091 compiler_use_next_block(c, end);
2092
2093 return 1;
2094}
2095
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096static int
2097compiler_while(struct compiler *c, stmt_ty s)
2098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002100 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (constant == 0) {
2103 if (s->v.While.orelse)
2104 VISIT_SEQ(c, stmt, s->v.While.orelse);
2105 return 1;
2106 }
2107 loop = compiler_new_block(c);
2108 end = compiler_new_block(c);
2109 if (constant == -1) {
2110 anchor = compiler_new_block(c);
2111 if (anchor == NULL)
2112 return 0;
2113 }
2114 if (loop == NULL || end == NULL)
2115 return 0;
2116 if (s->v.While.orelse) {
2117 orelse = compiler_new_block(c);
2118 if (orelse == NULL)
2119 return 0;
2120 }
2121 else
2122 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 ADDOP_JREL(c, SETUP_LOOP, end);
2125 compiler_use_next_block(c, loop);
2126 if (!compiler_push_fblock(c, LOOP, loop))
2127 return 0;
2128 if (constant == -1) {
2129 VISIT(c, expr, s->v.While.test);
2130 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2131 }
2132 VISIT_SEQ(c, stmt, s->v.While.body);
2133 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* XXX should the two POP instructions be in a separate block
2136 if there is no else clause ?
2137 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002139 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002141 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 compiler_pop_fblock(c, LOOP, loop);
2143 if (orelse != NULL) /* what if orelse is just pass? */
2144 VISIT_SEQ(c, stmt, s->v.While.orelse);
2145 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148}
2149
2150static int
2151compiler_continue(struct compiler *c)
2152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2154 static const char IN_FINALLY_ERROR_MSG[] =
2155 "'continue' not supported inside 'finally' clause";
2156 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (!c->u->u_nfblocks)
2159 return compiler_error(c, LOOP_ERROR_MSG);
2160 i = c->u->u_nfblocks - 1;
2161 switch (c->u->u_fblock[i].fb_type) {
2162 case LOOP:
2163 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2164 break;
2165 case EXCEPT:
2166 case FINALLY_TRY:
2167 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2168 /* Prevent continue anywhere under a finally
2169 even if hidden in a sub-try or except. */
2170 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2171 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2172 }
2173 if (i == -1)
2174 return compiler_error(c, LOOP_ERROR_MSG);
2175 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2176 break;
2177 case FINALLY_END:
2178 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2179 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182}
2183
2184/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185
2186 SETUP_FINALLY L
2187 <code for body>
2188 POP_BLOCK
2189 LOAD_CONST <None>
2190 L: <code for finalbody>
2191 END_FINALLY
2192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 The special instructions use the block stack. Each block
2194 stack entry contains the instruction that created it (here
2195 SETUP_FINALLY), the level of the value stack at the time the
2196 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 Pushes the current value stack level and the label
2200 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 Pops en entry from the block stack, and pops the value
2203 stack until its level is the same as indicated on the
2204 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 Pops a variable number of entries from the *value* stack
2207 and re-raises the exception they specify. The number of
2208 entries popped depends on the (pseudo) exception type.
2209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210 The block stack is unwound when an exception is raised:
2211 when a SETUP_FINALLY entry is found, the exception is pushed
2212 onto the value stack (and the exception condition is cleared),
2213 and the interpreter jumps to the label gotten from the block
2214 stack.
2215*/
2216
2217static int
2218compiler_try_finally(struct compiler *c, stmt_ty s)
2219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 basicblock *body, *end;
2221 body = compiler_new_block(c);
2222 end = compiler_new_block(c);
2223 if (body == NULL || end == NULL)
2224 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 ADDOP_JREL(c, SETUP_FINALLY, end);
2227 compiler_use_next_block(c, body);
2228 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2229 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002230 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2231 if (!compiler_try_except(c, s))
2232 return 0;
2233 }
2234 else {
2235 VISIT_SEQ(c, stmt, s->v.Try.body);
2236 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 ADDOP(c, POP_BLOCK);
2238 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2241 compiler_use_next_block(c, end);
2242 if (!compiler_push_fblock(c, FINALLY_END, end))
2243 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002244 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 ADDOP(c, END_FINALLY);
2246 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249}
2250
2251/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002252 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 (The contents of the value stack is shown in [], with the top
2254 at the right; 'tb' is trace-back info, 'val' the exception's
2255 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256
2257 Value stack Label Instruction Argument
2258 [] SETUP_EXCEPT L1
2259 [] <code for S>
2260 [] POP_BLOCK
2261 [] JUMP_FORWARD L0
2262
2263 [tb, val, exc] L1: DUP )
2264 [tb, val, exc, exc] <evaluate E1> )
2265 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2266 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2267 [tb, val, exc] POP
2268 [tb, val] <assign to V1> (or POP if no V1)
2269 [tb] POP
2270 [] <code for S1>
2271 JUMP_FORWARD L0
2272
2273 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 .............................etc.......................
2275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2277
2278 [] L0: <next statement>
2279
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 Of course, parts are not generated if Vi or Ei is not present.
2281*/
2282static int
2283compiler_try_except(struct compiler *c, stmt_ty s)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002286 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 body = compiler_new_block(c);
2289 except = compiler_new_block(c);
2290 orelse = compiler_new_block(c);
2291 end = compiler_new_block(c);
2292 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2293 return 0;
2294 ADDOP_JREL(c, SETUP_EXCEPT, except);
2295 compiler_use_next_block(c, body);
2296 if (!compiler_push_fblock(c, EXCEPT, body))
2297 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002298 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 ADDOP(c, POP_BLOCK);
2300 compiler_pop_fblock(c, EXCEPT, body);
2301 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002302 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 compiler_use_next_block(c, except);
2304 for (i = 0; i < n; i++) {
2305 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002306 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (!handler->v.ExceptHandler.type && i < n-1)
2308 return compiler_error(c, "default 'except:' must be last");
2309 c->u->u_lineno_set = 0;
2310 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002311 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 except = compiler_new_block(c);
2313 if (except == NULL)
2314 return 0;
2315 if (handler->v.ExceptHandler.type) {
2316 ADDOP(c, DUP_TOP);
2317 VISIT(c, expr, handler->v.ExceptHandler.type);
2318 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2319 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2320 }
2321 ADDOP(c, POP_TOP);
2322 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002323 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002324
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002325 cleanup_end = compiler_new_block(c);
2326 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002327 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002328 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002329
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002330 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2331 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002333 /*
2334 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002335 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002336 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002337 try:
2338 # body
2339 finally:
2340 name = None
2341 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002342 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002344 /* second try: */
2345 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2346 compiler_use_next_block(c, cleanup_body);
2347 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2348 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002350 /* second # body */
2351 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2352 ADDOP(c, POP_BLOCK);
2353 ADDOP(c, POP_EXCEPT);
2354 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002356 /* finally: */
2357 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2358 compiler_use_next_block(c, cleanup_end);
2359 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2360 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002362 /* name = None */
2363 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2364 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002366 /* del name */
2367 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002369 ADDOP(c, END_FINALLY);
2370 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 }
2372 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002373 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002375 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002376 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002377 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378
Guido van Rossumb940e112007-01-10 16:19:56 +00002379 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002380 ADDOP(c, POP_TOP);
2381 compiler_use_next_block(c, cleanup_body);
2382 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2383 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002385 ADDOP(c, POP_EXCEPT);
2386 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 }
2388 ADDOP_JREL(c, JUMP_FORWARD, end);
2389 compiler_use_next_block(c, except);
2390 }
2391 ADDOP(c, END_FINALLY);
2392 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002393 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 compiler_use_next_block(c, end);
2395 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396}
2397
2398static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002399compiler_try(struct compiler *c, stmt_ty s) {
2400 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2401 return compiler_try_finally(c, s);
2402 else
2403 return compiler_try_except(c, s);
2404}
2405
2406
2407static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408compiler_import_as(struct compiler *c, identifier name, identifier asname)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* The IMPORT_NAME opcode was already generated. This function
2411 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 If there is a dot in name, we need to split it and emit a
2414 LOAD_ATTR for each name.
2415 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2417 PyUnicode_GET_LENGTH(name), 1);
2418 if (dot == -2)
2419 return -1;
2420 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002422 Py_ssize_t pos = dot + 1;
2423 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002425 dot = PyUnicode_FindChar(name, '.', pos,
2426 PyUnicode_GET_LENGTH(name), 1);
2427 if (dot == -2)
2428 return -1;
2429 attr = PyUnicode_Substring(name, pos,
2430 (dot != -1) ? dot :
2431 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (!attr)
2433 return -1;
2434 ADDOP_O(c, LOAD_ATTR, attr, names);
2435 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002436 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 }
2438 }
2439 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440}
2441
2442static int
2443compiler_import(struct compiler *c, stmt_ty s)
2444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 /* The Import node stores a module name like a.b.c as a single
2446 string. This is convenient for all cases except
2447 import a.b.c as d
2448 where we need to parse that string to extract the individual
2449 module names.
2450 XXX Perhaps change the representation to make this case simpler?
2451 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002452 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 for (i = 0; i < n; i++) {
2455 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2456 int r;
2457 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 level = PyLong_FromLong(0);
2460 if (level == NULL)
2461 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 ADDOP_O(c, LOAD_CONST, level, consts);
2464 Py_DECREF(level);
2465 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2466 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (alias->asname) {
2469 r = compiler_import_as(c, alias->name, alias->asname);
2470 if (!r)
2471 return r;
2472 }
2473 else {
2474 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 Py_ssize_t dot = PyUnicode_FindChar(
2476 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002477 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002479 if (tmp == NULL)
2480 return 0;
2481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 Py_DECREF(tmp);
2485 }
2486 if (!r)
2487 return r;
2488 }
2489 }
2490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491}
2492
2493static int
2494compiler_from_import(struct compiler *c, stmt_ty s)
2495{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002496 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 PyObject *names = PyTuple_New(n);
2499 PyObject *level;
2500 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 if (!empty_string) {
2503 empty_string = PyUnicode_FromString("");
2504 if (!empty_string)
2505 return 0;
2506 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 if (!names)
2509 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 level = PyLong_FromLong(s->v.ImportFrom.level);
2512 if (!level) {
2513 Py_DECREF(names);
2514 return 0;
2515 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* build up the names */
2518 for (i = 0; i < n; i++) {
2519 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2520 Py_INCREF(alias->name);
2521 PyTuple_SET_ITEM(names, i, alias->name);
2522 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2525 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2526 Py_DECREF(level);
2527 Py_DECREF(names);
2528 return compiler_error(c, "from __future__ imports must occur "
2529 "at the beginning of the file");
2530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 ADDOP_O(c, LOAD_CONST, level, consts);
2533 Py_DECREF(level);
2534 ADDOP_O(c, LOAD_CONST, names, consts);
2535 Py_DECREF(names);
2536 if (s->v.ImportFrom.module) {
2537 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2538 }
2539 else {
2540 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2541 }
2542 for (i = 0; i < n; i++) {
2543 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2544 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002546 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 assert(n == 1);
2548 ADDOP(c, IMPORT_STAR);
2549 return 1;
2550 }
2551
2552 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2553 store_name = alias->name;
2554 if (alias->asname)
2555 store_name = alias->asname;
2556
2557 if (!compiler_nameop(c, store_name, Store)) {
2558 Py_DECREF(names);
2559 return 0;
2560 }
2561 }
2562 /* remove imported module */
2563 ADDOP(c, POP_TOP);
2564 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565}
2566
2567static int
2568compiler_assert(struct compiler *c, stmt_ty s)
2569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 static PyObject *assertion_error = NULL;
2571 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002572 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573
Georg Brandl8334fd92010-12-04 10:26:46 +00002574 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 return 1;
2576 if (assertion_error == NULL) {
2577 assertion_error = PyUnicode_InternFromString("AssertionError");
2578 if (assertion_error == NULL)
2579 return 0;
2580 }
2581 if (s->v.Assert.test->kind == Tuple_kind &&
2582 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002583 msg = PyUnicode_FromString("assertion is always true, "
2584 "perhaps remove parentheses?");
2585 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002587 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2588 c->c_filename, c->u->u_lineno,
2589 NULL, NULL) == -1) {
2590 Py_DECREF(msg);
2591 return 0;
2592 }
2593 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 }
2595 VISIT(c, expr, s->v.Assert.test);
2596 end = compiler_new_block(c);
2597 if (end == NULL)
2598 return 0;
2599 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2600 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2601 if (s->v.Assert.msg) {
2602 VISIT(c, expr, s->v.Assert.msg);
2603 ADDOP_I(c, CALL_FUNCTION, 1);
2604 }
2605 ADDOP_I(c, RAISE_VARARGS, 1);
2606 compiler_use_next_block(c, end);
2607 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608}
2609
2610static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002611compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2612{
2613 if (c->c_interactive && c->c_nestlevel <= 1) {
2614 VISIT(c, expr, value);
2615 ADDOP(c, PRINT_EXPR);
2616 return 1;
2617 }
2618
Victor Stinnera2724092016-02-08 18:17:58 +01002619 switch (value->kind)
2620 {
2621 case Str_kind:
Victor Stinnera2724092016-02-08 18:17:58 +01002622 case Num_kind:
Victor Stinner15a30952016-02-08 22:45:06 +01002623 case Ellipsis_kind:
2624 case Bytes_kind:
Victor Stinnera2724092016-02-08 18:17:58 +01002625 case NameConstant_kind:
2626 case Constant_kind:
Victor Stinner15a30952016-02-08 22:45:06 +01002627 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002628 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002629
Victor Stinnera2724092016-02-08 18:17:58 +01002630 default:
2631 break;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002632 }
2633
2634 VISIT(c, expr, value);
2635 ADDOP(c, POP_TOP);
2636 return 1;
2637}
2638
2639static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640compiler_visit_stmt(struct compiler *c, stmt_ty s)
2641{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002642 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 /* Always assign a lineno to the next instruction for a stmt. */
2645 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002646 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 switch (s->kind) {
2650 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002651 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 case ClassDef_kind:
2653 return compiler_class(c, s);
2654 case Return_kind:
2655 if (c->u->u_ste->ste_type != FunctionBlock)
2656 return compiler_error(c, "'return' outside function");
2657 if (s->v.Return.value) {
2658 VISIT(c, expr, s->v.Return.value);
2659 }
2660 else
2661 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2662 ADDOP(c, RETURN_VALUE);
2663 break;
2664 case Delete_kind:
2665 VISIT_SEQ(c, expr, s->v.Delete.targets)
2666 break;
2667 case Assign_kind:
2668 n = asdl_seq_LEN(s->v.Assign.targets);
2669 VISIT(c, expr, s->v.Assign.value);
2670 for (i = 0; i < n; i++) {
2671 if (i < n - 1)
2672 ADDOP(c, DUP_TOP);
2673 VISIT(c, expr,
2674 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2675 }
2676 break;
2677 case AugAssign_kind:
2678 return compiler_augassign(c, s);
2679 case For_kind:
2680 return compiler_for(c, s);
2681 case While_kind:
2682 return compiler_while(c, s);
2683 case If_kind:
2684 return compiler_if(c, s);
2685 case Raise_kind:
2686 n = 0;
2687 if (s->v.Raise.exc) {
2688 VISIT(c, expr, s->v.Raise.exc);
2689 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002690 if (s->v.Raise.cause) {
2691 VISIT(c, expr, s->v.Raise.cause);
2692 n++;
2693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002695 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002697 case Try_kind:
2698 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 case Assert_kind:
2700 return compiler_assert(c, s);
2701 case Import_kind:
2702 return compiler_import(c, s);
2703 case ImportFrom_kind:
2704 return compiler_from_import(c, s);
2705 case Global_kind:
2706 case Nonlocal_kind:
2707 break;
2708 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002709 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 case Pass_kind:
2711 break;
2712 case Break_kind:
2713 if (!compiler_in_loop(c))
2714 return compiler_error(c, "'break' outside loop");
2715 ADDOP(c, BREAK_LOOP);
2716 break;
2717 case Continue_kind:
2718 return compiler_continue(c);
2719 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002720 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002721 case AsyncFunctionDef_kind:
2722 return compiler_function(c, s, 1);
2723 case AsyncWith_kind:
2724 return compiler_async_with(c, s, 0);
2725 case AsyncFor_kind:
2726 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 }
Yury Selivanov75445082015-05-11 22:57:16 -04002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730}
2731
2732static int
2733unaryop(unaryop_ty op)
2734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 switch (op) {
2736 case Invert:
2737 return UNARY_INVERT;
2738 case Not:
2739 return UNARY_NOT;
2740 case UAdd:
2741 return UNARY_POSITIVE;
2742 case USub:
2743 return UNARY_NEGATIVE;
2744 default:
2745 PyErr_Format(PyExc_SystemError,
2746 "unary op %d should not be possible", op);
2747 return 0;
2748 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749}
2750
2751static int
2752binop(struct compiler *c, operator_ty op)
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 switch (op) {
2755 case Add:
2756 return BINARY_ADD;
2757 case Sub:
2758 return BINARY_SUBTRACT;
2759 case Mult:
2760 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002761 case MatMult:
2762 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 case Div:
2764 return BINARY_TRUE_DIVIDE;
2765 case Mod:
2766 return BINARY_MODULO;
2767 case Pow:
2768 return BINARY_POWER;
2769 case LShift:
2770 return BINARY_LSHIFT;
2771 case RShift:
2772 return BINARY_RSHIFT;
2773 case BitOr:
2774 return BINARY_OR;
2775 case BitXor:
2776 return BINARY_XOR;
2777 case BitAnd:
2778 return BINARY_AND;
2779 case FloorDiv:
2780 return BINARY_FLOOR_DIVIDE;
2781 default:
2782 PyErr_Format(PyExc_SystemError,
2783 "binary op %d should not be possible", op);
2784 return 0;
2785 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786}
2787
2788static int
2789cmpop(cmpop_ty op)
2790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 switch (op) {
2792 case Eq:
2793 return PyCmp_EQ;
2794 case NotEq:
2795 return PyCmp_NE;
2796 case Lt:
2797 return PyCmp_LT;
2798 case LtE:
2799 return PyCmp_LE;
2800 case Gt:
2801 return PyCmp_GT;
2802 case GtE:
2803 return PyCmp_GE;
2804 case Is:
2805 return PyCmp_IS;
2806 case IsNot:
2807 return PyCmp_IS_NOT;
2808 case In:
2809 return PyCmp_IN;
2810 case NotIn:
2811 return PyCmp_NOT_IN;
2812 default:
2813 return PyCmp_BAD;
2814 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815}
2816
2817static int
2818inplace_binop(struct compiler *c, operator_ty op)
2819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 switch (op) {
2821 case Add:
2822 return INPLACE_ADD;
2823 case Sub:
2824 return INPLACE_SUBTRACT;
2825 case Mult:
2826 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002827 case MatMult:
2828 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 case Div:
2830 return INPLACE_TRUE_DIVIDE;
2831 case Mod:
2832 return INPLACE_MODULO;
2833 case Pow:
2834 return INPLACE_POWER;
2835 case LShift:
2836 return INPLACE_LSHIFT;
2837 case RShift:
2838 return INPLACE_RSHIFT;
2839 case BitOr:
2840 return INPLACE_OR;
2841 case BitXor:
2842 return INPLACE_XOR;
2843 case BitAnd:
2844 return INPLACE_AND;
2845 case FloorDiv:
2846 return INPLACE_FLOOR_DIVIDE;
2847 default:
2848 PyErr_Format(PyExc_SystemError,
2849 "inplace binary op %d should not be possible", op);
2850 return 0;
2851 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852}
2853
2854static int
2855compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2856{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002857 int op, scope;
2858 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 PyObject *dict = c->u->u_names;
2862 PyObject *mangled;
2863 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 mangled = _Py_Mangle(c->u->u_private, name);
2866 if (!mangled)
2867 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002868
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002869 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2870 PyUnicode_CompareWithASCIIString(name, "True") &&
2871 PyUnicode_CompareWithASCIIString(name, "False"));
2872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 op = 0;
2874 optype = OP_NAME;
2875 scope = PyST_GetScope(c->u->u_ste, mangled);
2876 switch (scope) {
2877 case FREE:
2878 dict = c->u->u_freevars;
2879 optype = OP_DEREF;
2880 break;
2881 case CELL:
2882 dict = c->u->u_cellvars;
2883 optype = OP_DEREF;
2884 break;
2885 case LOCAL:
2886 if (c->u->u_ste->ste_type == FunctionBlock)
2887 optype = OP_FAST;
2888 break;
2889 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002890 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 optype = OP_GLOBAL;
2892 break;
2893 case GLOBAL_EXPLICIT:
2894 optype = OP_GLOBAL;
2895 break;
2896 default:
2897 /* scope can be 0 */
2898 break;
2899 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002902 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 switch (optype) {
2905 case OP_DEREF:
2906 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002907 case Load:
2908 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2909 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 case Store: op = STORE_DEREF; break;
2911 case AugLoad:
2912 case AugStore:
2913 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002914 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 case Param:
2916 default:
2917 PyErr_SetString(PyExc_SystemError,
2918 "param invalid for deref variable");
2919 return 0;
2920 }
2921 break;
2922 case OP_FAST:
2923 switch (ctx) {
2924 case Load: op = LOAD_FAST; break;
2925 case Store: op = STORE_FAST; break;
2926 case Del: op = DELETE_FAST; break;
2927 case AugLoad:
2928 case AugStore:
2929 break;
2930 case Param:
2931 default:
2932 PyErr_SetString(PyExc_SystemError,
2933 "param invalid for local variable");
2934 return 0;
2935 }
2936 ADDOP_O(c, op, mangled, varnames);
2937 Py_DECREF(mangled);
2938 return 1;
2939 case OP_GLOBAL:
2940 switch (ctx) {
2941 case Load: op = LOAD_GLOBAL; break;
2942 case Store: op = STORE_GLOBAL; break;
2943 case Del: op = DELETE_GLOBAL; break;
2944 case AugLoad:
2945 case AugStore:
2946 break;
2947 case Param:
2948 default:
2949 PyErr_SetString(PyExc_SystemError,
2950 "param invalid for global variable");
2951 return 0;
2952 }
2953 break;
2954 case OP_NAME:
2955 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002956 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 case Store: op = STORE_NAME; break;
2958 case Del: op = DELETE_NAME; break;
2959 case AugLoad:
2960 case AugStore:
2961 break;
2962 case Param:
2963 default:
2964 PyErr_SetString(PyExc_SystemError,
2965 "param invalid for name variable");
2966 return 0;
2967 }
2968 break;
2969 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 assert(op);
2972 arg = compiler_add_o(c, dict, mangled);
2973 Py_DECREF(mangled);
2974 if (arg < 0)
2975 return 0;
2976 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977}
2978
2979static int
2980compiler_boolop(struct compiler *c, expr_ty e)
2981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002983 int jumpi;
2984 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 assert(e->kind == BoolOp_kind);
2988 if (e->v.BoolOp.op == And)
2989 jumpi = JUMP_IF_FALSE_OR_POP;
2990 else
2991 jumpi = JUMP_IF_TRUE_OR_POP;
2992 end = compiler_new_block(c);
2993 if (end == NULL)
2994 return 0;
2995 s = e->v.BoolOp.values;
2996 n = asdl_seq_LEN(s) - 1;
2997 assert(n >= 0);
2998 for (i = 0; i < n; ++i) {
2999 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3000 ADDOP_JABS(c, jumpi, end);
3001 }
3002 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3003 compiler_use_next_block(c, end);
3004 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005}
3006
3007static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003008starunpack_helper(struct compiler *c, asdl_seq *elts,
3009 int single_op, int inner_op, int outer_op)
3010{
3011 Py_ssize_t n = asdl_seq_LEN(elts);
3012 Py_ssize_t i, nsubitems = 0, nseen = 0;
3013 for (i = 0; i < n; i++) {
3014 expr_ty elt = asdl_seq_GET(elts, i);
3015 if (elt->kind == Starred_kind) {
3016 if (nseen) {
3017 ADDOP_I(c, inner_op, nseen);
3018 nseen = 0;
3019 nsubitems++;
3020 }
3021 VISIT(c, expr, elt->v.Starred.value);
3022 nsubitems++;
3023 }
3024 else {
3025 VISIT(c, expr, elt);
3026 nseen++;
3027 }
3028 }
3029 if (nsubitems) {
3030 if (nseen) {
3031 ADDOP_I(c, inner_op, nseen);
3032 nsubitems++;
3033 }
3034 ADDOP_I(c, outer_op, nsubitems);
3035 }
3036 else
3037 ADDOP_I(c, single_op, nseen);
3038 return 1;
3039}
3040
3041static int
3042assignment_helper(struct compiler *c, asdl_seq *elts)
3043{
3044 Py_ssize_t n = asdl_seq_LEN(elts);
3045 Py_ssize_t i;
3046 int seen_star = 0;
3047 for (i = 0; i < n; i++) {
3048 expr_ty elt = asdl_seq_GET(elts, i);
3049 if (elt->kind == Starred_kind && !seen_star) {
3050 if ((i >= (1 << 8)) ||
3051 (n-i-1 >= (INT_MAX >> 8)))
3052 return compiler_error(c,
3053 "too many expressions in "
3054 "star-unpacking assignment");
3055 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3056 seen_star = 1;
3057 asdl_seq_SET(elts, i, elt->v.Starred.value);
3058 }
3059 else if (elt->kind == Starred_kind) {
3060 return compiler_error(c,
3061 "two starred expressions in assignment");
3062 }
3063 }
3064 if (!seen_star) {
3065 ADDOP_I(c, UNPACK_SEQUENCE, n);
3066 }
3067 VISIT_SEQ(c, expr, elts);
3068 return 1;
3069}
3070
3071static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072compiler_list(struct compiler *c, expr_ty e)
3073{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003074 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003076 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003078 else if (e->v.List.ctx == Load) {
3079 return starunpack_helper(c, elts,
3080 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003082 else
3083 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003085}
3086
3087static int
3088compiler_tuple(struct compiler *c, expr_ty e)
3089{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003090 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003092 return assignment_helper(c, elts);
3093 }
3094 else if (e->v.Tuple.ctx == Load) {
3095 return starunpack_helper(c, elts,
3096 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3097 }
3098 else
3099 VISIT_SEQ(c, expr, elts);
3100 return 1;
3101}
3102
3103static int
3104compiler_set(struct compiler *c, expr_ty e)
3105{
3106 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3107 BUILD_SET, BUILD_SET_UNPACK);
3108}
3109
3110static int
3111compiler_dict(struct compiler *c, expr_ty e)
3112{
3113 Py_ssize_t i, n, containers, elements;
3114 int is_unpacking = 0;
3115 n = asdl_seq_LEN(e->v.Dict.values);
3116 containers = 0;
3117 elements = 0;
3118 for (i = 0; i < n; i++) {
3119 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3120 if (elements == 0xFFFF || (elements && is_unpacking)) {
3121 ADDOP_I(c, BUILD_MAP, elements);
3122 containers++;
3123 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003125 if (is_unpacking) {
3126 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3127 containers++;
3128 }
3129 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003130 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003131 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003132 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 }
3134 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003135 if (elements || containers == 0) {
3136 ADDOP_I(c, BUILD_MAP, elements);
3137 containers++;
3138 }
3139 /* If there is more than one dict, they need to be merged into a new
3140 * dict. If there is one dict and it's an unpacking, then it needs
3141 * to be copied into a new dict." */
3142 while (containers > 1 || is_unpacking) {
3143 int oparg = containers < 255 ? containers : 255;
3144 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3145 containers -= (oparg - 1);
3146 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 }
3148 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149}
3150
3151static int
3152compiler_compare(struct compiler *c, expr_ty e)
3153{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003154 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3158 VISIT(c, expr, e->v.Compare.left);
3159 n = asdl_seq_LEN(e->v.Compare.ops);
3160 assert(n > 0);
3161 if (n > 1) {
3162 cleanup = compiler_new_block(c);
3163 if (cleanup == NULL)
3164 return 0;
3165 VISIT(c, expr,
3166 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3167 }
3168 for (i = 1; i < n; i++) {
3169 ADDOP(c, DUP_TOP);
3170 ADDOP(c, ROT_THREE);
3171 ADDOP_I(c, COMPARE_OP,
3172 cmpop((cmpop_ty)(asdl_seq_GET(
3173 e->v.Compare.ops, i - 1))));
3174 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3175 NEXT_BLOCK(c);
3176 if (i < (n - 1))
3177 VISIT(c, expr,
3178 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3179 }
3180 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3181 ADDOP_I(c, COMPARE_OP,
3182 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3183 if (n > 1) {
3184 basicblock *end = compiler_new_block(c);
3185 if (end == NULL)
3186 return 0;
3187 ADDOP_JREL(c, JUMP_FORWARD, end);
3188 compiler_use_next_block(c, cleanup);
3189 ADDOP(c, ROT_TWO);
3190 ADDOP(c, POP_TOP);
3191 compiler_use_next_block(c, end);
3192 }
3193 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194}
3195
3196static int
3197compiler_call(struct compiler *c, expr_ty e)
3198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 VISIT(c, expr, e->v.Call.func);
3200 return compiler_call_helper(c, 0,
3201 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003202 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003203}
3204
Eric V. Smith235a6f02015-09-19 14:51:32 -04003205static int
3206compiler_joined_str(struct compiler *c, expr_ty e)
3207{
3208 /* Concatenate parts of a string using ''.join(parts). There are
3209 probably better ways of doing this.
3210
3211 This is used for constructs like "'x=' f'{42}'", which have to
3212 be evaluated at compile time. */
3213
3214 static PyObject *empty_string;
3215 static PyObject *join_string;
3216
3217 if (!empty_string) {
3218 empty_string = PyUnicode_FromString("");
3219 if (!empty_string)
3220 return 0;
3221 }
3222 if (!join_string) {
3223 join_string = PyUnicode_FromString("join");
3224 if (!join_string)
3225 return 0;
3226 }
3227
3228 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3229 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3230 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3231 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3232 ADDOP_I(c, CALL_FUNCTION, 1);
3233 return 1;
3234}
3235
Eric V. Smitha78c7952015-11-03 12:45:05 -05003236/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003237static int
3238compiler_formatted_value(struct compiler *c, expr_ty e)
3239{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003240 /* Our oparg encodes 2 pieces of information: the conversion
3241 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003242
Eric V. Smitha78c7952015-11-03 12:45:05 -05003243 Convert the conversion char to 2 bits:
3244 None: 000 0x0 FVC_NONE
3245 !s : 001 0x1 FVC_STR
3246 !r : 010 0x2 FVC_REPR
3247 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003248
Eric V. Smitha78c7952015-11-03 12:45:05 -05003249 next bit is whether or not we have a format spec:
3250 yes : 100 0x4
3251 no : 000 0x0
3252 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003253
Eric V. Smitha78c7952015-11-03 12:45:05 -05003254 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003255
Eric V. Smitha78c7952015-11-03 12:45:05 -05003256 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003257 VISIT(c, expr, e->v.FormattedValue.value);
3258
Eric V. Smitha78c7952015-11-03 12:45:05 -05003259 switch (e->v.FormattedValue.conversion) {
3260 case 's': oparg = FVC_STR; break;
3261 case 'r': oparg = FVC_REPR; break;
3262 case 'a': oparg = FVC_ASCII; break;
3263 case -1: oparg = FVC_NONE; break;
3264 default:
3265 PyErr_SetString(PyExc_SystemError,
3266 "Unrecognized conversion character");
3267 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003268 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003269 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003270 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003271 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003272 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003273 }
3274
Eric V. Smitha78c7952015-11-03 12:45:05 -05003275 /* And push our opcode and oparg */
3276 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003277 return 1;
3278}
3279
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003280/* shared code between compiler_call and compiler_class */
3281static int
3282compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003283 Py_ssize_t n, /* Args already pushed */
3284 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003285 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003288 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003289
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003290 /* the number of tuples and dictionaries on the stack */
3291 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3292
3293 nkw = 0;
3294 nseen = 0; /* the number of positional arguments on the stack */
3295 nelts = asdl_seq_LEN(args);
3296 for (i = 0; i < nelts; i++) {
3297 expr_ty elt = asdl_seq_GET(args, i);
3298 if (elt->kind == Starred_kind) {
3299 /* A star-arg. If we've seen positional arguments,
3300 pack the positional arguments into a
3301 tuple. */
3302 if (nseen) {
3303 ADDOP_I(c, BUILD_TUPLE, nseen);
3304 nseen = 0;
3305 nsubargs++;
3306 }
3307 VISIT(c, expr, elt->v.Starred.value);
3308 nsubargs++;
3309 }
3310 else if (nsubargs) {
3311 /* We've seen star-args already, so we
3312 count towards items-to-pack-into-tuple. */
3313 VISIT(c, expr, elt);
3314 nseen++;
3315 }
3316 else {
3317 /* Positional arguments before star-arguments
3318 are left on the stack. */
3319 VISIT(c, expr, elt);
3320 n++;
3321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003323 if (nseen) {
3324 /* Pack up any trailing positional arguments. */
3325 ADDOP_I(c, BUILD_TUPLE, nseen);
3326 nsubargs++;
3327 }
3328 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003330 if (nsubargs > 1) {
3331 /* If we ended up with more than one stararg, we need
3332 to concatenate them into a single sequence. */
3333 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003336
3337 /* Same dance again for keyword arguments */
3338 nseen = 0; /* the number of keyword arguments on the stack following */
3339 nelts = asdl_seq_LEN(keywords);
3340 for (i = 0; i < nelts; i++) {
3341 keyword_ty kw = asdl_seq_GET(keywords, i);
3342 if (kw->arg == NULL) {
3343 /* A keyword argument unpacking. */
3344 if (nseen) {
3345 ADDOP_I(c, BUILD_MAP, nseen);
3346 nseen = 0;
3347 nsubkwargs++;
3348 }
3349 VISIT(c, expr, kw->value);
3350 nsubkwargs++;
3351 }
3352 else if (nsubkwargs) {
3353 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003354 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003355 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003356 nseen++;
3357 }
3358 else {
3359 /* keyword argument */
3360 VISIT(c, keyword, kw)
3361 nkw++;
3362 }
3363 }
3364 if (nseen) {
3365 /* Pack up any trailing keyword arguments. */
3366 ADDOP_I(c, BUILD_MAP, nseen);
3367 nsubkwargs++;
3368 }
3369 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003371 if (nsubkwargs > 1) {
3372 /* Pack it all up */
3373 int function_pos = n + (code & 1) + nkw + 1;
3374 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003377 assert(n < 1<<8);
3378 assert(nkw < 1<<24);
3379 n |= nkw << 8;
3380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 switch (code) {
3382 case 0:
3383 ADDOP_I(c, CALL_FUNCTION, n);
3384 break;
3385 case 1:
3386 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3387 break;
3388 case 2:
3389 ADDOP_I(c, CALL_FUNCTION_KW, n);
3390 break;
3391 case 3:
3392 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3393 break;
3394 }
3395 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396}
3397
Nick Coghlan650f0d02007-04-15 12:05:43 +00003398
3399/* List and set comprehensions and generator expressions work by creating a
3400 nested function to perform the actual iteration. This means that the
3401 iteration variables don't leak into the current scope.
3402 The defined function is called immediately following its definition, with the
3403 result of that call being the result of the expression.
3404 The LC/SC version returns the populated container, while the GE version is
3405 flagged in symtable.c as a generator, so it returns the generator object
3406 when the function is called.
3407 This code *knows* that the loop cannot contain break, continue, or return,
3408 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3409
3410 Possible cleanups:
3411 - iterate over the generator sequence instead of using recursion
3412*/
3413
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415compiler_comprehension_generator(struct compiler *c,
3416 asdl_seq *generators, int gen_index,
3417 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 /* generate code for the iterator, then each of the ifs,
3420 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 comprehension_ty gen;
3423 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003424 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 start = compiler_new_block(c);
3427 skip = compiler_new_block(c);
3428 if_cleanup = compiler_new_block(c);
3429 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3432 anchor == NULL)
3433 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 if (gen_index == 0) {
3438 /* Receive outermost iter as an implicit argument */
3439 c->u->u_argcount = 1;
3440 ADDOP_I(c, LOAD_FAST, 0);
3441 }
3442 else {
3443 /* Sub-iter - calculate on the fly */
3444 VISIT(c, expr, gen->iter);
3445 ADDOP(c, GET_ITER);
3446 }
3447 compiler_use_next_block(c, start);
3448 ADDOP_JREL(c, FOR_ITER, anchor);
3449 NEXT_BLOCK(c);
3450 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 /* XXX this needs to be cleaned up...a lot! */
3453 n = asdl_seq_LEN(gen->ifs);
3454 for (i = 0; i < n; i++) {
3455 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3456 VISIT(c, expr, e);
3457 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3458 NEXT_BLOCK(c);
3459 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 if (++gen_index < asdl_seq_LEN(generators))
3462 if (!compiler_comprehension_generator(c,
3463 generators, gen_index,
3464 elt, val, type))
3465 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 /* only append after the last for generator */
3468 if (gen_index >= asdl_seq_LEN(generators)) {
3469 /* comprehension specific code */
3470 switch (type) {
3471 case COMP_GENEXP:
3472 VISIT(c, expr, elt);
3473 ADDOP(c, YIELD_VALUE);
3474 ADDOP(c, POP_TOP);
3475 break;
3476 case COMP_LISTCOMP:
3477 VISIT(c, expr, elt);
3478 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3479 break;
3480 case COMP_SETCOMP:
3481 VISIT(c, expr, elt);
3482 ADDOP_I(c, SET_ADD, gen_index + 1);
3483 break;
3484 case COMP_DICTCOMP:
3485 /* With 'd[k] = v', v is evaluated before k, so we do
3486 the same. */
3487 VISIT(c, expr, val);
3488 VISIT(c, expr, elt);
3489 ADDOP_I(c, MAP_ADD, gen_index + 1);
3490 break;
3491 default:
3492 return 0;
3493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 compiler_use_next_block(c, skip);
3496 }
3497 compiler_use_next_block(c, if_cleanup);
3498 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3499 compiler_use_next_block(c, anchor);
3500
3501 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502}
3503
3504static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003505compiler_comprehension(struct compiler *c, expr_ty e, int type,
3506 identifier name, asdl_seq *generators, expr_ty elt,
3507 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 PyCodeObject *co = NULL;
3510 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003511 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 outermost_iter = ((comprehension_ty)
3514 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003515
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003516 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3517 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 if (type != COMP_GENEXP) {
3521 int op;
3522 switch (type) {
3523 case COMP_LISTCOMP:
3524 op = BUILD_LIST;
3525 break;
3526 case COMP_SETCOMP:
3527 op = BUILD_SET;
3528 break;
3529 case COMP_DICTCOMP:
3530 op = BUILD_MAP;
3531 break;
3532 default:
3533 PyErr_Format(PyExc_SystemError,
3534 "unknown comprehension type %d", type);
3535 goto error_in_scope;
3536 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 ADDOP_I(c, op, 0);
3539 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 if (!compiler_comprehension_generator(c, generators, 0, elt,
3542 val, type))
3543 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 if (type != COMP_GENEXP) {
3546 ADDOP(c, RETURN_VALUE);
3547 }
3548
3549 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003550 qualname = c->u->u_qualname;
3551 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003553 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 goto error;
3555
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003556 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003558 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 Py_DECREF(co);
3560
3561 VISIT(c, expr, outermost_iter);
3562 ADDOP(c, GET_ITER);
3563 ADDOP_I(c, CALL_FUNCTION, 1);
3564 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003565error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003567error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003568 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 Py_XDECREF(co);
3570 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003571}
3572
3573static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574compiler_genexp(struct compiler *c, expr_ty e)
3575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 static identifier name;
3577 if (!name) {
3578 name = PyUnicode_FromString("<genexpr>");
3579 if (!name)
3580 return 0;
3581 }
3582 assert(e->kind == GeneratorExp_kind);
3583 return compiler_comprehension(c, e, COMP_GENEXP, name,
3584 e->v.GeneratorExp.generators,
3585 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586}
3587
3588static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003589compiler_listcomp(struct compiler *c, expr_ty e)
3590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 static identifier name;
3592 if (!name) {
3593 name = PyUnicode_FromString("<listcomp>");
3594 if (!name)
3595 return 0;
3596 }
3597 assert(e->kind == ListComp_kind);
3598 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3599 e->v.ListComp.generators,
3600 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003601}
3602
3603static int
3604compiler_setcomp(struct compiler *c, expr_ty e)
3605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 static identifier name;
3607 if (!name) {
3608 name = PyUnicode_FromString("<setcomp>");
3609 if (!name)
3610 return 0;
3611 }
3612 assert(e->kind == SetComp_kind);
3613 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3614 e->v.SetComp.generators,
3615 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003616}
3617
3618
3619static int
3620compiler_dictcomp(struct compiler *c, expr_ty e)
3621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 static identifier name;
3623 if (!name) {
3624 name = PyUnicode_FromString("<dictcomp>");
3625 if (!name)
3626 return 0;
3627 }
3628 assert(e->kind == DictComp_kind);
3629 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3630 e->v.DictComp.generators,
3631 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003632}
3633
3634
3635static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636compiler_visit_keyword(struct compiler *c, keyword_ty k)
3637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3639 VISIT(c, expr, k->value);
3640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641}
3642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 whether they are true or false.
3645
3646 Return values: 1 for true, 0 for false, -1 for non-constant.
3647 */
3648
3649static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003650expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 char *id;
3653 switch (e->kind) {
3654 case Ellipsis_kind:
3655 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003656 case Constant_kind:
3657 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 case Num_kind:
3659 return PyObject_IsTrue(e->v.Num.n);
3660 case Str_kind:
3661 return PyObject_IsTrue(e->v.Str.s);
3662 case Name_kind:
3663 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003664 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003665 if (id && strcmp(id, "__debug__") == 0)
3666 return !c->c_optimize;
3667 return -1;
3668 case NameConstant_kind: {
3669 PyObject *o = e->v.NameConstant.value;
3670 if (o == Py_None)
3671 return 0;
3672 else if (o == Py_True)
3673 return 1;
3674 else if (o == Py_False)
3675 return 0;
3676 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 default:
3678 return -1;
3679 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680}
3681
Yury Selivanov75445082015-05-11 22:57:16 -04003682
3683/*
3684 Implements the async with statement.
3685
3686 The semantics outlined in that PEP are as follows:
3687
3688 async with EXPR as VAR:
3689 BLOCK
3690
3691 It is implemented roughly as:
3692
3693 context = EXPR
3694 exit = context.__aexit__ # not calling it
3695 value = await context.__aenter__()
3696 try:
3697 VAR = value # if VAR present in the syntax
3698 BLOCK
3699 finally:
3700 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003701 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003702 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003703 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003704 if not (await exit(*exc)):
3705 raise
3706 */
3707static int
3708compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3709{
3710 basicblock *block, *finally;
3711 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3712
3713 assert(s->kind == AsyncWith_kind);
3714
3715 block = compiler_new_block(c);
3716 finally = compiler_new_block(c);
3717 if (!block || !finally)
3718 return 0;
3719
3720 /* Evaluate EXPR */
3721 VISIT(c, expr, item->context_expr);
3722
3723 ADDOP(c, BEFORE_ASYNC_WITH);
3724 ADDOP(c, GET_AWAITABLE);
3725 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3726 ADDOP(c, YIELD_FROM);
3727
3728 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3729
3730 /* SETUP_ASYNC_WITH pushes a finally block. */
3731 compiler_use_next_block(c, block);
3732 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3733 return 0;
3734 }
3735
3736 if (item->optional_vars) {
3737 VISIT(c, expr, item->optional_vars);
3738 }
3739 else {
3740 /* Discard result from context.__aenter__() */
3741 ADDOP(c, POP_TOP);
3742 }
3743
3744 pos++;
3745 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3746 /* BLOCK code */
3747 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3748 else if (!compiler_async_with(c, s, pos))
3749 return 0;
3750
3751 /* End of try block; start the finally block */
3752 ADDOP(c, POP_BLOCK);
3753 compiler_pop_fblock(c, FINALLY_TRY, block);
3754
3755 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3756 compiler_use_next_block(c, finally);
3757 if (!compiler_push_fblock(c, FINALLY_END, finally))
3758 return 0;
3759
3760 /* Finally block starts; context.__exit__ is on the stack under
3761 the exception or return information. Just issue our magic
3762 opcode. */
3763 ADDOP(c, WITH_CLEANUP_START);
3764
3765 ADDOP(c, GET_AWAITABLE);
3766 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3767 ADDOP(c, YIELD_FROM);
3768
3769 ADDOP(c, WITH_CLEANUP_FINISH);
3770
3771 /* Finally block ends. */
3772 ADDOP(c, END_FINALLY);
3773 compiler_pop_fblock(c, FINALLY_END, finally);
3774 return 1;
3775}
3776
3777
Guido van Rossumc2e20742006-02-27 22:32:47 +00003778/*
3779 Implements the with statement from PEP 343.
3780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003782
3783 with EXPR as VAR:
3784 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785
Guido van Rossumc2e20742006-02-27 22:32:47 +00003786 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787
Thomas Wouters477c8d52006-05-27 19:21:47 +00003788 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003789 exit = context.__exit__ # not calling it
3790 value = context.__enter__()
3791 try:
3792 VAR = value # if VAR present in the syntax
3793 BLOCK
3794 finally:
3795 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003796 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003797 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003798 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003799 exit(*exc)
3800 */
3801static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003802compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003803{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003804 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003805 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003806
3807 assert(s->kind == With_kind);
3808
Guido van Rossumc2e20742006-02-27 22:32:47 +00003809 block = compiler_new_block(c);
3810 finally = compiler_new_block(c);
3811 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003812 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003813
Thomas Wouters477c8d52006-05-27 19:21:47 +00003814 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003815 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003816 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003817
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003818 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003819 compiler_use_next_block(c, block);
3820 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003821 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003822 }
3823
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003824 if (item->optional_vars) {
3825 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003826 }
3827 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003829 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003830 }
3831
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003832 pos++;
3833 if (pos == asdl_seq_LEN(s->v.With.items))
3834 /* BLOCK code */
3835 VISIT_SEQ(c, stmt, s->v.With.body)
3836 else if (!compiler_with(c, s, pos))
3837 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003838
3839 /* End of try block; start the finally block */
3840 ADDOP(c, POP_BLOCK);
3841 compiler_pop_fblock(c, FINALLY_TRY, block);
3842
3843 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3844 compiler_use_next_block(c, finally);
3845 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003846 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003847
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003848 /* Finally block starts; context.__exit__ is on the stack under
3849 the exception or return information. Just issue our magic
3850 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003851 ADDOP(c, WITH_CLEANUP_START);
3852 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003853
3854 /* Finally block ends. */
3855 ADDOP(c, END_FINALLY);
3856 compiler_pop_fblock(c, FINALLY_END, finally);
3857 return 1;
3858}
3859
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860static int
3861compiler_visit_expr(struct compiler *c, expr_ty e)
3862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 /* If expr e has a different line number than the last expr/stmt,
3864 set a new line number for the next instruction.
3865 */
3866 if (e->lineno > c->u->u_lineno) {
3867 c->u->u_lineno = e->lineno;
3868 c->u->u_lineno_set = 0;
3869 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003870 /* Updating the column offset is always harmless. */
3871 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 switch (e->kind) {
3873 case BoolOp_kind:
3874 return compiler_boolop(c, e);
3875 case BinOp_kind:
3876 VISIT(c, expr, e->v.BinOp.left);
3877 VISIT(c, expr, e->v.BinOp.right);
3878 ADDOP(c, binop(c, e->v.BinOp.op));
3879 break;
3880 case UnaryOp_kind:
3881 VISIT(c, expr, e->v.UnaryOp.operand);
3882 ADDOP(c, unaryop(e->v.UnaryOp.op));
3883 break;
3884 case Lambda_kind:
3885 return compiler_lambda(c, e);
3886 case IfExp_kind:
3887 return compiler_ifexp(c, e);
3888 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003889 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003891 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 case GeneratorExp_kind:
3893 return compiler_genexp(c, e);
3894 case ListComp_kind:
3895 return compiler_listcomp(c, e);
3896 case SetComp_kind:
3897 return compiler_setcomp(c, e);
3898 case DictComp_kind:
3899 return compiler_dictcomp(c, e);
3900 case Yield_kind:
3901 if (c->u->u_ste->ste_type != FunctionBlock)
3902 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003903 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3904 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003905 if (e->v.Yield.value) {
3906 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 }
3908 else {
3909 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3910 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003911 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003913 case YieldFrom_kind:
3914 if (c->u->u_ste->ste_type != FunctionBlock)
3915 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003916
3917 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3918 return compiler_error(c, "'yield from' inside async function");
3919
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003920 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003921 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003922 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3923 ADDOP(c, YIELD_FROM);
3924 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003925 case Await_kind:
3926 if (c->u->u_ste->ste_type != FunctionBlock)
3927 return compiler_error(c, "'await' outside function");
3928
Yury Selivanov9dec0352015-06-30 12:49:04 -04003929 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3930 return compiler_error(
3931 c, "'await' expressions in comprehensions are not supported");
3932
Yury Selivanov75445082015-05-11 22:57:16 -04003933 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3934 return compiler_error(c, "'await' outside async function");
3935
3936 VISIT(c, expr, e->v.Await.value);
3937 ADDOP(c, GET_AWAITABLE);
3938 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3939 ADDOP(c, YIELD_FROM);
3940 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 case Compare_kind:
3942 return compiler_compare(c, e);
3943 case Call_kind:
3944 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003945 case Constant_kind:
3946 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
3947 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 case Num_kind:
3949 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3950 break;
3951 case Str_kind:
3952 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3953 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003954 case JoinedStr_kind:
3955 return compiler_joined_str(c, e);
3956 case FormattedValue_kind:
3957 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 case Bytes_kind:
3959 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3960 break;
3961 case Ellipsis_kind:
3962 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3963 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003964 case NameConstant_kind:
3965 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3966 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* The following exprs can be assignment targets. */
3968 case Attribute_kind:
3969 if (e->v.Attribute.ctx != AugStore)
3970 VISIT(c, expr, e->v.Attribute.value);
3971 switch (e->v.Attribute.ctx) {
3972 case AugLoad:
3973 ADDOP(c, DUP_TOP);
3974 /* Fall through to load */
3975 case Load:
3976 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3977 break;
3978 case AugStore:
3979 ADDOP(c, ROT_TWO);
3980 /* Fall through to save */
3981 case Store:
3982 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3983 break;
3984 case Del:
3985 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3986 break;
3987 case Param:
3988 default:
3989 PyErr_SetString(PyExc_SystemError,
3990 "param invalid in attribute expression");
3991 return 0;
3992 }
3993 break;
3994 case Subscript_kind:
3995 switch (e->v.Subscript.ctx) {
3996 case AugLoad:
3997 VISIT(c, expr, e->v.Subscript.value);
3998 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3999 break;
4000 case Load:
4001 VISIT(c, expr, e->v.Subscript.value);
4002 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4003 break;
4004 case AugStore:
4005 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4006 break;
4007 case Store:
4008 VISIT(c, expr, e->v.Subscript.value);
4009 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4010 break;
4011 case Del:
4012 VISIT(c, expr, e->v.Subscript.value);
4013 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4014 break;
4015 case Param:
4016 default:
4017 PyErr_SetString(PyExc_SystemError,
4018 "param invalid in subscript expression");
4019 return 0;
4020 }
4021 break;
4022 case Starred_kind:
4023 switch (e->v.Starred.ctx) {
4024 case Store:
4025 /* In all legitimate cases, the Starred node was already replaced
4026 * by compiler_list/compiler_tuple. XXX: is that okay? */
4027 return compiler_error(c,
4028 "starred assignment target must be in a list or tuple");
4029 default:
4030 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004031 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 }
4033 break;
4034 case Name_kind:
4035 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4036 /* child nodes of List and Tuple will have expr_context set */
4037 case List_kind:
4038 return compiler_list(c, e);
4039 case Tuple_kind:
4040 return compiler_tuple(c, e);
4041 }
4042 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004043}
4044
4045static int
4046compiler_augassign(struct compiler *c, stmt_ty s)
4047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 expr_ty e = s->v.AugAssign.target;
4049 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 switch (e->kind) {
4054 case Attribute_kind:
4055 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4056 AugLoad, e->lineno, e->col_offset, c->c_arena);
4057 if (auge == NULL)
4058 return 0;
4059 VISIT(c, expr, auge);
4060 VISIT(c, expr, s->v.AugAssign.value);
4061 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4062 auge->v.Attribute.ctx = AugStore;
4063 VISIT(c, expr, auge);
4064 break;
4065 case Subscript_kind:
4066 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4067 AugLoad, e->lineno, e->col_offset, c->c_arena);
4068 if (auge == NULL)
4069 return 0;
4070 VISIT(c, expr, auge);
4071 VISIT(c, expr, s->v.AugAssign.value);
4072 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4073 auge->v.Subscript.ctx = AugStore;
4074 VISIT(c, expr, auge);
4075 break;
4076 case Name_kind:
4077 if (!compiler_nameop(c, e->v.Name.id, Load))
4078 return 0;
4079 VISIT(c, expr, s->v.AugAssign.value);
4080 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4081 return compiler_nameop(c, e->v.Name.id, Store);
4082 default:
4083 PyErr_Format(PyExc_SystemError,
4084 "invalid node type (%d) for augmented assignment",
4085 e->kind);
4086 return 0;
4087 }
4088 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004089}
4090
4091static int
4092compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 struct fblockinfo *f;
4095 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4096 PyErr_SetString(PyExc_SystemError,
4097 "too many statically nested blocks");
4098 return 0;
4099 }
4100 f = &c->u->u_fblock[c->u->u_nfblocks++];
4101 f->fb_type = t;
4102 f->fb_block = b;
4103 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004104}
4105
4106static void
4107compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 struct compiler_unit *u = c->u;
4110 assert(u->u_nfblocks > 0);
4111 u->u_nfblocks--;
4112 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4113 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114}
4115
Thomas Wouters89f507f2006-12-13 04:49:30 +00004116static int
4117compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 int i;
4119 struct compiler_unit *u = c->u;
4120 for (i = 0; i < u->u_nfblocks; ++i) {
4121 if (u->u_fblock[i].fb_type == LOOP)
4122 return 1;
4123 }
4124 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004125}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126/* Raises a SyntaxError and returns 0.
4127 If something goes wrong, a different exception may be raised.
4128*/
4129
4130static int
4131compiler_error(struct compiler *c, const char *errstr)
4132{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004133 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004135
Victor Stinner14e461d2013-08-26 22:28:21 +02004136 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 if (!loc) {
4138 Py_INCREF(Py_None);
4139 loc = Py_None;
4140 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004141 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004142 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 if (!u)
4144 goto exit;
4145 v = Py_BuildValue("(zO)", errstr, u);
4146 if (!v)
4147 goto exit;
4148 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 Py_DECREF(loc);
4151 Py_XDECREF(u);
4152 Py_XDECREF(v);
4153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154}
4155
4156static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157compiler_handle_subscr(struct compiler *c, const char *kind,
4158 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 /* XXX this code is duplicated */
4163 switch (ctx) {
4164 case AugLoad: /* fall through to Load */
4165 case Load: op = BINARY_SUBSCR; break;
4166 case AugStore:/* fall through to Store */
4167 case Store: op = STORE_SUBSCR; break;
4168 case Del: op = DELETE_SUBSCR; break;
4169 case Param:
4170 PyErr_Format(PyExc_SystemError,
4171 "invalid %s kind %d in subscript\n",
4172 kind, ctx);
4173 return 0;
4174 }
4175 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004176 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 }
4178 else if (ctx == AugStore) {
4179 ADDOP(c, ROT_THREE);
4180 }
4181 ADDOP(c, op);
4182 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183}
4184
4185static int
4186compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 int n = 2;
4189 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 /* only handles the cases where BUILD_SLICE is emitted */
4192 if (s->v.Slice.lower) {
4193 VISIT(c, expr, s->v.Slice.lower);
4194 }
4195 else {
4196 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4197 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 if (s->v.Slice.upper) {
4200 VISIT(c, expr, s->v.Slice.upper);
4201 }
4202 else {
4203 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4204 }
4205
4206 if (s->v.Slice.step) {
4207 n++;
4208 VISIT(c, expr, s->v.Slice.step);
4209 }
4210 ADDOP_I(c, BUILD_SLICE, n);
4211 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212}
4213
4214static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4216 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 switch (s->kind) {
4219 case Slice_kind:
4220 return compiler_slice(c, s, ctx);
4221 case Index_kind:
4222 VISIT(c, expr, s->v.Index.value);
4223 break;
4224 case ExtSlice_kind:
4225 default:
4226 PyErr_SetString(PyExc_SystemError,
4227 "extended slice invalid in nested slice");
4228 return 0;
4229 }
4230 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004231}
4232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233static int
4234compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 char * kindname = NULL;
4237 switch (s->kind) {
4238 case Index_kind:
4239 kindname = "index";
4240 if (ctx != AugStore) {
4241 VISIT(c, expr, s->v.Index.value);
4242 }
4243 break;
4244 case Slice_kind:
4245 kindname = "slice";
4246 if (ctx != AugStore) {
4247 if (!compiler_slice(c, s, ctx))
4248 return 0;
4249 }
4250 break;
4251 case ExtSlice_kind:
4252 kindname = "extended slice";
4253 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004254 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 for (i = 0; i < n; i++) {
4256 slice_ty sub = (slice_ty)asdl_seq_GET(
4257 s->v.ExtSlice.dims, i);
4258 if (!compiler_visit_nested_slice(c, sub, ctx))
4259 return 0;
4260 }
4261 ADDOP_I(c, BUILD_TUPLE, n);
4262 }
4263 break;
4264 default:
4265 PyErr_Format(PyExc_SystemError,
4266 "invalid subscript kind %d", s->kind);
4267 return 0;
4268 }
4269 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004270}
4271
Thomas Wouters89f507f2006-12-13 04:49:30 +00004272/* End of the compiler section, beginning of the assembler section */
4273
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004274/* do depth-first search of basic block graph, starting with block.
4275 post records the block indices in post-order.
4276
4277 XXX must handle implicit jumps from one block to next
4278*/
4279
Thomas Wouters89f507f2006-12-13 04:49:30 +00004280struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 PyObject *a_bytecode; /* string containing bytecode */
4282 int a_offset; /* offset into bytecode */
4283 int a_nblocks; /* number of reachable blocks */
4284 basicblock **a_postorder; /* list of blocks in dfs postorder */
4285 PyObject *a_lnotab; /* string containing lnotab */
4286 int a_lnotab_off; /* offset into lnotab */
4287 int a_lineno; /* last lineno of emitted instruction */
4288 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004289};
4290
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291static void
4292dfs(struct compiler *c, basicblock *b, struct assembler *a)
4293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 int i;
4295 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 if (b->b_seen)
4298 return;
4299 b->b_seen = 1;
4300 if (b->b_next != NULL)
4301 dfs(c, b->b_next, a);
4302 for (i = 0; i < b->b_iused; i++) {
4303 instr = &b->b_instr[i];
4304 if (instr->i_jrel || instr->i_jabs)
4305 dfs(c, instr->i_target, a);
4306 }
4307 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308}
4309
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004310static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4312{
Larry Hastings3a907972013-11-23 14:49:22 -08004313 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 struct instr *instr;
4315 if (b->b_seen || b->b_startdepth >= depth)
4316 return maxdepth;
4317 b->b_seen = 1;
4318 b->b_startdepth = depth;
4319 for (i = 0; i < b->b_iused; i++) {
4320 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004321 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4322 if (effect == PY_INVALID_STACK_EFFECT) {
4323 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4324 Py_FatalError("PyCompile_OpcodeStackEffect()");
4325 }
4326 depth += effect;
4327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 if (depth > maxdepth)
4329 maxdepth = depth;
4330 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4331 if (instr->i_jrel || instr->i_jabs) {
4332 target_depth = depth;
4333 if (instr->i_opcode == FOR_ITER) {
4334 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004335 }
4336 else if (instr->i_opcode == SETUP_FINALLY ||
4337 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 target_depth = depth+3;
4339 if (target_depth > maxdepth)
4340 maxdepth = target_depth;
4341 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004342 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4343 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4344 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 maxdepth = stackdepth_walk(c, instr->i_target,
4346 target_depth, maxdepth);
4347 if (instr->i_opcode == JUMP_ABSOLUTE ||
4348 instr->i_opcode == JUMP_FORWARD) {
4349 goto out; /* remaining code is dead */
4350 }
4351 }
4352 }
4353 if (b->b_next)
4354 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004355out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 b->b_seen = 0;
4357 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004358}
4359
4360/* Find the flow path that needs the largest stack. We assume that
4361 * cycles in the flow graph have no net effect on the stack depth.
4362 */
4363static int
4364stackdepth(struct compiler *c)
4365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 basicblock *b, *entryblock;
4367 entryblock = NULL;
4368 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4369 b->b_seen = 0;
4370 b->b_startdepth = INT_MIN;
4371 entryblock = b;
4372 }
4373 if (!entryblock)
4374 return 0;
4375 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004376}
4377
4378static int
4379assemble_init(struct assembler *a, int nblocks, int firstlineno)
4380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 memset(a, 0, sizeof(struct assembler));
4382 a->a_lineno = firstlineno;
4383 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4384 if (!a->a_bytecode)
4385 return 0;
4386 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4387 if (!a->a_lnotab)
4388 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004389 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 PyErr_NoMemory();
4391 return 0;
4392 }
4393 a->a_postorder = (basicblock **)PyObject_Malloc(
4394 sizeof(basicblock *) * nblocks);
4395 if (!a->a_postorder) {
4396 PyErr_NoMemory();
4397 return 0;
4398 }
4399 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400}
4401
4402static void
4403assemble_free(struct assembler *a)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 Py_XDECREF(a->a_bytecode);
4406 Py_XDECREF(a->a_lnotab);
4407 if (a->a_postorder)
4408 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004409}
4410
4411/* Return the size of a basic block in bytes. */
4412
4413static int
4414instrsize(struct instr *instr)
4415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 if (!instr->i_hasarg)
4417 return 1; /* 1 byte for the opcode*/
4418 if (instr->i_oparg > 0xffff)
4419 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4420 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421}
4422
4423static int
4424blocksize(basicblock *b)
4425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 int i;
4427 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 for (i = 0; i < b->b_iused; i++)
4430 size += instrsize(&b->b_instr[i]);
4431 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004432}
4433
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004434/* Appends a pair to the end of the line number table, a_lnotab, representing
4435 the instruction's bytecode offset and line number. See
4436 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004437
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004438static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004439assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004442 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 d_bytecode = a->a_offset - a->a_lineno_off;
4446 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 if(d_bytecode == 0 && d_lineno == 0)
4451 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 if (d_bytecode > 255) {
4454 int j, nbytes, ncodes = d_bytecode / 255;
4455 nbytes = a->a_lnotab_off + 2 * ncodes;
4456 len = PyBytes_GET_SIZE(a->a_lnotab);
4457 if (nbytes >= len) {
4458 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4459 len = nbytes;
4460 else if (len <= INT_MAX / 2)
4461 len *= 2;
4462 else {
4463 PyErr_NoMemory();
4464 return 0;
4465 }
4466 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4467 return 0;
4468 }
4469 lnotab = (unsigned char *)
4470 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4471 for (j = 0; j < ncodes; j++) {
4472 *lnotab++ = 255;
4473 *lnotab++ = 0;
4474 }
4475 d_bytecode -= ncodes * 255;
4476 a->a_lnotab_off += ncodes * 2;
4477 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004478 assert(0 <= d_bytecode && d_bytecode <= 255);
4479
4480 if (d_lineno < -128 || 127 < d_lineno) {
4481 int j, nbytes, ncodes, k;
4482 if (d_lineno < 0) {
4483 k = -128;
4484 /* use division on positive numbers */
4485 ncodes = (-d_lineno) / 128;
4486 }
4487 else {
4488 k = 127;
4489 ncodes = d_lineno / 127;
4490 }
4491 d_lineno -= ncodes * k;
4492 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 nbytes = a->a_lnotab_off + 2 * ncodes;
4494 len = PyBytes_GET_SIZE(a->a_lnotab);
4495 if (nbytes >= len) {
4496 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4497 len = nbytes;
4498 else if (len <= INT_MAX / 2)
4499 len *= 2;
4500 else {
4501 PyErr_NoMemory();
4502 return 0;
4503 }
4504 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4505 return 0;
4506 }
4507 lnotab = (unsigned char *)
4508 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4509 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004510 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 d_bytecode = 0;
4512 for (j = 1; j < ncodes; j++) {
4513 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004514 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 a->a_lnotab_off += ncodes * 2;
4517 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004518 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 len = PyBytes_GET_SIZE(a->a_lnotab);
4521 if (a->a_lnotab_off + 2 >= len) {
4522 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4523 return 0;
4524 }
4525 lnotab = (unsigned char *)
4526 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 a->a_lnotab_off += 2;
4529 if (d_bytecode) {
4530 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004531 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 }
4533 else { /* First line of a block; def stmt, etc. */
4534 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004535 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 }
4537 a->a_lineno = i->i_lineno;
4538 a->a_lineno_off = a->a_offset;
4539 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004540}
4541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004542/* assemble_emit()
4543 Extend the bytecode with a new instruction.
4544 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004545*/
4546
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004547static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004548assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 int size, arg = 0, ext = 0;
4551 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4552 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 size = instrsize(i);
4555 if (i->i_hasarg) {
4556 arg = i->i_oparg;
4557 ext = arg >> 16;
4558 }
4559 if (i->i_lineno && !assemble_lnotab(a, i))
4560 return 0;
4561 if (a->a_offset + size >= len) {
4562 if (len > PY_SSIZE_T_MAX / 2)
4563 return 0;
4564 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4565 return 0;
4566 }
4567 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4568 a->a_offset += size;
4569 if (size == 6) {
4570 assert(i->i_hasarg);
4571 *code++ = (char)EXTENDED_ARG;
4572 *code++ = ext & 0xff;
4573 *code++ = ext >> 8;
4574 arg &= 0xffff;
4575 }
4576 *code++ = i->i_opcode;
4577 if (i->i_hasarg) {
4578 assert(size == 3 || size == 6);
4579 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004580 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 }
4582 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004583}
4584
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004585static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004586assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 basicblock *b;
4589 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4590 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 /* Compute the size of each block and fixup jump args.
4593 Replace block pointer with position in bytecode. */
4594 do {
4595 totsize = 0;
4596 for (i = a->a_nblocks - 1; i >= 0; i--) {
4597 b = a->a_postorder[i];
4598 bsize = blocksize(b);
4599 b->b_offset = totsize;
4600 totsize += bsize;
4601 }
4602 last_extended_arg_count = extended_arg_count;
4603 extended_arg_count = 0;
4604 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4605 bsize = b->b_offset;
4606 for (i = 0; i < b->b_iused; i++) {
4607 struct instr *instr = &b->b_instr[i];
4608 /* Relative jumps are computed relative to
4609 the instruction pointer after fetching
4610 the jump instruction.
4611 */
4612 bsize += instrsize(instr);
4613 if (instr->i_jabs)
4614 instr->i_oparg = instr->i_target->b_offset;
4615 else if (instr->i_jrel) {
4616 int delta = instr->i_target->b_offset - bsize;
4617 instr->i_oparg = delta;
4618 }
4619 else
4620 continue;
4621 if (instr->i_oparg > 0xffff)
4622 extended_arg_count++;
4623 }
4624 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 /* XXX: This is an awful hack that could hurt performance, but
4627 on the bright side it should work until we come up
4628 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 The issue is that in the first loop blocksize() is called
4631 which calls instrsize() which requires i_oparg be set
4632 appropriately. There is a bootstrap problem because
4633 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 So we loop until we stop seeing new EXTENDED_ARGs.
4636 The only EXTENDED_ARGs that could be popping up are
4637 ones in jump instructions. So this should converge
4638 fairly quickly.
4639 */
4640 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004641}
4642
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004643static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004644dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 PyObject *tuple, *k, *v;
4647 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 tuple = PyTuple_New(size);
4650 if (tuple == NULL)
4651 return NULL;
4652 while (PyDict_Next(dict, &pos, &k, &v)) {
4653 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004654 /* The keys of the dictionary are tuples. (see compiler_add_o
4655 * and _PyCode_ConstantKey). The object we want is always second,
4656 * though. */
4657 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 Py_INCREF(k);
4659 assert((i - offset) < size);
4660 assert((i - offset) >= 0);
4661 PyTuple_SET_ITEM(tuple, i - offset, k);
4662 }
4663 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004664}
4665
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004666static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004667compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004670 int flags = 0;
4671 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004673 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 if (ste->ste_nested)
4675 flags |= CO_NESTED;
4676 if (ste->ste_generator)
4677 flags |= CO_GENERATOR;
4678 if (ste->ste_varargs)
4679 flags |= CO_VARARGS;
4680 if (ste->ste_varkeywords)
4681 flags |= CO_VARKEYWORDS;
4682 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 /* (Only) inherit compilerflags in PyCF_MASK */
4685 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 n = PyDict_Size(c->u->u_freevars);
4688 if (n < 0)
4689 return -1;
4690 if (n == 0) {
4691 n = PyDict_Size(c->u->u_cellvars);
4692 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004693 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004695 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 }
4697 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004700}
4701
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004702static PyCodeObject *
4703makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 PyObject *tmp;
4706 PyCodeObject *co = NULL;
4707 PyObject *consts = NULL;
4708 PyObject *names = NULL;
4709 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 PyObject *name = NULL;
4711 PyObject *freevars = NULL;
4712 PyObject *cellvars = NULL;
4713 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004714 Py_ssize_t nlocals;
4715 int nlocals_int;
4716 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004717 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 tmp = dict_keys_inorder(c->u->u_consts, 0);
4720 if (!tmp)
4721 goto error;
4722 consts = PySequence_List(tmp); /* optimize_code requires a list */
4723 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 names = dict_keys_inorder(c->u->u_names, 0);
4726 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4727 if (!consts || !names || !varnames)
4728 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4731 if (!cellvars)
4732 goto error;
4733 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4734 if (!freevars)
4735 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004738 assert(nlocals < INT_MAX);
4739 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 flags = compute_code_flags(c);
4742 if (flags < 0)
4743 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4746 if (!bytecode)
4747 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4750 if (!tmp)
4751 goto error;
4752 Py_DECREF(consts);
4753 consts = tmp;
4754
Victor Stinnerf8e32212013-11-19 23:56:34 +01004755 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4756 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4757 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004758 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 bytecode, consts, names, varnames,
4760 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004761 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 c->u->u_firstlineno,
4763 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004764 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 Py_XDECREF(consts);
4766 Py_XDECREF(names);
4767 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 Py_XDECREF(name);
4769 Py_XDECREF(freevars);
4770 Py_XDECREF(cellvars);
4771 Py_XDECREF(bytecode);
4772 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004773}
4774
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004775
4776/* For debugging purposes only */
4777#if 0
4778static void
4779dump_instr(const struct instr *i)
4780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 const char *jrel = i->i_jrel ? "jrel " : "";
4782 const char *jabs = i->i_jabs ? "jabs " : "";
4783 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 *arg = '\0';
4786 if (i->i_hasarg)
4787 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4790 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004791}
4792
4793static void
4794dump_basicblock(const basicblock *b)
4795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 const char *seen = b->b_seen ? "seen " : "";
4797 const char *b_return = b->b_return ? "return " : "";
4798 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4799 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4800 if (b->b_instr) {
4801 int i;
4802 for (i = 0; i < b->b_iused; i++) {
4803 fprintf(stderr, " [%02d] ", i);
4804 dump_instr(b->b_instr + i);
4805 }
4806 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004807}
4808#endif
4809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004810static PyCodeObject *
4811assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 basicblock *b, *entryblock;
4814 struct assembler a;
4815 int i, j, nblocks;
4816 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 /* Make sure every block that falls off the end returns None.
4819 XXX NEXT_BLOCK() isn't quite right, because if the last
4820 block ends with a jump or return b_next shouldn't set.
4821 */
4822 if (!c->u->u_curblock->b_return) {
4823 NEXT_BLOCK(c);
4824 if (addNone)
4825 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4826 ADDOP(c, RETURN_VALUE);
4827 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 nblocks = 0;
4830 entryblock = NULL;
4831 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4832 nblocks++;
4833 entryblock = b;
4834 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 /* Set firstlineno if it wasn't explicitly set. */
4837 if (!c->u->u_firstlineno) {
4838 if (entryblock && entryblock->b_instr)
4839 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4840 else
4841 c->u->u_firstlineno = 1;
4842 }
4843 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4844 goto error;
4845 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 /* Can't modify the bytecode after computing jump offsets. */
4848 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 /* Emit code in reverse postorder from dfs. */
4851 for (i = a.a_nblocks - 1; i >= 0; i--) {
4852 b = a.a_postorder[i];
4853 for (j = 0; j < b->b_iused; j++)
4854 if (!assemble_emit(&a, &b->b_instr[j]))
4855 goto error;
4856 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4859 goto error;
4860 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4861 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004864 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 assemble_free(&a);
4866 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004867}
Georg Brandl8334fd92010-12-04 10:26:46 +00004868
4869#undef PyAST_Compile
4870PyAPI_FUNC(PyCodeObject *)
4871PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4872 PyArena *arena)
4873{
4874 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4875}