blob: ebd73fb723197ce044f472537122d82344c43e91 [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
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
93
Antoine Pitrou86a36b52011-11-25 18:56:07 +010094enum {
95 COMPILER_SCOPE_MODULE,
96 COMPILER_SCOPE_CLASS,
97 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040098 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040099 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100 COMPILER_SCOPE_COMPREHENSION,
101};
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103/* The following items change on entry and exit of code blocks.
104 They must be saved and restored when returning to a block.
105*/
106struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400110 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100111 int u_scope_type;
112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 /* The following fields are dicts that map objects to
114 the index of them in co_XXX. The index is used as
115 the argument for opcodes that refer to those collections.
116 */
117 PyObject *u_consts; /* all constants */
118 PyObject *u_names; /* all names */
119 PyObject *u_varnames; /* local variables */
120 PyObject *u_cellvars; /* cell variables */
121 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Victor Stinnerf8e32212013-11-19 23:56:34 +0100125 Py_ssize_t u_argcount; /* number of arguments for block */
126 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 /* Pointer to the most recently allocated block. By following b_list
128 members, you can reach all early allocated blocks. */
129 basicblock *u_blocks;
130 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_nfblocks;
133 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_firstlineno; /* the first lineno of the block */
136 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000137 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_lineno_set; /* boolean to indicate whether instr
139 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140};
141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000147
148Note that we don't track recursion levels during compilation - the
149task of detecting and rejecting excessive levels of nesting is
150handled by the symbol analysis pass.
151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152*/
153
154struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200155 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 struct symtable *c_st;
157 PyFutureFeatures *c_future; /* pointer to module's __future__ */
158 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Georg Brandl8334fd92010-12-04 10:26:46 +0000160 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 int c_interactive; /* true if in interactive mode */
162 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 struct compiler_unit *u; /* compiler state for current block */
165 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
166 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167};
168
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100169static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170static void compiler_free(struct compiler *);
171static basicblock *compiler_new_block(struct compiler *);
172static int compiler_next_instr(struct compiler *, basicblock *);
173static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100174static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_error(struct compiler *, const char *);
177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700184static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200189static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500191static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400192static int compiler_async_with(struct compiler *, stmt_ty, int);
193static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100194static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400196 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500197static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400198static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000199
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700200static int compiler_sync_comprehension_generator(
201 struct compiler *c,
202 asdl_seq *generators, int gen_index,
203 expr_ty elt, expr_ty val, int type);
204
205static int compiler_async_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000211static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400213#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 /* Name mangling: __private becomes _classname__private.
219 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200220 PyObject *result;
221 size_t nlen, plen, ipriv;
222 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 PyUnicode_READ_CHAR(ident, 0) != '_' ||
225 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_INCREF(ident);
227 return ident;
228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 nlen = PyUnicode_GET_LENGTH(ident);
230 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 The only time a name with a dot can occur is when
234 we are compiling an import statement that has a
235 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 TODO(jhylton): Decide whether we want to support
238 mangling of the module name, e.g. __M.X.
239 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200240 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
241 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
242 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 Py_INCREF(ident);
244 return ident; /* Don't mangle __whatever__ */
245 }
246 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200247 ipriv = 0;
248 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
249 ipriv++;
250 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 Py_INCREF(ident);
252 return ident; /* Don't mangle if class is just underscores */
253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200254 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Antoine Pitrou55bff892013-04-06 21:21:04 +0200256 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
257 PyErr_SetString(PyExc_OverflowError,
258 "private identifier too large to be mangled");
259 return NULL;
260 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200262 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
263 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
264 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
265
266 result = PyUnicode_New(1 + nlen + plen, maxchar);
267 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200269 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
270 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200271 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
272 Py_DECREF(result);
273 return NULL;
274 }
275 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
276 Py_DECREF(result);
277 return NULL;
278 }
Victor Stinner8f825062012-04-27 13:55:39 +0200279 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000281}
282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283static int
284compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 c->c_stack = PyList_New(0);
289 if (!c->c_stack)
290 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293}
294
295PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200296PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
297 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 struct compiler c;
300 PyCodeObject *co = NULL;
301 PyCompilerFlags local_flags;
302 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!__doc__) {
305 __doc__ = PyUnicode_InternFromString("__doc__");
306 if (!__doc__)
307 return NULL;
308 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000309 if (!__annotations__) {
310 __annotations__ = PyUnicode_InternFromString("__annotations__");
311 if (!__annotations__)
312 return NULL;
313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!compiler_init(&c))
315 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200316 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 c.c_filename = filename;
318 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200319 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (c.c_future == NULL)
321 goto finally;
322 if (!flags) {
323 local_flags.cf_flags = 0;
324 flags = &local_flags;
325 }
326 merged = c.c_future->ff_features | flags->cf_flags;
327 c.c_future->ff_features = merged;
328 flags->cf_flags = merged;
329 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000330 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200333 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900334 goto finally;
335 }
336
Victor Stinner14e461d2013-08-26 22:28:21 +0200337 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (c.c_st == NULL) {
339 if (!PyErr_Occurred())
340 PyErr_SetString(PyExc_SystemError, "no symtable");
341 goto finally;
342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345
Thomas Wouters1175c432006-02-27 22:49:54 +0000346 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 compiler_free(&c);
348 assert(co || PyErr_Occurred());
349 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350}
351
352PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200353PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
354 int optimize, PyArena *arena)
355{
356 PyObject *filename;
357 PyCodeObject *co;
358 filename = PyUnicode_DecodeFSDefault(filename_str);
359 if (filename == NULL)
360 return NULL;
361 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
362 Py_DECREF(filename);
363 return co;
364
365}
366
367PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368PyNode_Compile(struct _node *n, const char *filename)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyCodeObject *co = NULL;
371 mod_ty mod;
372 PyArena *arena = PyArena_New();
373 if (!arena)
374 return NULL;
375 mod = PyAST_FromNode(n, NULL, filename, arena);
376 if (mod)
377 co = PyAST_Compile(mod, filename, NULL, arena);
378 PyArena_Free(arena);
379 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000380}
381
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000382static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (c->c_st)
386 PySymtable_Free(c->c_st);
387 if (c->c_future)
388 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200389 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391}
392
Guido van Rossum79f25d91997-04-29 20:08:16 +0000393static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 Py_ssize_t i, n;
397 PyObject *v, *k;
398 PyObject *dict = PyDict_New();
399 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 n = PyList_Size(list);
402 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100403 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (!v) {
405 Py_DECREF(dict);
406 return NULL;
407 }
408 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300409 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_DECREF(v);
411 Py_DECREF(dict);
412 return NULL;
413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300462 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300469 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_DECREF(item);
472 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return NULL;
474 }
475 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
477 }
Meador Inge2ca63152012-07-18 14:20:11 -0500478 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000480}
481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482static void
483compiler_unit_check(struct compiler_unit *u)
484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 basicblock *block;
486 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700487 assert((uintptr_t)block != 0xcbcbcbcbU);
488 assert((uintptr_t)block != 0xfbfbfbfbU);
489 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (block->b_instr != NULL) {
491 assert(block->b_ialloc > 0);
492 assert(block->b_iused > 0);
493 assert(block->b_ialloc >= block->b_iused);
494 }
495 else {
496 assert (block->b_iused == 0);
497 assert (block->b_ialloc == 0);
498 }
499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500}
501
502static void
503compiler_unit_free(struct compiler_unit *u)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 compiler_unit_check(u);
508 b = u->u_blocks;
509 while (b != NULL) {
510 if (b->b_instr)
511 PyObject_Free((void *)b->b_instr);
512 next = b->b_list;
513 PyObject_Free((void *)b);
514 b = next;
515 }
516 Py_CLEAR(u->u_ste);
517 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400518 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_CLEAR(u->u_consts);
520 Py_CLEAR(u->u_names);
521 Py_CLEAR(u->u_varnames);
522 Py_CLEAR(u->u_freevars);
523 Py_CLEAR(u->u_cellvars);
524 Py_CLEAR(u->u_private);
525 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526}
527
528static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100529compiler_enter_scope(struct compiler *c, identifier name,
530 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100533 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
536 struct compiler_unit));
537 if (!u) {
538 PyErr_NoMemory();
539 return 0;
540 }
541 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100542 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 u->u_argcount = 0;
544 u->u_kwonlyargcount = 0;
545 u->u_ste = PySymtable_Lookup(c->c_st, key);
546 if (!u->u_ste) {
547 compiler_unit_free(u);
548 return 0;
549 }
550 Py_INCREF(name);
551 u->u_name = name;
552 u->u_varnames = list2dict(u->u_ste->ste_varnames);
553 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
554 if (!u->u_varnames || !u->u_cellvars) {
555 compiler_unit_free(u);
556 return 0;
557 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500558 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000559 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500560 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300561 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500562 int res;
563 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200564 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 name = _PyUnicode_FromId(&PyId___class__);
566 if (!name) {
567 compiler_unit_free(u);
568 return 0;
569 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300570 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 if (res < 0) {
572 compiler_unit_free(u);
573 return 0;
574 }
575 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200578 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (!u->u_freevars) {
580 compiler_unit_free(u);
581 return 0;
582 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 u->u_blocks = NULL;
585 u->u_nfblocks = 0;
586 u->u_firstlineno = lineno;
587 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000588 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_lineno_set = 0;
590 u->u_consts = PyDict_New();
591 if (!u->u_consts) {
592 compiler_unit_free(u);
593 return 0;
594 }
595 u->u_names = PyDict_New();
596 if (!u->u_names) {
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_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 /* Push the old compiler_unit on the stack. */
604 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400605 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
607 Py_XDECREF(capsule);
608 compiler_unit_free(u);
609 return 0;
610 }
611 Py_DECREF(capsule);
612 u->u_private = c->u->u_private;
613 Py_XINCREF(u->u_private);
614 }
615 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100618
619 block = compiler_new_block(c);
620 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100622 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400624 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
625 if (!compiler_set_qualname(c))
626 return 0;
627 }
628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630}
631
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000632static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633compiler_exit_scope(struct compiler *c)
634{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100635 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 c->c_nestlevel--;
639 compiler_unit_free(c->u);
640 /* Restore c->u to the parent unit. */
641 n = PyList_GET_SIZE(c->c_stack) - 1;
642 if (n >= 0) {
643 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400644 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 assert(c->u);
646 /* we are deleting from a list so this really shouldn't fail */
647 if (PySequence_DelItem(c->c_stack, n) < 0)
648 Py_FatalError("compiler_exit_scope()");
649 compiler_unit_check(c->u);
650 }
651 else
652 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654}
655
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400656static int
657compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100658{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100659 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400660 _Py_static_string(dot_locals, ".<locals>");
661 Py_ssize_t stack_size;
662 struct compiler_unit *u = c->u;
663 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400667 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400668 if (stack_size > 1) {
669 int scope, force_global = 0;
670 struct compiler_unit *parent;
671 PyObject *mangled, *capsule;
672
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400673 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400674 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 assert(parent);
676
Yury Selivanov75445082015-05-11 22:57:16 -0400677 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
678 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
679 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 assert(u->u_name);
681 mangled = _Py_Mangle(parent->u_private, u->u_name);
682 if (!mangled)
683 return 0;
684 scope = PyST_GetScope(parent->u_ste, mangled);
685 Py_DECREF(mangled);
686 assert(scope != GLOBAL_IMPLICIT);
687 if (scope == GLOBAL_EXPLICIT)
688 force_global = 1;
689 }
690
691 if (!force_global) {
692 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400693 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
695 dot_locals_str = _PyUnicode_FromId(&dot_locals);
696 if (dot_locals_str == NULL)
697 return 0;
698 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
699 if (base == NULL)
700 return 0;
701 }
702 else {
703 Py_INCREF(parent->u_qualname);
704 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400705 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 }
707 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 if (base != NULL) {
710 dot_str = _PyUnicode_FromId(&dot);
711 if (dot_str == NULL) {
712 Py_DECREF(base);
713 return 0;
714 }
715 name = PyUnicode_Concat(base, dot_str);
716 Py_DECREF(base);
717 if (name == NULL)
718 return 0;
719 PyUnicode_Append(&name, u->u_name);
720 if (name == NULL)
721 return 0;
722 }
723 else {
724 Py_INCREF(u->u_name);
725 name = u->u_name;
726 }
727 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730}
731
Eric V. Smith235a6f02015-09-19 14:51:32 -0400732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733/* Allocate a new block and return a pointer to it.
734 Returns NULL on error.
735*/
736
737static basicblock *
738compiler_new_block(struct compiler *c)
739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 basicblock *b;
741 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 u = c->u;
744 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
745 if (b == NULL) {
746 PyErr_NoMemory();
747 return NULL;
748 }
749 memset((void *)b, 0, sizeof(basicblock));
750 /* Extend the singly linked list of blocks with new block. */
751 b->b_list = u->u_blocks;
752 u->u_blocks = b;
753 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754}
755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757compiler_next_block(struct compiler *c)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 basicblock *block = compiler_new_block(c);
760 if (block == NULL)
761 return NULL;
762 c->u->u_curblock->b_next = block;
763 c->u->u_curblock = block;
764 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
767static basicblock *
768compiler_use_next_block(struct compiler *c, basicblock *block)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 assert(block != NULL);
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776/* Returns the offset of the next instruction in the current block's
777 b_instr array. Resizes the b_instr as necessary.
778 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000779*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780
781static int
782compiler_next_instr(struct compiler *c, basicblock *b)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 assert(b != NULL);
785 if (b->b_instr == NULL) {
786 b->b_instr = (struct instr *)PyObject_Malloc(
787 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
788 if (b->b_instr == NULL) {
789 PyErr_NoMemory();
790 return -1;
791 }
792 b->b_ialloc = DEFAULT_BLOCK_SIZE;
793 memset((char *)b->b_instr, 0,
794 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
795 }
796 else if (b->b_iused == b->b_ialloc) {
797 struct instr *tmp;
798 size_t oldsize, newsize;
799 oldsize = b->b_ialloc * sizeof(struct instr);
800 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000801
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700802 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyErr_NoMemory();
804 return -1;
805 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (newsize == 0) {
808 PyErr_NoMemory();
809 return -1;
810 }
811 b->b_ialloc <<= 1;
812 tmp = (struct instr *)PyObject_Realloc(
813 (void *)b->b_instr, newsize);
814 if (tmp == NULL) {
815 PyErr_NoMemory();
816 return -1;
817 }
818 b->b_instr = tmp;
819 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
820 }
821 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822}
823
Christian Heimes2202f872008-02-06 14:31:34 +0000824/* Set the i_lineno member of the instruction at offset off if the
825 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 already been set. If it has been set, the call has no effect.
827
Christian Heimes2202f872008-02-06 14:31:34 +0000828 The line number is reset in the following cases:
829 - when entering a new scope
830 - on each statement
831 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200832 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000833 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836static void
837compiler_set_lineno(struct compiler *c, int off)
838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 basicblock *b;
840 if (c->u->u_lineno_set)
841 return;
842 c->u->u_lineno_set = 1;
843 b = c->u->u_curblock;
844 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845}
846
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200847/* Return the stack effect of opcode with argument oparg.
848
849 Some opcodes have different stack effect when jump to the target and
850 when not jump. The 'jump' parameter specifies the case:
851
852 * 0 -- when not jump
853 * 1 -- when jump
854 * -1 -- maximal
855 */
856/* XXX Make the stack effect of WITH_CLEANUP_START and
857 WITH_CLEANUP_FINISH deterministic. */
858static int
859stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300862 case NOP:
863 case EXTENDED_ARG:
864 return 0;
865
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200866 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 case POP_TOP:
868 return -1;
869 case ROT_TWO:
870 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200871 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return 0;
873 case DUP_TOP:
874 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000875 case DUP_TOP_TWO:
876 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200878 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 case UNARY_POSITIVE:
880 case UNARY_NEGATIVE:
881 case UNARY_NOT:
882 case UNARY_INVERT:
883 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case SET_ADD:
886 case LIST_APPEND:
887 return -1;
888 case MAP_ADD:
889 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000890
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200891 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case BINARY_POWER:
893 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400894 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case BINARY_MODULO:
896 case BINARY_ADD:
897 case BINARY_SUBTRACT:
898 case BINARY_SUBSCR:
899 case BINARY_FLOOR_DIVIDE:
900 case BINARY_TRUE_DIVIDE:
901 return -1;
902 case INPLACE_FLOOR_DIVIDE:
903 case INPLACE_TRUE_DIVIDE:
904 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case INPLACE_ADD:
907 case INPLACE_SUBTRACT:
908 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400909 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case INPLACE_MODULO:
911 return -1;
912 case STORE_SUBSCR:
913 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case DELETE_SUBSCR:
915 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case BINARY_LSHIFT:
918 case BINARY_RSHIFT:
919 case BINARY_AND:
920 case BINARY_XOR:
921 case BINARY_OR:
922 return -1;
923 case INPLACE_POWER:
924 return -1;
925 case GET_ITER:
926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case PRINT_EXPR:
929 return -1;
930 case LOAD_BUILD_CLASS:
931 return 1;
932 case INPLACE_LSHIFT:
933 case INPLACE_RSHIFT:
934 case INPLACE_AND:
935 case INPLACE_XOR:
936 case INPLACE_OR:
937 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200940 /* 1 in the normal flow.
941 * Restore the stack position and push 6 values before jumping to
942 * the handler if an exception be raised. */
943 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400944 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200945 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400946 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200947 /* Pop a variable number of values pushed by WITH_CLEANUP_START
948 * + __exit__ or __aexit__. */
949 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case RETURN_VALUE:
951 return -1;
952 case IMPORT_STAR:
953 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700954 case SETUP_ANNOTATIONS:
955 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case YIELD_VALUE:
957 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500958 case YIELD_FROM:
959 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case POP_BLOCK:
961 return 0;
962 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200963 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200965 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200966 /* Pop 6 values when an exception was raised. */
967 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case STORE_NAME:
970 return -1;
971 case DELETE_NAME:
972 return 0;
973 case UNPACK_SEQUENCE:
974 return oparg-1;
975 case UNPACK_EX:
976 return (oparg&0xFF) + (oparg>>8);
977 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200978 /* -1 at end of iterator, 1 if continue iterating. */
979 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_ATTR:
982 return -2;
983 case DELETE_ATTR:
984 return -1;
985 case STORE_GLOBAL:
986 return -1;
987 case DELETE_GLOBAL:
988 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case LOAD_CONST:
990 return 1;
991 case LOAD_NAME:
992 return 1;
993 case BUILD_TUPLE:
994 case BUILD_LIST:
995 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300996 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400998 case BUILD_LIST_UNPACK:
999 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001000 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001001 case BUILD_SET_UNPACK:
1002 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001003 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001004 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001006 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001007 case BUILD_CONST_KEY_MAP:
1008 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_ATTR:
1010 return 0;
1011 case COMPARE_OP:
1012 return -1;
1013 case IMPORT_NAME:
1014 return -1;
1015 case IMPORT_FROM:
1016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001018 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case JUMP_ABSOLUTE:
1021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001023 case JUMP_IF_TRUE_OR_POP:
1024 case JUMP_IF_FALSE_OR_POP:
1025 return jump ? 0 : -1;
1026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case POP_JUMP_IF_FALSE:
1028 case POP_JUMP_IF_TRUE:
1029 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case LOAD_GLOBAL:
1032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001034 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001036 /* 0 in the normal flow.
1037 * Restore the stack position and push 6 values before jumping to
1038 * the handler if an exception be raised. */
1039 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001040 case BEGIN_FINALLY:
1041 /* Actually pushes 1 value, but count 6 for balancing with
1042 * END_FINALLY and POP_FINALLY.
1043 * This is the main reason of using this opcode instead of
1044 * "LOAD_CONST None". */
1045 return 6;
1046 case CALL_FINALLY:
1047 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case LOAD_FAST:
1050 return 1;
1051 case STORE_FAST:
1052 return -1;
1053 case DELETE_FAST:
1054 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case RAISE_VARARGS:
1057 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001058
1059 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001061 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001062 case CALL_METHOD:
1063 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001065 return -oparg-1;
1066 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001067 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001068 case MAKE_FUNCTION:
1069 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1070 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case BUILD_SLICE:
1072 if (oparg == 3)
1073 return -2;
1074 else
1075 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001077 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 case LOAD_CLOSURE:
1079 return 1;
1080 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001081 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return 1;
1083 case STORE_DEREF:
1084 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001085 case DELETE_DEREF:
1086 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001087
1088 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001089 case GET_AWAITABLE:
1090 return 0;
1091 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001092 /* 0 in the normal flow.
1093 * Restore the stack position to the position before the result
1094 * of __aenter__ and push 6 values before jumping to the handler
1095 * if an exception be raised. */
1096 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001097 case BEFORE_ASYNC_WITH:
1098 return 1;
1099 case GET_AITER:
1100 return 0;
1101 case GET_ANEXT:
1102 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001103 case GET_YIELD_FROM_ITER:
1104 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001105 case END_ASYNC_FOR:
1106 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001107 case FORMAT_VALUE:
1108 /* If there's a fmt_spec on the stack, we go from 2->1,
1109 else 1->1. */
1110 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001111 case LOAD_METHOD:
1112 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001114 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 }
Larry Hastings3a907972013-11-23 14:49:22 -08001116 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117}
1118
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001119int
1120PyCompile_OpcodeStackEffect(int opcode, int oparg)
1121{
1122 return stack_effect(opcode, oparg, -1);
1123}
1124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125/* Add an opcode with no argument.
1126 Returns 0 on failure, 1 on success.
1127*/
1128
1129static int
1130compiler_addop(struct compiler *c, int opcode)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 basicblock *b;
1133 struct instr *i;
1134 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001135 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 off = compiler_next_instr(c, c->u->u_curblock);
1137 if (off < 0)
1138 return 0;
1139 b = c->u->u_curblock;
1140 i = &b->b_instr[off];
1141 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001142 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (opcode == RETURN_VALUE)
1144 b->b_return = 1;
1145 compiler_set_lineno(c, off);
1146 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
Victor Stinnerf8e32212013-11-19 23:56:34 +01001149static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1151{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001152 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001155 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001157 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001159 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001160 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001161 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return -1;
1164 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001165 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 Py_DECREF(v);
1167 return -1;
1168 }
1169 Py_DECREF(v);
1170 }
1171 else
1172 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001173 return arg;
1174}
1175
1176static Py_ssize_t
1177compiler_add_const(struct compiler *c, PyObject *o)
1178{
1179 PyObject *t;
1180 Py_ssize_t arg;
1181
1182 t = _PyCode_ConstantKey(o);
1183 if (t == NULL)
1184 return -1;
1185
1186 arg = compiler_add_o(c, c->u->u_consts, t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_DECREF(t);
1188 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189}
1190
1191static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001192compiler_addop_load_const(struct compiler *c, PyObject *o)
1193{
1194 Py_ssize_t arg = compiler_add_const(c, o);
1195 if (arg < 0)
1196 return 0;
1197 return compiler_addop_i(c, LOAD_CONST, arg);
1198}
1199
1200static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201compiler_addop_o(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 = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001206 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 return compiler_addop_i(c, opcode, arg);
1208}
1209
1210static int
1211compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001214 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1216 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001217 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 arg = compiler_add_o(c, dict, mangled);
1219 Py_DECREF(mangled);
1220 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001221 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 return compiler_addop_i(c, opcode, arg);
1223}
1224
1225/* Add an opcode with an integer argument.
1226 Returns 0 on failure, 1 on success.
1227*/
1228
1229static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001230compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 struct instr *i;
1233 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001234
Victor Stinner2ad474b2016-03-01 23:34:47 +01001235 /* oparg value is unsigned, but a signed C int is usually used to store
1236 it in the C code (like Python/ceval.c).
1237
1238 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1239
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001240 The argument of a concrete bytecode instruction is limited to 8-bit.
1241 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1242 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001243 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 off = compiler_next_instr(c, c->u->u_curblock);
1246 if (off < 0)
1247 return 0;
1248 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001249 i->i_opcode = opcode;
1250 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 compiler_set_lineno(c, off);
1252 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253}
1254
1255static int
1256compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 struct instr *i;
1259 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001261 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 assert(b != NULL);
1263 off = compiler_next_instr(c, c->u->u_curblock);
1264 if (off < 0)
1265 return 0;
1266 i = &c->u->u_curblock->b_instr[off];
1267 i->i_opcode = opcode;
1268 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (absolute)
1270 i->i_jabs = 1;
1271 else
1272 i->i_jrel = 1;
1273 compiler_set_lineno(c, off);
1274 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001277/* NEXT_BLOCK() creates an implicit jump from the current block
1278 to the new block.
1279
1280 The returns inside this macro make it impossible to decref objects
1281 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (compiler_next_block((C)) == NULL) \
1285 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286}
1287
1288#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!compiler_addop((C), (OP))) \
1290 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291}
1292
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001293#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_addop((C), (OP))) { \
1295 compiler_exit_scope(c); \
1296 return 0; \
1297 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001298}
1299
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001300#define ADDOP_LOAD_CONST(C, O) { \
1301 if (!compiler_addop_load_const((C), (O))) \
1302 return 0; \
1303}
1304
1305/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1306#define ADDOP_LOAD_CONST_NEW(C, O) { \
1307 PyObject *__new_const = (O); \
1308 if (__new_const == NULL) { \
1309 return 0; \
1310 } \
1311 if (!compiler_addop_load_const((C), __new_const)) { \
1312 Py_DECREF(__new_const); \
1313 return 0; \
1314 } \
1315 Py_DECREF(__new_const); \
1316}
1317
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1320 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321}
1322
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001323/* Same as ADDOP_O, but steals a reference. */
1324#define ADDOP_N(C, OP, O, TYPE) { \
1325 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1326 Py_DECREF((O)); \
1327 return 0; \
1328 } \
1329 Py_DECREF((O)); \
1330}
1331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1334 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335}
1336
1337#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (!compiler_addop_i((C), (OP), (O))) \
1339 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340}
1341
1342#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (!compiler_addop_j((C), (OP), (O), 1)) \
1344 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345}
1346
1347#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (!compiler_addop_j((C), (OP), (O), 0)) \
1349 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350}
1351
1352/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1353 the ASDL name to synthesize the name of the C type and the visit function.
1354*/
1355
1356#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 if (!compiler_visit_ ## TYPE((C), (V))) \
1358 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359}
1360
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001361#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 if (!compiler_visit_ ## TYPE((C), (V))) { \
1363 compiler_exit_scope(c); \
1364 return 0; \
1365 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001366}
1367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (!compiler_visit_slice((C), (V), (CTX))) \
1370 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371}
1372
1373#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 int _i; \
1375 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1376 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1377 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1378 if (!compiler_visit_ ## TYPE((C), elt)) \
1379 return 0; \
1380 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381}
1382
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001383#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 int _i; \
1385 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1386 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1387 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1388 if (!compiler_visit_ ## TYPE((C), elt)) { \
1389 compiler_exit_scope(c); \
1390 return 0; \
1391 } \
1392 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001393}
1394
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001396is_const(expr_ty e)
1397{
1398 switch (e->kind) {
1399 case Constant_kind:
1400 case Num_kind:
1401 case Str_kind:
1402 case Bytes_kind:
1403 case Ellipsis_kind:
1404 case NameConstant_kind:
1405 return 1;
1406 default:
1407 return 0;
1408 }
1409}
1410
1411static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001412get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001413{
1414 switch (e->kind) {
1415 case Constant_kind:
1416 return e->v.Constant.value;
1417 case Num_kind:
1418 return e->v.Num.n;
1419 case Str_kind:
1420 return e->v.Str.s;
1421 case Bytes_kind:
1422 return e->v.Bytes.s;
1423 case Ellipsis_kind:
1424 return Py_Ellipsis;
1425 case NameConstant_kind:
1426 return e->v.NameConstant.value;
1427 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001428 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001429 }
1430}
1431
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001432/* Search if variable annotations are present statically in a block. */
1433
1434static int
1435find_ann(asdl_seq *stmts)
1436{
1437 int i, j, res = 0;
1438 stmt_ty st;
1439
1440 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1441 st = (stmt_ty)asdl_seq_GET(stmts, i);
1442 switch (st->kind) {
1443 case AnnAssign_kind:
1444 return 1;
1445 case For_kind:
1446 res = find_ann(st->v.For.body) ||
1447 find_ann(st->v.For.orelse);
1448 break;
1449 case AsyncFor_kind:
1450 res = find_ann(st->v.AsyncFor.body) ||
1451 find_ann(st->v.AsyncFor.orelse);
1452 break;
1453 case While_kind:
1454 res = find_ann(st->v.While.body) ||
1455 find_ann(st->v.While.orelse);
1456 break;
1457 case If_kind:
1458 res = find_ann(st->v.If.body) ||
1459 find_ann(st->v.If.orelse);
1460 break;
1461 case With_kind:
1462 res = find_ann(st->v.With.body);
1463 break;
1464 case AsyncWith_kind:
1465 res = find_ann(st->v.AsyncWith.body);
1466 break;
1467 case Try_kind:
1468 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1469 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1470 st->v.Try.handlers, j);
1471 if (find_ann(handler->v.ExceptHandler.body)) {
1472 return 1;
1473 }
1474 }
1475 res = find_ann(st->v.Try.body) ||
1476 find_ann(st->v.Try.finalbody) ||
1477 find_ann(st->v.Try.orelse);
1478 break;
1479 default:
1480 res = 0;
1481 }
1482 if (res) {
1483 break;
1484 }
1485 }
1486 return res;
1487}
1488
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001489/*
1490 * Frame block handling functions
1491 */
1492
1493static int
1494compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1495 basicblock *exit)
1496{
1497 struct fblockinfo *f;
1498 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1499 PyErr_SetString(PyExc_SyntaxError,
1500 "too many statically nested blocks");
1501 return 0;
1502 }
1503 f = &c->u->u_fblock[c->u->u_nfblocks++];
1504 f->fb_type = t;
1505 f->fb_block = b;
1506 f->fb_exit = exit;
1507 return 1;
1508}
1509
1510static void
1511compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1512{
1513 struct compiler_unit *u = c->u;
1514 assert(u->u_nfblocks > 0);
1515 u->u_nfblocks--;
1516 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1517 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1518}
1519
1520/* Unwind a frame block. If preserve_tos is true, the TOS before
1521 * popping the blocks will be restored afterwards.
1522 */
1523static int
1524compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1525 int preserve_tos)
1526{
1527 switch (info->fb_type) {
1528 case WHILE_LOOP:
1529 return 1;
1530
1531 case FINALLY_END:
1532 ADDOP_I(c, POP_FINALLY, preserve_tos);
1533 return 1;
1534
1535 case FOR_LOOP:
1536 /* Pop the iterator */
1537 if (preserve_tos) {
1538 ADDOP(c, ROT_TWO);
1539 }
1540 ADDOP(c, POP_TOP);
1541 return 1;
1542
1543 case EXCEPT:
1544 ADDOP(c, POP_BLOCK);
1545 return 1;
1546
1547 case FINALLY_TRY:
1548 ADDOP(c, POP_BLOCK);
1549 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1550 return 1;
1551
1552 case WITH:
1553 case ASYNC_WITH:
1554 ADDOP(c, POP_BLOCK);
1555 if (preserve_tos) {
1556 ADDOP(c, ROT_TWO);
1557 }
1558 ADDOP(c, BEGIN_FINALLY);
1559 ADDOP(c, WITH_CLEANUP_START);
1560 if (info->fb_type == ASYNC_WITH) {
1561 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001562 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001563 ADDOP(c, YIELD_FROM);
1564 }
1565 ADDOP(c, WITH_CLEANUP_FINISH);
1566 ADDOP_I(c, POP_FINALLY, 0);
1567 return 1;
1568
1569 case HANDLER_CLEANUP:
1570 if (preserve_tos) {
1571 ADDOP(c, ROT_FOUR);
1572 }
1573 if (info->fb_exit) {
1574 ADDOP(c, POP_BLOCK);
1575 ADDOP(c, POP_EXCEPT);
1576 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1577 }
1578 else {
1579 ADDOP(c, POP_EXCEPT);
1580 }
1581 return 1;
1582 }
1583 Py_UNREACHABLE();
1584}
1585
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001586/* Compile a sequence of statements, checking for a docstring
1587 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588
1589static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001590compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001592 int i = 0;
1593 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001594 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001595
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001596 /* Set current line number to the line number of first statement.
1597 This way line number for SETUP_ANNOTATIONS will always
1598 coincide with the line number of first "real" statement in module.
1599 If body is empy, then lineno will be set later in assemble. */
1600 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1601 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001602 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001603 c->u->u_lineno = st->lineno;
1604 }
1605 /* Every annotated class and module should have __annotations__. */
1606 if (find_ann(stmts)) {
1607 ADDOP(c, SETUP_ANNOTATIONS);
1608 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001609 if (!asdl_seq_LEN(stmts))
1610 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001611 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001612 if (c->c_optimize < 2) {
1613 docstring = _PyAST_GetDocString(stmts);
1614 if (docstring) {
1615 i = 1;
1616 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1617 assert(st->kind == Expr_kind);
1618 VISIT(c, expr, st->v.Expr.value);
1619 if (!compiler_nameop(c, __doc__, Store))
1620 return 0;
1621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001623 for (; i < asdl_seq_LEN(stmts); i++)
1624 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626}
1627
1628static PyCodeObject *
1629compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 PyCodeObject *co;
1632 int addNone = 1;
1633 static PyObject *module;
1634 if (!module) {
1635 module = PyUnicode_InternFromString("<module>");
1636 if (!module)
1637 return NULL;
1638 }
1639 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001640 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 return NULL;
1642 switch (mod->kind) {
1643 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001644 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 compiler_exit_scope(c);
1646 return 0;
1647 }
1648 break;
1649 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001650 if (find_ann(mod->v.Interactive.body)) {
1651 ADDOP(c, SETUP_ANNOTATIONS);
1652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 c->c_interactive = 1;
1654 VISIT_SEQ_IN_SCOPE(c, stmt,
1655 mod->v.Interactive.body);
1656 break;
1657 case Expression_kind:
1658 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1659 addNone = 0;
1660 break;
1661 case Suite_kind:
1662 PyErr_SetString(PyExc_SystemError,
1663 "suite should not be possible");
1664 return 0;
1665 default:
1666 PyErr_Format(PyExc_SystemError,
1667 "module kind %d should not be possible",
1668 mod->kind);
1669 return 0;
1670 }
1671 co = assemble(c, addNone);
1672 compiler_exit_scope(c);
1673 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001674}
1675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676/* The test for LOCAL must come before the test for FREE in order to
1677 handle classes where name is both local and free. The local var is
1678 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001679*/
1680
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681static int
1682get_ref_type(struct compiler *c, PyObject *name)
1683{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001684 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001685 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001686 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001687 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001688 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (scope == 0) {
1690 char buf[350];
1691 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001692 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001694 PyUnicode_AsUTF8(name),
1695 PyUnicode_AsUTF8(c->u->u_name),
1696 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1697 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1698 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1699 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 );
1701 Py_FatalError(buf);
1702 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705}
1706
1707static int
1708compiler_lookup_arg(PyObject *dict, PyObject *name)
1709{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001710 PyObject *v;
1711 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001713 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001714 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715}
1716
1717static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001718compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001719{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001720 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001721 if (qualname == NULL)
1722 qualname = co->co_name;
1723
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001724 if (free) {
1725 for (i = 0; i < free; ++i) {
1726 /* Bypass com_addop_varname because it will generate
1727 LOAD_DEREF but LOAD_CLOSURE is needed.
1728 */
1729 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1730 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001732 /* Special case: If a class contains a method with a
1733 free variable that has the same name as a method,
1734 the name will be considered free *and* local in the
1735 class. It should be handled by the closure, as
1736 well as by the normal name loookup logic.
1737 */
1738 reftype = get_ref_type(c, name);
1739 if (reftype == CELL)
1740 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1741 else /* (reftype == FREE) */
1742 arg = compiler_lookup_arg(c->u->u_freevars, name);
1743 if (arg == -1) {
1744 fprintf(stderr,
1745 "lookup %s in %s %d %d\n"
1746 "freevars of %s: %s\n",
1747 PyUnicode_AsUTF8(PyObject_Repr(name)),
1748 PyUnicode_AsUTF8(c->u->u_name),
1749 reftype, arg,
1750 PyUnicode_AsUTF8(co->co_name),
1751 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1752 Py_FatalError("compiler_make_closure()");
1753 }
1754 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001756 flags |= 0x08;
1757 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001759 ADDOP_LOAD_CONST(c, (PyObject*)co);
1760 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763}
1764
1765static int
1766compiler_decorators(struct compiler *c, asdl_seq* decos)
1767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (!decos)
1771 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1774 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1775 }
1776 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777}
1778
1779static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001780compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001782{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001783 /* Push a dict of keyword-only default values.
1784
1785 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1786 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001787 int i;
1788 PyObject *keys = NULL;
1789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1791 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1792 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1793 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001794 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001795 if (!mangled) {
1796 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001798 if (keys == NULL) {
1799 keys = PyList_New(1);
1800 if (keys == NULL) {
1801 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001802 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001803 }
1804 PyList_SET_ITEM(keys, 0, mangled);
1805 }
1806 else {
1807 int res = PyList_Append(keys, mangled);
1808 Py_DECREF(mangled);
1809 if (res == -1) {
1810 goto error;
1811 }
1812 }
1813 if (!compiler_visit_expr(c, default_)) {
1814 goto error;
1815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 }
1817 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001818 if (keys != NULL) {
1819 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1820 PyObject *keys_tuple = PyList_AsTuple(keys);
1821 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001822 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001823 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001824 assert(default_count > 0);
1825 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001826 }
1827 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001828 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001829 }
1830
1831error:
1832 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001833 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001834}
1835
1836static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001837compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1838{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001839 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001840 return 1;
1841}
1842
1843static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001844compiler_visit_argannotation(struct compiler *c, identifier id,
1845 expr_ty annotation, PyObject *names)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001848 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001849 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1850 VISIT(c, annexpr, annotation)
1851 }
1852 else {
1853 VISIT(c, expr, annotation);
1854 }
Victor Stinner065efc32014-02-18 22:07:56 +01001855 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001856 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001857 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001858 if (PyList_Append(names, mangled) < 0) {
1859 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001860 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001861 }
1862 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001864 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001865}
1866
1867static int
1868compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1869 PyObject *names)
1870{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001871 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 for (i = 0; i < asdl_seq_LEN(args); i++) {
1873 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001874 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 c,
1876 arg->arg,
1877 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001878 names))
1879 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001881 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001882}
1883
1884static int
1885compiler_visit_annotations(struct compiler *c, arguments_ty args,
1886 expr_ty returns)
1887{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001888 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001889 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001890
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001891 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 */
1893 static identifier return_str;
1894 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001895 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 names = PyList_New(0);
1897 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001898 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001899
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001900 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001902 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001903 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001904 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001906 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001908 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001909 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001910 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (!return_str) {
1914 return_str = PyUnicode_InternFromString("return");
1915 if (!return_str)
1916 goto error;
1917 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001918 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 goto error;
1920 }
1921
1922 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 PyObject *keytuple = PyList_AsTuple(names);
1925 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001926 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001927 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001928 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001930 else {
1931 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001932 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001933 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001934
1935error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001937 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001938}
1939
1940static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001941compiler_visit_defaults(struct compiler *c, arguments_ty args)
1942{
1943 VISIT_SEQ(c, expr, args->defaults);
1944 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1945 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946}
1947
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001948static Py_ssize_t
1949compiler_default_arguments(struct compiler *c, arguments_ty args)
1950{
1951 Py_ssize_t funcflags = 0;
1952 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001953 if (!compiler_visit_defaults(c, args))
1954 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001955 funcflags |= 0x01;
1956 }
1957 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001958 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001959 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001960 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001961 return -1;
1962 }
1963 else if (res > 0) {
1964 funcflags |= 0x02;
1965 }
1966 }
1967 return funcflags;
1968}
1969
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970static int
Yury Selivanov75445082015-05-11 22:57:16 -04001971compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001974 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04001975 arguments_ty args;
1976 expr_ty returns;
1977 identifier name;
1978 asdl_seq* decos;
1979 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001980 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001981 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001982 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001983
Yury Selivanov75445082015-05-11 22:57:16 -04001984 if (is_async) {
1985 assert(s->kind == AsyncFunctionDef_kind);
1986
1987 args = s->v.AsyncFunctionDef.args;
1988 returns = s->v.AsyncFunctionDef.returns;
1989 decos = s->v.AsyncFunctionDef.decorator_list;
1990 name = s->v.AsyncFunctionDef.name;
1991 body = s->v.AsyncFunctionDef.body;
1992
1993 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1994 } else {
1995 assert(s->kind == FunctionDef_kind);
1996
1997 args = s->v.FunctionDef.args;
1998 returns = s->v.FunctionDef.returns;
1999 decos = s->v.FunctionDef.decorator_list;
2000 name = s->v.FunctionDef.name;
2001 body = s->v.FunctionDef.body;
2002
2003 scope_type = COMPILER_SCOPE_FUNCTION;
2004 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (!compiler_decorators(c, decos))
2007 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002008
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002009 funcflags = compiler_default_arguments(c, args);
2010 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 }
2013
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002014 annotations = compiler_visit_annotations(c, args, returns);
2015 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002016 return 0;
2017 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002018 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002019 funcflags |= 0x04;
2020 }
2021
2022 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
2023 return 0;
2024 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
INADA Naokicb41b272017-02-23 00:31:59 +09002026 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002027 if (c->c_optimize < 2) {
2028 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002029 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002030 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 compiler_exit_scope(c);
2032 return 0;
2033 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 c->u->u_argcount = asdl_seq_LEN(args->args);
2036 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002037 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002039 qualname = c->u->u_qualname;
2040 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002042 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002043 Py_XDECREF(qualname);
2044 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002046 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002048 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002049 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* decorators */
2053 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2054 ADDOP_I(c, CALL_FUNCTION, 1);
2055 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056
Yury Selivanov75445082015-05-11 22:57:16 -04002057 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058}
2059
2060static int
2061compiler_class(struct compiler *c, stmt_ty s)
2062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyCodeObject *co;
2064 PyObject *str;
2065 int i;
2066 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (!compiler_decorators(c, decos))
2069 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 /* ultimately generate code for:
2072 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2073 where:
2074 <func> is a function/closure created from the class body;
2075 it has a single argument (__locals__) where the dict
2076 (or MutableSequence) representing the locals is passed
2077 <name> is the class name
2078 <bases> is the positional arguments and *varargs argument
2079 <keywords> is the keyword arguments and **kwds argument
2080 This borrows from compiler_call.
2081 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002084 if (!compiler_enter_scope(c, s->v.ClassDef.name,
2085 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return 0;
2087 /* this block represents what we do in the new scope */
2088 {
2089 /* use the class name for name mangling */
2090 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002091 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* load (global) __name__ ... */
2093 str = PyUnicode_InternFromString("__name__");
2094 if (!str || !compiler_nameop(c, str, Load)) {
2095 Py_XDECREF(str);
2096 compiler_exit_scope(c);
2097 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002098 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 Py_DECREF(str);
2100 /* ... and store it as __module__ */
2101 str = PyUnicode_InternFromString("__module__");
2102 if (!str || !compiler_nameop(c, str, Store)) {
2103 Py_XDECREF(str);
2104 compiler_exit_scope(c);
2105 return 0;
2106 }
2107 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002108 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002109 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002110 str = PyUnicode_InternFromString("__qualname__");
2111 if (!str || !compiler_nameop(c, str, Store)) {
2112 Py_XDECREF(str);
2113 compiler_exit_scope(c);
2114 return 0;
2115 }
2116 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002118 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 compiler_exit_scope(c);
2120 return 0;
2121 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002122 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002123 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002124 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002125 str = PyUnicode_InternFromString("__class__");
2126 if (str == NULL) {
2127 compiler_exit_scope(c);
2128 return 0;
2129 }
2130 i = compiler_lookup_arg(c->u->u_cellvars, str);
2131 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002132 if (i < 0) {
2133 compiler_exit_scope(c);
2134 return 0;
2135 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002136 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002139 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002140 str = PyUnicode_InternFromString("__classcell__");
2141 if (!str || !compiler_nameop(c, str, Store)) {
2142 Py_XDECREF(str);
2143 compiler_exit_scope(c);
2144 return 0;
2145 }
2146 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002148 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002149 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002150 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002151 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002152 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002153 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 /* create the code object */
2155 co = assemble(c, 1);
2156 }
2157 /* leave the new scope */
2158 compiler_exit_scope(c);
2159 if (co == NULL)
2160 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 /* 2. load the 'build_class' function */
2163 ADDOP(c, LOAD_BUILD_CLASS);
2164
2165 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002166 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_DECREF(co);
2168
2169 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002170 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171
2172 /* 5. generate the rest of the code for the call */
2173 if (!compiler_call_helper(c, 2,
2174 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002175 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return 0;
2177
2178 /* 6. apply decorators */
2179 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2180 ADDOP_I(c, CALL_FUNCTION, 1);
2181 }
2182
2183 /* 7. store into <name> */
2184 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2185 return 0;
2186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187}
2188
2189static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002190cmpop(cmpop_ty op)
2191{
2192 switch (op) {
2193 case Eq:
2194 return PyCmp_EQ;
2195 case NotEq:
2196 return PyCmp_NE;
2197 case Lt:
2198 return PyCmp_LT;
2199 case LtE:
2200 return PyCmp_LE;
2201 case Gt:
2202 return PyCmp_GT;
2203 case GtE:
2204 return PyCmp_GE;
2205 case Is:
2206 return PyCmp_IS;
2207 case IsNot:
2208 return PyCmp_IS_NOT;
2209 case In:
2210 return PyCmp_IN;
2211 case NotIn:
2212 return PyCmp_NOT_IN;
2213 default:
2214 return PyCmp_BAD;
2215 }
2216}
2217
2218static int
2219compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2220{
2221 switch (e->kind) {
2222 case UnaryOp_kind:
2223 if (e->v.UnaryOp.op == Not)
2224 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2225 /* fallback to general implementation */
2226 break;
2227 case BoolOp_kind: {
2228 asdl_seq *s = e->v.BoolOp.values;
2229 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2230 assert(n >= 0);
2231 int cond2 = e->v.BoolOp.op == Or;
2232 basicblock *next2 = next;
2233 if (!cond2 != !cond) {
2234 next2 = compiler_new_block(c);
2235 if (next2 == NULL)
2236 return 0;
2237 }
2238 for (i = 0; i < n; ++i) {
2239 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2240 return 0;
2241 }
2242 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2243 return 0;
2244 if (next2 != next)
2245 compiler_use_next_block(c, next2);
2246 return 1;
2247 }
2248 case IfExp_kind: {
2249 basicblock *end, *next2;
2250 end = compiler_new_block(c);
2251 if (end == NULL)
2252 return 0;
2253 next2 = compiler_new_block(c);
2254 if (next2 == NULL)
2255 return 0;
2256 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2257 return 0;
2258 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2259 return 0;
2260 ADDOP_JREL(c, JUMP_FORWARD, end);
2261 compiler_use_next_block(c, next2);
2262 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2263 return 0;
2264 compiler_use_next_block(c, end);
2265 return 1;
2266 }
2267 case Compare_kind: {
2268 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2269 if (n > 0) {
2270 basicblock *cleanup = compiler_new_block(c);
2271 if (cleanup == NULL)
2272 return 0;
2273 VISIT(c, expr, e->v.Compare.left);
2274 for (i = 0; i < n; i++) {
2275 VISIT(c, expr,
2276 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2277 ADDOP(c, DUP_TOP);
2278 ADDOP(c, ROT_THREE);
2279 ADDOP_I(c, COMPARE_OP,
2280 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2281 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2282 NEXT_BLOCK(c);
2283 }
2284 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2285 ADDOP_I(c, COMPARE_OP,
2286 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2287 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2288 basicblock *end = compiler_new_block(c);
2289 if (end == NULL)
2290 return 0;
2291 ADDOP_JREL(c, JUMP_FORWARD, end);
2292 compiler_use_next_block(c, cleanup);
2293 ADDOP(c, POP_TOP);
2294 if (!cond) {
2295 ADDOP_JREL(c, JUMP_FORWARD, next);
2296 }
2297 compiler_use_next_block(c, end);
2298 return 1;
2299 }
2300 /* fallback to general implementation */
2301 break;
2302 }
2303 default:
2304 /* fallback to general implementation */
2305 break;
2306 }
2307
2308 /* general implementation */
2309 VISIT(c, expr, e);
2310 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2311 return 1;
2312}
2313
2314static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002315compiler_ifexp(struct compiler *c, expr_ty e)
2316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 basicblock *end, *next;
2318
2319 assert(e->kind == IfExp_kind);
2320 end = compiler_new_block(c);
2321 if (end == NULL)
2322 return 0;
2323 next = compiler_new_block(c);
2324 if (next == NULL)
2325 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002326 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2327 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 VISIT(c, expr, e->v.IfExp.body);
2329 ADDOP_JREL(c, JUMP_FORWARD, end);
2330 compiler_use_next_block(c, next);
2331 VISIT(c, expr, e->v.IfExp.orelse);
2332 compiler_use_next_block(c, end);
2333 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002334}
2335
2336static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337compiler_lambda(struct compiler *c, expr_ty e)
2338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002340 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002342 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 arguments_ty args = e->v.Lambda.args;
2344 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 if (!name) {
2347 name = PyUnicode_InternFromString("<lambda>");
2348 if (!name)
2349 return 0;
2350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002352 funcflags = compiler_default_arguments(c, args);
2353 if (funcflags == -1) {
2354 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002356
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002357 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002358 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* Make None the first constant, so the lambda can't have a
2362 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002363 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 c->u->u_argcount = asdl_seq_LEN(args->args);
2367 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2368 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2369 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002370 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 }
2372 else {
2373 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002374 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002376 qualname = c->u->u_qualname;
2377 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002379 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002381
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002382 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002383 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 Py_DECREF(co);
2385
2386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387}
2388
2389static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390compiler_if(struct compiler *c, stmt_ty s)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 basicblock *end, *next;
2393 int constant;
2394 assert(s->kind == If_kind);
2395 end = compiler_new_block(c);
2396 if (end == NULL)
2397 return 0;
2398
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002399 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* constant = 0: "if 0"
2401 * constant = 1: "if 1", "if 2", ...
2402 * constant = -1: rest */
2403 if (constant == 0) {
2404 if (s->v.If.orelse)
2405 VISIT_SEQ(c, stmt, s->v.If.orelse);
2406 } else if (constant == 1) {
2407 VISIT_SEQ(c, stmt, s->v.If.body);
2408 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002409 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 next = compiler_new_block(c);
2411 if (next == NULL)
2412 return 0;
2413 }
2414 else
2415 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002416 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2417 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002419 if (asdl_seq_LEN(s->v.If.orelse)) {
2420 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 compiler_use_next_block(c, next);
2422 VISIT_SEQ(c, stmt, s->v.If.orelse);
2423 }
2424 }
2425 compiler_use_next_block(c, end);
2426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427}
2428
2429static int
2430compiler_for(struct compiler *c, stmt_ty s)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 start = compiler_new_block(c);
2435 cleanup = compiler_new_block(c);
2436 end = compiler_new_block(c);
2437 if (start == NULL || end == NULL || cleanup == NULL)
2438 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002439
2440 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 VISIT(c, expr, s->v.For.iter);
2444 ADDOP(c, GET_ITER);
2445 compiler_use_next_block(c, start);
2446 ADDOP_JREL(c, FOR_ITER, cleanup);
2447 VISIT(c, expr, s->v.For.target);
2448 VISIT_SEQ(c, stmt, s->v.For.body);
2449 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2450 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002451
2452 compiler_pop_fblock(c, FOR_LOOP, start);
2453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 VISIT_SEQ(c, stmt, s->v.For.orelse);
2455 compiler_use_next_block(c, end);
2456 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457}
2458
Yury Selivanov75445082015-05-11 22:57:16 -04002459
2460static int
2461compiler_async_for(struct compiler *c, stmt_ty s)
2462{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002463 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002464 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2465 return compiler_error(c, "'async for' outside async function");
2466 }
2467
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002468 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002469 except = compiler_new_block(c);
2470 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002471
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002472 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002473 return 0;
2474
2475 VISIT(c, expr, s->v.AsyncFor.iter);
2476 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002477
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002478 compiler_use_next_block(c, start);
2479 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2480 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002481
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002482 /* SETUP_FINALLY to guard the __anext__ call */
2483 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002484 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002485 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002486 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002487 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002488
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002489 /* Success block for __anext__ */
2490 VISIT(c, expr, s->v.AsyncFor.target);
2491 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2492 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2493
2494 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002495
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002496 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002497 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002498 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002499
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002500 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002501 VISIT_SEQ(c, stmt, s->v.For.orelse);
2502
2503 compiler_use_next_block(c, end);
2504
2505 return 1;
2506}
2507
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508static int
2509compiler_while(struct compiler *c, stmt_ty s)
2510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002512 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (constant == 0) {
2515 if (s->v.While.orelse)
2516 VISIT_SEQ(c, stmt, s->v.While.orelse);
2517 return 1;
2518 }
2519 loop = compiler_new_block(c);
2520 end = compiler_new_block(c);
2521 if (constant == -1) {
2522 anchor = compiler_new_block(c);
2523 if (anchor == NULL)
2524 return 0;
2525 }
2526 if (loop == NULL || end == NULL)
2527 return 0;
2528 if (s->v.While.orelse) {
2529 orelse = compiler_new_block(c);
2530 if (orelse == NULL)
2531 return 0;
2532 }
2533 else
2534 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002537 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 return 0;
2539 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002540 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2541 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 }
2543 VISIT_SEQ(c, stmt, s->v.While.body);
2544 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* XXX should the two POP instructions be in a separate block
2547 if there is no else clause ?
2548 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002550 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002552 compiler_pop_fblock(c, WHILE_LOOP, loop);
2553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 if (orelse != NULL) /* what if orelse is just pass? */
2555 VISIT_SEQ(c, stmt, s->v.While.orelse);
2556 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559}
2560
2561static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002562compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002564 int preserve_tos = ((s->v.Return.value != NULL) &&
2565 !is_const(s->v.Return.value));
2566 if (c->u->u_ste->ste_type != FunctionBlock)
2567 return compiler_error(c, "'return' outside function");
2568 if (s->v.Return.value != NULL &&
2569 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2570 {
2571 return compiler_error(
2572 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002574 if (preserve_tos) {
2575 VISIT(c, expr, s->v.Return.value);
2576 }
2577 for (int depth = c->u->u_nfblocks; depth--;) {
2578 struct fblockinfo *info = &c->u->u_fblock[depth];
2579
2580 if (!compiler_unwind_fblock(c, info, preserve_tos))
2581 return 0;
2582 }
2583 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002584 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002585 }
2586 else if (!preserve_tos) {
2587 VISIT(c, expr, s->v.Return.value);
2588 }
2589 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592}
2593
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002594static int
2595compiler_break(struct compiler *c)
2596{
2597 for (int depth = c->u->u_nfblocks; depth--;) {
2598 struct fblockinfo *info = &c->u->u_fblock[depth];
2599
2600 if (!compiler_unwind_fblock(c, info, 0))
2601 return 0;
2602 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2603 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2604 return 1;
2605 }
2606 }
2607 return compiler_error(c, "'break' outside loop");
2608}
2609
2610static int
2611compiler_continue(struct compiler *c)
2612{
2613 for (int depth = c->u->u_nfblocks; depth--;) {
2614 struct fblockinfo *info = &c->u->u_fblock[depth];
2615
2616 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2617 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2618 return 1;
2619 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002620 if (!compiler_unwind_fblock(c, info, 0))
2621 return 0;
2622 }
2623 return compiler_error(c, "'continue' not properly in loop");
2624}
2625
2626
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628
2629 SETUP_FINALLY L
2630 <code for body>
2631 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002632 BEGIN_FINALLY
2633 L:
2634 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 END_FINALLY
2636
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 The special instructions use the block stack. Each block
2638 stack entry contains the instruction that created it (here
2639 SETUP_FINALLY), the level of the value stack at the time the
2640 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 Pushes the current value stack level and the label
2644 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002646 Pops en entry from the block stack.
2647 BEGIN_FINALLY
2648 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002650 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2651 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002654 when a SETUP_FINALLY entry is found, the raised and the caught
2655 exceptions are pushed onto the value stack (and the exception
2656 condition is cleared), and the interpreter jumps to the label
2657 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658*/
2659
2660static int
2661compiler_try_finally(struct compiler *c, stmt_ty s)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 body = compiler_new_block(c);
2666 end = compiler_new_block(c);
2667 if (body == NULL || end == NULL)
2668 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002670 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 ADDOP_JREL(c, SETUP_FINALLY, end);
2672 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002673 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002675 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2676 if (!compiler_try_except(c, s))
2677 return 0;
2678 }
2679 else {
2680 VISIT_SEQ(c, stmt, s->v.Try.body);
2681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002683 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002686 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002688 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002690 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 ADDOP(c, END_FINALLY);
2692 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694}
2695
2696/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002697 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 (The contents of the value stack is shown in [], with the top
2699 at the right; 'tb' is trace-back info, 'val' the exception's
2700 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701
2702 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002703 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 [] <code for S>
2705 [] POP_BLOCK
2706 [] JUMP_FORWARD L0
2707
2708 [tb, val, exc] L1: DUP )
2709 [tb, val, exc, exc] <evaluate E1> )
2710 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2711 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2712 [tb, val, exc] POP
2713 [tb, val] <assign to V1> (or POP if no V1)
2714 [tb] POP
2715 [] <code for S1>
2716 JUMP_FORWARD L0
2717
2718 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 .............................etc.......................
2720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2722
2723 [] L0: <next statement>
2724
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002725 Of course, parts are not generated if Vi or Ei is not present.
2726*/
2727static int
2728compiler_try_except(struct compiler *c, stmt_ty s)
2729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002731 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 body = compiler_new_block(c);
2734 except = compiler_new_block(c);
2735 orelse = compiler_new_block(c);
2736 end = compiler_new_block(c);
2737 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2738 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002739 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002741 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002743 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 ADDOP(c, POP_BLOCK);
2745 compiler_pop_fblock(c, EXCEPT, body);
2746 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002747 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 compiler_use_next_block(c, except);
2749 for (i = 0; i < n; i++) {
2750 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002751 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 if (!handler->v.ExceptHandler.type && i < n-1)
2753 return compiler_error(c, "default 'except:' must be last");
2754 c->u->u_lineno_set = 0;
2755 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002756 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 except = compiler_new_block(c);
2758 if (except == NULL)
2759 return 0;
2760 if (handler->v.ExceptHandler.type) {
2761 ADDOP(c, DUP_TOP);
2762 VISIT(c, expr, handler->v.ExceptHandler.type);
2763 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2764 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2765 }
2766 ADDOP(c, POP_TOP);
2767 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002768 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002769
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002770 cleanup_end = compiler_new_block(c);
2771 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002772 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002773 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002774
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002775 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2776 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002778 /*
2779 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002780 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002781 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002782 try:
2783 # body
2784 finally:
2785 name = None
2786 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002787 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002789 /* second try: */
2790 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2791 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002793 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002795 /* second # body */
2796 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2797 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002798 ADDOP(c, BEGIN_FINALLY);
2799 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002801 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002802 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002804 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002807 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002808 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002809 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002811 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002812 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002813 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 }
2815 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002816 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002818 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002819 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002820 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821
Guido van Rossumb940e112007-01-10 16:19:56 +00002822 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002823 ADDOP(c, POP_TOP);
2824 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002826 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002828 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002829 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 }
2831 ADDOP_JREL(c, JUMP_FORWARD, end);
2832 compiler_use_next_block(c, except);
2833 }
2834 ADDOP(c, END_FINALLY);
2835 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002836 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 compiler_use_next_block(c, end);
2838 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839}
2840
2841static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002842compiler_try(struct compiler *c, stmt_ty s) {
2843 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2844 return compiler_try_finally(c, s);
2845 else
2846 return compiler_try_except(c, s);
2847}
2848
2849
2850static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851compiler_import_as(struct compiler *c, identifier name, identifier asname)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 /* The IMPORT_NAME opcode was already generated. This function
2854 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002857 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002859 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2860 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002861 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002862 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002863 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002865 while (1) {
2866 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002868 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002869 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002870 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002871 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002873 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002874 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002875 if (dot == -1) {
2876 break;
2877 }
2878 ADDOP(c, ROT_TWO);
2879 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002881 if (!compiler_nameop(c, asname, Store)) {
2882 return 0;
2883 }
2884 ADDOP(c, POP_TOP);
2885 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 }
2887 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888}
2889
2890static int
2891compiler_import(struct compiler *c, stmt_ty s)
2892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 /* The Import node stores a module name like a.b.c as a single
2894 string. This is convenient for all cases except
2895 import a.b.c as d
2896 where we need to parse that string to extract the individual
2897 module names.
2898 XXX Perhaps change the representation to make this case simpler?
2899 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002900 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 for (i = 0; i < n; i++) {
2903 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2904 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002906 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2907 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 if (alias->asname) {
2911 r = compiler_import_as(c, alias->name, alias->asname);
2912 if (!r)
2913 return r;
2914 }
2915 else {
2916 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002917 Py_ssize_t dot = PyUnicode_FindChar(
2918 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002919 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002920 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002921 if (tmp == NULL)
2922 return 0;
2923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002925 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 Py_DECREF(tmp);
2927 }
2928 if (!r)
2929 return r;
2930 }
2931 }
2932 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933}
2934
2935static int
2936compiler_from_import(struct compiler *c, stmt_ty s)
2937{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002938 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002939 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 if (!empty_string) {
2943 empty_string = PyUnicode_FromString("");
2944 if (!empty_string)
2945 return 0;
2946 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002948 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002949
2950 names = PyTuple_New(n);
2951 if (!names)
2952 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 /* build up the names */
2955 for (i = 0; i < n; i++) {
2956 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2957 Py_INCREF(alias->name);
2958 PyTuple_SET_ITEM(names, i, alias->name);
2959 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002962 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 Py_DECREF(names);
2964 return compiler_error(c, "from __future__ imports must occur "
2965 "at the beginning of the file");
2966 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002967 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 if (s->v.ImportFrom.module) {
2970 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2971 }
2972 else {
2973 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2974 }
2975 for (i = 0; i < n; i++) {
2976 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2977 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002979 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 assert(n == 1);
2981 ADDOP(c, IMPORT_STAR);
2982 return 1;
2983 }
2984
2985 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2986 store_name = alias->name;
2987 if (alias->asname)
2988 store_name = alias->asname;
2989
2990 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 return 0;
2992 }
2993 }
2994 /* remove imported module */
2995 ADDOP(c, POP_TOP);
2996 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997}
2998
2999static int
3000compiler_assert(struct compiler *c, stmt_ty s)
3001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 static PyObject *assertion_error = NULL;
3003 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02003004 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005
Georg Brandl8334fd92010-12-04 10:26:46 +00003006 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 return 1;
3008 if (assertion_error == NULL) {
3009 assertion_error = PyUnicode_InternFromString("AssertionError");
3010 if (assertion_error == NULL)
3011 return 0;
3012 }
3013 if (s->v.Assert.test->kind == Tuple_kind &&
3014 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02003015 msg = PyUnicode_FromString("assertion is always true, "
3016 "perhaps remove parentheses?");
3017 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02003019 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
3020 c->c_filename, c->u->u_lineno,
3021 NULL, NULL) == -1) {
3022 Py_DECREF(msg);
3023 return 0;
3024 }
3025 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 end = compiler_new_block(c);
3028 if (end == NULL)
3029 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003030 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3031 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3033 if (s->v.Assert.msg) {
3034 VISIT(c, expr, s->v.Assert.msg);
3035 ADDOP_I(c, CALL_FUNCTION, 1);
3036 }
3037 ADDOP_I(c, RAISE_VARARGS, 1);
3038 compiler_use_next_block(c, end);
3039 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040}
3041
3042static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003043compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3044{
3045 if (c->c_interactive && c->c_nestlevel <= 1) {
3046 VISIT(c, expr, value);
3047 ADDOP(c, PRINT_EXPR);
3048 return 1;
3049 }
3050
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003051 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003052 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003053 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003054 }
3055
3056 VISIT(c, expr, value);
3057 ADDOP(c, POP_TOP);
3058 return 1;
3059}
3060
3061static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062compiler_visit_stmt(struct compiler *c, stmt_ty s)
3063{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003064 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* Always assign a lineno to the next instruction for a stmt. */
3067 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003068 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 switch (s->kind) {
3072 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003073 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 case ClassDef_kind:
3075 return compiler_class(c, s);
3076 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003077 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 case Delete_kind:
3079 VISIT_SEQ(c, expr, s->v.Delete.targets)
3080 break;
3081 case Assign_kind:
3082 n = asdl_seq_LEN(s->v.Assign.targets);
3083 VISIT(c, expr, s->v.Assign.value);
3084 for (i = 0; i < n; i++) {
3085 if (i < n - 1)
3086 ADDOP(c, DUP_TOP);
3087 VISIT(c, expr,
3088 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3089 }
3090 break;
3091 case AugAssign_kind:
3092 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003093 case AnnAssign_kind:
3094 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 case For_kind:
3096 return compiler_for(c, s);
3097 case While_kind:
3098 return compiler_while(c, s);
3099 case If_kind:
3100 return compiler_if(c, s);
3101 case Raise_kind:
3102 n = 0;
3103 if (s->v.Raise.exc) {
3104 VISIT(c, expr, s->v.Raise.exc);
3105 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003106 if (s->v.Raise.cause) {
3107 VISIT(c, expr, s->v.Raise.cause);
3108 n++;
3109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003111 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003113 case Try_kind:
3114 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 case Assert_kind:
3116 return compiler_assert(c, s);
3117 case Import_kind:
3118 return compiler_import(c, s);
3119 case ImportFrom_kind:
3120 return compiler_from_import(c, s);
3121 case Global_kind:
3122 case Nonlocal_kind:
3123 break;
3124 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003125 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 case Pass_kind:
3127 break;
3128 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003129 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 case Continue_kind:
3131 return compiler_continue(c);
3132 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003133 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003134 case AsyncFunctionDef_kind:
3135 return compiler_function(c, s, 1);
3136 case AsyncWith_kind:
3137 return compiler_async_with(c, s, 0);
3138 case AsyncFor_kind:
3139 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 }
Yury Selivanov75445082015-05-11 22:57:16 -04003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143}
3144
3145static int
3146unaryop(unaryop_ty op)
3147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 switch (op) {
3149 case Invert:
3150 return UNARY_INVERT;
3151 case Not:
3152 return UNARY_NOT;
3153 case UAdd:
3154 return UNARY_POSITIVE;
3155 case USub:
3156 return UNARY_NEGATIVE;
3157 default:
3158 PyErr_Format(PyExc_SystemError,
3159 "unary op %d should not be possible", op);
3160 return 0;
3161 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162}
3163
3164static int
3165binop(struct compiler *c, operator_ty op)
3166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 switch (op) {
3168 case Add:
3169 return BINARY_ADD;
3170 case Sub:
3171 return BINARY_SUBTRACT;
3172 case Mult:
3173 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003174 case MatMult:
3175 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 case Div:
3177 return BINARY_TRUE_DIVIDE;
3178 case Mod:
3179 return BINARY_MODULO;
3180 case Pow:
3181 return BINARY_POWER;
3182 case LShift:
3183 return BINARY_LSHIFT;
3184 case RShift:
3185 return BINARY_RSHIFT;
3186 case BitOr:
3187 return BINARY_OR;
3188 case BitXor:
3189 return BINARY_XOR;
3190 case BitAnd:
3191 return BINARY_AND;
3192 case FloorDiv:
3193 return BINARY_FLOOR_DIVIDE;
3194 default:
3195 PyErr_Format(PyExc_SystemError,
3196 "binary op %d should not be possible", op);
3197 return 0;
3198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199}
3200
3201static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202inplace_binop(struct compiler *c, operator_ty op)
3203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 switch (op) {
3205 case Add:
3206 return INPLACE_ADD;
3207 case Sub:
3208 return INPLACE_SUBTRACT;
3209 case Mult:
3210 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003211 case MatMult:
3212 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 case Div:
3214 return INPLACE_TRUE_DIVIDE;
3215 case Mod:
3216 return INPLACE_MODULO;
3217 case Pow:
3218 return INPLACE_POWER;
3219 case LShift:
3220 return INPLACE_LSHIFT;
3221 case RShift:
3222 return INPLACE_RSHIFT;
3223 case BitOr:
3224 return INPLACE_OR;
3225 case BitXor:
3226 return INPLACE_XOR;
3227 case BitAnd:
3228 return INPLACE_AND;
3229 case FloorDiv:
3230 return INPLACE_FLOOR_DIVIDE;
3231 default:
3232 PyErr_Format(PyExc_SystemError,
3233 "inplace binary op %d should not be possible", op);
3234 return 0;
3235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236}
3237
3238static int
3239compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3240{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003241 int op, scope;
3242 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 PyObject *dict = c->u->u_names;
3246 PyObject *mangled;
3247 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003249 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3250 !_PyUnicode_EqualToASCIIString(name, "True") &&
3251 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003252
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003253 mangled = _Py_Mangle(c->u->u_private, name);
3254 if (!mangled)
3255 return 0;
3256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 op = 0;
3258 optype = OP_NAME;
3259 scope = PyST_GetScope(c->u->u_ste, mangled);
3260 switch (scope) {
3261 case FREE:
3262 dict = c->u->u_freevars;
3263 optype = OP_DEREF;
3264 break;
3265 case CELL:
3266 dict = c->u->u_cellvars;
3267 optype = OP_DEREF;
3268 break;
3269 case LOCAL:
3270 if (c->u->u_ste->ste_type == FunctionBlock)
3271 optype = OP_FAST;
3272 break;
3273 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003274 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 optype = OP_GLOBAL;
3276 break;
3277 case GLOBAL_EXPLICIT:
3278 optype = OP_GLOBAL;
3279 break;
3280 default:
3281 /* scope can be 0 */
3282 break;
3283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003286 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 switch (optype) {
3289 case OP_DEREF:
3290 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003291 case Load:
3292 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3293 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 case Store: op = STORE_DEREF; break;
3295 case AugLoad:
3296 case AugStore:
3297 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003298 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 case Param:
3300 default:
3301 PyErr_SetString(PyExc_SystemError,
3302 "param invalid for deref variable");
3303 return 0;
3304 }
3305 break;
3306 case OP_FAST:
3307 switch (ctx) {
3308 case Load: op = LOAD_FAST; break;
3309 case Store: op = STORE_FAST; break;
3310 case Del: op = DELETE_FAST; break;
3311 case AugLoad:
3312 case AugStore:
3313 break;
3314 case Param:
3315 default:
3316 PyErr_SetString(PyExc_SystemError,
3317 "param invalid for local variable");
3318 return 0;
3319 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003320 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 return 1;
3322 case OP_GLOBAL:
3323 switch (ctx) {
3324 case Load: op = LOAD_GLOBAL; break;
3325 case Store: op = STORE_GLOBAL; break;
3326 case Del: op = DELETE_GLOBAL; break;
3327 case AugLoad:
3328 case AugStore:
3329 break;
3330 case Param:
3331 default:
3332 PyErr_SetString(PyExc_SystemError,
3333 "param invalid for global variable");
3334 return 0;
3335 }
3336 break;
3337 case OP_NAME:
3338 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003339 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 case Store: op = STORE_NAME; break;
3341 case Del: op = DELETE_NAME; break;
3342 case AugLoad:
3343 case AugStore:
3344 break;
3345 case Param:
3346 default:
3347 PyErr_SetString(PyExc_SystemError,
3348 "param invalid for name variable");
3349 return 0;
3350 }
3351 break;
3352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 assert(op);
3355 arg = compiler_add_o(c, dict, mangled);
3356 Py_DECREF(mangled);
3357 if (arg < 0)
3358 return 0;
3359 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360}
3361
3362static int
3363compiler_boolop(struct compiler *c, expr_ty e)
3364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003366 int jumpi;
3367 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 assert(e->kind == BoolOp_kind);
3371 if (e->v.BoolOp.op == And)
3372 jumpi = JUMP_IF_FALSE_OR_POP;
3373 else
3374 jumpi = JUMP_IF_TRUE_OR_POP;
3375 end = compiler_new_block(c);
3376 if (end == NULL)
3377 return 0;
3378 s = e->v.BoolOp.values;
3379 n = asdl_seq_LEN(s) - 1;
3380 assert(n >= 0);
3381 for (i = 0; i < n; ++i) {
3382 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3383 ADDOP_JABS(c, jumpi, end);
3384 }
3385 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3386 compiler_use_next_block(c, end);
3387 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003388}
3389
3390static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003391starunpack_helper(struct compiler *c, asdl_seq *elts,
3392 int single_op, int inner_op, int outer_op)
3393{
3394 Py_ssize_t n = asdl_seq_LEN(elts);
3395 Py_ssize_t i, nsubitems = 0, nseen = 0;
3396 for (i = 0; i < n; i++) {
3397 expr_ty elt = asdl_seq_GET(elts, i);
3398 if (elt->kind == Starred_kind) {
3399 if (nseen) {
3400 ADDOP_I(c, inner_op, nseen);
3401 nseen = 0;
3402 nsubitems++;
3403 }
3404 VISIT(c, expr, elt->v.Starred.value);
3405 nsubitems++;
3406 }
3407 else {
3408 VISIT(c, expr, elt);
3409 nseen++;
3410 }
3411 }
3412 if (nsubitems) {
3413 if (nseen) {
3414 ADDOP_I(c, inner_op, nseen);
3415 nsubitems++;
3416 }
3417 ADDOP_I(c, outer_op, nsubitems);
3418 }
3419 else
3420 ADDOP_I(c, single_op, nseen);
3421 return 1;
3422}
3423
3424static int
3425assignment_helper(struct compiler *c, asdl_seq *elts)
3426{
3427 Py_ssize_t n = asdl_seq_LEN(elts);
3428 Py_ssize_t i;
3429 int seen_star = 0;
3430 for (i = 0; i < n; i++) {
3431 expr_ty elt = asdl_seq_GET(elts, i);
3432 if (elt->kind == Starred_kind && !seen_star) {
3433 if ((i >= (1 << 8)) ||
3434 (n-i-1 >= (INT_MAX >> 8)))
3435 return compiler_error(c,
3436 "too many expressions in "
3437 "star-unpacking assignment");
3438 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3439 seen_star = 1;
3440 asdl_seq_SET(elts, i, elt->v.Starred.value);
3441 }
3442 else if (elt->kind == Starred_kind) {
3443 return compiler_error(c,
3444 "two starred expressions in assignment");
3445 }
3446 }
3447 if (!seen_star) {
3448 ADDOP_I(c, UNPACK_SEQUENCE, n);
3449 }
3450 VISIT_SEQ(c, expr, elts);
3451 return 1;
3452}
3453
3454static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455compiler_list(struct compiler *c, expr_ty e)
3456{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003457 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003459 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003461 else if (e->v.List.ctx == Load) {
3462 return starunpack_helper(c, elts,
3463 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003465 else
3466 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003468}
3469
3470static int
3471compiler_tuple(struct compiler *c, expr_ty e)
3472{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003473 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003475 return assignment_helper(c, elts);
3476 }
3477 else if (e->v.Tuple.ctx == Load) {
3478 return starunpack_helper(c, elts,
3479 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3480 }
3481 else
3482 VISIT_SEQ(c, expr, elts);
3483 return 1;
3484}
3485
3486static int
3487compiler_set(struct compiler *c, expr_ty e)
3488{
3489 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3490 BUILD_SET, BUILD_SET_UNPACK);
3491}
3492
3493static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003494are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3495{
3496 Py_ssize_t i;
3497 for (i = begin; i < end; i++) {
3498 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3499 if (key == NULL || !is_const(key))
3500 return 0;
3501 }
3502 return 1;
3503}
3504
3505static int
3506compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3507{
3508 Py_ssize_t i, n = end - begin;
3509 PyObject *keys, *key;
3510 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3511 for (i = begin; i < end; i++) {
3512 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3513 }
3514 keys = PyTuple_New(n);
3515 if (keys == NULL) {
3516 return 0;
3517 }
3518 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003519 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003520 Py_INCREF(key);
3521 PyTuple_SET_ITEM(keys, i - begin, key);
3522 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003523 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003524 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3525 }
3526 else {
3527 for (i = begin; i < end; i++) {
3528 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3529 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3530 }
3531 ADDOP_I(c, BUILD_MAP, n);
3532 }
3533 return 1;
3534}
3535
3536static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537compiler_dict(struct compiler *c, expr_ty e)
3538{
Victor Stinner976bb402016-03-23 11:36:19 +01003539 Py_ssize_t i, n, elements;
3540 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003541 int is_unpacking = 0;
3542 n = asdl_seq_LEN(e->v.Dict.values);
3543 containers = 0;
3544 elements = 0;
3545 for (i = 0; i < n; i++) {
3546 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3547 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003548 if (!compiler_subdict(c, e, i - elements, i))
3549 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003550 containers++;
3551 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003553 if (is_unpacking) {
3554 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3555 containers++;
3556 }
3557 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003558 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 }
3560 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003561 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003562 if (!compiler_subdict(c, e, n - elements, n))
3563 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003564 containers++;
3565 }
3566 /* If there is more than one dict, they need to be merged into a new
3567 * dict. If there is one dict and it's an unpacking, then it needs
3568 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003569 if (containers > 1 || is_unpacking) {
3570 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 }
3572 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573}
3574
3575static int
3576compiler_compare(struct compiler *c, expr_ty e)
3577{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003578 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003581 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3582 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3583 if (n == 0) {
3584 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3585 ADDOP_I(c, COMPARE_OP,
3586 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3587 }
3588 else {
3589 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 if (cleanup == NULL)
3591 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003592 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 VISIT(c, expr,
3594 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003595 ADDOP(c, DUP_TOP);
3596 ADDOP(c, ROT_THREE);
3597 ADDOP_I(c, COMPARE_OP,
3598 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3599 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3600 NEXT_BLOCK(c);
3601 }
3602 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3603 ADDOP_I(c, COMPARE_OP,
3604 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 basicblock *end = compiler_new_block(c);
3606 if (end == NULL)
3607 return 0;
3608 ADDOP_JREL(c, JUMP_FORWARD, end);
3609 compiler_use_next_block(c, cleanup);
3610 ADDOP(c, ROT_TWO);
3611 ADDOP(c, POP_TOP);
3612 compiler_use_next_block(c, end);
3613 }
3614 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615}
3616
3617static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003618maybe_optimize_method_call(struct compiler *c, expr_ty e)
3619{
3620 Py_ssize_t argsl, i;
3621 expr_ty meth = e->v.Call.func;
3622 asdl_seq *args = e->v.Call.args;
3623
3624 /* Check that the call node is an attribute access, and that
3625 the call doesn't have keyword parameters. */
3626 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3627 asdl_seq_LEN(e->v.Call.keywords))
3628 return -1;
3629
3630 /* Check that there are no *varargs types of arguments. */
3631 argsl = asdl_seq_LEN(args);
3632 for (i = 0; i < argsl; i++) {
3633 expr_ty elt = asdl_seq_GET(args, i);
3634 if (elt->kind == Starred_kind) {
3635 return -1;
3636 }
3637 }
3638
3639 /* Alright, we can optimize the code. */
3640 VISIT(c, expr, meth->v.Attribute.value);
3641 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3642 VISIT_SEQ(c, expr, e->v.Call.args);
3643 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3644 return 1;
3645}
3646
3647static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648compiler_call(struct compiler *c, expr_ty e)
3649{
Yury Selivanovf2392132016-12-13 19:03:51 -05003650 if (maybe_optimize_method_call(c, e) > 0)
3651 return 1;
3652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 VISIT(c, expr, e->v.Call.func);
3654 return compiler_call_helper(c, 0,
3655 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003656 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003657}
3658
Eric V. Smith235a6f02015-09-19 14:51:32 -04003659static int
3660compiler_joined_str(struct compiler *c, expr_ty e)
3661{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003662 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003663 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3664 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003665 return 1;
3666}
3667
Eric V. Smitha78c7952015-11-03 12:45:05 -05003668/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003669static int
3670compiler_formatted_value(struct compiler *c, expr_ty e)
3671{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003672 /* Our oparg encodes 2 pieces of information: the conversion
3673 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003674
Eric V. Smitha78c7952015-11-03 12:45:05 -05003675 Convert the conversion char to 2 bits:
3676 None: 000 0x0 FVC_NONE
3677 !s : 001 0x1 FVC_STR
3678 !r : 010 0x2 FVC_REPR
3679 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003680
Eric V. Smitha78c7952015-11-03 12:45:05 -05003681 next bit is whether or not we have a format spec:
3682 yes : 100 0x4
3683 no : 000 0x0
3684 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003685
Eric V. Smitha78c7952015-11-03 12:45:05 -05003686 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003687
Eric V. Smitha78c7952015-11-03 12:45:05 -05003688 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003689 VISIT(c, expr, e->v.FormattedValue.value);
3690
Eric V. Smitha78c7952015-11-03 12:45:05 -05003691 switch (e->v.FormattedValue.conversion) {
3692 case 's': oparg = FVC_STR; break;
3693 case 'r': oparg = FVC_REPR; break;
3694 case 'a': oparg = FVC_ASCII; break;
3695 case -1: oparg = FVC_NONE; break;
3696 default:
3697 PyErr_SetString(PyExc_SystemError,
3698 "Unrecognized conversion character");
3699 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003700 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003701 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003702 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003703 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003704 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003705 }
3706
Eric V. Smitha78c7952015-11-03 12:45:05 -05003707 /* And push our opcode and oparg */
3708 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003709 return 1;
3710}
3711
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003712static int
3713compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3714{
3715 Py_ssize_t i, n = end - begin;
3716 keyword_ty kw;
3717 PyObject *keys, *key;
3718 assert(n > 0);
3719 if (n > 1) {
3720 for (i = begin; i < end; i++) {
3721 kw = asdl_seq_GET(keywords, i);
3722 VISIT(c, expr, kw->value);
3723 }
3724 keys = PyTuple_New(n);
3725 if (keys == NULL) {
3726 return 0;
3727 }
3728 for (i = begin; i < end; i++) {
3729 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3730 Py_INCREF(key);
3731 PyTuple_SET_ITEM(keys, i - begin, key);
3732 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003733 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003734 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3735 }
3736 else {
3737 /* a for loop only executes once */
3738 for (i = begin; i < end; i++) {
3739 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003740 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003741 VISIT(c, expr, kw->value);
3742 }
3743 ADDOP_I(c, BUILD_MAP, n);
3744 }
3745 return 1;
3746}
3747
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003748/* shared code between compiler_call and compiler_class */
3749static int
3750compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003751 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003752 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003754{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003755 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003756 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003757
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003758 /* the number of tuples and dictionaries on the stack */
3759 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3760
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003761 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003762 nkwelts = asdl_seq_LEN(keywords);
3763
3764 for (i = 0; i < nkwelts; i++) {
3765 keyword_ty kw = asdl_seq_GET(keywords, i);
3766 if (kw->arg == NULL) {
3767 mustdictunpack = 1;
3768 break;
3769 }
3770 }
3771
3772 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 for (i = 0; i < nelts; i++) {
3774 expr_ty elt = asdl_seq_GET(args, i);
3775 if (elt->kind == Starred_kind) {
3776 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003777 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003778 if (nseen) {
3779 ADDOP_I(c, BUILD_TUPLE, nseen);
3780 nseen = 0;
3781 nsubargs++;
3782 }
3783 VISIT(c, expr, elt->v.Starred.value);
3784 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 }
3786 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003787 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003788 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791
3792 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003793 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003794 if (nseen) {
3795 /* Pack up any trailing positional arguments. */
3796 ADDOP_I(c, BUILD_TUPLE, nseen);
3797 nsubargs++;
3798 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003799 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003800 /* If we ended up with more than one stararg, we need
3801 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003802 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003803 }
3804 else if (nsubargs == 0) {
3805 ADDOP_I(c, BUILD_TUPLE, 0);
3806 }
3807 nseen = 0; /* the number of keyword arguments on the stack following */
3808 for (i = 0; i < nkwelts; i++) {
3809 keyword_ty kw = asdl_seq_GET(keywords, i);
3810 if (kw->arg == NULL) {
3811 /* A keyword argument unpacking. */
3812 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003813 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3814 return 0;
3815 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003816 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003817 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003818 VISIT(c, expr, kw->value);
3819 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003820 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003821 else {
3822 nseen++;
3823 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003824 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003825 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003826 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003827 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003828 return 0;
3829 nsubkwargs++;
3830 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003831 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003832 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003833 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003834 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003835 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3836 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003838 else if (nkwelts) {
3839 PyObject *names;
3840 VISIT_SEQ(c, keyword, keywords);
3841 names = PyTuple_New(nkwelts);
3842 if (names == NULL) {
3843 return 0;
3844 }
3845 for (i = 0; i < nkwelts; i++) {
3846 keyword_ty kw = asdl_seq_GET(keywords, i);
3847 Py_INCREF(kw->arg);
3848 PyTuple_SET_ITEM(names, i, kw->arg);
3849 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003850 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003851 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3852 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003854 else {
3855 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3856 return 1;
3857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003858}
3859
Nick Coghlan650f0d02007-04-15 12:05:43 +00003860
3861/* List and set comprehensions and generator expressions work by creating a
3862 nested function to perform the actual iteration. This means that the
3863 iteration variables don't leak into the current scope.
3864 The defined function is called immediately following its definition, with the
3865 result of that call being the result of the expression.
3866 The LC/SC version returns the populated container, while the GE version is
3867 flagged in symtable.c as a generator, so it returns the generator object
3868 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003869
3870 Possible cleanups:
3871 - iterate over the generator sequence instead of using recursion
3872*/
3873
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003874
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876compiler_comprehension_generator(struct compiler *c,
3877 asdl_seq *generators, int gen_index,
3878 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003879{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003880 comprehension_ty gen;
3881 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3882 if (gen->is_async) {
3883 return compiler_async_comprehension_generator(
3884 c, generators, gen_index, elt, val, type);
3885 } else {
3886 return compiler_sync_comprehension_generator(
3887 c, generators, gen_index, elt, val, type);
3888 }
3889}
3890
3891static int
3892compiler_sync_comprehension_generator(struct compiler *c,
3893 asdl_seq *generators, int gen_index,
3894 expr_ty elt, expr_ty val, int type)
3895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 /* generate code for the iterator, then each of the ifs,
3897 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 comprehension_ty gen;
3900 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003901 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 start = compiler_new_block(c);
3904 skip = compiler_new_block(c);
3905 if_cleanup = compiler_new_block(c);
3906 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3909 anchor == NULL)
3910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 if (gen_index == 0) {
3915 /* Receive outermost iter as an implicit argument */
3916 c->u->u_argcount = 1;
3917 ADDOP_I(c, LOAD_FAST, 0);
3918 }
3919 else {
3920 /* Sub-iter - calculate on the fly */
3921 VISIT(c, expr, gen->iter);
3922 ADDOP(c, GET_ITER);
3923 }
3924 compiler_use_next_block(c, start);
3925 ADDOP_JREL(c, FOR_ITER, anchor);
3926 NEXT_BLOCK(c);
3927 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 /* XXX this needs to be cleaned up...a lot! */
3930 n = asdl_seq_LEN(gen->ifs);
3931 for (i = 0; i < n; i++) {
3932 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003933 if (!compiler_jump_if(c, e, if_cleanup, 0))
3934 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 NEXT_BLOCK(c);
3936 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 if (++gen_index < asdl_seq_LEN(generators))
3939 if (!compiler_comprehension_generator(c,
3940 generators, gen_index,
3941 elt, val, type))
3942 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 /* only append after the last for generator */
3945 if (gen_index >= asdl_seq_LEN(generators)) {
3946 /* comprehension specific code */
3947 switch (type) {
3948 case COMP_GENEXP:
3949 VISIT(c, expr, elt);
3950 ADDOP(c, YIELD_VALUE);
3951 ADDOP(c, POP_TOP);
3952 break;
3953 case COMP_LISTCOMP:
3954 VISIT(c, expr, elt);
3955 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3956 break;
3957 case COMP_SETCOMP:
3958 VISIT(c, expr, elt);
3959 ADDOP_I(c, SET_ADD, gen_index + 1);
3960 break;
3961 case COMP_DICTCOMP:
3962 /* With 'd[k] = v', v is evaluated before k, so we do
3963 the same. */
3964 VISIT(c, expr, val);
3965 VISIT(c, expr, elt);
3966 ADDOP_I(c, MAP_ADD, gen_index + 1);
3967 break;
3968 default:
3969 return 0;
3970 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 compiler_use_next_block(c, skip);
3973 }
3974 compiler_use_next_block(c, if_cleanup);
3975 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3976 compiler_use_next_block(c, anchor);
3977
3978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003979}
3980
3981static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003982compiler_async_comprehension_generator(struct compiler *c,
3983 asdl_seq *generators, int gen_index,
3984 expr_ty elt, expr_ty val, int type)
3985{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003986 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003987 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003988 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003989 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003990 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003991 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003992
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003993 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003994 return 0;
3995 }
3996
3997 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3998
3999 if (gen_index == 0) {
4000 /* Receive outermost iter as an implicit argument */
4001 c->u->u_argcount = 1;
4002 ADDOP_I(c, LOAD_FAST, 0);
4003 }
4004 else {
4005 /* Sub-iter - calculate on the fly */
4006 VISIT(c, expr, gen->iter);
4007 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004008 }
4009
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004010 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004011
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004012 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004013 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004014 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004015 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004016 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004017 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004018
4019 n = asdl_seq_LEN(gen->ifs);
4020 for (i = 0; i < n; i++) {
4021 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004022 if (!compiler_jump_if(c, e, if_cleanup, 0))
4023 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004024 NEXT_BLOCK(c);
4025 }
4026
4027 if (++gen_index < asdl_seq_LEN(generators))
4028 if (!compiler_comprehension_generator(c,
4029 generators, gen_index,
4030 elt, val, type))
4031 return 0;
4032
4033 /* only append after the last for generator */
4034 if (gen_index >= asdl_seq_LEN(generators)) {
4035 /* comprehension specific code */
4036 switch (type) {
4037 case COMP_GENEXP:
4038 VISIT(c, expr, elt);
4039 ADDOP(c, YIELD_VALUE);
4040 ADDOP(c, POP_TOP);
4041 break;
4042 case COMP_LISTCOMP:
4043 VISIT(c, expr, elt);
4044 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4045 break;
4046 case COMP_SETCOMP:
4047 VISIT(c, expr, elt);
4048 ADDOP_I(c, SET_ADD, gen_index + 1);
4049 break;
4050 case COMP_DICTCOMP:
4051 /* With 'd[k] = v', v is evaluated before k, so we do
4052 the same. */
4053 VISIT(c, expr, val);
4054 VISIT(c, expr, elt);
4055 ADDOP_I(c, MAP_ADD, gen_index + 1);
4056 break;
4057 default:
4058 return 0;
4059 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004060 }
4061 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004062 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4063
4064 compiler_use_next_block(c, except);
4065 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004066
4067 return 1;
4068}
4069
4070static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004071compiler_comprehension(struct compiler *c, expr_ty e, int type,
4072 identifier name, asdl_seq *generators, expr_ty elt,
4073 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004076 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004077 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004078 int is_async_function = c->u->u_ste->ste_coroutine;
4079 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004080
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004081 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004082
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004083 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4084 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004085 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004087 }
4088
4089 is_async_generator = c->u->u_ste->ste_coroutine;
4090
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004091 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004092 compiler_error(c, "asynchronous comprehension outside of "
4093 "an asynchronous function");
4094 goto error_in_scope;
4095 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 if (type != COMP_GENEXP) {
4098 int op;
4099 switch (type) {
4100 case COMP_LISTCOMP:
4101 op = BUILD_LIST;
4102 break;
4103 case COMP_SETCOMP:
4104 op = BUILD_SET;
4105 break;
4106 case COMP_DICTCOMP:
4107 op = BUILD_MAP;
4108 break;
4109 default:
4110 PyErr_Format(PyExc_SystemError,
4111 "unknown comprehension type %d", type);
4112 goto error_in_scope;
4113 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 ADDOP_I(c, op, 0);
4116 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 if (!compiler_comprehension_generator(c, generators, 0, elt,
4119 val, type))
4120 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 if (type != COMP_GENEXP) {
4123 ADDOP(c, RETURN_VALUE);
4124 }
4125
4126 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004127 qualname = c->u->u_qualname;
4128 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004130 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 goto error;
4132
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004133 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004135 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 Py_DECREF(co);
4137
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004138 VISIT(c, expr, outermost->iter);
4139
4140 if (outermost->is_async) {
4141 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004142 } else {
4143 ADDOP(c, GET_ITER);
4144 }
4145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004147
4148 if (is_async_generator && type != COMP_GENEXP) {
4149 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004150 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004151 ADDOP(c, YIELD_FROM);
4152 }
4153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004155error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004157error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004158 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 Py_XDECREF(co);
4160 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004161}
4162
4163static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004164compiler_genexp(struct compiler *c, expr_ty e)
4165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 static identifier name;
4167 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004168 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 if (!name)
4170 return 0;
4171 }
4172 assert(e->kind == GeneratorExp_kind);
4173 return compiler_comprehension(c, e, COMP_GENEXP, name,
4174 e->v.GeneratorExp.generators,
4175 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176}
4177
4178static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004179compiler_listcomp(struct compiler *c, expr_ty e)
4180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 static identifier name;
4182 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004183 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 if (!name)
4185 return 0;
4186 }
4187 assert(e->kind == ListComp_kind);
4188 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4189 e->v.ListComp.generators,
4190 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004191}
4192
4193static int
4194compiler_setcomp(struct compiler *c, expr_ty e)
4195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 static identifier name;
4197 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004198 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 if (!name)
4200 return 0;
4201 }
4202 assert(e->kind == SetComp_kind);
4203 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4204 e->v.SetComp.generators,
4205 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004206}
4207
4208
4209static int
4210compiler_dictcomp(struct compiler *c, expr_ty e)
4211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 static identifier name;
4213 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004214 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 if (!name)
4216 return 0;
4217 }
4218 assert(e->kind == DictComp_kind);
4219 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4220 e->v.DictComp.generators,
4221 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004222}
4223
4224
4225static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226compiler_visit_keyword(struct compiler *c, keyword_ty k)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 VISIT(c, expr, k->value);
4229 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230}
4231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233 whether they are true or false.
4234
4235 Return values: 1 for true, 0 for false, -1 for non-constant.
4236 */
4237
4238static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004239expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004241 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004242 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004243 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004244 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245}
4246
Yury Selivanov75445082015-05-11 22:57:16 -04004247
4248/*
4249 Implements the async with statement.
4250
4251 The semantics outlined in that PEP are as follows:
4252
4253 async with EXPR as VAR:
4254 BLOCK
4255
4256 It is implemented roughly as:
4257
4258 context = EXPR
4259 exit = context.__aexit__ # not calling it
4260 value = await context.__aenter__()
4261 try:
4262 VAR = value # if VAR present in the syntax
4263 BLOCK
4264 finally:
4265 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004266 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004267 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004268 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004269 if not (await exit(*exc)):
4270 raise
4271 */
4272static int
4273compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4274{
4275 basicblock *block, *finally;
4276 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4277
4278 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004279 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4280 return compiler_error(c, "'async with' outside async function");
4281 }
Yury Selivanov75445082015-05-11 22:57:16 -04004282
4283 block = compiler_new_block(c);
4284 finally = compiler_new_block(c);
4285 if (!block || !finally)
4286 return 0;
4287
4288 /* Evaluate EXPR */
4289 VISIT(c, expr, item->context_expr);
4290
4291 ADDOP(c, BEFORE_ASYNC_WITH);
4292 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004293 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004294 ADDOP(c, YIELD_FROM);
4295
4296 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4297
4298 /* SETUP_ASYNC_WITH pushes a finally block. */
4299 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004300 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004301 return 0;
4302 }
4303
4304 if (item->optional_vars) {
4305 VISIT(c, expr, item->optional_vars);
4306 }
4307 else {
4308 /* Discard result from context.__aenter__() */
4309 ADDOP(c, POP_TOP);
4310 }
4311
4312 pos++;
4313 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4314 /* BLOCK code */
4315 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4316 else if (!compiler_async_with(c, s, pos))
4317 return 0;
4318
4319 /* End of try block; start the finally block */
4320 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004321 ADDOP(c, BEGIN_FINALLY);
4322 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004323
Yury Selivanov75445082015-05-11 22:57:16 -04004324 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004325 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004326 return 0;
4327
4328 /* Finally block starts; context.__exit__ is on the stack under
4329 the exception or return information. Just issue our magic
4330 opcode. */
4331 ADDOP(c, WITH_CLEANUP_START);
4332
4333 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004334 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004335 ADDOP(c, YIELD_FROM);
4336
4337 ADDOP(c, WITH_CLEANUP_FINISH);
4338
4339 /* Finally block ends. */
4340 ADDOP(c, END_FINALLY);
4341 compiler_pop_fblock(c, FINALLY_END, finally);
4342 return 1;
4343}
4344
4345
Guido van Rossumc2e20742006-02-27 22:32:47 +00004346/*
4347 Implements the with statement from PEP 343.
4348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004350
4351 with EXPR as VAR:
4352 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353
Guido van Rossumc2e20742006-02-27 22:32:47 +00004354 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355
Thomas Wouters477c8d52006-05-27 19:21:47 +00004356 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004357 exit = context.__exit__ # not calling it
4358 value = context.__enter__()
4359 try:
4360 VAR = value # if VAR present in the syntax
4361 BLOCK
4362 finally:
4363 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004364 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004365 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004366 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004367 exit(*exc)
4368 */
4369static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004370compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004371{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004372 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004373 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004374
4375 assert(s->kind == With_kind);
4376
Guido van Rossumc2e20742006-02-27 22:32:47 +00004377 block = compiler_new_block(c);
4378 finally = compiler_new_block(c);
4379 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004380 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004381
Thomas Wouters477c8d52006-05-27 19:21:47 +00004382 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004383 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004384 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004385
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004386 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004387 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004388 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004389 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004390 }
4391
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004392 if (item->optional_vars) {
4393 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004394 }
4395 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004397 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004398 }
4399
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004400 pos++;
4401 if (pos == asdl_seq_LEN(s->v.With.items))
4402 /* BLOCK code */
4403 VISIT_SEQ(c, stmt, s->v.With.body)
4404 else if (!compiler_with(c, s, pos))
4405 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004406
4407 /* End of try block; start the finally block */
4408 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004409 ADDOP(c, BEGIN_FINALLY);
4410 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004411
Guido van Rossumc2e20742006-02-27 22:32:47 +00004412 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004413 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004414 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004415
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004416 /* Finally block starts; context.__exit__ is on the stack under
4417 the exception or return information. Just issue our magic
4418 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004419 ADDOP(c, WITH_CLEANUP_START);
4420 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004421
4422 /* Finally block ends. */
4423 ADDOP(c, END_FINALLY);
4424 compiler_pop_fblock(c, FINALLY_END, finally);
4425 return 1;
4426}
4427
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004428static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004429compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 switch (e->kind) {
4432 case BoolOp_kind:
4433 return compiler_boolop(c, e);
4434 case BinOp_kind:
4435 VISIT(c, expr, e->v.BinOp.left);
4436 VISIT(c, expr, e->v.BinOp.right);
4437 ADDOP(c, binop(c, e->v.BinOp.op));
4438 break;
4439 case UnaryOp_kind:
4440 VISIT(c, expr, e->v.UnaryOp.operand);
4441 ADDOP(c, unaryop(e->v.UnaryOp.op));
4442 break;
4443 case Lambda_kind:
4444 return compiler_lambda(c, e);
4445 case IfExp_kind:
4446 return compiler_ifexp(c, e);
4447 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004448 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004450 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 case GeneratorExp_kind:
4452 return compiler_genexp(c, e);
4453 case ListComp_kind:
4454 return compiler_listcomp(c, e);
4455 case SetComp_kind:
4456 return compiler_setcomp(c, e);
4457 case DictComp_kind:
4458 return compiler_dictcomp(c, e);
4459 case Yield_kind:
4460 if (c->u->u_ste->ste_type != FunctionBlock)
4461 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004462 if (e->v.Yield.value) {
4463 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 }
4465 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004466 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004468 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004470 case YieldFrom_kind:
4471 if (c->u->u_ste->ste_type != FunctionBlock)
4472 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004473
4474 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4475 return compiler_error(c, "'yield from' inside async function");
4476
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004477 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004478 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004479 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004480 ADDOP(c, YIELD_FROM);
4481 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004482 case Await_kind:
4483 if (c->u->u_ste->ste_type != FunctionBlock)
4484 return compiler_error(c, "'await' outside function");
4485
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4487 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004488 return compiler_error(c, "'await' outside async function");
4489
4490 VISIT(c, expr, e->v.Await.value);
4491 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004492 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004493 ADDOP(c, YIELD_FROM);
4494 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 case Compare_kind:
4496 return compiler_compare(c, e);
4497 case Call_kind:
4498 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004499 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004500 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004501 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 case Num_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004503 ADDOP_LOAD_CONST(c, e->v.Num.n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 break;
4505 case Str_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004506 ADDOP_LOAD_CONST(c, e->v.Str.s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004508 case JoinedStr_kind:
4509 return compiler_joined_str(c, e);
4510 case FormattedValue_kind:
4511 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 case Bytes_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004513 ADDOP_LOAD_CONST(c, e->v.Bytes.s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 break;
4515 case Ellipsis_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004516 ADDOP_LOAD_CONST(c, Py_Ellipsis);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004518 case NameConstant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004519 ADDOP_LOAD_CONST(c, e->v.NameConstant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004520 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 /* The following exprs can be assignment targets. */
4522 case Attribute_kind:
4523 if (e->v.Attribute.ctx != AugStore)
4524 VISIT(c, expr, e->v.Attribute.value);
4525 switch (e->v.Attribute.ctx) {
4526 case AugLoad:
4527 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004528 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 case Load:
4530 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4531 break;
4532 case AugStore:
4533 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004534 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 case Store:
4536 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4537 break;
4538 case Del:
4539 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4540 break;
4541 case Param:
4542 default:
4543 PyErr_SetString(PyExc_SystemError,
4544 "param invalid in attribute expression");
4545 return 0;
4546 }
4547 break;
4548 case Subscript_kind:
4549 switch (e->v.Subscript.ctx) {
4550 case AugLoad:
4551 VISIT(c, expr, e->v.Subscript.value);
4552 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4553 break;
4554 case Load:
4555 VISIT(c, expr, e->v.Subscript.value);
4556 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4557 break;
4558 case AugStore:
4559 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4560 break;
4561 case Store:
4562 VISIT(c, expr, e->v.Subscript.value);
4563 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4564 break;
4565 case Del:
4566 VISIT(c, expr, e->v.Subscript.value);
4567 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4568 break;
4569 case Param:
4570 default:
4571 PyErr_SetString(PyExc_SystemError,
4572 "param invalid in subscript expression");
4573 return 0;
4574 }
4575 break;
4576 case Starred_kind:
4577 switch (e->v.Starred.ctx) {
4578 case Store:
4579 /* In all legitimate cases, the Starred node was already replaced
4580 * by compiler_list/compiler_tuple. XXX: is that okay? */
4581 return compiler_error(c,
4582 "starred assignment target must be in a list or tuple");
4583 default:
4584 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004585 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 }
4587 break;
4588 case Name_kind:
4589 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4590 /* child nodes of List and Tuple will have expr_context set */
4591 case List_kind:
4592 return compiler_list(c, e);
4593 case Tuple_kind:
4594 return compiler_tuple(c, e);
4595 }
4596 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004597}
4598
4599static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004600compiler_visit_expr(struct compiler *c, expr_ty e)
4601{
4602 /* If expr e has a different line number than the last expr/stmt,
4603 set a new line number for the next instruction.
4604 */
4605 int old_lineno = c->u->u_lineno;
4606 int old_col_offset = c->u->u_col_offset;
4607 if (e->lineno != c->u->u_lineno) {
4608 c->u->u_lineno = e->lineno;
4609 c->u->u_lineno_set = 0;
4610 }
4611 /* Updating the column offset is always harmless. */
4612 c->u->u_col_offset = e->col_offset;
4613
4614 int res = compiler_visit_expr1(c, e);
4615
4616 if (old_lineno != c->u->u_lineno) {
4617 c->u->u_lineno = old_lineno;
4618 c->u->u_lineno_set = 0;
4619 }
4620 c->u->u_col_offset = old_col_offset;
4621 return res;
4622}
4623
4624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004625compiler_augassign(struct compiler *c, stmt_ty s)
4626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 expr_ty e = s->v.AugAssign.target;
4628 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 switch (e->kind) {
4633 case Attribute_kind:
4634 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4635 AugLoad, e->lineno, e->col_offset, c->c_arena);
4636 if (auge == NULL)
4637 return 0;
4638 VISIT(c, expr, auge);
4639 VISIT(c, expr, s->v.AugAssign.value);
4640 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4641 auge->v.Attribute.ctx = AugStore;
4642 VISIT(c, expr, auge);
4643 break;
4644 case Subscript_kind:
4645 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4646 AugLoad, e->lineno, e->col_offset, c->c_arena);
4647 if (auge == NULL)
4648 return 0;
4649 VISIT(c, expr, auge);
4650 VISIT(c, expr, s->v.AugAssign.value);
4651 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4652 auge->v.Subscript.ctx = AugStore;
4653 VISIT(c, expr, auge);
4654 break;
4655 case Name_kind:
4656 if (!compiler_nameop(c, e->v.Name.id, Load))
4657 return 0;
4658 VISIT(c, expr, s->v.AugAssign.value);
4659 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4660 return compiler_nameop(c, e->v.Name.id, Store);
4661 default:
4662 PyErr_Format(PyExc_SystemError,
4663 "invalid node type (%d) for augmented assignment",
4664 e->kind);
4665 return 0;
4666 }
4667 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004668}
4669
4670static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004671check_ann_expr(struct compiler *c, expr_ty e)
4672{
4673 VISIT(c, expr, e);
4674 ADDOP(c, POP_TOP);
4675 return 1;
4676}
4677
4678static int
4679check_annotation(struct compiler *c, stmt_ty s)
4680{
4681 /* Annotations are only evaluated in a module or class. */
4682 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4683 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4684 return check_ann_expr(c, s->v.AnnAssign.annotation);
4685 }
4686 return 1;
4687}
4688
4689static int
4690check_ann_slice(struct compiler *c, slice_ty sl)
4691{
4692 switch(sl->kind) {
4693 case Index_kind:
4694 return check_ann_expr(c, sl->v.Index.value);
4695 case Slice_kind:
4696 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4697 return 0;
4698 }
4699 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4700 return 0;
4701 }
4702 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4703 return 0;
4704 }
4705 break;
4706 default:
4707 PyErr_SetString(PyExc_SystemError,
4708 "unexpected slice kind");
4709 return 0;
4710 }
4711 return 1;
4712}
4713
4714static int
4715check_ann_subscr(struct compiler *c, slice_ty sl)
4716{
4717 /* We check that everything in a subscript is defined at runtime. */
4718 Py_ssize_t i, n;
4719
4720 switch (sl->kind) {
4721 case Index_kind:
4722 case Slice_kind:
4723 if (!check_ann_slice(c, sl)) {
4724 return 0;
4725 }
4726 break;
4727 case ExtSlice_kind:
4728 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4729 for (i = 0; i < n; i++) {
4730 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4731 switch (subsl->kind) {
4732 case Index_kind:
4733 case Slice_kind:
4734 if (!check_ann_slice(c, subsl)) {
4735 return 0;
4736 }
4737 break;
4738 case ExtSlice_kind:
4739 default:
4740 PyErr_SetString(PyExc_SystemError,
4741 "extended slice invalid in nested slice");
4742 return 0;
4743 }
4744 }
4745 break;
4746 default:
4747 PyErr_Format(PyExc_SystemError,
4748 "invalid subscript kind %d", sl->kind);
4749 return 0;
4750 }
4751 return 1;
4752}
4753
4754static int
4755compiler_annassign(struct compiler *c, stmt_ty s)
4756{
4757 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004758 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004759
4760 assert(s->kind == AnnAssign_kind);
4761
4762 /* We perform the actual assignment first. */
4763 if (s->v.AnnAssign.value) {
4764 VISIT(c, expr, s->v.AnnAssign.value);
4765 VISIT(c, expr, targ);
4766 }
4767 switch (targ->kind) {
4768 case Name_kind:
4769 /* If we have a simple name in a module or class, store annotation. */
4770 if (s->v.AnnAssign.simple &&
4771 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4772 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004773 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4774 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4775 }
4776 else {
4777 VISIT(c, expr, s->v.AnnAssign.annotation);
4778 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004779 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004780 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004781 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004782 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004783 }
4784 break;
4785 case Attribute_kind:
4786 if (!s->v.AnnAssign.value &&
4787 !check_ann_expr(c, targ->v.Attribute.value)) {
4788 return 0;
4789 }
4790 break;
4791 case Subscript_kind:
4792 if (!s->v.AnnAssign.value &&
4793 (!check_ann_expr(c, targ->v.Subscript.value) ||
4794 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4795 return 0;
4796 }
4797 break;
4798 default:
4799 PyErr_Format(PyExc_SystemError,
4800 "invalid node type (%d) for annotated assignment",
4801 targ->kind);
4802 return 0;
4803 }
4804 /* Annotation is evaluated last. */
4805 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4806 return 0;
4807 }
4808 return 1;
4809}
4810
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004811/* Raises a SyntaxError and returns 0.
4812 If something goes wrong, a different exception may be raised.
4813*/
4814
4815static int
4816compiler_error(struct compiler *c, const char *errstr)
4817{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004818 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004820
Victor Stinner14e461d2013-08-26 22:28:21 +02004821 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 if (!loc) {
4823 Py_INCREF(Py_None);
4824 loc = Py_None;
4825 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004826 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004827 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 if (!u)
4829 goto exit;
4830 v = Py_BuildValue("(zO)", errstr, u);
4831 if (!v)
4832 goto exit;
4833 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004834 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 Py_DECREF(loc);
4836 Py_XDECREF(u);
4837 Py_XDECREF(v);
4838 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004839}
4840
4841static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842compiler_handle_subscr(struct compiler *c, const char *kind,
4843 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 /* XXX this code is duplicated */
4848 switch (ctx) {
4849 case AugLoad: /* fall through to Load */
4850 case Load: op = BINARY_SUBSCR; break;
4851 case AugStore:/* fall through to Store */
4852 case Store: op = STORE_SUBSCR; break;
4853 case Del: op = DELETE_SUBSCR; break;
4854 case Param:
4855 PyErr_Format(PyExc_SystemError,
4856 "invalid %s kind %d in subscript\n",
4857 kind, ctx);
4858 return 0;
4859 }
4860 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004861 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 }
4863 else if (ctx == AugStore) {
4864 ADDOP(c, ROT_THREE);
4865 }
4866 ADDOP(c, op);
4867 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004868}
4869
4870static int
4871compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 int n = 2;
4874 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 /* only handles the cases where BUILD_SLICE is emitted */
4877 if (s->v.Slice.lower) {
4878 VISIT(c, expr, s->v.Slice.lower);
4879 }
4880 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004881 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 if (s->v.Slice.upper) {
4885 VISIT(c, expr, s->v.Slice.upper);
4886 }
4887 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004888 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 }
4890
4891 if (s->v.Slice.step) {
4892 n++;
4893 VISIT(c, expr, s->v.Slice.step);
4894 }
4895 ADDOP_I(c, BUILD_SLICE, n);
4896 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004897}
4898
4899static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4901 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 switch (s->kind) {
4904 case Slice_kind:
4905 return compiler_slice(c, s, ctx);
4906 case Index_kind:
4907 VISIT(c, expr, s->v.Index.value);
4908 break;
4909 case ExtSlice_kind:
4910 default:
4911 PyErr_SetString(PyExc_SystemError,
4912 "extended slice invalid in nested slice");
4913 return 0;
4914 }
4915 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004916}
4917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004918static int
4919compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4920{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004921 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 switch (s->kind) {
4923 case Index_kind:
4924 kindname = "index";
4925 if (ctx != AugStore) {
4926 VISIT(c, expr, s->v.Index.value);
4927 }
4928 break;
4929 case Slice_kind:
4930 kindname = "slice";
4931 if (ctx != AugStore) {
4932 if (!compiler_slice(c, s, ctx))
4933 return 0;
4934 }
4935 break;
4936 case ExtSlice_kind:
4937 kindname = "extended slice";
4938 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004939 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 for (i = 0; i < n; i++) {
4941 slice_ty sub = (slice_ty)asdl_seq_GET(
4942 s->v.ExtSlice.dims, i);
4943 if (!compiler_visit_nested_slice(c, sub, ctx))
4944 return 0;
4945 }
4946 ADDOP_I(c, BUILD_TUPLE, n);
4947 }
4948 break;
4949 default:
4950 PyErr_Format(PyExc_SystemError,
4951 "invalid subscript kind %d", s->kind);
4952 return 0;
4953 }
4954 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004955}
4956
Thomas Wouters89f507f2006-12-13 04:49:30 +00004957/* End of the compiler section, beginning of the assembler section */
4958
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004959/* do depth-first search of basic block graph, starting with block.
4960 post records the block indices in post-order.
4961
4962 XXX must handle implicit jumps from one block to next
4963*/
4964
Thomas Wouters89f507f2006-12-13 04:49:30 +00004965struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 PyObject *a_bytecode; /* string containing bytecode */
4967 int a_offset; /* offset into bytecode */
4968 int a_nblocks; /* number of reachable blocks */
4969 basicblock **a_postorder; /* list of blocks in dfs postorder */
4970 PyObject *a_lnotab; /* string containing lnotab */
4971 int a_lnotab_off; /* offset into lnotab */
4972 int a_lineno; /* last lineno of emitted instruction */
4973 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004974};
4975
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004976static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004977dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004979 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004980
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004981 /* Get rid of recursion for normal control flow.
4982 Since the number of blocks is limited, unused space in a_postorder
4983 (from a_nblocks to end) can be used as a stack for still not ordered
4984 blocks. */
4985 for (j = end; b && !b->b_seen; b = b->b_next) {
4986 b->b_seen = 1;
4987 assert(a->a_nblocks < j);
4988 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004990 while (j < end) {
4991 b = a->a_postorder[j++];
4992 for (i = 0; i < b->b_iused; i++) {
4993 struct instr *instr = &b->b_instr[i];
4994 if (instr->i_jrel || instr->i_jabs)
4995 dfs(c, instr->i_target, a, j);
4996 }
4997 assert(a->a_nblocks < j);
4998 a->a_postorder[a->a_nblocks++] = b;
4999 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005000}
5001
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005002Py_LOCAL_INLINE(void)
5003stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005004{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005005 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005006 if (b->b_startdepth < depth) {
5007 assert(b->b_startdepth < 0);
5008 b->b_startdepth = depth;
5009 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005010 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005011}
5012
5013/* Find the flow path that needs the largest stack. We assume that
5014 * cycles in the flow graph have no net effect on the stack depth.
5015 */
5016static int
5017stackdepth(struct compiler *c)
5018{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005019 basicblock *b, *entryblock = NULL;
5020 basicblock **stack, **sp;
5021 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 b->b_startdepth = INT_MIN;
5024 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005025 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 }
5027 if (!entryblock)
5028 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005029 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5030 if (!stack) {
5031 PyErr_NoMemory();
5032 return -1;
5033 }
5034
5035 sp = stack;
5036 stackdepth_push(&sp, entryblock, 0);
5037 while (sp != stack) {
5038 b = *--sp;
5039 int depth = b->b_startdepth;
5040 assert(depth >= 0);
5041 basicblock *next = b->b_next;
5042 for (int i = 0; i < b->b_iused; i++) {
5043 struct instr *instr = &b->b_instr[i];
5044 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5045 if (effect == PY_INVALID_STACK_EFFECT) {
5046 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5047 Py_FatalError("PyCompile_OpcodeStackEffect()");
5048 }
5049 int new_depth = depth + effect;
5050 if (new_depth > maxdepth) {
5051 maxdepth = new_depth;
5052 }
5053 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5054 if (instr->i_jrel || instr->i_jabs) {
5055 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5056 assert(effect != PY_INVALID_STACK_EFFECT);
5057 int target_depth = depth + effect;
5058 if (target_depth > maxdepth) {
5059 maxdepth = target_depth;
5060 }
5061 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005062 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005063 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005064 assert(instr->i_target->b_startdepth >= target_depth);
5065 depth = new_depth;
5066 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005067 }
5068 stackdepth_push(&sp, instr->i_target, target_depth);
5069 }
5070 depth = new_depth;
5071 if (instr->i_opcode == JUMP_ABSOLUTE ||
5072 instr->i_opcode == JUMP_FORWARD ||
5073 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005074 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005075 {
5076 /* remaining code is dead */
5077 next = NULL;
5078 break;
5079 }
5080 }
5081 if (next != NULL) {
5082 stackdepth_push(&sp, next, depth);
5083 }
5084 }
5085 PyObject_Free(stack);
5086 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005087}
5088
5089static int
5090assemble_init(struct assembler *a, int nblocks, int firstlineno)
5091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 memset(a, 0, sizeof(struct assembler));
5093 a->a_lineno = firstlineno;
5094 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5095 if (!a->a_bytecode)
5096 return 0;
5097 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5098 if (!a->a_lnotab)
5099 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005100 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 PyErr_NoMemory();
5102 return 0;
5103 }
5104 a->a_postorder = (basicblock **)PyObject_Malloc(
5105 sizeof(basicblock *) * nblocks);
5106 if (!a->a_postorder) {
5107 PyErr_NoMemory();
5108 return 0;
5109 }
5110 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111}
5112
5113static void
5114assemble_free(struct assembler *a)
5115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 Py_XDECREF(a->a_bytecode);
5117 Py_XDECREF(a->a_lnotab);
5118 if (a->a_postorder)
5119 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005120}
5121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005122static int
5123blocksize(basicblock *b)
5124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 int i;
5126 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005129 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005131}
5132
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005133/* Appends a pair to the end of the line number table, a_lnotab, representing
5134 the instruction's bytecode offset and line number. See
5135 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005136
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005137static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005138assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005141 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005143
Serhiy Storchakaab874002016-09-11 13:48:15 +03005144 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 if(d_bytecode == 0 && d_lineno == 0)
5150 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 if (d_bytecode > 255) {
5153 int j, nbytes, ncodes = d_bytecode / 255;
5154 nbytes = a->a_lnotab_off + 2 * ncodes;
5155 len = PyBytes_GET_SIZE(a->a_lnotab);
5156 if (nbytes >= len) {
5157 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5158 len = nbytes;
5159 else if (len <= INT_MAX / 2)
5160 len *= 2;
5161 else {
5162 PyErr_NoMemory();
5163 return 0;
5164 }
5165 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5166 return 0;
5167 }
5168 lnotab = (unsigned char *)
5169 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5170 for (j = 0; j < ncodes; j++) {
5171 *lnotab++ = 255;
5172 *lnotab++ = 0;
5173 }
5174 d_bytecode -= ncodes * 255;
5175 a->a_lnotab_off += ncodes * 2;
5176 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005177 assert(0 <= d_bytecode && d_bytecode <= 255);
5178
5179 if (d_lineno < -128 || 127 < d_lineno) {
5180 int j, nbytes, ncodes, k;
5181 if (d_lineno < 0) {
5182 k = -128;
5183 /* use division on positive numbers */
5184 ncodes = (-d_lineno) / 128;
5185 }
5186 else {
5187 k = 127;
5188 ncodes = d_lineno / 127;
5189 }
5190 d_lineno -= ncodes * k;
5191 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 nbytes = a->a_lnotab_off + 2 * ncodes;
5193 len = PyBytes_GET_SIZE(a->a_lnotab);
5194 if (nbytes >= len) {
5195 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5196 len = nbytes;
5197 else if (len <= INT_MAX / 2)
5198 len *= 2;
5199 else {
5200 PyErr_NoMemory();
5201 return 0;
5202 }
5203 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5204 return 0;
5205 }
5206 lnotab = (unsigned char *)
5207 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5208 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005209 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 d_bytecode = 0;
5211 for (j = 1; j < ncodes; j++) {
5212 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005213 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 a->a_lnotab_off += ncodes * 2;
5216 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005217 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 len = PyBytes_GET_SIZE(a->a_lnotab);
5220 if (a->a_lnotab_off + 2 >= len) {
5221 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5222 return 0;
5223 }
5224 lnotab = (unsigned char *)
5225 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 a->a_lnotab_off += 2;
5228 if (d_bytecode) {
5229 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005230 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005231 }
5232 else { /* First line of a block; def stmt, etc. */
5233 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005234 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 }
5236 a->a_lineno = i->i_lineno;
5237 a->a_lineno_off = a->a_offset;
5238 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005239}
5240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005241/* assemble_emit()
5242 Extend the bytecode with a new instruction.
5243 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005244*/
5245
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005246static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005247assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005248{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005249 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005251 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005252
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005253 arg = i->i_oparg;
5254 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 if (i->i_lineno && !assemble_lnotab(a, i))
5256 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005257 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 if (len > PY_SSIZE_T_MAX / 2)
5259 return 0;
5260 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5261 return 0;
5262 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005263 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005265 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005267}
5268
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005269static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005270assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005273 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 /* Compute the size of each block and fixup jump args.
5277 Replace block pointer with position in bytecode. */
5278 do {
5279 totsize = 0;
5280 for (i = a->a_nblocks - 1; i >= 0; i--) {
5281 b = a->a_postorder[i];
5282 bsize = blocksize(b);
5283 b->b_offset = totsize;
5284 totsize += bsize;
5285 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005286 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5288 bsize = b->b_offset;
5289 for (i = 0; i < b->b_iused; i++) {
5290 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005291 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 /* Relative jumps are computed relative to
5293 the instruction pointer after fetching
5294 the jump instruction.
5295 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005296 bsize += isize;
5297 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005299 if (instr->i_jrel) {
5300 instr->i_oparg -= bsize;
5301 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005302 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005303 if (instrsize(instr->i_oparg) != isize) {
5304 extended_arg_recompile = 1;
5305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 }
5308 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005310 /* XXX: This is an awful hack that could hurt performance, but
5311 on the bright side it should work until we come up
5312 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 The issue is that in the first loop blocksize() is called
5315 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005316 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 So we loop until we stop seeing new EXTENDED_ARGs.
5320 The only EXTENDED_ARGs that could be popping up are
5321 ones in jump instructions. So this should converge
5322 fairly quickly.
5323 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005324 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005325}
5326
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005327static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005328dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005331 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 tuple = PyTuple_New(size);
5334 if (tuple == NULL)
5335 return NULL;
5336 while (PyDict_Next(dict, &pos, &k, &v)) {
5337 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005338 Py_INCREF(k);
5339 assert((i - offset) < size);
5340 assert((i - offset) >= 0);
5341 PyTuple_SET_ITEM(tuple, i - offset, k);
5342 }
5343 return tuple;
5344}
5345
5346static PyObject *
5347consts_dict_keys_inorder(PyObject *dict)
5348{
5349 PyObject *consts, *k, *v;
5350 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5351
5352 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5353 if (consts == NULL)
5354 return NULL;
5355 while (PyDict_Next(dict, &pos, &k, &v)) {
5356 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005357 /* The keys of the dictionary can be tuples wrapping a contant.
5358 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5359 * the object we want is always second. */
5360 if (PyTuple_CheckExact(k)) {
5361 k = PyTuple_GET_ITEM(k, 1);
5362 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005364 assert(i < size);
5365 assert(i >= 0);
5366 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005368 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005369}
5370
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005371static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005372compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005375 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005377 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 if (ste->ste_nested)
5379 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005380 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005382 if (!ste->ste_generator && ste->ste_coroutine)
5383 flags |= CO_COROUTINE;
5384 if (ste->ste_generator && ste->ste_coroutine)
5385 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 if (ste->ste_varargs)
5387 flags |= CO_VARARGS;
5388 if (ste->ste_varkeywords)
5389 flags |= CO_VARKEYWORDS;
5390 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 /* (Only) inherit compilerflags in PyCF_MASK */
5393 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005396}
5397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398static PyCodeObject *
5399makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 PyObject *tmp;
5402 PyCodeObject *co = NULL;
5403 PyObject *consts = NULL;
5404 PyObject *names = NULL;
5405 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 PyObject *name = NULL;
5407 PyObject *freevars = NULL;
5408 PyObject *cellvars = NULL;
5409 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005410 Py_ssize_t nlocals;
5411 int nlocals_int;
5412 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005413 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005414
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005415 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 names = dict_keys_inorder(c->u->u_names, 0);
5417 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5418 if (!consts || !names || !varnames)
5419 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5422 if (!cellvars)
5423 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005424 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 if (!freevars)
5426 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005427
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005428 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005429 assert(nlocals < INT_MAX);
5430 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 flags = compute_code_flags(c);
5433 if (flags < 0)
5434 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5437 if (!bytecode)
5438 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5441 if (!tmp)
5442 goto error;
5443 Py_DECREF(consts);
5444 consts = tmp;
5445
Victor Stinnerf8e32212013-11-19 23:56:34 +01005446 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5447 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 maxdepth = stackdepth(c);
5449 if (maxdepth < 0) {
5450 goto error;
5451 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005452 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005453 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 bytecode, consts, names, varnames,
5455 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005456 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 c->u->u_firstlineno,
5458 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005459 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 Py_XDECREF(consts);
5461 Py_XDECREF(names);
5462 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 Py_XDECREF(name);
5464 Py_XDECREF(freevars);
5465 Py_XDECREF(cellvars);
5466 Py_XDECREF(bytecode);
5467 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005468}
5469
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005470
5471/* For debugging purposes only */
5472#if 0
5473static void
5474dump_instr(const struct instr *i)
5475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 const char *jrel = i->i_jrel ? "jrel " : "";
5477 const char *jabs = i->i_jabs ? "jabs " : "";
5478 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005481 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5485 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005486}
5487
5488static void
5489dump_basicblock(const basicblock *b)
5490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 const char *seen = b->b_seen ? "seen " : "";
5492 const char *b_return = b->b_return ? "return " : "";
5493 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5494 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5495 if (b->b_instr) {
5496 int i;
5497 for (i = 0; i < b->b_iused; i++) {
5498 fprintf(stderr, " [%02d] ", i);
5499 dump_instr(b->b_instr + i);
5500 }
5501 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005502}
5503#endif
5504
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005505static PyCodeObject *
5506assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 basicblock *b, *entryblock;
5509 struct assembler a;
5510 int i, j, nblocks;
5511 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 /* Make sure every block that falls off the end returns None.
5514 XXX NEXT_BLOCK() isn't quite right, because if the last
5515 block ends with a jump or return b_next shouldn't set.
5516 */
5517 if (!c->u->u_curblock->b_return) {
5518 NEXT_BLOCK(c);
5519 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005520 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 ADDOP(c, RETURN_VALUE);
5522 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 nblocks = 0;
5525 entryblock = NULL;
5526 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5527 nblocks++;
5528 entryblock = b;
5529 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 /* Set firstlineno if it wasn't explicitly set. */
5532 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005533 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5535 else
5536 c->u->u_firstlineno = 1;
5537 }
5538 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5539 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005540 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 /* Can't modify the bytecode after computing jump offsets. */
5543 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 /* Emit code in reverse postorder from dfs. */
5546 for (i = a.a_nblocks - 1; i >= 0; i--) {
5547 b = a.a_postorder[i];
5548 for (j = 0; j < b->b_iused; j++)
5549 if (!assemble_emit(&a, &b->b_instr[j]))
5550 goto error;
5551 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5554 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005555 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005559 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 assemble_free(&a);
5561 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005562}
Georg Brandl8334fd92010-12-04 10:26:46 +00005563
5564#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005565PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005566PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5567 PyArena *arena)
5568{
5569 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5570}