blob: 92fea3d13c0087582482f72569711ecde292e9de [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 int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
182static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184
185static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189/* Returns true if there is a loop on the fblock stack. */
190static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
192static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000193static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500195static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400196static int compiler_async_with(struct compiler *, stmt_ty, int);
197static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400200 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500201static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400202static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static PyCodeObject *assemble(struct compiler *, int addNone);
205static PyObject *__doc__;
206
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400207#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Name mangling: __private becomes _classname__private.
213 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyObject *result;
215 size_t nlen, plen, ipriv;
216 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200218 PyUnicode_READ_CHAR(ident, 0) != '_' ||
219 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_INCREF(ident);
221 return ident;
222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 nlen = PyUnicode_GET_LENGTH(ident);
224 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 The only time a name with a dot can occur is when
228 we are compiling an import statement that has a
229 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 TODO(jhylton): Decide whether we want to support
232 mangling of the module name, e.g. __M.X.
233 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
235 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
236 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident; /* Don't mangle __whatever__ */
239 }
240 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 ipriv = 0;
242 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
243 ipriv++;
244 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle if class is just underscores */
247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000249
Antoine Pitrou55bff892013-04-06 21:21:04 +0200250 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
251 PyErr_SetString(PyExc_OverflowError,
252 "private identifier too large to be mangled");
253 return NULL;
254 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
257 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
258 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
259
260 result = PyUnicode_New(1 + nlen + plen, maxchar);
261 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
264 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200265 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
266 Py_DECREF(result);
267 return NULL;
268 }
269 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
270 Py_DECREF(result);
271 return NULL;
272 }
Victor Stinner8f825062012-04-27 13:55:39 +0200273 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000275}
276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277static int
278compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 c->c_stack = PyList_New(0);
283 if (!c->c_stack)
284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287}
288
289PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200290PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
291 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 struct compiler c;
294 PyCodeObject *co = NULL;
295 PyCompilerFlags local_flags;
296 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (!__doc__) {
299 __doc__ = PyUnicode_InternFromString("__doc__");
300 if (!__doc__)
301 return NULL;
302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!compiler_init(&c))
305 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200306 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 c.c_filename = filename;
308 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200309 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (c.c_future == NULL)
311 goto finally;
312 if (!flags) {
313 local_flags.cf_flags = 0;
314 flags = &local_flags;
315 }
316 merged = c.c_future->ff_features | flags->cf_flags;
317 c.c_future->ff_features = merged;
318 flags->cf_flags = merged;
319 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000320 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Victor Stinner14e461d2013-08-26 22:28:21 +0200323 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (c.c_st == NULL) {
325 if (!PyErr_Occurred())
326 PyErr_SetString(PyExc_SystemError, "no symtable");
327 goto finally;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Thomas Wouters1175c432006-02-27 22:49:54 +0000332 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 compiler_free(&c);
334 assert(co || PyErr_Occurred());
335 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336}
337
338PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200339PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
340 int optimize, PyArena *arena)
341{
342 PyObject *filename;
343 PyCodeObject *co;
344 filename = PyUnicode_DecodeFSDefault(filename_str);
345 if (filename == NULL)
346 return NULL;
347 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
348 Py_DECREF(filename);
349 return co;
350
351}
352
353PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354PyNode_Compile(struct _node *n, const char *filename)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyCodeObject *co = NULL;
357 mod_ty mod;
358 PyArena *arena = PyArena_New();
359 if (!arena)
360 return NULL;
361 mod = PyAST_FromNode(n, NULL, filename, arena);
362 if (mod)
363 co = PyAST_Compile(mod, filename, NULL, arena);
364 PyArena_Free(arena);
365 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000366}
367
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c->c_st)
372 PySymtable_Free(c->c_st);
373 if (c->c_future)
374 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000377}
378
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ssize_t i, n;
383 PyObject *v, *k;
384 PyObject *dict = PyDict_New();
385 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 n = PyList_Size(list);
388 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100389 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!v) {
391 Py_DECREF(dict);
392 return NULL;
393 }
394 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100395 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
397 Py_XDECREF(k);
398 Py_DECREF(v);
399 Py_DECREF(dict);
400 return NULL;
401 }
402 Py_DECREF(k);
403 Py_DECREF(v);
404 }
405 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408/* Return new dict containing names from src that match scope(s).
409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412values are integers, starting at offset and increasing by one for
413each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414*/
415
416static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100417dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700419 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500421 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(offset >= 0);
424 if (dest == NULL)
425 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426
Meador Inge2ca63152012-07-18 14:20:11 -0500427 /* Sort the keys so that we have a deterministic order on the indexes
428 saved in the returned dictionary. These indexes are used as indexes
429 into the free and cell var storage. Therefore if they aren't
430 deterministic, then the generated bytecode is not deterministic.
431 */
432 sorted_keys = PyDict_Keys(src);
433 if (sorted_keys == NULL)
434 return NULL;
435 if (PyList_Sort(sorted_keys) != 0) {
436 Py_DECREF(sorted_keys);
437 return NULL;
438 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500439 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500440
441 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* XXX this should probably be a macro in symtable.h */
443 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500444 k = PyList_GET_ITEM(sorted_keys, key_i);
445 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(PyLong_Check(v));
447 vi = PyLong_AS_LONG(v);
448 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100451 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500453 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 Py_DECREF(dest);
455 return NULL;
456 }
457 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100458 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500460 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_DECREF(item);
462 Py_DECREF(dest);
463 Py_XDECREF(tuple);
464 return NULL;
465 }
466 Py_DECREF(item);
467 Py_DECREF(tuple);
468 }
469 }
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000472}
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474static void
475compiler_unit_check(struct compiler_unit *u)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 basicblock *block;
478 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinner976bb402016-03-23 11:36:19 +0100479 assert((Py_uintptr_t)block != 0xcbcbcbcbU);
480 assert((Py_uintptr_t)block != 0xfbfbfbfbU);
481 assert((Py_uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (block->b_instr != NULL) {
483 assert(block->b_ialloc > 0);
484 assert(block->b_iused > 0);
485 assert(block->b_ialloc >= block->b_iused);
486 }
487 else {
488 assert (block->b_iused == 0);
489 assert (block->b_ialloc == 0);
490 }
491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492}
493
494static void
495compiler_unit_free(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 compiler_unit_check(u);
500 b = u->u_blocks;
501 while (b != NULL) {
502 if (b->b_instr)
503 PyObject_Free((void *)b->b_instr);
504 next = b->b_list;
505 PyObject_Free((void *)b);
506 b = next;
507 }
508 Py_CLEAR(u->u_ste);
509 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400510 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(u->u_consts);
512 Py_CLEAR(u->u_names);
513 Py_CLEAR(u->u_varnames);
514 Py_CLEAR(u->u_freevars);
515 Py_CLEAR(u->u_cellvars);
516 Py_CLEAR(u->u_private);
517 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100521compiler_enter_scope(struct compiler *c, identifier name,
522 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100525 basicblock *block;
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++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100623
624 block = compiler_new_block(c);
625 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400629 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
630 if (!compiler_set_qualname(c))
631 return 0;
632 }
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635}
636
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000637static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638compiler_exit_scope(struct compiler *c)
639{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100640 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 c->c_nestlevel--;
644 compiler_unit_free(c->u);
645 /* Restore c->u to the parent unit. */
646 n = PyList_GET_SIZE(c->c_stack) - 1;
647 if (n >= 0) {
648 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400649 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 assert(c->u);
651 /* we are deleting from a list so this really shouldn't fail */
652 if (PySequence_DelItem(c->c_stack, n) < 0)
653 Py_FatalError("compiler_exit_scope()");
654 compiler_unit_check(c->u);
655 }
656 else
657 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659}
660
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400661static int
662compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100663{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665 _Py_static_string(dot_locals, ".<locals>");
666 Py_ssize_t stack_size;
667 struct compiler_unit *u = c->u;
668 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400672 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 if (stack_size > 1) {
674 int scope, force_global = 0;
675 struct compiler_unit *parent;
676 PyObject *mangled, *capsule;
677
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400678 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400679 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 assert(parent);
681
Yury Selivanov75445082015-05-11 22:57:16 -0400682 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
683 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
684 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(u->u_name);
686 mangled = _Py_Mangle(parent->u_private, u->u_name);
687 if (!mangled)
688 return 0;
689 scope = PyST_GetScope(parent->u_ste, mangled);
690 Py_DECREF(mangled);
691 assert(scope != GLOBAL_IMPLICIT);
692 if (scope == GLOBAL_EXPLICIT)
693 force_global = 1;
694 }
695
696 if (!force_global) {
697 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400698 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
700 dot_locals_str = _PyUnicode_FromId(&dot_locals);
701 if (dot_locals_str == NULL)
702 return 0;
703 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
704 if (base == NULL)
705 return 0;
706 }
707 else {
708 Py_INCREF(parent->u_qualname);
709 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400710 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100711 }
712 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400714 if (base != NULL) {
715 dot_str = _PyUnicode_FromId(&dot);
716 if (dot_str == NULL) {
717 Py_DECREF(base);
718 return 0;
719 }
720 name = PyUnicode_Concat(base, dot_str);
721 Py_DECREF(base);
722 if (name == NULL)
723 return 0;
724 PyUnicode_Append(&name, u->u_name);
725 if (name == NULL)
726 return 0;
727 }
728 else {
729 Py_INCREF(u->u_name);
730 name = u->u_name;
731 }
732 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100733
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100735}
736
Eric V. Smith235a6f02015-09-19 14:51:32 -0400737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000738/* Allocate a new block and return a pointer to it.
739 Returns NULL on error.
740*/
741
742static basicblock *
743compiler_new_block(struct compiler *c)
744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 basicblock *b;
746 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 u = c->u;
749 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
750 if (b == NULL) {
751 PyErr_NoMemory();
752 return NULL;
753 }
754 memset((void *)b, 0, sizeof(basicblock));
755 /* Extend the singly linked list of blocks with new block. */
756 b->b_list = u->u_blocks;
757 u->u_blocks = b;
758 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759}
760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762compiler_next_block(struct compiler *c)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 basicblock *block = compiler_new_block(c);
765 if (block == NULL)
766 return NULL;
767 c->u->u_curblock->b_next = block;
768 c->u->u_curblock = block;
769 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
771
772static basicblock *
773compiler_use_next_block(struct compiler *c, basicblock *block)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 assert(block != NULL);
776 c->u->u_curblock->b_next = block;
777 c->u->u_curblock = block;
778 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779}
780
781/* Returns the offset of the next instruction in the current block's
782 b_instr array. Resizes the b_instr as necessary.
783 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000784*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785
786static int
787compiler_next_instr(struct compiler *c, basicblock *b)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 assert(b != NULL);
790 if (b->b_instr == NULL) {
791 b->b_instr = (struct instr *)PyObject_Malloc(
792 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
793 if (b->b_instr == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 b->b_ialloc = DEFAULT_BLOCK_SIZE;
798 memset((char *)b->b_instr, 0,
799 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
800 }
801 else if (b->b_iused == b->b_ialloc) {
802 struct instr *tmp;
803 size_t oldsize, newsize;
804 oldsize = b->b_ialloc * sizeof(struct instr);
805 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (oldsize > (PY_SIZE_MAX >> 1)) {
808 PyErr_NoMemory();
809 return -1;
810 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (newsize == 0) {
813 PyErr_NoMemory();
814 return -1;
815 }
816 b->b_ialloc <<= 1;
817 tmp = (struct instr *)PyObject_Realloc(
818 (void *)b->b_instr, newsize);
819 if (tmp == NULL) {
820 PyErr_NoMemory();
821 return -1;
822 }
823 b->b_instr = tmp;
824 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
825 }
826 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827}
828
Christian Heimes2202f872008-02-06 14:31:34 +0000829/* Set the i_lineno member of the instruction at offset off if the
830 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831 already been set. If it has been set, the call has no effect.
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833 The line number is reset in the following cases:
834 - when entering a new scope
835 - on each statement
836 - on each expression that start a new line
837 - before the "except" clause
838 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841static void
842compiler_set_lineno(struct compiler *c, int off)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 basicblock *b;
845 if (c->u->u_lineno_set)
846 return;
847 c->u->u_lineno_set = 1;
848 b = c->u->u_curblock;
849 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850}
851
Larry Hastings3a907972013-11-23 14:49:22 -0800852int
853PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 switch (opcode) {
856 case POP_TOP:
857 return -1;
858 case ROT_TWO:
859 case ROT_THREE:
860 return 0;
861 case DUP_TOP:
862 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000863 case DUP_TOP_TWO:
864 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 case UNARY_POSITIVE:
867 case UNARY_NEGATIVE:
868 case UNARY_NOT:
869 case UNARY_INVERT:
870 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case SET_ADD:
873 case LIST_APPEND:
874 return -1;
875 case MAP_ADD:
876 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case BINARY_POWER:
879 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400880 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 case BINARY_MODULO:
882 case BINARY_ADD:
883 case BINARY_SUBTRACT:
884 case BINARY_SUBSCR:
885 case BINARY_FLOOR_DIVIDE:
886 case BINARY_TRUE_DIVIDE:
887 return -1;
888 case INPLACE_FLOOR_DIVIDE:
889 case INPLACE_TRUE_DIVIDE:
890 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case INPLACE_ADD:
893 case INPLACE_SUBTRACT:
894 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400895 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_MODULO:
897 return -1;
898 case STORE_SUBSCR:
899 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case DELETE_SUBSCR:
901 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case BINARY_LSHIFT:
904 case BINARY_RSHIFT:
905 case BINARY_AND:
906 case BINARY_XOR:
907 case BINARY_OR:
908 return -1;
909 case INPLACE_POWER:
910 return -1;
911 case GET_ITER:
912 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case PRINT_EXPR:
915 return -1;
916 case LOAD_BUILD_CLASS:
917 return 1;
918 case INPLACE_LSHIFT:
919 case INPLACE_RSHIFT:
920 case INPLACE_AND:
921 case INPLACE_XOR:
922 case INPLACE_OR:
923 return -1;
924 case BREAK_LOOP:
925 return 0;
926 case SETUP_WITH:
927 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400928 case WITH_CLEANUP_START:
929 return 1;
930 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case RETURN_VALUE:
933 return -1;
934 case IMPORT_STAR:
935 return -1;
936 case YIELD_VALUE:
937 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500938 case YIELD_FROM:
939 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case POP_BLOCK:
941 return 0;
942 case POP_EXCEPT:
943 return 0; /* -3 except if bad bytecode */
944 case END_FINALLY:
945 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case STORE_NAME:
948 return -1;
949 case DELETE_NAME:
950 return 0;
951 case UNPACK_SEQUENCE:
952 return oparg-1;
953 case UNPACK_EX:
954 return (oparg&0xFF) + (oparg>>8);
955 case FOR_ITER:
956 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case STORE_ATTR:
959 return -2;
960 case DELETE_ATTR:
961 return -1;
962 case STORE_GLOBAL:
963 return -1;
964 case DELETE_GLOBAL:
965 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case LOAD_CONST:
967 return 1;
968 case LOAD_NAME:
969 return 1;
970 case BUILD_TUPLE:
971 case BUILD_LIST:
972 case BUILD_SET:
973 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400974 case BUILD_LIST_UNPACK:
975 case BUILD_TUPLE_UNPACK:
976 case BUILD_SET_UNPACK:
977 case BUILD_MAP_UNPACK:
978 return 1 - oparg;
979 case BUILD_MAP_UNPACK_WITH_CALL:
980 return 1 - (oparg & 0xFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700982 return 1 - 2*oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case LOAD_ATTR:
984 return 0;
985 case COMPARE_OP:
986 return -1;
987 case IMPORT_NAME:
988 return -1;
989 case IMPORT_FROM:
990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case JUMP_FORWARD:
993 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
994 case JUMP_IF_FALSE_OR_POP: /* "" */
995 case JUMP_ABSOLUTE:
996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case POP_JUMP_IF_FALSE:
999 case POP_JUMP_IF_TRUE:
1000 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case LOAD_GLOBAL:
1003 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case CONTINUE_LOOP:
1006 return 0;
1007 case SETUP_LOOP:
1008 return 0;
1009 case SETUP_EXCEPT:
1010 case SETUP_FINALLY:
1011 return 6; /* can push 3 values for the new exception
1012 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case LOAD_FAST:
1015 return 1;
1016 case STORE_FAST:
1017 return -1;
1018 case DELETE_FAST:
1019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case RAISE_VARARGS:
1022 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001023#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case CALL_FUNCTION:
1025 return -NARGS(oparg);
1026 case CALL_FUNCTION_VAR:
1027 case CALL_FUNCTION_KW:
1028 return -NARGS(oparg)-1;
1029 case CALL_FUNCTION_VAR_KW:
1030 return -NARGS(oparg)-2;
1031 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001032 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001034 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001035#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case BUILD_SLICE:
1037 if (oparg == 3)
1038 return -2;
1039 else
1040 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case LOAD_CLOSURE:
1043 return 1;
1044 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001045 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return 1;
1047 case STORE_DEREF:
1048 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001049 case DELETE_DEREF:
1050 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001051 case GET_AWAITABLE:
1052 return 0;
1053 case SETUP_ASYNC_WITH:
1054 return 6;
1055 case BEFORE_ASYNC_WITH:
1056 return 1;
1057 case GET_AITER:
1058 return 0;
1059 case GET_ANEXT:
1060 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001061 case GET_YIELD_FROM_ITER:
1062 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001063 case FORMAT_VALUE:
1064 /* If there's a fmt_spec on the stack, we go from 2->1,
1065 else 1->1. */
1066 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001068 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 }
Larry Hastings3a907972013-11-23 14:49:22 -08001070 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073/* Add an opcode with no argument.
1074 Returns 0 on failure, 1 on success.
1075*/
1076
1077static int
1078compiler_addop(struct compiler *c, int opcode)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 basicblock *b;
1081 struct instr *i;
1082 int off;
1083 off = compiler_next_instr(c, c->u->u_curblock);
1084 if (off < 0)
1085 return 0;
1086 b = c->u->u_curblock;
1087 i = &b->b_instr[off];
1088 i->i_opcode = opcode;
1089 i->i_hasarg = 0;
1090 if (opcode == RETURN_VALUE)
1091 b->b_return = 1;
1092 compiler_set_lineno(c, off);
1093 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001094}
1095
Victor Stinnerf8e32212013-11-19 23:56:34 +01001096static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *t, *v;
1100 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001101
Victor Stinnerefb24132016-01-22 12:33:12 +01001102 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (t == NULL)
1104 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 v = PyDict_GetItem(dict, t);
1107 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001108 if (PyErr_Occurred()) {
1109 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001113 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (!v) {
1115 Py_DECREF(t);
1116 return -1;
1117 }
1118 if (PyDict_SetItem(dict, t, v) < 0) {
1119 Py_DECREF(t);
1120 Py_DECREF(v);
1121 return -1;
1122 }
1123 Py_DECREF(v);
1124 }
1125 else
1126 arg = PyLong_AsLong(v);
1127 Py_DECREF(t);
1128 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129}
1130
1131static int
1132compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001135 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001137 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 return compiler_addop_i(c, opcode, arg);
1139}
1140
1141static int
1142compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001145 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1147 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001148 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149 arg = compiler_add_o(c, dict, mangled);
1150 Py_DECREF(mangled);
1151 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001152 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 return compiler_addop_i(c, opcode, arg);
1154}
1155
1156/* Add an opcode with an integer argument.
1157 Returns 0 on failure, 1 on success.
1158*/
1159
1160static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001161compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 struct instr *i;
1164 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001165
Victor Stinner2ad474b2016-03-01 23:34:47 +01001166 /* oparg value is unsigned, but a signed C int is usually used to store
1167 it in the C code (like Python/ceval.c).
1168
1169 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1170
1171 The argument of a concrete bytecode instruction is limited to 16-bit.
1172 EXTENDED_ARG is used for 32-bit arguments. */
1173 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 off = compiler_next_instr(c, c->u->u_curblock);
1176 if (off < 0)
1177 return 0;
1178 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001179 i->i_opcode = opcode;
1180 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 i->i_hasarg = 1;
1182 compiler_set_lineno(c, off);
1183 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184}
1185
1186static int
1187compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 struct instr *i;
1190 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 assert(b != NULL);
1193 off = compiler_next_instr(c, c->u->u_curblock);
1194 if (off < 0)
1195 return 0;
1196 i = &c->u->u_curblock->b_instr[off];
1197 i->i_opcode = opcode;
1198 i->i_target = b;
1199 i->i_hasarg = 1;
1200 if (absolute)
1201 i->i_jabs = 1;
1202 else
1203 i->i_jrel = 1;
1204 compiler_set_lineno(c, off);
1205 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206}
1207
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001208/* NEXT_BLOCK() creates an implicit jump from the current block
1209 to the new block.
1210
1211 The returns inside this macro make it impossible to decref objects
1212 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (compiler_next_block((C)) == NULL) \
1216 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217}
1218
1219#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (!compiler_addop((C), (OP))) \
1221 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222}
1223
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001224#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (!compiler_addop((C), (OP))) { \
1226 compiler_exit_scope(c); \
1227 return 0; \
1228 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001229}
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
1236#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1238 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239}
1240
1241#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (!compiler_addop_i((C), (OP), (O))) \
1243 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244}
1245
1246#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (!compiler_addop_j((C), (OP), (O), 1)) \
1248 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (!compiler_addop_j((C), (OP), (O), 0)) \
1253 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254}
1255
1256/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1257 the ASDL name to synthesize the name of the C type and the visit function.
1258*/
1259
1260#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (!compiler_visit_ ## TYPE((C), (V))) \
1262 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001265#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (!compiler_visit_ ## TYPE((C), (V))) { \
1267 compiler_exit_scope(c); \
1268 return 0; \
1269 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001270}
1271
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_visit_slice((C), (V), (CTX))) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
1277#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 int _i; \
1279 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1280 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1281 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1282 if (!compiler_visit_ ## TYPE((C), elt)) \
1283 return 0; \
1284 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285}
1286
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001287#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 int _i; \
1289 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1290 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1291 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1292 if (!compiler_visit_ ## TYPE((C), elt)) { \
1293 compiler_exit_scope(c); \
1294 return 0; \
1295 } \
1296 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001297}
1298
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299static int
1300compiler_isdocstring(stmt_ty s)
1301{
1302 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001303 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001304 if (s->v.Expr.value->kind == Str_kind)
1305 return 1;
1306 if (s->v.Expr.value->kind == Constant_kind)
1307 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1308 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
1311/* Compile a sequence of statements, checking for a docstring. */
1312
1313static int
1314compiler_body(struct compiler *c, asdl_seq *stmts)
1315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 int i = 0;
1317 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!asdl_seq_LEN(stmts))
1320 return 1;
1321 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001322 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* don't generate docstrings if -OO */
1324 i = 1;
1325 VISIT(c, expr, st->v.Expr.value);
1326 if (!compiler_nameop(c, __doc__, Store))
1327 return 0;
1328 }
1329 for (; i < asdl_seq_LEN(stmts); i++)
1330 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1331 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332}
1333
1334static PyCodeObject *
1335compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyCodeObject *co;
1338 int addNone = 1;
1339 static PyObject *module;
1340 if (!module) {
1341 module = PyUnicode_InternFromString("<module>");
1342 if (!module)
1343 return NULL;
1344 }
1345 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001346 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 return NULL;
1348 switch (mod->kind) {
1349 case Module_kind:
1350 if (!compiler_body(c, mod->v.Module.body)) {
1351 compiler_exit_scope(c);
1352 return 0;
1353 }
1354 break;
1355 case Interactive_kind:
1356 c->c_interactive = 1;
1357 VISIT_SEQ_IN_SCOPE(c, stmt,
1358 mod->v.Interactive.body);
1359 break;
1360 case Expression_kind:
1361 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1362 addNone = 0;
1363 break;
1364 case Suite_kind:
1365 PyErr_SetString(PyExc_SystemError,
1366 "suite should not be possible");
1367 return 0;
1368 default:
1369 PyErr_Format(PyExc_SystemError,
1370 "module kind %d should not be possible",
1371 mod->kind);
1372 return 0;
1373 }
1374 co = assemble(c, addNone);
1375 compiler_exit_scope(c);
1376 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001377}
1378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379/* The test for LOCAL must come before the test for FREE in order to
1380 handle classes where name is both local and free. The local var is
1381 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001382*/
1383
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384static int
1385get_ref_type(struct compiler *c, PyObject *name)
1386{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001387 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001388 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1389 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1390 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001391 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (scope == 0) {
1393 char buf[350];
1394 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001395 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001397 PyUnicode_AsUTF8(name),
1398 PyUnicode_AsUTF8(c->u->u_name),
1399 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1400 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1401 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1402 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 );
1404 Py_FatalError(buf);
1405 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408}
1409
1410static int
1411compiler_lookup_arg(PyObject *dict, PyObject *name)
1412{
1413 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001414 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001416 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001418 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001420 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001421 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422}
1423
1424static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001425compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001427 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001428 if (qualname == NULL)
1429 qualname = co->co_name;
1430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (free == 0) {
1432 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001433 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 ADDOP_I(c, MAKE_FUNCTION, args);
1435 return 1;
1436 }
1437 for (i = 0; i < free; ++i) {
1438 /* Bypass com_addop_varname because it will generate
1439 LOAD_DEREF but LOAD_CLOSURE is needed.
1440 */
1441 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1442 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 /* Special case: If a class contains a method with a
1445 free variable that has the same name as a method,
1446 the name will be considered free *and* local in the
1447 class. It should be handled by the closure, as
1448 well as by the normal name loookup logic.
1449 */
1450 reftype = get_ref_type(c, name);
1451 if (reftype == CELL)
1452 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1453 else /* (reftype == FREE) */
1454 arg = compiler_lookup_arg(c->u->u_freevars, name);
1455 if (arg == -1) {
1456 fprintf(stderr,
1457 "lookup %s in %s %d %d\n"
1458 "freevars of %s: %s\n",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001459 PyUnicode_AsUTF8(PyObject_Repr(name)),
1460 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 reftype, arg,
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001462 PyUnicode_AsUTF8(co->co_name),
1463 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 Py_FatalError("compiler_make_closure()");
1465 }
1466 ADDOP_I(c, LOAD_CLOSURE, arg);
1467 }
1468 ADDOP_I(c, BUILD_TUPLE, free);
1469 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001470 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 ADDOP_I(c, MAKE_CLOSURE, args);
1472 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473}
1474
1475static int
1476compiler_decorators(struct compiler *c, asdl_seq* decos)
1477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (!decos)
1481 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1484 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1485 }
1486 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
1489static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001490compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 int i, default_count = 0;
1494 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1495 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1496 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1497 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001498 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1499 if (!mangled)
1500 return -1;
1501 ADDOP_O(c, LOAD_CONST, mangled, consts);
1502 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (!compiler_visit_expr(c, default_)) {
1504 return -1;
1505 }
1506 default_count++;
1507 }
1508 }
1509 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001510}
1511
1512static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001513compiler_visit_argannotation(struct compiler *c, identifier id,
1514 expr_ty annotation, PyObject *names)
1515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001517 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001519 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001520 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001521 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001522 if (PyList_Append(names, mangled) < 0) {
1523 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001524 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001525 }
1526 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001528 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001529}
1530
1531static int
1532compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1533 PyObject *names)
1534{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001535 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 for (i = 0; i < asdl_seq_LEN(args); i++) {
1537 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001538 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 c,
1540 arg->arg,
1541 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001542 names))
1543 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001545 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001546}
1547
1548static int
1549compiler_visit_annotations(struct compiler *c, arguments_ty args,
1550 expr_ty returns)
1551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* Push arg annotations and a list of the argument names. Return the #
1553 of items pushed. The expressions are evaluated out-of-order wrt the
1554 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1557 */
1558 static identifier return_str;
1559 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001560 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 names = PyList_New(0);
1562 if (!names)
1563 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001564
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001565 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001567 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001568 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001569 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001571 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001573 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001574 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001575 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (!return_str) {
1579 return_str = PyUnicode_InternFromString("return");
1580 if (!return_str)
1581 goto error;
1582 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001583 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 goto error;
1585 }
1586
1587 len = PyList_GET_SIZE(names);
1588 if (len > 65534) {
1589 /* len must fit in 16 bits, and len is incremented below */
1590 PyErr_SetString(PyExc_SyntaxError,
1591 "too many annotations");
1592 goto error;
1593 }
1594 if (len) {
1595 /* convert names to a tuple and place on stack */
1596 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001597 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 PyObject *s = PyTuple_New(len);
1599 if (!s)
1600 goto error;
1601 for (i = 0; i < len; i++) {
1602 elt = PyList_GET_ITEM(names, i);
1603 Py_INCREF(elt);
1604 PyTuple_SET_ITEM(s, i, elt);
1605 }
1606 ADDOP_O(c, LOAD_CONST, s, consts);
1607 Py_DECREF(s);
1608 len++; /* include the just-pushed tuple */
1609 }
1610 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001611
1612 /* We just checked that len <= 65535, see above */
1613 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001614
1615error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 Py_DECREF(names);
1617 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001618}
1619
1620static int
Yury Selivanov75445082015-05-11 22:57:16 -04001621compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001624 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001625 arguments_ty args;
1626 expr_ty returns;
1627 identifier name;
1628 asdl_seq* decos;
1629 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001631 Py_ssize_t i, n, arglength;
1632 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 int num_annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001634 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635
Yury Selivanov75445082015-05-11 22:57:16 -04001636
1637 if (is_async) {
1638 assert(s->kind == AsyncFunctionDef_kind);
1639
1640 args = s->v.AsyncFunctionDef.args;
1641 returns = s->v.AsyncFunctionDef.returns;
1642 decos = s->v.AsyncFunctionDef.decorator_list;
1643 name = s->v.AsyncFunctionDef.name;
1644 body = s->v.AsyncFunctionDef.body;
1645
1646 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1647 } else {
1648 assert(s->kind == FunctionDef_kind);
1649
1650 args = s->v.FunctionDef.args;
1651 returns = s->v.FunctionDef.returns;
1652 decos = s->v.FunctionDef.decorator_list;
1653 name = s->v.FunctionDef.name;
1654 body = s->v.FunctionDef.body;
1655
1656 scope_type = COMPILER_SCOPE_FUNCTION;
1657 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (!compiler_decorators(c, decos))
1660 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001661 if (args->defaults)
1662 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (args->kwonlyargs) {
1664 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1665 args->kw_defaults);
1666 if (res < 0)
1667 return 0;
1668 kw_default_count = res;
1669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 num_annotations = compiler_visit_annotations(c, args, returns);
1671 if (num_annotations < 0)
1672 return 0;
1673 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001674
Yury Selivanov75445082015-05-11 22:57:16 -04001675 if (!compiler_enter_scope(c, name,
1676 scope_type, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 s->lineno))
1678 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679
Yury Selivanov75445082015-05-11 22:57:16 -04001680 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001682 if (docstring && c->c_optimize < 2) {
1683 if (st->v.Expr.value->kind == Constant_kind)
1684 first_const = st->v.Expr.value->v.Constant.value;
1685 else
1686 first_const = st->v.Expr.value->v.Str.s;
1687 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1689 compiler_exit_scope(c);
1690 return 0;
1691 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 c->u->u_argcount = asdl_seq_LEN(args->args);
1694 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001695 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* if there was a docstring, we need to skip the first statement */
1697 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001698 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 VISIT_IN_SCOPE(c, stmt, st);
1700 }
1701 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001702 qualname = c->u->u_qualname;
1703 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001705 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001706 Py_XDECREF(qualname);
1707 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001709 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 arglength = asdl_seq_LEN(args->defaults);
1712 arglength |= kw_default_count << 8;
1713 arglength |= num_annotations << 16;
Yury Selivanovb7666a32015-07-22 14:48:57 +03001714 if (is_async)
1715 co->co_flags |= CO_COROUTINE;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001716 compiler_make_closure(c, co, arglength, qualname);
1717 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 /* decorators */
1721 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1722 ADDOP_I(c, CALL_FUNCTION, 1);
1723 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724
Yury Selivanov75445082015-05-11 22:57:16 -04001725 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726}
1727
1728static int
1729compiler_class(struct compiler *c, stmt_ty s)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyCodeObject *co;
1732 PyObject *str;
1733 int i;
1734 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (!compiler_decorators(c, decos))
1737 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* ultimately generate code for:
1740 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1741 where:
1742 <func> is a function/closure created from the class body;
1743 it has a single argument (__locals__) where the dict
1744 (or MutableSequence) representing the locals is passed
1745 <name> is the class name
1746 <bases> is the positional arguments and *varargs argument
1747 <keywords> is the keyword arguments and **kwds argument
1748 This borrows from compiler_call.
1749 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001752 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1753 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 return 0;
1755 /* this block represents what we do in the new scope */
1756 {
1757 /* use the class name for name mangling */
1758 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001759 Py_SETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 /* load (global) __name__ ... */
1761 str = PyUnicode_InternFromString("__name__");
1762 if (!str || !compiler_nameop(c, str, Load)) {
1763 Py_XDECREF(str);
1764 compiler_exit_scope(c);
1765 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 Py_DECREF(str);
1768 /* ... and store it as __module__ */
1769 str = PyUnicode_InternFromString("__module__");
1770 if (!str || !compiler_nameop(c, str, Store)) {
1771 Py_XDECREF(str);
1772 compiler_exit_scope(c);
1773 return 0;
1774 }
1775 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001776 assert(c->u->u_qualname);
1777 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001778 str = PyUnicode_InternFromString("__qualname__");
1779 if (!str || !compiler_nameop(c, str, Store)) {
1780 Py_XDECREF(str);
1781 compiler_exit_scope(c);
1782 return 0;
1783 }
1784 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* compile the body proper */
1786 if (!compiler_body(c, s->v.ClassDef.body)) {
1787 compiler_exit_scope(c);
1788 return 0;
1789 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001790 if (c->u->u_ste->ste_needs_class_closure) {
1791 /* return the (empty) __class__ cell */
1792 str = PyUnicode_InternFromString("__class__");
1793 if (str == NULL) {
1794 compiler_exit_scope(c);
1795 return 0;
1796 }
1797 i = compiler_lookup_arg(c->u->u_cellvars, str);
1798 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001799 if (i < 0) {
1800 compiler_exit_scope(c);
1801 return 0;
1802 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001803 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Return the cell where to store __class__ */
1805 ADDOP_I(c, LOAD_CLOSURE, i);
1806 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001807 else {
1808 assert(PyDict_Size(c->u->u_cellvars) == 0);
1809 /* This happens when nobody references the cell. Return None. */
1810 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1813 /* create the code object */
1814 co = assemble(c, 1);
1815 }
1816 /* leave the new scope */
1817 compiler_exit_scope(c);
1818 if (co == NULL)
1819 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 /* 2. load the 'build_class' function */
1822 ADDOP(c, LOAD_BUILD_CLASS);
1823
1824 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001825 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 Py_DECREF(co);
1827
1828 /* 4. load class name */
1829 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1830
1831 /* 5. generate the rest of the code for the call */
1832 if (!compiler_call_helper(c, 2,
1833 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001834 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return 0;
1836
1837 /* 6. apply decorators */
1838 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1839 ADDOP_I(c, CALL_FUNCTION, 1);
1840 }
1841
1842 /* 7. store into <name> */
1843 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1844 return 0;
1845 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846}
1847
1848static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001849compiler_ifexp(struct compiler *c, expr_ty e)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 basicblock *end, *next;
1852
1853 assert(e->kind == IfExp_kind);
1854 end = compiler_new_block(c);
1855 if (end == NULL)
1856 return 0;
1857 next = compiler_new_block(c);
1858 if (next == NULL)
1859 return 0;
1860 VISIT(c, expr, e->v.IfExp.test);
1861 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1862 VISIT(c, expr, e->v.IfExp.body);
1863 ADDOP_JREL(c, JUMP_FORWARD, end);
1864 compiler_use_next_block(c, next);
1865 VISIT(c, expr, e->v.IfExp.orelse);
1866 compiler_use_next_block(c, end);
1867 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001868}
1869
1870static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871compiler_lambda(struct compiler *c, expr_ty e)
1872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001874 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001876 int kw_default_count = 0;
1877 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 arguments_ty args = e->v.Lambda.args;
1879 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (!name) {
1882 name = PyUnicode_InternFromString("<lambda>");
1883 if (!name)
1884 return 0;
1885 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001887 if (args->defaults)
1888 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (args->kwonlyargs) {
1890 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1891 args->kw_defaults);
1892 if (res < 0) return 0;
1893 kw_default_count = res;
1894 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001895 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001896 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Make None the first constant, so the lambda can't have a
1900 docstring. */
1901 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 c->u->u_argcount = asdl_seq_LEN(args->args);
1905 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1906 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1907 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001908 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
1910 else {
1911 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02001912 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001914 qualname = c->u->u_qualname;
1915 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001917 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 arglength = asdl_seq_LEN(args->defaults);
1921 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001922 compiler_make_closure(c, co, arglength, qualname);
1923 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 Py_DECREF(co);
1925
1926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927}
1928
1929static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930compiler_if(struct compiler *c, stmt_ty s)
1931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 basicblock *end, *next;
1933 int constant;
1934 assert(s->kind == If_kind);
1935 end = compiler_new_block(c);
1936 if (end == NULL)
1937 return 0;
1938
Georg Brandl8334fd92010-12-04 10:26:46 +00001939 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* constant = 0: "if 0"
1941 * constant = 1: "if 1", "if 2", ...
1942 * constant = -1: rest */
1943 if (constant == 0) {
1944 if (s->v.If.orelse)
1945 VISIT_SEQ(c, stmt, s->v.If.orelse);
1946 } else if (constant == 1) {
1947 VISIT_SEQ(c, stmt, s->v.If.body);
1948 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001949 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 next = compiler_new_block(c);
1951 if (next == NULL)
1952 return 0;
1953 }
1954 else
1955 next = end;
1956 VISIT(c, expr, s->v.If.test);
1957 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1958 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02001959 if (asdl_seq_LEN(s->v.If.orelse)) {
1960 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 compiler_use_next_block(c, next);
1962 VISIT_SEQ(c, stmt, s->v.If.orelse);
1963 }
1964 }
1965 compiler_use_next_block(c, end);
1966 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967}
1968
1969static int
1970compiler_for(struct compiler *c, stmt_ty s)
1971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 start = compiler_new_block(c);
1975 cleanup = compiler_new_block(c);
1976 end = compiler_new_block(c);
1977 if (start == NULL || end == NULL || cleanup == NULL)
1978 return 0;
1979 ADDOP_JREL(c, SETUP_LOOP, end);
1980 if (!compiler_push_fblock(c, LOOP, start))
1981 return 0;
1982 VISIT(c, expr, s->v.For.iter);
1983 ADDOP(c, GET_ITER);
1984 compiler_use_next_block(c, start);
1985 ADDOP_JREL(c, FOR_ITER, cleanup);
1986 VISIT(c, expr, s->v.For.target);
1987 VISIT_SEQ(c, stmt, s->v.For.body);
1988 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1989 compiler_use_next_block(c, cleanup);
1990 ADDOP(c, POP_BLOCK);
1991 compiler_pop_fblock(c, LOOP, start);
1992 VISIT_SEQ(c, stmt, s->v.For.orelse);
1993 compiler_use_next_block(c, end);
1994 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995}
1996
Yury Selivanov75445082015-05-11 22:57:16 -04001997
1998static int
1999compiler_async_for(struct compiler *c, stmt_ty s)
2000{
2001 static PyObject *stopiter_error = NULL;
2002 basicblock *try, *except, *end, *after_try, *try_cleanup,
2003 *after_loop, *after_loop_else;
2004
2005 if (stopiter_error == NULL) {
2006 stopiter_error = PyUnicode_InternFromString("StopAsyncIteration");
2007 if (stopiter_error == NULL)
2008 return 0;
2009 }
2010
2011 try = compiler_new_block(c);
2012 except = compiler_new_block(c);
2013 end = compiler_new_block(c);
2014 after_try = compiler_new_block(c);
2015 try_cleanup = compiler_new_block(c);
2016 after_loop = compiler_new_block(c);
2017 after_loop_else = compiler_new_block(c);
2018
2019 if (try == NULL || except == NULL || end == NULL
2020 || after_try == NULL || try_cleanup == NULL)
2021 return 0;
2022
2023 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2024 if (!compiler_push_fblock(c, LOOP, try))
2025 return 0;
2026
2027 VISIT(c, expr, s->v.AsyncFor.iter);
2028 ADDOP(c, GET_AITER);
2029 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2030 ADDOP(c, YIELD_FROM);
2031
2032 compiler_use_next_block(c, try);
2033
2034
2035 ADDOP_JREL(c, SETUP_EXCEPT, except);
2036 if (!compiler_push_fblock(c, EXCEPT, try))
2037 return 0;
2038
2039 ADDOP(c, GET_ANEXT);
2040 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2041 ADDOP(c, YIELD_FROM);
2042 VISIT(c, expr, s->v.AsyncFor.target);
2043 ADDOP(c, POP_BLOCK);
2044 compiler_pop_fblock(c, EXCEPT, try);
2045 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2046
2047
2048 compiler_use_next_block(c, except);
2049 ADDOP(c, DUP_TOP);
2050 ADDOP_O(c, LOAD_GLOBAL, stopiter_error, names);
2051 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2052 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2053
2054 ADDOP(c, POP_TOP);
2055 ADDOP(c, POP_TOP);
2056 ADDOP(c, POP_TOP);
2057 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2058 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2059 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2060
2061
2062 compiler_use_next_block(c, try_cleanup);
2063 ADDOP(c, END_FINALLY);
2064
2065 compiler_use_next_block(c, after_try);
2066 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2067 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2068
2069 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2070 compiler_pop_fblock(c, LOOP, try);
2071
2072 compiler_use_next_block(c, after_loop);
2073 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2074
2075 compiler_use_next_block(c, after_loop_else);
2076 VISIT_SEQ(c, stmt, s->v.For.orelse);
2077
2078 compiler_use_next_block(c, end);
2079
2080 return 1;
2081}
2082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083static int
2084compiler_while(struct compiler *c, stmt_ty s)
2085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002087 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (constant == 0) {
2090 if (s->v.While.orelse)
2091 VISIT_SEQ(c, stmt, s->v.While.orelse);
2092 return 1;
2093 }
2094 loop = compiler_new_block(c);
2095 end = compiler_new_block(c);
2096 if (constant == -1) {
2097 anchor = compiler_new_block(c);
2098 if (anchor == NULL)
2099 return 0;
2100 }
2101 if (loop == NULL || end == NULL)
2102 return 0;
2103 if (s->v.While.orelse) {
2104 orelse = compiler_new_block(c);
2105 if (orelse == NULL)
2106 return 0;
2107 }
2108 else
2109 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 ADDOP_JREL(c, SETUP_LOOP, end);
2112 compiler_use_next_block(c, loop);
2113 if (!compiler_push_fblock(c, LOOP, loop))
2114 return 0;
2115 if (constant == -1) {
2116 VISIT(c, expr, s->v.While.test);
2117 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2118 }
2119 VISIT_SEQ(c, stmt, s->v.While.body);
2120 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 /* XXX should the two POP instructions be in a separate block
2123 if there is no else clause ?
2124 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002126 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002128 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 compiler_pop_fblock(c, LOOP, loop);
2130 if (orelse != NULL) /* what if orelse is just pass? */
2131 VISIT_SEQ(c, stmt, s->v.While.orelse);
2132 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135}
2136
2137static int
2138compiler_continue(struct compiler *c)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2141 static const char IN_FINALLY_ERROR_MSG[] =
2142 "'continue' not supported inside 'finally' clause";
2143 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (!c->u->u_nfblocks)
2146 return compiler_error(c, LOOP_ERROR_MSG);
2147 i = c->u->u_nfblocks - 1;
2148 switch (c->u->u_fblock[i].fb_type) {
2149 case LOOP:
2150 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2151 break;
2152 case EXCEPT:
2153 case FINALLY_TRY:
2154 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2155 /* Prevent continue anywhere under a finally
2156 even if hidden in a sub-try or except. */
2157 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2158 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2159 }
2160 if (i == -1)
2161 return compiler_error(c, LOOP_ERROR_MSG);
2162 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2163 break;
2164 case FINALLY_END:
2165 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169}
2170
2171/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172
2173 SETUP_FINALLY L
2174 <code for body>
2175 POP_BLOCK
2176 LOAD_CONST <None>
2177 L: <code for finalbody>
2178 END_FINALLY
2179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 The special instructions use the block stack. Each block
2181 stack entry contains the instruction that created it (here
2182 SETUP_FINALLY), the level of the value stack at the time the
2183 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 Pushes the current value stack level and the label
2187 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 Pops en entry from the block stack, and pops the value
2190 stack until its level is the same as indicated on the
2191 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 Pops a variable number of entries from the *value* stack
2194 and re-raises the exception they specify. The number of
2195 entries popped depends on the (pseudo) exception type.
2196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 The block stack is unwound when an exception is raised:
2198 when a SETUP_FINALLY entry is found, the exception is pushed
2199 onto the value stack (and the exception condition is cleared),
2200 and the interpreter jumps to the label gotten from the block
2201 stack.
2202*/
2203
2204static int
2205compiler_try_finally(struct compiler *c, stmt_ty s)
2206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 basicblock *body, *end;
2208 body = compiler_new_block(c);
2209 end = compiler_new_block(c);
2210 if (body == NULL || end == NULL)
2211 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 ADDOP_JREL(c, SETUP_FINALLY, end);
2214 compiler_use_next_block(c, body);
2215 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2216 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002217 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2218 if (!compiler_try_except(c, s))
2219 return 0;
2220 }
2221 else {
2222 VISIT_SEQ(c, stmt, s->v.Try.body);
2223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 ADDOP(c, POP_BLOCK);
2225 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2228 compiler_use_next_block(c, end);
2229 if (!compiler_push_fblock(c, FINALLY_END, end))
2230 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002231 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 ADDOP(c, END_FINALLY);
2233 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236}
2237
2238/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002239 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 (The contents of the value stack is shown in [], with the top
2241 at the right; 'tb' is trace-back info, 'val' the exception's
2242 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243
2244 Value stack Label Instruction Argument
2245 [] SETUP_EXCEPT L1
2246 [] <code for S>
2247 [] POP_BLOCK
2248 [] JUMP_FORWARD L0
2249
2250 [tb, val, exc] L1: DUP )
2251 [tb, val, exc, exc] <evaluate E1> )
2252 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2253 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2254 [tb, val, exc] POP
2255 [tb, val] <assign to V1> (or POP if no V1)
2256 [tb] POP
2257 [] <code for S1>
2258 JUMP_FORWARD L0
2259
2260 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 .............................etc.......................
2262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2264
2265 [] L0: <next statement>
2266
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 Of course, parts are not generated if Vi or Ei is not present.
2268*/
2269static int
2270compiler_try_except(struct compiler *c, stmt_ty s)
2271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002273 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 body = compiler_new_block(c);
2276 except = compiler_new_block(c);
2277 orelse = compiler_new_block(c);
2278 end = compiler_new_block(c);
2279 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2280 return 0;
2281 ADDOP_JREL(c, SETUP_EXCEPT, except);
2282 compiler_use_next_block(c, body);
2283 if (!compiler_push_fblock(c, EXCEPT, body))
2284 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002285 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 ADDOP(c, POP_BLOCK);
2287 compiler_pop_fblock(c, EXCEPT, body);
2288 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002289 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_use_next_block(c, except);
2291 for (i = 0; i < n; i++) {
2292 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002293 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (!handler->v.ExceptHandler.type && i < n-1)
2295 return compiler_error(c, "default 'except:' must be last");
2296 c->u->u_lineno_set = 0;
2297 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002298 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 except = compiler_new_block(c);
2300 if (except == NULL)
2301 return 0;
2302 if (handler->v.ExceptHandler.type) {
2303 ADDOP(c, DUP_TOP);
2304 VISIT(c, expr, handler->v.ExceptHandler.type);
2305 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2306 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2307 }
2308 ADDOP(c, POP_TOP);
2309 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002310 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002311
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002312 cleanup_end = compiler_new_block(c);
2313 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002314 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002315 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002316
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002317 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2318 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002320 /*
2321 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002322 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002323 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002324 try:
2325 # body
2326 finally:
2327 name = None
2328 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002329 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002331 /* second try: */
2332 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2333 compiler_use_next_block(c, cleanup_body);
2334 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2335 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002337 /* second # body */
2338 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2339 ADDOP(c, POP_BLOCK);
2340 ADDOP(c, POP_EXCEPT);
2341 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002343 /* finally: */
2344 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2345 compiler_use_next_block(c, cleanup_end);
2346 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2347 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002349 /* name = None */
2350 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2351 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002353 /* del name */
2354 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002356 ADDOP(c, END_FINALLY);
2357 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 }
2359 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002360 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002362 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002363 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002364 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365
Guido van Rossumb940e112007-01-10 16:19:56 +00002366 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002367 ADDOP(c, POP_TOP);
2368 compiler_use_next_block(c, cleanup_body);
2369 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2370 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002372 ADDOP(c, POP_EXCEPT);
2373 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 }
2375 ADDOP_JREL(c, JUMP_FORWARD, end);
2376 compiler_use_next_block(c, except);
2377 }
2378 ADDOP(c, END_FINALLY);
2379 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002380 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 compiler_use_next_block(c, end);
2382 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383}
2384
2385static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002386compiler_try(struct compiler *c, stmt_ty s) {
2387 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2388 return compiler_try_finally(c, s);
2389 else
2390 return compiler_try_except(c, s);
2391}
2392
2393
2394static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395compiler_import_as(struct compiler *c, identifier name, identifier asname)
2396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* The IMPORT_NAME opcode was already generated. This function
2398 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 If there is a dot in name, we need to split it and emit a
2401 LOAD_ATTR for each name.
2402 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2404 PyUnicode_GET_LENGTH(name), 1);
2405 if (dot == -2)
2406 return -1;
2407 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002409 Py_ssize_t pos = dot + 1;
2410 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 dot = PyUnicode_FindChar(name, '.', pos,
2413 PyUnicode_GET_LENGTH(name), 1);
2414 if (dot == -2)
2415 return -1;
2416 attr = PyUnicode_Substring(name, pos,
2417 (dot != -1) ? dot :
2418 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (!attr)
2420 return -1;
2421 ADDOP_O(c, LOAD_ATTR, attr, names);
2422 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002423 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 }
2425 }
2426 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427}
2428
2429static int
2430compiler_import(struct compiler *c, stmt_ty s)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 /* The Import node stores a module name like a.b.c as a single
2433 string. This is convenient for all cases except
2434 import a.b.c as d
2435 where we need to parse that string to extract the individual
2436 module names.
2437 XXX Perhaps change the representation to make this case simpler?
2438 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002439 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 for (i = 0; i < n; i++) {
2442 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2443 int r;
2444 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 level = PyLong_FromLong(0);
2447 if (level == NULL)
2448 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 ADDOP_O(c, LOAD_CONST, level, consts);
2451 Py_DECREF(level);
2452 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2453 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (alias->asname) {
2456 r = compiler_import_as(c, alias->name, alias->asname);
2457 if (!r)
2458 return r;
2459 }
2460 else {
2461 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 Py_ssize_t dot = PyUnicode_FindChar(
2463 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002464 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002465 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002466 if (tmp == NULL)
2467 return 0;
2468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 Py_DECREF(tmp);
2472 }
2473 if (!r)
2474 return r;
2475 }
2476 }
2477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478}
2479
2480static int
2481compiler_from_import(struct compiler *c, stmt_ty s)
2482{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002483 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 PyObject *names = PyTuple_New(n);
2486 PyObject *level;
2487 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (!empty_string) {
2490 empty_string = PyUnicode_FromString("");
2491 if (!empty_string)
2492 return 0;
2493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (!names)
2496 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 level = PyLong_FromLong(s->v.ImportFrom.level);
2499 if (!level) {
2500 Py_DECREF(names);
2501 return 0;
2502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* build up the names */
2505 for (i = 0; i < n; i++) {
2506 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2507 Py_INCREF(alias->name);
2508 PyTuple_SET_ITEM(names, i, alias->name);
2509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2512 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2513 Py_DECREF(level);
2514 Py_DECREF(names);
2515 return compiler_error(c, "from __future__ imports must occur "
2516 "at the beginning of the file");
2517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 ADDOP_O(c, LOAD_CONST, level, consts);
2520 Py_DECREF(level);
2521 ADDOP_O(c, LOAD_CONST, names, consts);
2522 Py_DECREF(names);
2523 if (s->v.ImportFrom.module) {
2524 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2525 }
2526 else {
2527 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2528 }
2529 for (i = 0; i < n; i++) {
2530 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2531 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002533 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 assert(n == 1);
2535 ADDOP(c, IMPORT_STAR);
2536 return 1;
2537 }
2538
2539 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2540 store_name = alias->name;
2541 if (alias->asname)
2542 store_name = alias->asname;
2543
2544 if (!compiler_nameop(c, store_name, Store)) {
2545 Py_DECREF(names);
2546 return 0;
2547 }
2548 }
2549 /* remove imported module */
2550 ADDOP(c, POP_TOP);
2551 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552}
2553
2554static int
2555compiler_assert(struct compiler *c, stmt_ty s)
2556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 static PyObject *assertion_error = NULL;
2558 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002559 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560
Georg Brandl8334fd92010-12-04 10:26:46 +00002561 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return 1;
2563 if (assertion_error == NULL) {
2564 assertion_error = PyUnicode_InternFromString("AssertionError");
2565 if (assertion_error == NULL)
2566 return 0;
2567 }
2568 if (s->v.Assert.test->kind == Tuple_kind &&
2569 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002570 msg = PyUnicode_FromString("assertion is always true, "
2571 "perhaps remove parentheses?");
2572 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002574 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2575 c->c_filename, c->u->u_lineno,
2576 NULL, NULL) == -1) {
2577 Py_DECREF(msg);
2578 return 0;
2579 }
2580 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 }
2582 VISIT(c, expr, s->v.Assert.test);
2583 end = compiler_new_block(c);
2584 if (end == NULL)
2585 return 0;
2586 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2587 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2588 if (s->v.Assert.msg) {
2589 VISIT(c, expr, s->v.Assert.msg);
2590 ADDOP_I(c, CALL_FUNCTION, 1);
2591 }
2592 ADDOP_I(c, RAISE_VARARGS, 1);
2593 compiler_use_next_block(c, end);
2594 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595}
2596
2597static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002598compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2599{
2600 if (c->c_interactive && c->c_nestlevel <= 1) {
2601 VISIT(c, expr, value);
2602 ADDOP(c, PRINT_EXPR);
2603 return 1;
2604 }
2605
Victor Stinnera2724092016-02-08 18:17:58 +01002606 switch (value->kind)
2607 {
2608 case Str_kind:
Victor Stinnera2724092016-02-08 18:17:58 +01002609 case Num_kind:
Victor Stinner15a30952016-02-08 22:45:06 +01002610 case Ellipsis_kind:
2611 case Bytes_kind:
Victor Stinnera2724092016-02-08 18:17:58 +01002612 case NameConstant_kind:
2613 case Constant_kind:
Victor Stinner15a30952016-02-08 22:45:06 +01002614 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002615 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002616
Victor Stinnera2724092016-02-08 18:17:58 +01002617 default:
2618 break;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002619 }
2620
2621 VISIT(c, expr, value);
2622 ADDOP(c, POP_TOP);
2623 return 1;
2624}
2625
2626static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627compiler_visit_stmt(struct compiler *c, stmt_ty s)
2628{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002629 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 /* Always assign a lineno to the next instruction for a stmt. */
2632 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002633 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 switch (s->kind) {
2637 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002638 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 case ClassDef_kind:
2640 return compiler_class(c, s);
2641 case Return_kind:
2642 if (c->u->u_ste->ste_type != FunctionBlock)
2643 return compiler_error(c, "'return' outside function");
2644 if (s->v.Return.value) {
2645 VISIT(c, expr, s->v.Return.value);
2646 }
2647 else
2648 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2649 ADDOP(c, RETURN_VALUE);
2650 break;
2651 case Delete_kind:
2652 VISIT_SEQ(c, expr, s->v.Delete.targets)
2653 break;
2654 case Assign_kind:
2655 n = asdl_seq_LEN(s->v.Assign.targets);
2656 VISIT(c, expr, s->v.Assign.value);
2657 for (i = 0; i < n; i++) {
2658 if (i < n - 1)
2659 ADDOP(c, DUP_TOP);
2660 VISIT(c, expr,
2661 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2662 }
2663 break;
2664 case AugAssign_kind:
2665 return compiler_augassign(c, s);
2666 case For_kind:
2667 return compiler_for(c, s);
2668 case While_kind:
2669 return compiler_while(c, s);
2670 case If_kind:
2671 return compiler_if(c, s);
2672 case Raise_kind:
2673 n = 0;
2674 if (s->v.Raise.exc) {
2675 VISIT(c, expr, s->v.Raise.exc);
2676 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002677 if (s->v.Raise.cause) {
2678 VISIT(c, expr, s->v.Raise.cause);
2679 n++;
2680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002682 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002684 case Try_kind:
2685 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 case Assert_kind:
2687 return compiler_assert(c, s);
2688 case Import_kind:
2689 return compiler_import(c, s);
2690 case ImportFrom_kind:
2691 return compiler_from_import(c, s);
2692 case Global_kind:
2693 case Nonlocal_kind:
2694 break;
2695 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002696 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 case Pass_kind:
2698 break;
2699 case Break_kind:
2700 if (!compiler_in_loop(c))
2701 return compiler_error(c, "'break' outside loop");
2702 ADDOP(c, BREAK_LOOP);
2703 break;
2704 case Continue_kind:
2705 return compiler_continue(c);
2706 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002707 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002708 case AsyncFunctionDef_kind:
2709 return compiler_function(c, s, 1);
2710 case AsyncWith_kind:
2711 return compiler_async_with(c, s, 0);
2712 case AsyncFor_kind:
2713 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 }
Yury Selivanov75445082015-05-11 22:57:16 -04002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717}
2718
2719static int
2720unaryop(unaryop_ty op)
2721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 switch (op) {
2723 case Invert:
2724 return UNARY_INVERT;
2725 case Not:
2726 return UNARY_NOT;
2727 case UAdd:
2728 return UNARY_POSITIVE;
2729 case USub:
2730 return UNARY_NEGATIVE;
2731 default:
2732 PyErr_Format(PyExc_SystemError,
2733 "unary op %d should not be possible", op);
2734 return 0;
2735 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736}
2737
2738static int
2739binop(struct compiler *c, operator_ty op)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 switch (op) {
2742 case Add:
2743 return BINARY_ADD;
2744 case Sub:
2745 return BINARY_SUBTRACT;
2746 case Mult:
2747 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002748 case MatMult:
2749 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 case Div:
2751 return BINARY_TRUE_DIVIDE;
2752 case Mod:
2753 return BINARY_MODULO;
2754 case Pow:
2755 return BINARY_POWER;
2756 case LShift:
2757 return BINARY_LSHIFT;
2758 case RShift:
2759 return BINARY_RSHIFT;
2760 case BitOr:
2761 return BINARY_OR;
2762 case BitXor:
2763 return BINARY_XOR;
2764 case BitAnd:
2765 return BINARY_AND;
2766 case FloorDiv:
2767 return BINARY_FLOOR_DIVIDE;
2768 default:
2769 PyErr_Format(PyExc_SystemError,
2770 "binary op %d should not be possible", op);
2771 return 0;
2772 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773}
2774
2775static int
2776cmpop(cmpop_ty op)
2777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 switch (op) {
2779 case Eq:
2780 return PyCmp_EQ;
2781 case NotEq:
2782 return PyCmp_NE;
2783 case Lt:
2784 return PyCmp_LT;
2785 case LtE:
2786 return PyCmp_LE;
2787 case Gt:
2788 return PyCmp_GT;
2789 case GtE:
2790 return PyCmp_GE;
2791 case Is:
2792 return PyCmp_IS;
2793 case IsNot:
2794 return PyCmp_IS_NOT;
2795 case In:
2796 return PyCmp_IN;
2797 case NotIn:
2798 return PyCmp_NOT_IN;
2799 default:
2800 return PyCmp_BAD;
2801 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802}
2803
2804static int
2805inplace_binop(struct compiler *c, operator_ty op)
2806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 switch (op) {
2808 case Add:
2809 return INPLACE_ADD;
2810 case Sub:
2811 return INPLACE_SUBTRACT;
2812 case Mult:
2813 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002814 case MatMult:
2815 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 case Div:
2817 return INPLACE_TRUE_DIVIDE;
2818 case Mod:
2819 return INPLACE_MODULO;
2820 case Pow:
2821 return INPLACE_POWER;
2822 case LShift:
2823 return INPLACE_LSHIFT;
2824 case RShift:
2825 return INPLACE_RSHIFT;
2826 case BitOr:
2827 return INPLACE_OR;
2828 case BitXor:
2829 return INPLACE_XOR;
2830 case BitAnd:
2831 return INPLACE_AND;
2832 case FloorDiv:
2833 return INPLACE_FLOOR_DIVIDE;
2834 default:
2835 PyErr_Format(PyExc_SystemError,
2836 "inplace binary op %d should not be possible", op);
2837 return 0;
2838 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839}
2840
2841static int
2842compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2843{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002844 int op, scope;
2845 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 PyObject *dict = c->u->u_names;
2849 PyObject *mangled;
2850 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 mangled = _Py_Mangle(c->u->u_private, name);
2853 if (!mangled)
2854 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002855
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002856 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2857 PyUnicode_CompareWithASCIIString(name, "True") &&
2858 PyUnicode_CompareWithASCIIString(name, "False"));
2859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 op = 0;
2861 optype = OP_NAME;
2862 scope = PyST_GetScope(c->u->u_ste, mangled);
2863 switch (scope) {
2864 case FREE:
2865 dict = c->u->u_freevars;
2866 optype = OP_DEREF;
2867 break;
2868 case CELL:
2869 dict = c->u->u_cellvars;
2870 optype = OP_DEREF;
2871 break;
2872 case LOCAL:
2873 if (c->u->u_ste->ste_type == FunctionBlock)
2874 optype = OP_FAST;
2875 break;
2876 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04002877 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 optype = OP_GLOBAL;
2879 break;
2880 case GLOBAL_EXPLICIT:
2881 optype = OP_GLOBAL;
2882 break;
2883 default:
2884 /* scope can be 0 */
2885 break;
2886 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002889 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 switch (optype) {
2892 case OP_DEREF:
2893 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002894 case Load:
2895 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2896 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 case Store: op = STORE_DEREF; break;
2898 case AugLoad:
2899 case AugStore:
2900 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002901 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 case Param:
2903 default:
2904 PyErr_SetString(PyExc_SystemError,
2905 "param invalid for deref variable");
2906 return 0;
2907 }
2908 break;
2909 case OP_FAST:
2910 switch (ctx) {
2911 case Load: op = LOAD_FAST; break;
2912 case Store: op = STORE_FAST; break;
2913 case Del: op = DELETE_FAST; break;
2914 case AugLoad:
2915 case AugStore:
2916 break;
2917 case Param:
2918 default:
2919 PyErr_SetString(PyExc_SystemError,
2920 "param invalid for local variable");
2921 return 0;
2922 }
2923 ADDOP_O(c, op, mangled, varnames);
2924 Py_DECREF(mangled);
2925 return 1;
2926 case OP_GLOBAL:
2927 switch (ctx) {
2928 case Load: op = LOAD_GLOBAL; break;
2929 case Store: op = STORE_GLOBAL; break;
2930 case Del: op = DELETE_GLOBAL; break;
2931 case AugLoad:
2932 case AugStore:
2933 break;
2934 case Param:
2935 default:
2936 PyErr_SetString(PyExc_SystemError,
2937 "param invalid for global variable");
2938 return 0;
2939 }
2940 break;
2941 case OP_NAME:
2942 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002943 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 case Store: op = STORE_NAME; break;
2945 case Del: op = DELETE_NAME; break;
2946 case AugLoad:
2947 case AugStore:
2948 break;
2949 case Param:
2950 default:
2951 PyErr_SetString(PyExc_SystemError,
2952 "param invalid for name variable");
2953 return 0;
2954 }
2955 break;
2956 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 assert(op);
2959 arg = compiler_add_o(c, dict, mangled);
2960 Py_DECREF(mangled);
2961 if (arg < 0)
2962 return 0;
2963 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964}
2965
2966static int
2967compiler_boolop(struct compiler *c, expr_ty e)
2968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002970 int jumpi;
2971 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 assert(e->kind == BoolOp_kind);
2975 if (e->v.BoolOp.op == And)
2976 jumpi = JUMP_IF_FALSE_OR_POP;
2977 else
2978 jumpi = JUMP_IF_TRUE_OR_POP;
2979 end = compiler_new_block(c);
2980 if (end == NULL)
2981 return 0;
2982 s = e->v.BoolOp.values;
2983 n = asdl_seq_LEN(s) - 1;
2984 assert(n >= 0);
2985 for (i = 0; i < n; ++i) {
2986 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2987 ADDOP_JABS(c, jumpi, end);
2988 }
2989 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2990 compiler_use_next_block(c, end);
2991 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992}
2993
2994static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002995starunpack_helper(struct compiler *c, asdl_seq *elts,
2996 int single_op, int inner_op, int outer_op)
2997{
2998 Py_ssize_t n = asdl_seq_LEN(elts);
2999 Py_ssize_t i, nsubitems = 0, nseen = 0;
3000 for (i = 0; i < n; i++) {
3001 expr_ty elt = asdl_seq_GET(elts, i);
3002 if (elt->kind == Starred_kind) {
3003 if (nseen) {
3004 ADDOP_I(c, inner_op, nseen);
3005 nseen = 0;
3006 nsubitems++;
3007 }
3008 VISIT(c, expr, elt->v.Starred.value);
3009 nsubitems++;
3010 }
3011 else {
3012 VISIT(c, expr, elt);
3013 nseen++;
3014 }
3015 }
3016 if (nsubitems) {
3017 if (nseen) {
3018 ADDOP_I(c, inner_op, nseen);
3019 nsubitems++;
3020 }
3021 ADDOP_I(c, outer_op, nsubitems);
3022 }
3023 else
3024 ADDOP_I(c, single_op, nseen);
3025 return 1;
3026}
3027
3028static int
3029assignment_helper(struct compiler *c, asdl_seq *elts)
3030{
3031 Py_ssize_t n = asdl_seq_LEN(elts);
3032 Py_ssize_t i;
3033 int seen_star = 0;
3034 for (i = 0; i < n; i++) {
3035 expr_ty elt = asdl_seq_GET(elts, i);
3036 if (elt->kind == Starred_kind && !seen_star) {
3037 if ((i >= (1 << 8)) ||
3038 (n-i-1 >= (INT_MAX >> 8)))
3039 return compiler_error(c,
3040 "too many expressions in "
3041 "star-unpacking assignment");
3042 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3043 seen_star = 1;
3044 asdl_seq_SET(elts, i, elt->v.Starred.value);
3045 }
3046 else if (elt->kind == Starred_kind) {
3047 return compiler_error(c,
3048 "two starred expressions in assignment");
3049 }
3050 }
3051 if (!seen_star) {
3052 ADDOP_I(c, UNPACK_SEQUENCE, n);
3053 }
3054 VISIT_SEQ(c, expr, elts);
3055 return 1;
3056}
3057
3058static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059compiler_list(struct compiler *c, expr_ty e)
3060{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003061 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003063 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003065 else if (e->v.List.ctx == Load) {
3066 return starunpack_helper(c, elts,
3067 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003069 else
3070 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072}
3073
3074static int
3075compiler_tuple(struct compiler *c, expr_ty e)
3076{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003077 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003079 return assignment_helper(c, elts);
3080 }
3081 else if (e->v.Tuple.ctx == Load) {
3082 return starunpack_helper(c, elts,
3083 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3084 }
3085 else
3086 VISIT_SEQ(c, expr, elts);
3087 return 1;
3088}
3089
3090static int
3091compiler_set(struct compiler *c, expr_ty e)
3092{
3093 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3094 BUILD_SET, BUILD_SET_UNPACK);
3095}
3096
3097static int
3098compiler_dict(struct compiler *c, expr_ty e)
3099{
Victor Stinner976bb402016-03-23 11:36:19 +01003100 Py_ssize_t i, n, elements;
3101 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003102 int is_unpacking = 0;
3103 n = asdl_seq_LEN(e->v.Dict.values);
3104 containers = 0;
3105 elements = 0;
3106 for (i = 0; i < n; i++) {
3107 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3108 if (elements == 0xFFFF || (elements && is_unpacking)) {
3109 ADDOP_I(c, BUILD_MAP, elements);
3110 containers++;
3111 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003113 if (is_unpacking) {
3114 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3115 containers++;
3116 }
3117 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003118 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003119 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003120 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 }
3122 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003123 if (elements || containers == 0) {
3124 ADDOP_I(c, BUILD_MAP, elements);
3125 containers++;
3126 }
3127 /* If there is more than one dict, they need to be merged into a new
3128 * dict. If there is one dict and it's an unpacking, then it needs
3129 * to be copied into a new dict." */
3130 while (containers > 1 || is_unpacking) {
3131 int oparg = containers < 255 ? containers : 255;
3132 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3133 containers -= (oparg - 1);
3134 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 }
3136 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137}
3138
3139static int
3140compiler_compare(struct compiler *c, expr_ty e)
3141{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003142 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3146 VISIT(c, expr, e->v.Compare.left);
3147 n = asdl_seq_LEN(e->v.Compare.ops);
3148 assert(n > 0);
3149 if (n > 1) {
3150 cleanup = compiler_new_block(c);
3151 if (cleanup == NULL)
3152 return 0;
3153 VISIT(c, expr,
3154 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3155 }
3156 for (i = 1; i < n; i++) {
3157 ADDOP(c, DUP_TOP);
3158 ADDOP(c, ROT_THREE);
3159 ADDOP_I(c, COMPARE_OP,
3160 cmpop((cmpop_ty)(asdl_seq_GET(
3161 e->v.Compare.ops, i - 1))));
3162 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3163 NEXT_BLOCK(c);
3164 if (i < (n - 1))
3165 VISIT(c, expr,
3166 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3167 }
3168 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3169 ADDOP_I(c, COMPARE_OP,
3170 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3171 if (n > 1) {
3172 basicblock *end = compiler_new_block(c);
3173 if (end == NULL)
3174 return 0;
3175 ADDOP_JREL(c, JUMP_FORWARD, end);
3176 compiler_use_next_block(c, cleanup);
3177 ADDOP(c, ROT_TWO);
3178 ADDOP(c, POP_TOP);
3179 compiler_use_next_block(c, end);
3180 }
3181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182}
3183
3184static int
3185compiler_call(struct compiler *c, expr_ty e)
3186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 VISIT(c, expr, e->v.Call.func);
3188 return compiler_call_helper(c, 0,
3189 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003190 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003191}
3192
Eric V. Smith235a6f02015-09-19 14:51:32 -04003193static int
3194compiler_joined_str(struct compiler *c, expr_ty e)
3195{
3196 /* Concatenate parts of a string using ''.join(parts). There are
3197 probably better ways of doing this.
3198
3199 This is used for constructs like "'x=' f'{42}'", which have to
3200 be evaluated at compile time. */
3201
3202 static PyObject *empty_string;
3203 static PyObject *join_string;
3204
3205 if (!empty_string) {
3206 empty_string = PyUnicode_FromString("");
3207 if (!empty_string)
3208 return 0;
3209 }
3210 if (!join_string) {
3211 join_string = PyUnicode_FromString("join");
3212 if (!join_string)
3213 return 0;
3214 }
3215
3216 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3217 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3218 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3219 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3220 ADDOP_I(c, CALL_FUNCTION, 1);
3221 return 1;
3222}
3223
Eric V. Smitha78c7952015-11-03 12:45:05 -05003224/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003225static int
3226compiler_formatted_value(struct compiler *c, expr_ty e)
3227{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003228 /* Our oparg encodes 2 pieces of information: the conversion
3229 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003230
Eric V. Smitha78c7952015-11-03 12:45:05 -05003231 Convert the conversion char to 2 bits:
3232 None: 000 0x0 FVC_NONE
3233 !s : 001 0x1 FVC_STR
3234 !r : 010 0x2 FVC_REPR
3235 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003236
Eric V. Smitha78c7952015-11-03 12:45:05 -05003237 next bit is whether or not we have a format spec:
3238 yes : 100 0x4
3239 no : 000 0x0
3240 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003241
Eric V. Smitha78c7952015-11-03 12:45:05 -05003242 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003243
Eric V. Smitha78c7952015-11-03 12:45:05 -05003244 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003245 VISIT(c, expr, e->v.FormattedValue.value);
3246
Eric V. Smitha78c7952015-11-03 12:45:05 -05003247 switch (e->v.FormattedValue.conversion) {
3248 case 's': oparg = FVC_STR; break;
3249 case 'r': oparg = FVC_REPR; break;
3250 case 'a': oparg = FVC_ASCII; break;
3251 case -1: oparg = FVC_NONE; break;
3252 default:
3253 PyErr_SetString(PyExc_SystemError,
3254 "Unrecognized conversion character");
3255 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003256 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003257 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003258 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003259 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003260 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003261 }
3262
Eric V. Smitha78c7952015-11-03 12:45:05 -05003263 /* And push our opcode and oparg */
3264 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003265 return 1;
3266}
3267
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003268/* shared code between compiler_call and compiler_class */
3269static int
3270compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003271 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003272 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003273 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 int code = 0;
Victor Stinner976bb402016-03-23 11:36:19 +01003276 Py_ssize_t nelts, i, nseen;
3277 int nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003278
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003279 /* the number of tuples and dictionaries on the stack */
3280 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3281
3282 nkw = 0;
3283 nseen = 0; /* the number of positional arguments on the stack */
3284 nelts = asdl_seq_LEN(args);
3285 for (i = 0; i < nelts; i++) {
3286 expr_ty elt = asdl_seq_GET(args, i);
3287 if (elt->kind == Starred_kind) {
3288 /* A star-arg. If we've seen positional arguments,
3289 pack the positional arguments into a
3290 tuple. */
3291 if (nseen) {
3292 ADDOP_I(c, BUILD_TUPLE, nseen);
3293 nseen = 0;
3294 nsubargs++;
3295 }
3296 VISIT(c, expr, elt->v.Starred.value);
3297 nsubargs++;
3298 }
3299 else if (nsubargs) {
3300 /* We've seen star-args already, so we
3301 count towards items-to-pack-into-tuple. */
3302 VISIT(c, expr, elt);
3303 nseen++;
3304 }
3305 else {
3306 /* Positional arguments before star-arguments
3307 are left on the stack. */
3308 VISIT(c, expr, elt);
3309 n++;
3310 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003312 if (nseen) {
3313 /* Pack up any trailing positional arguments. */
3314 ADDOP_I(c, BUILD_TUPLE, nseen);
3315 nsubargs++;
3316 }
3317 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003319 if (nsubargs > 1) {
3320 /* If we ended up with more than one stararg, we need
3321 to concatenate them into a single sequence. */
3322 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003325
3326 /* Same dance again for keyword arguments */
3327 nseen = 0; /* the number of keyword arguments on the stack following */
3328 nelts = asdl_seq_LEN(keywords);
3329 for (i = 0; i < nelts; i++) {
3330 keyword_ty kw = asdl_seq_GET(keywords, i);
3331 if (kw->arg == NULL) {
3332 /* A keyword argument unpacking. */
3333 if (nseen) {
3334 ADDOP_I(c, BUILD_MAP, nseen);
3335 nseen = 0;
3336 nsubkwargs++;
3337 }
3338 VISIT(c, expr, kw->value);
3339 nsubkwargs++;
3340 }
3341 else if (nsubkwargs) {
3342 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003343 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003344 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003345 nseen++;
3346 }
3347 else {
3348 /* keyword argument */
3349 VISIT(c, keyword, kw)
3350 nkw++;
3351 }
3352 }
3353 if (nseen) {
3354 /* Pack up any trailing keyword arguments. */
3355 ADDOP_I(c, BUILD_MAP, nseen);
3356 nsubkwargs++;
3357 }
3358 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003360 if (nsubkwargs > 1) {
3361 /* Pack it all up */
3362 int function_pos = n + (code & 1) + nkw + 1;
3363 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003366 assert(n < 1<<8);
3367 assert(nkw < 1<<24);
3368 n |= nkw << 8;
3369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 switch (code) {
3371 case 0:
3372 ADDOP_I(c, CALL_FUNCTION, n);
3373 break;
3374 case 1:
3375 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3376 break;
3377 case 2:
3378 ADDOP_I(c, CALL_FUNCTION_KW, n);
3379 break;
3380 case 3:
3381 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3382 break;
3383 }
3384 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385}
3386
Nick Coghlan650f0d02007-04-15 12:05:43 +00003387
3388/* List and set comprehensions and generator expressions work by creating a
3389 nested function to perform the actual iteration. This means that the
3390 iteration variables don't leak into the current scope.
3391 The defined function is called immediately following its definition, with the
3392 result of that call being the result of the expression.
3393 The LC/SC version returns the populated container, while the GE version is
3394 flagged in symtable.c as a generator, so it returns the generator object
3395 when the function is called.
3396 This code *knows* that the loop cannot contain break, continue, or return,
3397 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3398
3399 Possible cleanups:
3400 - iterate over the generator sequence instead of using recursion
3401*/
3402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404compiler_comprehension_generator(struct compiler *c,
3405 asdl_seq *generators, int gen_index,
3406 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 /* generate code for the iterator, then each of the ifs,
3409 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 comprehension_ty gen;
3412 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003413 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 start = compiler_new_block(c);
3416 skip = compiler_new_block(c);
3417 if_cleanup = compiler_new_block(c);
3418 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3421 anchor == NULL)
3422 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 if (gen_index == 0) {
3427 /* Receive outermost iter as an implicit argument */
3428 c->u->u_argcount = 1;
3429 ADDOP_I(c, LOAD_FAST, 0);
3430 }
3431 else {
3432 /* Sub-iter - calculate on the fly */
3433 VISIT(c, expr, gen->iter);
3434 ADDOP(c, GET_ITER);
3435 }
3436 compiler_use_next_block(c, start);
3437 ADDOP_JREL(c, FOR_ITER, anchor);
3438 NEXT_BLOCK(c);
3439 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 /* XXX this needs to be cleaned up...a lot! */
3442 n = asdl_seq_LEN(gen->ifs);
3443 for (i = 0; i < n; i++) {
3444 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3445 VISIT(c, expr, e);
3446 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3447 NEXT_BLOCK(c);
3448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 if (++gen_index < asdl_seq_LEN(generators))
3451 if (!compiler_comprehension_generator(c,
3452 generators, gen_index,
3453 elt, val, type))
3454 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 /* only append after the last for generator */
3457 if (gen_index >= asdl_seq_LEN(generators)) {
3458 /* comprehension specific code */
3459 switch (type) {
3460 case COMP_GENEXP:
3461 VISIT(c, expr, elt);
3462 ADDOP(c, YIELD_VALUE);
3463 ADDOP(c, POP_TOP);
3464 break;
3465 case COMP_LISTCOMP:
3466 VISIT(c, expr, elt);
3467 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3468 break;
3469 case COMP_SETCOMP:
3470 VISIT(c, expr, elt);
3471 ADDOP_I(c, SET_ADD, gen_index + 1);
3472 break;
3473 case COMP_DICTCOMP:
3474 /* With 'd[k] = v', v is evaluated before k, so we do
3475 the same. */
3476 VISIT(c, expr, val);
3477 VISIT(c, expr, elt);
3478 ADDOP_I(c, MAP_ADD, gen_index + 1);
3479 break;
3480 default:
3481 return 0;
3482 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 compiler_use_next_block(c, skip);
3485 }
3486 compiler_use_next_block(c, if_cleanup);
3487 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3488 compiler_use_next_block(c, anchor);
3489
3490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491}
3492
3493static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003494compiler_comprehension(struct compiler *c, expr_ty e, int type,
3495 identifier name, asdl_seq *generators, expr_ty elt,
3496 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 PyCodeObject *co = NULL;
3499 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003500 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 outermost_iter = ((comprehension_ty)
3503 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003504
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003505 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3506 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 if (type != COMP_GENEXP) {
3510 int op;
3511 switch (type) {
3512 case COMP_LISTCOMP:
3513 op = BUILD_LIST;
3514 break;
3515 case COMP_SETCOMP:
3516 op = BUILD_SET;
3517 break;
3518 case COMP_DICTCOMP:
3519 op = BUILD_MAP;
3520 break;
3521 default:
3522 PyErr_Format(PyExc_SystemError,
3523 "unknown comprehension type %d", type);
3524 goto error_in_scope;
3525 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 ADDOP_I(c, op, 0);
3528 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 if (!compiler_comprehension_generator(c, generators, 0, elt,
3531 val, type))
3532 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 if (type != COMP_GENEXP) {
3535 ADDOP(c, RETURN_VALUE);
3536 }
3537
3538 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003539 qualname = c->u->u_qualname;
3540 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003542 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 goto error;
3544
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003545 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003547 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 Py_DECREF(co);
3549
3550 VISIT(c, expr, outermost_iter);
3551 ADDOP(c, GET_ITER);
3552 ADDOP_I(c, CALL_FUNCTION, 1);
3553 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003554error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003556error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003557 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 Py_XDECREF(co);
3559 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003560}
3561
3562static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563compiler_genexp(struct compiler *c, expr_ty e)
3564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 static identifier name;
3566 if (!name) {
3567 name = PyUnicode_FromString("<genexpr>");
3568 if (!name)
3569 return 0;
3570 }
3571 assert(e->kind == GeneratorExp_kind);
3572 return compiler_comprehension(c, e, COMP_GENEXP, name,
3573 e->v.GeneratorExp.generators,
3574 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575}
3576
3577static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003578compiler_listcomp(struct compiler *c, expr_ty e)
3579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 static identifier name;
3581 if (!name) {
3582 name = PyUnicode_FromString("<listcomp>");
3583 if (!name)
3584 return 0;
3585 }
3586 assert(e->kind == ListComp_kind);
3587 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3588 e->v.ListComp.generators,
3589 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003590}
3591
3592static int
3593compiler_setcomp(struct compiler *c, expr_ty e)
3594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 static identifier name;
3596 if (!name) {
3597 name = PyUnicode_FromString("<setcomp>");
3598 if (!name)
3599 return 0;
3600 }
3601 assert(e->kind == SetComp_kind);
3602 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3603 e->v.SetComp.generators,
3604 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003605}
3606
3607
3608static int
3609compiler_dictcomp(struct compiler *c, expr_ty e)
3610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 static identifier name;
3612 if (!name) {
3613 name = PyUnicode_FromString("<dictcomp>");
3614 if (!name)
3615 return 0;
3616 }
3617 assert(e->kind == DictComp_kind);
3618 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3619 e->v.DictComp.generators,
3620 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003621}
3622
3623
3624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625compiler_visit_keyword(struct compiler *c, keyword_ty k)
3626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3628 VISIT(c, expr, k->value);
3629 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 whether they are true or false.
3634
3635 Return values: 1 for true, 0 for false, -1 for non-constant.
3636 */
3637
3638static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003639expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 char *id;
3642 switch (e->kind) {
3643 case Ellipsis_kind:
3644 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003645 case Constant_kind:
3646 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 case Num_kind:
3648 return PyObject_IsTrue(e->v.Num.n);
3649 case Str_kind:
3650 return PyObject_IsTrue(e->v.Str.s);
3651 case Name_kind:
3652 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003653 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003654 if (id && strcmp(id, "__debug__") == 0)
3655 return !c->c_optimize;
3656 return -1;
3657 case NameConstant_kind: {
3658 PyObject *o = e->v.NameConstant.value;
3659 if (o == Py_None)
3660 return 0;
3661 else if (o == Py_True)
3662 return 1;
3663 else if (o == Py_False)
3664 return 0;
3665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 default:
3667 return -1;
3668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669}
3670
Yury Selivanov75445082015-05-11 22:57:16 -04003671
3672/*
3673 Implements the async with statement.
3674
3675 The semantics outlined in that PEP are as follows:
3676
3677 async with EXPR as VAR:
3678 BLOCK
3679
3680 It is implemented roughly as:
3681
3682 context = EXPR
3683 exit = context.__aexit__ # not calling it
3684 value = await context.__aenter__()
3685 try:
3686 VAR = value # if VAR present in the syntax
3687 BLOCK
3688 finally:
3689 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003690 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003691 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003692 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003693 if not (await exit(*exc)):
3694 raise
3695 */
3696static int
3697compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3698{
3699 basicblock *block, *finally;
3700 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3701
3702 assert(s->kind == AsyncWith_kind);
3703
3704 block = compiler_new_block(c);
3705 finally = compiler_new_block(c);
3706 if (!block || !finally)
3707 return 0;
3708
3709 /* Evaluate EXPR */
3710 VISIT(c, expr, item->context_expr);
3711
3712 ADDOP(c, BEFORE_ASYNC_WITH);
3713 ADDOP(c, GET_AWAITABLE);
3714 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3715 ADDOP(c, YIELD_FROM);
3716
3717 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3718
3719 /* SETUP_ASYNC_WITH pushes a finally block. */
3720 compiler_use_next_block(c, block);
3721 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3722 return 0;
3723 }
3724
3725 if (item->optional_vars) {
3726 VISIT(c, expr, item->optional_vars);
3727 }
3728 else {
3729 /* Discard result from context.__aenter__() */
3730 ADDOP(c, POP_TOP);
3731 }
3732
3733 pos++;
3734 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3735 /* BLOCK code */
3736 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3737 else if (!compiler_async_with(c, s, pos))
3738 return 0;
3739
3740 /* End of try block; start the finally block */
3741 ADDOP(c, POP_BLOCK);
3742 compiler_pop_fblock(c, FINALLY_TRY, block);
3743
3744 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3745 compiler_use_next_block(c, finally);
3746 if (!compiler_push_fblock(c, FINALLY_END, finally))
3747 return 0;
3748
3749 /* Finally block starts; context.__exit__ is on the stack under
3750 the exception or return information. Just issue our magic
3751 opcode. */
3752 ADDOP(c, WITH_CLEANUP_START);
3753
3754 ADDOP(c, GET_AWAITABLE);
3755 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3756 ADDOP(c, YIELD_FROM);
3757
3758 ADDOP(c, WITH_CLEANUP_FINISH);
3759
3760 /* Finally block ends. */
3761 ADDOP(c, END_FINALLY);
3762 compiler_pop_fblock(c, FINALLY_END, finally);
3763 return 1;
3764}
3765
3766
Guido van Rossumc2e20742006-02-27 22:32:47 +00003767/*
3768 Implements the with statement from PEP 343.
3769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003771
3772 with EXPR as VAR:
3773 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774
Guido van Rossumc2e20742006-02-27 22:32:47 +00003775 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776
Thomas Wouters477c8d52006-05-27 19:21:47 +00003777 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003778 exit = context.__exit__ # not calling it
3779 value = context.__enter__()
3780 try:
3781 VAR = value # if VAR present in the syntax
3782 BLOCK
3783 finally:
3784 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003785 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003786 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003787 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003788 exit(*exc)
3789 */
3790static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003791compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003792{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003793 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003794 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003795
3796 assert(s->kind == With_kind);
3797
Guido van Rossumc2e20742006-02-27 22:32:47 +00003798 block = compiler_new_block(c);
3799 finally = compiler_new_block(c);
3800 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003801 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003802
Thomas Wouters477c8d52006-05-27 19:21:47 +00003803 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003804 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003805 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003806
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003807 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003808 compiler_use_next_block(c, block);
3809 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003810 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003811 }
3812
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003813 if (item->optional_vars) {
3814 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003815 }
3816 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003818 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003819 }
3820
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003821 pos++;
3822 if (pos == asdl_seq_LEN(s->v.With.items))
3823 /* BLOCK code */
3824 VISIT_SEQ(c, stmt, s->v.With.body)
3825 else if (!compiler_with(c, s, pos))
3826 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003827
3828 /* End of try block; start the finally block */
3829 ADDOP(c, POP_BLOCK);
3830 compiler_pop_fblock(c, FINALLY_TRY, block);
3831
3832 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3833 compiler_use_next_block(c, finally);
3834 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003835 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003836
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003837 /* Finally block starts; context.__exit__ is on the stack under
3838 the exception or return information. Just issue our magic
3839 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003840 ADDOP(c, WITH_CLEANUP_START);
3841 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003842
3843 /* Finally block ends. */
3844 ADDOP(c, END_FINALLY);
3845 compiler_pop_fblock(c, FINALLY_END, finally);
3846 return 1;
3847}
3848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849static int
3850compiler_visit_expr(struct compiler *c, expr_ty e)
3851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 /* If expr e has a different line number than the last expr/stmt,
3853 set a new line number for the next instruction.
3854 */
3855 if (e->lineno > c->u->u_lineno) {
3856 c->u->u_lineno = e->lineno;
3857 c->u->u_lineno_set = 0;
3858 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003859 /* Updating the column offset is always harmless. */
3860 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 switch (e->kind) {
3862 case BoolOp_kind:
3863 return compiler_boolop(c, e);
3864 case BinOp_kind:
3865 VISIT(c, expr, e->v.BinOp.left);
3866 VISIT(c, expr, e->v.BinOp.right);
3867 ADDOP(c, binop(c, e->v.BinOp.op));
3868 break;
3869 case UnaryOp_kind:
3870 VISIT(c, expr, e->v.UnaryOp.operand);
3871 ADDOP(c, unaryop(e->v.UnaryOp.op));
3872 break;
3873 case Lambda_kind:
3874 return compiler_lambda(c, e);
3875 case IfExp_kind:
3876 return compiler_ifexp(c, e);
3877 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003878 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003880 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 case GeneratorExp_kind:
3882 return compiler_genexp(c, e);
3883 case ListComp_kind:
3884 return compiler_listcomp(c, e);
3885 case SetComp_kind:
3886 return compiler_setcomp(c, e);
3887 case DictComp_kind:
3888 return compiler_dictcomp(c, e);
3889 case Yield_kind:
3890 if (c->u->u_ste->ste_type != FunctionBlock)
3891 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003892 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3893 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003894 if (e->v.Yield.value) {
3895 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 }
3897 else {
3898 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3899 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003900 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003902 case YieldFrom_kind:
3903 if (c->u->u_ste->ste_type != FunctionBlock)
3904 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003905
3906 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3907 return compiler_error(c, "'yield from' inside async function");
3908
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003909 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003910 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003911 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3912 ADDOP(c, YIELD_FROM);
3913 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003914 case Await_kind:
3915 if (c->u->u_ste->ste_type != FunctionBlock)
3916 return compiler_error(c, "'await' outside function");
3917
Yury Selivanov9dec0352015-06-30 12:49:04 -04003918 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3919 return compiler_error(
3920 c, "'await' expressions in comprehensions are not supported");
3921
Yury Selivanov75445082015-05-11 22:57:16 -04003922 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3923 return compiler_error(c, "'await' outside async function");
3924
3925 VISIT(c, expr, e->v.Await.value);
3926 ADDOP(c, GET_AWAITABLE);
3927 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3928 ADDOP(c, YIELD_FROM);
3929 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 case Compare_kind:
3931 return compiler_compare(c, e);
3932 case Call_kind:
3933 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003934 case Constant_kind:
3935 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
3936 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 case Num_kind:
3938 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3939 break;
3940 case Str_kind:
3941 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3942 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003943 case JoinedStr_kind:
3944 return compiler_joined_str(c, e);
3945 case FormattedValue_kind:
3946 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 case Bytes_kind:
3948 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3949 break;
3950 case Ellipsis_kind:
3951 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3952 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003953 case NameConstant_kind:
3954 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3955 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 /* The following exprs can be assignment targets. */
3957 case Attribute_kind:
3958 if (e->v.Attribute.ctx != AugStore)
3959 VISIT(c, expr, e->v.Attribute.value);
3960 switch (e->v.Attribute.ctx) {
3961 case AugLoad:
3962 ADDOP(c, DUP_TOP);
3963 /* Fall through to load */
3964 case Load:
3965 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3966 break;
3967 case AugStore:
3968 ADDOP(c, ROT_TWO);
3969 /* Fall through to save */
3970 case Store:
3971 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3972 break;
3973 case Del:
3974 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3975 break;
3976 case Param:
3977 default:
3978 PyErr_SetString(PyExc_SystemError,
3979 "param invalid in attribute expression");
3980 return 0;
3981 }
3982 break;
3983 case Subscript_kind:
3984 switch (e->v.Subscript.ctx) {
3985 case AugLoad:
3986 VISIT(c, expr, e->v.Subscript.value);
3987 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3988 break;
3989 case Load:
3990 VISIT(c, expr, e->v.Subscript.value);
3991 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3992 break;
3993 case AugStore:
3994 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3995 break;
3996 case Store:
3997 VISIT(c, expr, e->v.Subscript.value);
3998 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3999 break;
4000 case Del:
4001 VISIT(c, expr, e->v.Subscript.value);
4002 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4003 break;
4004 case Param:
4005 default:
4006 PyErr_SetString(PyExc_SystemError,
4007 "param invalid in subscript expression");
4008 return 0;
4009 }
4010 break;
4011 case Starred_kind:
4012 switch (e->v.Starred.ctx) {
4013 case Store:
4014 /* In all legitimate cases, the Starred node was already replaced
4015 * by compiler_list/compiler_tuple. XXX: is that okay? */
4016 return compiler_error(c,
4017 "starred assignment target must be in a list or tuple");
4018 default:
4019 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004020 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 }
4022 break;
4023 case Name_kind:
4024 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4025 /* child nodes of List and Tuple will have expr_context set */
4026 case List_kind:
4027 return compiler_list(c, e);
4028 case Tuple_kind:
4029 return compiler_tuple(c, e);
4030 }
4031 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032}
4033
4034static int
4035compiler_augassign(struct compiler *c, stmt_ty s)
4036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 expr_ty e = s->v.AugAssign.target;
4038 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 switch (e->kind) {
4043 case Attribute_kind:
4044 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4045 AugLoad, e->lineno, e->col_offset, c->c_arena);
4046 if (auge == NULL)
4047 return 0;
4048 VISIT(c, expr, auge);
4049 VISIT(c, expr, s->v.AugAssign.value);
4050 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4051 auge->v.Attribute.ctx = AugStore;
4052 VISIT(c, expr, auge);
4053 break;
4054 case Subscript_kind:
4055 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
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.Subscript.ctx = AugStore;
4063 VISIT(c, expr, auge);
4064 break;
4065 case Name_kind:
4066 if (!compiler_nameop(c, e->v.Name.id, Load))
4067 return 0;
4068 VISIT(c, expr, s->v.AugAssign.value);
4069 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4070 return compiler_nameop(c, e->v.Name.id, Store);
4071 default:
4072 PyErr_Format(PyExc_SystemError,
4073 "invalid node type (%d) for augmented assignment",
4074 e->kind);
4075 return 0;
4076 }
4077 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004078}
4079
4080static int
4081compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 struct fblockinfo *f;
4084 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4085 PyErr_SetString(PyExc_SystemError,
4086 "too many statically nested blocks");
4087 return 0;
4088 }
4089 f = &c->u->u_fblock[c->u->u_nfblocks++];
4090 f->fb_type = t;
4091 f->fb_block = b;
4092 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093}
4094
4095static void
4096compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 struct compiler_unit *u = c->u;
4099 assert(u->u_nfblocks > 0);
4100 u->u_nfblocks--;
4101 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4102 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103}
4104
Thomas Wouters89f507f2006-12-13 04:49:30 +00004105static int
4106compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 int i;
4108 struct compiler_unit *u = c->u;
4109 for (i = 0; i < u->u_nfblocks; ++i) {
4110 if (u->u_fblock[i].fb_type == LOOP)
4111 return 1;
4112 }
4113 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004114}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115/* Raises a SyntaxError and returns 0.
4116 If something goes wrong, a different exception may be raised.
4117*/
4118
4119static int
4120compiler_error(struct compiler *c, const char *errstr)
4121{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004122 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124
Victor Stinner14e461d2013-08-26 22:28:21 +02004125 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 if (!loc) {
4127 Py_INCREF(Py_None);
4128 loc = Py_None;
4129 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004130 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004131 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 if (!u)
4133 goto exit;
4134 v = Py_BuildValue("(zO)", errstr, u);
4135 if (!v)
4136 goto exit;
4137 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 Py_DECREF(loc);
4140 Py_XDECREF(u);
4141 Py_XDECREF(v);
4142 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143}
4144
4145static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146compiler_handle_subscr(struct compiler *c, const char *kind,
4147 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 /* XXX this code is duplicated */
4152 switch (ctx) {
4153 case AugLoad: /* fall through to Load */
4154 case Load: op = BINARY_SUBSCR; break;
4155 case AugStore:/* fall through to Store */
4156 case Store: op = STORE_SUBSCR; break;
4157 case Del: op = DELETE_SUBSCR; break;
4158 case Param:
4159 PyErr_Format(PyExc_SystemError,
4160 "invalid %s kind %d in subscript\n",
4161 kind, ctx);
4162 return 0;
4163 }
4164 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004165 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 }
4167 else if (ctx == AugStore) {
4168 ADDOP(c, ROT_THREE);
4169 }
4170 ADDOP(c, op);
4171 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172}
4173
4174static int
4175compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 int n = 2;
4178 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 /* only handles the cases where BUILD_SLICE is emitted */
4181 if (s->v.Slice.lower) {
4182 VISIT(c, expr, s->v.Slice.lower);
4183 }
4184 else {
4185 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4186 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 if (s->v.Slice.upper) {
4189 VISIT(c, expr, s->v.Slice.upper);
4190 }
4191 else {
4192 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4193 }
4194
4195 if (s->v.Slice.step) {
4196 n++;
4197 VISIT(c, expr, s->v.Slice.step);
4198 }
4199 ADDOP_I(c, BUILD_SLICE, n);
4200 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201}
4202
4203static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4205 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 switch (s->kind) {
4208 case Slice_kind:
4209 return compiler_slice(c, s, ctx);
4210 case Index_kind:
4211 VISIT(c, expr, s->v.Index.value);
4212 break;
4213 case ExtSlice_kind:
4214 default:
4215 PyErr_SetString(PyExc_SystemError,
4216 "extended slice invalid in nested slice");
4217 return 0;
4218 }
4219 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220}
4221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004222static int
4223compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 char * kindname = NULL;
4226 switch (s->kind) {
4227 case Index_kind:
4228 kindname = "index";
4229 if (ctx != AugStore) {
4230 VISIT(c, expr, s->v.Index.value);
4231 }
4232 break;
4233 case Slice_kind:
4234 kindname = "slice";
4235 if (ctx != AugStore) {
4236 if (!compiler_slice(c, s, ctx))
4237 return 0;
4238 }
4239 break;
4240 case ExtSlice_kind:
4241 kindname = "extended slice";
4242 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004243 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 for (i = 0; i < n; i++) {
4245 slice_ty sub = (slice_ty)asdl_seq_GET(
4246 s->v.ExtSlice.dims, i);
4247 if (!compiler_visit_nested_slice(c, sub, ctx))
4248 return 0;
4249 }
4250 ADDOP_I(c, BUILD_TUPLE, n);
4251 }
4252 break;
4253 default:
4254 PyErr_Format(PyExc_SystemError,
4255 "invalid subscript kind %d", s->kind);
4256 return 0;
4257 }
4258 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004259}
4260
Thomas Wouters89f507f2006-12-13 04:49:30 +00004261/* End of the compiler section, beginning of the assembler section */
4262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004263/* do depth-first search of basic block graph, starting with block.
4264 post records the block indices in post-order.
4265
4266 XXX must handle implicit jumps from one block to next
4267*/
4268
Thomas Wouters89f507f2006-12-13 04:49:30 +00004269struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 PyObject *a_bytecode; /* string containing bytecode */
4271 int a_offset; /* offset into bytecode */
4272 int a_nblocks; /* number of reachable blocks */
4273 basicblock **a_postorder; /* list of blocks in dfs postorder */
4274 PyObject *a_lnotab; /* string containing lnotab */
4275 int a_lnotab_off; /* offset into lnotab */
4276 int a_lineno; /* last lineno of emitted instruction */
4277 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004278};
4279
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280static void
4281dfs(struct compiler *c, basicblock *b, struct assembler *a)
4282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 int i;
4284 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 if (b->b_seen)
4287 return;
4288 b->b_seen = 1;
4289 if (b->b_next != NULL)
4290 dfs(c, b->b_next, a);
4291 for (i = 0; i < b->b_iused; i++) {
4292 instr = &b->b_instr[i];
4293 if (instr->i_jrel || instr->i_jabs)
4294 dfs(c, instr->i_target, a);
4295 }
4296 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004297}
4298
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004299static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004300stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4301{
Larry Hastings3a907972013-11-23 14:49:22 -08004302 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 struct instr *instr;
4304 if (b->b_seen || b->b_startdepth >= depth)
4305 return maxdepth;
4306 b->b_seen = 1;
4307 b->b_startdepth = depth;
4308 for (i = 0; i < b->b_iused; i++) {
4309 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004310 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4311 if (effect == PY_INVALID_STACK_EFFECT) {
4312 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4313 Py_FatalError("PyCompile_OpcodeStackEffect()");
4314 }
4315 depth += effect;
4316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 if (depth > maxdepth)
4318 maxdepth = depth;
4319 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4320 if (instr->i_jrel || instr->i_jabs) {
4321 target_depth = depth;
4322 if (instr->i_opcode == FOR_ITER) {
4323 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004324 }
4325 else if (instr->i_opcode == SETUP_FINALLY ||
4326 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 target_depth = depth+3;
4328 if (target_depth > maxdepth)
4329 maxdepth = target_depth;
4330 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004331 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4332 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4333 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 maxdepth = stackdepth_walk(c, instr->i_target,
4335 target_depth, maxdepth);
4336 if (instr->i_opcode == JUMP_ABSOLUTE ||
4337 instr->i_opcode == JUMP_FORWARD) {
4338 goto out; /* remaining code is dead */
4339 }
4340 }
4341 }
4342 if (b->b_next)
4343 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 b->b_seen = 0;
4346 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347}
4348
4349/* Find the flow path that needs the largest stack. We assume that
4350 * cycles in the flow graph have no net effect on the stack depth.
4351 */
4352static int
4353stackdepth(struct compiler *c)
4354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 basicblock *b, *entryblock;
4356 entryblock = NULL;
4357 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4358 b->b_seen = 0;
4359 b->b_startdepth = INT_MIN;
4360 entryblock = b;
4361 }
4362 if (!entryblock)
4363 return 0;
4364 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365}
4366
4367static int
4368assemble_init(struct assembler *a, int nblocks, int firstlineno)
4369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 memset(a, 0, sizeof(struct assembler));
4371 a->a_lineno = firstlineno;
4372 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4373 if (!a->a_bytecode)
4374 return 0;
4375 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4376 if (!a->a_lnotab)
4377 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004378 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 PyErr_NoMemory();
4380 return 0;
4381 }
4382 a->a_postorder = (basicblock **)PyObject_Malloc(
4383 sizeof(basicblock *) * nblocks);
4384 if (!a->a_postorder) {
4385 PyErr_NoMemory();
4386 return 0;
4387 }
4388 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389}
4390
4391static void
4392assemble_free(struct assembler *a)
4393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 Py_XDECREF(a->a_bytecode);
4395 Py_XDECREF(a->a_lnotab);
4396 if (a->a_postorder)
4397 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004398}
4399
4400/* Return the size of a basic block in bytes. */
4401
4402static int
4403instrsize(struct instr *instr)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 if (!instr->i_hasarg)
4406 return 1; /* 1 byte for the opcode*/
4407 if (instr->i_oparg > 0xffff)
4408 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4409 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004410}
4411
4412static int
4413blocksize(basicblock *b)
4414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 int i;
4416 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 for (i = 0; i < b->b_iused; i++)
4419 size += instrsize(&b->b_instr[i]);
4420 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421}
4422
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004423/* Appends a pair to the end of the line number table, a_lnotab, representing
4424 the instruction's bytecode offset and line number. See
4425 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004426
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004427static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004428assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004431 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 d_bytecode = a->a_offset - a->a_lineno_off;
4435 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 if(d_bytecode == 0 && d_lineno == 0)
4440 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 if (d_bytecode > 255) {
4443 int j, nbytes, ncodes = d_bytecode / 255;
4444 nbytes = a->a_lnotab_off + 2 * ncodes;
4445 len = PyBytes_GET_SIZE(a->a_lnotab);
4446 if (nbytes >= len) {
4447 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4448 len = nbytes;
4449 else if (len <= INT_MAX / 2)
4450 len *= 2;
4451 else {
4452 PyErr_NoMemory();
4453 return 0;
4454 }
4455 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4456 return 0;
4457 }
4458 lnotab = (unsigned char *)
4459 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4460 for (j = 0; j < ncodes; j++) {
4461 *lnotab++ = 255;
4462 *lnotab++ = 0;
4463 }
4464 d_bytecode -= ncodes * 255;
4465 a->a_lnotab_off += ncodes * 2;
4466 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004467 assert(0 <= d_bytecode && d_bytecode <= 255);
4468
4469 if (d_lineno < -128 || 127 < d_lineno) {
4470 int j, nbytes, ncodes, k;
4471 if (d_lineno < 0) {
4472 k = -128;
4473 /* use division on positive numbers */
4474 ncodes = (-d_lineno) / 128;
4475 }
4476 else {
4477 k = 127;
4478 ncodes = d_lineno / 127;
4479 }
4480 d_lineno -= ncodes * k;
4481 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 nbytes = a->a_lnotab_off + 2 * ncodes;
4483 len = PyBytes_GET_SIZE(a->a_lnotab);
4484 if (nbytes >= len) {
4485 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4486 len = nbytes;
4487 else if (len <= INT_MAX / 2)
4488 len *= 2;
4489 else {
4490 PyErr_NoMemory();
4491 return 0;
4492 }
4493 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4494 return 0;
4495 }
4496 lnotab = (unsigned char *)
4497 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4498 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004499 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 d_bytecode = 0;
4501 for (j = 1; j < ncodes; j++) {
4502 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004503 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 a->a_lnotab_off += ncodes * 2;
4506 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004507 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 len = PyBytes_GET_SIZE(a->a_lnotab);
4510 if (a->a_lnotab_off + 2 >= len) {
4511 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4512 return 0;
4513 }
4514 lnotab = (unsigned char *)
4515 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 a->a_lnotab_off += 2;
4518 if (d_bytecode) {
4519 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004520 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 }
4522 else { /* First line of a block; def stmt, etc. */
4523 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004524 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 }
4526 a->a_lineno = i->i_lineno;
4527 a->a_lineno_off = a->a_offset;
4528 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004529}
4530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004531/* assemble_emit()
4532 Extend the bytecode with a new instruction.
4533 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004534*/
4535
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004536static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004537assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 int size, arg = 0, ext = 0;
4540 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4541 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 size = instrsize(i);
4544 if (i->i_hasarg) {
4545 arg = i->i_oparg;
4546 ext = arg >> 16;
4547 }
4548 if (i->i_lineno && !assemble_lnotab(a, i))
4549 return 0;
4550 if (a->a_offset + size >= len) {
4551 if (len > PY_SSIZE_T_MAX / 2)
4552 return 0;
4553 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4554 return 0;
4555 }
4556 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4557 a->a_offset += size;
4558 if (size == 6) {
4559 assert(i->i_hasarg);
4560 *code++ = (char)EXTENDED_ARG;
4561 *code++ = ext & 0xff;
4562 *code++ = ext >> 8;
4563 arg &= 0xffff;
4564 }
4565 *code++ = i->i_opcode;
4566 if (i->i_hasarg) {
4567 assert(size == 3 || size == 6);
4568 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004569 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 }
4571 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004572}
4573
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004574static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004575assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 basicblock *b;
4578 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4579 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 /* Compute the size of each block and fixup jump args.
4582 Replace block pointer with position in bytecode. */
4583 do {
4584 totsize = 0;
4585 for (i = a->a_nblocks - 1; i >= 0; i--) {
4586 b = a->a_postorder[i];
4587 bsize = blocksize(b);
4588 b->b_offset = totsize;
4589 totsize += bsize;
4590 }
4591 last_extended_arg_count = extended_arg_count;
4592 extended_arg_count = 0;
4593 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4594 bsize = b->b_offset;
4595 for (i = 0; i < b->b_iused; i++) {
4596 struct instr *instr = &b->b_instr[i];
4597 /* Relative jumps are computed relative to
4598 the instruction pointer after fetching
4599 the jump instruction.
4600 */
4601 bsize += instrsize(instr);
4602 if (instr->i_jabs)
4603 instr->i_oparg = instr->i_target->b_offset;
4604 else if (instr->i_jrel) {
4605 int delta = instr->i_target->b_offset - bsize;
4606 instr->i_oparg = delta;
4607 }
4608 else
4609 continue;
4610 if (instr->i_oparg > 0xffff)
4611 extended_arg_count++;
4612 }
4613 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 /* XXX: This is an awful hack that could hurt performance, but
4616 on the bright side it should work until we come up
4617 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 The issue is that in the first loop blocksize() is called
4620 which calls instrsize() which requires i_oparg be set
4621 appropriately. There is a bootstrap problem because
4622 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 So we loop until we stop seeing new EXTENDED_ARGs.
4625 The only EXTENDED_ARGs that could be popping up are
4626 ones in jump instructions. So this should converge
4627 fairly quickly.
4628 */
4629 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004630}
4631
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004632static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004633dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 PyObject *tuple, *k, *v;
4636 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 tuple = PyTuple_New(size);
4639 if (tuple == NULL)
4640 return NULL;
4641 while (PyDict_Next(dict, &pos, &k, &v)) {
4642 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004643 /* The keys of the dictionary are tuples. (see compiler_add_o
4644 * and _PyCode_ConstantKey). The object we want is always second,
4645 * though. */
4646 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 Py_INCREF(k);
4648 assert((i - offset) < size);
4649 assert((i - offset) >= 0);
4650 PyTuple_SET_ITEM(tuple, i - offset, k);
4651 }
4652 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004653}
4654
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004655static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004656compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004659 int flags = 0;
4660 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004662 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 if (ste->ste_nested)
4664 flags |= CO_NESTED;
4665 if (ste->ste_generator)
4666 flags |= CO_GENERATOR;
4667 if (ste->ste_varargs)
4668 flags |= CO_VARARGS;
4669 if (ste->ste_varkeywords)
4670 flags |= CO_VARKEYWORDS;
4671 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 /* (Only) inherit compilerflags in PyCF_MASK */
4674 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 n = PyDict_Size(c->u->u_freevars);
4677 if (n < 0)
4678 return -1;
4679 if (n == 0) {
4680 n = PyDict_Size(c->u->u_cellvars);
4681 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004682 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004684 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 }
4686 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004689}
4690
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004691static PyCodeObject *
4692makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 PyObject *tmp;
4695 PyCodeObject *co = NULL;
4696 PyObject *consts = NULL;
4697 PyObject *names = NULL;
4698 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 PyObject *name = NULL;
4700 PyObject *freevars = NULL;
4701 PyObject *cellvars = NULL;
4702 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004703 Py_ssize_t nlocals;
4704 int nlocals_int;
4705 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004706 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 tmp = dict_keys_inorder(c->u->u_consts, 0);
4709 if (!tmp)
4710 goto error;
4711 consts = PySequence_List(tmp); /* optimize_code requires a list */
4712 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 names = dict_keys_inorder(c->u->u_names, 0);
4715 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4716 if (!consts || !names || !varnames)
4717 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4720 if (!cellvars)
4721 goto error;
4722 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4723 if (!freevars)
4724 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004727 assert(nlocals < INT_MAX);
4728 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 flags = compute_code_flags(c);
4731 if (flags < 0)
4732 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4735 if (!bytecode)
4736 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4739 if (!tmp)
4740 goto error;
4741 Py_DECREF(consts);
4742 consts = tmp;
4743
Victor Stinnerf8e32212013-11-19 23:56:34 +01004744 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4745 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4746 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004747 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 bytecode, consts, names, varnames,
4749 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004750 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 c->u->u_firstlineno,
4752 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004753 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 Py_XDECREF(consts);
4755 Py_XDECREF(names);
4756 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 Py_XDECREF(name);
4758 Py_XDECREF(freevars);
4759 Py_XDECREF(cellvars);
4760 Py_XDECREF(bytecode);
4761 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004762}
4763
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004764
4765/* For debugging purposes only */
4766#if 0
4767static void
4768dump_instr(const struct instr *i)
4769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 const char *jrel = i->i_jrel ? "jrel " : "";
4771 const char *jabs = i->i_jabs ? "jabs " : "";
4772 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 *arg = '\0';
4775 if (i->i_hasarg)
4776 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4779 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004780}
4781
4782static void
4783dump_basicblock(const basicblock *b)
4784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 const char *seen = b->b_seen ? "seen " : "";
4786 const char *b_return = b->b_return ? "return " : "";
4787 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4788 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4789 if (b->b_instr) {
4790 int i;
4791 for (i = 0; i < b->b_iused; i++) {
4792 fprintf(stderr, " [%02d] ", i);
4793 dump_instr(b->b_instr + i);
4794 }
4795 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004796}
4797#endif
4798
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004799static PyCodeObject *
4800assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 basicblock *b, *entryblock;
4803 struct assembler a;
4804 int i, j, nblocks;
4805 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 /* Make sure every block that falls off the end returns None.
4808 XXX NEXT_BLOCK() isn't quite right, because if the last
4809 block ends with a jump or return b_next shouldn't set.
4810 */
4811 if (!c->u->u_curblock->b_return) {
4812 NEXT_BLOCK(c);
4813 if (addNone)
4814 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4815 ADDOP(c, RETURN_VALUE);
4816 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 nblocks = 0;
4819 entryblock = NULL;
4820 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4821 nblocks++;
4822 entryblock = b;
4823 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 /* Set firstlineno if it wasn't explicitly set. */
4826 if (!c->u->u_firstlineno) {
4827 if (entryblock && entryblock->b_instr)
4828 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4829 else
4830 c->u->u_firstlineno = 1;
4831 }
4832 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4833 goto error;
4834 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 /* Can't modify the bytecode after computing jump offsets. */
4837 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 /* Emit code in reverse postorder from dfs. */
4840 for (i = a.a_nblocks - 1; i >= 0; i--) {
4841 b = a.a_postorder[i];
4842 for (j = 0; j < b->b_iused; j++)
4843 if (!assemble_emit(&a, &b->b_instr[j]))
4844 goto error;
4845 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4848 goto error;
4849 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4850 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004853 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 assemble_free(&a);
4855 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004856}
Georg Brandl8334fd92010-12-04 10:26:46 +00004857
4858#undef PyAST_Compile
4859PyAPI_FUNC(PyCodeObject *)
4860PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4861 PyArena *arena)
4862{
4863 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4864}