blob: cd039168ebace62a82545e81be80b3e9470027d7 [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"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 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);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200194static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700205static int compiler_sync_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
210static int compiler_async_comprehension_generator(
211 struct compiler *c,
212 asdl_seq *generators, int gen_index,
213 expr_ty elt, expr_ty val, int type);
214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static PyCodeObject *assemble(struct compiler *, int addNone);
216static PyObject *__doc__;
217
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400218#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Name mangling: __private becomes _classname__private.
224 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyObject *result;
226 size_t nlen, plen, ipriv;
227 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyUnicode_READ_CHAR(ident, 0) != '_' ||
230 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident;
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 nlen = PyUnicode_GET_LENGTH(ident);
235 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 The only time a name with a dot can occur is when
239 we are compiling an import statement that has a
240 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 TODO(jhylton): Decide whether we want to support
243 mangling of the module name, e.g. __M.X.
244 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
246 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
247 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_INCREF(ident);
249 return ident; /* Don't mangle __whatever__ */
250 }
251 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 ipriv = 0;
253 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
254 ipriv++;
255 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle if class is just underscores */
258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000260
Antoine Pitrou55bff892013-04-06 21:21:04 +0200261 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
262 PyErr_SetString(PyExc_OverflowError,
263 "private identifier too large to be mangled");
264 return NULL;
265 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
268 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
269 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
270
271 result = PyUnicode_New(1 + nlen + plen, maxchar);
272 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
275 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200276 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
280 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
Victor Stinner8f825062012-04-27 13:55:39 +0200284 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000286}
287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288static int
289compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 c->c_stack = PyList_New(0);
294 if (!c->c_stack)
295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200301PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
302 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 struct compiler c;
305 PyCodeObject *co = NULL;
306 PyCompilerFlags local_flags;
307 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!__doc__) {
310 __doc__ = PyUnicode_InternFromString("__doc__");
311 if (!__doc__)
312 return NULL;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200334 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900335 goto finally;
336 }
337
Victor Stinner14e461d2013-08-26 22:28:21 +0200338 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (c.c_st == NULL) {
340 if (!PyErr_Occurred())
341 PyErr_SetString(PyExc_SystemError, "no symtable");
342 goto finally;
343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000346
Thomas Wouters1175c432006-02-27 22:49:54 +0000347 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 compiler_free(&c);
349 assert(co || PyErr_Occurred());
350 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351}
352
353PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200354PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
355 int optimize, PyArena *arena)
356{
357 PyObject *filename;
358 PyCodeObject *co;
359 filename = PyUnicode_DecodeFSDefault(filename_str);
360 if (filename == NULL)
361 return NULL;
362 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
363 Py_DECREF(filename);
364 return co;
365
366}
367
368PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369PyNode_Compile(struct _node *n, const char *filename)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyCodeObject *co = NULL;
372 mod_ty mod;
373 PyArena *arena = PyArena_New();
374 if (!arena)
375 return NULL;
376 mod = PyAST_FromNode(n, NULL, filename, arena);
377 if (mod)
378 co = PyAST_Compile(mod, filename, NULL, arena);
379 PyArena_Free(arena);
380 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000381}
382
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000383static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (c->c_st)
387 PySymtable_Free(c->c_st);
388 if (c->c_future)
389 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200390 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000392}
393
Guido van Rossum79f25d91997-04-29 20:08:16 +0000394static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 Py_ssize_t i, n;
398 PyObject *v, *k;
399 PyObject *dict = PyDict_New();
400 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 n = PyList_Size(list);
403 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100404 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (!v) {
406 Py_DECREF(dict);
407 return NULL;
408 }
409 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100410 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
412 Py_XDECREF(k);
413 Py_DECREF(v);
414 Py_DECREF(dict);
415 return NULL;
416 }
417 Py_DECREF(k);
418 Py_DECREF(v);
419 }
420 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421}
422
423/* Return new dict containing names from src that match scope(s).
424
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000425src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000427values are integers, starting at offset and increasing by one for
428each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429*/
430
431static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100432dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700434 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500436 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 assert(offset >= 0);
439 if (dest == NULL)
440 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441
Meador Inge2ca63152012-07-18 14:20:11 -0500442 /* Sort the keys so that we have a deterministic order on the indexes
443 saved in the returned dictionary. These indexes are used as indexes
444 into the free and cell var storage. Therefore if they aren't
445 deterministic, then the generated bytecode is not deterministic.
446 */
447 sorted_keys = PyDict_Keys(src);
448 if (sorted_keys == NULL)
449 return NULL;
450 if (PyList_Sort(sorted_keys) != 0) {
451 Py_DECREF(sorted_keys);
452 return NULL;
453 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500454 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500455
456 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* XXX this should probably be a macro in symtable.h */
458 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500459 k = PyList_GET_ITEM(sorted_keys, key_i);
460 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 assert(PyLong_Check(v));
462 vi = PyLong_AS_LONG(v);
463 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100466 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500468 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_DECREF(dest);
470 return NULL;
471 }
472 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100473 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500475 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(item);
477 Py_DECREF(dest);
478 Py_XDECREF(tuple);
479 return NULL;
480 }
481 Py_DECREF(item);
482 Py_DECREF(tuple);
483 }
484 }
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000487}
488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000489static void
490compiler_unit_check(struct compiler_unit *u)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 basicblock *block;
493 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700494 assert((uintptr_t)block != 0xcbcbcbcbU);
495 assert((uintptr_t)block != 0xfbfbfbfbU);
496 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (block->b_instr != NULL) {
498 assert(block->b_ialloc > 0);
499 assert(block->b_iused > 0);
500 assert(block->b_ialloc >= block->b_iused);
501 }
502 else {
503 assert (block->b_iused == 0);
504 assert (block->b_ialloc == 0);
505 }
506 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507}
508
509static void
510compiler_unit_free(struct compiler_unit *u)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 compiler_unit_check(u);
515 b = u->u_blocks;
516 while (b != NULL) {
517 if (b->b_instr)
518 PyObject_Free((void *)b->b_instr);
519 next = b->b_list;
520 PyObject_Free((void *)b);
521 b = next;
522 }
523 Py_CLEAR(u->u_ste);
524 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400525 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 Py_CLEAR(u->u_consts);
527 Py_CLEAR(u->u_names);
528 Py_CLEAR(u->u_varnames);
529 Py_CLEAR(u->u_freevars);
530 Py_CLEAR(u->u_cellvars);
531 Py_CLEAR(u->u_private);
532 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533}
534
535static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100536compiler_enter_scope(struct compiler *c, identifier name,
537 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100540 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
543 struct compiler_unit));
544 if (!u) {
545 PyErr_NoMemory();
546 return 0;
547 }
548 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100549 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 u->u_argcount = 0;
551 u->u_kwonlyargcount = 0;
552 u->u_ste = PySymtable_Lookup(c->c_st, key);
553 if (!u->u_ste) {
554 compiler_unit_free(u);
555 return 0;
556 }
557 Py_INCREF(name);
558 u->u_name = name;
559 u->u_varnames = list2dict(u->u_ste->ste_varnames);
560 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
561 if (!u->u_varnames || !u->u_cellvars) {
562 compiler_unit_free(u);
563 return 0;
564 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000566 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500567 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300568 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 int res;
570 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200571 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 name = _PyUnicode_FromId(&PyId___class__);
573 if (!name) {
574 compiler_unit_free(u);
575 return 0;
576 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100577 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500578 if (!tuple) {
579 compiler_unit_free(u);
580 return 0;
581 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300582 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500583 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 if (res < 0) {
585 compiler_unit_free(u);
586 return 0;
587 }
588 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200591 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (!u->u_freevars) {
593 compiler_unit_free(u);
594 return 0;
595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 u->u_blocks = NULL;
598 u->u_nfblocks = 0;
599 u->u_firstlineno = lineno;
600 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000601 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 u->u_lineno_set = 0;
603 u->u_consts = PyDict_New();
604 if (!u->u_consts) {
605 compiler_unit_free(u);
606 return 0;
607 }
608 u->u_names = PyDict_New();
609 if (!u->u_names) {
610 compiler_unit_free(u);
611 return 0;
612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Push the old compiler_unit on the stack. */
617 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400618 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
620 Py_XDECREF(capsule);
621 compiler_unit_free(u);
622 return 0;
623 }
624 Py_DECREF(capsule);
625 u->u_private = c->u->u_private;
626 Py_XINCREF(u->u_private);
627 }
628 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631
632 block = compiler_new_block(c);
633 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100635 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400637 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
638 if (!compiler_set_qualname(c))
639 return 0;
640 }
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643}
644
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000645static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646compiler_exit_scope(struct compiler *c)
647{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100648 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c->c_nestlevel--;
652 compiler_unit_free(c->u);
653 /* Restore c->u to the parent unit. */
654 n = PyList_GET_SIZE(c->c_stack) - 1;
655 if (n >= 0) {
656 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400657 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 assert(c->u);
659 /* we are deleting from a list so this really shouldn't fail */
660 if (PySequence_DelItem(c->c_stack, n) < 0)
661 Py_FatalError("compiler_exit_scope()");
662 compiler_unit_check(c->u);
663 }
664 else
665 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667}
668
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669static int
670compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100672 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 _Py_static_string(dot_locals, ".<locals>");
674 Py_ssize_t stack_size;
675 struct compiler_unit *u = c->u;
676 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400680 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 if (stack_size > 1) {
682 int scope, force_global = 0;
683 struct compiler_unit *parent;
684 PyObject *mangled, *capsule;
685
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400686 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400687 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400688 assert(parent);
689
Yury Selivanov75445082015-05-11 22:57:16 -0400690 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
691 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
692 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400693 assert(u->u_name);
694 mangled = _Py_Mangle(parent->u_private, u->u_name);
695 if (!mangled)
696 return 0;
697 scope = PyST_GetScope(parent->u_ste, mangled);
698 Py_DECREF(mangled);
699 assert(scope != GLOBAL_IMPLICIT);
700 if (scope == GLOBAL_EXPLICIT)
701 force_global = 1;
702 }
703
704 if (!force_global) {
705 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400706 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400707 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
708 dot_locals_str = _PyUnicode_FromId(&dot_locals);
709 if (dot_locals_str == NULL)
710 return 0;
711 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
712 if (base == NULL)
713 return 0;
714 }
715 else {
716 Py_INCREF(parent->u_qualname);
717 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100719 }
720 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400721
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400722 if (base != NULL) {
723 dot_str = _PyUnicode_FromId(&dot);
724 if (dot_str == NULL) {
725 Py_DECREF(base);
726 return 0;
727 }
728 name = PyUnicode_Concat(base, dot_str);
729 Py_DECREF(base);
730 if (name == NULL)
731 return 0;
732 PyUnicode_Append(&name, u->u_name);
733 if (name == NULL)
734 return 0;
735 }
736 else {
737 Py_INCREF(u->u_name);
738 name = u->u_name;
739 }
740 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400742 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100743}
744
Eric V. Smith235a6f02015-09-19 14:51:32 -0400745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000746/* Allocate a new block and return a pointer to it.
747 Returns NULL on error.
748*/
749
750static basicblock *
751compiler_new_block(struct compiler *c)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 basicblock *b;
754 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 u = c->u;
757 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
758 if (b == NULL) {
759 PyErr_NoMemory();
760 return NULL;
761 }
762 memset((void *)b, 0, sizeof(basicblock));
763 /* Extend the singly linked list of blocks with new block. */
764 b->b_list = u->u_blocks;
765 u->u_blocks = b;
766 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767}
768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770compiler_next_block(struct compiler *c)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 basicblock *block = compiler_new_block(c);
773 if (block == NULL)
774 return NULL;
775 c->u->u_curblock->b_next = block;
776 c->u->u_curblock = block;
777 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778}
779
780static basicblock *
781compiler_use_next_block(struct compiler *c, basicblock *block)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 assert(block != NULL);
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789/* Returns the offset of the next instruction in the current block's
790 b_instr array. Resizes the b_instr as necessary.
791 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793
794static int
795compiler_next_instr(struct compiler *c, basicblock *b)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 assert(b != NULL);
798 if (b->b_instr == NULL) {
799 b->b_instr = (struct instr *)PyObject_Malloc(
800 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
801 if (b->b_instr == NULL) {
802 PyErr_NoMemory();
803 return -1;
804 }
805 b->b_ialloc = DEFAULT_BLOCK_SIZE;
806 memset((char *)b->b_instr, 0,
807 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
808 }
809 else if (b->b_iused == b->b_ialloc) {
810 struct instr *tmp;
811 size_t oldsize, newsize;
812 oldsize = b->b_ialloc * sizeof(struct instr);
813 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000814
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700815 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyErr_NoMemory();
817 return -1;
818 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (newsize == 0) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 b->b_ialloc <<= 1;
825 tmp = (struct instr *)PyObject_Realloc(
826 (void *)b->b_instr, newsize);
827 if (tmp == NULL) {
828 PyErr_NoMemory();
829 return -1;
830 }
831 b->b_instr = tmp;
832 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
833 }
834 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835}
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837/* Set the i_lineno member of the instruction at offset off if the
838 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 already been set. If it has been set, the call has no effect.
840
Christian Heimes2202f872008-02-06 14:31:34 +0000841 The line number is reset in the following cases:
842 - when entering a new scope
843 - on each statement
844 - on each expression that start a new line
845 - before the "except" clause
846 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849static void
850compiler_set_lineno(struct compiler *c, int off)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 basicblock *b;
853 if (c->u->u_lineno_set)
854 return;
855 c->u->u_lineno_set = 1;
856 b = c->u->u_curblock;
857 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858}
859
Larry Hastings3a907972013-11-23 14:49:22 -0800860int
861PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 switch (opcode) {
864 case POP_TOP:
865 return -1;
866 case ROT_TWO:
867 case ROT_THREE:
868 return 0;
869 case DUP_TOP:
870 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000871 case DUP_TOP_TWO:
872 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 case UNARY_POSITIVE:
875 case UNARY_NEGATIVE:
876 case UNARY_NOT:
877 case UNARY_INVERT:
878 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case SET_ADD:
881 case LIST_APPEND:
882 return -1;
883 case MAP_ADD:
884 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case BINARY_POWER:
887 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400888 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case BINARY_MODULO:
890 case BINARY_ADD:
891 case BINARY_SUBTRACT:
892 case BINARY_SUBSCR:
893 case BINARY_FLOOR_DIVIDE:
894 case BINARY_TRUE_DIVIDE:
895 return -1;
896 case INPLACE_FLOOR_DIVIDE:
897 case INPLACE_TRUE_DIVIDE:
898 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_ADD:
901 case INPLACE_SUBTRACT:
902 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400903 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case INPLACE_MODULO:
905 return -1;
906 case STORE_SUBSCR:
907 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 case DELETE_SUBSCR:
909 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case BINARY_LSHIFT:
912 case BINARY_RSHIFT:
913 case BINARY_AND:
914 case BINARY_XOR:
915 case BINARY_OR:
916 return -1;
917 case INPLACE_POWER:
918 return -1;
919 case GET_ITER:
920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case PRINT_EXPR:
923 return -1;
924 case LOAD_BUILD_CLASS:
925 return 1;
926 case INPLACE_LSHIFT:
927 case INPLACE_RSHIFT:
928 case INPLACE_AND:
929 case INPLACE_XOR:
930 case INPLACE_OR:
931 return -1;
932 case BREAK_LOOP:
933 return 0;
934 case SETUP_WITH:
935 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400936 case WITH_CLEANUP_START:
937 return 1;
938 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case RETURN_VALUE:
941 return -1;
942 case IMPORT_STAR:
943 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700944 case SETUP_ANNOTATIONS:
945 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case YIELD_VALUE:
947 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500948 case YIELD_FROM:
949 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case POP_BLOCK:
951 return 0;
952 case POP_EXCEPT:
953 return 0; /* -3 except if bad bytecode */
954 case END_FINALLY:
955 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case STORE_NAME:
958 return -1;
959 case DELETE_NAME:
960 return 0;
961 case UNPACK_SEQUENCE:
962 return oparg-1;
963 case UNPACK_EX:
964 return (oparg&0xFF) + (oparg>>8);
965 case FOR_ITER:
966 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case STORE_ATTR:
969 return -2;
970 case DELETE_ATTR:
971 return -1;
972 case STORE_GLOBAL:
973 return -1;
974 case DELETE_GLOBAL:
975 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case LOAD_CONST:
977 return 1;
978 case LOAD_NAME:
979 return 1;
980 case BUILD_TUPLE:
981 case BUILD_LIST:
982 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300983 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400985 case BUILD_LIST_UNPACK:
986 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300987 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400988 case BUILD_SET_UNPACK:
989 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400990 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700991 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700993 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300994 case BUILD_CONST_KEY_MAP:
995 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 case LOAD_ATTR:
997 return 0;
998 case COMPARE_OP:
999 return -1;
1000 case IMPORT_NAME:
1001 return -1;
1002 case IMPORT_FROM:
1003 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case JUMP_FORWARD:
1006 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1007 case JUMP_IF_FALSE_OR_POP: /* "" */
1008 case JUMP_ABSOLUTE:
1009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case POP_JUMP_IF_FALSE:
1012 case POP_JUMP_IF_TRUE:
1013 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case LOAD_GLOBAL:
1016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case CONTINUE_LOOP:
1019 return 0;
1020 case SETUP_LOOP:
1021 return 0;
1022 case SETUP_EXCEPT:
1023 case SETUP_FINALLY:
1024 return 6; /* can push 3 values for the new exception
1025 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case LOAD_FAST:
1028 return 1;
1029 case STORE_FAST:
1030 return -1;
1031 case DELETE_FAST:
1032 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001033 case STORE_ANNOTATION:
1034 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case RAISE_VARARGS:
1037 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001039 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001040 case CALL_METHOD:
1041 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001043 return -oparg-1;
1044 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001045 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001046 case MAKE_FUNCTION:
1047 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1048 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case BUILD_SLICE:
1050 if (oparg == 3)
1051 return -2;
1052 else
1053 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case LOAD_CLOSURE:
1056 return 1;
1057 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001058 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return 1;
1060 case STORE_DEREF:
1061 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001062 case DELETE_DEREF:
1063 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001064 case GET_AWAITABLE:
1065 return 0;
1066 case SETUP_ASYNC_WITH:
1067 return 6;
1068 case BEFORE_ASYNC_WITH:
1069 return 1;
1070 case GET_AITER:
1071 return 0;
1072 case GET_ANEXT:
1073 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001074 case GET_YIELD_FROM_ITER:
1075 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001076 case FORMAT_VALUE:
1077 /* If there's a fmt_spec on the stack, we go from 2->1,
1078 else 1->1. */
1079 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001080 case LOAD_METHOD:
1081 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001083 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
Larry Hastings3a907972013-11-23 14:49:22 -08001085 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086}
1087
1088/* Add an opcode with no argument.
1089 Returns 0 on failure, 1 on success.
1090*/
1091
1092static int
1093compiler_addop(struct compiler *c, int opcode)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 basicblock *b;
1096 struct instr *i;
1097 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001098 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 off = compiler_next_instr(c, c->u->u_curblock);
1100 if (off < 0)
1101 return 0;
1102 b = c->u->u_curblock;
1103 i = &b->b_instr[off];
1104 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001105 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (opcode == RETURN_VALUE)
1107 b->b_return = 1;
1108 compiler_set_lineno(c, off);
1109 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001110}
1111
Victor Stinnerf8e32212013-11-19 23:56:34 +01001112static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *t, *v;
1116 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
Victor Stinnerefb24132016-01-22 12:33:12 +01001118 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (t == NULL)
1120 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 v = PyDict_GetItem(dict, t);
1123 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001124 if (PyErr_Occurred()) {
1125 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001127 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001128 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001129 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!v) {
1131 Py_DECREF(t);
1132 return -1;
1133 }
1134 if (PyDict_SetItem(dict, t, v) < 0) {
1135 Py_DECREF(t);
1136 Py_DECREF(v);
1137 return -1;
1138 }
1139 Py_DECREF(v);
1140 }
1141 else
1142 arg = PyLong_AsLong(v);
1143 Py_DECREF(t);
1144 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145}
1146
1147static int
1148compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001151 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return compiler_addop_i(c, opcode, arg);
1155}
1156
1157static int
1158compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001161 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1163 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 arg = compiler_add_o(c, dict, mangled);
1166 Py_DECREF(mangled);
1167 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001168 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 return compiler_addop_i(c, opcode, arg);
1170}
1171
1172/* Add an opcode with an integer argument.
1173 Returns 0 on failure, 1 on success.
1174*/
1175
1176static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 struct instr *i;
1180 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001181
Victor Stinner2ad474b2016-03-01 23:34:47 +01001182 /* oparg value is unsigned, but a signed C int is usually used to store
1183 it in the C code (like Python/ceval.c).
1184
1185 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1186
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001187 The argument of a concrete bytecode instruction is limited to 8-bit.
1188 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1189 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001190 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 off = compiler_next_instr(c, c->u->u_curblock);
1193 if (off < 0)
1194 return 0;
1195 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001196 i->i_opcode = opcode;
1197 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 compiler_set_lineno(c, off);
1199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200}
1201
1202static int
1203compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 struct instr *i;
1206 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001208 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 assert(b != NULL);
1210 off = compiler_next_instr(c, c->u->u_curblock);
1211 if (off < 0)
1212 return 0;
1213 i = &c->u->u_curblock->b_instr[off];
1214 i->i_opcode = opcode;
1215 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (absolute)
1217 i->i_jabs = 1;
1218 else
1219 i->i_jrel = 1;
1220 compiler_set_lineno(c, off);
1221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222}
1223
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001224/* NEXT_BLOCK() creates an implicit jump from the current block
1225 to the new block.
1226
1227 The returns inside this macro make it impossible to decref objects
1228 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (compiler_next_block((C)) == NULL) \
1232 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233}
1234
1235#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (!compiler_addop((C), (OP))) \
1237 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238}
1239
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001240#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (!compiler_addop((C), (OP))) { \
1242 compiler_exit_scope(c); \
1243 return 0; \
1244 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001245}
1246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1249 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001252/* Same as ADDOP_O, but steals a reference. */
1253#define ADDOP_N(C, OP, O, TYPE) { \
1254 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1255 Py_DECREF((O)); \
1256 return 0; \
1257 } \
1258 Py_DECREF((O)); \
1259}
1260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1263 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264}
1265
1266#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (!compiler_addop_i((C), (OP), (O))) \
1268 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269}
1270
1271#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!compiler_addop_j((C), (OP), (O), 1)) \
1273 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
1276#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!compiler_addop_j((C), (OP), (O), 0)) \
1278 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1282 the ASDL name to synthesize the name of the C type and the visit function.
1283*/
1284
1285#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (!compiler_visit_ ## TYPE((C), (V))) \
1287 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288}
1289
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001290#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (!compiler_visit_ ## TYPE((C), (V))) { \
1292 compiler_exit_scope(c); \
1293 return 0; \
1294 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001295}
1296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (!compiler_visit_slice((C), (V), (CTX))) \
1299 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300}
1301
1302#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 int _i; \
1304 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1305 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1306 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1307 if (!compiler_visit_ ## TYPE((C), elt)) \
1308 return 0; \
1309 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001312#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 int _i; \
1314 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1315 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1316 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1317 if (!compiler_visit_ ## TYPE((C), elt)) { \
1318 compiler_exit_scope(c); \
1319 return 0; \
1320 } \
1321 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001322}
1323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001325is_const(expr_ty e)
1326{
1327 switch (e->kind) {
1328 case Constant_kind:
1329 case Num_kind:
1330 case Str_kind:
1331 case Bytes_kind:
1332 case Ellipsis_kind:
1333 case NameConstant_kind:
1334 return 1;
1335 default:
1336 return 0;
1337 }
1338}
1339
1340static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001341get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001342{
1343 switch (e->kind) {
1344 case Constant_kind:
1345 return e->v.Constant.value;
1346 case Num_kind:
1347 return e->v.Num.n;
1348 case Str_kind:
1349 return e->v.Str.s;
1350 case Bytes_kind:
1351 return e->v.Bytes.s;
1352 case Ellipsis_kind:
1353 return Py_Ellipsis;
1354 case NameConstant_kind:
1355 return e->v.NameConstant.value;
1356 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001357 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001358 }
1359}
1360
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001361/* Search if variable annotations are present statically in a block. */
1362
1363static int
1364find_ann(asdl_seq *stmts)
1365{
1366 int i, j, res = 0;
1367 stmt_ty st;
1368
1369 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1370 st = (stmt_ty)asdl_seq_GET(stmts, i);
1371 switch (st->kind) {
1372 case AnnAssign_kind:
1373 return 1;
1374 case For_kind:
1375 res = find_ann(st->v.For.body) ||
1376 find_ann(st->v.For.orelse);
1377 break;
1378 case AsyncFor_kind:
1379 res = find_ann(st->v.AsyncFor.body) ||
1380 find_ann(st->v.AsyncFor.orelse);
1381 break;
1382 case While_kind:
1383 res = find_ann(st->v.While.body) ||
1384 find_ann(st->v.While.orelse);
1385 break;
1386 case If_kind:
1387 res = find_ann(st->v.If.body) ||
1388 find_ann(st->v.If.orelse);
1389 break;
1390 case With_kind:
1391 res = find_ann(st->v.With.body);
1392 break;
1393 case AsyncWith_kind:
1394 res = find_ann(st->v.AsyncWith.body);
1395 break;
1396 case Try_kind:
1397 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1398 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1399 st->v.Try.handlers, j);
1400 if (find_ann(handler->v.ExceptHandler.body)) {
1401 return 1;
1402 }
1403 }
1404 res = find_ann(st->v.Try.body) ||
1405 find_ann(st->v.Try.finalbody) ||
1406 find_ann(st->v.Try.orelse);
1407 break;
1408 default:
1409 res = 0;
1410 }
1411 if (res) {
1412 break;
1413 }
1414 }
1415 return res;
1416}
1417
1418/* Compile a sequence of statements, checking for a docstring
1419 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420
1421static int
INADA Naokicb41b272017-02-23 00:31:59 +09001422compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001424 /* Set current line number to the line number of first statement.
1425 This way line number for SETUP_ANNOTATIONS will always
1426 coincide with the line number of first "real" statement in module.
1427 If body is empy, then lineno will be set later in assemble. */
1428 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1429 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001430 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001431 c->u->u_lineno = st->lineno;
1432 }
1433 /* Every annotated class and module should have __annotations__. */
1434 if (find_ann(stmts)) {
1435 ADDOP(c, SETUP_ANNOTATIONS);
1436 }
INADA Naokicb41b272017-02-23 00:31:59 +09001437 /* if not -OO mode, set docstring */
1438 if (c->c_optimize < 2 && docstring) {
1439 ADDOP_O(c, LOAD_CONST, docstring, consts);
1440 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 }
INADA Naokicb41b272017-02-23 00:31:59 +09001442 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
1446static PyCodeObject *
1447compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 PyCodeObject *co;
1450 int addNone = 1;
1451 static PyObject *module;
1452 if (!module) {
1453 module = PyUnicode_InternFromString("<module>");
1454 if (!module)
1455 return NULL;
1456 }
1457 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001458 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 return NULL;
1460 switch (mod->kind) {
1461 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001462 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 compiler_exit_scope(c);
1464 return 0;
1465 }
1466 break;
1467 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001468 if (find_ann(mod->v.Interactive.body)) {
1469 ADDOP(c, SETUP_ANNOTATIONS);
1470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 c->c_interactive = 1;
1472 VISIT_SEQ_IN_SCOPE(c, stmt,
1473 mod->v.Interactive.body);
1474 break;
1475 case Expression_kind:
1476 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1477 addNone = 0;
1478 break;
1479 case Suite_kind:
1480 PyErr_SetString(PyExc_SystemError,
1481 "suite should not be possible");
1482 return 0;
1483 default:
1484 PyErr_Format(PyExc_SystemError,
1485 "module kind %d should not be possible",
1486 mod->kind);
1487 return 0;
1488 }
1489 co = assemble(c, addNone);
1490 compiler_exit_scope(c);
1491 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001492}
1493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494/* The test for LOCAL must come before the test for FREE in order to
1495 handle classes where name is both local and free. The local var is
1496 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001497*/
1498
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499static int
1500get_ref_type(struct compiler *c, PyObject *name)
1501{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001502 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001503 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001504 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001505 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001506 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (scope == 0) {
1508 char buf[350];
1509 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001510 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001512 PyUnicode_AsUTF8(name),
1513 PyUnicode_AsUTF8(c->u->u_name),
1514 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1515 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1516 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1517 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 );
1519 Py_FatalError(buf);
1520 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523}
1524
1525static int
1526compiler_lookup_arg(PyObject *dict, PyObject *name)
1527{
1528 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001529 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001531 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001533 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001535 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001536 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537}
1538
1539static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001540compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001541{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001542 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001543 if (qualname == NULL)
1544 qualname = co->co_name;
1545
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001546 if (free) {
1547 for (i = 0; i < free; ++i) {
1548 /* Bypass com_addop_varname because it will generate
1549 LOAD_DEREF but LOAD_CLOSURE is needed.
1550 */
1551 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1552 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001553
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001554 /* Special case: If a class contains a method with a
1555 free variable that has the same name as a method,
1556 the name will be considered free *and* local in the
1557 class. It should be handled by the closure, as
1558 well as by the normal name loookup logic.
1559 */
1560 reftype = get_ref_type(c, name);
1561 if (reftype == CELL)
1562 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1563 else /* (reftype == FREE) */
1564 arg = compiler_lookup_arg(c->u->u_freevars, name);
1565 if (arg == -1) {
1566 fprintf(stderr,
1567 "lookup %s in %s %d %d\n"
1568 "freevars of %s: %s\n",
1569 PyUnicode_AsUTF8(PyObject_Repr(name)),
1570 PyUnicode_AsUTF8(c->u->u_name),
1571 reftype, arg,
1572 PyUnicode_AsUTF8(co->co_name),
1573 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1574 Py_FatalError("compiler_make_closure()");
1575 }
1576 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001578 flags |= 0x08;
1579 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001582 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001583 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001585}
1586
1587static int
1588compiler_decorators(struct compiler *c, asdl_seq* decos)
1589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (!decos)
1593 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1596 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1597 }
1598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599}
1600
1601static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001602compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001604{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001605 /* Push a dict of keyword-only default values.
1606
1607 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1608 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001609 int i;
1610 PyObject *keys = NULL;
1611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1613 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1614 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1615 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001616 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001617 if (!mangled) {
1618 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001620 if (keys == NULL) {
1621 keys = PyList_New(1);
1622 if (keys == NULL) {
1623 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001624 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001625 }
1626 PyList_SET_ITEM(keys, 0, mangled);
1627 }
1628 else {
1629 int res = PyList_Append(keys, mangled);
1630 Py_DECREF(mangled);
1631 if (res == -1) {
1632 goto error;
1633 }
1634 }
1635 if (!compiler_visit_expr(c, default_)) {
1636 goto error;
1637 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 }
1639 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001640 if (keys != NULL) {
1641 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1642 PyObject *keys_tuple = PyList_AsTuple(keys);
1643 Py_DECREF(keys);
1644 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001645 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001646 }
1647 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1648 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001649 assert(default_count > 0);
1650 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001651 }
1652 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001653 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001654 }
1655
1656error:
1657 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001658 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001659}
1660
1661static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001662compiler_visit_argannotation(struct compiler *c, identifier id,
1663 expr_ty annotation, PyObject *names)
1664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001666 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001668 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001669 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001670 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001671 if (PyList_Append(names, mangled) < 0) {
1672 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001673 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001674 }
1675 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001677 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001678}
1679
1680static int
1681compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1682 PyObject *names)
1683{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001684 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 for (i = 0; i < asdl_seq_LEN(args); i++) {
1686 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001687 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 c,
1689 arg->arg,
1690 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001691 names))
1692 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001694 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001695}
1696
1697static int
1698compiler_visit_annotations(struct compiler *c, arguments_ty args,
1699 expr_ty returns)
1700{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001701 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001702 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001703
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001704 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 */
1706 static identifier return_str;
1707 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001708 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 names = PyList_New(0);
1710 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001711 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001712
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001713 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001715 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001716 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001717 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001719 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001721 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001722 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001723 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (!return_str) {
1727 return_str = PyUnicode_InternFromString("return");
1728 if (!return_str)
1729 goto error;
1730 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001731 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 goto error;
1733 }
1734
1735 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001737 PyObject *keytuple = PyList_AsTuple(names);
1738 Py_DECREF(names);
1739 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001740 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001742 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1743 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001744 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001746 else {
1747 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001748 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001749 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001750
1751error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001753 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001754}
1755
1756static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001757compiler_visit_defaults(struct compiler *c, arguments_ty args)
1758{
1759 VISIT_SEQ(c, expr, args->defaults);
1760 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001762}
1763
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001764static Py_ssize_t
1765compiler_default_arguments(struct compiler *c, arguments_ty args)
1766{
1767 Py_ssize_t funcflags = 0;
1768 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001769 if (!compiler_visit_defaults(c, args))
1770 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001771 funcflags |= 0x01;
1772 }
1773 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001774 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001775 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001776 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001777 return -1;
1778 }
1779 else if (res > 0) {
1780 funcflags |= 0x02;
1781 }
1782 }
1783 return funcflags;
1784}
1785
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786static int
Yury Selivanov75445082015-05-11 22:57:16 -04001787compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001790 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001791 arguments_ty args;
1792 expr_ty returns;
1793 identifier name;
1794 asdl_seq* decos;
1795 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001796 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001797 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001798 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799
Yury Selivanov75445082015-05-11 22:57:16 -04001800 if (is_async) {
1801 assert(s->kind == AsyncFunctionDef_kind);
1802
1803 args = s->v.AsyncFunctionDef.args;
1804 returns = s->v.AsyncFunctionDef.returns;
1805 decos = s->v.AsyncFunctionDef.decorator_list;
1806 name = s->v.AsyncFunctionDef.name;
1807 body = s->v.AsyncFunctionDef.body;
1808
1809 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1810 } else {
1811 assert(s->kind == FunctionDef_kind);
1812
1813 args = s->v.FunctionDef.args;
1814 returns = s->v.FunctionDef.returns;
1815 decos = s->v.FunctionDef.decorator_list;
1816 name = s->v.FunctionDef.name;
1817 body = s->v.FunctionDef.body;
1818
1819 scope_type = COMPILER_SCOPE_FUNCTION;
1820 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (!compiler_decorators(c, decos))
1823 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001824
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001825 funcflags = compiler_default_arguments(c, args);
1826 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001828 }
1829
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001830 annotations = compiler_visit_annotations(c, args, returns);
1831 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001832 return 0;
1833 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001834 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001835 funcflags |= 0x04;
1836 }
1837
1838 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1839 return 0;
1840 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001841
INADA Naokicb41b272017-02-23 00:31:59 +09001842 /* if not -OO mode, add docstring */
1843 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1844 docstring = s->v.FunctionDef.docstring;
1845 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 compiler_exit_scope(c);
1847 return 0;
1848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 c->u->u_argcount = asdl_seq_LEN(args->args);
1851 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001853 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001855 qualname = c->u->u_qualname;
1856 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001858 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001859 Py_XDECREF(qualname);
1860 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001862 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001864 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001865 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 /* decorators */
1869 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1870 ADDOP_I(c, CALL_FUNCTION, 1);
1871 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872
Yury Selivanov75445082015-05-11 22:57:16 -04001873 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874}
1875
1876static int
1877compiler_class(struct compiler *c, stmt_ty s)
1878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 PyCodeObject *co;
1880 PyObject *str;
1881 int i;
1882 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (!compiler_decorators(c, decos))
1885 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* ultimately generate code for:
1888 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1889 where:
1890 <func> is a function/closure created from the class body;
1891 it has a single argument (__locals__) where the dict
1892 (or MutableSequence) representing the locals is passed
1893 <name> is the class name
1894 <bases> is the positional arguments and *varargs argument
1895 <keywords> is the keyword arguments and **kwds argument
1896 This borrows from compiler_call.
1897 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001900 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1901 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 return 0;
1903 /* this block represents what we do in the new scope */
1904 {
1905 /* use the class name for name mangling */
1906 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001907 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 /* load (global) __name__ ... */
1909 str = PyUnicode_InternFromString("__name__");
1910 if (!str || !compiler_nameop(c, str, Load)) {
1911 Py_XDECREF(str);
1912 compiler_exit_scope(c);
1913 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Py_DECREF(str);
1916 /* ... and store it as __module__ */
1917 str = PyUnicode_InternFromString("__module__");
1918 if (!str || !compiler_nameop(c, str, Store)) {
1919 Py_XDECREF(str);
1920 compiler_exit_scope(c);
1921 return 0;
1922 }
1923 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001924 assert(c->u->u_qualname);
1925 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001926 str = PyUnicode_InternFromString("__qualname__");
1927 if (!str || !compiler_nameop(c, str, Store)) {
1928 Py_XDECREF(str);
1929 compiler_exit_scope(c);
1930 return 0;
1931 }
1932 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001934 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 compiler_exit_scope(c);
1936 return 0;
1937 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001938 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001939 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001940 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001941 str = PyUnicode_InternFromString("__class__");
1942 if (str == NULL) {
1943 compiler_exit_scope(c);
1944 return 0;
1945 }
1946 i = compiler_lookup_arg(c->u->u_cellvars, str);
1947 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001948 if (i < 0) {
1949 compiler_exit_scope(c);
1950 return 0;
1951 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001952 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001955 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001956 str = PyUnicode_InternFromString("__classcell__");
1957 if (!str || !compiler_nameop(c, str, Store)) {
1958 Py_XDECREF(str);
1959 compiler_exit_scope(c);
1960 return 0;
1961 }
1962 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001964 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10001965 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001966 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10001967 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05001968 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001969 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 /* create the code object */
1971 co = assemble(c, 1);
1972 }
1973 /* leave the new scope */
1974 compiler_exit_scope(c);
1975 if (co == NULL)
1976 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* 2. load the 'build_class' function */
1979 ADDOP(c, LOAD_BUILD_CLASS);
1980
1981 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001982 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 Py_DECREF(co);
1984
1985 /* 4. load class name */
1986 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1987
1988 /* 5. generate the rest of the code for the call */
1989 if (!compiler_call_helper(c, 2,
1990 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001991 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 return 0;
1993
1994 /* 6. apply decorators */
1995 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1996 ADDOP_I(c, CALL_FUNCTION, 1);
1997 }
1998
1999 /* 7. store into <name> */
2000 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2001 return 0;
2002 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003}
2004
2005static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002006cmpop(cmpop_ty op)
2007{
2008 switch (op) {
2009 case Eq:
2010 return PyCmp_EQ;
2011 case NotEq:
2012 return PyCmp_NE;
2013 case Lt:
2014 return PyCmp_LT;
2015 case LtE:
2016 return PyCmp_LE;
2017 case Gt:
2018 return PyCmp_GT;
2019 case GtE:
2020 return PyCmp_GE;
2021 case Is:
2022 return PyCmp_IS;
2023 case IsNot:
2024 return PyCmp_IS_NOT;
2025 case In:
2026 return PyCmp_IN;
2027 case NotIn:
2028 return PyCmp_NOT_IN;
2029 default:
2030 return PyCmp_BAD;
2031 }
2032}
2033
2034static int
2035compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2036{
2037 switch (e->kind) {
2038 case UnaryOp_kind:
2039 if (e->v.UnaryOp.op == Not)
2040 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2041 /* fallback to general implementation */
2042 break;
2043 case BoolOp_kind: {
2044 asdl_seq *s = e->v.BoolOp.values;
2045 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2046 assert(n >= 0);
2047 int cond2 = e->v.BoolOp.op == Or;
2048 basicblock *next2 = next;
2049 if (!cond2 != !cond) {
2050 next2 = compiler_new_block(c);
2051 if (next2 == NULL)
2052 return 0;
2053 }
2054 for (i = 0; i < n; ++i) {
2055 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2056 return 0;
2057 }
2058 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2059 return 0;
2060 if (next2 != next)
2061 compiler_use_next_block(c, next2);
2062 return 1;
2063 }
2064 case IfExp_kind: {
2065 basicblock *end, *next2;
2066 end = compiler_new_block(c);
2067 if (end == NULL)
2068 return 0;
2069 next2 = compiler_new_block(c);
2070 if (next2 == NULL)
2071 return 0;
2072 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2073 return 0;
2074 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2075 return 0;
2076 ADDOP_JREL(c, JUMP_FORWARD, end);
2077 compiler_use_next_block(c, next2);
2078 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2079 return 0;
2080 compiler_use_next_block(c, end);
2081 return 1;
2082 }
2083 case Compare_kind: {
2084 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2085 if (n > 0) {
2086 basicblock *cleanup = compiler_new_block(c);
2087 if (cleanup == NULL)
2088 return 0;
2089 VISIT(c, expr, e->v.Compare.left);
2090 for (i = 0; i < n; i++) {
2091 VISIT(c, expr,
2092 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2093 ADDOP(c, DUP_TOP);
2094 ADDOP(c, ROT_THREE);
2095 ADDOP_I(c, COMPARE_OP,
2096 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2097 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2098 NEXT_BLOCK(c);
2099 }
2100 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2101 ADDOP_I(c, COMPARE_OP,
2102 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2103 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2104 basicblock *end = compiler_new_block(c);
2105 if (end == NULL)
2106 return 0;
2107 ADDOP_JREL(c, JUMP_FORWARD, end);
2108 compiler_use_next_block(c, cleanup);
2109 ADDOP(c, POP_TOP);
2110 if (!cond) {
2111 ADDOP_JREL(c, JUMP_FORWARD, next);
2112 }
2113 compiler_use_next_block(c, end);
2114 return 1;
2115 }
2116 /* fallback to general implementation */
2117 break;
2118 }
2119 default:
2120 /* fallback to general implementation */
2121 break;
2122 }
2123
2124 /* general implementation */
2125 VISIT(c, expr, e);
2126 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2127 return 1;
2128}
2129
2130static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002131compiler_ifexp(struct compiler *c, expr_ty e)
2132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 basicblock *end, *next;
2134
2135 assert(e->kind == IfExp_kind);
2136 end = compiler_new_block(c);
2137 if (end == NULL)
2138 return 0;
2139 next = compiler_new_block(c);
2140 if (next == NULL)
2141 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002142 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2143 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 VISIT(c, expr, e->v.IfExp.body);
2145 ADDOP_JREL(c, JUMP_FORWARD, end);
2146 compiler_use_next_block(c, next);
2147 VISIT(c, expr, e->v.IfExp.orelse);
2148 compiler_use_next_block(c, end);
2149 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002150}
2151
2152static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153compiler_lambda(struct compiler *c, expr_ty e)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002156 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002158 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 arguments_ty args = e->v.Lambda.args;
2160 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (!name) {
2163 name = PyUnicode_InternFromString("<lambda>");
2164 if (!name)
2165 return 0;
2166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002168 funcflags = compiler_default_arguments(c, args);
2169 if (funcflags == -1) {
2170 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002172
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002173 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002174 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* Make None the first constant, so the lambda can't have a
2178 docstring. */
2179 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2180 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 c->u->u_argcount = asdl_seq_LEN(args->args);
2183 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2184 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2185 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002186 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 }
2188 else {
2189 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002190 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002192 qualname = c->u->u_qualname;
2193 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002195 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002198 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002199 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 Py_DECREF(co);
2201
2202 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203}
2204
2205static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206compiler_if(struct compiler *c, stmt_ty s)
2207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 basicblock *end, *next;
2209 int constant;
2210 assert(s->kind == If_kind);
2211 end = compiler_new_block(c);
2212 if (end == NULL)
2213 return 0;
2214
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002215 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* constant = 0: "if 0"
2217 * constant = 1: "if 1", "if 2", ...
2218 * constant = -1: rest */
2219 if (constant == 0) {
2220 if (s->v.If.orelse)
2221 VISIT_SEQ(c, stmt, s->v.If.orelse);
2222 } else if (constant == 1) {
2223 VISIT_SEQ(c, stmt, s->v.If.body);
2224 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002225 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 next = compiler_new_block(c);
2227 if (next == NULL)
2228 return 0;
2229 }
2230 else
2231 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002232 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2233 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002235 if (asdl_seq_LEN(s->v.If.orelse)) {
2236 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 compiler_use_next_block(c, next);
2238 VISIT_SEQ(c, stmt, s->v.If.orelse);
2239 }
2240 }
2241 compiler_use_next_block(c, end);
2242 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243}
2244
2245static int
2246compiler_for(struct compiler *c, stmt_ty s)
2247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 start = compiler_new_block(c);
2251 cleanup = compiler_new_block(c);
2252 end = compiler_new_block(c);
2253 if (start == NULL || end == NULL || cleanup == NULL)
2254 return 0;
2255 ADDOP_JREL(c, SETUP_LOOP, end);
2256 if (!compiler_push_fblock(c, LOOP, start))
2257 return 0;
2258 VISIT(c, expr, s->v.For.iter);
2259 ADDOP(c, GET_ITER);
2260 compiler_use_next_block(c, start);
2261 ADDOP_JREL(c, FOR_ITER, cleanup);
2262 VISIT(c, expr, s->v.For.target);
2263 VISIT_SEQ(c, stmt, s->v.For.body);
2264 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2265 compiler_use_next_block(c, cleanup);
2266 ADDOP(c, POP_BLOCK);
2267 compiler_pop_fblock(c, LOOP, start);
2268 VISIT_SEQ(c, stmt, s->v.For.orelse);
2269 compiler_use_next_block(c, end);
2270 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271}
2272
Yury Selivanov75445082015-05-11 22:57:16 -04002273
2274static int
2275compiler_async_for(struct compiler *c, stmt_ty s)
2276{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002277 _Py_IDENTIFIER(StopAsyncIteration);
2278
Yury Selivanov75445082015-05-11 22:57:16 -04002279 basicblock *try, *except, *end, *after_try, *try_cleanup,
2280 *after_loop, *after_loop_else;
2281
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002282 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2283 if (stop_aiter_error == NULL) {
2284 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002285 }
2286
2287 try = compiler_new_block(c);
2288 except = compiler_new_block(c);
2289 end = compiler_new_block(c);
2290 after_try = compiler_new_block(c);
2291 try_cleanup = compiler_new_block(c);
2292 after_loop = compiler_new_block(c);
2293 after_loop_else = compiler_new_block(c);
2294
2295 if (try == NULL || except == NULL || end == NULL
2296 || after_try == NULL || try_cleanup == NULL)
2297 return 0;
2298
2299 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2300 if (!compiler_push_fblock(c, LOOP, try))
2301 return 0;
2302
2303 VISIT(c, expr, s->v.AsyncFor.iter);
2304 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002305
2306 compiler_use_next_block(c, try);
2307
2308
2309 ADDOP_JREL(c, SETUP_EXCEPT, except);
2310 if (!compiler_push_fblock(c, EXCEPT, try))
2311 return 0;
2312
2313 ADDOP(c, GET_ANEXT);
2314 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2315 ADDOP(c, YIELD_FROM);
2316 VISIT(c, expr, s->v.AsyncFor.target);
2317 ADDOP(c, POP_BLOCK);
2318 compiler_pop_fblock(c, EXCEPT, try);
2319 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2320
2321
2322 compiler_use_next_block(c, except);
2323 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002324 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002325 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2326 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2327
2328 ADDOP(c, POP_TOP);
2329 ADDOP(c, POP_TOP);
2330 ADDOP(c, POP_TOP);
2331 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2332 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2333 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2334
2335
2336 compiler_use_next_block(c, try_cleanup);
2337 ADDOP(c, END_FINALLY);
2338
2339 compiler_use_next_block(c, after_try);
2340 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2341 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2342
2343 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2344 compiler_pop_fblock(c, LOOP, try);
2345
2346 compiler_use_next_block(c, after_loop);
2347 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2348
2349 compiler_use_next_block(c, after_loop_else);
2350 VISIT_SEQ(c, stmt, s->v.For.orelse);
2351
2352 compiler_use_next_block(c, end);
2353
2354 return 1;
2355}
2356
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357static int
2358compiler_while(struct compiler *c, stmt_ty s)
2359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002361 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (constant == 0) {
2364 if (s->v.While.orelse)
2365 VISIT_SEQ(c, stmt, s->v.While.orelse);
2366 return 1;
2367 }
2368 loop = compiler_new_block(c);
2369 end = compiler_new_block(c);
2370 if (constant == -1) {
2371 anchor = compiler_new_block(c);
2372 if (anchor == NULL)
2373 return 0;
2374 }
2375 if (loop == NULL || end == NULL)
2376 return 0;
2377 if (s->v.While.orelse) {
2378 orelse = compiler_new_block(c);
2379 if (orelse == NULL)
2380 return 0;
2381 }
2382 else
2383 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 ADDOP_JREL(c, SETUP_LOOP, end);
2386 compiler_use_next_block(c, loop);
2387 if (!compiler_push_fblock(c, LOOP, loop))
2388 return 0;
2389 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002390 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2391 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 }
2393 VISIT_SEQ(c, stmt, s->v.While.body);
2394 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* XXX should the two POP instructions be in a separate block
2397 if there is no else clause ?
2398 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002400 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002402 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 compiler_pop_fblock(c, LOOP, loop);
2404 if (orelse != NULL) /* what if orelse is just pass? */
2405 VISIT_SEQ(c, stmt, s->v.While.orelse);
2406 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409}
2410
2411static int
2412compiler_continue(struct compiler *c)
2413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2415 static const char IN_FINALLY_ERROR_MSG[] =
2416 "'continue' not supported inside 'finally' clause";
2417 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (!c->u->u_nfblocks)
2420 return compiler_error(c, LOOP_ERROR_MSG);
2421 i = c->u->u_nfblocks - 1;
2422 switch (c->u->u_fblock[i].fb_type) {
2423 case LOOP:
2424 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2425 break;
2426 case EXCEPT:
2427 case FINALLY_TRY:
2428 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2429 /* Prevent continue anywhere under a finally
2430 even if hidden in a sub-try or except. */
2431 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2432 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2433 }
2434 if (i == -1)
2435 return compiler_error(c, LOOP_ERROR_MSG);
2436 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2437 break;
2438 case FINALLY_END:
2439 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443}
2444
2445/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446
2447 SETUP_FINALLY L
2448 <code for body>
2449 POP_BLOCK
2450 LOAD_CONST <None>
2451 L: <code for finalbody>
2452 END_FINALLY
2453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 The special instructions use the block stack. Each block
2455 stack entry contains the instruction that created it (here
2456 SETUP_FINALLY), the level of the value stack at the time the
2457 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 Pushes the current value stack level and the label
2461 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 Pops en entry from the block stack, and pops the value
2464 stack until its level is the same as indicated on the
2465 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 Pops a variable number of entries from the *value* stack
2468 and re-raises the exception they specify. The number of
2469 entries popped depends on the (pseudo) exception type.
2470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 The block stack is unwound when an exception is raised:
2472 when a SETUP_FINALLY entry is found, the exception is pushed
2473 onto the value stack (and the exception condition is cleared),
2474 and the interpreter jumps to the label gotten from the block
2475 stack.
2476*/
2477
2478static int
2479compiler_try_finally(struct compiler *c, stmt_ty s)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 basicblock *body, *end;
2482 body = compiler_new_block(c);
2483 end = compiler_new_block(c);
2484 if (body == NULL || end == NULL)
2485 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 ADDOP_JREL(c, SETUP_FINALLY, end);
2488 compiler_use_next_block(c, body);
2489 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2490 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002491 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2492 if (!compiler_try_except(c, s))
2493 return 0;
2494 }
2495 else {
2496 VISIT_SEQ(c, stmt, s->v.Try.body);
2497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 ADDOP(c, POP_BLOCK);
2499 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2502 compiler_use_next_block(c, end);
2503 if (!compiler_push_fblock(c, FINALLY_END, end))
2504 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002505 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 ADDOP(c, END_FINALLY);
2507 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510}
2511
2512/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002513 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514 (The contents of the value stack is shown in [], with the top
2515 at the right; 'tb' is trace-back info, 'val' the exception's
2516 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517
2518 Value stack Label Instruction Argument
2519 [] SETUP_EXCEPT L1
2520 [] <code for S>
2521 [] POP_BLOCK
2522 [] JUMP_FORWARD L0
2523
2524 [tb, val, exc] L1: DUP )
2525 [tb, val, exc, exc] <evaluate E1> )
2526 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2527 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2528 [tb, val, exc] POP
2529 [tb, val] <assign to V1> (or POP if no V1)
2530 [tb] POP
2531 [] <code for S1>
2532 JUMP_FORWARD L0
2533
2534 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 .............................etc.......................
2536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2538
2539 [] L0: <next statement>
2540
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 Of course, parts are not generated if Vi or Ei is not present.
2542*/
2543static int
2544compiler_try_except(struct compiler *c, stmt_ty s)
2545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002547 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 body = compiler_new_block(c);
2550 except = compiler_new_block(c);
2551 orelse = compiler_new_block(c);
2552 end = compiler_new_block(c);
2553 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2554 return 0;
2555 ADDOP_JREL(c, SETUP_EXCEPT, except);
2556 compiler_use_next_block(c, body);
2557 if (!compiler_push_fblock(c, EXCEPT, body))
2558 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002559 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 ADDOP(c, POP_BLOCK);
2561 compiler_pop_fblock(c, EXCEPT, body);
2562 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002563 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 compiler_use_next_block(c, except);
2565 for (i = 0; i < n; i++) {
2566 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002567 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 if (!handler->v.ExceptHandler.type && i < n-1)
2569 return compiler_error(c, "default 'except:' must be last");
2570 c->u->u_lineno_set = 0;
2571 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002572 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 except = compiler_new_block(c);
2574 if (except == NULL)
2575 return 0;
2576 if (handler->v.ExceptHandler.type) {
2577 ADDOP(c, DUP_TOP);
2578 VISIT(c, expr, handler->v.ExceptHandler.type);
2579 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2580 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2581 }
2582 ADDOP(c, POP_TOP);
2583 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002584 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002585
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002586 cleanup_end = compiler_new_block(c);
2587 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002588 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002589 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002590
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002591 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2592 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002594 /*
2595 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002596 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002597 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002598 try:
2599 # body
2600 finally:
2601 name = None
2602 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002603 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002605 /* second try: */
2606 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2607 compiler_use_next_block(c, cleanup_body);
2608 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2609 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002611 /* second # body */
2612 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2613 ADDOP(c, POP_BLOCK);
2614 ADDOP(c, POP_EXCEPT);
2615 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002617 /* finally: */
2618 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2619 compiler_use_next_block(c, cleanup_end);
2620 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2621 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002623 /* name = None */
2624 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2625 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002627 /* del name */
2628 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002630 ADDOP(c, END_FINALLY);
2631 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 }
2633 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002634 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002636 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002637 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002638 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639
Guido van Rossumb940e112007-01-10 16:19:56 +00002640 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002641 ADDOP(c, POP_TOP);
2642 compiler_use_next_block(c, cleanup_body);
2643 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2644 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002646 ADDOP(c, POP_EXCEPT);
2647 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 }
2649 ADDOP_JREL(c, JUMP_FORWARD, end);
2650 compiler_use_next_block(c, except);
2651 }
2652 ADDOP(c, END_FINALLY);
2653 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002654 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 compiler_use_next_block(c, end);
2656 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657}
2658
2659static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002660compiler_try(struct compiler *c, stmt_ty s) {
2661 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2662 return compiler_try_finally(c, s);
2663 else
2664 return compiler_try_except(c, s);
2665}
2666
2667
2668static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669compiler_import_as(struct compiler *c, identifier name, identifier asname)
2670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 /* The IMPORT_NAME opcode was already generated. This function
2672 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002675 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002677 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2678 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002679 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002680 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002681 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002683 while (1) {
2684 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002686 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002688 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002689 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002691 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002692 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002694 if (dot == -1) {
2695 break;
2696 }
2697 ADDOP(c, ROT_TWO);
2698 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002700 if (!compiler_nameop(c, asname, Store)) {
2701 return 0;
2702 }
2703 ADDOP(c, POP_TOP);
2704 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 }
2706 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707}
2708
2709static int
2710compiler_import(struct compiler *c, stmt_ty s)
2711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 /* The Import node stores a module name like a.b.c as a single
2713 string. This is convenient for all cases except
2714 import a.b.c as d
2715 where we need to parse that string to extract the individual
2716 module names.
2717 XXX Perhaps change the representation to make this case simpler?
2718 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002719 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 for (i = 0; i < n; i++) {
2722 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2723 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002725 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2727 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 if (alias->asname) {
2730 r = compiler_import_as(c, alias->name, alias->asname);
2731 if (!r)
2732 return r;
2733 }
2734 else {
2735 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 Py_ssize_t dot = PyUnicode_FindChar(
2737 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002738 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002739 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002740 if (tmp == NULL)
2741 return 0;
2742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 Py_DECREF(tmp);
2746 }
2747 if (!r)
2748 return r;
2749 }
2750 }
2751 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752}
2753
2754static int
2755compiler_from_import(struct compiler *c, stmt_ty s)
2756{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002757 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 PyObject *names = PyTuple_New(n);
2760 PyObject *level;
2761 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 if (!empty_string) {
2764 empty_string = PyUnicode_FromString("");
2765 if (!empty_string)
2766 return 0;
2767 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (!names)
2770 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 level = PyLong_FromLong(s->v.ImportFrom.level);
2773 if (!level) {
2774 Py_DECREF(names);
2775 return 0;
2776 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 /* build up the names */
2779 for (i = 0; i < n; i++) {
2780 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2781 Py_INCREF(alias->name);
2782 PyTuple_SET_ITEM(names, i, alias->name);
2783 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002786 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 Py_DECREF(level);
2788 Py_DECREF(names);
2789 return compiler_error(c, "from __future__ imports must occur "
2790 "at the beginning of the file");
2791 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 ADDOP_O(c, LOAD_CONST, level, consts);
2794 Py_DECREF(level);
2795 ADDOP_O(c, LOAD_CONST, names, consts);
2796 Py_DECREF(names);
2797 if (s->v.ImportFrom.module) {
2798 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2799 }
2800 else {
2801 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2802 }
2803 for (i = 0; i < n; i++) {
2804 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2805 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002807 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 assert(n == 1);
2809 ADDOP(c, IMPORT_STAR);
2810 return 1;
2811 }
2812
2813 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2814 store_name = alias->name;
2815 if (alias->asname)
2816 store_name = alias->asname;
2817
2818 if (!compiler_nameop(c, store_name, Store)) {
2819 Py_DECREF(names);
2820 return 0;
2821 }
2822 }
2823 /* remove imported module */
2824 ADDOP(c, POP_TOP);
2825 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826}
2827
2828static int
2829compiler_assert(struct compiler *c, stmt_ty s)
2830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 static PyObject *assertion_error = NULL;
2832 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002833 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834
Georg Brandl8334fd92010-12-04 10:26:46 +00002835 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 1;
2837 if (assertion_error == NULL) {
2838 assertion_error = PyUnicode_InternFromString("AssertionError");
2839 if (assertion_error == NULL)
2840 return 0;
2841 }
2842 if (s->v.Assert.test->kind == Tuple_kind &&
2843 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002844 msg = PyUnicode_FromString("assertion is always true, "
2845 "perhaps remove parentheses?");
2846 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002848 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2849 c->c_filename, c->u->u_lineno,
2850 NULL, NULL) == -1) {
2851 Py_DECREF(msg);
2852 return 0;
2853 }
2854 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 end = compiler_new_block(c);
2857 if (end == NULL)
2858 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002859 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2860 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2862 if (s->v.Assert.msg) {
2863 VISIT(c, expr, s->v.Assert.msg);
2864 ADDOP_I(c, CALL_FUNCTION, 1);
2865 }
2866 ADDOP_I(c, RAISE_VARARGS, 1);
2867 compiler_use_next_block(c, end);
2868 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869}
2870
2871static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002872compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2873{
2874 if (c->c_interactive && c->c_nestlevel <= 1) {
2875 VISIT(c, expr, value);
2876 ADDOP(c, PRINT_EXPR);
2877 return 1;
2878 }
2879
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002880 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002881 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002882 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002883 }
2884
2885 VISIT(c, expr, value);
2886 ADDOP(c, POP_TOP);
2887 return 1;
2888}
2889
2890static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891compiler_visit_stmt(struct compiler *c, stmt_ty s)
2892{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002893 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 /* Always assign a lineno to the next instruction for a stmt. */
2896 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002897 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 switch (s->kind) {
2901 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002902 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 case ClassDef_kind:
2904 return compiler_class(c, s);
2905 case Return_kind:
2906 if (c->u->u_ste->ste_type != FunctionBlock)
2907 return compiler_error(c, "'return' outside function");
2908 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002909 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2910 return compiler_error(
2911 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 VISIT(c, expr, s->v.Return.value);
2913 }
2914 else
2915 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2916 ADDOP(c, RETURN_VALUE);
2917 break;
2918 case Delete_kind:
2919 VISIT_SEQ(c, expr, s->v.Delete.targets)
2920 break;
2921 case Assign_kind:
2922 n = asdl_seq_LEN(s->v.Assign.targets);
2923 VISIT(c, expr, s->v.Assign.value);
2924 for (i = 0; i < n; i++) {
2925 if (i < n - 1)
2926 ADDOP(c, DUP_TOP);
2927 VISIT(c, expr,
2928 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2929 }
2930 break;
2931 case AugAssign_kind:
2932 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002933 case AnnAssign_kind:
2934 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 case For_kind:
2936 return compiler_for(c, s);
2937 case While_kind:
2938 return compiler_while(c, s);
2939 case If_kind:
2940 return compiler_if(c, s);
2941 case Raise_kind:
2942 n = 0;
2943 if (s->v.Raise.exc) {
2944 VISIT(c, expr, s->v.Raise.exc);
2945 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002946 if (s->v.Raise.cause) {
2947 VISIT(c, expr, s->v.Raise.cause);
2948 n++;
2949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002951 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002953 case Try_kind:
2954 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 case Assert_kind:
2956 return compiler_assert(c, s);
2957 case Import_kind:
2958 return compiler_import(c, s);
2959 case ImportFrom_kind:
2960 return compiler_from_import(c, s);
2961 case Global_kind:
2962 case Nonlocal_kind:
2963 break;
2964 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002965 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 case Pass_kind:
2967 break;
2968 case Break_kind:
2969 if (!compiler_in_loop(c))
2970 return compiler_error(c, "'break' outside loop");
2971 ADDOP(c, BREAK_LOOP);
2972 break;
2973 case Continue_kind:
2974 return compiler_continue(c);
2975 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002976 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002977 case AsyncFunctionDef_kind:
2978 return compiler_function(c, s, 1);
2979 case AsyncWith_kind:
2980 return compiler_async_with(c, s, 0);
2981 case AsyncFor_kind:
2982 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 }
Yury Selivanov75445082015-05-11 22:57:16 -04002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986}
2987
2988static int
2989unaryop(unaryop_ty op)
2990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 switch (op) {
2992 case Invert:
2993 return UNARY_INVERT;
2994 case Not:
2995 return UNARY_NOT;
2996 case UAdd:
2997 return UNARY_POSITIVE;
2998 case USub:
2999 return UNARY_NEGATIVE;
3000 default:
3001 PyErr_Format(PyExc_SystemError,
3002 "unary op %d should not be possible", op);
3003 return 0;
3004 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005}
3006
3007static int
3008binop(struct compiler *c, operator_ty op)
3009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 switch (op) {
3011 case Add:
3012 return BINARY_ADD;
3013 case Sub:
3014 return BINARY_SUBTRACT;
3015 case Mult:
3016 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003017 case MatMult:
3018 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 case Div:
3020 return BINARY_TRUE_DIVIDE;
3021 case Mod:
3022 return BINARY_MODULO;
3023 case Pow:
3024 return BINARY_POWER;
3025 case LShift:
3026 return BINARY_LSHIFT;
3027 case RShift:
3028 return BINARY_RSHIFT;
3029 case BitOr:
3030 return BINARY_OR;
3031 case BitXor:
3032 return BINARY_XOR;
3033 case BitAnd:
3034 return BINARY_AND;
3035 case FloorDiv:
3036 return BINARY_FLOOR_DIVIDE;
3037 default:
3038 PyErr_Format(PyExc_SystemError,
3039 "binary op %d should not be possible", op);
3040 return 0;
3041 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042}
3043
3044static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045inplace_binop(struct compiler *c, operator_ty op)
3046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 switch (op) {
3048 case Add:
3049 return INPLACE_ADD;
3050 case Sub:
3051 return INPLACE_SUBTRACT;
3052 case Mult:
3053 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003054 case MatMult:
3055 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 case Div:
3057 return INPLACE_TRUE_DIVIDE;
3058 case Mod:
3059 return INPLACE_MODULO;
3060 case Pow:
3061 return INPLACE_POWER;
3062 case LShift:
3063 return INPLACE_LSHIFT;
3064 case RShift:
3065 return INPLACE_RSHIFT;
3066 case BitOr:
3067 return INPLACE_OR;
3068 case BitXor:
3069 return INPLACE_XOR;
3070 case BitAnd:
3071 return INPLACE_AND;
3072 case FloorDiv:
3073 return INPLACE_FLOOR_DIVIDE;
3074 default:
3075 PyErr_Format(PyExc_SystemError,
3076 "inplace binary op %d should not be possible", op);
3077 return 0;
3078 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003079}
3080
3081static int
3082compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3083{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003084 int op, scope;
3085 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 PyObject *dict = c->u->u_names;
3089 PyObject *mangled;
3090 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003092 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3093 !_PyUnicode_EqualToASCIIString(name, "True") &&
3094 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003095
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003096 mangled = _Py_Mangle(c->u->u_private, name);
3097 if (!mangled)
3098 return 0;
3099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 op = 0;
3101 optype = OP_NAME;
3102 scope = PyST_GetScope(c->u->u_ste, mangled);
3103 switch (scope) {
3104 case FREE:
3105 dict = c->u->u_freevars;
3106 optype = OP_DEREF;
3107 break;
3108 case CELL:
3109 dict = c->u->u_cellvars;
3110 optype = OP_DEREF;
3111 break;
3112 case LOCAL:
3113 if (c->u->u_ste->ste_type == FunctionBlock)
3114 optype = OP_FAST;
3115 break;
3116 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003117 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 optype = OP_GLOBAL;
3119 break;
3120 case GLOBAL_EXPLICIT:
3121 optype = OP_GLOBAL;
3122 break;
3123 default:
3124 /* scope can be 0 */
3125 break;
3126 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003129 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 switch (optype) {
3132 case OP_DEREF:
3133 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003134 case Load:
3135 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3136 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 case Store: op = STORE_DEREF; break;
3138 case AugLoad:
3139 case AugStore:
3140 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003141 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 case Param:
3143 default:
3144 PyErr_SetString(PyExc_SystemError,
3145 "param invalid for deref variable");
3146 return 0;
3147 }
3148 break;
3149 case OP_FAST:
3150 switch (ctx) {
3151 case Load: op = LOAD_FAST; break;
3152 case Store: op = STORE_FAST; break;
3153 case Del: op = DELETE_FAST; break;
3154 case AugLoad:
3155 case AugStore:
3156 break;
3157 case Param:
3158 default:
3159 PyErr_SetString(PyExc_SystemError,
3160 "param invalid for local variable");
3161 return 0;
3162 }
3163 ADDOP_O(c, op, mangled, varnames);
3164 Py_DECREF(mangled);
3165 return 1;
3166 case OP_GLOBAL:
3167 switch (ctx) {
3168 case Load: op = LOAD_GLOBAL; break;
3169 case Store: op = STORE_GLOBAL; break;
3170 case Del: op = DELETE_GLOBAL; break;
3171 case AugLoad:
3172 case AugStore:
3173 break;
3174 case Param:
3175 default:
3176 PyErr_SetString(PyExc_SystemError,
3177 "param invalid for global variable");
3178 return 0;
3179 }
3180 break;
3181 case OP_NAME:
3182 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003183 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 case Store: op = STORE_NAME; break;
3185 case Del: op = DELETE_NAME; break;
3186 case AugLoad:
3187 case AugStore:
3188 break;
3189 case Param:
3190 default:
3191 PyErr_SetString(PyExc_SystemError,
3192 "param invalid for name variable");
3193 return 0;
3194 }
3195 break;
3196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 assert(op);
3199 arg = compiler_add_o(c, dict, mangled);
3200 Py_DECREF(mangled);
3201 if (arg < 0)
3202 return 0;
3203 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204}
3205
3206static int
3207compiler_boolop(struct compiler *c, expr_ty e)
3208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003210 int jumpi;
3211 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 assert(e->kind == BoolOp_kind);
3215 if (e->v.BoolOp.op == And)
3216 jumpi = JUMP_IF_FALSE_OR_POP;
3217 else
3218 jumpi = JUMP_IF_TRUE_OR_POP;
3219 end = compiler_new_block(c);
3220 if (end == NULL)
3221 return 0;
3222 s = e->v.BoolOp.values;
3223 n = asdl_seq_LEN(s) - 1;
3224 assert(n >= 0);
3225 for (i = 0; i < n; ++i) {
3226 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3227 ADDOP_JABS(c, jumpi, end);
3228 }
3229 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3230 compiler_use_next_block(c, end);
3231 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232}
3233
3234static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003235starunpack_helper(struct compiler *c, asdl_seq *elts,
3236 int single_op, int inner_op, int outer_op)
3237{
3238 Py_ssize_t n = asdl_seq_LEN(elts);
3239 Py_ssize_t i, nsubitems = 0, nseen = 0;
3240 for (i = 0; i < n; i++) {
3241 expr_ty elt = asdl_seq_GET(elts, i);
3242 if (elt->kind == Starred_kind) {
3243 if (nseen) {
3244 ADDOP_I(c, inner_op, nseen);
3245 nseen = 0;
3246 nsubitems++;
3247 }
3248 VISIT(c, expr, elt->v.Starred.value);
3249 nsubitems++;
3250 }
3251 else {
3252 VISIT(c, expr, elt);
3253 nseen++;
3254 }
3255 }
3256 if (nsubitems) {
3257 if (nseen) {
3258 ADDOP_I(c, inner_op, nseen);
3259 nsubitems++;
3260 }
3261 ADDOP_I(c, outer_op, nsubitems);
3262 }
3263 else
3264 ADDOP_I(c, single_op, nseen);
3265 return 1;
3266}
3267
3268static int
3269assignment_helper(struct compiler *c, asdl_seq *elts)
3270{
3271 Py_ssize_t n = asdl_seq_LEN(elts);
3272 Py_ssize_t i;
3273 int seen_star = 0;
3274 for (i = 0; i < n; i++) {
3275 expr_ty elt = asdl_seq_GET(elts, i);
3276 if (elt->kind == Starred_kind && !seen_star) {
3277 if ((i >= (1 << 8)) ||
3278 (n-i-1 >= (INT_MAX >> 8)))
3279 return compiler_error(c,
3280 "too many expressions in "
3281 "star-unpacking assignment");
3282 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3283 seen_star = 1;
3284 asdl_seq_SET(elts, i, elt->v.Starred.value);
3285 }
3286 else if (elt->kind == Starred_kind) {
3287 return compiler_error(c,
3288 "two starred expressions in assignment");
3289 }
3290 }
3291 if (!seen_star) {
3292 ADDOP_I(c, UNPACK_SEQUENCE, n);
3293 }
3294 VISIT_SEQ(c, expr, elts);
3295 return 1;
3296}
3297
3298static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299compiler_list(struct compiler *c, expr_ty e)
3300{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003301 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003303 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003305 else if (e->v.List.ctx == Load) {
3306 return starunpack_helper(c, elts,
3307 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003309 else
3310 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312}
3313
3314static int
3315compiler_tuple(struct compiler *c, expr_ty e)
3316{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003317 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003319 return assignment_helper(c, elts);
3320 }
3321 else if (e->v.Tuple.ctx == Load) {
3322 return starunpack_helper(c, elts,
3323 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3324 }
3325 else
3326 VISIT_SEQ(c, expr, elts);
3327 return 1;
3328}
3329
3330static int
3331compiler_set(struct compiler *c, expr_ty e)
3332{
3333 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3334 BUILD_SET, BUILD_SET_UNPACK);
3335}
3336
3337static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003338are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3339{
3340 Py_ssize_t i;
3341 for (i = begin; i < end; i++) {
3342 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3343 if (key == NULL || !is_const(key))
3344 return 0;
3345 }
3346 return 1;
3347}
3348
3349static int
3350compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3351{
3352 Py_ssize_t i, n = end - begin;
3353 PyObject *keys, *key;
3354 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3355 for (i = begin; i < end; i++) {
3356 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3357 }
3358 keys = PyTuple_New(n);
3359 if (keys == NULL) {
3360 return 0;
3361 }
3362 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003363 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003364 Py_INCREF(key);
3365 PyTuple_SET_ITEM(keys, i - begin, key);
3366 }
3367 ADDOP_N(c, LOAD_CONST, keys, consts);
3368 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3369 }
3370 else {
3371 for (i = begin; i < end; i++) {
3372 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3373 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3374 }
3375 ADDOP_I(c, BUILD_MAP, n);
3376 }
3377 return 1;
3378}
3379
3380static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003381compiler_dict(struct compiler *c, expr_ty e)
3382{
Victor Stinner976bb402016-03-23 11:36:19 +01003383 Py_ssize_t i, n, elements;
3384 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003385 int is_unpacking = 0;
3386 n = asdl_seq_LEN(e->v.Dict.values);
3387 containers = 0;
3388 elements = 0;
3389 for (i = 0; i < n; i++) {
3390 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3391 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003392 if (!compiler_subdict(c, e, i - elements, i))
3393 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003394 containers++;
3395 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003397 if (is_unpacking) {
3398 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3399 containers++;
3400 }
3401 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003402 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 }
3404 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003405 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003406 if (!compiler_subdict(c, e, n - elements, n))
3407 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003408 containers++;
3409 }
3410 /* If there is more than one dict, they need to be merged into a new
3411 * dict. If there is one dict and it's an unpacking, then it needs
3412 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003413 if (containers > 1 || is_unpacking) {
3414 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 }
3416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003417}
3418
3419static int
3420compiler_compare(struct compiler *c, expr_ty e)
3421{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003422 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003425 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3426 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3427 if (n == 0) {
3428 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3429 ADDOP_I(c, COMPARE_OP,
3430 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3431 }
3432 else {
3433 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 if (cleanup == NULL)
3435 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003436 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 VISIT(c, expr,
3438 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003439 ADDOP(c, DUP_TOP);
3440 ADDOP(c, ROT_THREE);
3441 ADDOP_I(c, COMPARE_OP,
3442 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3443 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3444 NEXT_BLOCK(c);
3445 }
3446 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3447 ADDOP_I(c, COMPARE_OP,
3448 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 basicblock *end = compiler_new_block(c);
3450 if (end == NULL)
3451 return 0;
3452 ADDOP_JREL(c, JUMP_FORWARD, end);
3453 compiler_use_next_block(c, cleanup);
3454 ADDOP(c, ROT_TWO);
3455 ADDOP(c, POP_TOP);
3456 compiler_use_next_block(c, end);
3457 }
3458 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459}
3460
3461static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003462maybe_optimize_method_call(struct compiler *c, expr_ty e)
3463{
3464 Py_ssize_t argsl, i;
3465 expr_ty meth = e->v.Call.func;
3466 asdl_seq *args = e->v.Call.args;
3467
3468 /* Check that the call node is an attribute access, and that
3469 the call doesn't have keyword parameters. */
3470 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3471 asdl_seq_LEN(e->v.Call.keywords))
3472 return -1;
3473
3474 /* Check that there are no *varargs types of arguments. */
3475 argsl = asdl_seq_LEN(args);
3476 for (i = 0; i < argsl; i++) {
3477 expr_ty elt = asdl_seq_GET(args, i);
3478 if (elt->kind == Starred_kind) {
3479 return -1;
3480 }
3481 }
3482
3483 /* Alright, we can optimize the code. */
3484 VISIT(c, expr, meth->v.Attribute.value);
3485 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3486 VISIT_SEQ(c, expr, e->v.Call.args);
3487 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3488 return 1;
3489}
3490
3491static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492compiler_call(struct compiler *c, expr_ty e)
3493{
Yury Selivanovf2392132016-12-13 19:03:51 -05003494 if (maybe_optimize_method_call(c, e) > 0)
3495 return 1;
3496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 VISIT(c, expr, e->v.Call.func);
3498 return compiler_call_helper(c, 0,
3499 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003500 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003501}
3502
Eric V. Smith235a6f02015-09-19 14:51:32 -04003503static int
3504compiler_joined_str(struct compiler *c, expr_ty e)
3505{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003506 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003507 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3508 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003509 return 1;
3510}
3511
Eric V. Smitha78c7952015-11-03 12:45:05 -05003512/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003513static int
3514compiler_formatted_value(struct compiler *c, expr_ty e)
3515{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003516 /* Our oparg encodes 2 pieces of information: the conversion
3517 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003518
Eric V. Smitha78c7952015-11-03 12:45:05 -05003519 Convert the conversion char to 2 bits:
3520 None: 000 0x0 FVC_NONE
3521 !s : 001 0x1 FVC_STR
3522 !r : 010 0x2 FVC_REPR
3523 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003524
Eric V. Smitha78c7952015-11-03 12:45:05 -05003525 next bit is whether or not we have a format spec:
3526 yes : 100 0x4
3527 no : 000 0x0
3528 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003529
Eric V. Smitha78c7952015-11-03 12:45:05 -05003530 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003531
Eric V. Smitha78c7952015-11-03 12:45:05 -05003532 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003533 VISIT(c, expr, e->v.FormattedValue.value);
3534
Eric V. Smitha78c7952015-11-03 12:45:05 -05003535 switch (e->v.FormattedValue.conversion) {
3536 case 's': oparg = FVC_STR; break;
3537 case 'r': oparg = FVC_REPR; break;
3538 case 'a': oparg = FVC_ASCII; break;
3539 case -1: oparg = FVC_NONE; break;
3540 default:
3541 PyErr_SetString(PyExc_SystemError,
3542 "Unrecognized conversion character");
3543 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003544 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003545 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003546 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003547 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003548 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003549 }
3550
Eric V. Smitha78c7952015-11-03 12:45:05 -05003551 /* And push our opcode and oparg */
3552 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003553 return 1;
3554}
3555
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003556static int
3557compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3558{
3559 Py_ssize_t i, n = end - begin;
3560 keyword_ty kw;
3561 PyObject *keys, *key;
3562 assert(n > 0);
3563 if (n > 1) {
3564 for (i = begin; i < end; i++) {
3565 kw = asdl_seq_GET(keywords, i);
3566 VISIT(c, expr, kw->value);
3567 }
3568 keys = PyTuple_New(n);
3569 if (keys == NULL) {
3570 return 0;
3571 }
3572 for (i = begin; i < end; i++) {
3573 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3574 Py_INCREF(key);
3575 PyTuple_SET_ITEM(keys, i - begin, key);
3576 }
3577 ADDOP_N(c, LOAD_CONST, keys, consts);
3578 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3579 }
3580 else {
3581 /* a for loop only executes once */
3582 for (i = begin; i < end; i++) {
3583 kw = asdl_seq_GET(keywords, i);
3584 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3585 VISIT(c, expr, kw->value);
3586 }
3587 ADDOP_I(c, BUILD_MAP, n);
3588 }
3589 return 1;
3590}
3591
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003592/* shared code between compiler_call and compiler_class */
3593static int
3594compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003595 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003596 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003597 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003598{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003599 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003600 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003601
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003602 /* the number of tuples and dictionaries on the stack */
3603 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3604
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003605 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003606 nkwelts = asdl_seq_LEN(keywords);
3607
3608 for (i = 0; i < nkwelts; i++) {
3609 keyword_ty kw = asdl_seq_GET(keywords, i);
3610 if (kw->arg == NULL) {
3611 mustdictunpack = 1;
3612 break;
3613 }
3614 }
3615
3616 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003617 for (i = 0; i < nelts; i++) {
3618 expr_ty elt = asdl_seq_GET(args, i);
3619 if (elt->kind == Starred_kind) {
3620 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003621 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003622 if (nseen) {
3623 ADDOP_I(c, BUILD_TUPLE, nseen);
3624 nseen = 0;
3625 nsubargs++;
3626 }
3627 VISIT(c, expr, elt->v.Starred.value);
3628 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003629 }
3630 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003631 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003632 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003635
3636 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003637 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003638 if (nseen) {
3639 /* Pack up any trailing positional arguments. */
3640 ADDOP_I(c, BUILD_TUPLE, nseen);
3641 nsubargs++;
3642 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003643 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003644 /* If we ended up with more than one stararg, we need
3645 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003646 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003647 }
3648 else if (nsubargs == 0) {
3649 ADDOP_I(c, BUILD_TUPLE, 0);
3650 }
3651 nseen = 0; /* the number of keyword arguments on the stack following */
3652 for (i = 0; i < nkwelts; i++) {
3653 keyword_ty kw = asdl_seq_GET(keywords, i);
3654 if (kw->arg == NULL) {
3655 /* A keyword argument unpacking. */
3656 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003657 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3658 return 0;
3659 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003660 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003661 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003662 VISIT(c, expr, kw->value);
3663 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003664 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003665 else {
3666 nseen++;
3667 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003668 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003669 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003670 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003671 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003672 return 0;
3673 nsubkwargs++;
3674 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003675 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003676 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003677 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003678 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003679 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3680 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003682 else if (nkwelts) {
3683 PyObject *names;
3684 VISIT_SEQ(c, keyword, keywords);
3685 names = PyTuple_New(nkwelts);
3686 if (names == NULL) {
3687 return 0;
3688 }
3689 for (i = 0; i < nkwelts; i++) {
3690 keyword_ty kw = asdl_seq_GET(keywords, i);
3691 Py_INCREF(kw->arg);
3692 PyTuple_SET_ITEM(names, i, kw->arg);
3693 }
3694 ADDOP_N(c, LOAD_CONST, names, consts);
3695 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3696 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003698 else {
3699 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3700 return 1;
3701 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702}
3703
Nick Coghlan650f0d02007-04-15 12:05:43 +00003704
3705/* List and set comprehensions and generator expressions work by creating a
3706 nested function to perform the actual iteration. This means that the
3707 iteration variables don't leak into the current scope.
3708 The defined function is called immediately following its definition, with the
3709 result of that call being the result of the expression.
3710 The LC/SC version returns the populated container, while the GE version is
3711 flagged in symtable.c as a generator, so it returns the generator object
3712 when the function is called.
3713 This code *knows* that the loop cannot contain break, continue, or return,
3714 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3715
3716 Possible cleanups:
3717 - iterate over the generator sequence instead of using recursion
3718*/
3719
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003720
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722compiler_comprehension_generator(struct compiler *c,
3723 asdl_seq *generators, int gen_index,
3724 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003726 comprehension_ty gen;
3727 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3728 if (gen->is_async) {
3729 return compiler_async_comprehension_generator(
3730 c, generators, gen_index, elt, val, type);
3731 } else {
3732 return compiler_sync_comprehension_generator(
3733 c, generators, gen_index, elt, val, type);
3734 }
3735}
3736
3737static int
3738compiler_sync_comprehension_generator(struct compiler *c,
3739 asdl_seq *generators, int gen_index,
3740 expr_ty elt, expr_ty val, int type)
3741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 /* generate code for the iterator, then each of the ifs,
3743 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 comprehension_ty gen;
3746 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003747 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 start = compiler_new_block(c);
3750 skip = compiler_new_block(c);
3751 if_cleanup = compiler_new_block(c);
3752 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3755 anchor == NULL)
3756 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 if (gen_index == 0) {
3761 /* Receive outermost iter as an implicit argument */
3762 c->u->u_argcount = 1;
3763 ADDOP_I(c, LOAD_FAST, 0);
3764 }
3765 else {
3766 /* Sub-iter - calculate on the fly */
3767 VISIT(c, expr, gen->iter);
3768 ADDOP(c, GET_ITER);
3769 }
3770 compiler_use_next_block(c, start);
3771 ADDOP_JREL(c, FOR_ITER, anchor);
3772 NEXT_BLOCK(c);
3773 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 /* XXX this needs to be cleaned up...a lot! */
3776 n = asdl_seq_LEN(gen->ifs);
3777 for (i = 0; i < n; i++) {
3778 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003779 if (!compiler_jump_if(c, e, if_cleanup, 0))
3780 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 NEXT_BLOCK(c);
3782 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (++gen_index < asdl_seq_LEN(generators))
3785 if (!compiler_comprehension_generator(c,
3786 generators, gen_index,
3787 elt, val, type))
3788 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 /* only append after the last for generator */
3791 if (gen_index >= asdl_seq_LEN(generators)) {
3792 /* comprehension specific code */
3793 switch (type) {
3794 case COMP_GENEXP:
3795 VISIT(c, expr, elt);
3796 ADDOP(c, YIELD_VALUE);
3797 ADDOP(c, POP_TOP);
3798 break;
3799 case COMP_LISTCOMP:
3800 VISIT(c, expr, elt);
3801 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3802 break;
3803 case COMP_SETCOMP:
3804 VISIT(c, expr, elt);
3805 ADDOP_I(c, SET_ADD, gen_index + 1);
3806 break;
3807 case COMP_DICTCOMP:
3808 /* With 'd[k] = v', v is evaluated before k, so we do
3809 the same. */
3810 VISIT(c, expr, val);
3811 VISIT(c, expr, elt);
3812 ADDOP_I(c, MAP_ADD, gen_index + 1);
3813 break;
3814 default:
3815 return 0;
3816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 compiler_use_next_block(c, skip);
3819 }
3820 compiler_use_next_block(c, if_cleanup);
3821 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3822 compiler_use_next_block(c, anchor);
3823
3824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825}
3826
3827static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003828compiler_async_comprehension_generator(struct compiler *c,
3829 asdl_seq *generators, int gen_index,
3830 expr_ty elt, expr_ty val, int type)
3831{
3832 _Py_IDENTIFIER(StopAsyncIteration);
3833
3834 comprehension_ty gen;
3835 basicblock *anchor, *skip, *if_cleanup, *try,
3836 *after_try, *except, *try_cleanup;
3837 Py_ssize_t i, n;
3838
3839 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3840 if (stop_aiter_error == NULL) {
3841 return 0;
3842 }
3843
3844 try = compiler_new_block(c);
3845 after_try = compiler_new_block(c);
3846 try_cleanup = compiler_new_block(c);
3847 except = compiler_new_block(c);
3848 skip = compiler_new_block(c);
3849 if_cleanup = compiler_new_block(c);
3850 anchor = compiler_new_block(c);
3851
3852 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3853 try == NULL || after_try == NULL ||
3854 except == NULL || after_try == NULL) {
3855 return 0;
3856 }
3857
3858 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3859
3860 if (gen_index == 0) {
3861 /* Receive outermost iter as an implicit argument */
3862 c->u->u_argcount = 1;
3863 ADDOP_I(c, LOAD_FAST, 0);
3864 }
3865 else {
3866 /* Sub-iter - calculate on the fly */
3867 VISIT(c, expr, gen->iter);
3868 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003869 }
3870
3871 compiler_use_next_block(c, try);
3872
3873
3874 ADDOP_JREL(c, SETUP_EXCEPT, except);
3875 if (!compiler_push_fblock(c, EXCEPT, try))
3876 return 0;
3877
3878 ADDOP(c, GET_ANEXT);
3879 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3880 ADDOP(c, YIELD_FROM);
3881 VISIT(c, expr, gen->target);
3882 ADDOP(c, POP_BLOCK);
3883 compiler_pop_fblock(c, EXCEPT, try);
3884 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3885
3886
3887 compiler_use_next_block(c, except);
3888 ADDOP(c, DUP_TOP);
3889 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3890 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3891 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3892
3893 ADDOP(c, POP_TOP);
3894 ADDOP(c, POP_TOP);
3895 ADDOP(c, POP_TOP);
3896 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3897 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3898
3899
3900 compiler_use_next_block(c, try_cleanup);
3901 ADDOP(c, END_FINALLY);
3902
3903 compiler_use_next_block(c, after_try);
3904
3905 n = asdl_seq_LEN(gen->ifs);
3906 for (i = 0; i < n; i++) {
3907 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003908 if (!compiler_jump_if(c, e, if_cleanup, 0))
3909 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003910 NEXT_BLOCK(c);
3911 }
3912
3913 if (++gen_index < asdl_seq_LEN(generators))
3914 if (!compiler_comprehension_generator(c,
3915 generators, gen_index,
3916 elt, val, type))
3917 return 0;
3918
3919 /* only append after the last for generator */
3920 if (gen_index >= asdl_seq_LEN(generators)) {
3921 /* comprehension specific code */
3922 switch (type) {
3923 case COMP_GENEXP:
3924 VISIT(c, expr, elt);
3925 ADDOP(c, YIELD_VALUE);
3926 ADDOP(c, POP_TOP);
3927 break;
3928 case COMP_LISTCOMP:
3929 VISIT(c, expr, elt);
3930 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3931 break;
3932 case COMP_SETCOMP:
3933 VISIT(c, expr, elt);
3934 ADDOP_I(c, SET_ADD, gen_index + 1);
3935 break;
3936 case COMP_DICTCOMP:
3937 /* With 'd[k] = v', v is evaluated before k, so we do
3938 the same. */
3939 VISIT(c, expr, val);
3940 VISIT(c, expr, elt);
3941 ADDOP_I(c, MAP_ADD, gen_index + 1);
3942 break;
3943 default:
3944 return 0;
3945 }
3946
3947 compiler_use_next_block(c, skip);
3948 }
3949 compiler_use_next_block(c, if_cleanup);
3950 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3951 compiler_use_next_block(c, anchor);
3952 ADDOP(c, POP_TOP);
3953
3954 return 1;
3955}
3956
3957static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003958compiler_comprehension(struct compiler *c, expr_ty e, int type,
3959 identifier name, asdl_seq *generators, expr_ty elt,
3960 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003963 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003964 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003965 int is_async_function = c->u->u_ste->ste_coroutine;
3966 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003967
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003969
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003970 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3971 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003974 }
3975
3976 is_async_generator = c->u->u_ste->ste_coroutine;
3977
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04003978 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003979 if (e->lineno > c->u->u_lineno) {
3980 c->u->u_lineno = e->lineno;
3981 c->u->u_lineno_set = 0;
3982 }
3983 compiler_error(c, "asynchronous comprehension outside of "
3984 "an asynchronous function");
3985 goto error_in_scope;
3986 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 if (type != COMP_GENEXP) {
3989 int op;
3990 switch (type) {
3991 case COMP_LISTCOMP:
3992 op = BUILD_LIST;
3993 break;
3994 case COMP_SETCOMP:
3995 op = BUILD_SET;
3996 break;
3997 case COMP_DICTCOMP:
3998 op = BUILD_MAP;
3999 break;
4000 default:
4001 PyErr_Format(PyExc_SystemError,
4002 "unknown comprehension type %d", type);
4003 goto error_in_scope;
4004 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 ADDOP_I(c, op, 0);
4007 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 if (!compiler_comprehension_generator(c, generators, 0, elt,
4010 val, type))
4011 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 if (type != COMP_GENEXP) {
4014 ADDOP(c, RETURN_VALUE);
4015 }
4016
4017 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004018 qualname = c->u->u_qualname;
4019 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004021 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 goto error;
4023
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004024 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004026 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 Py_DECREF(co);
4028
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004029 VISIT(c, expr, outermost->iter);
4030
4031 if (outermost->is_async) {
4032 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004033 } else {
4034 ADDOP(c, GET_ITER);
4035 }
4036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004038
4039 if (is_async_generator && type != COMP_GENEXP) {
4040 ADDOP(c, GET_AWAITABLE);
4041 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4042 ADDOP(c, YIELD_FROM);
4043 }
4044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004046error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004048error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004049 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 Py_XDECREF(co);
4051 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004052}
4053
4054static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004055compiler_genexp(struct compiler *c, expr_ty e)
4056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 static identifier name;
4058 if (!name) {
4059 name = PyUnicode_FromString("<genexpr>");
4060 if (!name)
4061 return 0;
4062 }
4063 assert(e->kind == GeneratorExp_kind);
4064 return compiler_comprehension(c, e, COMP_GENEXP, name,
4065 e->v.GeneratorExp.generators,
4066 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067}
4068
4069static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004070compiler_listcomp(struct compiler *c, expr_ty e)
4071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 static identifier name;
4073 if (!name) {
4074 name = PyUnicode_FromString("<listcomp>");
4075 if (!name)
4076 return 0;
4077 }
4078 assert(e->kind == ListComp_kind);
4079 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4080 e->v.ListComp.generators,
4081 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004082}
4083
4084static int
4085compiler_setcomp(struct compiler *c, expr_ty e)
4086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 static identifier name;
4088 if (!name) {
4089 name = PyUnicode_FromString("<setcomp>");
4090 if (!name)
4091 return 0;
4092 }
4093 assert(e->kind == SetComp_kind);
4094 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4095 e->v.SetComp.generators,
4096 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004097}
4098
4099
4100static int
4101compiler_dictcomp(struct compiler *c, expr_ty e)
4102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 static identifier name;
4104 if (!name) {
4105 name = PyUnicode_FromString("<dictcomp>");
4106 if (!name)
4107 return 0;
4108 }
4109 assert(e->kind == DictComp_kind);
4110 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4111 e->v.DictComp.generators,
4112 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004113}
4114
4115
4116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117compiler_visit_keyword(struct compiler *c, keyword_ty k)
4118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 VISIT(c, expr, k->value);
4120 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121}
4122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 whether they are true or false.
4125
4126 Return values: 1 for true, 0 for false, -1 for non-constant.
4127 */
4128
4129static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004130expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004132 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004133 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004134 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004135 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004136}
4137
Yury Selivanov75445082015-05-11 22:57:16 -04004138
4139/*
4140 Implements the async with statement.
4141
4142 The semantics outlined in that PEP are as follows:
4143
4144 async with EXPR as VAR:
4145 BLOCK
4146
4147 It is implemented roughly as:
4148
4149 context = EXPR
4150 exit = context.__aexit__ # not calling it
4151 value = await context.__aenter__()
4152 try:
4153 VAR = value # if VAR present in the syntax
4154 BLOCK
4155 finally:
4156 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004157 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004158 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004159 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004160 if not (await exit(*exc)):
4161 raise
4162 */
4163static int
4164compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4165{
4166 basicblock *block, *finally;
4167 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4168
4169 assert(s->kind == AsyncWith_kind);
4170
4171 block = compiler_new_block(c);
4172 finally = compiler_new_block(c);
4173 if (!block || !finally)
4174 return 0;
4175
4176 /* Evaluate EXPR */
4177 VISIT(c, expr, item->context_expr);
4178
4179 ADDOP(c, BEFORE_ASYNC_WITH);
4180 ADDOP(c, GET_AWAITABLE);
4181 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4182 ADDOP(c, YIELD_FROM);
4183
4184 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4185
4186 /* SETUP_ASYNC_WITH pushes a finally block. */
4187 compiler_use_next_block(c, block);
4188 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4189 return 0;
4190 }
4191
4192 if (item->optional_vars) {
4193 VISIT(c, expr, item->optional_vars);
4194 }
4195 else {
4196 /* Discard result from context.__aenter__() */
4197 ADDOP(c, POP_TOP);
4198 }
4199
4200 pos++;
4201 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4202 /* BLOCK code */
4203 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4204 else if (!compiler_async_with(c, s, pos))
4205 return 0;
4206
4207 /* End of try block; start the finally block */
4208 ADDOP(c, POP_BLOCK);
4209 compiler_pop_fblock(c, FINALLY_TRY, block);
4210
4211 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4212 compiler_use_next_block(c, finally);
4213 if (!compiler_push_fblock(c, FINALLY_END, finally))
4214 return 0;
4215
4216 /* Finally block starts; context.__exit__ is on the stack under
4217 the exception or return information. Just issue our magic
4218 opcode. */
4219 ADDOP(c, WITH_CLEANUP_START);
4220
4221 ADDOP(c, GET_AWAITABLE);
4222 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4223 ADDOP(c, YIELD_FROM);
4224
4225 ADDOP(c, WITH_CLEANUP_FINISH);
4226
4227 /* Finally block ends. */
4228 ADDOP(c, END_FINALLY);
4229 compiler_pop_fblock(c, FINALLY_END, finally);
4230 return 1;
4231}
4232
4233
Guido van Rossumc2e20742006-02-27 22:32:47 +00004234/*
4235 Implements the with statement from PEP 343.
4236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004238
4239 with EXPR as VAR:
4240 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241
Guido van Rossumc2e20742006-02-27 22:32:47 +00004242 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243
Thomas Wouters477c8d52006-05-27 19:21:47 +00004244 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004245 exit = context.__exit__ # not calling it
4246 value = context.__enter__()
4247 try:
4248 VAR = value # if VAR present in the syntax
4249 BLOCK
4250 finally:
4251 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004252 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004253 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004254 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004255 exit(*exc)
4256 */
4257static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004258compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004259{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004260 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004261 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004262
4263 assert(s->kind == With_kind);
4264
Guido van Rossumc2e20742006-02-27 22:32:47 +00004265 block = compiler_new_block(c);
4266 finally = compiler_new_block(c);
4267 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004268 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004269
Thomas Wouters477c8d52006-05-27 19:21:47 +00004270 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004271 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004272 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004273
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004274 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004275 compiler_use_next_block(c, block);
4276 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004277 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004278 }
4279
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004280 if (item->optional_vars) {
4281 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004282 }
4283 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004285 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004286 }
4287
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004288 pos++;
4289 if (pos == asdl_seq_LEN(s->v.With.items))
4290 /* BLOCK code */
4291 VISIT_SEQ(c, stmt, s->v.With.body)
4292 else if (!compiler_with(c, s, pos))
4293 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004294
4295 /* End of try block; start the finally block */
4296 ADDOP(c, POP_BLOCK);
4297 compiler_pop_fblock(c, FINALLY_TRY, block);
4298
4299 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4300 compiler_use_next_block(c, finally);
4301 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004302 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004303
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004304 /* Finally block starts; context.__exit__ is on the stack under
4305 the exception or return information. Just issue our magic
4306 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004307 ADDOP(c, WITH_CLEANUP_START);
4308 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004309
4310 /* Finally block ends. */
4311 ADDOP(c, END_FINALLY);
4312 compiler_pop_fblock(c, FINALLY_END, finally);
4313 return 1;
4314}
4315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316static int
4317compiler_visit_expr(struct compiler *c, expr_ty e)
4318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 /* If expr e has a different line number than the last expr/stmt,
4320 set a new line number for the next instruction.
4321 */
4322 if (e->lineno > c->u->u_lineno) {
4323 c->u->u_lineno = e->lineno;
4324 c->u->u_lineno_set = 0;
4325 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004326 /* Updating the column offset is always harmless. */
4327 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 switch (e->kind) {
4329 case BoolOp_kind:
4330 return compiler_boolop(c, e);
4331 case BinOp_kind:
4332 VISIT(c, expr, e->v.BinOp.left);
4333 VISIT(c, expr, e->v.BinOp.right);
4334 ADDOP(c, binop(c, e->v.BinOp.op));
4335 break;
4336 case UnaryOp_kind:
4337 VISIT(c, expr, e->v.UnaryOp.operand);
4338 ADDOP(c, unaryop(e->v.UnaryOp.op));
4339 break;
4340 case Lambda_kind:
4341 return compiler_lambda(c, e);
4342 case IfExp_kind:
4343 return compiler_ifexp(c, e);
4344 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004345 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004347 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 case GeneratorExp_kind:
4349 return compiler_genexp(c, e);
4350 case ListComp_kind:
4351 return compiler_listcomp(c, e);
4352 case SetComp_kind:
4353 return compiler_setcomp(c, e);
4354 case DictComp_kind:
4355 return compiler_dictcomp(c, e);
4356 case Yield_kind:
4357 if (c->u->u_ste->ste_type != FunctionBlock)
4358 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004359 if (e->v.Yield.value) {
4360 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 }
4362 else {
4363 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4364 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004365 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004367 case YieldFrom_kind:
4368 if (c->u->u_ste->ste_type != FunctionBlock)
4369 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004370
4371 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4372 return compiler_error(c, "'yield from' inside async function");
4373
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004374 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004375 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004376 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4377 ADDOP(c, YIELD_FROM);
4378 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004379 case Await_kind:
4380 if (c->u->u_ste->ste_type != FunctionBlock)
4381 return compiler_error(c, "'await' outside function");
4382
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004383 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4384 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004385 return compiler_error(c, "'await' outside async function");
4386
4387 VISIT(c, expr, e->v.Await.value);
4388 ADDOP(c, GET_AWAITABLE);
4389 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4390 ADDOP(c, YIELD_FROM);
4391 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 case Compare_kind:
4393 return compiler_compare(c, e);
4394 case Call_kind:
4395 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004396 case Constant_kind:
4397 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4398 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 case Num_kind:
4400 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4401 break;
4402 case Str_kind:
4403 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4404 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004405 case JoinedStr_kind:
4406 return compiler_joined_str(c, e);
4407 case FormattedValue_kind:
4408 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 case Bytes_kind:
4410 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4411 break;
4412 case Ellipsis_kind:
4413 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4414 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004415 case NameConstant_kind:
4416 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4417 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 /* The following exprs can be assignment targets. */
4419 case Attribute_kind:
4420 if (e->v.Attribute.ctx != AugStore)
4421 VISIT(c, expr, e->v.Attribute.value);
4422 switch (e->v.Attribute.ctx) {
4423 case AugLoad:
4424 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004425 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 case Load:
4427 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4428 break;
4429 case AugStore:
4430 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004431 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 case Store:
4433 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4434 break;
4435 case Del:
4436 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4437 break;
4438 case Param:
4439 default:
4440 PyErr_SetString(PyExc_SystemError,
4441 "param invalid in attribute expression");
4442 return 0;
4443 }
4444 break;
4445 case Subscript_kind:
4446 switch (e->v.Subscript.ctx) {
4447 case AugLoad:
4448 VISIT(c, expr, e->v.Subscript.value);
4449 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4450 break;
4451 case Load:
4452 VISIT(c, expr, e->v.Subscript.value);
4453 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4454 break;
4455 case AugStore:
4456 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4457 break;
4458 case Store:
4459 VISIT(c, expr, e->v.Subscript.value);
4460 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4461 break;
4462 case Del:
4463 VISIT(c, expr, e->v.Subscript.value);
4464 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4465 break;
4466 case Param:
4467 default:
4468 PyErr_SetString(PyExc_SystemError,
4469 "param invalid in subscript expression");
4470 return 0;
4471 }
4472 break;
4473 case Starred_kind:
4474 switch (e->v.Starred.ctx) {
4475 case Store:
4476 /* In all legitimate cases, the Starred node was already replaced
4477 * by compiler_list/compiler_tuple. XXX: is that okay? */
4478 return compiler_error(c,
4479 "starred assignment target must be in a list or tuple");
4480 default:
4481 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004482 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 }
4484 break;
4485 case Name_kind:
4486 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4487 /* child nodes of List and Tuple will have expr_context set */
4488 case List_kind:
4489 return compiler_list(c, e);
4490 case Tuple_kind:
4491 return compiler_tuple(c, e);
4492 }
4493 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004494}
4495
4496static int
4497compiler_augassign(struct compiler *c, stmt_ty s)
4498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 expr_ty e = s->v.AugAssign.target;
4500 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 switch (e->kind) {
4505 case Attribute_kind:
4506 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4507 AugLoad, e->lineno, e->col_offset, c->c_arena);
4508 if (auge == NULL)
4509 return 0;
4510 VISIT(c, expr, auge);
4511 VISIT(c, expr, s->v.AugAssign.value);
4512 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4513 auge->v.Attribute.ctx = AugStore;
4514 VISIT(c, expr, auge);
4515 break;
4516 case Subscript_kind:
4517 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4518 AugLoad, e->lineno, e->col_offset, c->c_arena);
4519 if (auge == NULL)
4520 return 0;
4521 VISIT(c, expr, auge);
4522 VISIT(c, expr, s->v.AugAssign.value);
4523 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4524 auge->v.Subscript.ctx = AugStore;
4525 VISIT(c, expr, auge);
4526 break;
4527 case Name_kind:
4528 if (!compiler_nameop(c, e->v.Name.id, Load))
4529 return 0;
4530 VISIT(c, expr, s->v.AugAssign.value);
4531 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4532 return compiler_nameop(c, e->v.Name.id, Store);
4533 default:
4534 PyErr_Format(PyExc_SystemError,
4535 "invalid node type (%d) for augmented assignment",
4536 e->kind);
4537 return 0;
4538 }
4539 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004540}
4541
4542static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004543check_ann_expr(struct compiler *c, expr_ty e)
4544{
4545 VISIT(c, expr, e);
4546 ADDOP(c, POP_TOP);
4547 return 1;
4548}
4549
4550static int
4551check_annotation(struct compiler *c, stmt_ty s)
4552{
4553 /* Annotations are only evaluated in a module or class. */
4554 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4555 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4556 return check_ann_expr(c, s->v.AnnAssign.annotation);
4557 }
4558 return 1;
4559}
4560
4561static int
4562check_ann_slice(struct compiler *c, slice_ty sl)
4563{
4564 switch(sl->kind) {
4565 case Index_kind:
4566 return check_ann_expr(c, sl->v.Index.value);
4567 case Slice_kind:
4568 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4569 return 0;
4570 }
4571 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4572 return 0;
4573 }
4574 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4575 return 0;
4576 }
4577 break;
4578 default:
4579 PyErr_SetString(PyExc_SystemError,
4580 "unexpected slice kind");
4581 return 0;
4582 }
4583 return 1;
4584}
4585
4586static int
4587check_ann_subscr(struct compiler *c, slice_ty sl)
4588{
4589 /* We check that everything in a subscript is defined at runtime. */
4590 Py_ssize_t i, n;
4591
4592 switch (sl->kind) {
4593 case Index_kind:
4594 case Slice_kind:
4595 if (!check_ann_slice(c, sl)) {
4596 return 0;
4597 }
4598 break;
4599 case ExtSlice_kind:
4600 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4601 for (i = 0; i < n; i++) {
4602 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4603 switch (subsl->kind) {
4604 case Index_kind:
4605 case Slice_kind:
4606 if (!check_ann_slice(c, subsl)) {
4607 return 0;
4608 }
4609 break;
4610 case ExtSlice_kind:
4611 default:
4612 PyErr_SetString(PyExc_SystemError,
4613 "extended slice invalid in nested slice");
4614 return 0;
4615 }
4616 }
4617 break;
4618 default:
4619 PyErr_Format(PyExc_SystemError,
4620 "invalid subscript kind %d", sl->kind);
4621 return 0;
4622 }
4623 return 1;
4624}
4625
4626static int
4627compiler_annassign(struct compiler *c, stmt_ty s)
4628{
4629 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004630 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004631
4632 assert(s->kind == AnnAssign_kind);
4633
4634 /* We perform the actual assignment first. */
4635 if (s->v.AnnAssign.value) {
4636 VISIT(c, expr, s->v.AnnAssign.value);
4637 VISIT(c, expr, targ);
4638 }
4639 switch (targ->kind) {
4640 case Name_kind:
4641 /* If we have a simple name in a module or class, store annotation. */
4642 if (s->v.AnnAssign.simple &&
4643 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4644 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004645 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4646 if (!mangled) {
4647 return 0;
4648 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004649 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004650 /* ADDOP_N decrefs its argument */
4651 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004652 }
4653 break;
4654 case Attribute_kind:
4655 if (!s->v.AnnAssign.value &&
4656 !check_ann_expr(c, targ->v.Attribute.value)) {
4657 return 0;
4658 }
4659 break;
4660 case Subscript_kind:
4661 if (!s->v.AnnAssign.value &&
4662 (!check_ann_expr(c, targ->v.Subscript.value) ||
4663 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4664 return 0;
4665 }
4666 break;
4667 default:
4668 PyErr_Format(PyExc_SystemError,
4669 "invalid node type (%d) for annotated assignment",
4670 targ->kind);
4671 return 0;
4672 }
4673 /* Annotation is evaluated last. */
4674 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4675 return 0;
4676 }
4677 return 1;
4678}
4679
4680static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004681compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 struct fblockinfo *f;
4684 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004685 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 "too many statically nested blocks");
4687 return 0;
4688 }
4689 f = &c->u->u_fblock[c->u->u_nfblocks++];
4690 f->fb_type = t;
4691 f->fb_block = b;
4692 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004693}
4694
4695static void
4696compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 struct compiler_unit *u = c->u;
4699 assert(u->u_nfblocks > 0);
4700 u->u_nfblocks--;
4701 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4702 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004703}
4704
Thomas Wouters89f507f2006-12-13 04:49:30 +00004705static int
4706compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 int i;
4708 struct compiler_unit *u = c->u;
4709 for (i = 0; i < u->u_nfblocks; ++i) {
4710 if (u->u_fblock[i].fb_type == LOOP)
4711 return 1;
4712 }
4713 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004714}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715/* Raises a SyntaxError and returns 0.
4716 If something goes wrong, a different exception may be raised.
4717*/
4718
4719static int
4720compiler_error(struct compiler *c, const char *errstr)
4721{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004722 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004724
Victor Stinner14e461d2013-08-26 22:28:21 +02004725 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 if (!loc) {
4727 Py_INCREF(Py_None);
4728 loc = Py_None;
4729 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004730 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004731 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 if (!u)
4733 goto exit;
4734 v = Py_BuildValue("(zO)", errstr, u);
4735 if (!v)
4736 goto exit;
4737 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004738 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 Py_DECREF(loc);
4740 Py_XDECREF(u);
4741 Py_XDECREF(v);
4742 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004743}
4744
4745static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746compiler_handle_subscr(struct compiler *c, const char *kind,
4747 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 /* XXX this code is duplicated */
4752 switch (ctx) {
4753 case AugLoad: /* fall through to Load */
4754 case Load: op = BINARY_SUBSCR; break;
4755 case AugStore:/* fall through to Store */
4756 case Store: op = STORE_SUBSCR; break;
4757 case Del: op = DELETE_SUBSCR; break;
4758 case Param:
4759 PyErr_Format(PyExc_SystemError,
4760 "invalid %s kind %d in subscript\n",
4761 kind, ctx);
4762 return 0;
4763 }
4764 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004765 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004766 }
4767 else if (ctx == AugStore) {
4768 ADDOP(c, ROT_THREE);
4769 }
4770 ADDOP(c, op);
4771 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004772}
4773
4774static int
4775compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 int n = 2;
4778 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 /* only handles the cases where BUILD_SLICE is emitted */
4781 if (s->v.Slice.lower) {
4782 VISIT(c, expr, s->v.Slice.lower);
4783 }
4784 else {
4785 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4786 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 if (s->v.Slice.upper) {
4789 VISIT(c, expr, s->v.Slice.upper);
4790 }
4791 else {
4792 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4793 }
4794
4795 if (s->v.Slice.step) {
4796 n++;
4797 VISIT(c, expr, s->v.Slice.step);
4798 }
4799 ADDOP_I(c, BUILD_SLICE, n);
4800 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004801}
4802
4803static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4805 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 switch (s->kind) {
4808 case Slice_kind:
4809 return compiler_slice(c, s, ctx);
4810 case Index_kind:
4811 VISIT(c, expr, s->v.Index.value);
4812 break;
4813 case ExtSlice_kind:
4814 default:
4815 PyErr_SetString(PyExc_SystemError,
4816 "extended slice invalid in nested slice");
4817 return 0;
4818 }
4819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004820}
4821
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004822static int
4823compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4824{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004825 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 switch (s->kind) {
4827 case Index_kind:
4828 kindname = "index";
4829 if (ctx != AugStore) {
4830 VISIT(c, expr, s->v.Index.value);
4831 }
4832 break;
4833 case Slice_kind:
4834 kindname = "slice";
4835 if (ctx != AugStore) {
4836 if (!compiler_slice(c, s, ctx))
4837 return 0;
4838 }
4839 break;
4840 case ExtSlice_kind:
4841 kindname = "extended slice";
4842 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004843 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 for (i = 0; i < n; i++) {
4845 slice_ty sub = (slice_ty)asdl_seq_GET(
4846 s->v.ExtSlice.dims, i);
4847 if (!compiler_visit_nested_slice(c, sub, ctx))
4848 return 0;
4849 }
4850 ADDOP_I(c, BUILD_TUPLE, n);
4851 }
4852 break;
4853 default:
4854 PyErr_Format(PyExc_SystemError,
4855 "invalid subscript kind %d", s->kind);
4856 return 0;
4857 }
4858 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004859}
4860
Thomas Wouters89f507f2006-12-13 04:49:30 +00004861/* End of the compiler section, beginning of the assembler section */
4862
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004863/* do depth-first search of basic block graph, starting with block.
4864 post records the block indices in post-order.
4865
4866 XXX must handle implicit jumps from one block to next
4867*/
4868
Thomas Wouters89f507f2006-12-13 04:49:30 +00004869struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 PyObject *a_bytecode; /* string containing bytecode */
4871 int a_offset; /* offset into bytecode */
4872 int a_nblocks; /* number of reachable blocks */
4873 basicblock **a_postorder; /* list of blocks in dfs postorder */
4874 PyObject *a_lnotab; /* string containing lnotab */
4875 int a_lnotab_off; /* offset into lnotab */
4876 int a_lineno; /* last lineno of emitted instruction */
4877 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004878};
4879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004880static void
4881dfs(struct compiler *c, basicblock *b, struct assembler *a)
4882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 int i;
4884 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 if (b->b_seen)
4887 return;
4888 b->b_seen = 1;
4889 if (b->b_next != NULL)
4890 dfs(c, b->b_next, a);
4891 for (i = 0; i < b->b_iused; i++) {
4892 instr = &b->b_instr[i];
4893 if (instr->i_jrel || instr->i_jabs)
4894 dfs(c, instr->i_target, a);
4895 }
4896 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004897}
4898
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004899static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004900stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4901{
Larry Hastings3a907972013-11-23 14:49:22 -08004902 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 struct instr *instr;
4904 if (b->b_seen || b->b_startdepth >= depth)
4905 return maxdepth;
4906 b->b_seen = 1;
4907 b->b_startdepth = depth;
4908 for (i = 0; i < b->b_iused; i++) {
4909 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004910 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4911 if (effect == PY_INVALID_STACK_EFFECT) {
4912 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4913 Py_FatalError("PyCompile_OpcodeStackEffect()");
4914 }
4915 depth += effect;
4916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 if (depth > maxdepth)
4918 maxdepth = depth;
4919 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4920 if (instr->i_jrel || instr->i_jabs) {
4921 target_depth = depth;
4922 if (instr->i_opcode == FOR_ITER) {
4923 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004924 }
4925 else if (instr->i_opcode == SETUP_FINALLY ||
4926 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004927 target_depth = depth+3;
4928 if (target_depth > maxdepth)
4929 maxdepth = target_depth;
4930 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004931 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4932 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4933 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 maxdepth = stackdepth_walk(c, instr->i_target,
4935 target_depth, maxdepth);
4936 if (instr->i_opcode == JUMP_ABSOLUTE ||
4937 instr->i_opcode == JUMP_FORWARD) {
4938 goto out; /* remaining code is dead */
4939 }
4940 }
4941 }
4942 if (b->b_next)
4943 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 b->b_seen = 0;
4946 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004947}
4948
4949/* Find the flow path that needs the largest stack. We assume that
4950 * cycles in the flow graph have no net effect on the stack depth.
4951 */
4952static int
4953stackdepth(struct compiler *c)
4954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 basicblock *b, *entryblock;
4956 entryblock = NULL;
4957 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4958 b->b_seen = 0;
4959 b->b_startdepth = INT_MIN;
4960 entryblock = b;
4961 }
4962 if (!entryblock)
4963 return 0;
4964 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004965}
4966
4967static int
4968assemble_init(struct assembler *a, int nblocks, int firstlineno)
4969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 memset(a, 0, sizeof(struct assembler));
4971 a->a_lineno = firstlineno;
4972 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4973 if (!a->a_bytecode)
4974 return 0;
4975 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4976 if (!a->a_lnotab)
4977 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004978 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 PyErr_NoMemory();
4980 return 0;
4981 }
4982 a->a_postorder = (basicblock **)PyObject_Malloc(
4983 sizeof(basicblock *) * nblocks);
4984 if (!a->a_postorder) {
4985 PyErr_NoMemory();
4986 return 0;
4987 }
4988 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004989}
4990
4991static void
4992assemble_free(struct assembler *a)
4993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 Py_XDECREF(a->a_bytecode);
4995 Py_XDECREF(a->a_lnotab);
4996 if (a->a_postorder)
4997 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004998}
4999
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005000static int
5001blocksize(basicblock *b)
5002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 int i;
5004 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005007 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005009}
5010
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005011/* Appends a pair to the end of the line number table, a_lnotab, representing
5012 the instruction's bytecode offset and line number. See
5013 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005014
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005015static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005016assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005019 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005021
Serhiy Storchakaab874002016-09-11 13:48:15 +03005022 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 if(d_bytecode == 0 && d_lineno == 0)
5028 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 if (d_bytecode > 255) {
5031 int j, nbytes, ncodes = d_bytecode / 255;
5032 nbytes = a->a_lnotab_off + 2 * ncodes;
5033 len = PyBytes_GET_SIZE(a->a_lnotab);
5034 if (nbytes >= len) {
5035 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5036 len = nbytes;
5037 else if (len <= INT_MAX / 2)
5038 len *= 2;
5039 else {
5040 PyErr_NoMemory();
5041 return 0;
5042 }
5043 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5044 return 0;
5045 }
5046 lnotab = (unsigned char *)
5047 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5048 for (j = 0; j < ncodes; j++) {
5049 *lnotab++ = 255;
5050 *lnotab++ = 0;
5051 }
5052 d_bytecode -= ncodes * 255;
5053 a->a_lnotab_off += ncodes * 2;
5054 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005055 assert(0 <= d_bytecode && d_bytecode <= 255);
5056
5057 if (d_lineno < -128 || 127 < d_lineno) {
5058 int j, nbytes, ncodes, k;
5059 if (d_lineno < 0) {
5060 k = -128;
5061 /* use division on positive numbers */
5062 ncodes = (-d_lineno) / 128;
5063 }
5064 else {
5065 k = 127;
5066 ncodes = d_lineno / 127;
5067 }
5068 d_lineno -= ncodes * k;
5069 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 nbytes = a->a_lnotab_off + 2 * ncodes;
5071 len = PyBytes_GET_SIZE(a->a_lnotab);
5072 if (nbytes >= len) {
5073 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5074 len = nbytes;
5075 else if (len <= INT_MAX / 2)
5076 len *= 2;
5077 else {
5078 PyErr_NoMemory();
5079 return 0;
5080 }
5081 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5082 return 0;
5083 }
5084 lnotab = (unsigned char *)
5085 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5086 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005087 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 d_bytecode = 0;
5089 for (j = 1; j < ncodes; j++) {
5090 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005091 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 a->a_lnotab_off += ncodes * 2;
5094 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005095 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 len = PyBytes_GET_SIZE(a->a_lnotab);
5098 if (a->a_lnotab_off + 2 >= len) {
5099 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5100 return 0;
5101 }
5102 lnotab = (unsigned char *)
5103 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 a->a_lnotab_off += 2;
5106 if (d_bytecode) {
5107 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005108 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 }
5110 else { /* First line of a block; def stmt, etc. */
5111 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005112 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 }
5114 a->a_lineno = i->i_lineno;
5115 a->a_lineno_off = a->a_offset;
5116 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005117}
5118
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005119/* assemble_emit()
5120 Extend the bytecode with a new instruction.
5121 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005122*/
5123
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005124static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005125assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005126{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005127 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005129 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005130
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005131 arg = i->i_oparg;
5132 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 if (i->i_lineno && !assemble_lnotab(a, i))
5134 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005135 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 if (len > PY_SSIZE_T_MAX / 2)
5137 return 0;
5138 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5139 return 0;
5140 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005141 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005143 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005145}
5146
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005147static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005148assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005151 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 /* Compute the size of each block and fixup jump args.
5155 Replace block pointer with position in bytecode. */
5156 do {
5157 totsize = 0;
5158 for (i = a->a_nblocks - 1; i >= 0; i--) {
5159 b = a->a_postorder[i];
5160 bsize = blocksize(b);
5161 b->b_offset = totsize;
5162 totsize += bsize;
5163 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005164 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5166 bsize = b->b_offset;
5167 for (i = 0; i < b->b_iused; i++) {
5168 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005169 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 /* Relative jumps are computed relative to
5171 the instruction pointer after fetching
5172 the jump instruction.
5173 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005174 bsize += isize;
5175 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005177 if (instr->i_jrel) {
5178 instr->i_oparg -= bsize;
5179 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005180 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005181 if (instrsize(instr->i_oparg) != isize) {
5182 extended_arg_recompile = 1;
5183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 }
5186 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 /* XXX: This is an awful hack that could hurt performance, but
5189 on the bright side it should work until we come up
5190 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 The issue is that in the first loop blocksize() is called
5193 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005194 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 So we loop until we stop seeing new EXTENDED_ARGs.
5198 The only EXTENDED_ARGs that could be popping up are
5199 ones in jump instructions. So this should converge
5200 fairly quickly.
5201 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005202 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005203}
5204
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005205static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005206dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005209 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 tuple = PyTuple_New(size);
5212 if (tuple == NULL)
5213 return NULL;
5214 while (PyDict_Next(dict, &pos, &k, &v)) {
5215 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005216 /* The keys of the dictionary are tuples. (see compiler_add_o
5217 * and _PyCode_ConstantKey). The object we want is always second,
5218 * though. */
5219 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 Py_INCREF(k);
5221 assert((i - offset) < size);
5222 assert((i - offset) >= 0);
5223 PyTuple_SET_ITEM(tuple, i - offset, k);
5224 }
5225 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005226}
5227
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005228static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005229compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005232 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005234 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 if (ste->ste_nested)
5236 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005237 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005239 if (!ste->ste_generator && ste->ste_coroutine)
5240 flags |= CO_COROUTINE;
5241 if (ste->ste_generator && ste->ste_coroutine)
5242 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 if (ste->ste_varargs)
5244 flags |= CO_VARARGS;
5245 if (ste->ste_varkeywords)
5246 flags |= CO_VARKEYWORDS;
5247 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 /* (Only) inherit compilerflags in PyCF_MASK */
5250 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005253}
5254
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005255static PyCodeObject *
5256makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 PyObject *tmp;
5259 PyCodeObject *co = NULL;
5260 PyObject *consts = NULL;
5261 PyObject *names = NULL;
5262 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 PyObject *name = NULL;
5264 PyObject *freevars = NULL;
5265 PyObject *cellvars = NULL;
5266 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005267 Py_ssize_t nlocals;
5268 int nlocals_int;
5269 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005270 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 tmp = dict_keys_inorder(c->u->u_consts, 0);
5273 if (!tmp)
5274 goto error;
5275 consts = PySequence_List(tmp); /* optimize_code requires a list */
5276 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 names = dict_keys_inorder(c->u->u_names, 0);
5279 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5280 if (!consts || !names || !varnames)
5281 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5284 if (!cellvars)
5285 goto error;
5286 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5287 if (!freevars)
5288 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005289
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005290 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005291 assert(nlocals < INT_MAX);
5292 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 flags = compute_code_flags(c);
5295 if (flags < 0)
5296 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5299 if (!bytecode)
5300 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5303 if (!tmp)
5304 goto error;
5305 Py_DECREF(consts);
5306 consts = tmp;
5307
Victor Stinnerf8e32212013-11-19 23:56:34 +01005308 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5309 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5310 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005311 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 bytecode, consts, names, varnames,
5313 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005314 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 c->u->u_firstlineno,
5316 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 Py_XDECREF(consts);
5319 Py_XDECREF(names);
5320 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 Py_XDECREF(name);
5322 Py_XDECREF(freevars);
5323 Py_XDECREF(cellvars);
5324 Py_XDECREF(bytecode);
5325 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005326}
5327
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005328
5329/* For debugging purposes only */
5330#if 0
5331static void
5332dump_instr(const struct instr *i)
5333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 const char *jrel = i->i_jrel ? "jrel " : "";
5335 const char *jabs = i->i_jabs ? "jabs " : "";
5336 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005339 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005341 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5343 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005344}
5345
5346static void
5347dump_basicblock(const basicblock *b)
5348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 const char *seen = b->b_seen ? "seen " : "";
5350 const char *b_return = b->b_return ? "return " : "";
5351 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5352 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5353 if (b->b_instr) {
5354 int i;
5355 for (i = 0; i < b->b_iused; i++) {
5356 fprintf(stderr, " [%02d] ", i);
5357 dump_instr(b->b_instr + i);
5358 }
5359 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005360}
5361#endif
5362
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005363static PyCodeObject *
5364assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 basicblock *b, *entryblock;
5367 struct assembler a;
5368 int i, j, nblocks;
5369 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 /* Make sure every block that falls off the end returns None.
5372 XXX NEXT_BLOCK() isn't quite right, because if the last
5373 block ends with a jump or return b_next shouldn't set.
5374 */
5375 if (!c->u->u_curblock->b_return) {
5376 NEXT_BLOCK(c);
5377 if (addNone)
5378 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5379 ADDOP(c, RETURN_VALUE);
5380 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 nblocks = 0;
5383 entryblock = NULL;
5384 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5385 nblocks++;
5386 entryblock = b;
5387 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 /* Set firstlineno if it wasn't explicitly set. */
5390 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005391 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5393 else
5394 c->u->u_firstlineno = 1;
5395 }
5396 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5397 goto error;
5398 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 /* Can't modify the bytecode after computing jump offsets. */
5401 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 /* Emit code in reverse postorder from dfs. */
5404 for (i = a.a_nblocks - 1; i >= 0; i--) {
5405 b = a.a_postorder[i];
5406 for (j = 0; j < b->b_iused; j++)
5407 if (!assemble_emit(&a, &b->b_instr[j]))
5408 goto error;
5409 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5412 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005413 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005417 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 assemble_free(&a);
5419 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005420}
Georg Brandl8334fd92010-12-04 10:26:46 +00005421
5422#undef PyAST_Compile
5423PyAPI_FUNC(PyCodeObject *)
5424PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5425 PyArena *arena)
5426{
5427 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5428}