blob: 618f31a47d362cc1403ac60523051115231603df [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);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000216static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217
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 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000314 if (!__annotations__) {
315 __annotations__ = PyUnicode_InternFromString("__annotations__");
316 if (!__annotations__)
317 return NULL;
318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 if (!compiler_init(&c))
320 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200321 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 c.c_filename = filename;
323 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200324 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (c.c_future == NULL)
326 goto finally;
327 if (!flags) {
328 local_flags.cf_flags = 0;
329 flags = &local_flags;
330 }
331 merged = c.c_future->ff_features | flags->cf_flags;
332 c.c_future->ff_features = merged;
333 flags->cf_flags = merged;
334 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000335 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200338 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900339 goto finally;
340 }
341
Victor Stinner14e461d2013-08-26 22:28:21 +0200342 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (c.c_st == NULL) {
344 if (!PyErr_Occurred())
345 PyErr_SetString(PyExc_SystemError, "no symtable");
346 goto finally;
347 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350
Thomas Wouters1175c432006-02-27 22:49:54 +0000351 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 compiler_free(&c);
353 assert(co || PyErr_Occurred());
354 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355}
356
357PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200358PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
359 int optimize, PyArena *arena)
360{
361 PyObject *filename;
362 PyCodeObject *co;
363 filename = PyUnicode_DecodeFSDefault(filename_str);
364 if (filename == NULL)
365 return NULL;
366 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
367 Py_DECREF(filename);
368 return co;
369
370}
371
372PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373PyNode_Compile(struct _node *n, const char *filename)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyCodeObject *co = NULL;
376 mod_ty mod;
377 PyArena *arena = PyArena_New();
378 if (!arena)
379 return NULL;
380 mod = PyAST_FromNode(n, NULL, filename, arena);
381 if (mod)
382 co = PyAST_Compile(mod, filename, NULL, arena);
383 PyArena_Free(arena);
384 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000385}
386
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000387static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (c->c_st)
391 PySymtable_Free(c->c_st);
392 if (c->c_future)
393 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200394 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000396}
397
Guido van Rossum79f25d91997-04-29 20:08:16 +0000398static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_ssize_t i, n;
402 PyObject *v, *k;
403 PyObject *dict = PyDict_New();
404 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 n = PyList_Size(list);
407 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100408 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (!v) {
410 Py_DECREF(dict);
411 return NULL;
412 }
413 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100414 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
416 Py_XDECREF(k);
417 Py_DECREF(v);
418 Py_DECREF(dict);
419 return NULL;
420 }
421 Py_DECREF(k);
422 Py_DECREF(v);
423 }
424 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425}
426
427/* Return new dict containing names from src that match scope(s).
428
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000429src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000431values are integers, starting at offset and increasing by one for
432each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433*/
434
435static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100436dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700438 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500440 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 assert(offset >= 0);
443 if (dest == NULL)
444 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445
Meador Inge2ca63152012-07-18 14:20:11 -0500446 /* Sort the keys so that we have a deterministic order on the indexes
447 saved in the returned dictionary. These indexes are used as indexes
448 into the free and cell var storage. Therefore if they aren't
449 deterministic, then the generated bytecode is not deterministic.
450 */
451 sorted_keys = PyDict_Keys(src);
452 if (sorted_keys == NULL)
453 return NULL;
454 if (PyList_Sort(sorted_keys) != 0) {
455 Py_DECREF(sorted_keys);
456 return NULL;
457 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500458 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500459
460 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* XXX this should probably be a macro in symtable.h */
462 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500463 k = PyList_GET_ITEM(sorted_keys, key_i);
464 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 assert(PyLong_Check(v));
466 vi = PyLong_AS_LONG(v);
467 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100470 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500472 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 Py_DECREF(dest);
474 return NULL;
475 }
476 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100477 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500479 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 Py_DECREF(item);
481 Py_DECREF(dest);
482 Py_XDECREF(tuple);
483 return NULL;
484 }
485 Py_DECREF(item);
486 Py_DECREF(tuple);
487 }
488 }
Meador Inge2ca63152012-07-18 14:20:11 -0500489 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000491}
492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493static void
494compiler_unit_check(struct compiler_unit *u)
495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 basicblock *block;
497 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700498 assert((uintptr_t)block != 0xcbcbcbcbU);
499 assert((uintptr_t)block != 0xfbfbfbfbU);
500 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (block->b_instr != NULL) {
502 assert(block->b_ialloc > 0);
503 assert(block->b_iused > 0);
504 assert(block->b_ialloc >= block->b_iused);
505 }
506 else {
507 assert (block->b_iused == 0);
508 assert (block->b_ialloc == 0);
509 }
510 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511}
512
513static void
514compiler_unit_free(struct compiler_unit *u)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 compiler_unit_check(u);
519 b = u->u_blocks;
520 while (b != NULL) {
521 if (b->b_instr)
522 PyObject_Free((void *)b->b_instr);
523 next = b->b_list;
524 PyObject_Free((void *)b);
525 b = next;
526 }
527 Py_CLEAR(u->u_ste);
528 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400529 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 Py_CLEAR(u->u_consts);
531 Py_CLEAR(u->u_names);
532 Py_CLEAR(u->u_varnames);
533 Py_CLEAR(u->u_freevars);
534 Py_CLEAR(u->u_cellvars);
535 Py_CLEAR(u->u_private);
536 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537}
538
539static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100540compiler_enter_scope(struct compiler *c, identifier name,
541 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100544 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
547 struct compiler_unit));
548 if (!u) {
549 PyErr_NoMemory();
550 return 0;
551 }
552 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100553 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 u->u_argcount = 0;
555 u->u_kwonlyargcount = 0;
556 u->u_ste = PySymtable_Lookup(c->c_st, key);
557 if (!u->u_ste) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 Py_INCREF(name);
562 u->u_name = name;
563 u->u_varnames = list2dict(u->u_ste->ste_varnames);
564 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
565 if (!u->u_varnames || !u->u_cellvars) {
566 compiler_unit_free(u);
567 return 0;
568 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000570 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300572 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500573 int res;
574 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200575 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500576 name = _PyUnicode_FromId(&PyId___class__);
577 if (!name) {
578 compiler_unit_free(u);
579 return 0;
580 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100581 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 if (!tuple) {
583 compiler_unit_free(u);
584 return 0;
585 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300586 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500587 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500588 if (res < 0) {
589 compiler_unit_free(u);
590 return 0;
591 }
592 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200595 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (!u->u_freevars) {
597 compiler_unit_free(u);
598 return 0;
599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 u->u_blocks = NULL;
602 u->u_nfblocks = 0;
603 u->u_firstlineno = lineno;
604 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000605 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_lineno_set = 0;
607 u->u_consts = PyDict_New();
608 if (!u->u_consts) {
609 compiler_unit_free(u);
610 return 0;
611 }
612 u->u_names = PyDict_New();
613 if (!u->u_names) {
614 compiler_unit_free(u);
615 return 0;
616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* Push the old compiler_unit on the stack. */
621 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400622 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
624 Py_XDECREF(capsule);
625 compiler_unit_free(u);
626 return 0;
627 }
628 Py_DECREF(capsule);
629 u->u_private = c->u->u_private;
630 Py_XINCREF(u->u_private);
631 }
632 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100635
636 block = compiler_new_block(c);
637 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100639 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400641 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
642 if (!compiler_set_qualname(c))
643 return 0;
644 }
645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647}
648
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000649static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650compiler_exit_scope(struct compiler *c)
651{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100652 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 c->c_nestlevel--;
656 compiler_unit_free(c->u);
657 /* Restore c->u to the parent unit. */
658 n = PyList_GET_SIZE(c->c_stack) - 1;
659 if (n >= 0) {
660 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400661 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 assert(c->u);
663 /* we are deleting from a list so this really shouldn't fail */
664 if (PySequence_DelItem(c->c_stack, n) < 0)
665 Py_FatalError("compiler_exit_scope()");
666 compiler_unit_check(c->u);
667 }
668 else
669 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000671}
672
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673static int
674compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100676 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 _Py_static_string(dot_locals, ".<locals>");
678 Py_ssize_t stack_size;
679 struct compiler_unit *u = c->u;
680 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100683 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400684 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 if (stack_size > 1) {
686 int scope, force_global = 0;
687 struct compiler_unit *parent;
688 PyObject *mangled, *capsule;
689
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400690 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400691 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400692 assert(parent);
693
Yury Selivanov75445082015-05-11 22:57:16 -0400694 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
695 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
696 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400697 assert(u->u_name);
698 mangled = _Py_Mangle(parent->u_private, u->u_name);
699 if (!mangled)
700 return 0;
701 scope = PyST_GetScope(parent->u_ste, mangled);
702 Py_DECREF(mangled);
703 assert(scope != GLOBAL_IMPLICIT);
704 if (scope == GLOBAL_EXPLICIT)
705 force_global = 1;
706 }
707
708 if (!force_global) {
709 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400710 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400711 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
712 dot_locals_str = _PyUnicode_FromId(&dot_locals);
713 if (dot_locals_str == NULL)
714 return 0;
715 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
716 if (base == NULL)
717 return 0;
718 }
719 else {
720 Py_INCREF(parent->u_qualname);
721 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400722 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100723 }
724 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400725
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400726 if (base != NULL) {
727 dot_str = _PyUnicode_FromId(&dot);
728 if (dot_str == NULL) {
729 Py_DECREF(base);
730 return 0;
731 }
732 name = PyUnicode_Concat(base, dot_str);
733 Py_DECREF(base);
734 if (name == NULL)
735 return 0;
736 PyUnicode_Append(&name, u->u_name);
737 if (name == NULL)
738 return 0;
739 }
740 else {
741 Py_INCREF(u->u_name);
742 name = u->u_name;
743 }
744 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100745
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400746 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100747}
748
Eric V. Smith235a6f02015-09-19 14:51:32 -0400749
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000750/* Allocate a new block and return a pointer to it.
751 Returns NULL on error.
752*/
753
754static basicblock *
755compiler_new_block(struct compiler *c)
756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 basicblock *b;
758 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 u = c->u;
761 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
762 if (b == NULL) {
763 PyErr_NoMemory();
764 return NULL;
765 }
766 memset((void *)b, 0, sizeof(basicblock));
767 /* Extend the singly linked list of blocks with new block. */
768 b->b_list = u->u_blocks;
769 u->u_blocks = b;
770 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771}
772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774compiler_next_block(struct compiler *c)
775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 basicblock *block = compiler_new_block(c);
777 if (block == NULL)
778 return NULL;
779 c->u->u_curblock->b_next = block;
780 c->u->u_curblock = block;
781 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782}
783
784static basicblock *
785compiler_use_next_block(struct compiler *c, basicblock *block)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 assert(block != NULL);
788 c->u->u_curblock->b_next = block;
789 c->u->u_curblock = block;
790 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791}
792
793/* Returns the offset of the next instruction in the current block's
794 b_instr array. Resizes the b_instr as necessary.
795 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000797
798static int
799compiler_next_instr(struct compiler *c, basicblock *b)
800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 assert(b != NULL);
802 if (b->b_instr == NULL) {
803 b->b_instr = (struct instr *)PyObject_Malloc(
804 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
805 if (b->b_instr == NULL) {
806 PyErr_NoMemory();
807 return -1;
808 }
809 b->b_ialloc = DEFAULT_BLOCK_SIZE;
810 memset((char *)b->b_instr, 0,
811 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
812 }
813 else if (b->b_iused == b->b_ialloc) {
814 struct instr *tmp;
815 size_t oldsize, newsize;
816 oldsize = b->b_ialloc * sizeof(struct instr);
817 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000818
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700819 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyErr_NoMemory();
821 return -1;
822 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (newsize == 0) {
825 PyErr_NoMemory();
826 return -1;
827 }
828 b->b_ialloc <<= 1;
829 tmp = (struct instr *)PyObject_Realloc(
830 (void *)b->b_instr, newsize);
831 if (tmp == NULL) {
832 PyErr_NoMemory();
833 return -1;
834 }
835 b->b_instr = tmp;
836 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
837 }
838 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000839}
840
Christian Heimes2202f872008-02-06 14:31:34 +0000841/* Set the i_lineno member of the instruction at offset off if the
842 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843 already been set. If it has been set, the call has no effect.
844
Christian Heimes2202f872008-02-06 14:31:34 +0000845 The line number is reset in the following cases:
846 - when entering a new scope
847 - on each statement
848 - on each expression that start a new line
849 - before the "except" clause
850 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000851*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000853static void
854compiler_set_lineno(struct compiler *c, int off)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 basicblock *b;
857 if (c->u->u_lineno_set)
858 return;
859 c->u->u_lineno_set = 1;
860 b = c->u->u_curblock;
861 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862}
863
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200864/* Return the stack effect of opcode with argument oparg.
865
866 Some opcodes have different stack effect when jump to the target and
867 when not jump. The 'jump' parameter specifies the case:
868
869 * 0 -- when not jump
870 * 1 -- when jump
871 * -1 -- maximal
872 */
873/* XXX Make the stack effect of WITH_CLEANUP_START and
874 WITH_CLEANUP_FINISH deterministic. */
875static int
876stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 switch (opcode) {
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200879 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case POP_TOP:
881 return -1;
882 case ROT_TWO:
883 case ROT_THREE:
884 return 0;
885 case DUP_TOP:
886 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000887 case DUP_TOP_TWO:
888 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000889
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200890 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 case UNARY_POSITIVE:
892 case UNARY_NEGATIVE:
893 case UNARY_NOT:
894 case UNARY_INVERT:
895 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 case SET_ADD:
898 case LIST_APPEND:
899 return -1;
900 case MAP_ADD:
901 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000902
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200903 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case BINARY_POWER:
905 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400906 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_MODULO:
908 case BINARY_ADD:
909 case BINARY_SUBTRACT:
910 case BINARY_SUBSCR:
911 case BINARY_FLOOR_DIVIDE:
912 case BINARY_TRUE_DIVIDE:
913 return -1;
914 case INPLACE_FLOOR_DIVIDE:
915 case INPLACE_TRUE_DIVIDE:
916 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case INPLACE_ADD:
919 case INPLACE_SUBTRACT:
920 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400921 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case INPLACE_MODULO:
923 return -1;
924 case STORE_SUBSCR:
925 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 case DELETE_SUBSCR:
927 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case BINARY_LSHIFT:
930 case BINARY_RSHIFT:
931 case BINARY_AND:
932 case BINARY_XOR:
933 case BINARY_OR:
934 return -1;
935 case INPLACE_POWER:
936 return -1;
937 case GET_ITER:
938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case PRINT_EXPR:
941 return -1;
942 case LOAD_BUILD_CLASS:
943 return 1;
944 case INPLACE_LSHIFT:
945 case INPLACE_RSHIFT:
946 case INPLACE_AND:
947 case INPLACE_XOR:
948 case INPLACE_OR:
949 return -1;
950 case BREAK_LOOP:
951 return 0;
952 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200953 /* 1 in the normal flow.
954 * Restore the stack position and push 6 values before jumping to
955 * the handler if an exception be raised. */
956 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400957 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200958 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400959 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200960 /* Pop a variable number of values pushed by WITH_CLEANUP_START
961 * + __exit__ or __aexit__. */
962 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case RETURN_VALUE:
964 return -1;
965 case IMPORT_STAR:
966 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700967 case SETUP_ANNOTATIONS:
968 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case YIELD_VALUE:
970 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500971 case YIELD_FROM:
972 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case POP_BLOCK:
974 return 0;
975 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200976 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case END_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200978 /* Pop 6 values when an exception was raised. */
979 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_NAME:
982 return -1;
983 case DELETE_NAME:
984 return 0;
985 case UNPACK_SEQUENCE:
986 return oparg-1;
987 case UNPACK_EX:
988 return (oparg&0xFF) + (oparg>>8);
989 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200990 /* -1 at end of iterator, 1 if continue iterating. */
991 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case STORE_ATTR:
994 return -2;
995 case DELETE_ATTR:
996 return -1;
997 case STORE_GLOBAL:
998 return -1;
999 case DELETE_GLOBAL:
1000 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case LOAD_CONST:
1002 return 1;
1003 case LOAD_NAME:
1004 return 1;
1005 case BUILD_TUPLE:
1006 case BUILD_LIST:
1007 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001008 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001010 case BUILD_LIST_UNPACK:
1011 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001012 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_SET_UNPACK:
1014 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001015 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001016 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001018 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001019 case BUILD_CONST_KEY_MAP:
1020 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case LOAD_ATTR:
1022 return 0;
1023 case COMPARE_OP:
1024 return -1;
1025 case IMPORT_NAME:
1026 return -1;
1027 case IMPORT_FROM:
1028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001030 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case JUMP_ABSOLUTE:
1033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001035 case JUMP_IF_TRUE_OR_POP:
1036 case JUMP_IF_FALSE_OR_POP:
1037 return jump ? 0 : -1;
1038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case POP_JUMP_IF_FALSE:
1040 case POP_JUMP_IF_TRUE:
1041 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case LOAD_GLOBAL:
1044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case CONTINUE_LOOP:
1047 return 0;
1048 case SETUP_LOOP:
1049 return 0;
1050 case SETUP_EXCEPT:
1051 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001052 /* 0 in the normal flow.
1053 * Restore the stack position and push 6 values before jumping to
1054 * the handler if an exception be raised. */
1055 return jump ? 6 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case LOAD_FAST:
1058 return 1;
1059 case STORE_FAST:
1060 return -1;
1061 case DELETE_FAST:
1062 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case RAISE_VARARGS:
1065 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001066
1067 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001069 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001070 case CALL_METHOD:
1071 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001073 return -oparg-1;
1074 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001075 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001076 case MAKE_FUNCTION:
1077 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1078 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case BUILD_SLICE:
1080 if (oparg == 3)
1081 return -2;
1082 else
1083 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001084
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001085 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 case LOAD_CLOSURE:
1087 return 1;
1088 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001089 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 return 1;
1091 case STORE_DEREF:
1092 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001093 case DELETE_DEREF:
1094 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001095
1096 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001097 case GET_AWAITABLE:
1098 return 0;
1099 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001100 /* 0 in the normal flow.
1101 * Restore the stack position to the position before the result
1102 * of __aenter__ and push 6 values before jumping to the handler
1103 * if an exception be raised. */
1104 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001105 case BEFORE_ASYNC_WITH:
1106 return 1;
1107 case GET_AITER:
1108 return 0;
1109 case GET_ANEXT:
1110 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001111 case GET_YIELD_FROM_ITER:
1112 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001113 case FORMAT_VALUE:
1114 /* If there's a fmt_spec on the stack, we go from 2->1,
1115 else 1->1. */
1116 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001117 case LOAD_METHOD:
1118 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001120 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
Larry Hastings3a907972013-11-23 14:49:22 -08001122 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123}
1124
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001125int
1126PyCompile_OpcodeStackEffect(int opcode, int oparg)
1127{
1128 return stack_effect(opcode, oparg, -1);
1129}
1130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131/* Add an opcode with no argument.
1132 Returns 0 on failure, 1 on success.
1133*/
1134
1135static int
1136compiler_addop(struct compiler *c, int opcode)
1137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 basicblock *b;
1139 struct instr *i;
1140 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001141 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 off = compiler_next_instr(c, c->u->u_curblock);
1143 if (off < 0)
1144 return 0;
1145 b = c->u->u_curblock;
1146 i = &b->b_instr[off];
1147 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001148 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (opcode == RETURN_VALUE)
1150 b->b_return = 1;
1151 compiler_set_lineno(c, off);
1152 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153}
1154
Victor Stinnerf8e32212013-11-19 23:56:34 +01001155static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyObject *t, *v;
1159 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160
Victor Stinnerefb24132016-01-22 12:33:12 +01001161 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (t == NULL)
1163 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 v = PyDict_GetItem(dict, t);
1166 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001167 if (PyErr_Occurred()) {
1168 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001170 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001171 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001172 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (!v) {
1174 Py_DECREF(t);
1175 return -1;
1176 }
1177 if (PyDict_SetItem(dict, t, v) < 0) {
1178 Py_DECREF(t);
1179 Py_DECREF(v);
1180 return -1;
1181 }
1182 Py_DECREF(v);
1183 }
1184 else
1185 arg = PyLong_AsLong(v);
1186 Py_DECREF(t);
1187 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188}
1189
1190static int
1191compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001194 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001196 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 return compiler_addop_i(c, opcode, arg);
1198}
1199
1200static int
1201compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001204 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1206 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001207 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 arg = compiler_add_o(c, dict, mangled);
1209 Py_DECREF(mangled);
1210 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001211 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 return compiler_addop_i(c, opcode, arg);
1213}
1214
1215/* Add an opcode with an integer argument.
1216 Returns 0 on failure, 1 on success.
1217*/
1218
1219static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001220compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 struct instr *i;
1223 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001224
Victor Stinner2ad474b2016-03-01 23:34:47 +01001225 /* oparg value is unsigned, but a signed C int is usually used to store
1226 it in the C code (like Python/ceval.c).
1227
1228 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1229
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001230 The argument of a concrete bytecode instruction is limited to 8-bit.
1231 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1232 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001233 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 off = compiler_next_instr(c, c->u->u_curblock);
1236 if (off < 0)
1237 return 0;
1238 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001239 i->i_opcode = opcode;
1240 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 compiler_set_lineno(c, off);
1242 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243}
1244
1245static int
1246compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 struct instr *i;
1249 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001251 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 assert(b != NULL);
1253 off = compiler_next_instr(c, c->u->u_curblock);
1254 if (off < 0)
1255 return 0;
1256 i = &c->u->u_curblock->b_instr[off];
1257 i->i_opcode = opcode;
1258 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (absolute)
1260 i->i_jabs = 1;
1261 else
1262 i->i_jrel = 1;
1263 compiler_set_lineno(c, off);
1264 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001267/* NEXT_BLOCK() creates an implicit jump from the current block
1268 to the new block.
1269
1270 The returns inside this macro make it impossible to decref objects
1271 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (compiler_next_block((C)) == NULL) \
1275 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_addop((C), (OP))) \
1280 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001283#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!compiler_addop((C), (OP))) { \
1285 compiler_exit_scope(c); \
1286 return 0; \
1287 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001288}
1289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1292 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293}
1294
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001295/* Same as ADDOP_O, but steals a reference. */
1296#define ADDOP_N(C, OP, O, TYPE) { \
1297 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1298 Py_DECREF((O)); \
1299 return 0; \
1300 } \
1301 Py_DECREF((O)); \
1302}
1303
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001304#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1306 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307}
1308
1309#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!compiler_addop_i((C), (OP), (O))) \
1311 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312}
1313
1314#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (!compiler_addop_j((C), (OP), (O), 1)) \
1316 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317}
1318
1319#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!compiler_addop_j((C), (OP), (O), 0)) \
1321 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1325 the ASDL name to synthesize the name of the C type and the visit function.
1326*/
1327
1328#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (!compiler_visit_ ## TYPE((C), (V))) \
1330 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331}
1332
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001333#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (!compiler_visit_ ## TYPE((C), (V))) { \
1335 compiler_exit_scope(c); \
1336 return 0; \
1337 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001338}
1339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 if (!compiler_visit_slice((C), (V), (CTX))) \
1342 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343}
1344
1345#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 int _i; \
1347 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1348 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1349 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1350 if (!compiler_visit_ ## TYPE((C), elt)) \
1351 return 0; \
1352 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353}
1354
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001355#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 int _i; \
1357 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1358 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1359 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1360 if (!compiler_visit_ ## TYPE((C), elt)) { \
1361 compiler_exit_scope(c); \
1362 return 0; \
1363 } \
1364 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001365}
1366
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001368is_const(expr_ty e)
1369{
1370 switch (e->kind) {
1371 case Constant_kind:
1372 case Num_kind:
1373 case Str_kind:
1374 case Bytes_kind:
1375 case Ellipsis_kind:
1376 case NameConstant_kind:
1377 return 1;
1378 default:
1379 return 0;
1380 }
1381}
1382
1383static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001384get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001385{
1386 switch (e->kind) {
1387 case Constant_kind:
1388 return e->v.Constant.value;
1389 case Num_kind:
1390 return e->v.Num.n;
1391 case Str_kind:
1392 return e->v.Str.s;
1393 case Bytes_kind:
1394 return e->v.Bytes.s;
1395 case Ellipsis_kind:
1396 return Py_Ellipsis;
1397 case NameConstant_kind:
1398 return e->v.NameConstant.value;
1399 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001400 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001401 }
1402}
1403
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001404/* Search if variable annotations are present statically in a block. */
1405
1406static int
1407find_ann(asdl_seq *stmts)
1408{
1409 int i, j, res = 0;
1410 stmt_ty st;
1411
1412 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1413 st = (stmt_ty)asdl_seq_GET(stmts, i);
1414 switch (st->kind) {
1415 case AnnAssign_kind:
1416 return 1;
1417 case For_kind:
1418 res = find_ann(st->v.For.body) ||
1419 find_ann(st->v.For.orelse);
1420 break;
1421 case AsyncFor_kind:
1422 res = find_ann(st->v.AsyncFor.body) ||
1423 find_ann(st->v.AsyncFor.orelse);
1424 break;
1425 case While_kind:
1426 res = find_ann(st->v.While.body) ||
1427 find_ann(st->v.While.orelse);
1428 break;
1429 case If_kind:
1430 res = find_ann(st->v.If.body) ||
1431 find_ann(st->v.If.orelse);
1432 break;
1433 case With_kind:
1434 res = find_ann(st->v.With.body);
1435 break;
1436 case AsyncWith_kind:
1437 res = find_ann(st->v.AsyncWith.body);
1438 break;
1439 case Try_kind:
1440 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1441 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1442 st->v.Try.handlers, j);
1443 if (find_ann(handler->v.ExceptHandler.body)) {
1444 return 1;
1445 }
1446 }
1447 res = find_ann(st->v.Try.body) ||
1448 find_ann(st->v.Try.finalbody) ||
1449 find_ann(st->v.Try.orelse);
1450 break;
1451 default:
1452 res = 0;
1453 }
1454 if (res) {
1455 break;
1456 }
1457 }
1458 return res;
1459}
1460
1461/* Compile a sequence of statements, checking for a docstring
1462 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463
1464static int
INADA Naokicb41b272017-02-23 00:31:59 +09001465compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001467 /* Set current line number to the line number of first statement.
1468 This way line number for SETUP_ANNOTATIONS will always
1469 coincide with the line number of first "real" statement in module.
1470 If body is empy, then lineno will be set later in assemble. */
1471 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1472 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001473 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001474 c->u->u_lineno = st->lineno;
1475 }
1476 /* Every annotated class and module should have __annotations__. */
1477 if (find_ann(stmts)) {
1478 ADDOP(c, SETUP_ANNOTATIONS);
1479 }
INADA Naokicb41b272017-02-23 00:31:59 +09001480 /* if not -OO mode, set docstring */
1481 if (c->c_optimize < 2 && docstring) {
1482 ADDOP_O(c, LOAD_CONST, docstring, consts);
1483 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 }
INADA Naokicb41b272017-02-23 00:31:59 +09001485 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
1489static PyCodeObject *
1490compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 PyCodeObject *co;
1493 int addNone = 1;
1494 static PyObject *module;
1495 if (!module) {
1496 module = PyUnicode_InternFromString("<module>");
1497 if (!module)
1498 return NULL;
1499 }
1500 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001501 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 return NULL;
1503 switch (mod->kind) {
1504 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001505 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 compiler_exit_scope(c);
1507 return 0;
1508 }
1509 break;
1510 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001511 if (find_ann(mod->v.Interactive.body)) {
1512 ADDOP(c, SETUP_ANNOTATIONS);
1513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 c->c_interactive = 1;
1515 VISIT_SEQ_IN_SCOPE(c, stmt,
1516 mod->v.Interactive.body);
1517 break;
1518 case Expression_kind:
1519 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1520 addNone = 0;
1521 break;
1522 case Suite_kind:
1523 PyErr_SetString(PyExc_SystemError,
1524 "suite should not be possible");
1525 return 0;
1526 default:
1527 PyErr_Format(PyExc_SystemError,
1528 "module kind %d should not be possible",
1529 mod->kind);
1530 return 0;
1531 }
1532 co = assemble(c, addNone);
1533 compiler_exit_scope(c);
1534 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001535}
1536
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537/* The test for LOCAL must come before the test for FREE in order to
1538 handle classes where name is both local and free. The local var is
1539 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001540*/
1541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542static int
1543get_ref_type(struct compiler *c, PyObject *name)
1544{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001545 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001546 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001547 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001548 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001549 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (scope == 0) {
1551 char buf[350];
1552 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001553 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001555 PyUnicode_AsUTF8(name),
1556 PyUnicode_AsUTF8(c->u->u_name),
1557 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1558 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1559 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1560 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 );
1562 Py_FatalError(buf);
1563 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566}
1567
1568static int
1569compiler_lookup_arg(PyObject *dict, PyObject *name)
1570{
1571 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001572 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001574 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001576 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001578 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001579 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580}
1581
1582static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001583compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001584{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001585 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001586 if (qualname == NULL)
1587 qualname = co->co_name;
1588
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001589 if (free) {
1590 for (i = 0; i < free; ++i) {
1591 /* Bypass com_addop_varname because it will generate
1592 LOAD_DEREF but LOAD_CLOSURE is needed.
1593 */
1594 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1595 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001597 /* Special case: If a class contains a method with a
1598 free variable that has the same name as a method,
1599 the name will be considered free *and* local in the
1600 class. It should be handled by the closure, as
1601 well as by the normal name loookup logic.
1602 */
1603 reftype = get_ref_type(c, name);
1604 if (reftype == CELL)
1605 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1606 else /* (reftype == FREE) */
1607 arg = compiler_lookup_arg(c->u->u_freevars, name);
1608 if (arg == -1) {
1609 fprintf(stderr,
1610 "lookup %s in %s %d %d\n"
1611 "freevars of %s: %s\n",
1612 PyUnicode_AsUTF8(PyObject_Repr(name)),
1613 PyUnicode_AsUTF8(c->u->u_name),
1614 reftype, arg,
1615 PyUnicode_AsUTF8(co->co_name),
1616 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1617 Py_FatalError("compiler_make_closure()");
1618 }
1619 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001621 flags |= 0x08;
1622 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001625 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001626 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628}
1629
1630static int
1631compiler_decorators(struct compiler *c, asdl_seq* decos)
1632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 if (!decos)
1636 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1639 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1640 }
1641 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642}
1643
1644static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001645compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001647{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001648 /* Push a dict of keyword-only default values.
1649
1650 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1651 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001652 int i;
1653 PyObject *keys = NULL;
1654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1656 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1657 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1658 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001659 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001660 if (!mangled) {
1661 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001663 if (keys == NULL) {
1664 keys = PyList_New(1);
1665 if (keys == NULL) {
1666 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001667 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001668 }
1669 PyList_SET_ITEM(keys, 0, mangled);
1670 }
1671 else {
1672 int res = PyList_Append(keys, mangled);
1673 Py_DECREF(mangled);
1674 if (res == -1) {
1675 goto error;
1676 }
1677 }
1678 if (!compiler_visit_expr(c, default_)) {
1679 goto error;
1680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 }
1682 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001683 if (keys != NULL) {
1684 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1685 PyObject *keys_tuple = PyList_AsTuple(keys);
1686 Py_DECREF(keys);
1687 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001688 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001689 }
1690 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1691 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001692 assert(default_count > 0);
1693 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001694 }
1695 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001696 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001697 }
1698
1699error:
1700 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001701 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001702}
1703
1704static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001705compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1706{
1707 PyObject *ann_as_str;
1708 ann_as_str = _PyAST_ExprAsUnicode(annotation, 1);
1709 if (!ann_as_str) {
1710 return 0;
1711 }
1712 ADDOP_N(c, LOAD_CONST, ann_as_str, consts);
1713 return 1;
1714}
1715
1716static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001717compiler_visit_argannotation(struct compiler *c, identifier id,
1718 expr_ty annotation, PyObject *names)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001721 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001722 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1723 VISIT(c, annexpr, annotation)
1724 }
1725 else {
1726 VISIT(c, expr, annotation);
1727 }
Victor Stinner065efc32014-02-18 22:07:56 +01001728 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001729 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001730 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001731 if (PyList_Append(names, mangled) < 0) {
1732 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001733 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001734 }
1735 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001737 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001738}
1739
1740static int
1741compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1742 PyObject *names)
1743{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001744 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 for (i = 0; i < asdl_seq_LEN(args); i++) {
1746 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001747 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 c,
1749 arg->arg,
1750 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001751 names))
1752 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001754 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001755}
1756
1757static int
1758compiler_visit_annotations(struct compiler *c, arguments_ty args,
1759 expr_ty returns)
1760{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001761 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001762 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001763
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001764 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 */
1766 static identifier return_str;
1767 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001768 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 names = PyList_New(0);
1770 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001771 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001772
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001773 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001775 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001776 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001777 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001779 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001781 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001782 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001783 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (!return_str) {
1787 return_str = PyUnicode_InternFromString("return");
1788 if (!return_str)
1789 goto error;
1790 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001791 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 goto error;
1793 }
1794
1795 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001797 PyObject *keytuple = PyList_AsTuple(names);
1798 Py_DECREF(names);
1799 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001800 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001802 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1803 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001804 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001806 else {
1807 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001808 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001809 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001810
1811error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001813 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001814}
1815
1816static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001817compiler_visit_defaults(struct compiler *c, arguments_ty args)
1818{
1819 VISIT_SEQ(c, expr, args->defaults);
1820 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1821 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822}
1823
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001824static Py_ssize_t
1825compiler_default_arguments(struct compiler *c, arguments_ty args)
1826{
1827 Py_ssize_t funcflags = 0;
1828 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001829 if (!compiler_visit_defaults(c, args))
1830 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001831 funcflags |= 0x01;
1832 }
1833 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001834 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001835 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001836 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001837 return -1;
1838 }
1839 else if (res > 0) {
1840 funcflags |= 0x02;
1841 }
1842 }
1843 return funcflags;
1844}
1845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846static int
Yury Selivanov75445082015-05-11 22:57:16 -04001847compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001850 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001851 arguments_ty args;
1852 expr_ty returns;
1853 identifier name;
1854 asdl_seq* decos;
1855 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001856 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001857 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001858 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Yury Selivanov75445082015-05-11 22:57:16 -04001860 if (is_async) {
1861 assert(s->kind == AsyncFunctionDef_kind);
1862
1863 args = s->v.AsyncFunctionDef.args;
1864 returns = s->v.AsyncFunctionDef.returns;
1865 decos = s->v.AsyncFunctionDef.decorator_list;
1866 name = s->v.AsyncFunctionDef.name;
1867 body = s->v.AsyncFunctionDef.body;
1868
1869 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1870 } else {
1871 assert(s->kind == FunctionDef_kind);
1872
1873 args = s->v.FunctionDef.args;
1874 returns = s->v.FunctionDef.returns;
1875 decos = s->v.FunctionDef.decorator_list;
1876 name = s->v.FunctionDef.name;
1877 body = s->v.FunctionDef.body;
1878
1879 scope_type = COMPILER_SCOPE_FUNCTION;
1880 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (!compiler_decorators(c, decos))
1883 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001884
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 funcflags = compiler_default_arguments(c, args);
1886 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001888 }
1889
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001890 annotations = compiler_visit_annotations(c, args, returns);
1891 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001892 return 0;
1893 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001894 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001895 funcflags |= 0x04;
1896 }
1897
1898 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1899 return 0;
1900 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901
INADA Naokicb41b272017-02-23 00:31:59 +09001902 /* if not -OO mode, add docstring */
1903 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
1904 docstring = s->v.FunctionDef.docstring;
1905 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 compiler_exit_scope(c);
1907 return 0;
1908 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 c->u->u_argcount = asdl_seq_LEN(args->args);
1911 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09001913 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001915 qualname = c->u->u_qualname;
1916 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001918 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001919 Py_XDECREF(qualname);
1920 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001922 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001925 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 /* decorators */
1929 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1930 ADDOP_I(c, CALL_FUNCTION, 1);
1931 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932
Yury Selivanov75445082015-05-11 22:57:16 -04001933 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001934}
1935
1936static int
1937compiler_class(struct compiler *c, stmt_ty s)
1938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyCodeObject *co;
1940 PyObject *str;
1941 int i;
1942 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (!compiler_decorators(c, decos))
1945 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 /* ultimately generate code for:
1948 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1949 where:
1950 <func> is a function/closure created from the class body;
1951 it has a single argument (__locals__) where the dict
1952 (or MutableSequence) representing the locals is passed
1953 <name> is the class name
1954 <bases> is the positional arguments and *varargs argument
1955 <keywords> is the keyword arguments and **kwds argument
1956 This borrows from compiler_call.
1957 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001960 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1961 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return 0;
1963 /* this block represents what we do in the new scope */
1964 {
1965 /* use the class name for name mangling */
1966 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001967 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* load (global) __name__ ... */
1969 str = PyUnicode_InternFromString("__name__");
1970 if (!str || !compiler_nameop(c, str, Load)) {
1971 Py_XDECREF(str);
1972 compiler_exit_scope(c);
1973 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001974 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 Py_DECREF(str);
1976 /* ... and store it as __module__ */
1977 str = PyUnicode_InternFromString("__module__");
1978 if (!str || !compiler_nameop(c, str, Store)) {
1979 Py_XDECREF(str);
1980 compiler_exit_scope(c);
1981 return 0;
1982 }
1983 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001984 assert(c->u->u_qualname);
1985 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001986 str = PyUnicode_InternFromString("__qualname__");
1987 if (!str || !compiler_nameop(c, str, Store)) {
1988 Py_XDECREF(str);
1989 compiler_exit_scope(c);
1990 return 0;
1991 }
1992 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09001994 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 compiler_exit_scope(c);
1996 return 0;
1997 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001998 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001999 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002000 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002001 str = PyUnicode_InternFromString("__class__");
2002 if (str == NULL) {
2003 compiler_exit_scope(c);
2004 return 0;
2005 }
2006 i = compiler_lookup_arg(c->u->u_cellvars, str);
2007 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002008 if (i < 0) {
2009 compiler_exit_scope(c);
2010 return 0;
2011 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002012 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002015 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002016 str = PyUnicode_InternFromString("__classcell__");
2017 if (!str || !compiler_nameop(c, str, Store)) {
2018 Py_XDECREF(str);
2019 compiler_exit_scope(c);
2020 return 0;
2021 }
2022 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002024 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002025 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002026 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10002027 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002028 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002029 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* create the code object */
2031 co = assemble(c, 1);
2032 }
2033 /* leave the new scope */
2034 compiler_exit_scope(c);
2035 if (co == NULL)
2036 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* 2. load the 'build_class' function */
2039 ADDOP(c, LOAD_BUILD_CLASS);
2040
2041 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002042 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 Py_DECREF(co);
2044
2045 /* 4. load class name */
2046 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2047
2048 /* 5. generate the rest of the code for the call */
2049 if (!compiler_call_helper(c, 2,
2050 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002051 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 return 0;
2053
2054 /* 6. apply decorators */
2055 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2056 ADDOP_I(c, CALL_FUNCTION, 1);
2057 }
2058
2059 /* 7. store into <name> */
2060 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2061 return 0;
2062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063}
2064
2065static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002066cmpop(cmpop_ty op)
2067{
2068 switch (op) {
2069 case Eq:
2070 return PyCmp_EQ;
2071 case NotEq:
2072 return PyCmp_NE;
2073 case Lt:
2074 return PyCmp_LT;
2075 case LtE:
2076 return PyCmp_LE;
2077 case Gt:
2078 return PyCmp_GT;
2079 case GtE:
2080 return PyCmp_GE;
2081 case Is:
2082 return PyCmp_IS;
2083 case IsNot:
2084 return PyCmp_IS_NOT;
2085 case In:
2086 return PyCmp_IN;
2087 case NotIn:
2088 return PyCmp_NOT_IN;
2089 default:
2090 return PyCmp_BAD;
2091 }
2092}
2093
2094static int
2095compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2096{
2097 switch (e->kind) {
2098 case UnaryOp_kind:
2099 if (e->v.UnaryOp.op == Not)
2100 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2101 /* fallback to general implementation */
2102 break;
2103 case BoolOp_kind: {
2104 asdl_seq *s = e->v.BoolOp.values;
2105 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2106 assert(n >= 0);
2107 int cond2 = e->v.BoolOp.op == Or;
2108 basicblock *next2 = next;
2109 if (!cond2 != !cond) {
2110 next2 = compiler_new_block(c);
2111 if (next2 == NULL)
2112 return 0;
2113 }
2114 for (i = 0; i < n; ++i) {
2115 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2116 return 0;
2117 }
2118 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2119 return 0;
2120 if (next2 != next)
2121 compiler_use_next_block(c, next2);
2122 return 1;
2123 }
2124 case IfExp_kind: {
2125 basicblock *end, *next2;
2126 end = compiler_new_block(c);
2127 if (end == NULL)
2128 return 0;
2129 next2 = compiler_new_block(c);
2130 if (next2 == NULL)
2131 return 0;
2132 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2133 return 0;
2134 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2135 return 0;
2136 ADDOP_JREL(c, JUMP_FORWARD, end);
2137 compiler_use_next_block(c, next2);
2138 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2139 return 0;
2140 compiler_use_next_block(c, end);
2141 return 1;
2142 }
2143 case Compare_kind: {
2144 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2145 if (n > 0) {
2146 basicblock *cleanup = compiler_new_block(c);
2147 if (cleanup == NULL)
2148 return 0;
2149 VISIT(c, expr, e->v.Compare.left);
2150 for (i = 0; i < n; i++) {
2151 VISIT(c, expr,
2152 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2153 ADDOP(c, DUP_TOP);
2154 ADDOP(c, ROT_THREE);
2155 ADDOP_I(c, COMPARE_OP,
2156 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2157 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2158 NEXT_BLOCK(c);
2159 }
2160 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2161 ADDOP_I(c, COMPARE_OP,
2162 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2163 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2164 basicblock *end = compiler_new_block(c);
2165 if (end == NULL)
2166 return 0;
2167 ADDOP_JREL(c, JUMP_FORWARD, end);
2168 compiler_use_next_block(c, cleanup);
2169 ADDOP(c, POP_TOP);
2170 if (!cond) {
2171 ADDOP_JREL(c, JUMP_FORWARD, next);
2172 }
2173 compiler_use_next_block(c, end);
2174 return 1;
2175 }
2176 /* fallback to general implementation */
2177 break;
2178 }
2179 default:
2180 /* fallback to general implementation */
2181 break;
2182 }
2183
2184 /* general implementation */
2185 VISIT(c, expr, e);
2186 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2187 return 1;
2188}
2189
2190static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002191compiler_ifexp(struct compiler *c, expr_ty e)
2192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 basicblock *end, *next;
2194
2195 assert(e->kind == IfExp_kind);
2196 end = compiler_new_block(c);
2197 if (end == NULL)
2198 return 0;
2199 next = compiler_new_block(c);
2200 if (next == NULL)
2201 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002202 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2203 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 VISIT(c, expr, e->v.IfExp.body);
2205 ADDOP_JREL(c, JUMP_FORWARD, end);
2206 compiler_use_next_block(c, next);
2207 VISIT(c, expr, e->v.IfExp.orelse);
2208 compiler_use_next_block(c, end);
2209 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002210}
2211
2212static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213compiler_lambda(struct compiler *c, expr_ty e)
2214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002216 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002218 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 arguments_ty args = e->v.Lambda.args;
2220 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (!name) {
2223 name = PyUnicode_InternFromString("<lambda>");
2224 if (!name)
2225 return 0;
2226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002228 funcflags = compiler_default_arguments(c, args);
2229 if (funcflags == -1) {
2230 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002232
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002233 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002234 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Make None the first constant, so the lambda can't have a
2238 docstring. */
2239 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2240 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 c->u->u_argcount = asdl_seq_LEN(args->args);
2243 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2244 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2245 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002246 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 }
2248 else {
2249 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002250 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002252 qualname = c->u->u_qualname;
2253 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002255 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002258 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002259 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 Py_DECREF(co);
2261
2262 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263}
2264
2265static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266compiler_if(struct compiler *c, stmt_ty s)
2267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 basicblock *end, *next;
2269 int constant;
2270 assert(s->kind == If_kind);
2271 end = compiler_new_block(c);
2272 if (end == NULL)
2273 return 0;
2274
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002275 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 /* constant = 0: "if 0"
2277 * constant = 1: "if 1", "if 2", ...
2278 * constant = -1: rest */
2279 if (constant == 0) {
2280 if (s->v.If.orelse)
2281 VISIT_SEQ(c, stmt, s->v.If.orelse);
2282 } else if (constant == 1) {
2283 VISIT_SEQ(c, stmt, s->v.If.body);
2284 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002285 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 next = compiler_new_block(c);
2287 if (next == NULL)
2288 return 0;
2289 }
2290 else
2291 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002292 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2293 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002295 if (asdl_seq_LEN(s->v.If.orelse)) {
2296 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 compiler_use_next_block(c, next);
2298 VISIT_SEQ(c, stmt, s->v.If.orelse);
2299 }
2300 }
2301 compiler_use_next_block(c, end);
2302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303}
2304
2305static int
2306compiler_for(struct compiler *c, stmt_ty s)
2307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 start = compiler_new_block(c);
2311 cleanup = compiler_new_block(c);
2312 end = compiler_new_block(c);
2313 if (start == NULL || end == NULL || cleanup == NULL)
2314 return 0;
2315 ADDOP_JREL(c, SETUP_LOOP, end);
2316 if (!compiler_push_fblock(c, LOOP, start))
2317 return 0;
2318 VISIT(c, expr, s->v.For.iter);
2319 ADDOP(c, GET_ITER);
2320 compiler_use_next_block(c, start);
2321 ADDOP_JREL(c, FOR_ITER, cleanup);
2322 VISIT(c, expr, s->v.For.target);
2323 VISIT_SEQ(c, stmt, s->v.For.body);
2324 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2325 compiler_use_next_block(c, cleanup);
2326 ADDOP(c, POP_BLOCK);
2327 compiler_pop_fblock(c, LOOP, start);
2328 VISIT_SEQ(c, stmt, s->v.For.orelse);
2329 compiler_use_next_block(c, end);
2330 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331}
2332
Yury Selivanov75445082015-05-11 22:57:16 -04002333
2334static int
2335compiler_async_for(struct compiler *c, stmt_ty s)
2336{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002337 _Py_IDENTIFIER(StopAsyncIteration);
2338
Yury Selivanov75445082015-05-11 22:57:16 -04002339 basicblock *try, *except, *end, *after_try, *try_cleanup,
Serhiy Storchaka9e94c0d2018-03-10 20:45:05 +02002340 *after_loop_else;
Yury Selivanov75445082015-05-11 22:57:16 -04002341
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002342 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2343 if (stop_aiter_error == NULL) {
2344 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002345 }
2346
2347 try = compiler_new_block(c);
2348 except = compiler_new_block(c);
2349 end = compiler_new_block(c);
2350 after_try = compiler_new_block(c);
2351 try_cleanup = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002352 after_loop_else = compiler_new_block(c);
2353
2354 if (try == NULL || except == NULL || end == NULL
Serhiy Storchaka9e94c0d2018-03-10 20:45:05 +02002355 || after_try == NULL || try_cleanup == NULL
2356 || after_loop_else == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002357 return 0;
2358
Serhiy Storchaka9e94c0d2018-03-10 20:45:05 +02002359 ADDOP_JREL(c, SETUP_LOOP, end);
Yury Selivanov75445082015-05-11 22:57:16 -04002360 if (!compiler_push_fblock(c, LOOP, try))
2361 return 0;
2362
2363 VISIT(c, expr, s->v.AsyncFor.iter);
2364 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002365
2366 compiler_use_next_block(c, try);
2367
2368
2369 ADDOP_JREL(c, SETUP_EXCEPT, except);
2370 if (!compiler_push_fblock(c, EXCEPT, try))
2371 return 0;
2372
2373 ADDOP(c, GET_ANEXT);
2374 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2375 ADDOP(c, YIELD_FROM);
2376 VISIT(c, expr, s->v.AsyncFor.target);
2377 ADDOP(c, POP_BLOCK);
2378 compiler_pop_fblock(c, EXCEPT, try);
2379 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2380
2381
2382 compiler_use_next_block(c, except);
2383 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002384 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002385 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Serhiy Storchakab9744e92018-03-23 14:35:33 +02002386 ADDOP_JABS(c, POP_JUMP_IF_TRUE, try_cleanup);
Yury Selivanov75445082015-05-11 22:57:16 -04002387 ADDOP(c, END_FINALLY);
2388
2389 compiler_use_next_block(c, after_try);
2390 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2391 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2392
Serhiy Storchakab9744e92018-03-23 14:35:33 +02002393 compiler_use_next_block(c, try_cleanup);
2394 ADDOP(c, POP_TOP);
2395 ADDOP(c, POP_TOP);
2396 ADDOP(c, POP_TOP);
2397 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2398 ADDOP(c, POP_TOP); /* for correct calculation of stack effect */
Yury Selivanov75445082015-05-11 22:57:16 -04002399 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2400 compiler_pop_fblock(c, LOOP, try);
2401
Yury Selivanov75445082015-05-11 22:57:16 -04002402 compiler_use_next_block(c, after_loop_else);
2403 VISIT_SEQ(c, stmt, s->v.For.orelse);
2404
2405 compiler_use_next_block(c, end);
2406
2407 return 1;
2408}
2409
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410static int
2411compiler_while(struct compiler *c, stmt_ty s)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002414 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (constant == 0) {
2417 if (s->v.While.orelse)
2418 VISIT_SEQ(c, stmt, s->v.While.orelse);
2419 return 1;
2420 }
2421 loop = compiler_new_block(c);
2422 end = compiler_new_block(c);
2423 if (constant == -1) {
2424 anchor = compiler_new_block(c);
2425 if (anchor == NULL)
2426 return 0;
2427 }
2428 if (loop == NULL || end == NULL)
2429 return 0;
2430 if (s->v.While.orelse) {
2431 orelse = compiler_new_block(c);
2432 if (orelse == NULL)
2433 return 0;
2434 }
2435 else
2436 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 ADDOP_JREL(c, SETUP_LOOP, end);
2439 compiler_use_next_block(c, loop);
2440 if (!compiler_push_fblock(c, LOOP, loop))
2441 return 0;
2442 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002443 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2444 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 }
2446 VISIT_SEQ(c, stmt, s->v.While.body);
2447 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* XXX should the two POP instructions be in a separate block
2450 if there is no else clause ?
2451 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002452
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002453 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002455 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 compiler_pop_fblock(c, LOOP, loop);
2457 if (orelse != NULL) /* what if orelse is just pass? */
2458 VISIT_SEQ(c, stmt, s->v.While.orelse);
2459 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462}
2463
2464static int
2465compiler_continue(struct compiler *c)
2466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2468 static const char IN_FINALLY_ERROR_MSG[] =
2469 "'continue' not supported inside 'finally' clause";
2470 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 if (!c->u->u_nfblocks)
2473 return compiler_error(c, LOOP_ERROR_MSG);
2474 i = c->u->u_nfblocks - 1;
2475 switch (c->u->u_fblock[i].fb_type) {
2476 case LOOP:
2477 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2478 break;
2479 case EXCEPT:
2480 case FINALLY_TRY:
2481 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2482 /* Prevent continue anywhere under a finally
2483 even if hidden in a sub-try or except. */
2484 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2485 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2486 }
2487 if (i == -1)
2488 return compiler_error(c, LOOP_ERROR_MSG);
2489 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2490 break;
2491 case FINALLY_END:
2492 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496}
2497
2498/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499
2500 SETUP_FINALLY L
2501 <code for body>
2502 POP_BLOCK
2503 LOAD_CONST <None>
2504 L: <code for finalbody>
2505 END_FINALLY
2506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 The special instructions use the block stack. Each block
2508 stack entry contains the instruction that created it (here
2509 SETUP_FINALLY), the level of the value stack at the time the
2510 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002512 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 Pushes the current value stack level and the label
2514 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 Pops en entry from the block stack, and pops the value
2517 stack until its level is the same as indicated on the
2518 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 Pops a variable number of entries from the *value* stack
2521 and re-raises the exception they specify. The number of
2522 entries popped depends on the (pseudo) exception type.
2523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 The block stack is unwound when an exception is raised:
2525 when a SETUP_FINALLY entry is found, the exception is pushed
2526 onto the value stack (and the exception condition is cleared),
2527 and the interpreter jumps to the label gotten from the block
2528 stack.
2529*/
2530
2531static int
2532compiler_try_finally(struct compiler *c, stmt_ty s)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 basicblock *body, *end;
2535 body = compiler_new_block(c);
2536 end = compiler_new_block(c);
2537 if (body == NULL || end == NULL)
2538 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 ADDOP_JREL(c, SETUP_FINALLY, end);
2541 compiler_use_next_block(c, body);
2542 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2543 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002544 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2545 if (!compiler_try_except(c, s))
2546 return 0;
2547 }
2548 else {
2549 VISIT_SEQ(c, stmt, s->v.Try.body);
2550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 ADDOP(c, POP_BLOCK);
2552 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2555 compiler_use_next_block(c, end);
2556 if (!compiler_push_fblock(c, FINALLY_END, end))
2557 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002558 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 ADDOP(c, END_FINALLY);
2560 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563}
2564
2565/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002566 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 (The contents of the value stack is shown in [], with the top
2568 at the right; 'tb' is trace-back info, 'val' the exception's
2569 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570
2571 Value stack Label Instruction Argument
2572 [] SETUP_EXCEPT L1
2573 [] <code for S>
2574 [] POP_BLOCK
2575 [] JUMP_FORWARD L0
2576
2577 [tb, val, exc] L1: DUP )
2578 [tb, val, exc, exc] <evaluate E1> )
2579 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2580 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2581 [tb, val, exc] POP
2582 [tb, val] <assign to V1> (or POP if no V1)
2583 [tb] POP
2584 [] <code for S1>
2585 JUMP_FORWARD L0
2586
2587 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 .............................etc.......................
2589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2591
2592 [] L0: <next statement>
2593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 Of course, parts are not generated if Vi or Ei is not present.
2595*/
2596static int
2597compiler_try_except(struct compiler *c, stmt_ty s)
2598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002600 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 body = compiler_new_block(c);
2603 except = compiler_new_block(c);
2604 orelse = compiler_new_block(c);
2605 end = compiler_new_block(c);
2606 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2607 return 0;
2608 ADDOP_JREL(c, SETUP_EXCEPT, except);
2609 compiler_use_next_block(c, body);
2610 if (!compiler_push_fblock(c, EXCEPT, body))
2611 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002612 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 ADDOP(c, POP_BLOCK);
2614 compiler_pop_fblock(c, EXCEPT, body);
2615 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002616 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 compiler_use_next_block(c, except);
2618 for (i = 0; i < n; i++) {
2619 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002620 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 if (!handler->v.ExceptHandler.type && i < n-1)
2622 return compiler_error(c, "default 'except:' must be last");
2623 c->u->u_lineno_set = 0;
2624 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002625 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 except = compiler_new_block(c);
2627 if (except == NULL)
2628 return 0;
2629 if (handler->v.ExceptHandler.type) {
2630 ADDOP(c, DUP_TOP);
2631 VISIT(c, expr, handler->v.ExceptHandler.type);
2632 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2633 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2634 }
2635 ADDOP(c, POP_TOP);
2636 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002637 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002638
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002639 cleanup_end = compiler_new_block(c);
2640 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002641 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002642 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002643
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002644 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2645 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002647 /*
2648 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002649 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002650 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002651 try:
2652 # body
2653 finally:
2654 name = None
2655 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002656 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002658 /* second try: */
2659 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2660 compiler_use_next_block(c, cleanup_body);
2661 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2662 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002664 /* second # body */
2665 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2666 ADDOP(c, POP_BLOCK);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002667 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002669 /* finally: */
2670 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2671 compiler_use_next_block(c, cleanup_end);
2672 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2673 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002675 /* name = None */
2676 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2677 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002679 /* del name */
2680 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002682 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002683 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002684 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 }
2686 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002687 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002689 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002690 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002691 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692
Guido van Rossumb940e112007-01-10 16:19:56 +00002693 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002694 ADDOP(c, POP_TOP);
2695 compiler_use_next_block(c, cleanup_body);
2696 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2697 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002699 ADDOP(c, POP_EXCEPT);
2700 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 }
2702 ADDOP_JREL(c, JUMP_FORWARD, end);
2703 compiler_use_next_block(c, except);
2704 }
2705 ADDOP(c, END_FINALLY);
2706 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002707 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 compiler_use_next_block(c, end);
2709 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710}
2711
2712static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002713compiler_try(struct compiler *c, stmt_ty s) {
2714 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2715 return compiler_try_finally(c, s);
2716 else
2717 return compiler_try_except(c, s);
2718}
2719
2720
2721static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722compiler_import_as(struct compiler *c, identifier name, identifier asname)
2723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 /* The IMPORT_NAME opcode was already generated. This function
2725 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002728 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002730 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2731 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002733 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002736 while (1) {
2737 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002739 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002741 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002742 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002744 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002745 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002747 if (dot == -1) {
2748 break;
2749 }
2750 ADDOP(c, ROT_TWO);
2751 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002753 if (!compiler_nameop(c, asname, Store)) {
2754 return 0;
2755 }
2756 ADDOP(c, POP_TOP);
2757 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 }
2759 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760}
2761
2762static int
2763compiler_import(struct compiler *c, stmt_ty s)
2764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 /* The Import node stores a module name like a.b.c as a single
2766 string. This is convenient for all cases except
2767 import a.b.c as d
2768 where we need to parse that string to extract the individual
2769 module names.
2770 XXX Perhaps change the representation to make this case simpler?
2771 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002772 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 for (i = 0; i < n; i++) {
2775 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2776 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002778 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2780 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 if (alias->asname) {
2783 r = compiler_import_as(c, alias->name, alias->asname);
2784 if (!r)
2785 return r;
2786 }
2787 else {
2788 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 Py_ssize_t dot = PyUnicode_FindChar(
2790 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002791 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002793 if (tmp == NULL)
2794 return 0;
2795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002797 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 Py_DECREF(tmp);
2799 }
2800 if (!r)
2801 return r;
2802 }
2803 }
2804 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805}
2806
2807static int
2808compiler_from_import(struct compiler *c, stmt_ty s)
2809{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002810 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 PyObject *names = PyTuple_New(n);
2813 PyObject *level;
2814 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 if (!empty_string) {
2817 empty_string = PyUnicode_FromString("");
2818 if (!empty_string)
2819 return 0;
2820 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 if (!names)
2823 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 level = PyLong_FromLong(s->v.ImportFrom.level);
2826 if (!level) {
2827 Py_DECREF(names);
2828 return 0;
2829 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 /* build up the names */
2832 for (i = 0; i < n; i++) {
2833 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2834 Py_INCREF(alias->name);
2835 PyTuple_SET_ITEM(names, i, alias->name);
2836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002839 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 Py_DECREF(level);
2841 Py_DECREF(names);
2842 return compiler_error(c, "from __future__ imports must occur "
2843 "at the beginning of the file");
2844 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 ADDOP_O(c, LOAD_CONST, level, consts);
2847 Py_DECREF(level);
2848 ADDOP_O(c, LOAD_CONST, names, consts);
2849 Py_DECREF(names);
2850 if (s->v.ImportFrom.module) {
2851 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2852 }
2853 else {
2854 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2855 }
2856 for (i = 0; i < n; i++) {
2857 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2858 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002860 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 assert(n == 1);
2862 ADDOP(c, IMPORT_STAR);
2863 return 1;
2864 }
2865
2866 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2867 store_name = alias->name;
2868 if (alias->asname)
2869 store_name = alias->asname;
2870
2871 if (!compiler_nameop(c, store_name, Store)) {
2872 Py_DECREF(names);
2873 return 0;
2874 }
2875 }
2876 /* remove imported module */
2877 ADDOP(c, POP_TOP);
2878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879}
2880
2881static int
2882compiler_assert(struct compiler *c, stmt_ty s)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 static PyObject *assertion_error = NULL;
2885 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002886 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887
Georg Brandl8334fd92010-12-04 10:26:46 +00002888 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return 1;
2890 if (assertion_error == NULL) {
2891 assertion_error = PyUnicode_InternFromString("AssertionError");
2892 if (assertion_error == NULL)
2893 return 0;
2894 }
2895 if (s->v.Assert.test->kind == Tuple_kind &&
2896 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002897 msg = PyUnicode_FromString("assertion is always true, "
2898 "perhaps remove parentheses?");
2899 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002901 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2902 c->c_filename, c->u->u_lineno,
2903 NULL, NULL) == -1) {
2904 Py_DECREF(msg);
2905 return 0;
2906 }
2907 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 end = compiler_new_block(c);
2910 if (end == NULL)
2911 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002912 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2913 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2915 if (s->v.Assert.msg) {
2916 VISIT(c, expr, s->v.Assert.msg);
2917 ADDOP_I(c, CALL_FUNCTION, 1);
2918 }
2919 ADDOP_I(c, RAISE_VARARGS, 1);
2920 compiler_use_next_block(c, end);
2921 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922}
2923
2924static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002925compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2926{
2927 if (c->c_interactive && c->c_nestlevel <= 1) {
2928 VISIT(c, expr, value);
2929 ADDOP(c, PRINT_EXPR);
2930 return 1;
2931 }
2932
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002933 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002934 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002935 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002936 }
2937
2938 VISIT(c, expr, value);
2939 ADDOP(c, POP_TOP);
2940 return 1;
2941}
2942
2943static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944compiler_visit_stmt(struct compiler *c, stmt_ty s)
2945{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002946 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 /* Always assign a lineno to the next instruction for a stmt. */
2949 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002950 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 switch (s->kind) {
2954 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002955 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 case ClassDef_kind:
2957 return compiler_class(c, s);
2958 case Return_kind:
2959 if (c->u->u_ste->ste_type != FunctionBlock)
2960 return compiler_error(c, "'return' outside function");
2961 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002962 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2963 return compiler_error(
2964 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 VISIT(c, expr, s->v.Return.value);
2966 }
2967 else
2968 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2969 ADDOP(c, RETURN_VALUE);
2970 break;
2971 case Delete_kind:
2972 VISIT_SEQ(c, expr, s->v.Delete.targets)
2973 break;
2974 case Assign_kind:
2975 n = asdl_seq_LEN(s->v.Assign.targets);
2976 VISIT(c, expr, s->v.Assign.value);
2977 for (i = 0; i < n; i++) {
2978 if (i < n - 1)
2979 ADDOP(c, DUP_TOP);
2980 VISIT(c, expr,
2981 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2982 }
2983 break;
2984 case AugAssign_kind:
2985 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002986 case AnnAssign_kind:
2987 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 case For_kind:
2989 return compiler_for(c, s);
2990 case While_kind:
2991 return compiler_while(c, s);
2992 case If_kind:
2993 return compiler_if(c, s);
2994 case Raise_kind:
2995 n = 0;
2996 if (s->v.Raise.exc) {
2997 VISIT(c, expr, s->v.Raise.exc);
2998 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002999 if (s->v.Raise.cause) {
3000 VISIT(c, expr, s->v.Raise.cause);
3001 n++;
3002 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003004 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003006 case Try_kind:
3007 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 case Assert_kind:
3009 return compiler_assert(c, s);
3010 case Import_kind:
3011 return compiler_import(c, s);
3012 case ImportFrom_kind:
3013 return compiler_from_import(c, s);
3014 case Global_kind:
3015 case Nonlocal_kind:
3016 break;
3017 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003018 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 case Pass_kind:
3020 break;
3021 case Break_kind:
3022 if (!compiler_in_loop(c))
3023 return compiler_error(c, "'break' outside loop");
3024 ADDOP(c, BREAK_LOOP);
3025 break;
3026 case Continue_kind:
3027 return compiler_continue(c);
3028 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003029 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003030 case AsyncFunctionDef_kind:
3031 return compiler_function(c, s, 1);
3032 case AsyncWith_kind:
3033 return compiler_async_with(c, s, 0);
3034 case AsyncFor_kind:
3035 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 }
Yury Selivanov75445082015-05-11 22:57:16 -04003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039}
3040
3041static int
3042unaryop(unaryop_ty op)
3043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 switch (op) {
3045 case Invert:
3046 return UNARY_INVERT;
3047 case Not:
3048 return UNARY_NOT;
3049 case UAdd:
3050 return UNARY_POSITIVE;
3051 case USub:
3052 return UNARY_NEGATIVE;
3053 default:
3054 PyErr_Format(PyExc_SystemError,
3055 "unary op %d should not be possible", op);
3056 return 0;
3057 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058}
3059
3060static int
3061binop(struct compiler *c, operator_ty op)
3062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 switch (op) {
3064 case Add:
3065 return BINARY_ADD;
3066 case Sub:
3067 return BINARY_SUBTRACT;
3068 case Mult:
3069 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003070 case MatMult:
3071 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 case Div:
3073 return BINARY_TRUE_DIVIDE;
3074 case Mod:
3075 return BINARY_MODULO;
3076 case Pow:
3077 return BINARY_POWER;
3078 case LShift:
3079 return BINARY_LSHIFT;
3080 case RShift:
3081 return BINARY_RSHIFT;
3082 case BitOr:
3083 return BINARY_OR;
3084 case BitXor:
3085 return BINARY_XOR;
3086 case BitAnd:
3087 return BINARY_AND;
3088 case FloorDiv:
3089 return BINARY_FLOOR_DIVIDE;
3090 default:
3091 PyErr_Format(PyExc_SystemError,
3092 "binary op %d should not be possible", op);
3093 return 0;
3094 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095}
3096
3097static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003098inplace_binop(struct compiler *c, operator_ty op)
3099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 switch (op) {
3101 case Add:
3102 return INPLACE_ADD;
3103 case Sub:
3104 return INPLACE_SUBTRACT;
3105 case Mult:
3106 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003107 case MatMult:
3108 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 case Div:
3110 return INPLACE_TRUE_DIVIDE;
3111 case Mod:
3112 return INPLACE_MODULO;
3113 case Pow:
3114 return INPLACE_POWER;
3115 case LShift:
3116 return INPLACE_LSHIFT;
3117 case RShift:
3118 return INPLACE_RSHIFT;
3119 case BitOr:
3120 return INPLACE_OR;
3121 case BitXor:
3122 return INPLACE_XOR;
3123 case BitAnd:
3124 return INPLACE_AND;
3125 case FloorDiv:
3126 return INPLACE_FLOOR_DIVIDE;
3127 default:
3128 PyErr_Format(PyExc_SystemError,
3129 "inplace binary op %d should not be possible", op);
3130 return 0;
3131 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003132}
3133
3134static int
3135compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3136{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003137 int op, scope;
3138 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 PyObject *dict = c->u->u_names;
3142 PyObject *mangled;
3143 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003145 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3146 !_PyUnicode_EqualToASCIIString(name, "True") &&
3147 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003148
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003149 mangled = _Py_Mangle(c->u->u_private, name);
3150 if (!mangled)
3151 return 0;
3152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 op = 0;
3154 optype = OP_NAME;
3155 scope = PyST_GetScope(c->u->u_ste, mangled);
3156 switch (scope) {
3157 case FREE:
3158 dict = c->u->u_freevars;
3159 optype = OP_DEREF;
3160 break;
3161 case CELL:
3162 dict = c->u->u_cellvars;
3163 optype = OP_DEREF;
3164 break;
3165 case LOCAL:
3166 if (c->u->u_ste->ste_type == FunctionBlock)
3167 optype = OP_FAST;
3168 break;
3169 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003170 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 optype = OP_GLOBAL;
3172 break;
3173 case GLOBAL_EXPLICIT:
3174 optype = OP_GLOBAL;
3175 break;
3176 default:
3177 /* scope can be 0 */
3178 break;
3179 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003182 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 switch (optype) {
3185 case OP_DEREF:
3186 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003187 case Load:
3188 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3189 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 case Store: op = STORE_DEREF; break;
3191 case AugLoad:
3192 case AugStore:
3193 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003194 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 case Param:
3196 default:
3197 PyErr_SetString(PyExc_SystemError,
3198 "param invalid for deref variable");
3199 return 0;
3200 }
3201 break;
3202 case OP_FAST:
3203 switch (ctx) {
3204 case Load: op = LOAD_FAST; break;
3205 case Store: op = STORE_FAST; break;
3206 case Del: op = DELETE_FAST; break;
3207 case AugLoad:
3208 case AugStore:
3209 break;
3210 case Param:
3211 default:
3212 PyErr_SetString(PyExc_SystemError,
3213 "param invalid for local variable");
3214 return 0;
3215 }
3216 ADDOP_O(c, op, mangled, varnames);
3217 Py_DECREF(mangled);
3218 return 1;
3219 case OP_GLOBAL:
3220 switch (ctx) {
3221 case Load: op = LOAD_GLOBAL; break;
3222 case Store: op = STORE_GLOBAL; break;
3223 case Del: op = DELETE_GLOBAL; break;
3224 case AugLoad:
3225 case AugStore:
3226 break;
3227 case Param:
3228 default:
3229 PyErr_SetString(PyExc_SystemError,
3230 "param invalid for global variable");
3231 return 0;
3232 }
3233 break;
3234 case OP_NAME:
3235 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003236 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 case Store: op = STORE_NAME; break;
3238 case Del: op = DELETE_NAME; break;
3239 case AugLoad:
3240 case AugStore:
3241 break;
3242 case Param:
3243 default:
3244 PyErr_SetString(PyExc_SystemError,
3245 "param invalid for name variable");
3246 return 0;
3247 }
3248 break;
3249 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 assert(op);
3252 arg = compiler_add_o(c, dict, mangled);
3253 Py_DECREF(mangled);
3254 if (arg < 0)
3255 return 0;
3256 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257}
3258
3259static int
3260compiler_boolop(struct compiler *c, expr_ty e)
3261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003263 int jumpi;
3264 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 assert(e->kind == BoolOp_kind);
3268 if (e->v.BoolOp.op == And)
3269 jumpi = JUMP_IF_FALSE_OR_POP;
3270 else
3271 jumpi = JUMP_IF_TRUE_OR_POP;
3272 end = compiler_new_block(c);
3273 if (end == NULL)
3274 return 0;
3275 s = e->v.BoolOp.values;
3276 n = asdl_seq_LEN(s) - 1;
3277 assert(n >= 0);
3278 for (i = 0; i < n; ++i) {
3279 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3280 ADDOP_JABS(c, jumpi, end);
3281 }
3282 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3283 compiler_use_next_block(c, end);
3284 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285}
3286
3287static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003288starunpack_helper(struct compiler *c, asdl_seq *elts,
3289 int single_op, int inner_op, int outer_op)
3290{
3291 Py_ssize_t n = asdl_seq_LEN(elts);
3292 Py_ssize_t i, nsubitems = 0, nseen = 0;
3293 for (i = 0; i < n; i++) {
3294 expr_ty elt = asdl_seq_GET(elts, i);
3295 if (elt->kind == Starred_kind) {
3296 if (nseen) {
3297 ADDOP_I(c, inner_op, nseen);
3298 nseen = 0;
3299 nsubitems++;
3300 }
3301 VISIT(c, expr, elt->v.Starred.value);
3302 nsubitems++;
3303 }
3304 else {
3305 VISIT(c, expr, elt);
3306 nseen++;
3307 }
3308 }
3309 if (nsubitems) {
3310 if (nseen) {
3311 ADDOP_I(c, inner_op, nseen);
3312 nsubitems++;
3313 }
3314 ADDOP_I(c, outer_op, nsubitems);
3315 }
3316 else
3317 ADDOP_I(c, single_op, nseen);
3318 return 1;
3319}
3320
3321static int
3322assignment_helper(struct compiler *c, asdl_seq *elts)
3323{
3324 Py_ssize_t n = asdl_seq_LEN(elts);
3325 Py_ssize_t i;
3326 int seen_star = 0;
3327 for (i = 0; i < n; i++) {
3328 expr_ty elt = asdl_seq_GET(elts, i);
3329 if (elt->kind == Starred_kind && !seen_star) {
3330 if ((i >= (1 << 8)) ||
3331 (n-i-1 >= (INT_MAX >> 8)))
3332 return compiler_error(c,
3333 "too many expressions in "
3334 "star-unpacking assignment");
3335 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3336 seen_star = 1;
3337 asdl_seq_SET(elts, i, elt->v.Starred.value);
3338 }
3339 else if (elt->kind == Starred_kind) {
3340 return compiler_error(c,
3341 "two starred expressions in assignment");
3342 }
3343 }
3344 if (!seen_star) {
3345 ADDOP_I(c, UNPACK_SEQUENCE, n);
3346 }
3347 VISIT_SEQ(c, expr, elts);
3348 return 1;
3349}
3350
3351static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352compiler_list(struct compiler *c, expr_ty e)
3353{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003354 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003356 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003358 else if (e->v.List.ctx == Load) {
3359 return starunpack_helper(c, elts,
3360 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003362 else
3363 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365}
3366
3367static int
3368compiler_tuple(struct compiler *c, expr_ty e)
3369{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003370 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003372 return assignment_helper(c, elts);
3373 }
3374 else if (e->v.Tuple.ctx == Load) {
3375 return starunpack_helper(c, elts,
3376 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3377 }
3378 else
3379 VISIT_SEQ(c, expr, elts);
3380 return 1;
3381}
3382
3383static int
3384compiler_set(struct compiler *c, expr_ty e)
3385{
3386 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3387 BUILD_SET, BUILD_SET_UNPACK);
3388}
3389
3390static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003391are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3392{
3393 Py_ssize_t i;
3394 for (i = begin; i < end; i++) {
3395 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3396 if (key == NULL || !is_const(key))
3397 return 0;
3398 }
3399 return 1;
3400}
3401
3402static int
3403compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3404{
3405 Py_ssize_t i, n = end - begin;
3406 PyObject *keys, *key;
3407 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3408 for (i = begin; i < end; i++) {
3409 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3410 }
3411 keys = PyTuple_New(n);
3412 if (keys == NULL) {
3413 return 0;
3414 }
3415 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003416 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003417 Py_INCREF(key);
3418 PyTuple_SET_ITEM(keys, i - begin, key);
3419 }
3420 ADDOP_N(c, LOAD_CONST, keys, consts);
3421 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3422 }
3423 else {
3424 for (i = begin; i < end; i++) {
3425 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3426 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3427 }
3428 ADDOP_I(c, BUILD_MAP, n);
3429 }
3430 return 1;
3431}
3432
3433static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003434compiler_dict(struct compiler *c, expr_ty e)
3435{
Victor Stinner976bb402016-03-23 11:36:19 +01003436 Py_ssize_t i, n, elements;
3437 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003438 int is_unpacking = 0;
3439 n = asdl_seq_LEN(e->v.Dict.values);
3440 containers = 0;
3441 elements = 0;
3442 for (i = 0; i < n; i++) {
3443 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3444 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003445 if (!compiler_subdict(c, e, i - elements, i))
3446 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003447 containers++;
3448 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003450 if (is_unpacking) {
3451 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3452 containers++;
3453 }
3454 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003455 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 }
3457 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003458 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003459 if (!compiler_subdict(c, e, n - elements, n))
3460 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003461 containers++;
3462 }
3463 /* If there is more than one dict, they need to be merged into a new
3464 * dict. If there is one dict and it's an unpacking, then it needs
3465 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003466 if (containers > 1 || is_unpacking) {
3467 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 }
3469 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003470}
3471
3472static int
3473compiler_compare(struct compiler *c, expr_ty e)
3474{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003475 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003478 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3479 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3480 if (n == 0) {
3481 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3482 ADDOP_I(c, COMPARE_OP,
3483 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3484 }
3485 else {
3486 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 if (cleanup == NULL)
3488 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003489 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 VISIT(c, expr,
3491 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003492 ADDOP(c, DUP_TOP);
3493 ADDOP(c, ROT_THREE);
3494 ADDOP_I(c, COMPARE_OP,
3495 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3496 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3497 NEXT_BLOCK(c);
3498 }
3499 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3500 ADDOP_I(c, COMPARE_OP,
3501 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 basicblock *end = compiler_new_block(c);
3503 if (end == NULL)
3504 return 0;
3505 ADDOP_JREL(c, JUMP_FORWARD, end);
3506 compiler_use_next_block(c, cleanup);
3507 ADDOP(c, ROT_TWO);
3508 ADDOP(c, POP_TOP);
3509 compiler_use_next_block(c, end);
3510 }
3511 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512}
3513
3514static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003515maybe_optimize_method_call(struct compiler *c, expr_ty e)
3516{
3517 Py_ssize_t argsl, i;
3518 expr_ty meth = e->v.Call.func;
3519 asdl_seq *args = e->v.Call.args;
3520
3521 /* Check that the call node is an attribute access, and that
3522 the call doesn't have keyword parameters. */
3523 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3524 asdl_seq_LEN(e->v.Call.keywords))
3525 return -1;
3526
3527 /* Check that there are no *varargs types of arguments. */
3528 argsl = asdl_seq_LEN(args);
3529 for (i = 0; i < argsl; i++) {
3530 expr_ty elt = asdl_seq_GET(args, i);
3531 if (elt->kind == Starred_kind) {
3532 return -1;
3533 }
3534 }
3535
3536 /* Alright, we can optimize the code. */
3537 VISIT(c, expr, meth->v.Attribute.value);
3538 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3539 VISIT_SEQ(c, expr, e->v.Call.args);
3540 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3541 return 1;
3542}
3543
3544static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545compiler_call(struct compiler *c, expr_ty e)
3546{
Yury Selivanovf2392132016-12-13 19:03:51 -05003547 if (maybe_optimize_method_call(c, e) > 0)
3548 return 1;
3549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 VISIT(c, expr, e->v.Call.func);
3551 return compiler_call_helper(c, 0,
3552 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003553 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003554}
3555
Eric V. Smith235a6f02015-09-19 14:51:32 -04003556static int
3557compiler_joined_str(struct compiler *c, expr_ty e)
3558{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003559 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003560 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3561 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003562 return 1;
3563}
3564
Eric V. Smitha78c7952015-11-03 12:45:05 -05003565/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003566static int
3567compiler_formatted_value(struct compiler *c, expr_ty e)
3568{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003569 /* Our oparg encodes 2 pieces of information: the conversion
3570 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003571
Eric V. Smitha78c7952015-11-03 12:45:05 -05003572 Convert the conversion char to 2 bits:
3573 None: 000 0x0 FVC_NONE
3574 !s : 001 0x1 FVC_STR
3575 !r : 010 0x2 FVC_REPR
3576 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003577
Eric V. Smitha78c7952015-11-03 12:45:05 -05003578 next bit is whether or not we have a format spec:
3579 yes : 100 0x4
3580 no : 000 0x0
3581 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003582
Eric V. Smitha78c7952015-11-03 12:45:05 -05003583 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003584
Eric V. Smitha78c7952015-11-03 12:45:05 -05003585 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003586 VISIT(c, expr, e->v.FormattedValue.value);
3587
Eric V. Smitha78c7952015-11-03 12:45:05 -05003588 switch (e->v.FormattedValue.conversion) {
3589 case 's': oparg = FVC_STR; break;
3590 case 'r': oparg = FVC_REPR; break;
3591 case 'a': oparg = FVC_ASCII; break;
3592 case -1: oparg = FVC_NONE; break;
3593 default:
3594 PyErr_SetString(PyExc_SystemError,
3595 "Unrecognized conversion character");
3596 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003597 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003598 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003599 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003600 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003601 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003602 }
3603
Eric V. Smitha78c7952015-11-03 12:45:05 -05003604 /* And push our opcode and oparg */
3605 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003606 return 1;
3607}
3608
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003609static int
3610compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3611{
3612 Py_ssize_t i, n = end - begin;
3613 keyword_ty kw;
3614 PyObject *keys, *key;
3615 assert(n > 0);
3616 if (n > 1) {
3617 for (i = begin; i < end; i++) {
3618 kw = asdl_seq_GET(keywords, i);
3619 VISIT(c, expr, kw->value);
3620 }
3621 keys = PyTuple_New(n);
3622 if (keys == NULL) {
3623 return 0;
3624 }
3625 for (i = begin; i < end; i++) {
3626 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3627 Py_INCREF(key);
3628 PyTuple_SET_ITEM(keys, i - begin, key);
3629 }
3630 ADDOP_N(c, LOAD_CONST, keys, consts);
3631 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3632 }
3633 else {
3634 /* a for loop only executes once */
3635 for (i = begin; i < end; i++) {
3636 kw = asdl_seq_GET(keywords, i);
3637 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3638 VISIT(c, expr, kw->value);
3639 }
3640 ADDOP_I(c, BUILD_MAP, n);
3641 }
3642 return 1;
3643}
3644
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003645/* shared code between compiler_call and compiler_class */
3646static int
3647compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003648 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003649 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003650 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003651{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003652 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003653 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003654
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003655 /* the number of tuples and dictionaries on the stack */
3656 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3657
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003658 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003659 nkwelts = asdl_seq_LEN(keywords);
3660
3661 for (i = 0; i < nkwelts; i++) {
3662 keyword_ty kw = asdl_seq_GET(keywords, i);
3663 if (kw->arg == NULL) {
3664 mustdictunpack = 1;
3665 break;
3666 }
3667 }
3668
3669 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003670 for (i = 0; i < nelts; i++) {
3671 expr_ty elt = asdl_seq_GET(args, i);
3672 if (elt->kind == Starred_kind) {
3673 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003674 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003675 if (nseen) {
3676 ADDOP_I(c, BUILD_TUPLE, nseen);
3677 nseen = 0;
3678 nsubargs++;
3679 }
3680 VISIT(c, expr, elt->v.Starred.value);
3681 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003682 }
3683 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003684 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003685 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003686 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003688
3689 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003690 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003691 if (nseen) {
3692 /* Pack up any trailing positional arguments. */
3693 ADDOP_I(c, BUILD_TUPLE, nseen);
3694 nsubargs++;
3695 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003696 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003697 /* If we ended up with more than one stararg, we need
3698 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003699 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003700 }
3701 else if (nsubargs == 0) {
3702 ADDOP_I(c, BUILD_TUPLE, 0);
3703 }
3704 nseen = 0; /* the number of keyword arguments on the stack following */
3705 for (i = 0; i < nkwelts; i++) {
3706 keyword_ty kw = asdl_seq_GET(keywords, i);
3707 if (kw->arg == NULL) {
3708 /* A keyword argument unpacking. */
3709 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003710 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3711 return 0;
3712 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003713 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003714 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003715 VISIT(c, expr, kw->value);
3716 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003718 else {
3719 nseen++;
3720 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003721 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003722 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003723 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003724 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003725 return 0;
3726 nsubkwargs++;
3727 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003728 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003730 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003732 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3733 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003735 else if (nkwelts) {
3736 PyObject *names;
3737 VISIT_SEQ(c, keyword, keywords);
3738 names = PyTuple_New(nkwelts);
3739 if (names == NULL) {
3740 return 0;
3741 }
3742 for (i = 0; i < nkwelts; i++) {
3743 keyword_ty kw = asdl_seq_GET(keywords, i);
3744 Py_INCREF(kw->arg);
3745 PyTuple_SET_ITEM(names, i, kw->arg);
3746 }
3747 ADDOP_N(c, LOAD_CONST, names, consts);
3748 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3749 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003751 else {
3752 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3753 return 1;
3754 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755}
3756
Nick Coghlan650f0d02007-04-15 12:05:43 +00003757
3758/* List and set comprehensions and generator expressions work by creating a
3759 nested function to perform the actual iteration. This means that the
3760 iteration variables don't leak into the current scope.
3761 The defined function is called immediately following its definition, with the
3762 result of that call being the result of the expression.
3763 The LC/SC version returns the populated container, while the GE version is
3764 flagged in symtable.c as a generator, so it returns the generator object
3765 when the function is called.
3766 This code *knows* that the loop cannot contain break, continue, or return,
3767 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3768
3769 Possible cleanups:
3770 - iterate over the generator sequence instead of using recursion
3771*/
3772
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003773
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775compiler_comprehension_generator(struct compiler *c,
3776 asdl_seq *generators, int gen_index,
3777 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003779 comprehension_ty gen;
3780 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3781 if (gen->is_async) {
3782 return compiler_async_comprehension_generator(
3783 c, generators, gen_index, elt, val, type);
3784 } else {
3785 return compiler_sync_comprehension_generator(
3786 c, generators, gen_index, elt, val, type);
3787 }
3788}
3789
3790static int
3791compiler_sync_comprehension_generator(struct compiler *c,
3792 asdl_seq *generators, int gen_index,
3793 expr_ty elt, expr_ty val, int type)
3794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 /* generate code for the iterator, then each of the ifs,
3796 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 comprehension_ty gen;
3799 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003800 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 start = compiler_new_block(c);
3803 skip = compiler_new_block(c);
3804 if_cleanup = compiler_new_block(c);
3805 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3808 anchor == NULL)
3809 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 if (gen_index == 0) {
3814 /* Receive outermost iter as an implicit argument */
3815 c->u->u_argcount = 1;
3816 ADDOP_I(c, LOAD_FAST, 0);
3817 }
3818 else {
3819 /* Sub-iter - calculate on the fly */
3820 VISIT(c, expr, gen->iter);
3821 ADDOP(c, GET_ITER);
3822 }
3823 compiler_use_next_block(c, start);
3824 ADDOP_JREL(c, FOR_ITER, anchor);
3825 NEXT_BLOCK(c);
3826 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 /* XXX this needs to be cleaned up...a lot! */
3829 n = asdl_seq_LEN(gen->ifs);
3830 for (i = 0; i < n; i++) {
3831 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003832 if (!compiler_jump_if(c, e, if_cleanup, 0))
3833 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 NEXT_BLOCK(c);
3835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 if (++gen_index < asdl_seq_LEN(generators))
3838 if (!compiler_comprehension_generator(c,
3839 generators, gen_index,
3840 elt, val, type))
3841 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 /* only append after the last for generator */
3844 if (gen_index >= asdl_seq_LEN(generators)) {
3845 /* comprehension specific code */
3846 switch (type) {
3847 case COMP_GENEXP:
3848 VISIT(c, expr, elt);
3849 ADDOP(c, YIELD_VALUE);
3850 ADDOP(c, POP_TOP);
3851 break;
3852 case COMP_LISTCOMP:
3853 VISIT(c, expr, elt);
3854 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3855 break;
3856 case COMP_SETCOMP:
3857 VISIT(c, expr, elt);
3858 ADDOP_I(c, SET_ADD, gen_index + 1);
3859 break;
3860 case COMP_DICTCOMP:
3861 /* With 'd[k] = v', v is evaluated before k, so we do
3862 the same. */
3863 VISIT(c, expr, val);
3864 VISIT(c, expr, elt);
3865 ADDOP_I(c, MAP_ADD, gen_index + 1);
3866 break;
3867 default:
3868 return 0;
3869 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 compiler_use_next_block(c, skip);
3872 }
3873 compiler_use_next_block(c, if_cleanup);
3874 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3875 compiler_use_next_block(c, anchor);
3876
3877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878}
3879
3880static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003881compiler_async_comprehension_generator(struct compiler *c,
3882 asdl_seq *generators, int gen_index,
3883 expr_ty elt, expr_ty val, int type)
3884{
3885 _Py_IDENTIFIER(StopAsyncIteration);
3886
3887 comprehension_ty gen;
Serhiy Storchakab9744e92018-03-23 14:35:33 +02003888 basicblock *if_cleanup, *try,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003889 *after_try, *except, *try_cleanup;
3890 Py_ssize_t i, n;
3891
3892 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3893 if (stop_aiter_error == NULL) {
3894 return 0;
3895 }
3896
3897 try = compiler_new_block(c);
3898 after_try = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003899 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003900 if_cleanup = compiler_new_block(c);
Serhiy Storchakab9744e92018-03-23 14:35:33 +02003901 try_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003902
Serhiy Storchakab9744e92018-03-23 14:35:33 +02003903 if (if_cleanup == NULL ||
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003904 try == NULL || after_try == NULL ||
Serhiy Storchaka9e94c0d2018-03-10 20:45:05 +02003905 except == NULL || try_cleanup == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003906 return 0;
3907 }
3908
3909 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3910
3911 if (gen_index == 0) {
3912 /* Receive outermost iter as an implicit argument */
3913 c->u->u_argcount = 1;
3914 ADDOP_I(c, LOAD_FAST, 0);
3915 }
3916 else {
3917 /* Sub-iter - calculate on the fly */
3918 VISIT(c, expr, gen->iter);
3919 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003920 }
3921
3922 compiler_use_next_block(c, try);
3923
3924
3925 ADDOP_JREL(c, SETUP_EXCEPT, except);
3926 if (!compiler_push_fblock(c, EXCEPT, try))
3927 return 0;
3928
3929 ADDOP(c, GET_ANEXT);
3930 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3931 ADDOP(c, YIELD_FROM);
3932 VISIT(c, expr, gen->target);
3933 ADDOP(c, POP_BLOCK);
3934 compiler_pop_fblock(c, EXCEPT, try);
3935 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3936
3937
3938 compiler_use_next_block(c, except);
3939 ADDOP(c, DUP_TOP);
3940 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3941 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Serhiy Storchakab9744e92018-03-23 14:35:33 +02003942 ADDOP_JABS(c, POP_JUMP_IF_TRUE, try_cleanup);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003943 ADDOP(c, END_FINALLY);
3944
3945 compiler_use_next_block(c, after_try);
3946
3947 n = asdl_seq_LEN(gen->ifs);
3948 for (i = 0; i < n; i++) {
3949 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003950 if (!compiler_jump_if(c, e, if_cleanup, 0))
3951 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003952 NEXT_BLOCK(c);
3953 }
3954
3955 if (++gen_index < asdl_seq_LEN(generators))
3956 if (!compiler_comprehension_generator(c,
3957 generators, gen_index,
3958 elt, val, type))
3959 return 0;
3960
3961 /* only append after the last for generator */
3962 if (gen_index >= asdl_seq_LEN(generators)) {
3963 /* comprehension specific code */
3964 switch (type) {
3965 case COMP_GENEXP:
3966 VISIT(c, expr, elt);
3967 ADDOP(c, YIELD_VALUE);
3968 ADDOP(c, POP_TOP);
3969 break;
3970 case COMP_LISTCOMP:
3971 VISIT(c, expr, elt);
3972 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3973 break;
3974 case COMP_SETCOMP:
3975 VISIT(c, expr, elt);
3976 ADDOP_I(c, SET_ADD, gen_index + 1);
3977 break;
3978 case COMP_DICTCOMP:
3979 /* With 'd[k] = v', v is evaluated before k, so we do
3980 the same. */
3981 VISIT(c, expr, val);
3982 VISIT(c, expr, elt);
3983 ADDOP_I(c, MAP_ADD, gen_index + 1);
3984 break;
3985 default:
3986 return 0;
3987 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003988 }
3989 compiler_use_next_block(c, if_cleanup);
3990 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
Serhiy Storchakab9744e92018-03-23 14:35:33 +02003991
3992 compiler_use_next_block(c, try_cleanup);
3993 ADDOP(c, POP_TOP);
3994 ADDOP(c, POP_TOP);
3995 ADDOP(c, POP_TOP);
3996 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003997 ADDOP(c, POP_TOP);
3998
3999 return 1;
4000}
4001
4002static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004003compiler_comprehension(struct compiler *c, expr_ty e, int type,
4004 identifier name, asdl_seq *generators, expr_ty elt,
4005 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004008 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004009 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004010 int is_async_function = c->u->u_ste->ste_coroutine;
4011 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004012
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004013 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004014
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004015 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4016 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004017 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004019 }
4020
4021 is_async_generator = c->u->u_ste->ste_coroutine;
4022
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004023 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004024 if (e->lineno > c->u->u_lineno) {
4025 c->u->u_lineno = e->lineno;
4026 c->u->u_lineno_set = 0;
4027 }
4028 compiler_error(c, "asynchronous comprehension outside of "
4029 "an asynchronous function");
4030 goto error_in_scope;
4031 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 if (type != COMP_GENEXP) {
4034 int op;
4035 switch (type) {
4036 case COMP_LISTCOMP:
4037 op = BUILD_LIST;
4038 break;
4039 case COMP_SETCOMP:
4040 op = BUILD_SET;
4041 break;
4042 case COMP_DICTCOMP:
4043 op = BUILD_MAP;
4044 break;
4045 default:
4046 PyErr_Format(PyExc_SystemError,
4047 "unknown comprehension type %d", type);
4048 goto error_in_scope;
4049 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 ADDOP_I(c, op, 0);
4052 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 if (!compiler_comprehension_generator(c, generators, 0, elt,
4055 val, type))
4056 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 if (type != COMP_GENEXP) {
4059 ADDOP(c, RETURN_VALUE);
4060 }
4061
4062 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004063 qualname = c->u->u_qualname;
4064 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004066 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 goto error;
4068
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004069 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004071 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 Py_DECREF(co);
4073
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004074 VISIT(c, expr, outermost->iter);
4075
4076 if (outermost->is_async) {
4077 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004078 } else {
4079 ADDOP(c, GET_ITER);
4080 }
4081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004083
4084 if (is_async_generator && type != COMP_GENEXP) {
4085 ADDOP(c, GET_AWAITABLE);
4086 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4087 ADDOP(c, YIELD_FROM);
4088 }
4089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004091error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004093error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004094 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 Py_XDECREF(co);
4096 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004097}
4098
4099static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100compiler_genexp(struct compiler *c, expr_ty e)
4101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 static identifier name;
4103 if (!name) {
4104 name = PyUnicode_FromString("<genexpr>");
4105 if (!name)
4106 return 0;
4107 }
4108 assert(e->kind == GeneratorExp_kind);
4109 return compiler_comprehension(c, e, COMP_GENEXP, name,
4110 e->v.GeneratorExp.generators,
4111 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004112}
4113
4114static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004115compiler_listcomp(struct compiler *c, expr_ty e)
4116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 static identifier name;
4118 if (!name) {
4119 name = PyUnicode_FromString("<listcomp>");
4120 if (!name)
4121 return 0;
4122 }
4123 assert(e->kind == ListComp_kind);
4124 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4125 e->v.ListComp.generators,
4126 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004127}
4128
4129static int
4130compiler_setcomp(struct compiler *c, expr_ty e)
4131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 static identifier name;
4133 if (!name) {
4134 name = PyUnicode_FromString("<setcomp>");
4135 if (!name)
4136 return 0;
4137 }
4138 assert(e->kind == SetComp_kind);
4139 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4140 e->v.SetComp.generators,
4141 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004142}
4143
4144
4145static int
4146compiler_dictcomp(struct compiler *c, expr_ty e)
4147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 static identifier name;
4149 if (!name) {
4150 name = PyUnicode_FromString("<dictcomp>");
4151 if (!name)
4152 return 0;
4153 }
4154 assert(e->kind == DictComp_kind);
4155 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4156 e->v.DictComp.generators,
4157 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004158}
4159
4160
4161static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162compiler_visit_keyword(struct compiler *c, keyword_ty k)
4163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 VISIT(c, expr, k->value);
4165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166}
4167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 whether they are true or false.
4170
4171 Return values: 1 for true, 0 for false, -1 for non-constant.
4172 */
4173
4174static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004175expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004177 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004178 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004179 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004180 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181}
4182
Yury Selivanov75445082015-05-11 22:57:16 -04004183
4184/*
4185 Implements the async with statement.
4186
4187 The semantics outlined in that PEP are as follows:
4188
4189 async with EXPR as VAR:
4190 BLOCK
4191
4192 It is implemented roughly as:
4193
4194 context = EXPR
4195 exit = context.__aexit__ # not calling it
4196 value = await context.__aenter__()
4197 try:
4198 VAR = value # if VAR present in the syntax
4199 BLOCK
4200 finally:
4201 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004202 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004203 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004204 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004205 if not (await exit(*exc)):
4206 raise
4207 */
4208static int
4209compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4210{
4211 basicblock *block, *finally;
4212 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4213
4214 assert(s->kind == AsyncWith_kind);
4215
4216 block = compiler_new_block(c);
4217 finally = compiler_new_block(c);
4218 if (!block || !finally)
4219 return 0;
4220
4221 /* Evaluate EXPR */
4222 VISIT(c, expr, item->context_expr);
4223
4224 ADDOP(c, BEFORE_ASYNC_WITH);
4225 ADDOP(c, GET_AWAITABLE);
4226 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4227 ADDOP(c, YIELD_FROM);
4228
4229 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4230
4231 /* SETUP_ASYNC_WITH pushes a finally block. */
4232 compiler_use_next_block(c, block);
4233 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4234 return 0;
4235 }
4236
4237 if (item->optional_vars) {
4238 VISIT(c, expr, item->optional_vars);
4239 }
4240 else {
4241 /* Discard result from context.__aenter__() */
4242 ADDOP(c, POP_TOP);
4243 }
4244
4245 pos++;
4246 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4247 /* BLOCK code */
4248 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4249 else if (!compiler_async_with(c, s, pos))
4250 return 0;
4251
4252 /* End of try block; start the finally block */
4253 ADDOP(c, POP_BLOCK);
4254 compiler_pop_fblock(c, FINALLY_TRY, block);
4255
4256 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4257 compiler_use_next_block(c, finally);
4258 if (!compiler_push_fblock(c, FINALLY_END, finally))
4259 return 0;
4260
4261 /* Finally block starts; context.__exit__ is on the stack under
4262 the exception or return information. Just issue our magic
4263 opcode. */
4264 ADDOP(c, WITH_CLEANUP_START);
4265
4266 ADDOP(c, GET_AWAITABLE);
4267 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4268 ADDOP(c, YIELD_FROM);
4269
4270 ADDOP(c, WITH_CLEANUP_FINISH);
4271
4272 /* Finally block ends. */
4273 ADDOP(c, END_FINALLY);
4274 compiler_pop_fblock(c, FINALLY_END, finally);
4275 return 1;
4276}
4277
4278
Guido van Rossumc2e20742006-02-27 22:32:47 +00004279/*
4280 Implements the with statement from PEP 343.
4281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004283
4284 with EXPR as VAR:
4285 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286
Guido van Rossumc2e20742006-02-27 22:32:47 +00004287 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288
Thomas Wouters477c8d52006-05-27 19:21:47 +00004289 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004290 exit = context.__exit__ # not calling it
4291 value = context.__enter__()
4292 try:
4293 VAR = value # if VAR present in the syntax
4294 BLOCK
4295 finally:
4296 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004297 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004298 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004299 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004300 exit(*exc)
4301 */
4302static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004303compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004304{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004305 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004306 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004307
4308 assert(s->kind == With_kind);
4309
Guido van Rossumc2e20742006-02-27 22:32:47 +00004310 block = compiler_new_block(c);
4311 finally = compiler_new_block(c);
4312 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004313 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004314
Thomas Wouters477c8d52006-05-27 19:21:47 +00004315 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004316 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004317 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004318
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004319 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004320 compiler_use_next_block(c, block);
4321 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004322 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004323 }
4324
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004325 if (item->optional_vars) {
4326 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004327 }
4328 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004330 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004331 }
4332
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004333 pos++;
4334 if (pos == asdl_seq_LEN(s->v.With.items))
4335 /* BLOCK code */
4336 VISIT_SEQ(c, stmt, s->v.With.body)
4337 else if (!compiler_with(c, s, pos))
4338 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004339
4340 /* End of try block; start the finally block */
4341 ADDOP(c, POP_BLOCK);
4342 compiler_pop_fblock(c, FINALLY_TRY, block);
4343
4344 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4345 compiler_use_next_block(c, finally);
4346 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004347 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004348
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004349 /* Finally block starts; context.__exit__ is on the stack under
4350 the exception or return information. Just issue our magic
4351 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004352 ADDOP(c, WITH_CLEANUP_START);
4353 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004354
4355 /* Finally block ends. */
4356 ADDOP(c, END_FINALLY);
4357 compiler_pop_fblock(c, FINALLY_END, finally);
4358 return 1;
4359}
4360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004361static int
4362compiler_visit_expr(struct compiler *c, expr_ty e)
4363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 /* If expr e has a different line number than the last expr/stmt,
4365 set a new line number for the next instruction.
4366 */
4367 if (e->lineno > c->u->u_lineno) {
4368 c->u->u_lineno = e->lineno;
4369 c->u->u_lineno_set = 0;
4370 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004371 /* Updating the column offset is always harmless. */
4372 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 switch (e->kind) {
4374 case BoolOp_kind:
4375 return compiler_boolop(c, e);
4376 case BinOp_kind:
4377 VISIT(c, expr, e->v.BinOp.left);
4378 VISIT(c, expr, e->v.BinOp.right);
4379 ADDOP(c, binop(c, e->v.BinOp.op));
4380 break;
4381 case UnaryOp_kind:
4382 VISIT(c, expr, e->v.UnaryOp.operand);
4383 ADDOP(c, unaryop(e->v.UnaryOp.op));
4384 break;
4385 case Lambda_kind:
4386 return compiler_lambda(c, e);
4387 case IfExp_kind:
4388 return compiler_ifexp(c, e);
4389 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004390 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004392 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 case GeneratorExp_kind:
4394 return compiler_genexp(c, e);
4395 case ListComp_kind:
4396 return compiler_listcomp(c, e);
4397 case SetComp_kind:
4398 return compiler_setcomp(c, e);
4399 case DictComp_kind:
4400 return compiler_dictcomp(c, e);
4401 case Yield_kind:
4402 if (c->u->u_ste->ste_type != FunctionBlock)
4403 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004404 if (e->v.Yield.value) {
4405 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 }
4407 else {
4408 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4409 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004410 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004412 case YieldFrom_kind:
4413 if (c->u->u_ste->ste_type != FunctionBlock)
4414 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004415
4416 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4417 return compiler_error(c, "'yield from' inside async function");
4418
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004419 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004420 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004421 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4422 ADDOP(c, YIELD_FROM);
4423 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004424 case Await_kind:
4425 if (c->u->u_ste->ste_type != FunctionBlock)
4426 return compiler_error(c, "'await' outside function");
4427
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004428 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4429 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004430 return compiler_error(c, "'await' outside async function");
4431
4432 VISIT(c, expr, e->v.Await.value);
4433 ADDOP(c, GET_AWAITABLE);
4434 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4435 ADDOP(c, YIELD_FROM);
4436 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 case Compare_kind:
4438 return compiler_compare(c, e);
4439 case Call_kind:
4440 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004441 case Constant_kind:
4442 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4443 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 case Num_kind:
4445 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4446 break;
4447 case Str_kind:
4448 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4449 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004450 case JoinedStr_kind:
4451 return compiler_joined_str(c, e);
4452 case FormattedValue_kind:
4453 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 case Bytes_kind:
4455 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4456 break;
4457 case Ellipsis_kind:
4458 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4459 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004460 case NameConstant_kind:
4461 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4462 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 /* The following exprs can be assignment targets. */
4464 case Attribute_kind:
4465 if (e->v.Attribute.ctx != AugStore)
4466 VISIT(c, expr, e->v.Attribute.value);
4467 switch (e->v.Attribute.ctx) {
4468 case AugLoad:
4469 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004470 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 case Load:
4472 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4473 break;
4474 case AugStore:
4475 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004476 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 case Store:
4478 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4479 break;
4480 case Del:
4481 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4482 break;
4483 case Param:
4484 default:
4485 PyErr_SetString(PyExc_SystemError,
4486 "param invalid in attribute expression");
4487 return 0;
4488 }
4489 break;
4490 case Subscript_kind:
4491 switch (e->v.Subscript.ctx) {
4492 case AugLoad:
4493 VISIT(c, expr, e->v.Subscript.value);
4494 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4495 break;
4496 case Load:
4497 VISIT(c, expr, e->v.Subscript.value);
4498 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4499 break;
4500 case AugStore:
4501 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4502 break;
4503 case Store:
4504 VISIT(c, expr, e->v.Subscript.value);
4505 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4506 break;
4507 case Del:
4508 VISIT(c, expr, e->v.Subscript.value);
4509 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4510 break;
4511 case Param:
4512 default:
4513 PyErr_SetString(PyExc_SystemError,
4514 "param invalid in subscript expression");
4515 return 0;
4516 }
4517 break;
4518 case Starred_kind:
4519 switch (e->v.Starred.ctx) {
4520 case Store:
4521 /* In all legitimate cases, the Starred node was already replaced
4522 * by compiler_list/compiler_tuple. XXX: is that okay? */
4523 return compiler_error(c,
4524 "starred assignment target must be in a list or tuple");
4525 default:
4526 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004527 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 }
4529 break;
4530 case Name_kind:
4531 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4532 /* child nodes of List and Tuple will have expr_context set */
4533 case List_kind:
4534 return compiler_list(c, e);
4535 case Tuple_kind:
4536 return compiler_tuple(c, e);
4537 }
4538 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004539}
4540
4541static int
4542compiler_augassign(struct compiler *c, stmt_ty s)
4543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 expr_ty e = s->v.AugAssign.target;
4545 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 switch (e->kind) {
4550 case Attribute_kind:
4551 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4552 AugLoad, e->lineno, e->col_offset, c->c_arena);
4553 if (auge == NULL)
4554 return 0;
4555 VISIT(c, expr, auge);
4556 VISIT(c, expr, s->v.AugAssign.value);
4557 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4558 auge->v.Attribute.ctx = AugStore;
4559 VISIT(c, expr, auge);
4560 break;
4561 case Subscript_kind:
4562 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4563 AugLoad, e->lineno, e->col_offset, c->c_arena);
4564 if (auge == NULL)
4565 return 0;
4566 VISIT(c, expr, auge);
4567 VISIT(c, expr, s->v.AugAssign.value);
4568 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4569 auge->v.Subscript.ctx = AugStore;
4570 VISIT(c, expr, auge);
4571 break;
4572 case Name_kind:
4573 if (!compiler_nameop(c, e->v.Name.id, Load))
4574 return 0;
4575 VISIT(c, expr, s->v.AugAssign.value);
4576 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4577 return compiler_nameop(c, e->v.Name.id, Store);
4578 default:
4579 PyErr_Format(PyExc_SystemError,
4580 "invalid node type (%d) for augmented assignment",
4581 e->kind);
4582 return 0;
4583 }
4584 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004585}
4586
4587static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004588check_ann_expr(struct compiler *c, expr_ty e)
4589{
4590 VISIT(c, expr, e);
4591 ADDOP(c, POP_TOP);
4592 return 1;
4593}
4594
4595static int
4596check_annotation(struct compiler *c, stmt_ty s)
4597{
4598 /* Annotations are only evaluated in a module or class. */
4599 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4600 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4601 return check_ann_expr(c, s->v.AnnAssign.annotation);
4602 }
4603 return 1;
4604}
4605
4606static int
4607check_ann_slice(struct compiler *c, slice_ty sl)
4608{
4609 switch(sl->kind) {
4610 case Index_kind:
4611 return check_ann_expr(c, sl->v.Index.value);
4612 case Slice_kind:
4613 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4614 return 0;
4615 }
4616 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4617 return 0;
4618 }
4619 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4620 return 0;
4621 }
4622 break;
4623 default:
4624 PyErr_SetString(PyExc_SystemError,
4625 "unexpected slice kind");
4626 return 0;
4627 }
4628 return 1;
4629}
4630
4631static int
4632check_ann_subscr(struct compiler *c, slice_ty sl)
4633{
4634 /* We check that everything in a subscript is defined at runtime. */
4635 Py_ssize_t i, n;
4636
4637 switch (sl->kind) {
4638 case Index_kind:
4639 case Slice_kind:
4640 if (!check_ann_slice(c, sl)) {
4641 return 0;
4642 }
4643 break;
4644 case ExtSlice_kind:
4645 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4646 for (i = 0; i < n; i++) {
4647 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4648 switch (subsl->kind) {
4649 case Index_kind:
4650 case Slice_kind:
4651 if (!check_ann_slice(c, subsl)) {
4652 return 0;
4653 }
4654 break;
4655 case ExtSlice_kind:
4656 default:
4657 PyErr_SetString(PyExc_SystemError,
4658 "extended slice invalid in nested slice");
4659 return 0;
4660 }
4661 }
4662 break;
4663 default:
4664 PyErr_Format(PyExc_SystemError,
4665 "invalid subscript kind %d", sl->kind);
4666 return 0;
4667 }
4668 return 1;
4669}
4670
4671static int
4672compiler_annassign(struct compiler *c, stmt_ty s)
4673{
4674 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004675 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004676
4677 assert(s->kind == AnnAssign_kind);
4678
4679 /* We perform the actual assignment first. */
4680 if (s->v.AnnAssign.value) {
4681 VISIT(c, expr, s->v.AnnAssign.value);
4682 VISIT(c, expr, targ);
4683 }
4684 switch (targ->kind) {
4685 case Name_kind:
4686 /* If we have a simple name in a module or class, store annotation. */
4687 if (s->v.AnnAssign.simple &&
4688 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4689 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004690 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4691 if (!mangled) {
4692 return 0;
4693 }
Guido van Rossum95e4d582018-01-26 08:20:18 -08004694 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4695 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4696 }
4697 else {
4698 VISIT(c, expr, s->v.AnnAssign.annotation);
4699 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004700 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
4701 ADDOP_O(c, LOAD_CONST, mangled, consts);
4702 Py_DECREF(mangled);
4703 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004704 }
4705 break;
4706 case Attribute_kind:
4707 if (!s->v.AnnAssign.value &&
4708 !check_ann_expr(c, targ->v.Attribute.value)) {
4709 return 0;
4710 }
4711 break;
4712 case Subscript_kind:
4713 if (!s->v.AnnAssign.value &&
4714 (!check_ann_expr(c, targ->v.Subscript.value) ||
4715 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4716 return 0;
4717 }
4718 break;
4719 default:
4720 PyErr_Format(PyExc_SystemError,
4721 "invalid node type (%d) for annotated assignment",
4722 targ->kind);
4723 return 0;
4724 }
4725 /* Annotation is evaluated last. */
4726 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4727 return 0;
4728 }
4729 return 1;
4730}
4731
4732static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004733compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 struct fblockinfo *f;
4736 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004737 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 "too many statically nested blocks");
4739 return 0;
4740 }
4741 f = &c->u->u_fblock[c->u->u_nfblocks++];
4742 f->fb_type = t;
4743 f->fb_block = b;
4744 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745}
4746
4747static void
4748compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 struct compiler_unit *u = c->u;
4751 assert(u->u_nfblocks > 0);
4752 u->u_nfblocks--;
4753 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4754 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004755}
4756
Thomas Wouters89f507f2006-12-13 04:49:30 +00004757static int
4758compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 int i;
4760 struct compiler_unit *u = c->u;
4761 for (i = 0; i < u->u_nfblocks; ++i) {
4762 if (u->u_fblock[i].fb_type == LOOP)
4763 return 1;
4764 }
4765 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004766}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004767/* Raises a SyntaxError and returns 0.
4768 If something goes wrong, a different exception may be raised.
4769*/
4770
4771static int
4772compiler_error(struct compiler *c, const char *errstr)
4773{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004774 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004776
Victor Stinner14e461d2013-08-26 22:28:21 +02004777 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 if (!loc) {
4779 Py_INCREF(Py_None);
4780 loc = Py_None;
4781 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004782 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004783 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 if (!u)
4785 goto exit;
4786 v = Py_BuildValue("(zO)", errstr, u);
4787 if (!v)
4788 goto exit;
4789 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004790 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 Py_DECREF(loc);
4792 Py_XDECREF(u);
4793 Py_XDECREF(v);
4794 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004795}
4796
4797static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798compiler_handle_subscr(struct compiler *c, const char *kind,
4799 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 /* XXX this code is duplicated */
4804 switch (ctx) {
4805 case AugLoad: /* fall through to Load */
4806 case Load: op = BINARY_SUBSCR; break;
4807 case AugStore:/* fall through to Store */
4808 case Store: op = STORE_SUBSCR; break;
4809 case Del: op = DELETE_SUBSCR; break;
4810 case Param:
4811 PyErr_Format(PyExc_SystemError,
4812 "invalid %s kind %d in subscript\n",
4813 kind, ctx);
4814 return 0;
4815 }
4816 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004817 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 }
4819 else if (ctx == AugStore) {
4820 ADDOP(c, ROT_THREE);
4821 }
4822 ADDOP(c, op);
4823 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004824}
4825
4826static int
4827compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 int n = 2;
4830 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 /* only handles the cases where BUILD_SLICE is emitted */
4833 if (s->v.Slice.lower) {
4834 VISIT(c, expr, s->v.Slice.lower);
4835 }
4836 else {
4837 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4838 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 if (s->v.Slice.upper) {
4841 VISIT(c, expr, s->v.Slice.upper);
4842 }
4843 else {
4844 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4845 }
4846
4847 if (s->v.Slice.step) {
4848 n++;
4849 VISIT(c, expr, s->v.Slice.step);
4850 }
4851 ADDOP_I(c, BUILD_SLICE, n);
4852 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004853}
4854
4855static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4857 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 switch (s->kind) {
4860 case Slice_kind:
4861 return compiler_slice(c, s, ctx);
4862 case Index_kind:
4863 VISIT(c, expr, s->v.Index.value);
4864 break;
4865 case ExtSlice_kind:
4866 default:
4867 PyErr_SetString(PyExc_SystemError,
4868 "extended slice invalid in nested slice");
4869 return 0;
4870 }
4871 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004872}
4873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004874static int
4875compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4876{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004877 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 switch (s->kind) {
4879 case Index_kind:
4880 kindname = "index";
4881 if (ctx != AugStore) {
4882 VISIT(c, expr, s->v.Index.value);
4883 }
4884 break;
4885 case Slice_kind:
4886 kindname = "slice";
4887 if (ctx != AugStore) {
4888 if (!compiler_slice(c, s, ctx))
4889 return 0;
4890 }
4891 break;
4892 case ExtSlice_kind:
4893 kindname = "extended slice";
4894 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004895 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 for (i = 0; i < n; i++) {
4897 slice_ty sub = (slice_ty)asdl_seq_GET(
4898 s->v.ExtSlice.dims, i);
4899 if (!compiler_visit_nested_slice(c, sub, ctx))
4900 return 0;
4901 }
4902 ADDOP_I(c, BUILD_TUPLE, n);
4903 }
4904 break;
4905 default:
4906 PyErr_Format(PyExc_SystemError,
4907 "invalid subscript kind %d", s->kind);
4908 return 0;
4909 }
4910 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004911}
4912
Thomas Wouters89f507f2006-12-13 04:49:30 +00004913/* End of the compiler section, beginning of the assembler section */
4914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004915/* do depth-first search of basic block graph, starting with block.
4916 post records the block indices in post-order.
4917
4918 XXX must handle implicit jumps from one block to next
4919*/
4920
Thomas Wouters89f507f2006-12-13 04:49:30 +00004921struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 PyObject *a_bytecode; /* string containing bytecode */
4923 int a_offset; /* offset into bytecode */
4924 int a_nblocks; /* number of reachable blocks */
4925 basicblock **a_postorder; /* list of blocks in dfs postorder */
4926 PyObject *a_lnotab; /* string containing lnotab */
4927 int a_lnotab_off; /* offset into lnotab */
4928 int a_lineno; /* last lineno of emitted instruction */
4929 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004930};
4931
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004932static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004933dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004934{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004935 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004936
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004937 /* Get rid of recursion for normal control flow.
4938 Since the number of blocks is limited, unused space in a_postorder
4939 (from a_nblocks to end) can be used as a stack for still not ordered
4940 blocks. */
4941 for (j = end; b && !b->b_seen; b = b->b_next) {
4942 b->b_seen = 1;
4943 assert(a->a_nblocks < j);
4944 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004946 while (j < end) {
4947 b = a->a_postorder[j++];
4948 for (i = 0; i < b->b_iused; i++) {
4949 struct instr *instr = &b->b_instr[i];
4950 if (instr->i_jrel || instr->i_jabs)
4951 dfs(c, instr->i_target, a, j);
4952 }
4953 assert(a->a_nblocks < j);
4954 a->a_postorder[a->a_nblocks++] = b;
4955 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004956}
4957
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004958Py_LOCAL_INLINE(void)
4959stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004960{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004961 /* XXX b->b_startdepth > depth only for the target of SETUP_FINALLY,
4962 * SETUP_WITH and SETUP_ASYNC_WITH. */
4963 assert(b->b_startdepth < 0 || b->b_startdepth >= depth);
4964 if (b->b_startdepth < depth) {
4965 assert(b->b_startdepth < 0);
4966 b->b_startdepth = depth;
4967 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004968 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004969}
4970
4971/* Find the flow path that needs the largest stack. We assume that
4972 * cycles in the flow graph have no net effect on the stack depth.
4973 */
4974static int
4975stackdepth(struct compiler *c)
4976{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004977 basicblock *b, *entryblock = NULL;
4978 basicblock **stack, **sp;
4979 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 b->b_startdepth = INT_MIN;
4982 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004983 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 }
4985 if (!entryblock)
4986 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004987 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
4988 if (!stack) {
4989 PyErr_NoMemory();
4990 return -1;
4991 }
4992
4993 sp = stack;
4994 stackdepth_push(&sp, entryblock, 0);
4995 while (sp != stack) {
4996 b = *--sp;
4997 int depth = b->b_startdepth;
4998 assert(depth >= 0);
4999 basicblock *next = b->b_next;
5000 for (int i = 0; i < b->b_iused; i++) {
5001 struct instr *instr = &b->b_instr[i];
5002 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5003 if (effect == PY_INVALID_STACK_EFFECT) {
5004 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5005 Py_FatalError("PyCompile_OpcodeStackEffect()");
5006 }
5007 int new_depth = depth + effect;
5008 if (new_depth > maxdepth) {
5009 maxdepth = new_depth;
5010 }
5011 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5012 if (instr->i_jrel || instr->i_jabs) {
5013 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5014 assert(effect != PY_INVALID_STACK_EFFECT);
5015 int target_depth = depth + effect;
5016 if (target_depth > maxdepth) {
5017 maxdepth = target_depth;
5018 }
5019 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
5020 if (instr->i_opcode == CONTINUE_LOOP) {
5021 /* Pops a variable number of values from the stack,
5022 * but the target should be already proceeding.
5023 */
5024 assert(instr->i_target->b_startdepth >= 0);
5025 assert(instr->i_target->b_startdepth <= depth);
5026 /* remaining code is dead */
5027 next = NULL;
5028 break;
5029 }
5030 stackdepth_push(&sp, instr->i_target, target_depth);
5031 }
5032 depth = new_depth;
5033 if (instr->i_opcode == JUMP_ABSOLUTE ||
5034 instr->i_opcode == JUMP_FORWARD ||
5035 instr->i_opcode == RETURN_VALUE ||
5036 instr->i_opcode == RAISE_VARARGS ||
5037 instr->i_opcode == BREAK_LOOP)
5038 {
5039 /* remaining code is dead */
5040 next = NULL;
5041 break;
5042 }
5043 }
5044 if (next != NULL) {
5045 stackdepth_push(&sp, next, depth);
5046 }
5047 }
5048 PyObject_Free(stack);
5049 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005050}
5051
5052static int
5053assemble_init(struct assembler *a, int nblocks, int firstlineno)
5054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 memset(a, 0, sizeof(struct assembler));
5056 a->a_lineno = firstlineno;
5057 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5058 if (!a->a_bytecode)
5059 return 0;
5060 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5061 if (!a->a_lnotab)
5062 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005063 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 PyErr_NoMemory();
5065 return 0;
5066 }
5067 a->a_postorder = (basicblock **)PyObject_Malloc(
5068 sizeof(basicblock *) * nblocks);
5069 if (!a->a_postorder) {
5070 PyErr_NoMemory();
5071 return 0;
5072 }
5073 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005074}
5075
5076static void
5077assemble_free(struct assembler *a)
5078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 Py_XDECREF(a->a_bytecode);
5080 Py_XDECREF(a->a_lnotab);
5081 if (a->a_postorder)
5082 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005083}
5084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005085static int
5086blocksize(basicblock *b)
5087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 int i;
5089 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005092 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005094}
5095
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005096/* Appends a pair to the end of the line number table, a_lnotab, representing
5097 the instruction's bytecode offset and line number. See
5098 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005099
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005100static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005101assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005104 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005106
Serhiy Storchakaab874002016-09-11 13:48:15 +03005107 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 if(d_bytecode == 0 && d_lineno == 0)
5113 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 if (d_bytecode > 255) {
5116 int j, nbytes, ncodes = d_bytecode / 255;
5117 nbytes = a->a_lnotab_off + 2 * ncodes;
5118 len = PyBytes_GET_SIZE(a->a_lnotab);
5119 if (nbytes >= len) {
5120 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5121 len = nbytes;
5122 else if (len <= INT_MAX / 2)
5123 len *= 2;
5124 else {
5125 PyErr_NoMemory();
5126 return 0;
5127 }
5128 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5129 return 0;
5130 }
5131 lnotab = (unsigned char *)
5132 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5133 for (j = 0; j < ncodes; j++) {
5134 *lnotab++ = 255;
5135 *lnotab++ = 0;
5136 }
5137 d_bytecode -= ncodes * 255;
5138 a->a_lnotab_off += ncodes * 2;
5139 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005140 assert(0 <= d_bytecode && d_bytecode <= 255);
5141
5142 if (d_lineno < -128 || 127 < d_lineno) {
5143 int j, nbytes, ncodes, k;
5144 if (d_lineno < 0) {
5145 k = -128;
5146 /* use division on positive numbers */
5147 ncodes = (-d_lineno) / 128;
5148 }
5149 else {
5150 k = 127;
5151 ncodes = d_lineno / 127;
5152 }
5153 d_lineno -= ncodes * k;
5154 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 nbytes = a->a_lnotab_off + 2 * ncodes;
5156 len = PyBytes_GET_SIZE(a->a_lnotab);
5157 if (nbytes >= len) {
5158 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5159 len = nbytes;
5160 else if (len <= INT_MAX / 2)
5161 len *= 2;
5162 else {
5163 PyErr_NoMemory();
5164 return 0;
5165 }
5166 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5167 return 0;
5168 }
5169 lnotab = (unsigned char *)
5170 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5171 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005172 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 d_bytecode = 0;
5174 for (j = 1; j < ncodes; j++) {
5175 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005176 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 a->a_lnotab_off += ncodes * 2;
5179 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005180 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 len = PyBytes_GET_SIZE(a->a_lnotab);
5183 if (a->a_lnotab_off + 2 >= len) {
5184 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5185 return 0;
5186 }
5187 lnotab = (unsigned char *)
5188 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 a->a_lnotab_off += 2;
5191 if (d_bytecode) {
5192 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005193 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 }
5195 else { /* First line of a block; def stmt, etc. */
5196 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005197 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 }
5199 a->a_lineno = i->i_lineno;
5200 a->a_lineno_off = a->a_offset;
5201 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005202}
5203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005204/* assemble_emit()
5205 Extend the bytecode with a new instruction.
5206 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005207*/
5208
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005209static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005210assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005211{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005212 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005214 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005215
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005216 arg = i->i_oparg;
5217 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 if (i->i_lineno && !assemble_lnotab(a, i))
5219 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005220 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 if (len > PY_SSIZE_T_MAX / 2)
5222 return 0;
5223 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5224 return 0;
5225 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005226 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005228 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005230}
5231
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005232static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005233assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005236 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005237 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 /* Compute the size of each block and fixup jump args.
5240 Replace block pointer with position in bytecode. */
5241 do {
5242 totsize = 0;
5243 for (i = a->a_nblocks - 1; i >= 0; i--) {
5244 b = a->a_postorder[i];
5245 bsize = blocksize(b);
5246 b->b_offset = totsize;
5247 totsize += bsize;
5248 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005249 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5251 bsize = b->b_offset;
5252 for (i = 0; i < b->b_iused; i++) {
5253 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005254 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 /* Relative jumps are computed relative to
5256 the instruction pointer after fetching
5257 the jump instruction.
5258 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005259 bsize += isize;
5260 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005262 if (instr->i_jrel) {
5263 instr->i_oparg -= bsize;
5264 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005265 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005266 if (instrsize(instr->i_oparg) != isize) {
5267 extended_arg_recompile = 1;
5268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 }
5271 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 /* XXX: This is an awful hack that could hurt performance, but
5274 on the bright side it should work until we come up
5275 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 The issue is that in the first loop blocksize() is called
5278 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005279 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 So we loop until we stop seeing new EXTENDED_ARGs.
5283 The only EXTENDED_ARGs that could be popping up are
5284 ones in jump instructions. So this should converge
5285 fairly quickly.
5286 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005287 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005288}
5289
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005290static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005291dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005294 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 tuple = PyTuple_New(size);
5297 if (tuple == NULL)
5298 return NULL;
5299 while (PyDict_Next(dict, &pos, &k, &v)) {
5300 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005301 /* The keys of the dictionary are tuples. (see compiler_add_o
5302 * and _PyCode_ConstantKey). The object we want is always second,
5303 * though. */
5304 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 Py_INCREF(k);
5306 assert((i - offset) < size);
5307 assert((i - offset) >= 0);
5308 PyTuple_SET_ITEM(tuple, i - offset, k);
5309 }
5310 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005311}
5312
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005313static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005314compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005317 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005319 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 if (ste->ste_nested)
5321 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005322 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005324 if (!ste->ste_generator && ste->ste_coroutine)
5325 flags |= CO_COROUTINE;
5326 if (ste->ste_generator && ste->ste_coroutine)
5327 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 if (ste->ste_varargs)
5329 flags |= CO_VARARGS;
5330 if (ste->ste_varkeywords)
5331 flags |= CO_VARKEYWORDS;
5332 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 /* (Only) inherit compilerflags in PyCF_MASK */
5335 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005338}
5339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005340static PyCodeObject *
5341makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 PyObject *tmp;
5344 PyCodeObject *co = NULL;
5345 PyObject *consts = NULL;
5346 PyObject *names = NULL;
5347 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 PyObject *name = NULL;
5349 PyObject *freevars = NULL;
5350 PyObject *cellvars = NULL;
5351 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005352 Py_ssize_t nlocals;
5353 int nlocals_int;
5354 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005355 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 tmp = dict_keys_inorder(c->u->u_consts, 0);
5358 if (!tmp)
5359 goto error;
5360 consts = PySequence_List(tmp); /* optimize_code requires a list */
5361 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 names = dict_keys_inorder(c->u->u_names, 0);
5364 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5365 if (!consts || !names || !varnames)
5366 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5369 if (!cellvars)
5370 goto error;
5371 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5372 if (!freevars)
5373 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005374
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005375 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005376 assert(nlocals < INT_MAX);
5377 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 flags = compute_code_flags(c);
5380 if (flags < 0)
5381 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5384 if (!bytecode)
5385 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5388 if (!tmp)
5389 goto error;
5390 Py_DECREF(consts);
5391 consts = tmp;
5392
Victor Stinnerf8e32212013-11-19 23:56:34 +01005393 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5394 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005395 maxdepth = stackdepth(c);
5396 if (maxdepth < 0) {
5397 goto error;
5398 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005399 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005400 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 bytecode, consts, names, varnames,
5402 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005403 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 c->u->u_firstlineno,
5405 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005406 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 Py_XDECREF(consts);
5408 Py_XDECREF(names);
5409 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 Py_XDECREF(name);
5411 Py_XDECREF(freevars);
5412 Py_XDECREF(cellvars);
5413 Py_XDECREF(bytecode);
5414 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005415}
5416
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005417
5418/* For debugging purposes only */
5419#if 0
5420static void
5421dump_instr(const struct instr *i)
5422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 const char *jrel = i->i_jrel ? "jrel " : "";
5424 const char *jabs = i->i_jabs ? "jabs " : "";
5425 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005428 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5432 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005433}
5434
5435static void
5436dump_basicblock(const basicblock *b)
5437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 const char *seen = b->b_seen ? "seen " : "";
5439 const char *b_return = b->b_return ? "return " : "";
5440 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5441 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5442 if (b->b_instr) {
5443 int i;
5444 for (i = 0; i < b->b_iused; i++) {
5445 fprintf(stderr, " [%02d] ", i);
5446 dump_instr(b->b_instr + i);
5447 }
5448 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005449}
5450#endif
5451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005452static PyCodeObject *
5453assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 basicblock *b, *entryblock;
5456 struct assembler a;
5457 int i, j, nblocks;
5458 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 /* Make sure every block that falls off the end returns None.
5461 XXX NEXT_BLOCK() isn't quite right, because if the last
5462 block ends with a jump or return b_next shouldn't set.
5463 */
5464 if (!c->u->u_curblock->b_return) {
5465 NEXT_BLOCK(c);
5466 if (addNone)
5467 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5468 ADDOP(c, RETURN_VALUE);
5469 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 nblocks = 0;
5472 entryblock = NULL;
5473 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5474 nblocks++;
5475 entryblock = b;
5476 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 /* Set firstlineno if it wasn't explicitly set. */
5479 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005480 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5482 else
5483 c->u->u_firstlineno = 1;
5484 }
5485 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5486 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005487 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 /* Can't modify the bytecode after computing jump offsets. */
5490 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 /* Emit code in reverse postorder from dfs. */
5493 for (i = a.a_nblocks - 1; i >= 0; i--) {
5494 b = a.a_postorder[i];
5495 for (j = 0; j < b->b_iused; j++)
5496 if (!assemble_emit(&a, &b->b_instr[j]))
5497 goto error;
5498 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005500 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5501 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005502 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005506 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 assemble_free(&a);
5508 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005509}
Georg Brandl8334fd92010-12-04 10:26:46 +00005510
5511#undef PyAST_Compile
5512PyAPI_FUNC(PyCodeObject *)
5513PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5514 PyArena *arena)
5515{
5516 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5517}