blob: e86b2935432d4512ddeb439928950a43444e0674 [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 Stinnerad9a0662013-11-19 22:23:20 +0100198static int compiler_call_helper(struct compiler *c, Py_ssize_t 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) {
479 assert((void *)block != (void *)0xcbcbcbcb);
480 assert((void *)block != (void *)0xfbfbfbfb);
481 assert((void *)block != (void *)0xdbdbdbdb);
482 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{
3100 Py_ssize_t i, n, containers, elements;
3101 int is_unpacking = 0;
3102 n = asdl_seq_LEN(e->v.Dict.values);
3103 containers = 0;
3104 elements = 0;
3105 for (i = 0; i < n; i++) {
3106 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3107 if (elements == 0xFFFF || (elements && is_unpacking)) {
3108 ADDOP_I(c, BUILD_MAP, elements);
3109 containers++;
3110 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003112 if (is_unpacking) {
3113 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3114 containers++;
3115 }
3116 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003117 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Benjamin Petersonee853392015-05-28 14:30:26 -05003118 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003119 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 }
3121 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003122 if (elements || containers == 0) {
3123 ADDOP_I(c, BUILD_MAP, elements);
3124 containers++;
3125 }
3126 /* If there is more than one dict, they need to be merged into a new
3127 * dict. If there is one dict and it's an unpacking, then it needs
3128 * to be copied into a new dict." */
3129 while (containers > 1 || is_unpacking) {
3130 int oparg = containers < 255 ? containers : 255;
3131 ADDOP_I(c, BUILD_MAP_UNPACK, oparg);
3132 containers -= (oparg - 1);
3133 is_unpacking = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 }
3135 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136}
3137
3138static int
3139compiler_compare(struct compiler *c, expr_ty e)
3140{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003141 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3145 VISIT(c, expr, e->v.Compare.left);
3146 n = asdl_seq_LEN(e->v.Compare.ops);
3147 assert(n > 0);
3148 if (n > 1) {
3149 cleanup = compiler_new_block(c);
3150 if (cleanup == NULL)
3151 return 0;
3152 VISIT(c, expr,
3153 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3154 }
3155 for (i = 1; i < n; i++) {
3156 ADDOP(c, DUP_TOP);
3157 ADDOP(c, ROT_THREE);
3158 ADDOP_I(c, COMPARE_OP,
3159 cmpop((cmpop_ty)(asdl_seq_GET(
3160 e->v.Compare.ops, i - 1))));
3161 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3162 NEXT_BLOCK(c);
3163 if (i < (n - 1))
3164 VISIT(c, expr,
3165 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3166 }
3167 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3168 ADDOP_I(c, COMPARE_OP,
3169 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3170 if (n > 1) {
3171 basicblock *end = compiler_new_block(c);
3172 if (end == NULL)
3173 return 0;
3174 ADDOP_JREL(c, JUMP_FORWARD, end);
3175 compiler_use_next_block(c, cleanup);
3176 ADDOP(c, ROT_TWO);
3177 ADDOP(c, POP_TOP);
3178 compiler_use_next_block(c, end);
3179 }
3180 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
3183static int
3184compiler_call(struct compiler *c, expr_ty e)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 VISIT(c, expr, e->v.Call.func);
3187 return compiler_call_helper(c, 0,
3188 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003189 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003190}
3191
Eric V. Smith235a6f02015-09-19 14:51:32 -04003192static int
3193compiler_joined_str(struct compiler *c, expr_ty e)
3194{
3195 /* Concatenate parts of a string using ''.join(parts). There are
3196 probably better ways of doing this.
3197
3198 This is used for constructs like "'x=' f'{42}'", which have to
3199 be evaluated at compile time. */
3200
3201 static PyObject *empty_string;
3202 static PyObject *join_string;
3203
3204 if (!empty_string) {
3205 empty_string = PyUnicode_FromString("");
3206 if (!empty_string)
3207 return 0;
3208 }
3209 if (!join_string) {
3210 join_string = PyUnicode_FromString("join");
3211 if (!join_string)
3212 return 0;
3213 }
3214
3215 ADDOP_O(c, LOAD_CONST, empty_string, consts);
3216 ADDOP_NAME(c, LOAD_ATTR, join_string, names);
3217 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
3218 ADDOP_I(c, BUILD_LIST, asdl_seq_LEN(e->v.JoinedStr.values));
3219 ADDOP_I(c, CALL_FUNCTION, 1);
3220 return 1;
3221}
3222
Eric V. Smitha78c7952015-11-03 12:45:05 -05003223/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003224static int
3225compiler_formatted_value(struct compiler *c, expr_ty e)
3226{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003227 /* Our oparg encodes 2 pieces of information: the conversion
3228 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003229
Eric V. Smitha78c7952015-11-03 12:45:05 -05003230 Convert the conversion char to 2 bits:
3231 None: 000 0x0 FVC_NONE
3232 !s : 001 0x1 FVC_STR
3233 !r : 010 0x2 FVC_REPR
3234 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003235
Eric V. Smitha78c7952015-11-03 12:45:05 -05003236 next bit is whether or not we have a format spec:
3237 yes : 100 0x4
3238 no : 000 0x0
3239 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003240
Eric V. Smitha78c7952015-11-03 12:45:05 -05003241 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003242
Eric V. Smitha78c7952015-11-03 12:45:05 -05003243 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003244 VISIT(c, expr, e->v.FormattedValue.value);
3245
Eric V. Smitha78c7952015-11-03 12:45:05 -05003246 switch (e->v.FormattedValue.conversion) {
3247 case 's': oparg = FVC_STR; break;
3248 case 'r': oparg = FVC_REPR; break;
3249 case 'a': oparg = FVC_ASCII; break;
3250 case -1: oparg = FVC_NONE; break;
3251 default:
3252 PyErr_SetString(PyExc_SystemError,
3253 "Unrecognized conversion character");
3254 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003255 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003256 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003257 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003258 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003259 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003260 }
3261
Eric V. Smitha78c7952015-11-03 12:45:05 -05003262 /* And push our opcode and oparg */
3263 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003264 return 1;
3265}
3266
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003267/* shared code between compiler_call and compiler_class */
3268static int
3269compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003270 Py_ssize_t n, /* Args already pushed */
3271 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003272 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 int code = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003275 Py_ssize_t nelts, i, nseen, nkw;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003276
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003277 /* the number of tuples and dictionaries on the stack */
3278 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3279
3280 nkw = 0;
3281 nseen = 0; /* the number of positional arguments on the stack */
3282 nelts = asdl_seq_LEN(args);
3283 for (i = 0; i < nelts; i++) {
3284 expr_ty elt = asdl_seq_GET(args, i);
3285 if (elt->kind == Starred_kind) {
3286 /* A star-arg. If we've seen positional arguments,
3287 pack the positional arguments into a
3288 tuple. */
3289 if (nseen) {
3290 ADDOP_I(c, BUILD_TUPLE, nseen);
3291 nseen = 0;
3292 nsubargs++;
3293 }
3294 VISIT(c, expr, elt->v.Starred.value);
3295 nsubargs++;
3296 }
3297 else if (nsubargs) {
3298 /* We've seen star-args already, so we
3299 count towards items-to-pack-into-tuple. */
3300 VISIT(c, expr, elt);
3301 nseen++;
3302 }
3303 else {
3304 /* Positional arguments before star-arguments
3305 are left on the stack. */
3306 VISIT(c, expr, elt);
3307 n++;
3308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003310 if (nseen) {
3311 /* Pack up any trailing positional arguments. */
3312 ADDOP_I(c, BUILD_TUPLE, nseen);
3313 nsubargs++;
3314 }
3315 if (nsubargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 code |= 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003317 if (nsubargs > 1) {
3318 /* If we ended up with more than one stararg, we need
3319 to concatenate them into a single sequence. */
3320 ADDOP_I(c, BUILD_LIST_UNPACK, nsubargs);
3321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003323
3324 /* Same dance again for keyword arguments */
3325 nseen = 0; /* the number of keyword arguments on the stack following */
3326 nelts = asdl_seq_LEN(keywords);
3327 for (i = 0; i < nelts; i++) {
3328 keyword_ty kw = asdl_seq_GET(keywords, i);
3329 if (kw->arg == NULL) {
3330 /* A keyword argument unpacking. */
3331 if (nseen) {
3332 ADDOP_I(c, BUILD_MAP, nseen);
3333 nseen = 0;
3334 nsubkwargs++;
3335 }
3336 VISIT(c, expr, kw->value);
3337 nsubkwargs++;
3338 }
3339 else if (nsubkwargs) {
3340 /* A keyword argument and we already have a dict. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003341 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
Benjamin Petersonee853392015-05-28 14:30:26 -05003342 VISIT(c, expr, kw->value);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003343 nseen++;
3344 }
3345 else {
3346 /* keyword argument */
3347 VISIT(c, keyword, kw)
3348 nkw++;
3349 }
3350 }
3351 if (nseen) {
3352 /* Pack up any trailing keyword arguments. */
3353 ADDOP_I(c, BUILD_MAP, nseen);
3354 nsubkwargs++;
3355 }
3356 if (nsubkwargs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 code |= 2;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003358 if (nsubkwargs > 1) {
3359 /* Pack it all up */
3360 int function_pos = n + (code & 1) + nkw + 1;
3361 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
3362 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003364 assert(n < 1<<8);
3365 assert(nkw < 1<<24);
3366 n |= nkw << 8;
3367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 switch (code) {
3369 case 0:
3370 ADDOP_I(c, CALL_FUNCTION, n);
3371 break;
3372 case 1:
3373 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3374 break;
3375 case 2:
3376 ADDOP_I(c, CALL_FUNCTION_KW, n);
3377 break;
3378 case 3:
3379 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3380 break;
3381 }
3382 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383}
3384
Nick Coghlan650f0d02007-04-15 12:05:43 +00003385
3386/* List and set comprehensions and generator expressions work by creating a
3387 nested function to perform the actual iteration. This means that the
3388 iteration variables don't leak into the current scope.
3389 The defined function is called immediately following its definition, with the
3390 result of that call being the result of the expression.
3391 The LC/SC version returns the populated container, while the GE version is
3392 flagged in symtable.c as a generator, so it returns the generator object
3393 when the function is called.
3394 This code *knows* that the loop cannot contain break, continue, or return,
3395 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3396
3397 Possible cleanups:
3398 - iterate over the generator sequence instead of using recursion
3399*/
3400
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402compiler_comprehension_generator(struct compiler *c,
3403 asdl_seq *generators, int gen_index,
3404 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* generate code for the iterator, then each of the ifs,
3407 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 comprehension_ty gen;
3410 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003411 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 start = compiler_new_block(c);
3414 skip = compiler_new_block(c);
3415 if_cleanup = compiler_new_block(c);
3416 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3419 anchor == NULL)
3420 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 if (gen_index == 0) {
3425 /* Receive outermost iter as an implicit argument */
3426 c->u->u_argcount = 1;
3427 ADDOP_I(c, LOAD_FAST, 0);
3428 }
3429 else {
3430 /* Sub-iter - calculate on the fly */
3431 VISIT(c, expr, gen->iter);
3432 ADDOP(c, GET_ITER);
3433 }
3434 compiler_use_next_block(c, start);
3435 ADDOP_JREL(c, FOR_ITER, anchor);
3436 NEXT_BLOCK(c);
3437 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 /* XXX this needs to be cleaned up...a lot! */
3440 n = asdl_seq_LEN(gen->ifs);
3441 for (i = 0; i < n; i++) {
3442 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3443 VISIT(c, expr, e);
3444 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3445 NEXT_BLOCK(c);
3446 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 if (++gen_index < asdl_seq_LEN(generators))
3449 if (!compiler_comprehension_generator(c,
3450 generators, gen_index,
3451 elt, val, type))
3452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 /* only append after the last for generator */
3455 if (gen_index >= asdl_seq_LEN(generators)) {
3456 /* comprehension specific code */
3457 switch (type) {
3458 case COMP_GENEXP:
3459 VISIT(c, expr, elt);
3460 ADDOP(c, YIELD_VALUE);
3461 ADDOP(c, POP_TOP);
3462 break;
3463 case COMP_LISTCOMP:
3464 VISIT(c, expr, elt);
3465 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3466 break;
3467 case COMP_SETCOMP:
3468 VISIT(c, expr, elt);
3469 ADDOP_I(c, SET_ADD, gen_index + 1);
3470 break;
3471 case COMP_DICTCOMP:
3472 /* With 'd[k] = v', v is evaluated before k, so we do
3473 the same. */
3474 VISIT(c, expr, val);
3475 VISIT(c, expr, elt);
3476 ADDOP_I(c, MAP_ADD, gen_index + 1);
3477 break;
3478 default:
3479 return 0;
3480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 compiler_use_next_block(c, skip);
3483 }
3484 compiler_use_next_block(c, if_cleanup);
3485 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3486 compiler_use_next_block(c, anchor);
3487
3488 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489}
3490
3491static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003492compiler_comprehension(struct compiler *c, expr_ty e, int type,
3493 identifier name, asdl_seq *generators, expr_ty elt,
3494 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 PyCodeObject *co = NULL;
3497 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003498 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 outermost_iter = ((comprehension_ty)
3501 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003502
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003503 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3504 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 if (type != COMP_GENEXP) {
3508 int op;
3509 switch (type) {
3510 case COMP_LISTCOMP:
3511 op = BUILD_LIST;
3512 break;
3513 case COMP_SETCOMP:
3514 op = BUILD_SET;
3515 break;
3516 case COMP_DICTCOMP:
3517 op = BUILD_MAP;
3518 break;
3519 default:
3520 PyErr_Format(PyExc_SystemError,
3521 "unknown comprehension type %d", type);
3522 goto error_in_scope;
3523 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 ADDOP_I(c, op, 0);
3526 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 if (!compiler_comprehension_generator(c, generators, 0, elt,
3529 val, type))
3530 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 if (type != COMP_GENEXP) {
3533 ADDOP(c, RETURN_VALUE);
3534 }
3535
3536 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003537 qualname = c->u->u_qualname;
3538 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003540 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 goto error;
3542
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003543 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003545 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 Py_DECREF(co);
3547
3548 VISIT(c, expr, outermost_iter);
3549 ADDOP(c, GET_ITER);
3550 ADDOP_I(c, CALL_FUNCTION, 1);
3551 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003552error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003554error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003555 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 Py_XDECREF(co);
3557 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003558}
3559
3560static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561compiler_genexp(struct compiler *c, expr_ty e)
3562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 static identifier name;
3564 if (!name) {
3565 name = PyUnicode_FromString("<genexpr>");
3566 if (!name)
3567 return 0;
3568 }
3569 assert(e->kind == GeneratorExp_kind);
3570 return compiler_comprehension(c, e, COMP_GENEXP, name,
3571 e->v.GeneratorExp.generators,
3572 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573}
3574
3575static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003576compiler_listcomp(struct compiler *c, expr_ty e)
3577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 static identifier name;
3579 if (!name) {
3580 name = PyUnicode_FromString("<listcomp>");
3581 if (!name)
3582 return 0;
3583 }
3584 assert(e->kind == ListComp_kind);
3585 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3586 e->v.ListComp.generators,
3587 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003588}
3589
3590static int
3591compiler_setcomp(struct compiler *c, expr_ty e)
3592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 static identifier name;
3594 if (!name) {
3595 name = PyUnicode_FromString("<setcomp>");
3596 if (!name)
3597 return 0;
3598 }
3599 assert(e->kind == SetComp_kind);
3600 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3601 e->v.SetComp.generators,
3602 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003603}
3604
3605
3606static int
3607compiler_dictcomp(struct compiler *c, expr_ty e)
3608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 static identifier name;
3610 if (!name) {
3611 name = PyUnicode_FromString("<dictcomp>");
3612 if (!name)
3613 return 0;
3614 }
3615 assert(e->kind == DictComp_kind);
3616 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3617 e->v.DictComp.generators,
3618 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003619}
3620
3621
3622static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623compiler_visit_keyword(struct compiler *c, keyword_ty k)
3624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3626 VISIT(c, expr, k->value);
3627 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628}
3629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 whether they are true or false.
3632
3633 Return values: 1 for true, 0 for false, -1 for non-constant.
3634 */
3635
3636static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003637expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 char *id;
3640 switch (e->kind) {
3641 case Ellipsis_kind:
3642 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003643 case Constant_kind:
3644 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 case Num_kind:
3646 return PyObject_IsTrue(e->v.Num.n);
3647 case Str_kind:
3648 return PyObject_IsTrue(e->v.Str.s);
3649 case Name_kind:
3650 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003651 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003652 if (id && strcmp(id, "__debug__") == 0)
3653 return !c->c_optimize;
3654 return -1;
3655 case NameConstant_kind: {
3656 PyObject *o = e->v.NameConstant.value;
3657 if (o == Py_None)
3658 return 0;
3659 else if (o == Py_True)
3660 return 1;
3661 else if (o == Py_False)
3662 return 0;
3663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 default:
3665 return -1;
3666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667}
3668
Yury Selivanov75445082015-05-11 22:57:16 -04003669
3670/*
3671 Implements the async with statement.
3672
3673 The semantics outlined in that PEP are as follows:
3674
3675 async with EXPR as VAR:
3676 BLOCK
3677
3678 It is implemented roughly as:
3679
3680 context = EXPR
3681 exit = context.__aexit__ # not calling it
3682 value = await context.__aenter__()
3683 try:
3684 VAR = value # if VAR present in the syntax
3685 BLOCK
3686 finally:
3687 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003688 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04003689 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03003690 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04003691 if not (await exit(*exc)):
3692 raise
3693 */
3694static int
3695compiler_async_with(struct compiler *c, stmt_ty s, int pos)
3696{
3697 basicblock *block, *finally;
3698 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
3699
3700 assert(s->kind == AsyncWith_kind);
3701
3702 block = compiler_new_block(c);
3703 finally = compiler_new_block(c);
3704 if (!block || !finally)
3705 return 0;
3706
3707 /* Evaluate EXPR */
3708 VISIT(c, expr, item->context_expr);
3709
3710 ADDOP(c, BEFORE_ASYNC_WITH);
3711 ADDOP(c, GET_AWAITABLE);
3712 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3713 ADDOP(c, YIELD_FROM);
3714
3715 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
3716
3717 /* SETUP_ASYNC_WITH pushes a finally block. */
3718 compiler_use_next_block(c, block);
3719 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3720 return 0;
3721 }
3722
3723 if (item->optional_vars) {
3724 VISIT(c, expr, item->optional_vars);
3725 }
3726 else {
3727 /* Discard result from context.__aenter__() */
3728 ADDOP(c, POP_TOP);
3729 }
3730
3731 pos++;
3732 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
3733 /* BLOCK code */
3734 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
3735 else if (!compiler_async_with(c, s, pos))
3736 return 0;
3737
3738 /* End of try block; start the finally block */
3739 ADDOP(c, POP_BLOCK);
3740 compiler_pop_fblock(c, FINALLY_TRY, block);
3741
3742 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3743 compiler_use_next_block(c, finally);
3744 if (!compiler_push_fblock(c, FINALLY_END, finally))
3745 return 0;
3746
3747 /* Finally block starts; context.__exit__ is on the stack under
3748 the exception or return information. Just issue our magic
3749 opcode. */
3750 ADDOP(c, WITH_CLEANUP_START);
3751
3752 ADDOP(c, GET_AWAITABLE);
3753 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3754 ADDOP(c, YIELD_FROM);
3755
3756 ADDOP(c, WITH_CLEANUP_FINISH);
3757
3758 /* Finally block ends. */
3759 ADDOP(c, END_FINALLY);
3760 compiler_pop_fblock(c, FINALLY_END, finally);
3761 return 1;
3762}
3763
3764
Guido van Rossumc2e20742006-02-27 22:32:47 +00003765/*
3766 Implements the with statement from PEP 343.
3767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003769
3770 with EXPR as VAR:
3771 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772
Guido van Rossumc2e20742006-02-27 22:32:47 +00003773 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774
Thomas Wouters477c8d52006-05-27 19:21:47 +00003775 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003776 exit = context.__exit__ # not calling it
3777 value = context.__enter__()
3778 try:
3779 VAR = value # if VAR present in the syntax
3780 BLOCK
3781 finally:
3782 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003783 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003784 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03003785 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003786 exit(*exc)
3787 */
3788static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003789compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003790{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003791 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003792 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003793
3794 assert(s->kind == With_kind);
3795
Guido van Rossumc2e20742006-02-27 22:32:47 +00003796 block = compiler_new_block(c);
3797 finally = compiler_new_block(c);
3798 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003799 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003800
Thomas Wouters477c8d52006-05-27 19:21:47 +00003801 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003802 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003803 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003804
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003805 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003806 compiler_use_next_block(c, block);
3807 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003808 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003809 }
3810
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003811 if (item->optional_vars) {
3812 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003813 }
3814 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003816 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003817 }
3818
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003819 pos++;
3820 if (pos == asdl_seq_LEN(s->v.With.items))
3821 /* BLOCK code */
3822 VISIT_SEQ(c, stmt, s->v.With.body)
3823 else if (!compiler_with(c, s, pos))
3824 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003825
3826 /* End of try block; start the finally block */
3827 ADDOP(c, POP_BLOCK);
3828 compiler_pop_fblock(c, FINALLY_TRY, block);
3829
3830 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3831 compiler_use_next_block(c, finally);
3832 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003834
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003835 /* Finally block starts; context.__exit__ is on the stack under
3836 the exception or return information. Just issue our magic
3837 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04003838 ADDOP(c, WITH_CLEANUP_START);
3839 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003840
3841 /* Finally block ends. */
3842 ADDOP(c, END_FINALLY);
3843 compiler_pop_fblock(c, FINALLY_END, finally);
3844 return 1;
3845}
3846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847static int
3848compiler_visit_expr(struct compiler *c, expr_ty e)
3849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 /* If expr e has a different line number than the last expr/stmt,
3851 set a new line number for the next instruction.
3852 */
3853 if (e->lineno > c->u->u_lineno) {
3854 c->u->u_lineno = e->lineno;
3855 c->u->u_lineno_set = 0;
3856 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003857 /* Updating the column offset is always harmless. */
3858 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 switch (e->kind) {
3860 case BoolOp_kind:
3861 return compiler_boolop(c, e);
3862 case BinOp_kind:
3863 VISIT(c, expr, e->v.BinOp.left);
3864 VISIT(c, expr, e->v.BinOp.right);
3865 ADDOP(c, binop(c, e->v.BinOp.op));
3866 break;
3867 case UnaryOp_kind:
3868 VISIT(c, expr, e->v.UnaryOp.operand);
3869 ADDOP(c, unaryop(e->v.UnaryOp.op));
3870 break;
3871 case Lambda_kind:
3872 return compiler_lambda(c, e);
3873 case IfExp_kind:
3874 return compiler_ifexp(c, e);
3875 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003876 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003878 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 case GeneratorExp_kind:
3880 return compiler_genexp(c, e);
3881 case ListComp_kind:
3882 return compiler_listcomp(c, e);
3883 case SetComp_kind:
3884 return compiler_setcomp(c, e);
3885 case DictComp_kind:
3886 return compiler_dictcomp(c, e);
3887 case Yield_kind:
3888 if (c->u->u_ste->ste_type != FunctionBlock)
3889 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003890 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3891 return compiler_error(c, "'yield' inside async function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003892 if (e->v.Yield.value) {
3893 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 }
3895 else {
3896 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3897 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003898 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003900 case YieldFrom_kind:
3901 if (c->u->u_ste->ste_type != FunctionBlock)
3902 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04003903
3904 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
3905 return compiler_error(c, "'yield from' inside async function");
3906
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003907 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04003908 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003909 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3910 ADDOP(c, YIELD_FROM);
3911 break;
Yury Selivanov75445082015-05-11 22:57:16 -04003912 case Await_kind:
3913 if (c->u->u_ste->ste_type != FunctionBlock)
3914 return compiler_error(c, "'await' outside function");
3915
Yury Selivanov9dec0352015-06-30 12:49:04 -04003916 if (c->u->u_scope_type == COMPILER_SCOPE_COMPREHENSION)
3917 return compiler_error(
3918 c, "'await' expressions in comprehensions are not supported");
3919
Yury Selivanov75445082015-05-11 22:57:16 -04003920 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION)
3921 return compiler_error(c, "'await' outside async function");
3922
3923 VISIT(c, expr, e->v.Await.value);
3924 ADDOP(c, GET_AWAITABLE);
3925 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3926 ADDOP(c, YIELD_FROM);
3927 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 case Compare_kind:
3929 return compiler_compare(c, e);
3930 case Call_kind:
3931 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003932 case Constant_kind:
3933 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
3934 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 case Num_kind:
3936 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3937 break;
3938 case Str_kind:
3939 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3940 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003941 case JoinedStr_kind:
3942 return compiler_joined_str(c, e);
3943 case FormattedValue_kind:
3944 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 case Bytes_kind:
3946 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3947 break;
3948 case Ellipsis_kind:
3949 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3950 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003951 case NameConstant_kind:
3952 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3953 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 /* The following exprs can be assignment targets. */
3955 case Attribute_kind:
3956 if (e->v.Attribute.ctx != AugStore)
3957 VISIT(c, expr, e->v.Attribute.value);
3958 switch (e->v.Attribute.ctx) {
3959 case AugLoad:
3960 ADDOP(c, DUP_TOP);
3961 /* Fall through to load */
3962 case Load:
3963 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3964 break;
3965 case AugStore:
3966 ADDOP(c, ROT_TWO);
3967 /* Fall through to save */
3968 case Store:
3969 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3970 break;
3971 case Del:
3972 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3973 break;
3974 case Param:
3975 default:
3976 PyErr_SetString(PyExc_SystemError,
3977 "param invalid in attribute expression");
3978 return 0;
3979 }
3980 break;
3981 case Subscript_kind:
3982 switch (e->v.Subscript.ctx) {
3983 case AugLoad:
3984 VISIT(c, expr, e->v.Subscript.value);
3985 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3986 break;
3987 case Load:
3988 VISIT(c, expr, e->v.Subscript.value);
3989 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3990 break;
3991 case AugStore:
3992 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3993 break;
3994 case Store:
3995 VISIT(c, expr, e->v.Subscript.value);
3996 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3997 break;
3998 case Del:
3999 VISIT(c, expr, e->v.Subscript.value);
4000 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4001 break;
4002 case Param:
4003 default:
4004 PyErr_SetString(PyExc_SystemError,
4005 "param invalid in subscript expression");
4006 return 0;
4007 }
4008 break;
4009 case Starred_kind:
4010 switch (e->v.Starred.ctx) {
4011 case Store:
4012 /* In all legitimate cases, the Starred node was already replaced
4013 * by compiler_list/compiler_tuple. XXX: is that okay? */
4014 return compiler_error(c,
4015 "starred assignment target must be in a list or tuple");
4016 default:
4017 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004018 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 }
4020 break;
4021 case Name_kind:
4022 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4023 /* child nodes of List and Tuple will have expr_context set */
4024 case List_kind:
4025 return compiler_list(c, e);
4026 case Tuple_kind:
4027 return compiler_tuple(c, e);
4028 }
4029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030}
4031
4032static int
4033compiler_augassign(struct compiler *c, stmt_ty s)
4034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 expr_ty e = s->v.AugAssign.target;
4036 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 switch (e->kind) {
4041 case Attribute_kind:
4042 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4043 AugLoad, e->lineno, e->col_offset, c->c_arena);
4044 if (auge == NULL)
4045 return 0;
4046 VISIT(c, expr, auge);
4047 VISIT(c, expr, s->v.AugAssign.value);
4048 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4049 auge->v.Attribute.ctx = AugStore;
4050 VISIT(c, expr, auge);
4051 break;
4052 case Subscript_kind:
4053 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4054 AugLoad, e->lineno, e->col_offset, c->c_arena);
4055 if (auge == NULL)
4056 return 0;
4057 VISIT(c, expr, auge);
4058 VISIT(c, expr, s->v.AugAssign.value);
4059 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4060 auge->v.Subscript.ctx = AugStore;
4061 VISIT(c, expr, auge);
4062 break;
4063 case Name_kind:
4064 if (!compiler_nameop(c, e->v.Name.id, Load))
4065 return 0;
4066 VISIT(c, expr, s->v.AugAssign.value);
4067 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4068 return compiler_nameop(c, e->v.Name.id, Store);
4069 default:
4070 PyErr_Format(PyExc_SystemError,
4071 "invalid node type (%d) for augmented assignment",
4072 e->kind);
4073 return 0;
4074 }
4075 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004076}
4077
4078static int
4079compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 struct fblockinfo *f;
4082 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
4083 PyErr_SetString(PyExc_SystemError,
4084 "too many statically nested blocks");
4085 return 0;
4086 }
4087 f = &c->u->u_fblock[c->u->u_nfblocks++];
4088 f->fb_type = t;
4089 f->fb_block = b;
4090 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004091}
4092
4093static void
4094compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 struct compiler_unit *u = c->u;
4097 assert(u->u_nfblocks > 0);
4098 u->u_nfblocks--;
4099 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4100 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101}
4102
Thomas Wouters89f507f2006-12-13 04:49:30 +00004103static int
4104compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 int i;
4106 struct compiler_unit *u = c->u;
4107 for (i = 0; i < u->u_nfblocks; ++i) {
4108 if (u->u_fblock[i].fb_type == LOOP)
4109 return 1;
4110 }
4111 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004112}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113/* Raises a SyntaxError and returns 0.
4114 If something goes wrong, a different exception may be raised.
4115*/
4116
4117static int
4118compiler_error(struct compiler *c, const char *errstr)
4119{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004120 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122
Victor Stinner14e461d2013-08-26 22:28:21 +02004123 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 if (!loc) {
4125 Py_INCREF(Py_None);
4126 loc = Py_None;
4127 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004128 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004129 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 if (!u)
4131 goto exit;
4132 v = Py_BuildValue("(zO)", errstr, u);
4133 if (!v)
4134 goto exit;
4135 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004136 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 Py_DECREF(loc);
4138 Py_XDECREF(u);
4139 Py_XDECREF(v);
4140 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141}
4142
4143static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144compiler_handle_subscr(struct compiler *c, const char *kind,
4145 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 /* XXX this code is duplicated */
4150 switch (ctx) {
4151 case AugLoad: /* fall through to Load */
4152 case Load: op = BINARY_SUBSCR; break;
4153 case AugStore:/* fall through to Store */
4154 case Store: op = STORE_SUBSCR; break;
4155 case Del: op = DELETE_SUBSCR; break;
4156 case Param:
4157 PyErr_Format(PyExc_SystemError,
4158 "invalid %s kind %d in subscript\n",
4159 kind, ctx);
4160 return 0;
4161 }
4162 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004163 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 }
4165 else if (ctx == AugStore) {
4166 ADDOP(c, ROT_THREE);
4167 }
4168 ADDOP(c, op);
4169 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170}
4171
4172static int
4173compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 int n = 2;
4176 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 /* only handles the cases where BUILD_SLICE is emitted */
4179 if (s->v.Slice.lower) {
4180 VISIT(c, expr, s->v.Slice.lower);
4181 }
4182 else {
4183 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4184 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (s->v.Slice.upper) {
4187 VISIT(c, expr, s->v.Slice.upper);
4188 }
4189 else {
4190 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4191 }
4192
4193 if (s->v.Slice.step) {
4194 n++;
4195 VISIT(c, expr, s->v.Slice.step);
4196 }
4197 ADDOP_I(c, BUILD_SLICE, n);
4198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199}
4200
4201static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4203 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 switch (s->kind) {
4206 case Slice_kind:
4207 return compiler_slice(c, s, ctx);
4208 case Index_kind:
4209 VISIT(c, expr, s->v.Index.value);
4210 break;
4211 case ExtSlice_kind:
4212 default:
4213 PyErr_SetString(PyExc_SystemError,
4214 "extended slice invalid in nested slice");
4215 return 0;
4216 }
4217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218}
4219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220static int
4221compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 char * kindname = NULL;
4224 switch (s->kind) {
4225 case Index_kind:
4226 kindname = "index";
4227 if (ctx != AugStore) {
4228 VISIT(c, expr, s->v.Index.value);
4229 }
4230 break;
4231 case Slice_kind:
4232 kindname = "slice";
4233 if (ctx != AugStore) {
4234 if (!compiler_slice(c, s, ctx))
4235 return 0;
4236 }
4237 break;
4238 case ExtSlice_kind:
4239 kindname = "extended slice";
4240 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004241 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 for (i = 0; i < n; i++) {
4243 slice_ty sub = (slice_ty)asdl_seq_GET(
4244 s->v.ExtSlice.dims, i);
4245 if (!compiler_visit_nested_slice(c, sub, ctx))
4246 return 0;
4247 }
4248 ADDOP_I(c, BUILD_TUPLE, n);
4249 }
4250 break;
4251 default:
4252 PyErr_Format(PyExc_SystemError,
4253 "invalid subscript kind %d", s->kind);
4254 return 0;
4255 }
4256 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257}
4258
Thomas Wouters89f507f2006-12-13 04:49:30 +00004259/* End of the compiler section, beginning of the assembler section */
4260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004261/* do depth-first search of basic block graph, starting with block.
4262 post records the block indices in post-order.
4263
4264 XXX must handle implicit jumps from one block to next
4265*/
4266
Thomas Wouters89f507f2006-12-13 04:49:30 +00004267struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 PyObject *a_bytecode; /* string containing bytecode */
4269 int a_offset; /* offset into bytecode */
4270 int a_nblocks; /* number of reachable blocks */
4271 basicblock **a_postorder; /* list of blocks in dfs postorder */
4272 PyObject *a_lnotab; /* string containing lnotab */
4273 int a_lnotab_off; /* offset into lnotab */
4274 int a_lineno; /* last lineno of emitted instruction */
4275 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004276};
4277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004278static void
4279dfs(struct compiler *c, basicblock *b, struct assembler *a)
4280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 int i;
4282 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 if (b->b_seen)
4285 return;
4286 b->b_seen = 1;
4287 if (b->b_next != NULL)
4288 dfs(c, b->b_next, a);
4289 for (i = 0; i < b->b_iused; i++) {
4290 instr = &b->b_instr[i];
4291 if (instr->i_jrel || instr->i_jabs)
4292 dfs(c, instr->i_target, a);
4293 }
4294 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295}
4296
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004297static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004298stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4299{
Larry Hastings3a907972013-11-23 14:49:22 -08004300 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 struct instr *instr;
4302 if (b->b_seen || b->b_startdepth >= depth)
4303 return maxdepth;
4304 b->b_seen = 1;
4305 b->b_startdepth = depth;
4306 for (i = 0; i < b->b_iused; i++) {
4307 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004308 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4309 if (effect == PY_INVALID_STACK_EFFECT) {
4310 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4311 Py_FatalError("PyCompile_OpcodeStackEffect()");
4312 }
4313 depth += effect;
4314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 if (depth > maxdepth)
4316 maxdepth = depth;
4317 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4318 if (instr->i_jrel || instr->i_jabs) {
4319 target_depth = depth;
4320 if (instr->i_opcode == FOR_ITER) {
4321 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004322 }
4323 else if (instr->i_opcode == SETUP_FINALLY ||
4324 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 target_depth = depth+3;
4326 if (target_depth > maxdepth)
4327 maxdepth = target_depth;
4328 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004329 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4330 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4331 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 maxdepth = stackdepth_walk(c, instr->i_target,
4333 target_depth, maxdepth);
4334 if (instr->i_opcode == JUMP_ABSOLUTE ||
4335 instr->i_opcode == JUMP_FORWARD) {
4336 goto out; /* remaining code is dead */
4337 }
4338 }
4339 }
4340 if (b->b_next)
4341 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 b->b_seen = 0;
4344 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004345}
4346
4347/* Find the flow path that needs the largest stack. We assume that
4348 * cycles in the flow graph have no net effect on the stack depth.
4349 */
4350static int
4351stackdepth(struct compiler *c)
4352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 basicblock *b, *entryblock;
4354 entryblock = NULL;
4355 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4356 b->b_seen = 0;
4357 b->b_startdepth = INT_MIN;
4358 entryblock = b;
4359 }
4360 if (!entryblock)
4361 return 0;
4362 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004363}
4364
4365static int
4366assemble_init(struct assembler *a, int nblocks, int firstlineno)
4367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 memset(a, 0, sizeof(struct assembler));
4369 a->a_lineno = firstlineno;
4370 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4371 if (!a->a_bytecode)
4372 return 0;
4373 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4374 if (!a->a_lnotab)
4375 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01004376 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 PyErr_NoMemory();
4378 return 0;
4379 }
4380 a->a_postorder = (basicblock **)PyObject_Malloc(
4381 sizeof(basicblock *) * nblocks);
4382 if (!a->a_postorder) {
4383 PyErr_NoMemory();
4384 return 0;
4385 }
4386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387}
4388
4389static void
4390assemble_free(struct assembler *a)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 Py_XDECREF(a->a_bytecode);
4393 Py_XDECREF(a->a_lnotab);
4394 if (a->a_postorder)
4395 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004396}
4397
4398/* Return the size of a basic block in bytes. */
4399
4400static int
4401instrsize(struct instr *instr)
4402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 if (!instr->i_hasarg)
4404 return 1; /* 1 byte for the opcode*/
4405 if (instr->i_oparg > 0xffff)
4406 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
4407 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408}
4409
4410static int
4411blocksize(basicblock *b)
4412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 int i;
4414 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 for (i = 0; i < b->b_iused; i++)
4417 size += instrsize(&b->b_instr[i]);
4418 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419}
4420
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004421/* Appends a pair to the end of the line number table, a_lnotab, representing
4422 the instruction's bytecode offset and line number. See
4423 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004424
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004425static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004429 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 d_bytecode = a->a_offset - a->a_lineno_off;
4433 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 if(d_bytecode == 0 && d_lineno == 0)
4438 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 if (d_bytecode > 255) {
4441 int j, nbytes, ncodes = d_bytecode / 255;
4442 nbytes = a->a_lnotab_off + 2 * ncodes;
4443 len = PyBytes_GET_SIZE(a->a_lnotab);
4444 if (nbytes >= len) {
4445 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
4446 len = nbytes;
4447 else if (len <= INT_MAX / 2)
4448 len *= 2;
4449 else {
4450 PyErr_NoMemory();
4451 return 0;
4452 }
4453 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4454 return 0;
4455 }
4456 lnotab = (unsigned char *)
4457 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4458 for (j = 0; j < ncodes; j++) {
4459 *lnotab++ = 255;
4460 *lnotab++ = 0;
4461 }
4462 d_bytecode -= ncodes * 255;
4463 a->a_lnotab_off += ncodes * 2;
4464 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004465 assert(0 <= d_bytecode && d_bytecode <= 255);
4466
4467 if (d_lineno < -128 || 127 < d_lineno) {
4468 int j, nbytes, ncodes, k;
4469 if (d_lineno < 0) {
4470 k = -128;
4471 /* use division on positive numbers */
4472 ncodes = (-d_lineno) / 128;
4473 }
4474 else {
4475 k = 127;
4476 ncodes = d_lineno / 127;
4477 }
4478 d_lineno -= ncodes * k;
4479 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 nbytes = a->a_lnotab_off + 2 * ncodes;
4481 len = PyBytes_GET_SIZE(a->a_lnotab);
4482 if (nbytes >= len) {
4483 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4484 len = nbytes;
4485 else if (len <= INT_MAX / 2)
4486 len *= 2;
4487 else {
4488 PyErr_NoMemory();
4489 return 0;
4490 }
4491 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4492 return 0;
4493 }
4494 lnotab = (unsigned char *)
4495 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4496 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004497 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 d_bytecode = 0;
4499 for (j = 1; j < ncodes; j++) {
4500 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004501 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 a->a_lnotab_off += ncodes * 2;
4504 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01004505 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 len = PyBytes_GET_SIZE(a->a_lnotab);
4508 if (a->a_lnotab_off + 2 >= len) {
4509 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4510 return 0;
4511 }
4512 lnotab = (unsigned char *)
4513 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 a->a_lnotab_off += 2;
4516 if (d_bytecode) {
4517 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004518 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 }
4520 else { /* First line of a block; def stmt, etc. */
4521 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004522 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 }
4524 a->a_lineno = i->i_lineno;
4525 a->a_lineno_off = a->a_offset;
4526 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004527}
4528
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004529/* assemble_emit()
4530 Extend the bytecode with a new instruction.
4531 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004532*/
4533
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004534static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004535assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 int size, arg = 0, ext = 0;
4538 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4539 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 size = instrsize(i);
4542 if (i->i_hasarg) {
4543 arg = i->i_oparg;
4544 ext = arg >> 16;
4545 }
4546 if (i->i_lineno && !assemble_lnotab(a, i))
4547 return 0;
4548 if (a->a_offset + size >= len) {
4549 if (len > PY_SSIZE_T_MAX / 2)
4550 return 0;
4551 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4552 return 0;
4553 }
4554 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4555 a->a_offset += size;
4556 if (size == 6) {
4557 assert(i->i_hasarg);
4558 *code++ = (char)EXTENDED_ARG;
4559 *code++ = ext & 0xff;
4560 *code++ = ext >> 8;
4561 arg &= 0xffff;
4562 }
4563 *code++ = i->i_opcode;
4564 if (i->i_hasarg) {
4565 assert(size == 3 || size == 6);
4566 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004567 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 }
4569 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004570}
4571
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004572static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004573assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 basicblock *b;
4576 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4577 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 /* Compute the size of each block and fixup jump args.
4580 Replace block pointer with position in bytecode. */
4581 do {
4582 totsize = 0;
4583 for (i = a->a_nblocks - 1; i >= 0; i--) {
4584 b = a->a_postorder[i];
4585 bsize = blocksize(b);
4586 b->b_offset = totsize;
4587 totsize += bsize;
4588 }
4589 last_extended_arg_count = extended_arg_count;
4590 extended_arg_count = 0;
4591 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4592 bsize = b->b_offset;
4593 for (i = 0; i < b->b_iused; i++) {
4594 struct instr *instr = &b->b_instr[i];
4595 /* Relative jumps are computed relative to
4596 the instruction pointer after fetching
4597 the jump instruction.
4598 */
4599 bsize += instrsize(instr);
4600 if (instr->i_jabs)
4601 instr->i_oparg = instr->i_target->b_offset;
4602 else if (instr->i_jrel) {
4603 int delta = instr->i_target->b_offset - bsize;
4604 instr->i_oparg = delta;
4605 }
4606 else
4607 continue;
4608 if (instr->i_oparg > 0xffff)
4609 extended_arg_count++;
4610 }
4611 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 /* XXX: This is an awful hack that could hurt performance, but
4614 on the bright side it should work until we come up
4615 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 The issue is that in the first loop blocksize() is called
4618 which calls instrsize() which requires i_oparg be set
4619 appropriately. There is a bootstrap problem because
4620 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 So we loop until we stop seeing new EXTENDED_ARGs.
4623 The only EXTENDED_ARGs that could be popping up are
4624 ones in jump instructions. So this should converge
4625 fairly quickly.
4626 */
4627 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004628}
4629
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004630static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004631dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 PyObject *tuple, *k, *v;
4634 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 tuple = PyTuple_New(size);
4637 if (tuple == NULL)
4638 return NULL;
4639 while (PyDict_Next(dict, &pos, &k, &v)) {
4640 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01004641 /* The keys of the dictionary are tuples. (see compiler_add_o
4642 * and _PyCode_ConstantKey). The object we want is always second,
4643 * though. */
4644 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 Py_INCREF(k);
4646 assert((i - offset) < size);
4647 assert((i - offset) >= 0);
4648 PyTuple_SET_ITEM(tuple, i - offset, k);
4649 }
4650 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004651}
4652
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004653static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004654compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004657 int flags = 0;
4658 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04004660 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 if (ste->ste_nested)
4662 flags |= CO_NESTED;
4663 if (ste->ste_generator)
4664 flags |= CO_GENERATOR;
4665 if (ste->ste_varargs)
4666 flags |= CO_VARARGS;
4667 if (ste->ste_varkeywords)
4668 flags |= CO_VARKEYWORDS;
4669 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 /* (Only) inherit compilerflags in PyCF_MASK */
4672 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 n = PyDict_Size(c->u->u_freevars);
4675 if (n < 0)
4676 return -1;
4677 if (n == 0) {
4678 n = PyDict_Size(c->u->u_cellvars);
4679 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004680 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004682 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 }
4684 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004687}
4688
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004689static PyCodeObject *
4690makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 PyObject *tmp;
4693 PyCodeObject *co = NULL;
4694 PyObject *consts = NULL;
4695 PyObject *names = NULL;
4696 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 PyObject *name = NULL;
4698 PyObject *freevars = NULL;
4699 PyObject *cellvars = NULL;
4700 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004701 Py_ssize_t nlocals;
4702 int nlocals_int;
4703 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004704 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 tmp = dict_keys_inorder(c->u->u_consts, 0);
4707 if (!tmp)
4708 goto error;
4709 consts = PySequence_List(tmp); /* optimize_code requires a list */
4710 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 names = dict_keys_inorder(c->u->u_names, 0);
4713 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4714 if (!consts || !names || !varnames)
4715 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4718 if (!cellvars)
4719 goto error;
4720 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4721 if (!freevars)
4722 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004725 assert(nlocals < INT_MAX);
4726 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 flags = compute_code_flags(c);
4729 if (flags < 0)
4730 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4733 if (!bytecode)
4734 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4737 if (!tmp)
4738 goto error;
4739 Py_DECREF(consts);
4740 consts = tmp;
4741
Victor Stinnerf8e32212013-11-19 23:56:34 +01004742 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4743 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4744 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004745 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 bytecode, consts, names, varnames,
4747 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004748 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 c->u->u_firstlineno,
4750 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004751 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 Py_XDECREF(consts);
4753 Py_XDECREF(names);
4754 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 Py_XDECREF(name);
4756 Py_XDECREF(freevars);
4757 Py_XDECREF(cellvars);
4758 Py_XDECREF(bytecode);
4759 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004760}
4761
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004762
4763/* For debugging purposes only */
4764#if 0
4765static void
4766dump_instr(const struct instr *i)
4767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 const char *jrel = i->i_jrel ? "jrel " : "";
4769 const char *jabs = i->i_jabs ? "jabs " : "";
4770 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 *arg = '\0';
4773 if (i->i_hasarg)
4774 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4777 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004778}
4779
4780static void
4781dump_basicblock(const basicblock *b)
4782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 const char *seen = b->b_seen ? "seen " : "";
4784 const char *b_return = b->b_return ? "return " : "";
4785 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4786 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4787 if (b->b_instr) {
4788 int i;
4789 for (i = 0; i < b->b_iused; i++) {
4790 fprintf(stderr, " [%02d] ", i);
4791 dump_instr(b->b_instr + i);
4792 }
4793 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004794}
4795#endif
4796
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004797static PyCodeObject *
4798assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 basicblock *b, *entryblock;
4801 struct assembler a;
4802 int i, j, nblocks;
4803 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 /* Make sure every block that falls off the end returns None.
4806 XXX NEXT_BLOCK() isn't quite right, because if the last
4807 block ends with a jump or return b_next shouldn't set.
4808 */
4809 if (!c->u->u_curblock->b_return) {
4810 NEXT_BLOCK(c);
4811 if (addNone)
4812 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4813 ADDOP(c, RETURN_VALUE);
4814 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 nblocks = 0;
4817 entryblock = NULL;
4818 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4819 nblocks++;
4820 entryblock = b;
4821 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 /* Set firstlineno if it wasn't explicitly set. */
4824 if (!c->u->u_firstlineno) {
4825 if (entryblock && entryblock->b_instr)
4826 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4827 else
4828 c->u->u_firstlineno = 1;
4829 }
4830 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4831 goto error;
4832 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 /* Can't modify the bytecode after computing jump offsets. */
4835 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 /* Emit code in reverse postorder from dfs. */
4838 for (i = a.a_nblocks - 1; i >= 0; i--) {
4839 b = a.a_postorder[i];
4840 for (j = 0; j < b->b_iused; j++)
4841 if (!assemble_emit(&a, &b->b_instr[j]))
4842 goto error;
4843 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4846 goto error;
4847 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4848 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004851 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 assemble_free(&a);
4853 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004854}
Georg Brandl8334fd92010-12-04 10:26:46 +00004855
4856#undef PyAST_Compile
4857PyAPI_FUNC(PyCodeObject *)
4858PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4859 PyArena *arena)
4860{
4861 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4862}