blob: c3397f0c455d9a7a97753542f0386c37bd0355e4 [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
INADA Naokicb41b272017-02-23 00:31:59 +09001590compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001592 /* Set current line number to the line number of first statement.
1593 This way line number for SETUP_ANNOTATIONS will always
1594 coincide with the line number of first "real" statement in module.
1595 If body is empy, then lineno will be set later in assemble. */
1596 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1597 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001598 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001599 c->u->u_lineno = st->lineno;
1600 }
1601 /* Every annotated class and module should have __annotations__. */
1602 if (find_ann(stmts)) {
1603 ADDOP(c, SETUP_ANNOTATIONS);
1604 }
INADA Naokicb41b272017-02-23 00:31:59 +09001605 /* if not -OO mode, set docstring */
1606 if (c->c_optimize < 2 && docstring) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001607 ADDOP_LOAD_CONST(c, docstring);
INADA Naokicb41b272017-02-23 00:31:59 +09001608 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 }
INADA Naokicb41b272017-02-23 00:31:59 +09001610 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612}
1613
1614static PyCodeObject *
1615compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyCodeObject *co;
1618 int addNone = 1;
1619 static PyObject *module;
1620 if (!module) {
1621 module = PyUnicode_InternFromString("<module>");
1622 if (!module)
1623 return NULL;
1624 }
1625 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001626 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 return NULL;
1628 switch (mod->kind) {
1629 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001630 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 compiler_exit_scope(c);
1632 return 0;
1633 }
1634 break;
1635 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001636 if (find_ann(mod->v.Interactive.body)) {
1637 ADDOP(c, SETUP_ANNOTATIONS);
1638 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 c->c_interactive = 1;
1640 VISIT_SEQ_IN_SCOPE(c, stmt,
1641 mod->v.Interactive.body);
1642 break;
1643 case Expression_kind:
1644 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1645 addNone = 0;
1646 break;
1647 case Suite_kind:
1648 PyErr_SetString(PyExc_SystemError,
1649 "suite should not be possible");
1650 return 0;
1651 default:
1652 PyErr_Format(PyExc_SystemError,
1653 "module kind %d should not be possible",
1654 mod->kind);
1655 return 0;
1656 }
1657 co = assemble(c, addNone);
1658 compiler_exit_scope(c);
1659 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001660}
1661
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662/* The test for LOCAL must come before the test for FREE in order to
1663 handle classes where name is both local and free. The local var is
1664 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001665*/
1666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667static int
1668get_ref_type(struct compiler *c, PyObject *name)
1669{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001670 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001671 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001672 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001673 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001674 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (scope == 0) {
1676 char buf[350];
1677 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001678 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001680 PyUnicode_AsUTF8(name),
1681 PyUnicode_AsUTF8(c->u->u_name),
1682 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1683 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1684 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1685 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 );
1687 Py_FatalError(buf);
1688 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691}
1692
1693static int
1694compiler_lookup_arg(PyObject *dict, PyObject *name)
1695{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001696 PyObject *v;
1697 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001699 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001700 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701}
1702
1703static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001704compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001706 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001707 if (qualname == NULL)
1708 qualname = co->co_name;
1709
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001710 if (free) {
1711 for (i = 0; i < free; ++i) {
1712 /* Bypass com_addop_varname because it will generate
1713 LOAD_DEREF but LOAD_CLOSURE is needed.
1714 */
1715 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1716 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001718 /* Special case: If a class contains a method with a
1719 free variable that has the same name as a method,
1720 the name will be considered free *and* local in the
1721 class. It should be handled by the closure, as
1722 well as by the normal name loookup logic.
1723 */
1724 reftype = get_ref_type(c, name);
1725 if (reftype == CELL)
1726 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1727 else /* (reftype == FREE) */
1728 arg = compiler_lookup_arg(c->u->u_freevars, name);
1729 if (arg == -1) {
1730 fprintf(stderr,
1731 "lookup %s in %s %d %d\n"
1732 "freevars of %s: %s\n",
1733 PyUnicode_AsUTF8(PyObject_Repr(name)),
1734 PyUnicode_AsUTF8(c->u->u_name),
1735 reftype, arg,
1736 PyUnicode_AsUTF8(co->co_name),
1737 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1738 Py_FatalError("compiler_make_closure()");
1739 }
1740 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001742 flags |= 0x08;
1743 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001745 ADDOP_LOAD_CONST(c, (PyObject*)co);
1746 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001747 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001749}
1750
1751static int
1752compiler_decorators(struct compiler *c, asdl_seq* decos)
1753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (!decos)
1757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1760 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1761 }
1762 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763}
1764
1765static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001766compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001768{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001769 /* Push a dict of keyword-only default values.
1770
1771 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1772 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001773 int i;
1774 PyObject *keys = NULL;
1775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1777 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1778 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1779 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001780 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001781 if (!mangled) {
1782 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001784 if (keys == NULL) {
1785 keys = PyList_New(1);
1786 if (keys == NULL) {
1787 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001788 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001789 }
1790 PyList_SET_ITEM(keys, 0, mangled);
1791 }
1792 else {
1793 int res = PyList_Append(keys, mangled);
1794 Py_DECREF(mangled);
1795 if (res == -1) {
1796 goto error;
1797 }
1798 }
1799 if (!compiler_visit_expr(c, default_)) {
1800 goto error;
1801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 }
1803 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001804 if (keys != NULL) {
1805 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1806 PyObject *keys_tuple = PyList_AsTuple(keys);
1807 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001808 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001809 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001810 assert(default_count > 0);
1811 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001812 }
1813 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001814 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001815 }
1816
1817error:
1818 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001819 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001820}
1821
1822static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001823compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1824{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001825 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001826 return 1;
1827}
1828
1829static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001830compiler_visit_argannotation(struct compiler *c, identifier id,
1831 expr_ty annotation, PyObject *names)
1832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001834 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001835 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1836 VISIT(c, annexpr, annotation)
1837 }
1838 else {
1839 VISIT(c, expr, annotation);
1840 }
Victor Stinner065efc32014-02-18 22:07:56 +01001841 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001842 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001843 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001844 if (PyList_Append(names, mangled) < 0) {
1845 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001846 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001847 }
1848 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001850 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001851}
1852
1853static int
1854compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1855 PyObject *names)
1856{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001857 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 for (i = 0; i < asdl_seq_LEN(args); i++) {
1859 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001860 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 c,
1862 arg->arg,
1863 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001864 names))
1865 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001867 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001868}
1869
1870static int
1871compiler_visit_annotations(struct compiler *c, arguments_ty args,
1872 expr_ty returns)
1873{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001874 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001875 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001876
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001877 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 */
1879 static identifier return_str;
1880 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001881 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 names = PyList_New(0);
1883 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001884 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001885
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001886 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001888 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001889 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001890 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001892 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001894 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001895 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001896 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (!return_str) {
1900 return_str = PyUnicode_InternFromString("return");
1901 if (!return_str)
1902 goto error;
1903 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001904 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 goto error;
1906 }
1907
1908 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 PyObject *keytuple = PyList_AsTuple(names);
1911 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001912 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001914 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 else {
1917 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001918 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001919 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001920
1921error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001923 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001924}
1925
1926static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001927compiler_visit_defaults(struct compiler *c, arguments_ty args)
1928{
1929 VISIT_SEQ(c, expr, args->defaults);
1930 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932}
1933
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001934static Py_ssize_t
1935compiler_default_arguments(struct compiler *c, arguments_ty args)
1936{
1937 Py_ssize_t funcflags = 0;
1938 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001939 if (!compiler_visit_defaults(c, args))
1940 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 funcflags |= 0x01;
1942 }
1943 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001944 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001945 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001946 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001947 return -1;
1948 }
1949 else if (res > 0) {
1950 funcflags |= 0x02;
1951 }
1952 }
1953 return funcflags;
1954}
1955
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956static int
Yury Selivanov75445082015-05-11 22:57:16 -04001957compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001960 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001961 arguments_ty args;
1962 expr_ty returns;
1963 identifier name;
1964 asdl_seq* decos;
1965 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001966 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001967 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001968 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969
Yury Selivanov75445082015-05-11 22:57:16 -04001970 if (is_async) {
1971 assert(s->kind == AsyncFunctionDef_kind);
1972
1973 args = s->v.AsyncFunctionDef.args;
1974 returns = s->v.AsyncFunctionDef.returns;
1975 decos = s->v.AsyncFunctionDef.decorator_list;
1976 name = s->v.AsyncFunctionDef.name;
1977 body = s->v.AsyncFunctionDef.body;
1978
1979 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1980 } else {
1981 assert(s->kind == FunctionDef_kind);
1982
1983 args = s->v.FunctionDef.args;
1984 returns = s->v.FunctionDef.returns;
1985 decos = s->v.FunctionDef.decorator_list;
1986 name = s->v.FunctionDef.name;
1987 body = s->v.FunctionDef.body;
1988
1989 scope_type = COMPILER_SCOPE_FUNCTION;
1990 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if (!compiler_decorators(c, decos))
1993 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001994
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001995 funcflags = compiler_default_arguments(c, args);
1996 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 }
1999
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002000 annotations = compiler_visit_annotations(c, args, returns);
2001 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002002 return 0;
2003 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002004 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002005 funcflags |= 0x04;
2006 }
2007
2008 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
2009 return 0;
2010 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011
INADA Naokicb41b272017-02-23 00:31:59 +09002012 /* if not -OO mode, add docstring */
2013 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
2014 docstring = s->v.FunctionDef.docstring;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002015 if (compiler_add_const(c, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 compiler_exit_scope(c);
2017 return 0;
2018 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 c->u->u_argcount = asdl_seq_LEN(args->args);
2021 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09002023 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002025 qualname = c->u->u_qualname;
2026 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002028 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002029 Py_XDECREF(qualname);
2030 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002032 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002034 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002035 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* decorators */
2039 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2040 ADDOP_I(c, CALL_FUNCTION, 1);
2041 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042
Yury Selivanov75445082015-05-11 22:57:16 -04002043 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044}
2045
2046static int
2047compiler_class(struct compiler *c, stmt_ty s)
2048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 PyCodeObject *co;
2050 PyObject *str;
2051 int i;
2052 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (!compiler_decorators(c, decos))
2055 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 /* ultimately generate code for:
2058 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2059 where:
2060 <func> is a function/closure created from the class body;
2061 it has a single argument (__locals__) where the dict
2062 (or MutableSequence) representing the locals is passed
2063 <name> is the class name
2064 <bases> is the positional arguments and *varargs argument
2065 <keywords> is the keyword arguments and **kwds argument
2066 This borrows from compiler_call.
2067 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002070 if (!compiler_enter_scope(c, s->v.ClassDef.name,
2071 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 return 0;
2073 /* this block represents what we do in the new scope */
2074 {
2075 /* use the class name for name mangling */
2076 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002077 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* load (global) __name__ ... */
2079 str = PyUnicode_InternFromString("__name__");
2080 if (!str || !compiler_nameop(c, str, Load)) {
2081 Py_XDECREF(str);
2082 compiler_exit_scope(c);
2083 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002084 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 Py_DECREF(str);
2086 /* ... and store it as __module__ */
2087 str = PyUnicode_InternFromString("__module__");
2088 if (!str || !compiler_nameop(c, str, Store)) {
2089 Py_XDECREF(str);
2090 compiler_exit_scope(c);
2091 return 0;
2092 }
2093 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002094 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002095 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002096 str = PyUnicode_InternFromString("__qualname__");
2097 if (!str || !compiler_nameop(c, str, Store)) {
2098 Py_XDECREF(str);
2099 compiler_exit_scope(c);
2100 return 0;
2101 }
2102 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09002104 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 compiler_exit_scope(c);
2106 return 0;
2107 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002108 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002109 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002110 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002111 str = PyUnicode_InternFromString("__class__");
2112 if (str == NULL) {
2113 compiler_exit_scope(c);
2114 return 0;
2115 }
2116 i = compiler_lookup_arg(c->u->u_cellvars, str);
2117 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002118 if (i < 0) {
2119 compiler_exit_scope(c);
2120 return 0;
2121 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002122 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002125 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002126 str = PyUnicode_InternFromString("__classcell__");
2127 if (!str || !compiler_nameop(c, str, Store)) {
2128 Py_XDECREF(str);
2129 compiler_exit_scope(c);
2130 return 0;
2131 }
2132 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002134 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002135 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002136 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002137 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002138 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002139 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 /* create the code object */
2141 co = assemble(c, 1);
2142 }
2143 /* leave the new scope */
2144 compiler_exit_scope(c);
2145 if (co == NULL)
2146 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* 2. load the 'build_class' function */
2149 ADDOP(c, LOAD_BUILD_CLASS);
2150
2151 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002152 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 Py_DECREF(co);
2154
2155 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002156 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157
2158 /* 5. generate the rest of the code for the call */
2159 if (!compiler_call_helper(c, 2,
2160 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002161 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 return 0;
2163
2164 /* 6. apply decorators */
2165 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2166 ADDOP_I(c, CALL_FUNCTION, 1);
2167 }
2168
2169 /* 7. store into <name> */
2170 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2171 return 0;
2172 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173}
2174
2175static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002176cmpop(cmpop_ty op)
2177{
2178 switch (op) {
2179 case Eq:
2180 return PyCmp_EQ;
2181 case NotEq:
2182 return PyCmp_NE;
2183 case Lt:
2184 return PyCmp_LT;
2185 case LtE:
2186 return PyCmp_LE;
2187 case Gt:
2188 return PyCmp_GT;
2189 case GtE:
2190 return PyCmp_GE;
2191 case Is:
2192 return PyCmp_IS;
2193 case IsNot:
2194 return PyCmp_IS_NOT;
2195 case In:
2196 return PyCmp_IN;
2197 case NotIn:
2198 return PyCmp_NOT_IN;
2199 default:
2200 return PyCmp_BAD;
2201 }
2202}
2203
2204static int
2205compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2206{
2207 switch (e->kind) {
2208 case UnaryOp_kind:
2209 if (e->v.UnaryOp.op == Not)
2210 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2211 /* fallback to general implementation */
2212 break;
2213 case BoolOp_kind: {
2214 asdl_seq *s = e->v.BoolOp.values;
2215 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2216 assert(n >= 0);
2217 int cond2 = e->v.BoolOp.op == Or;
2218 basicblock *next2 = next;
2219 if (!cond2 != !cond) {
2220 next2 = compiler_new_block(c);
2221 if (next2 == NULL)
2222 return 0;
2223 }
2224 for (i = 0; i < n; ++i) {
2225 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2226 return 0;
2227 }
2228 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2229 return 0;
2230 if (next2 != next)
2231 compiler_use_next_block(c, next2);
2232 return 1;
2233 }
2234 case IfExp_kind: {
2235 basicblock *end, *next2;
2236 end = compiler_new_block(c);
2237 if (end == NULL)
2238 return 0;
2239 next2 = compiler_new_block(c);
2240 if (next2 == NULL)
2241 return 0;
2242 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2243 return 0;
2244 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2245 return 0;
2246 ADDOP_JREL(c, JUMP_FORWARD, end);
2247 compiler_use_next_block(c, next2);
2248 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2249 return 0;
2250 compiler_use_next_block(c, end);
2251 return 1;
2252 }
2253 case Compare_kind: {
2254 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2255 if (n > 0) {
2256 basicblock *cleanup = compiler_new_block(c);
2257 if (cleanup == NULL)
2258 return 0;
2259 VISIT(c, expr, e->v.Compare.left);
2260 for (i = 0; i < n; i++) {
2261 VISIT(c, expr,
2262 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2263 ADDOP(c, DUP_TOP);
2264 ADDOP(c, ROT_THREE);
2265 ADDOP_I(c, COMPARE_OP,
2266 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2267 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2268 NEXT_BLOCK(c);
2269 }
2270 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2271 ADDOP_I(c, COMPARE_OP,
2272 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2273 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2274 basicblock *end = compiler_new_block(c);
2275 if (end == NULL)
2276 return 0;
2277 ADDOP_JREL(c, JUMP_FORWARD, end);
2278 compiler_use_next_block(c, cleanup);
2279 ADDOP(c, POP_TOP);
2280 if (!cond) {
2281 ADDOP_JREL(c, JUMP_FORWARD, next);
2282 }
2283 compiler_use_next_block(c, end);
2284 return 1;
2285 }
2286 /* fallback to general implementation */
2287 break;
2288 }
2289 default:
2290 /* fallback to general implementation */
2291 break;
2292 }
2293
2294 /* general implementation */
2295 VISIT(c, expr, e);
2296 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2297 return 1;
2298}
2299
2300static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002301compiler_ifexp(struct compiler *c, expr_ty e)
2302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 basicblock *end, *next;
2304
2305 assert(e->kind == IfExp_kind);
2306 end = compiler_new_block(c);
2307 if (end == NULL)
2308 return 0;
2309 next = compiler_new_block(c);
2310 if (next == NULL)
2311 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002312 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2313 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 VISIT(c, expr, e->v.IfExp.body);
2315 ADDOP_JREL(c, JUMP_FORWARD, end);
2316 compiler_use_next_block(c, next);
2317 VISIT(c, expr, e->v.IfExp.orelse);
2318 compiler_use_next_block(c, end);
2319 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002320}
2321
2322static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323compiler_lambda(struct compiler *c, expr_ty e)
2324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002326 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002328 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 arguments_ty args = e->v.Lambda.args;
2330 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (!name) {
2333 name = PyUnicode_InternFromString("<lambda>");
2334 if (!name)
2335 return 0;
2336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002338 funcflags = compiler_default_arguments(c, args);
2339 if (funcflags == -1) {
2340 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002342
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002343 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002344 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* Make None the first constant, so the lambda can't have a
2348 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002349 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 c->u->u_argcount = asdl_seq_LEN(args->args);
2353 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2354 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2355 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002356 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 }
2358 else {
2359 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002360 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002362 qualname = c->u->u_qualname;
2363 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002365 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002368 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002369 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 Py_DECREF(co);
2371
2372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002373}
2374
2375static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376compiler_if(struct compiler *c, stmt_ty s)
2377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 basicblock *end, *next;
2379 int constant;
2380 assert(s->kind == If_kind);
2381 end = compiler_new_block(c);
2382 if (end == NULL)
2383 return 0;
2384
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002385 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* constant = 0: "if 0"
2387 * constant = 1: "if 1", "if 2", ...
2388 * constant = -1: rest */
2389 if (constant == 0) {
2390 if (s->v.If.orelse)
2391 VISIT_SEQ(c, stmt, s->v.If.orelse);
2392 } else if (constant == 1) {
2393 VISIT_SEQ(c, stmt, s->v.If.body);
2394 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002395 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 next = compiler_new_block(c);
2397 if (next == NULL)
2398 return 0;
2399 }
2400 else
2401 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002402 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2403 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002405 if (asdl_seq_LEN(s->v.If.orelse)) {
2406 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 compiler_use_next_block(c, next);
2408 VISIT_SEQ(c, stmt, s->v.If.orelse);
2409 }
2410 }
2411 compiler_use_next_block(c, end);
2412 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413}
2414
2415static int
2416compiler_for(struct compiler *c, stmt_ty s)
2417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 start = compiler_new_block(c);
2421 cleanup = compiler_new_block(c);
2422 end = compiler_new_block(c);
2423 if (start == NULL || end == NULL || cleanup == NULL)
2424 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002425
2426 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 VISIT(c, expr, s->v.For.iter);
2430 ADDOP(c, GET_ITER);
2431 compiler_use_next_block(c, start);
2432 ADDOP_JREL(c, FOR_ITER, cleanup);
2433 VISIT(c, expr, s->v.For.target);
2434 VISIT_SEQ(c, stmt, s->v.For.body);
2435 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2436 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002437
2438 compiler_pop_fblock(c, FOR_LOOP, start);
2439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 VISIT_SEQ(c, stmt, s->v.For.orelse);
2441 compiler_use_next_block(c, end);
2442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443}
2444
Yury Selivanov75445082015-05-11 22:57:16 -04002445
2446static int
2447compiler_async_for(struct compiler *c, stmt_ty s)
2448{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002449 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002450 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2451 return compiler_error(c, "'async for' outside async function");
2452 }
2453
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002454 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002455 except = compiler_new_block(c);
2456 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002457
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002458 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002459 return 0;
2460
2461 VISIT(c, expr, s->v.AsyncFor.iter);
2462 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002463
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002464 compiler_use_next_block(c, start);
2465 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2466 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002467
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002468 /* SETUP_FINALLY to guard the __anext__ call */
2469 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002470 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002471 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002472 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002473 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002474
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002475 /* Success block for __anext__ */
2476 VISIT(c, expr, s->v.AsyncFor.target);
2477 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2478 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2479
2480 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002481
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002482 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002483 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002484 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002485
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002486 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002487 VISIT_SEQ(c, stmt, s->v.For.orelse);
2488
2489 compiler_use_next_block(c, end);
2490
2491 return 1;
2492}
2493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494static int
2495compiler_while(struct compiler *c, stmt_ty s)
2496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002498 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (constant == 0) {
2501 if (s->v.While.orelse)
2502 VISIT_SEQ(c, stmt, s->v.While.orelse);
2503 return 1;
2504 }
2505 loop = compiler_new_block(c);
2506 end = compiler_new_block(c);
2507 if (constant == -1) {
2508 anchor = compiler_new_block(c);
2509 if (anchor == NULL)
2510 return 0;
2511 }
2512 if (loop == NULL || end == NULL)
2513 return 0;
2514 if (s->v.While.orelse) {
2515 orelse = compiler_new_block(c);
2516 if (orelse == NULL)
2517 return 0;
2518 }
2519 else
2520 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002523 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return 0;
2525 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002526 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2527 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 }
2529 VISIT_SEQ(c, stmt, s->v.While.body);
2530 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 /* XXX should the two POP instructions be in a separate block
2533 if there is no else clause ?
2534 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002536 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002538 compiler_pop_fblock(c, WHILE_LOOP, loop);
2539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 if (orelse != NULL) /* what if orelse is just pass? */
2541 VISIT_SEQ(c, stmt, s->v.While.orelse);
2542 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545}
2546
2547static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002548compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002550 int preserve_tos = ((s->v.Return.value != NULL) &&
2551 !is_const(s->v.Return.value));
2552 if (c->u->u_ste->ste_type != FunctionBlock)
2553 return compiler_error(c, "'return' outside function");
2554 if (s->v.Return.value != NULL &&
2555 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2556 {
2557 return compiler_error(
2558 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002560 if (preserve_tos) {
2561 VISIT(c, expr, s->v.Return.value);
2562 }
2563 for (int depth = c->u->u_nfblocks; depth--;) {
2564 struct fblockinfo *info = &c->u->u_fblock[depth];
2565
2566 if (!compiler_unwind_fblock(c, info, preserve_tos))
2567 return 0;
2568 }
2569 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002570 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002571 }
2572 else if (!preserve_tos) {
2573 VISIT(c, expr, s->v.Return.value);
2574 }
2575 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578}
2579
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002580static int
2581compiler_break(struct compiler *c)
2582{
2583 for (int depth = c->u->u_nfblocks; depth--;) {
2584 struct fblockinfo *info = &c->u->u_fblock[depth];
2585
2586 if (!compiler_unwind_fblock(c, info, 0))
2587 return 0;
2588 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2589 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2590 return 1;
2591 }
2592 }
2593 return compiler_error(c, "'break' outside loop");
2594}
2595
2596static int
2597compiler_continue(struct compiler *c)
2598{
2599 for (int depth = c->u->u_nfblocks; depth--;) {
2600 struct fblockinfo *info = &c->u->u_fblock[depth];
2601
2602 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2603 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2604 return 1;
2605 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002606 if (!compiler_unwind_fblock(c, info, 0))
2607 return 0;
2608 }
2609 return compiler_error(c, "'continue' not properly in loop");
2610}
2611
2612
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614
2615 SETUP_FINALLY L
2616 <code for body>
2617 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002618 BEGIN_FINALLY
2619 L:
2620 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 END_FINALLY
2622
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 The special instructions use the block stack. Each block
2624 stack entry contains the instruction that created it (here
2625 SETUP_FINALLY), the level of the value stack at the time the
2626 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 Pushes the current value stack level and the label
2630 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002632 Pops en entry from the block stack.
2633 BEGIN_FINALLY
2634 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002636 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2637 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002640 when a SETUP_FINALLY entry is found, the raised and the caught
2641 exceptions are pushed onto the value stack (and the exception
2642 condition is cleared), and the interpreter jumps to the label
2643 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644*/
2645
2646static int
2647compiler_try_finally(struct compiler *c, stmt_ty s)
2648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 body = compiler_new_block(c);
2652 end = compiler_new_block(c);
2653 if (body == NULL || end == NULL)
2654 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002656 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 ADDOP_JREL(c, SETUP_FINALLY, end);
2658 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002659 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002661 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2662 if (!compiler_try_except(c, s))
2663 return 0;
2664 }
2665 else {
2666 VISIT_SEQ(c, stmt, s->v.Try.body);
2667 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002669 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002672 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002674 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002676 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 ADDOP(c, END_FINALLY);
2678 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680}
2681
2682/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002683 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 (The contents of the value stack is shown in [], with the top
2685 at the right; 'tb' is trace-back info, 'val' the exception's
2686 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687
2688 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002689 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 [] <code for S>
2691 [] POP_BLOCK
2692 [] JUMP_FORWARD L0
2693
2694 [tb, val, exc] L1: DUP )
2695 [tb, val, exc, exc] <evaluate E1> )
2696 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2697 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2698 [tb, val, exc] POP
2699 [tb, val] <assign to V1> (or POP if no V1)
2700 [tb] POP
2701 [] <code for S1>
2702 JUMP_FORWARD L0
2703
2704 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 .............................etc.......................
2706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2708
2709 [] L0: <next statement>
2710
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 Of course, parts are not generated if Vi or Ei is not present.
2712*/
2713static int
2714compiler_try_except(struct compiler *c, stmt_ty s)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002717 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 body = compiler_new_block(c);
2720 except = compiler_new_block(c);
2721 orelse = compiler_new_block(c);
2722 end = compiler_new_block(c);
2723 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2724 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002725 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002727 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002729 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 ADDOP(c, POP_BLOCK);
2731 compiler_pop_fblock(c, EXCEPT, body);
2732 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002733 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 compiler_use_next_block(c, except);
2735 for (i = 0; i < n; i++) {
2736 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002737 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 if (!handler->v.ExceptHandler.type && i < n-1)
2739 return compiler_error(c, "default 'except:' must be last");
2740 c->u->u_lineno_set = 0;
2741 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002742 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 except = compiler_new_block(c);
2744 if (except == NULL)
2745 return 0;
2746 if (handler->v.ExceptHandler.type) {
2747 ADDOP(c, DUP_TOP);
2748 VISIT(c, expr, handler->v.ExceptHandler.type);
2749 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2750 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2751 }
2752 ADDOP(c, POP_TOP);
2753 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002754 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002755
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002756 cleanup_end = compiler_new_block(c);
2757 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002758 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002759 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002760
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002761 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2762 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002764 /*
2765 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002766 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002767 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002768 try:
2769 # body
2770 finally:
2771 name = None
2772 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002773 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002775 /* second try: */
2776 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2777 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002778 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002779 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002781 /* second # body */
2782 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2783 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 ADDOP(c, BEGIN_FINALLY);
2785 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002787 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002788 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002790 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002793 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002794 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002795 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002797 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002798 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002799 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 }
2801 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002802 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002804 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002805 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002806 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807
Guido van Rossumb940e112007-01-10 16:19:56 +00002808 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002809 ADDOP(c, POP_TOP);
2810 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002812 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002814 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002815 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 }
2817 ADDOP_JREL(c, JUMP_FORWARD, end);
2818 compiler_use_next_block(c, except);
2819 }
2820 ADDOP(c, END_FINALLY);
2821 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002822 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 compiler_use_next_block(c, end);
2824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825}
2826
2827static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002828compiler_try(struct compiler *c, stmt_ty s) {
2829 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2830 return compiler_try_finally(c, s);
2831 else
2832 return compiler_try_except(c, s);
2833}
2834
2835
2836static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837compiler_import_as(struct compiler *c, identifier name, identifier asname)
2838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 /* The IMPORT_NAME opcode was already generated. This function
2840 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002843 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002845 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2846 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002847 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002848 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002849 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002851 while (1) {
2852 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002854 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002856 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002857 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002859 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002860 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002861 if (dot == -1) {
2862 break;
2863 }
2864 ADDOP(c, ROT_TWO);
2865 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002867 if (!compiler_nameop(c, asname, Store)) {
2868 return 0;
2869 }
2870 ADDOP(c, POP_TOP);
2871 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 }
2873 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874}
2875
2876static int
2877compiler_import(struct compiler *c, stmt_ty s)
2878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 /* The Import node stores a module name like a.b.c as a single
2880 string. This is convenient for all cases except
2881 import a.b.c as d
2882 where we need to parse that string to extract the individual
2883 module names.
2884 XXX Perhaps change the representation to make this case simpler?
2885 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002886 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 for (i = 0; i < n; i++) {
2889 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2890 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002892 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2893 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 if (alias->asname) {
2897 r = compiler_import_as(c, alias->name, alias->asname);
2898 if (!r)
2899 return r;
2900 }
2901 else {
2902 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002903 Py_ssize_t dot = PyUnicode_FindChar(
2904 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002905 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002906 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002907 if (tmp == NULL)
2908 return 0;
2909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002911 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 Py_DECREF(tmp);
2913 }
2914 if (!r)
2915 return r;
2916 }
2917 }
2918 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919}
2920
2921static int
2922compiler_from_import(struct compiler *c, stmt_ty s)
2923{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002924 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002925 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 if (!empty_string) {
2929 empty_string = PyUnicode_FromString("");
2930 if (!empty_string)
2931 return 0;
2932 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002934 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002935
2936 names = PyTuple_New(n);
2937 if (!names)
2938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 /* build up the names */
2941 for (i = 0; i < n; i++) {
2942 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2943 Py_INCREF(alias->name);
2944 PyTuple_SET_ITEM(names, i, alias->name);
2945 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002948 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 Py_DECREF(names);
2950 return compiler_error(c, "from __future__ imports must occur "
2951 "at the beginning of the file");
2952 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002953 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 if (s->v.ImportFrom.module) {
2956 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2957 }
2958 else {
2959 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2960 }
2961 for (i = 0; i < n; i++) {
2962 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2963 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002965 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 assert(n == 1);
2967 ADDOP(c, IMPORT_STAR);
2968 return 1;
2969 }
2970
2971 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2972 store_name = alias->name;
2973 if (alias->asname)
2974 store_name = alias->asname;
2975
2976 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 return 0;
2978 }
2979 }
2980 /* remove imported module */
2981 ADDOP(c, POP_TOP);
2982 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983}
2984
2985static int
2986compiler_assert(struct compiler *c, stmt_ty s)
2987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 static PyObject *assertion_error = NULL;
2989 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002990 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991
Georg Brandl8334fd92010-12-04 10:26:46 +00002992 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 return 1;
2994 if (assertion_error == NULL) {
2995 assertion_error = PyUnicode_InternFromString("AssertionError");
2996 if (assertion_error == NULL)
2997 return 0;
2998 }
2999 if (s->v.Assert.test->kind == Tuple_kind &&
3000 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02003001 msg = PyUnicode_FromString("assertion is always true, "
3002 "perhaps remove parentheses?");
3003 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02003005 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
3006 c->c_filename, c->u->u_lineno,
3007 NULL, NULL) == -1) {
3008 Py_DECREF(msg);
3009 return 0;
3010 }
3011 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 end = compiler_new_block(c);
3014 if (end == NULL)
3015 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003016 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3017 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3019 if (s->v.Assert.msg) {
3020 VISIT(c, expr, s->v.Assert.msg);
3021 ADDOP_I(c, CALL_FUNCTION, 1);
3022 }
3023 ADDOP_I(c, RAISE_VARARGS, 1);
3024 compiler_use_next_block(c, end);
3025 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026}
3027
3028static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003029compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3030{
3031 if (c->c_interactive && c->c_nestlevel <= 1) {
3032 VISIT(c, expr, value);
3033 ADDOP(c, PRINT_EXPR);
3034 return 1;
3035 }
3036
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003037 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003038 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003039 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003040 }
3041
3042 VISIT(c, expr, value);
3043 ADDOP(c, POP_TOP);
3044 return 1;
3045}
3046
3047static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048compiler_visit_stmt(struct compiler *c, stmt_ty s)
3049{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003050 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 /* Always assign a lineno to the next instruction for a stmt. */
3053 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003054 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 switch (s->kind) {
3058 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003059 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 case ClassDef_kind:
3061 return compiler_class(c, s);
3062 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003063 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 case Delete_kind:
3065 VISIT_SEQ(c, expr, s->v.Delete.targets)
3066 break;
3067 case Assign_kind:
3068 n = asdl_seq_LEN(s->v.Assign.targets);
3069 VISIT(c, expr, s->v.Assign.value);
3070 for (i = 0; i < n; i++) {
3071 if (i < n - 1)
3072 ADDOP(c, DUP_TOP);
3073 VISIT(c, expr,
3074 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3075 }
3076 break;
3077 case AugAssign_kind:
3078 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003079 case AnnAssign_kind:
3080 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 case For_kind:
3082 return compiler_for(c, s);
3083 case While_kind:
3084 return compiler_while(c, s);
3085 case If_kind:
3086 return compiler_if(c, s);
3087 case Raise_kind:
3088 n = 0;
3089 if (s->v.Raise.exc) {
3090 VISIT(c, expr, s->v.Raise.exc);
3091 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003092 if (s->v.Raise.cause) {
3093 VISIT(c, expr, s->v.Raise.cause);
3094 n++;
3095 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003097 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003099 case Try_kind:
3100 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 case Assert_kind:
3102 return compiler_assert(c, s);
3103 case Import_kind:
3104 return compiler_import(c, s);
3105 case ImportFrom_kind:
3106 return compiler_from_import(c, s);
3107 case Global_kind:
3108 case Nonlocal_kind:
3109 break;
3110 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003111 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 case Pass_kind:
3113 break;
3114 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003115 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 case Continue_kind:
3117 return compiler_continue(c);
3118 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003119 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003120 case AsyncFunctionDef_kind:
3121 return compiler_function(c, s, 1);
3122 case AsyncWith_kind:
3123 return compiler_async_with(c, s, 0);
3124 case AsyncFor_kind:
3125 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 }
Yury Selivanov75445082015-05-11 22:57:16 -04003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003129}
3130
3131static int
3132unaryop(unaryop_ty op)
3133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 switch (op) {
3135 case Invert:
3136 return UNARY_INVERT;
3137 case Not:
3138 return UNARY_NOT;
3139 case UAdd:
3140 return UNARY_POSITIVE;
3141 case USub:
3142 return UNARY_NEGATIVE;
3143 default:
3144 PyErr_Format(PyExc_SystemError,
3145 "unary op %d should not be possible", op);
3146 return 0;
3147 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148}
3149
3150static int
3151binop(struct compiler *c, operator_ty op)
3152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 switch (op) {
3154 case Add:
3155 return BINARY_ADD;
3156 case Sub:
3157 return BINARY_SUBTRACT;
3158 case Mult:
3159 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003160 case MatMult:
3161 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 case Div:
3163 return BINARY_TRUE_DIVIDE;
3164 case Mod:
3165 return BINARY_MODULO;
3166 case Pow:
3167 return BINARY_POWER;
3168 case LShift:
3169 return BINARY_LSHIFT;
3170 case RShift:
3171 return BINARY_RSHIFT;
3172 case BitOr:
3173 return BINARY_OR;
3174 case BitXor:
3175 return BINARY_XOR;
3176 case BitAnd:
3177 return BINARY_AND;
3178 case FloorDiv:
3179 return BINARY_FLOOR_DIVIDE;
3180 default:
3181 PyErr_Format(PyExc_SystemError,
3182 "binary op %d should not be possible", op);
3183 return 0;
3184 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185}
3186
3187static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188inplace_binop(struct compiler *c, operator_ty op)
3189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 switch (op) {
3191 case Add:
3192 return INPLACE_ADD;
3193 case Sub:
3194 return INPLACE_SUBTRACT;
3195 case Mult:
3196 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003197 case MatMult:
3198 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 case Div:
3200 return INPLACE_TRUE_DIVIDE;
3201 case Mod:
3202 return INPLACE_MODULO;
3203 case Pow:
3204 return INPLACE_POWER;
3205 case LShift:
3206 return INPLACE_LSHIFT;
3207 case RShift:
3208 return INPLACE_RSHIFT;
3209 case BitOr:
3210 return INPLACE_OR;
3211 case BitXor:
3212 return INPLACE_XOR;
3213 case BitAnd:
3214 return INPLACE_AND;
3215 case FloorDiv:
3216 return INPLACE_FLOOR_DIVIDE;
3217 default:
3218 PyErr_Format(PyExc_SystemError,
3219 "inplace binary op %d should not be possible", op);
3220 return 0;
3221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222}
3223
3224static int
3225compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3226{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003227 int op, scope;
3228 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 PyObject *dict = c->u->u_names;
3232 PyObject *mangled;
3233 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003235 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3236 !_PyUnicode_EqualToASCIIString(name, "True") &&
3237 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003238
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003239 mangled = _Py_Mangle(c->u->u_private, name);
3240 if (!mangled)
3241 return 0;
3242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 op = 0;
3244 optype = OP_NAME;
3245 scope = PyST_GetScope(c->u->u_ste, mangled);
3246 switch (scope) {
3247 case FREE:
3248 dict = c->u->u_freevars;
3249 optype = OP_DEREF;
3250 break;
3251 case CELL:
3252 dict = c->u->u_cellvars;
3253 optype = OP_DEREF;
3254 break;
3255 case LOCAL:
3256 if (c->u->u_ste->ste_type == FunctionBlock)
3257 optype = OP_FAST;
3258 break;
3259 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003260 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 optype = OP_GLOBAL;
3262 break;
3263 case GLOBAL_EXPLICIT:
3264 optype = OP_GLOBAL;
3265 break;
3266 default:
3267 /* scope can be 0 */
3268 break;
3269 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003272 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 switch (optype) {
3275 case OP_DEREF:
3276 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003277 case Load:
3278 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3279 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 case Store: op = STORE_DEREF; break;
3281 case AugLoad:
3282 case AugStore:
3283 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003284 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 case Param:
3286 default:
3287 PyErr_SetString(PyExc_SystemError,
3288 "param invalid for deref variable");
3289 return 0;
3290 }
3291 break;
3292 case OP_FAST:
3293 switch (ctx) {
3294 case Load: op = LOAD_FAST; break;
3295 case Store: op = STORE_FAST; break;
3296 case Del: op = DELETE_FAST; break;
3297 case AugLoad:
3298 case AugStore:
3299 break;
3300 case Param:
3301 default:
3302 PyErr_SetString(PyExc_SystemError,
3303 "param invalid for local variable");
3304 return 0;
3305 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003306 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 return 1;
3308 case OP_GLOBAL:
3309 switch (ctx) {
3310 case Load: op = LOAD_GLOBAL; break;
3311 case Store: op = STORE_GLOBAL; break;
3312 case Del: op = DELETE_GLOBAL; break;
3313 case AugLoad:
3314 case AugStore:
3315 break;
3316 case Param:
3317 default:
3318 PyErr_SetString(PyExc_SystemError,
3319 "param invalid for global variable");
3320 return 0;
3321 }
3322 break;
3323 case OP_NAME:
3324 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003325 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 case Store: op = STORE_NAME; break;
3327 case Del: op = DELETE_NAME; break;
3328 case AugLoad:
3329 case AugStore:
3330 break;
3331 case Param:
3332 default:
3333 PyErr_SetString(PyExc_SystemError,
3334 "param invalid for name variable");
3335 return 0;
3336 }
3337 break;
3338 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 assert(op);
3341 arg = compiler_add_o(c, dict, mangled);
3342 Py_DECREF(mangled);
3343 if (arg < 0)
3344 return 0;
3345 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346}
3347
3348static int
3349compiler_boolop(struct compiler *c, expr_ty e)
3350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003352 int jumpi;
3353 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 assert(e->kind == BoolOp_kind);
3357 if (e->v.BoolOp.op == And)
3358 jumpi = JUMP_IF_FALSE_OR_POP;
3359 else
3360 jumpi = JUMP_IF_TRUE_OR_POP;
3361 end = compiler_new_block(c);
3362 if (end == NULL)
3363 return 0;
3364 s = e->v.BoolOp.values;
3365 n = asdl_seq_LEN(s) - 1;
3366 assert(n >= 0);
3367 for (i = 0; i < n; ++i) {
3368 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3369 ADDOP_JABS(c, jumpi, end);
3370 }
3371 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3372 compiler_use_next_block(c, end);
3373 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003374}
3375
3376static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003377starunpack_helper(struct compiler *c, asdl_seq *elts,
3378 int single_op, int inner_op, int outer_op)
3379{
3380 Py_ssize_t n = asdl_seq_LEN(elts);
3381 Py_ssize_t i, nsubitems = 0, nseen = 0;
3382 for (i = 0; i < n; i++) {
3383 expr_ty elt = asdl_seq_GET(elts, i);
3384 if (elt->kind == Starred_kind) {
3385 if (nseen) {
3386 ADDOP_I(c, inner_op, nseen);
3387 nseen = 0;
3388 nsubitems++;
3389 }
3390 VISIT(c, expr, elt->v.Starred.value);
3391 nsubitems++;
3392 }
3393 else {
3394 VISIT(c, expr, elt);
3395 nseen++;
3396 }
3397 }
3398 if (nsubitems) {
3399 if (nseen) {
3400 ADDOP_I(c, inner_op, nseen);
3401 nsubitems++;
3402 }
3403 ADDOP_I(c, outer_op, nsubitems);
3404 }
3405 else
3406 ADDOP_I(c, single_op, nseen);
3407 return 1;
3408}
3409
3410static int
3411assignment_helper(struct compiler *c, asdl_seq *elts)
3412{
3413 Py_ssize_t n = asdl_seq_LEN(elts);
3414 Py_ssize_t i;
3415 int seen_star = 0;
3416 for (i = 0; i < n; i++) {
3417 expr_ty elt = asdl_seq_GET(elts, i);
3418 if (elt->kind == Starred_kind && !seen_star) {
3419 if ((i >= (1 << 8)) ||
3420 (n-i-1 >= (INT_MAX >> 8)))
3421 return compiler_error(c,
3422 "too many expressions in "
3423 "star-unpacking assignment");
3424 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3425 seen_star = 1;
3426 asdl_seq_SET(elts, i, elt->v.Starred.value);
3427 }
3428 else if (elt->kind == Starred_kind) {
3429 return compiler_error(c,
3430 "two starred expressions in assignment");
3431 }
3432 }
3433 if (!seen_star) {
3434 ADDOP_I(c, UNPACK_SEQUENCE, n);
3435 }
3436 VISIT_SEQ(c, expr, elts);
3437 return 1;
3438}
3439
3440static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441compiler_list(struct compiler *c, expr_ty e)
3442{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003443 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003445 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003447 else if (e->v.List.ctx == Load) {
3448 return starunpack_helper(c, elts,
3449 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003451 else
3452 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454}
3455
3456static int
3457compiler_tuple(struct compiler *c, expr_ty e)
3458{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003459 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003461 return assignment_helper(c, elts);
3462 }
3463 else if (e->v.Tuple.ctx == Load) {
3464 return starunpack_helper(c, elts,
3465 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3466 }
3467 else
3468 VISIT_SEQ(c, expr, elts);
3469 return 1;
3470}
3471
3472static int
3473compiler_set(struct compiler *c, expr_ty e)
3474{
3475 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3476 BUILD_SET, BUILD_SET_UNPACK);
3477}
3478
3479static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003480are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3481{
3482 Py_ssize_t i;
3483 for (i = begin; i < end; i++) {
3484 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3485 if (key == NULL || !is_const(key))
3486 return 0;
3487 }
3488 return 1;
3489}
3490
3491static int
3492compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3493{
3494 Py_ssize_t i, n = end - begin;
3495 PyObject *keys, *key;
3496 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3497 for (i = begin; i < end; i++) {
3498 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3499 }
3500 keys = PyTuple_New(n);
3501 if (keys == NULL) {
3502 return 0;
3503 }
3504 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003505 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003506 Py_INCREF(key);
3507 PyTuple_SET_ITEM(keys, i - begin, key);
3508 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003509 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003510 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3511 }
3512 else {
3513 for (i = begin; i < end; i++) {
3514 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3515 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3516 }
3517 ADDOP_I(c, BUILD_MAP, n);
3518 }
3519 return 1;
3520}
3521
3522static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003523compiler_dict(struct compiler *c, expr_ty e)
3524{
Victor Stinner976bb402016-03-23 11:36:19 +01003525 Py_ssize_t i, n, elements;
3526 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003527 int is_unpacking = 0;
3528 n = asdl_seq_LEN(e->v.Dict.values);
3529 containers = 0;
3530 elements = 0;
3531 for (i = 0; i < n; i++) {
3532 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3533 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003534 if (!compiler_subdict(c, e, i - elements, i))
3535 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003536 containers++;
3537 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003539 if (is_unpacking) {
3540 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3541 containers++;
3542 }
3543 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003544 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 }
3546 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003547 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003548 if (!compiler_subdict(c, e, n - elements, n))
3549 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003550 containers++;
3551 }
3552 /* If there is more than one dict, they need to be merged into a new
3553 * dict. If there is one dict and it's an unpacking, then it needs
3554 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003555 if (containers > 1 || is_unpacking) {
3556 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 }
3558 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559}
3560
3561static int
3562compiler_compare(struct compiler *c, expr_ty e)
3563{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003564 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003567 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3568 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3569 if (n == 0) {
3570 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3571 ADDOP_I(c, COMPARE_OP,
3572 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3573 }
3574 else {
3575 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 if (cleanup == NULL)
3577 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003578 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 VISIT(c, expr,
3580 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003581 ADDOP(c, DUP_TOP);
3582 ADDOP(c, ROT_THREE);
3583 ADDOP_I(c, COMPARE_OP,
3584 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3585 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3586 NEXT_BLOCK(c);
3587 }
3588 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3589 ADDOP_I(c, COMPARE_OP,
3590 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 basicblock *end = compiler_new_block(c);
3592 if (end == NULL)
3593 return 0;
3594 ADDOP_JREL(c, JUMP_FORWARD, end);
3595 compiler_use_next_block(c, cleanup);
3596 ADDOP(c, ROT_TWO);
3597 ADDOP(c, POP_TOP);
3598 compiler_use_next_block(c, end);
3599 }
3600 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601}
3602
3603static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003604maybe_optimize_method_call(struct compiler *c, expr_ty e)
3605{
3606 Py_ssize_t argsl, i;
3607 expr_ty meth = e->v.Call.func;
3608 asdl_seq *args = e->v.Call.args;
3609
3610 /* Check that the call node is an attribute access, and that
3611 the call doesn't have keyword parameters. */
3612 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3613 asdl_seq_LEN(e->v.Call.keywords))
3614 return -1;
3615
3616 /* Check that there are no *varargs types of arguments. */
3617 argsl = asdl_seq_LEN(args);
3618 for (i = 0; i < argsl; i++) {
3619 expr_ty elt = asdl_seq_GET(args, i);
3620 if (elt->kind == Starred_kind) {
3621 return -1;
3622 }
3623 }
3624
3625 /* Alright, we can optimize the code. */
3626 VISIT(c, expr, meth->v.Attribute.value);
3627 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3628 VISIT_SEQ(c, expr, e->v.Call.args);
3629 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3630 return 1;
3631}
3632
3633static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634compiler_call(struct compiler *c, expr_ty e)
3635{
Yury Selivanovf2392132016-12-13 19:03:51 -05003636 if (maybe_optimize_method_call(c, e) > 0)
3637 return 1;
3638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 VISIT(c, expr, e->v.Call.func);
3640 return compiler_call_helper(c, 0,
3641 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003642 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003643}
3644
Eric V. Smith235a6f02015-09-19 14:51:32 -04003645static int
3646compiler_joined_str(struct compiler *c, expr_ty e)
3647{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003648 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003649 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3650 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003651 return 1;
3652}
3653
Eric V. Smitha78c7952015-11-03 12:45:05 -05003654/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003655static int
3656compiler_formatted_value(struct compiler *c, expr_ty e)
3657{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003658 /* Our oparg encodes 2 pieces of information: the conversion
3659 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003660
Eric V. Smitha78c7952015-11-03 12:45:05 -05003661 Convert the conversion char to 2 bits:
3662 None: 000 0x0 FVC_NONE
3663 !s : 001 0x1 FVC_STR
3664 !r : 010 0x2 FVC_REPR
3665 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003666
Eric V. Smitha78c7952015-11-03 12:45:05 -05003667 next bit is whether or not we have a format spec:
3668 yes : 100 0x4
3669 no : 000 0x0
3670 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003671
Eric V. Smitha78c7952015-11-03 12:45:05 -05003672 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003673
Eric V. Smitha78c7952015-11-03 12:45:05 -05003674 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003675 VISIT(c, expr, e->v.FormattedValue.value);
3676
Eric V. Smitha78c7952015-11-03 12:45:05 -05003677 switch (e->v.FormattedValue.conversion) {
3678 case 's': oparg = FVC_STR; break;
3679 case 'r': oparg = FVC_REPR; break;
3680 case 'a': oparg = FVC_ASCII; break;
3681 case -1: oparg = FVC_NONE; break;
3682 default:
3683 PyErr_SetString(PyExc_SystemError,
3684 "Unrecognized conversion character");
3685 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003686 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003687 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003688 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003689 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003690 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003691 }
3692
Eric V. Smitha78c7952015-11-03 12:45:05 -05003693 /* And push our opcode and oparg */
3694 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003695 return 1;
3696}
3697
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003698static int
3699compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3700{
3701 Py_ssize_t i, n = end - begin;
3702 keyword_ty kw;
3703 PyObject *keys, *key;
3704 assert(n > 0);
3705 if (n > 1) {
3706 for (i = begin; i < end; i++) {
3707 kw = asdl_seq_GET(keywords, i);
3708 VISIT(c, expr, kw->value);
3709 }
3710 keys = PyTuple_New(n);
3711 if (keys == NULL) {
3712 return 0;
3713 }
3714 for (i = begin; i < end; i++) {
3715 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3716 Py_INCREF(key);
3717 PyTuple_SET_ITEM(keys, i - begin, key);
3718 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003719 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003720 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3721 }
3722 else {
3723 /* a for loop only executes once */
3724 for (i = begin; i < end; i++) {
3725 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003726 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003727 VISIT(c, expr, kw->value);
3728 }
3729 ADDOP_I(c, BUILD_MAP, n);
3730 }
3731 return 1;
3732}
3733
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003734/* shared code between compiler_call and compiler_class */
3735static int
3736compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003737 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003738 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003740{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003741 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003742 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003743
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003744 /* the number of tuples and dictionaries on the stack */
3745 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3746
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003747 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003748 nkwelts = asdl_seq_LEN(keywords);
3749
3750 for (i = 0; i < nkwelts; i++) {
3751 keyword_ty kw = asdl_seq_GET(keywords, i);
3752 if (kw->arg == NULL) {
3753 mustdictunpack = 1;
3754 break;
3755 }
3756 }
3757
3758 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003759 for (i = 0; i < nelts; i++) {
3760 expr_ty elt = asdl_seq_GET(args, i);
3761 if (elt->kind == Starred_kind) {
3762 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003763 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003764 if (nseen) {
3765 ADDOP_I(c, BUILD_TUPLE, nseen);
3766 nseen = 0;
3767 nsubargs++;
3768 }
3769 VISIT(c, expr, elt->v.Starred.value);
3770 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003771 }
3772 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003774 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003777
3778 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003779 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003780 if (nseen) {
3781 /* Pack up any trailing positional arguments. */
3782 ADDOP_I(c, BUILD_TUPLE, nseen);
3783 nsubargs++;
3784 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003785 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003786 /* If we ended up with more than one stararg, we need
3787 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003788 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003789 }
3790 else if (nsubargs == 0) {
3791 ADDOP_I(c, BUILD_TUPLE, 0);
3792 }
3793 nseen = 0; /* the number of keyword arguments on the stack following */
3794 for (i = 0; i < nkwelts; i++) {
3795 keyword_ty kw = asdl_seq_GET(keywords, i);
3796 if (kw->arg == NULL) {
3797 /* A keyword argument unpacking. */
3798 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003799 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3800 return 0;
3801 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003802 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003803 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003804 VISIT(c, expr, kw->value);
3805 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003806 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003807 else {
3808 nseen++;
3809 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003811 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003812 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003813 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003814 return 0;
3815 nsubkwargs++;
3816 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003817 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003819 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003820 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003821 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3822 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003824 else if (nkwelts) {
3825 PyObject *names;
3826 VISIT_SEQ(c, keyword, keywords);
3827 names = PyTuple_New(nkwelts);
3828 if (names == NULL) {
3829 return 0;
3830 }
3831 for (i = 0; i < nkwelts; i++) {
3832 keyword_ty kw = asdl_seq_GET(keywords, i);
3833 Py_INCREF(kw->arg);
3834 PyTuple_SET_ITEM(names, i, kw->arg);
3835 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003836 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003837 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3838 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003840 else {
3841 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3842 return 1;
3843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844}
3845
Nick Coghlan650f0d02007-04-15 12:05:43 +00003846
3847/* List and set comprehensions and generator expressions work by creating a
3848 nested function to perform the actual iteration. This means that the
3849 iteration variables don't leak into the current scope.
3850 The defined function is called immediately following its definition, with the
3851 result of that call being the result of the expression.
3852 The LC/SC version returns the populated container, while the GE version is
3853 flagged in symtable.c as a generator, so it returns the generator object
3854 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003855
3856 Possible cleanups:
3857 - iterate over the generator sequence instead of using recursion
3858*/
3859
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003860
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862compiler_comprehension_generator(struct compiler *c,
3863 asdl_seq *generators, int gen_index,
3864 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003866 comprehension_ty gen;
3867 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3868 if (gen->is_async) {
3869 return compiler_async_comprehension_generator(
3870 c, generators, gen_index, elt, val, type);
3871 } else {
3872 return compiler_sync_comprehension_generator(
3873 c, generators, gen_index, elt, val, type);
3874 }
3875}
3876
3877static int
3878compiler_sync_comprehension_generator(struct compiler *c,
3879 asdl_seq *generators, int gen_index,
3880 expr_ty elt, expr_ty val, int type)
3881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* generate code for the iterator, then each of the ifs,
3883 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 comprehension_ty gen;
3886 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003887 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 start = compiler_new_block(c);
3890 skip = compiler_new_block(c);
3891 if_cleanup = compiler_new_block(c);
3892 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3895 anchor == NULL)
3896 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 if (gen_index == 0) {
3901 /* Receive outermost iter as an implicit argument */
3902 c->u->u_argcount = 1;
3903 ADDOP_I(c, LOAD_FAST, 0);
3904 }
3905 else {
3906 /* Sub-iter - calculate on the fly */
3907 VISIT(c, expr, gen->iter);
3908 ADDOP(c, GET_ITER);
3909 }
3910 compiler_use_next_block(c, start);
3911 ADDOP_JREL(c, FOR_ITER, anchor);
3912 NEXT_BLOCK(c);
3913 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 /* XXX this needs to be cleaned up...a lot! */
3916 n = asdl_seq_LEN(gen->ifs);
3917 for (i = 0; i < n; i++) {
3918 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003919 if (!compiler_jump_if(c, e, if_cleanup, 0))
3920 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 NEXT_BLOCK(c);
3922 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 if (++gen_index < asdl_seq_LEN(generators))
3925 if (!compiler_comprehension_generator(c,
3926 generators, gen_index,
3927 elt, val, type))
3928 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 /* only append after the last for generator */
3931 if (gen_index >= asdl_seq_LEN(generators)) {
3932 /* comprehension specific code */
3933 switch (type) {
3934 case COMP_GENEXP:
3935 VISIT(c, expr, elt);
3936 ADDOP(c, YIELD_VALUE);
3937 ADDOP(c, POP_TOP);
3938 break;
3939 case COMP_LISTCOMP:
3940 VISIT(c, expr, elt);
3941 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3942 break;
3943 case COMP_SETCOMP:
3944 VISIT(c, expr, elt);
3945 ADDOP_I(c, SET_ADD, gen_index + 1);
3946 break;
3947 case COMP_DICTCOMP:
3948 /* With 'd[k] = v', v is evaluated before k, so we do
3949 the same. */
3950 VISIT(c, expr, val);
3951 VISIT(c, expr, elt);
3952 ADDOP_I(c, MAP_ADD, gen_index + 1);
3953 break;
3954 default:
3955 return 0;
3956 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 compiler_use_next_block(c, skip);
3959 }
3960 compiler_use_next_block(c, if_cleanup);
3961 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3962 compiler_use_next_block(c, anchor);
3963
3964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003965}
3966
3967static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968compiler_async_comprehension_generator(struct compiler *c,
3969 asdl_seq *generators, int gen_index,
3970 expr_ty elt, expr_ty val, int type)
3971{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003973 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003974 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003975 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003976 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003977 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003978
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003979 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003980 return 0;
3981 }
3982
3983 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3984
3985 if (gen_index == 0) {
3986 /* Receive outermost iter as an implicit argument */
3987 c->u->u_argcount = 1;
3988 ADDOP_I(c, LOAD_FAST, 0);
3989 }
3990 else {
3991 /* Sub-iter - calculate on the fly */
3992 VISIT(c, expr, gen->iter);
3993 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003994 }
3995
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003996 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003997
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003998 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003999 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004000 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004001 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004002 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004003 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004004
4005 n = asdl_seq_LEN(gen->ifs);
4006 for (i = 0; i < n; i++) {
4007 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004008 if (!compiler_jump_if(c, e, if_cleanup, 0))
4009 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004010 NEXT_BLOCK(c);
4011 }
4012
4013 if (++gen_index < asdl_seq_LEN(generators))
4014 if (!compiler_comprehension_generator(c,
4015 generators, gen_index,
4016 elt, val, type))
4017 return 0;
4018
4019 /* only append after the last for generator */
4020 if (gen_index >= asdl_seq_LEN(generators)) {
4021 /* comprehension specific code */
4022 switch (type) {
4023 case COMP_GENEXP:
4024 VISIT(c, expr, elt);
4025 ADDOP(c, YIELD_VALUE);
4026 ADDOP(c, POP_TOP);
4027 break;
4028 case COMP_LISTCOMP:
4029 VISIT(c, expr, elt);
4030 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4031 break;
4032 case COMP_SETCOMP:
4033 VISIT(c, expr, elt);
4034 ADDOP_I(c, SET_ADD, gen_index + 1);
4035 break;
4036 case COMP_DICTCOMP:
4037 /* With 'd[k] = v', v is evaluated before k, so we do
4038 the same. */
4039 VISIT(c, expr, val);
4040 VISIT(c, expr, elt);
4041 ADDOP_I(c, MAP_ADD, gen_index + 1);
4042 break;
4043 default:
4044 return 0;
4045 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004046 }
4047 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004048 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4049
4050 compiler_use_next_block(c, except);
4051 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004052
4053 return 1;
4054}
4055
4056static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004057compiler_comprehension(struct compiler *c, expr_ty e, int type,
4058 identifier name, asdl_seq *generators, expr_ty elt,
4059 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004062 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004063 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004064 int is_async_function = c->u->u_ste->ste_coroutine;
4065 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004066
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004067 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004068
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004069 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4070 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004071 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004073 }
4074
4075 is_async_generator = c->u->u_ste->ste_coroutine;
4076
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004077 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004078 if (e->lineno > c->u->u_lineno) {
4079 c->u->u_lineno = e->lineno;
4080 c->u->u_lineno_set = 0;
4081 }
4082 compiler_error(c, "asynchronous comprehension outside of "
4083 "an asynchronous function");
4084 goto error_in_scope;
4085 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 if (type != COMP_GENEXP) {
4088 int op;
4089 switch (type) {
4090 case COMP_LISTCOMP:
4091 op = BUILD_LIST;
4092 break;
4093 case COMP_SETCOMP:
4094 op = BUILD_SET;
4095 break;
4096 case COMP_DICTCOMP:
4097 op = BUILD_MAP;
4098 break;
4099 default:
4100 PyErr_Format(PyExc_SystemError,
4101 "unknown comprehension type %d", type);
4102 goto error_in_scope;
4103 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 ADDOP_I(c, op, 0);
4106 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 if (!compiler_comprehension_generator(c, generators, 0, elt,
4109 val, type))
4110 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 if (type != COMP_GENEXP) {
4113 ADDOP(c, RETURN_VALUE);
4114 }
4115
4116 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004117 qualname = c->u->u_qualname;
4118 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004120 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 goto error;
4122
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004123 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004125 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 Py_DECREF(co);
4127
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004128 VISIT(c, expr, outermost->iter);
4129
4130 if (outermost->is_async) {
4131 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004132 } else {
4133 ADDOP(c, GET_ITER);
4134 }
4135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004137
4138 if (is_async_generator && type != COMP_GENEXP) {
4139 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004140 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004141 ADDOP(c, YIELD_FROM);
4142 }
4143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004145error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004147error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004148 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 Py_XDECREF(co);
4150 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004151}
4152
4153static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154compiler_genexp(struct compiler *c, expr_ty e)
4155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 static identifier name;
4157 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004158 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 if (!name)
4160 return 0;
4161 }
4162 assert(e->kind == GeneratorExp_kind);
4163 return compiler_comprehension(c, e, COMP_GENEXP, name,
4164 e->v.GeneratorExp.generators,
4165 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166}
4167
4168static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004169compiler_listcomp(struct compiler *c, expr_ty e)
4170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 static identifier name;
4172 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004173 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 if (!name)
4175 return 0;
4176 }
4177 assert(e->kind == ListComp_kind);
4178 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4179 e->v.ListComp.generators,
4180 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004181}
4182
4183static int
4184compiler_setcomp(struct compiler *c, expr_ty e)
4185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 static identifier name;
4187 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004188 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 if (!name)
4190 return 0;
4191 }
4192 assert(e->kind == SetComp_kind);
4193 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4194 e->v.SetComp.generators,
4195 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004196}
4197
4198
4199static int
4200compiler_dictcomp(struct compiler *c, expr_ty e)
4201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 static identifier name;
4203 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004204 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 if (!name)
4206 return 0;
4207 }
4208 assert(e->kind == DictComp_kind);
4209 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4210 e->v.DictComp.generators,
4211 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004212}
4213
4214
4215static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004216compiler_visit_keyword(struct compiler *c, keyword_ty k)
4217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 VISIT(c, expr, k->value);
4219 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220}
4221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004223 whether they are true or false.
4224
4225 Return values: 1 for true, 0 for false, -1 for non-constant.
4226 */
4227
4228static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004229expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004231 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004232 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004233 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004234 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004235}
4236
Yury Selivanov75445082015-05-11 22:57:16 -04004237
4238/*
4239 Implements the async with statement.
4240
4241 The semantics outlined in that PEP are as follows:
4242
4243 async with EXPR as VAR:
4244 BLOCK
4245
4246 It is implemented roughly as:
4247
4248 context = EXPR
4249 exit = context.__aexit__ # not calling it
4250 value = await context.__aenter__()
4251 try:
4252 VAR = value # if VAR present in the syntax
4253 BLOCK
4254 finally:
4255 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004256 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004257 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004258 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004259 if not (await exit(*exc)):
4260 raise
4261 */
4262static int
4263compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4264{
4265 basicblock *block, *finally;
4266 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4267
4268 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004269 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4270 return compiler_error(c, "'async with' outside async function");
4271 }
Yury Selivanov75445082015-05-11 22:57:16 -04004272
4273 block = compiler_new_block(c);
4274 finally = compiler_new_block(c);
4275 if (!block || !finally)
4276 return 0;
4277
4278 /* Evaluate EXPR */
4279 VISIT(c, expr, item->context_expr);
4280
4281 ADDOP(c, BEFORE_ASYNC_WITH);
4282 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004283 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004284 ADDOP(c, YIELD_FROM);
4285
4286 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4287
4288 /* SETUP_ASYNC_WITH pushes a finally block. */
4289 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004290 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004291 return 0;
4292 }
4293
4294 if (item->optional_vars) {
4295 VISIT(c, expr, item->optional_vars);
4296 }
4297 else {
4298 /* Discard result from context.__aenter__() */
4299 ADDOP(c, POP_TOP);
4300 }
4301
4302 pos++;
4303 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4304 /* BLOCK code */
4305 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4306 else if (!compiler_async_with(c, s, pos))
4307 return 0;
4308
4309 /* End of try block; start the finally block */
4310 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004311 ADDOP(c, BEGIN_FINALLY);
4312 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004313
Yury Selivanov75445082015-05-11 22:57:16 -04004314 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004315 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004316 return 0;
4317
4318 /* Finally block starts; context.__exit__ is on the stack under
4319 the exception or return information. Just issue our magic
4320 opcode. */
4321 ADDOP(c, WITH_CLEANUP_START);
4322
4323 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004324 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004325 ADDOP(c, YIELD_FROM);
4326
4327 ADDOP(c, WITH_CLEANUP_FINISH);
4328
4329 /* Finally block ends. */
4330 ADDOP(c, END_FINALLY);
4331 compiler_pop_fblock(c, FINALLY_END, finally);
4332 return 1;
4333}
4334
4335
Guido van Rossumc2e20742006-02-27 22:32:47 +00004336/*
4337 Implements the with statement from PEP 343.
4338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004340
4341 with EXPR as VAR:
4342 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343
Guido van Rossumc2e20742006-02-27 22:32:47 +00004344 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345
Thomas Wouters477c8d52006-05-27 19:21:47 +00004346 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004347 exit = context.__exit__ # not calling it
4348 value = context.__enter__()
4349 try:
4350 VAR = value # if VAR present in the syntax
4351 BLOCK
4352 finally:
4353 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004354 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004355 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004356 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004357 exit(*exc)
4358 */
4359static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004360compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004361{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004362 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004363 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004364
4365 assert(s->kind == With_kind);
4366
Guido van Rossumc2e20742006-02-27 22:32:47 +00004367 block = compiler_new_block(c);
4368 finally = compiler_new_block(c);
4369 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004370 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004371
Thomas Wouters477c8d52006-05-27 19:21:47 +00004372 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004373 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004374 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004375
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004376 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004377 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004378 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004379 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004380 }
4381
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004382 if (item->optional_vars) {
4383 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004384 }
4385 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004387 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004388 }
4389
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004390 pos++;
4391 if (pos == asdl_seq_LEN(s->v.With.items))
4392 /* BLOCK code */
4393 VISIT_SEQ(c, stmt, s->v.With.body)
4394 else if (!compiler_with(c, s, pos))
4395 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004396
4397 /* End of try block; start the finally block */
4398 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004399 ADDOP(c, BEGIN_FINALLY);
4400 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004401
Guido van Rossumc2e20742006-02-27 22:32:47 +00004402 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004403 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004404 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004405
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004406 /* Finally block starts; context.__exit__ is on the stack under
4407 the exception or return information. Just issue our magic
4408 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004409 ADDOP(c, WITH_CLEANUP_START);
4410 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004411
4412 /* Finally block ends. */
4413 ADDOP(c, END_FINALLY);
4414 compiler_pop_fblock(c, FINALLY_END, finally);
4415 return 1;
4416}
4417
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004418static int
4419compiler_visit_expr(struct compiler *c, expr_ty e)
4420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 /* If expr e has a different line number than the last expr/stmt,
4422 set a new line number for the next instruction.
4423 */
4424 if (e->lineno > c->u->u_lineno) {
4425 c->u->u_lineno = e->lineno;
4426 c->u->u_lineno_set = 0;
4427 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004428 /* Updating the column offset is always harmless. */
4429 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 switch (e->kind) {
4431 case BoolOp_kind:
4432 return compiler_boolop(c, e);
4433 case BinOp_kind:
4434 VISIT(c, expr, e->v.BinOp.left);
4435 VISIT(c, expr, e->v.BinOp.right);
4436 ADDOP(c, binop(c, e->v.BinOp.op));
4437 break;
4438 case UnaryOp_kind:
4439 VISIT(c, expr, e->v.UnaryOp.operand);
4440 ADDOP(c, unaryop(e->v.UnaryOp.op));
4441 break;
4442 case Lambda_kind:
4443 return compiler_lambda(c, e);
4444 case IfExp_kind:
4445 return compiler_ifexp(c, e);
4446 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004447 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004449 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 case GeneratorExp_kind:
4451 return compiler_genexp(c, e);
4452 case ListComp_kind:
4453 return compiler_listcomp(c, e);
4454 case SetComp_kind:
4455 return compiler_setcomp(c, e);
4456 case DictComp_kind:
4457 return compiler_dictcomp(c, e);
4458 case Yield_kind:
4459 if (c->u->u_ste->ste_type != FunctionBlock)
4460 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004461 if (e->v.Yield.value) {
4462 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 }
4464 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004465 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004467 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004469 case YieldFrom_kind:
4470 if (c->u->u_ste->ste_type != FunctionBlock)
4471 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004472
4473 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4474 return compiler_error(c, "'yield from' inside async function");
4475
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004476 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004477 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004478 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004479 ADDOP(c, YIELD_FROM);
4480 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004481 case Await_kind:
4482 if (c->u->u_ste->ste_type != FunctionBlock)
4483 return compiler_error(c, "'await' outside function");
4484
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004485 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4486 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004487 return compiler_error(c, "'await' outside async function");
4488
4489 VISIT(c, expr, e->v.Await.value);
4490 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004491 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004492 ADDOP(c, YIELD_FROM);
4493 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 case Compare_kind:
4495 return compiler_compare(c, e);
4496 case Call_kind:
4497 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004498 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004499 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004500 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 case Num_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004502 ADDOP_LOAD_CONST(c, e->v.Num.n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 break;
4504 case Str_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004505 ADDOP_LOAD_CONST(c, e->v.Str.s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004507 case JoinedStr_kind:
4508 return compiler_joined_str(c, e);
4509 case FormattedValue_kind:
4510 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 case Bytes_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004512 ADDOP_LOAD_CONST(c, e->v.Bytes.s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 break;
4514 case Ellipsis_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004515 ADDOP_LOAD_CONST(c, Py_Ellipsis);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004517 case NameConstant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004518 ADDOP_LOAD_CONST(c, e->v.NameConstant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004519 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 /* The following exprs can be assignment targets. */
4521 case Attribute_kind:
4522 if (e->v.Attribute.ctx != AugStore)
4523 VISIT(c, expr, e->v.Attribute.value);
4524 switch (e->v.Attribute.ctx) {
4525 case AugLoad:
4526 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004527 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 case Load:
4529 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4530 break;
4531 case AugStore:
4532 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004533 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 case Store:
4535 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4536 break;
4537 case Del:
4538 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4539 break;
4540 case Param:
4541 default:
4542 PyErr_SetString(PyExc_SystemError,
4543 "param invalid in attribute expression");
4544 return 0;
4545 }
4546 break;
4547 case Subscript_kind:
4548 switch (e->v.Subscript.ctx) {
4549 case AugLoad:
4550 VISIT(c, expr, e->v.Subscript.value);
4551 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4552 break;
4553 case Load:
4554 VISIT(c, expr, e->v.Subscript.value);
4555 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4556 break;
4557 case AugStore:
4558 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4559 break;
4560 case Store:
4561 VISIT(c, expr, e->v.Subscript.value);
4562 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4563 break;
4564 case Del:
4565 VISIT(c, expr, e->v.Subscript.value);
4566 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4567 break;
4568 case Param:
4569 default:
4570 PyErr_SetString(PyExc_SystemError,
4571 "param invalid in subscript expression");
4572 return 0;
4573 }
4574 break;
4575 case Starred_kind:
4576 switch (e->v.Starred.ctx) {
4577 case Store:
4578 /* In all legitimate cases, the Starred node was already replaced
4579 * by compiler_list/compiler_tuple. XXX: is that okay? */
4580 return compiler_error(c,
4581 "starred assignment target must be in a list or tuple");
4582 default:
4583 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004584 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 }
4586 break;
4587 case Name_kind:
4588 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4589 /* child nodes of List and Tuple will have expr_context set */
4590 case List_kind:
4591 return compiler_list(c, e);
4592 case Tuple_kind:
4593 return compiler_tuple(c, e);
4594 }
4595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004596}
4597
4598static int
4599compiler_augassign(struct compiler *c, stmt_ty s)
4600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 expr_ty e = s->v.AugAssign.target;
4602 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 switch (e->kind) {
4607 case Attribute_kind:
4608 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4609 AugLoad, e->lineno, e->col_offset, c->c_arena);
4610 if (auge == NULL)
4611 return 0;
4612 VISIT(c, expr, auge);
4613 VISIT(c, expr, s->v.AugAssign.value);
4614 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4615 auge->v.Attribute.ctx = AugStore;
4616 VISIT(c, expr, auge);
4617 break;
4618 case Subscript_kind:
4619 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4620 AugLoad, e->lineno, e->col_offset, c->c_arena);
4621 if (auge == NULL)
4622 return 0;
4623 VISIT(c, expr, auge);
4624 VISIT(c, expr, s->v.AugAssign.value);
4625 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4626 auge->v.Subscript.ctx = AugStore;
4627 VISIT(c, expr, auge);
4628 break;
4629 case Name_kind:
4630 if (!compiler_nameop(c, e->v.Name.id, Load))
4631 return 0;
4632 VISIT(c, expr, s->v.AugAssign.value);
4633 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4634 return compiler_nameop(c, e->v.Name.id, Store);
4635 default:
4636 PyErr_Format(PyExc_SystemError,
4637 "invalid node type (%d) for augmented assignment",
4638 e->kind);
4639 return 0;
4640 }
4641 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004642}
4643
4644static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004645check_ann_expr(struct compiler *c, expr_ty e)
4646{
4647 VISIT(c, expr, e);
4648 ADDOP(c, POP_TOP);
4649 return 1;
4650}
4651
4652static int
4653check_annotation(struct compiler *c, stmt_ty s)
4654{
4655 /* Annotations are only evaluated in a module or class. */
4656 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4657 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4658 return check_ann_expr(c, s->v.AnnAssign.annotation);
4659 }
4660 return 1;
4661}
4662
4663static int
4664check_ann_slice(struct compiler *c, slice_ty sl)
4665{
4666 switch(sl->kind) {
4667 case Index_kind:
4668 return check_ann_expr(c, sl->v.Index.value);
4669 case Slice_kind:
4670 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4671 return 0;
4672 }
4673 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4674 return 0;
4675 }
4676 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4677 return 0;
4678 }
4679 break;
4680 default:
4681 PyErr_SetString(PyExc_SystemError,
4682 "unexpected slice kind");
4683 return 0;
4684 }
4685 return 1;
4686}
4687
4688static int
4689check_ann_subscr(struct compiler *c, slice_ty sl)
4690{
4691 /* We check that everything in a subscript is defined at runtime. */
4692 Py_ssize_t i, n;
4693
4694 switch (sl->kind) {
4695 case Index_kind:
4696 case Slice_kind:
4697 if (!check_ann_slice(c, sl)) {
4698 return 0;
4699 }
4700 break;
4701 case ExtSlice_kind:
4702 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4703 for (i = 0; i < n; i++) {
4704 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4705 switch (subsl->kind) {
4706 case Index_kind:
4707 case Slice_kind:
4708 if (!check_ann_slice(c, subsl)) {
4709 return 0;
4710 }
4711 break;
4712 case ExtSlice_kind:
4713 default:
4714 PyErr_SetString(PyExc_SystemError,
4715 "extended slice invalid in nested slice");
4716 return 0;
4717 }
4718 }
4719 break;
4720 default:
4721 PyErr_Format(PyExc_SystemError,
4722 "invalid subscript kind %d", sl->kind);
4723 return 0;
4724 }
4725 return 1;
4726}
4727
4728static int
4729compiler_annassign(struct compiler *c, stmt_ty s)
4730{
4731 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004732 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004733
4734 assert(s->kind == AnnAssign_kind);
4735
4736 /* We perform the actual assignment first. */
4737 if (s->v.AnnAssign.value) {
4738 VISIT(c, expr, s->v.AnnAssign.value);
4739 VISIT(c, expr, targ);
4740 }
4741 switch (targ->kind) {
4742 case Name_kind:
4743 /* If we have a simple name in a module or class, store annotation. */
4744 if (s->v.AnnAssign.simple &&
4745 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4746 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004747 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4748 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4749 }
4750 else {
4751 VISIT(c, expr, s->v.AnnAssign.annotation);
4752 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004753 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004754 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004755 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004756 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004757 }
4758 break;
4759 case Attribute_kind:
4760 if (!s->v.AnnAssign.value &&
4761 !check_ann_expr(c, targ->v.Attribute.value)) {
4762 return 0;
4763 }
4764 break;
4765 case Subscript_kind:
4766 if (!s->v.AnnAssign.value &&
4767 (!check_ann_expr(c, targ->v.Subscript.value) ||
4768 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4769 return 0;
4770 }
4771 break;
4772 default:
4773 PyErr_Format(PyExc_SystemError,
4774 "invalid node type (%d) for annotated assignment",
4775 targ->kind);
4776 return 0;
4777 }
4778 /* Annotation is evaluated last. */
4779 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4780 return 0;
4781 }
4782 return 1;
4783}
4784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004785/* Raises a SyntaxError and returns 0.
4786 If something goes wrong, a different exception may be raised.
4787*/
4788
4789static int
4790compiler_error(struct compiler *c, const char *errstr)
4791{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004792 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004794
Victor Stinner14e461d2013-08-26 22:28:21 +02004795 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 if (!loc) {
4797 Py_INCREF(Py_None);
4798 loc = Py_None;
4799 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004800 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004801 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 if (!u)
4803 goto exit;
4804 v = Py_BuildValue("(zO)", errstr, u);
4805 if (!v)
4806 goto exit;
4807 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004808 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 Py_DECREF(loc);
4810 Py_XDECREF(u);
4811 Py_XDECREF(v);
4812 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004813}
4814
4815static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816compiler_handle_subscr(struct compiler *c, const char *kind,
4817 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 /* XXX this code is duplicated */
4822 switch (ctx) {
4823 case AugLoad: /* fall through to Load */
4824 case Load: op = BINARY_SUBSCR; break;
4825 case AugStore:/* fall through to Store */
4826 case Store: op = STORE_SUBSCR; break;
4827 case Del: op = DELETE_SUBSCR; break;
4828 case Param:
4829 PyErr_Format(PyExc_SystemError,
4830 "invalid %s kind %d in subscript\n",
4831 kind, ctx);
4832 return 0;
4833 }
4834 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004835 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 }
4837 else if (ctx == AugStore) {
4838 ADDOP(c, ROT_THREE);
4839 }
4840 ADDOP(c, op);
4841 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004842}
4843
4844static int
4845compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 int n = 2;
4848 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 /* only handles the cases where BUILD_SLICE is emitted */
4851 if (s->v.Slice.lower) {
4852 VISIT(c, expr, s->v.Slice.lower);
4853 }
4854 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004855 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 if (s->v.Slice.upper) {
4859 VISIT(c, expr, s->v.Slice.upper);
4860 }
4861 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004862 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 }
4864
4865 if (s->v.Slice.step) {
4866 n++;
4867 VISIT(c, expr, s->v.Slice.step);
4868 }
4869 ADDOP_I(c, BUILD_SLICE, n);
4870 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004871}
4872
4873static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4875 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 switch (s->kind) {
4878 case Slice_kind:
4879 return compiler_slice(c, s, ctx);
4880 case Index_kind:
4881 VISIT(c, expr, s->v.Index.value);
4882 break;
4883 case ExtSlice_kind:
4884 default:
4885 PyErr_SetString(PyExc_SystemError,
4886 "extended slice invalid in nested slice");
4887 return 0;
4888 }
4889 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004890}
4891
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004892static int
4893compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4894{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004895 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 switch (s->kind) {
4897 case Index_kind:
4898 kindname = "index";
4899 if (ctx != AugStore) {
4900 VISIT(c, expr, s->v.Index.value);
4901 }
4902 break;
4903 case Slice_kind:
4904 kindname = "slice";
4905 if (ctx != AugStore) {
4906 if (!compiler_slice(c, s, ctx))
4907 return 0;
4908 }
4909 break;
4910 case ExtSlice_kind:
4911 kindname = "extended slice";
4912 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004913 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 for (i = 0; i < n; i++) {
4915 slice_ty sub = (slice_ty)asdl_seq_GET(
4916 s->v.ExtSlice.dims, i);
4917 if (!compiler_visit_nested_slice(c, sub, ctx))
4918 return 0;
4919 }
4920 ADDOP_I(c, BUILD_TUPLE, n);
4921 }
4922 break;
4923 default:
4924 PyErr_Format(PyExc_SystemError,
4925 "invalid subscript kind %d", s->kind);
4926 return 0;
4927 }
4928 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004929}
4930
Thomas Wouters89f507f2006-12-13 04:49:30 +00004931/* End of the compiler section, beginning of the assembler section */
4932
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004933/* do depth-first search of basic block graph, starting with block.
4934 post records the block indices in post-order.
4935
4936 XXX must handle implicit jumps from one block to next
4937*/
4938
Thomas Wouters89f507f2006-12-13 04:49:30 +00004939struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 PyObject *a_bytecode; /* string containing bytecode */
4941 int a_offset; /* offset into bytecode */
4942 int a_nblocks; /* number of reachable blocks */
4943 basicblock **a_postorder; /* list of blocks in dfs postorder */
4944 PyObject *a_lnotab; /* string containing lnotab */
4945 int a_lnotab_off; /* offset into lnotab */
4946 int a_lineno; /* last lineno of emitted instruction */
4947 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004948};
4949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004950static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004951dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004952{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004953 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004954
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004955 /* Get rid of recursion for normal control flow.
4956 Since the number of blocks is limited, unused space in a_postorder
4957 (from a_nblocks to end) can be used as a stack for still not ordered
4958 blocks. */
4959 for (j = end; b && !b->b_seen; b = b->b_next) {
4960 b->b_seen = 1;
4961 assert(a->a_nblocks < j);
4962 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004964 while (j < end) {
4965 b = a->a_postorder[j++];
4966 for (i = 0; i < b->b_iused; i++) {
4967 struct instr *instr = &b->b_instr[i];
4968 if (instr->i_jrel || instr->i_jabs)
4969 dfs(c, instr->i_target, a, j);
4970 }
4971 assert(a->a_nblocks < j);
4972 a->a_postorder[a->a_nblocks++] = b;
4973 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004974}
4975
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004976Py_LOCAL_INLINE(void)
4977stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004979 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004980 if (b->b_startdepth < depth) {
4981 assert(b->b_startdepth < 0);
4982 b->b_startdepth = depth;
4983 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004984 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004985}
4986
4987/* Find the flow path that needs the largest stack. We assume that
4988 * cycles in the flow graph have no net effect on the stack depth.
4989 */
4990static int
4991stackdepth(struct compiler *c)
4992{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004993 basicblock *b, *entryblock = NULL;
4994 basicblock **stack, **sp;
4995 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 b->b_startdepth = INT_MIN;
4998 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004999 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 }
5001 if (!entryblock)
5002 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005003 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5004 if (!stack) {
5005 PyErr_NoMemory();
5006 return -1;
5007 }
5008
5009 sp = stack;
5010 stackdepth_push(&sp, entryblock, 0);
5011 while (sp != stack) {
5012 b = *--sp;
5013 int depth = b->b_startdepth;
5014 assert(depth >= 0);
5015 basicblock *next = b->b_next;
5016 for (int i = 0; i < b->b_iused; i++) {
5017 struct instr *instr = &b->b_instr[i];
5018 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5019 if (effect == PY_INVALID_STACK_EFFECT) {
5020 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5021 Py_FatalError("PyCompile_OpcodeStackEffect()");
5022 }
5023 int new_depth = depth + effect;
5024 if (new_depth > maxdepth) {
5025 maxdepth = new_depth;
5026 }
5027 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5028 if (instr->i_jrel || instr->i_jabs) {
5029 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5030 assert(effect != PY_INVALID_STACK_EFFECT);
5031 int target_depth = depth + effect;
5032 if (target_depth > maxdepth) {
5033 maxdepth = target_depth;
5034 }
5035 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005036 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005037 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005038 assert(instr->i_target->b_startdepth >= target_depth);
5039 depth = new_depth;
5040 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005041 }
5042 stackdepth_push(&sp, instr->i_target, target_depth);
5043 }
5044 depth = new_depth;
5045 if (instr->i_opcode == JUMP_ABSOLUTE ||
5046 instr->i_opcode == JUMP_FORWARD ||
5047 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005048 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005049 {
5050 /* remaining code is dead */
5051 next = NULL;
5052 break;
5053 }
5054 }
5055 if (next != NULL) {
5056 stackdepth_push(&sp, next, depth);
5057 }
5058 }
5059 PyObject_Free(stack);
5060 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005061}
5062
5063static int
5064assemble_init(struct assembler *a, int nblocks, int firstlineno)
5065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 memset(a, 0, sizeof(struct assembler));
5067 a->a_lineno = firstlineno;
5068 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5069 if (!a->a_bytecode)
5070 return 0;
5071 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5072 if (!a->a_lnotab)
5073 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005074 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 PyErr_NoMemory();
5076 return 0;
5077 }
5078 a->a_postorder = (basicblock **)PyObject_Malloc(
5079 sizeof(basicblock *) * nblocks);
5080 if (!a->a_postorder) {
5081 PyErr_NoMemory();
5082 return 0;
5083 }
5084 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005085}
5086
5087static void
5088assemble_free(struct assembler *a)
5089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 Py_XDECREF(a->a_bytecode);
5091 Py_XDECREF(a->a_lnotab);
5092 if (a->a_postorder)
5093 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005094}
5095
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005096static int
5097blocksize(basicblock *b)
5098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 int i;
5100 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005103 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005105}
5106
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005107/* Appends a pair to the end of the line number table, a_lnotab, representing
5108 the instruction's bytecode offset and line number. See
5109 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005110
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005111static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005112assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005115 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005117
Serhiy Storchakaab874002016-09-11 13:48:15 +03005118 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 if(d_bytecode == 0 && d_lineno == 0)
5124 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 if (d_bytecode > 255) {
5127 int j, nbytes, ncodes = d_bytecode / 255;
5128 nbytes = a->a_lnotab_off + 2 * ncodes;
5129 len = PyBytes_GET_SIZE(a->a_lnotab);
5130 if (nbytes >= len) {
5131 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5132 len = nbytes;
5133 else if (len <= INT_MAX / 2)
5134 len *= 2;
5135 else {
5136 PyErr_NoMemory();
5137 return 0;
5138 }
5139 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5140 return 0;
5141 }
5142 lnotab = (unsigned char *)
5143 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5144 for (j = 0; j < ncodes; j++) {
5145 *lnotab++ = 255;
5146 *lnotab++ = 0;
5147 }
5148 d_bytecode -= ncodes * 255;
5149 a->a_lnotab_off += ncodes * 2;
5150 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005151 assert(0 <= d_bytecode && d_bytecode <= 255);
5152
5153 if (d_lineno < -128 || 127 < d_lineno) {
5154 int j, nbytes, ncodes, k;
5155 if (d_lineno < 0) {
5156 k = -128;
5157 /* use division on positive numbers */
5158 ncodes = (-d_lineno) / 128;
5159 }
5160 else {
5161 k = 127;
5162 ncodes = d_lineno / 127;
5163 }
5164 d_lineno -= ncodes * k;
5165 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 nbytes = a->a_lnotab_off + 2 * ncodes;
5167 len = PyBytes_GET_SIZE(a->a_lnotab);
5168 if (nbytes >= len) {
5169 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5170 len = nbytes;
5171 else if (len <= INT_MAX / 2)
5172 len *= 2;
5173 else {
5174 PyErr_NoMemory();
5175 return 0;
5176 }
5177 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5178 return 0;
5179 }
5180 lnotab = (unsigned char *)
5181 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5182 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005183 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 d_bytecode = 0;
5185 for (j = 1; j < ncodes; j++) {
5186 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005187 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 a->a_lnotab_off += ncodes * 2;
5190 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005191 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 len = PyBytes_GET_SIZE(a->a_lnotab);
5194 if (a->a_lnotab_off + 2 >= len) {
5195 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5196 return 0;
5197 }
5198 lnotab = (unsigned char *)
5199 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 a->a_lnotab_off += 2;
5202 if (d_bytecode) {
5203 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005204 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 }
5206 else { /* First line of a block; def stmt, etc. */
5207 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005208 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 }
5210 a->a_lineno = i->i_lineno;
5211 a->a_lineno_off = a->a_offset;
5212 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005213}
5214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005215/* assemble_emit()
5216 Extend the bytecode with a new instruction.
5217 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005218*/
5219
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005220static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005221assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005222{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005223 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005225 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005226
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005227 arg = i->i_oparg;
5228 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 if (i->i_lineno && !assemble_lnotab(a, i))
5230 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005231 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 if (len > PY_SSIZE_T_MAX / 2)
5233 return 0;
5234 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5235 return 0;
5236 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005237 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005239 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005241}
5242
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005243static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005244assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005247 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 /* Compute the size of each block and fixup jump args.
5251 Replace block pointer with position in bytecode. */
5252 do {
5253 totsize = 0;
5254 for (i = a->a_nblocks - 1; i >= 0; i--) {
5255 b = a->a_postorder[i];
5256 bsize = blocksize(b);
5257 b->b_offset = totsize;
5258 totsize += bsize;
5259 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005260 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5262 bsize = b->b_offset;
5263 for (i = 0; i < b->b_iused; i++) {
5264 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005265 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 /* Relative jumps are computed relative to
5267 the instruction pointer after fetching
5268 the jump instruction.
5269 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005270 bsize += isize;
5271 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005273 if (instr->i_jrel) {
5274 instr->i_oparg -= bsize;
5275 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005276 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005277 if (instrsize(instr->i_oparg) != isize) {
5278 extended_arg_recompile = 1;
5279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 }
5282 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 /* XXX: This is an awful hack that could hurt performance, but
5285 on the bright side it should work until we come up
5286 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 The issue is that in the first loop blocksize() is called
5289 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005290 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 So we loop until we stop seeing new EXTENDED_ARGs.
5294 The only EXTENDED_ARGs that could be popping up are
5295 ones in jump instructions. So this should converge
5296 fairly quickly.
5297 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005298 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005299}
5300
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005301static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005302dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005305 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 tuple = PyTuple_New(size);
5308 if (tuple == NULL)
5309 return NULL;
5310 while (PyDict_Next(dict, &pos, &k, &v)) {
5311 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005312 Py_INCREF(k);
5313 assert((i - offset) < size);
5314 assert((i - offset) >= 0);
5315 PyTuple_SET_ITEM(tuple, i - offset, k);
5316 }
5317 return tuple;
5318}
5319
5320static PyObject *
5321consts_dict_keys_inorder(PyObject *dict)
5322{
5323 PyObject *consts, *k, *v;
5324 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5325
5326 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5327 if (consts == NULL)
5328 return NULL;
5329 while (PyDict_Next(dict, &pos, &k, &v)) {
5330 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005331 /* The keys of the dictionary can be tuples wrapping a contant.
5332 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5333 * the object we want is always second. */
5334 if (PyTuple_CheckExact(k)) {
5335 k = PyTuple_GET_ITEM(k, 1);
5336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005338 assert(i < size);
5339 assert(i >= 0);
5340 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005342 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005343}
5344
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005345static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005349 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005351 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 if (ste->ste_nested)
5353 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005354 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005356 if (!ste->ste_generator && ste->ste_coroutine)
5357 flags |= CO_COROUTINE;
5358 if (ste->ste_generator && ste->ste_coroutine)
5359 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 if (ste->ste_varargs)
5361 flags |= CO_VARARGS;
5362 if (ste->ste_varkeywords)
5363 flags |= CO_VARKEYWORDS;
5364 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 /* (Only) inherit compilerflags in PyCF_MASK */
5367 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005370}
5371
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005372static PyCodeObject *
5373makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 PyObject *tmp;
5376 PyCodeObject *co = NULL;
5377 PyObject *consts = NULL;
5378 PyObject *names = NULL;
5379 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 PyObject *name = NULL;
5381 PyObject *freevars = NULL;
5382 PyObject *cellvars = NULL;
5383 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005384 Py_ssize_t nlocals;
5385 int nlocals_int;
5386 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005387 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005388
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005389 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 names = dict_keys_inorder(c->u->u_names, 0);
5391 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5392 if (!consts || !names || !varnames)
5393 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5396 if (!cellvars)
5397 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005398 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 if (!freevars)
5400 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005401
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005402 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005403 assert(nlocals < INT_MAX);
5404 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 flags = compute_code_flags(c);
5407 if (flags < 0)
5408 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5411 if (!bytecode)
5412 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5415 if (!tmp)
5416 goto error;
5417 Py_DECREF(consts);
5418 consts = tmp;
5419
Victor Stinnerf8e32212013-11-19 23:56:34 +01005420 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5421 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005422 maxdepth = stackdepth(c);
5423 if (maxdepth < 0) {
5424 goto error;
5425 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005426 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005427 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 bytecode, consts, names, varnames,
5429 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005430 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 c->u->u_firstlineno,
5432 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005433 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 Py_XDECREF(consts);
5435 Py_XDECREF(names);
5436 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 Py_XDECREF(name);
5438 Py_XDECREF(freevars);
5439 Py_XDECREF(cellvars);
5440 Py_XDECREF(bytecode);
5441 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005442}
5443
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005444
5445/* For debugging purposes only */
5446#if 0
5447static void
5448dump_instr(const struct instr *i)
5449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 const char *jrel = i->i_jrel ? "jrel " : "";
5451 const char *jabs = i->i_jabs ? "jabs " : "";
5452 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005455 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5459 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005460}
5461
5462static void
5463dump_basicblock(const basicblock *b)
5464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 const char *seen = b->b_seen ? "seen " : "";
5466 const char *b_return = b->b_return ? "return " : "";
5467 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5468 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5469 if (b->b_instr) {
5470 int i;
5471 for (i = 0; i < b->b_iused; i++) {
5472 fprintf(stderr, " [%02d] ", i);
5473 dump_instr(b->b_instr + i);
5474 }
5475 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005476}
5477#endif
5478
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005479static PyCodeObject *
5480assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 basicblock *b, *entryblock;
5483 struct assembler a;
5484 int i, j, nblocks;
5485 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 /* Make sure every block that falls off the end returns None.
5488 XXX NEXT_BLOCK() isn't quite right, because if the last
5489 block ends with a jump or return b_next shouldn't set.
5490 */
5491 if (!c->u->u_curblock->b_return) {
5492 NEXT_BLOCK(c);
5493 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005494 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 ADDOP(c, RETURN_VALUE);
5496 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 nblocks = 0;
5499 entryblock = NULL;
5500 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5501 nblocks++;
5502 entryblock = b;
5503 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 /* Set firstlineno if it wasn't explicitly set. */
5506 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005507 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5509 else
5510 c->u->u_firstlineno = 1;
5511 }
5512 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5513 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005514 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 /* Can't modify the bytecode after computing jump offsets. */
5517 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 /* Emit code in reverse postorder from dfs. */
5520 for (i = a.a_nblocks - 1; i >= 0; i--) {
5521 b = a.a_postorder[i];
5522 for (j = 0; j < b->b_iused; j++)
5523 if (!assemble_emit(&a, &b->b_instr[j]))
5524 goto error;
5525 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5528 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005529 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005533 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 assemble_free(&a);
5535 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005536}
Georg Brandl8334fd92010-12-04 10:26:46 +00005537
5538#undef PyAST_Compile
5539PyAPI_FUNC(PyCodeObject *)
5540PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5541 PyArena *arena)
5542{
5543 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5544}