blob: 11958d3841752a21c34a36a56b4c43f9c78f77e1 [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 *);
Serhiy Storchakad31e7732018-10-21 10:09:39 +0300177static int compiler_warn(struct compiler *, const char *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
179
180static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
181static int compiler_visit_stmt(struct compiler *, stmt_ty);
182static int compiler_visit_keyword(struct compiler *, keyword_ty);
183static int compiler_visit_expr(struct compiler *, expr_ty);
184static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700185static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200190static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500192static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400193static int compiler_async_with(struct compiler *, stmt_ty, int);
194static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100195static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400197 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500198static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400199static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000200
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700201static int compiler_sync_comprehension_generator(
202 struct compiler *c,
203 asdl_seq *generators, int gen_index,
204 expr_ty elt, expr_ty val, int type);
205
206static int compiler_async_comprehension_generator(
207 struct compiler *c,
208 asdl_seq *generators, int gen_index,
209 expr_ty elt, expr_ty val, int type);
210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000212static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400214#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000215
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 /* Name mangling: __private becomes _classname__private.
220 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200221 PyObject *result;
222 size_t nlen, plen, ipriv;
223 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyUnicode_READ_CHAR(ident, 0) != '_' ||
226 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_INCREF(ident);
228 return ident;
229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200230 nlen = PyUnicode_GET_LENGTH(ident);
231 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 The only time a name with a dot can occur is when
235 we are compiling an import statement that has a
236 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 TODO(jhylton): Decide whether we want to support
239 mangling of the module name, e.g. __M.X.
240 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
242 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
243 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Py_INCREF(ident);
245 return ident; /* Don't mangle __whatever__ */
246 }
247 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 ipriv = 0;
249 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
250 ipriv++;
251 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_INCREF(ident);
253 return ident; /* Don't mangle if class is just underscores */
254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200255 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Antoine Pitrou55bff892013-04-06 21:21:04 +0200257 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
258 PyErr_SetString(PyExc_OverflowError,
259 "private identifier too large to be mangled");
260 return NULL;
261 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
264 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
265 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
266
267 result = PyUnicode_New(1 + nlen + plen, maxchar);
268 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200270 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
271 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200272 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
273 Py_DECREF(result);
274 return NULL;
275 }
276 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
Victor Stinner8f825062012-04-27 13:55:39 +0200280 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000282}
283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284static int
285compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 c->c_stack = PyList_New(0);
290 if (!c->c_stack)
291 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294}
295
296PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200297PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
298 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 struct compiler c;
301 PyCodeObject *co = NULL;
302 PyCompilerFlags local_flags;
303 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!__doc__) {
306 __doc__ = PyUnicode_InternFromString("__doc__");
307 if (!__doc__)
308 return NULL;
309 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000310 if (!__annotations__) {
311 __annotations__ = PyUnicode_InternFromString("__annotations__");
312 if (!__annotations__)
313 return NULL;
314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200334 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900335 goto finally;
336 }
337
Victor Stinner14e461d2013-08-26 22:28:21 +0200338 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (c.c_st == NULL) {
340 if (!PyErr_Occurred())
341 PyErr_SetString(PyExc_SystemError, "no symtable");
342 goto finally;
343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000346
Thomas Wouters1175c432006-02-27 22:49:54 +0000347 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 compiler_free(&c);
349 assert(co || PyErr_Occurred());
350 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351}
352
353PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200354PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
355 int optimize, PyArena *arena)
356{
357 PyObject *filename;
358 PyCodeObject *co;
359 filename = PyUnicode_DecodeFSDefault(filename_str);
360 if (filename == NULL)
361 return NULL;
362 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
363 Py_DECREF(filename);
364 return co;
365
366}
367
368PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369PyNode_Compile(struct _node *n, const char *filename)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyCodeObject *co = NULL;
372 mod_ty mod;
373 PyArena *arena = PyArena_New();
374 if (!arena)
375 return NULL;
376 mod = PyAST_FromNode(n, NULL, filename, arena);
377 if (mod)
378 co = PyAST_Compile(mod, filename, NULL, arena);
379 PyArena_Free(arena);
380 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000381}
382
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000383static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (c->c_st)
387 PySymtable_Free(c->c_st);
388 if (c->c_future)
389 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200390 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000392}
393
Guido van Rossum79f25d91997-04-29 20:08:16 +0000394static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 Py_ssize_t i, n;
398 PyObject *v, *k;
399 PyObject *dict = PyDict_New();
400 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 n = PyList_Size(list);
403 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100404 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (!v) {
406 Py_DECREF(dict);
407 return NULL;
408 }
409 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300410 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_DECREF(v);
412 Py_DECREF(dict);
413 return NULL;
414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 Py_DECREF(v);
416 }
417 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418}
419
420/* Return new dict containing names from src that match scope(s).
421
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000422src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000424values are integers, starting at offset and increasing by one for
425each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426*/
427
428static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100429dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000430{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700431 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500433 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 assert(offset >= 0);
436 if (dest == NULL)
437 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438
Meador Inge2ca63152012-07-18 14:20:11 -0500439 /* Sort the keys so that we have a deterministic order on the indexes
440 saved in the returned dictionary. These indexes are used as indexes
441 into the free and cell var storage. Therefore if they aren't
442 deterministic, then the generated bytecode is not deterministic.
443 */
444 sorted_keys = PyDict_Keys(src);
445 if (sorted_keys == NULL)
446 return NULL;
447 if (PyList_Sort(sorted_keys) != 0) {
448 Py_DECREF(sorted_keys);
449 return NULL;
450 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500451 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500452
453 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* XXX this should probably be a macro in symtable.h */
455 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500456 k = PyList_GET_ITEM(sorted_keys, key_i);
457 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 assert(PyLong_Check(v));
459 vi = PyLong_AS_LONG(v);
460 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300463 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500465 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 Py_DECREF(dest);
467 return NULL;
468 }
469 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300470 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_DECREF(item);
473 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return NULL;
475 }
476 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
478 }
Meador Inge2ca63152012-07-18 14:20:11 -0500479 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000481}
482
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483static void
484compiler_unit_check(struct compiler_unit *u)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 basicblock *block;
487 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700488 assert((uintptr_t)block != 0xcbcbcbcbU);
489 assert((uintptr_t)block != 0xfbfbfbfbU);
490 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (block->b_instr != NULL) {
492 assert(block->b_ialloc > 0);
493 assert(block->b_iused > 0);
494 assert(block->b_ialloc >= block->b_iused);
495 }
496 else {
497 assert (block->b_iused == 0);
498 assert (block->b_ialloc == 0);
499 }
500 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501}
502
503static void
504compiler_unit_free(struct compiler_unit *u)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 compiler_unit_check(u);
509 b = u->u_blocks;
510 while (b != NULL) {
511 if (b->b_instr)
512 PyObject_Free((void *)b->b_instr);
513 next = b->b_list;
514 PyObject_Free((void *)b);
515 b = next;
516 }
517 Py_CLEAR(u->u_ste);
518 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400519 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_CLEAR(u->u_consts);
521 Py_CLEAR(u->u_names);
522 Py_CLEAR(u->u_varnames);
523 Py_CLEAR(u->u_freevars);
524 Py_CLEAR(u->u_cellvars);
525 Py_CLEAR(u->u_private);
526 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527}
528
529static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100530compiler_enter_scope(struct compiler *c, identifier name,
531 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100534 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
537 struct compiler_unit));
538 if (!u) {
539 PyErr_NoMemory();
540 return 0;
541 }
542 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100543 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 u->u_argcount = 0;
545 u->u_kwonlyargcount = 0;
546 u->u_ste = PySymtable_Lookup(c->c_st, key);
547 if (!u->u_ste) {
548 compiler_unit_free(u);
549 return 0;
550 }
551 Py_INCREF(name);
552 u->u_name = name;
553 u->u_varnames = list2dict(u->u_ste->ste_varnames);
554 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
555 if (!u->u_varnames || !u->u_cellvars) {
556 compiler_unit_free(u);
557 return 0;
558 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500559 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000560 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500561 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300562 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 int res;
564 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200565 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500566 name = _PyUnicode_FromId(&PyId___class__);
567 if (!name) {
568 compiler_unit_free(u);
569 return 0;
570 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300571 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 if (res < 0) {
573 compiler_unit_free(u);
574 return 0;
575 }
576 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200579 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (!u->u_freevars) {
581 compiler_unit_free(u);
582 return 0;
583 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 u->u_blocks = NULL;
586 u->u_nfblocks = 0;
587 u->u_firstlineno = lineno;
588 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000589 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_lineno_set = 0;
591 u->u_consts = PyDict_New();
592 if (!u->u_consts) {
593 compiler_unit_free(u);
594 return 0;
595 }
596 u->u_names = PyDict_New();
597 if (!u->u_names) {
598 compiler_unit_free(u);
599 return 0;
600 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 /* Push the old compiler_unit on the stack. */
605 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400606 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
608 Py_XDECREF(capsule);
609 compiler_unit_free(u);
610 return 0;
611 }
612 Py_DECREF(capsule);
613 u->u_private = c->u->u_private;
614 Py_XINCREF(u->u_private);
615 }
616 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100619
620 block = compiler_new_block(c);
621 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100623 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400625 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
626 if (!compiler_set_qualname(c))
627 return 0;
628 }
629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631}
632
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000633static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634compiler_exit_scope(struct compiler *c)
635{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100636 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 c->c_nestlevel--;
640 compiler_unit_free(c->u);
641 /* Restore c->u to the parent unit. */
642 n = PyList_GET_SIZE(c->c_stack) - 1;
643 if (n >= 0) {
644 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400645 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 assert(c->u);
647 /* we are deleting from a list so this really shouldn't fail */
648 if (PySequence_DelItem(c->c_stack, n) < 0)
649 Py_FatalError("compiler_exit_scope()");
650 compiler_unit_check(c->u);
651 }
652 else
653 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655}
656
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400657static int
658compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100659{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100660 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400661 _Py_static_string(dot_locals, ".<locals>");
662 Py_ssize_t stack_size;
663 struct compiler_unit *u = c->u;
664 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400668 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 if (stack_size > 1) {
670 int scope, force_global = 0;
671 struct compiler_unit *parent;
672 PyObject *mangled, *capsule;
673
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400674 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400675 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400676 assert(parent);
677
Yury Selivanov75445082015-05-11 22:57:16 -0400678 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
679 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
680 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 assert(u->u_name);
682 mangled = _Py_Mangle(parent->u_private, u->u_name);
683 if (!mangled)
684 return 0;
685 scope = PyST_GetScope(parent->u_ste, mangled);
686 Py_DECREF(mangled);
687 assert(scope != GLOBAL_IMPLICIT);
688 if (scope == GLOBAL_EXPLICIT)
689 force_global = 1;
690 }
691
692 if (!force_global) {
693 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400694 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400695 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
696 dot_locals_str = _PyUnicode_FromId(&dot_locals);
697 if (dot_locals_str == NULL)
698 return 0;
699 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
700 if (base == NULL)
701 return 0;
702 }
703 else {
704 Py_INCREF(parent->u_qualname);
705 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400706 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100707 }
708 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400709
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400710 if (base != NULL) {
711 dot_str = _PyUnicode_FromId(&dot);
712 if (dot_str == NULL) {
713 Py_DECREF(base);
714 return 0;
715 }
716 name = PyUnicode_Concat(base, dot_str);
717 Py_DECREF(base);
718 if (name == NULL)
719 return 0;
720 PyUnicode_Append(&name, u->u_name);
721 if (name == NULL)
722 return 0;
723 }
724 else {
725 Py_INCREF(u->u_name);
726 name = u->u_name;
727 }
728 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100729
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400730 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100731}
732
Eric V. Smith235a6f02015-09-19 14:51:32 -0400733
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734/* Allocate a new block and return a pointer to it.
735 Returns NULL on error.
736*/
737
738static basicblock *
739compiler_new_block(struct compiler *c)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 basicblock *b;
742 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 u = c->u;
745 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
746 if (b == NULL) {
747 PyErr_NoMemory();
748 return NULL;
749 }
750 memset((void *)b, 0, sizeof(basicblock));
751 /* Extend the singly linked list of blocks with new block. */
752 b->b_list = u->u_blocks;
753 u->u_blocks = b;
754 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755}
756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758compiler_next_block(struct compiler *c)
759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 basicblock *block = compiler_new_block(c);
761 if (block == NULL)
762 return NULL;
763 c->u->u_curblock->b_next = block;
764 c->u->u_curblock = block;
765 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766}
767
768static basicblock *
769compiler_use_next_block(struct compiler *c, basicblock *block)
770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 assert(block != NULL);
772 c->u->u_curblock->b_next = block;
773 c->u->u_curblock = block;
774 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
776
777/* Returns the offset of the next instruction in the current block's
778 b_instr array. Resizes the b_instr as necessary.
779 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000780*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781
782static int
783compiler_next_instr(struct compiler *c, basicblock *b)
784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 assert(b != NULL);
786 if (b->b_instr == NULL) {
787 b->b_instr = (struct instr *)PyObject_Malloc(
788 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
789 if (b->b_instr == NULL) {
790 PyErr_NoMemory();
791 return -1;
792 }
793 b->b_ialloc = DEFAULT_BLOCK_SIZE;
794 memset((char *)b->b_instr, 0,
795 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
796 }
797 else if (b->b_iused == b->b_ialloc) {
798 struct instr *tmp;
799 size_t oldsize, newsize;
800 oldsize = b->b_ialloc * sizeof(struct instr);
801 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000802
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700803 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 PyErr_NoMemory();
805 return -1;
806 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (newsize == 0) {
809 PyErr_NoMemory();
810 return -1;
811 }
812 b->b_ialloc <<= 1;
813 tmp = (struct instr *)PyObject_Realloc(
814 (void *)b->b_instr, newsize);
815 if (tmp == NULL) {
816 PyErr_NoMemory();
817 return -1;
818 }
819 b->b_instr = tmp;
820 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
821 }
822 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000823}
824
Christian Heimes2202f872008-02-06 14:31:34 +0000825/* Set the i_lineno member of the instruction at offset off if the
826 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000827 already been set. If it has been set, the call has no effect.
828
Christian Heimes2202f872008-02-06 14:31:34 +0000829 The line number is reset in the following cases:
830 - when entering a new scope
831 - on each statement
832 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200833 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000834 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000835*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837static void
838compiler_set_lineno(struct compiler *c, int off)
839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 basicblock *b;
841 if (c->u->u_lineno_set)
842 return;
843 c->u->u_lineno_set = 1;
844 b = c->u->u_curblock;
845 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846}
847
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200848/* Return the stack effect of opcode with argument oparg.
849
850 Some opcodes have different stack effect when jump to the target and
851 when not jump. The 'jump' parameter specifies the case:
852
853 * 0 -- when not jump
854 * 1 -- when jump
855 * -1 -- maximal
856 */
857/* XXX Make the stack effect of WITH_CLEANUP_START and
858 WITH_CLEANUP_FINISH deterministic. */
859static int
860stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300863 case NOP:
864 case EXTENDED_ARG:
865 return 0;
866
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200867 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 case POP_TOP:
869 return -1;
870 case ROT_TWO:
871 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200872 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 return 0;
874 case DUP_TOP:
875 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000876 case DUP_TOP_TWO:
877 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000878
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200879 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case UNARY_POSITIVE:
881 case UNARY_NEGATIVE:
882 case UNARY_NOT:
883 case UNARY_INVERT:
884 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case SET_ADD:
887 case LIST_APPEND:
888 return -1;
889 case MAP_ADD:
890 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000891
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200892 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 case BINARY_POWER:
894 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400895 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case BINARY_MODULO:
897 case BINARY_ADD:
898 case BINARY_SUBTRACT:
899 case BINARY_SUBSCR:
900 case BINARY_FLOOR_DIVIDE:
901 case BINARY_TRUE_DIVIDE:
902 return -1;
903 case INPLACE_FLOOR_DIVIDE:
904 case INPLACE_TRUE_DIVIDE:
905 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case INPLACE_ADD:
908 case INPLACE_SUBTRACT:
909 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400910 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case INPLACE_MODULO:
912 return -1;
913 case STORE_SUBSCR:
914 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case DELETE_SUBSCR:
916 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case BINARY_LSHIFT:
919 case BINARY_RSHIFT:
920 case BINARY_AND:
921 case BINARY_XOR:
922 case BINARY_OR:
923 return -1;
924 case INPLACE_POWER:
925 return -1;
926 case GET_ITER:
927 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case PRINT_EXPR:
930 return -1;
931 case LOAD_BUILD_CLASS:
932 return 1;
933 case INPLACE_LSHIFT:
934 case INPLACE_RSHIFT:
935 case INPLACE_AND:
936 case INPLACE_XOR:
937 case INPLACE_OR:
938 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200941 /* 1 in the normal flow.
942 * Restore the stack position and push 6 values before jumping to
943 * the handler if an exception be raised. */
944 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400945 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200946 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400947 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200948 /* Pop a variable number of values pushed by WITH_CLEANUP_START
949 * + __exit__ or __aexit__. */
950 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 case RETURN_VALUE:
952 return -1;
953 case IMPORT_STAR:
954 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700955 case SETUP_ANNOTATIONS:
956 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case YIELD_VALUE:
958 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500959 case YIELD_FROM:
960 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case POP_BLOCK:
962 return 0;
963 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200964 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200966 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200967 /* Pop 6 values when an exception was raised. */
968 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case STORE_NAME:
971 return -1;
972 case DELETE_NAME:
973 return 0;
974 case UNPACK_SEQUENCE:
975 return oparg-1;
976 case UNPACK_EX:
977 return (oparg&0xFF) + (oparg>>8);
978 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200979 /* -1 at end of iterator, 1 if continue iterating. */
980 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case STORE_ATTR:
983 return -2;
984 case DELETE_ATTR:
985 return -1;
986 case STORE_GLOBAL:
987 return -1;
988 case DELETE_GLOBAL:
989 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case LOAD_CONST:
991 return 1;
992 case LOAD_NAME:
993 return 1;
994 case BUILD_TUPLE:
995 case BUILD_LIST:
996 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300997 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400999 case BUILD_LIST_UNPACK:
1000 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001001 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001002 case BUILD_SET_UNPACK:
1003 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001004 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001005 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001007 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001008 case BUILD_CONST_KEY_MAP:
1009 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 case LOAD_ATTR:
1011 return 0;
1012 case COMPARE_OP:
1013 return -1;
1014 case IMPORT_NAME:
1015 return -1;
1016 case IMPORT_FROM:
1017 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001018
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001019 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case JUMP_ABSOLUTE:
1022 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001024 case JUMP_IF_TRUE_OR_POP:
1025 case JUMP_IF_FALSE_OR_POP:
1026 return jump ? 0 : -1;
1027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case POP_JUMP_IF_FALSE:
1029 case POP_JUMP_IF_TRUE:
1030 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case LOAD_GLOBAL:
1033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001035 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001037 /* 0 in the normal flow.
1038 * Restore the stack position and push 6 values before jumping to
1039 * the handler if an exception be raised. */
1040 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001041 case BEGIN_FINALLY:
1042 /* Actually pushes 1 value, but count 6 for balancing with
1043 * END_FINALLY and POP_FINALLY.
1044 * This is the main reason of using this opcode instead of
1045 * "LOAD_CONST None". */
1046 return 6;
1047 case CALL_FINALLY:
1048 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case LOAD_FAST:
1051 return 1;
1052 case STORE_FAST:
1053 return -1;
1054 case DELETE_FAST:
1055 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case RAISE_VARARGS:
1058 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001059
1060 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001062 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001063 case CALL_METHOD:
1064 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001066 return -oparg-1;
1067 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001068 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001069 case MAKE_FUNCTION:
1070 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1071 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case BUILD_SLICE:
1073 if (oparg == 3)
1074 return -2;
1075 else
1076 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001077
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001078 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case LOAD_CLOSURE:
1080 return 1;
1081 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001082 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 return 1;
1084 case STORE_DEREF:
1085 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001086 case DELETE_DEREF:
1087 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001088
1089 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001090 case GET_AWAITABLE:
1091 return 0;
1092 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001093 /* 0 in the normal flow.
1094 * Restore the stack position to the position before the result
1095 * of __aenter__ and push 6 values before jumping to the handler
1096 * if an exception be raised. */
1097 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001098 case BEFORE_ASYNC_WITH:
1099 return 1;
1100 case GET_AITER:
1101 return 0;
1102 case GET_ANEXT:
1103 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001104 case GET_YIELD_FROM_ITER:
1105 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001106 case END_ASYNC_FOR:
1107 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001108 case FORMAT_VALUE:
1109 /* If there's a fmt_spec on the stack, we go from 2->1,
1110 else 1->1. */
1111 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001112 case LOAD_METHOD:
1113 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001115 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 }
Larry Hastings3a907972013-11-23 14:49:22 -08001117 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118}
1119
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001120int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001121PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1122{
1123 return stack_effect(opcode, oparg, jump);
1124}
1125
1126int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001127PyCompile_OpcodeStackEffect(int opcode, int oparg)
1128{
1129 return stack_effect(opcode, oparg, -1);
1130}
1131
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132/* Add an opcode with no argument.
1133 Returns 0 on failure, 1 on success.
1134*/
1135
1136static int
1137compiler_addop(struct compiler *c, int opcode)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 basicblock *b;
1140 struct instr *i;
1141 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001142 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 off = compiler_next_instr(c, c->u->u_curblock);
1144 if (off < 0)
1145 return 0;
1146 b = c->u->u_curblock;
1147 i = &b->b_instr[off];
1148 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001149 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (opcode == RETURN_VALUE)
1151 b->b_return = 1;
1152 compiler_set_lineno(c, off);
1153 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154}
1155
Victor Stinnerf8e32212013-11-19 23:56:34 +01001156static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1158{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001159 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001162 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001164 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001166 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001167 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001168 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return -1;
1171 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 Py_DECREF(v);
1174 return -1;
1175 }
1176 Py_DECREF(v);
1177 }
1178 else
1179 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001180 return arg;
1181}
1182
1183static Py_ssize_t
1184compiler_add_const(struct compiler *c, PyObject *o)
1185{
1186 PyObject *t;
1187 Py_ssize_t arg;
1188
1189 t = _PyCode_ConstantKey(o);
1190 if (t == NULL)
1191 return -1;
1192
1193 arg = compiler_add_o(c, c->u->u_consts, t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_DECREF(t);
1195 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001199compiler_addop_load_const(struct compiler *c, PyObject *o)
1200{
1201 Py_ssize_t arg = compiler_add_const(c, o);
1202 if (arg < 0)
1203 return 0;
1204 return compiler_addop_i(c, LOAD_CONST, arg);
1205}
1206
1207static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001211 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001213 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 return compiler_addop_i(c, opcode, arg);
1215}
1216
1217static int
1218compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001221 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1223 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001224 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225 arg = compiler_add_o(c, dict, mangled);
1226 Py_DECREF(mangled);
1227 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229 return compiler_addop_i(c, opcode, arg);
1230}
1231
1232/* Add an opcode with an integer argument.
1233 Returns 0 on failure, 1 on success.
1234*/
1235
1236static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001237compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 struct instr *i;
1240 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001241
Victor Stinner2ad474b2016-03-01 23:34:47 +01001242 /* oparg value is unsigned, but a signed C int is usually used to store
1243 it in the C code (like Python/ceval.c).
1244
1245 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1246
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001247 The argument of a concrete bytecode instruction is limited to 8-bit.
1248 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1249 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001250 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 off = compiler_next_instr(c, c->u->u_curblock);
1253 if (off < 0)
1254 return 0;
1255 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001256 i->i_opcode = opcode;
1257 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 compiler_set_lineno(c, off);
1259 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262static int
1263compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 struct instr *i;
1266 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001268 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 assert(b != NULL);
1270 off = compiler_next_instr(c, c->u->u_curblock);
1271 if (off < 0)
1272 return 0;
1273 i = &c->u->u_curblock->b_instr[off];
1274 i->i_opcode = opcode;
1275 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (absolute)
1277 i->i_jabs = 1;
1278 else
1279 i->i_jrel = 1;
1280 compiler_set_lineno(c, off);
1281 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001284/* NEXT_BLOCK() creates an implicit jump from the current block
1285 to the new block.
1286
1287 The returns inside this macro make it impossible to decref objects
1288 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (compiler_next_block((C)) == NULL) \
1292 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293}
1294
1295#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (!compiler_addop((C), (OP))) \
1297 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298}
1299
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001300#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 if (!compiler_addop((C), (OP))) { \
1302 compiler_exit_scope(c); \
1303 return 0; \
1304 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001305}
1306
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001307#define ADDOP_LOAD_CONST(C, O) { \
1308 if (!compiler_addop_load_const((C), (O))) \
1309 return 0; \
1310}
1311
1312/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1313#define ADDOP_LOAD_CONST_NEW(C, O) { \
1314 PyObject *__new_const = (O); \
1315 if (__new_const == NULL) { \
1316 return 0; \
1317 } \
1318 if (!compiler_addop_load_const((C), __new_const)) { \
1319 Py_DECREF(__new_const); \
1320 return 0; \
1321 } \
1322 Py_DECREF(__new_const); \
1323}
1324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1327 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328}
1329
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001330/* Same as ADDOP_O, but steals a reference. */
1331#define ADDOP_N(C, OP, O, TYPE) { \
1332 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1333 Py_DECREF((O)); \
1334 return 0; \
1335 } \
1336 Py_DECREF((O)); \
1337}
1338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1341 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342}
1343
1344#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (!compiler_addop_i((C), (OP), (O))) \
1346 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347}
1348
1349#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 if (!compiler_addop_j((C), (OP), (O), 1)) \
1351 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352}
1353
1354#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 if (!compiler_addop_j((C), (OP), (O), 0)) \
1356 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357}
1358
1359/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1360 the ASDL name to synthesize the name of the C type and the visit function.
1361*/
1362
1363#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 if (!compiler_visit_ ## TYPE((C), (V))) \
1365 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366}
1367
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001368#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (!compiler_visit_ ## TYPE((C), (V))) { \
1370 compiler_exit_scope(c); \
1371 return 0; \
1372 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001373}
1374
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (!compiler_visit_slice((C), (V), (CTX))) \
1377 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378}
1379
1380#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 int _i; \
1382 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1383 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1384 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1385 if (!compiler_visit_ ## TYPE((C), elt)) \
1386 return 0; \
1387 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388}
1389
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001390#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 int _i; \
1392 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1393 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1394 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1395 if (!compiler_visit_ ## TYPE((C), elt)) { \
1396 compiler_exit_scope(c); \
1397 return 0; \
1398 } \
1399 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001400}
1401
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001402/* Search if variable annotations are present statically in a block. */
1403
1404static int
1405find_ann(asdl_seq *stmts)
1406{
1407 int i, j, res = 0;
1408 stmt_ty st;
1409
1410 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1411 st = (stmt_ty)asdl_seq_GET(stmts, i);
1412 switch (st->kind) {
1413 case AnnAssign_kind:
1414 return 1;
1415 case For_kind:
1416 res = find_ann(st->v.For.body) ||
1417 find_ann(st->v.For.orelse);
1418 break;
1419 case AsyncFor_kind:
1420 res = find_ann(st->v.AsyncFor.body) ||
1421 find_ann(st->v.AsyncFor.orelse);
1422 break;
1423 case While_kind:
1424 res = find_ann(st->v.While.body) ||
1425 find_ann(st->v.While.orelse);
1426 break;
1427 case If_kind:
1428 res = find_ann(st->v.If.body) ||
1429 find_ann(st->v.If.orelse);
1430 break;
1431 case With_kind:
1432 res = find_ann(st->v.With.body);
1433 break;
1434 case AsyncWith_kind:
1435 res = find_ann(st->v.AsyncWith.body);
1436 break;
1437 case Try_kind:
1438 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1439 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1440 st->v.Try.handlers, j);
1441 if (find_ann(handler->v.ExceptHandler.body)) {
1442 return 1;
1443 }
1444 }
1445 res = find_ann(st->v.Try.body) ||
1446 find_ann(st->v.Try.finalbody) ||
1447 find_ann(st->v.Try.orelse);
1448 break;
1449 default:
1450 res = 0;
1451 }
1452 if (res) {
1453 break;
1454 }
1455 }
1456 return res;
1457}
1458
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001459/*
1460 * Frame block handling functions
1461 */
1462
1463static int
1464compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1465 basicblock *exit)
1466{
1467 struct fblockinfo *f;
1468 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1469 PyErr_SetString(PyExc_SyntaxError,
1470 "too many statically nested blocks");
1471 return 0;
1472 }
1473 f = &c->u->u_fblock[c->u->u_nfblocks++];
1474 f->fb_type = t;
1475 f->fb_block = b;
1476 f->fb_exit = exit;
1477 return 1;
1478}
1479
1480static void
1481compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1482{
1483 struct compiler_unit *u = c->u;
1484 assert(u->u_nfblocks > 0);
1485 u->u_nfblocks--;
1486 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1487 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1488}
1489
1490/* Unwind a frame block. If preserve_tos is true, the TOS before
1491 * popping the blocks will be restored afterwards.
1492 */
1493static int
1494compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1495 int preserve_tos)
1496{
1497 switch (info->fb_type) {
1498 case WHILE_LOOP:
1499 return 1;
1500
1501 case FINALLY_END:
1502 ADDOP_I(c, POP_FINALLY, preserve_tos);
1503 return 1;
1504
1505 case FOR_LOOP:
1506 /* Pop the iterator */
1507 if (preserve_tos) {
1508 ADDOP(c, ROT_TWO);
1509 }
1510 ADDOP(c, POP_TOP);
1511 return 1;
1512
1513 case EXCEPT:
1514 ADDOP(c, POP_BLOCK);
1515 return 1;
1516
1517 case FINALLY_TRY:
1518 ADDOP(c, POP_BLOCK);
1519 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1520 return 1;
1521
1522 case WITH:
1523 case ASYNC_WITH:
1524 ADDOP(c, POP_BLOCK);
1525 if (preserve_tos) {
1526 ADDOP(c, ROT_TWO);
1527 }
1528 ADDOP(c, BEGIN_FINALLY);
1529 ADDOP(c, WITH_CLEANUP_START);
1530 if (info->fb_type == ASYNC_WITH) {
1531 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001532 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001533 ADDOP(c, YIELD_FROM);
1534 }
1535 ADDOP(c, WITH_CLEANUP_FINISH);
1536 ADDOP_I(c, POP_FINALLY, 0);
1537 return 1;
1538
1539 case HANDLER_CLEANUP:
1540 if (preserve_tos) {
1541 ADDOP(c, ROT_FOUR);
1542 }
1543 if (info->fb_exit) {
1544 ADDOP(c, POP_BLOCK);
1545 ADDOP(c, POP_EXCEPT);
1546 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1547 }
1548 else {
1549 ADDOP(c, POP_EXCEPT);
1550 }
1551 return 1;
1552 }
1553 Py_UNREACHABLE();
1554}
1555
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001556/* Compile a sequence of statements, checking for a docstring
1557 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001558
1559static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001560compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001562 int i = 0;
1563 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001564 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001565
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001566 /* Set current line number to the line number of first statement.
1567 This way line number for SETUP_ANNOTATIONS will always
1568 coincide with the line number of first "real" statement in module.
1569 If body is empy, then lineno will be set later in assemble. */
1570 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1571 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001572 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001573 c->u->u_lineno = st->lineno;
1574 }
1575 /* Every annotated class and module should have __annotations__. */
1576 if (find_ann(stmts)) {
1577 ADDOP(c, SETUP_ANNOTATIONS);
1578 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001579 if (!asdl_seq_LEN(stmts))
1580 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001581 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001582 if (c->c_optimize < 2) {
1583 docstring = _PyAST_GetDocString(stmts);
1584 if (docstring) {
1585 i = 1;
1586 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1587 assert(st->kind == Expr_kind);
1588 VISIT(c, expr, st->v.Expr.value);
1589 if (!compiler_nameop(c, __doc__, Store))
1590 return 0;
1591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001593 for (; i < asdl_seq_LEN(stmts); i++)
1594 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596}
1597
1598static PyCodeObject *
1599compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 PyCodeObject *co;
1602 int addNone = 1;
1603 static PyObject *module;
1604 if (!module) {
1605 module = PyUnicode_InternFromString("<module>");
1606 if (!module)
1607 return NULL;
1608 }
1609 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001610 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return NULL;
1612 switch (mod->kind) {
1613 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001614 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 compiler_exit_scope(c);
1616 return 0;
1617 }
1618 break;
1619 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001620 if (find_ann(mod->v.Interactive.body)) {
1621 ADDOP(c, SETUP_ANNOTATIONS);
1622 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 c->c_interactive = 1;
1624 VISIT_SEQ_IN_SCOPE(c, stmt,
1625 mod->v.Interactive.body);
1626 break;
1627 case Expression_kind:
1628 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1629 addNone = 0;
1630 break;
1631 case Suite_kind:
1632 PyErr_SetString(PyExc_SystemError,
1633 "suite should not be possible");
1634 return 0;
1635 default:
1636 PyErr_Format(PyExc_SystemError,
1637 "module kind %d should not be possible",
1638 mod->kind);
1639 return 0;
1640 }
1641 co = assemble(c, addNone);
1642 compiler_exit_scope(c);
1643 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001644}
1645
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646/* The test for LOCAL must come before the test for FREE in order to
1647 handle classes where name is both local and free. The local var is
1648 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001649*/
1650
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651static int
1652get_ref_type(struct compiler *c, PyObject *name)
1653{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001654 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001655 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001656 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001657 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001658 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (scope == 0) {
1660 char buf[350];
1661 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001662 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001664 PyUnicode_AsUTF8(name),
1665 PyUnicode_AsUTF8(c->u->u_name),
1666 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1667 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1668 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1669 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 );
1671 Py_FatalError(buf);
1672 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675}
1676
1677static int
1678compiler_lookup_arg(PyObject *dict, PyObject *name)
1679{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001680 PyObject *v;
1681 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001683 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001684 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001685}
1686
1687static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001688compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001690 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001691 if (qualname == NULL)
1692 qualname = co->co_name;
1693
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001694 if (free) {
1695 for (i = 0; i < free; ++i) {
1696 /* Bypass com_addop_varname because it will generate
1697 LOAD_DEREF but LOAD_CLOSURE is needed.
1698 */
1699 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1700 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001702 /* Special case: If a class contains a method with a
1703 free variable that has the same name as a method,
1704 the name will be considered free *and* local in the
1705 class. It should be handled by the closure, as
1706 well as by the normal name loookup logic.
1707 */
1708 reftype = get_ref_type(c, name);
1709 if (reftype == CELL)
1710 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1711 else /* (reftype == FREE) */
1712 arg = compiler_lookup_arg(c->u->u_freevars, name);
1713 if (arg == -1) {
1714 fprintf(stderr,
1715 "lookup %s in %s %d %d\n"
1716 "freevars of %s: %s\n",
1717 PyUnicode_AsUTF8(PyObject_Repr(name)),
1718 PyUnicode_AsUTF8(c->u->u_name),
1719 reftype, arg,
1720 PyUnicode_AsUTF8(co->co_name),
1721 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1722 Py_FatalError("compiler_make_closure()");
1723 }
1724 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001726 flags |= 0x08;
1727 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001729 ADDOP_LOAD_CONST(c, (PyObject*)co);
1730 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001731 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001733}
1734
1735static int
1736compiler_decorators(struct compiler *c, asdl_seq* decos)
1737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (!decos)
1741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1744 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1745 }
1746 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747}
1748
1749static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001750compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001752{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001753 /* Push a dict of keyword-only default values.
1754
1755 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1756 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001757 int i;
1758 PyObject *keys = NULL;
1759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1761 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1762 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1763 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001764 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001765 if (!mangled) {
1766 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001768 if (keys == NULL) {
1769 keys = PyList_New(1);
1770 if (keys == NULL) {
1771 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001772 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001773 }
1774 PyList_SET_ITEM(keys, 0, mangled);
1775 }
1776 else {
1777 int res = PyList_Append(keys, mangled);
1778 Py_DECREF(mangled);
1779 if (res == -1) {
1780 goto error;
1781 }
1782 }
1783 if (!compiler_visit_expr(c, default_)) {
1784 goto error;
1785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
1787 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001788 if (keys != NULL) {
1789 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1790 PyObject *keys_tuple = PyList_AsTuple(keys);
1791 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001792 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001793 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001794 assert(default_count > 0);
1795 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001796 }
1797 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001798 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001799 }
1800
1801error:
1802 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001803 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001804}
1805
1806static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001807compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1808{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001809 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001810 return 1;
1811}
1812
1813static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001814compiler_visit_argannotation(struct compiler *c, identifier id,
1815 expr_ty annotation, PyObject *names)
1816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001818 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001819 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1820 VISIT(c, annexpr, annotation)
1821 }
1822 else {
1823 VISIT(c, expr, annotation);
1824 }
Victor Stinner065efc32014-02-18 22:07:56 +01001825 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001826 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001827 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001828 if (PyList_Append(names, mangled) < 0) {
1829 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001830 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001831 }
1832 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001834 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001835}
1836
1837static int
1838compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1839 PyObject *names)
1840{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001841 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 for (i = 0; i < asdl_seq_LEN(args); i++) {
1843 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001844 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 c,
1846 arg->arg,
1847 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001848 names))
1849 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001851 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001852}
1853
1854static int
1855compiler_visit_annotations(struct compiler *c, arguments_ty args,
1856 expr_ty returns)
1857{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001858 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001859 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001860
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001861 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 */
1863 static identifier return_str;
1864 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001865 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 names = PyList_New(0);
1867 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001868 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001869
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001870 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001872 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001873 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001874 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001876 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001878 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001879 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001880 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (!return_str) {
1884 return_str = PyUnicode_InternFromString("return");
1885 if (!return_str)
1886 goto error;
1887 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001888 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 goto error;
1890 }
1891
1892 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001894 PyObject *keytuple = PyList_AsTuple(names);
1895 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001896 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001897 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001898 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001900 else {
1901 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001902 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001903 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001904
1905error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001907 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001908}
1909
1910static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001911compiler_visit_defaults(struct compiler *c, arguments_ty args)
1912{
1913 VISIT_SEQ(c, expr, args->defaults);
1914 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1915 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916}
1917
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918static Py_ssize_t
1919compiler_default_arguments(struct compiler *c, arguments_ty args)
1920{
1921 Py_ssize_t funcflags = 0;
1922 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001923 if (!compiler_visit_defaults(c, args))
1924 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001925 funcflags |= 0x01;
1926 }
1927 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001928 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001929 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001930 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001931 return -1;
1932 }
1933 else if (res > 0) {
1934 funcflags |= 0x02;
1935 }
1936 }
1937 return funcflags;
1938}
1939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940static int
Yury Selivanov75445082015-05-11 22:57:16 -04001941compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001944 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04001945 arguments_ty args;
1946 expr_ty returns;
1947 identifier name;
1948 asdl_seq* decos;
1949 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001950 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001951 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001952 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953
Yury Selivanov75445082015-05-11 22:57:16 -04001954 if (is_async) {
1955 assert(s->kind == AsyncFunctionDef_kind);
1956
1957 args = s->v.AsyncFunctionDef.args;
1958 returns = s->v.AsyncFunctionDef.returns;
1959 decos = s->v.AsyncFunctionDef.decorator_list;
1960 name = s->v.AsyncFunctionDef.name;
1961 body = s->v.AsyncFunctionDef.body;
1962
1963 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1964 } else {
1965 assert(s->kind == FunctionDef_kind);
1966
1967 args = s->v.FunctionDef.args;
1968 returns = s->v.FunctionDef.returns;
1969 decos = s->v.FunctionDef.decorator_list;
1970 name = s->v.FunctionDef.name;
1971 body = s->v.FunctionDef.body;
1972
1973 scope_type = COMPILER_SCOPE_FUNCTION;
1974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (!compiler_decorators(c, decos))
1977 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001978
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001979 funcflags = compiler_default_arguments(c, args);
1980 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001982 }
1983
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001984 annotations = compiler_visit_annotations(c, args, returns);
1985 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 return 0;
1987 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001988 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001989 funcflags |= 0x04;
1990 }
1991
1992 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1993 return 0;
1994 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995
INADA Naokicb41b272017-02-23 00:31:59 +09001996 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001997 if (c->c_optimize < 2) {
1998 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001999 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002000 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 compiler_exit_scope(c);
2002 return 0;
2003 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 c->u->u_argcount = asdl_seq_LEN(args->args);
2006 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002007 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002009 qualname = c->u->u_qualname;
2010 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002012 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002013 Py_XDECREF(qualname);
2014 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002016 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002019 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* decorators */
2023 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2024 ADDOP_I(c, CALL_FUNCTION, 1);
2025 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026
Yury Selivanov75445082015-05-11 22:57:16 -04002027 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028}
2029
2030static int
2031compiler_class(struct compiler *c, stmt_ty s)
2032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 PyCodeObject *co;
2034 PyObject *str;
2035 int i;
2036 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (!compiler_decorators(c, decos))
2039 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* ultimately generate code for:
2042 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2043 where:
2044 <func> is a function/closure created from the class body;
2045 it has a single argument (__locals__) where the dict
2046 (or MutableSequence) representing the locals is passed
2047 <name> is the class name
2048 <bases> is the positional arguments and *varargs argument
2049 <keywords> is the keyword arguments and **kwds argument
2050 This borrows from compiler_call.
2051 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002054 if (!compiler_enter_scope(c, s->v.ClassDef.name,
2055 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 return 0;
2057 /* this block represents what we do in the new scope */
2058 {
2059 /* use the class name for name mangling */
2060 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002061 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* load (global) __name__ ... */
2063 str = PyUnicode_InternFromString("__name__");
2064 if (!str || !compiler_nameop(c, str, Load)) {
2065 Py_XDECREF(str);
2066 compiler_exit_scope(c);
2067 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002068 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 Py_DECREF(str);
2070 /* ... and store it as __module__ */
2071 str = PyUnicode_InternFromString("__module__");
2072 if (!str || !compiler_nameop(c, str, Store)) {
2073 Py_XDECREF(str);
2074 compiler_exit_scope(c);
2075 return 0;
2076 }
2077 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002078 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002079 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002080 str = PyUnicode_InternFromString("__qualname__");
2081 if (!str || !compiler_nameop(c, str, Store)) {
2082 Py_XDECREF(str);
2083 compiler_exit_scope(c);
2084 return 0;
2085 }
2086 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002088 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 compiler_exit_scope(c);
2090 return 0;
2091 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002092 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002093 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002094 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002095 str = PyUnicode_InternFromString("__class__");
2096 if (str == NULL) {
2097 compiler_exit_scope(c);
2098 return 0;
2099 }
2100 i = compiler_lookup_arg(c->u->u_cellvars, str);
2101 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002102 if (i < 0) {
2103 compiler_exit_scope(c);
2104 return 0;
2105 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002106 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002109 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002110 str = PyUnicode_InternFromString("__classcell__");
2111 if (!str || !compiler_nameop(c, str, Store)) {
2112 Py_XDECREF(str);
2113 compiler_exit_scope(c);
2114 return 0;
2115 }
2116 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002118 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002119 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002120 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002121 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002122 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002123 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* create the code object */
2125 co = assemble(c, 1);
2126 }
2127 /* leave the new scope */
2128 compiler_exit_scope(c);
2129 if (co == NULL)
2130 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* 2. load the 'build_class' function */
2133 ADDOP(c, LOAD_BUILD_CLASS);
2134
2135 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002136 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 Py_DECREF(co);
2138
2139 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002140 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141
2142 /* 5. generate the rest of the code for the call */
2143 if (!compiler_call_helper(c, 2,
2144 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002145 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 return 0;
2147
2148 /* 6. apply decorators */
2149 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2150 ADDOP_I(c, CALL_FUNCTION, 1);
2151 }
2152
2153 /* 7. store into <name> */
2154 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2155 return 0;
2156 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157}
2158
2159static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002160cmpop(cmpop_ty op)
2161{
2162 switch (op) {
2163 case Eq:
2164 return PyCmp_EQ;
2165 case NotEq:
2166 return PyCmp_NE;
2167 case Lt:
2168 return PyCmp_LT;
2169 case LtE:
2170 return PyCmp_LE;
2171 case Gt:
2172 return PyCmp_GT;
2173 case GtE:
2174 return PyCmp_GE;
2175 case Is:
2176 return PyCmp_IS;
2177 case IsNot:
2178 return PyCmp_IS_NOT;
2179 case In:
2180 return PyCmp_IN;
2181 case NotIn:
2182 return PyCmp_NOT_IN;
2183 default:
2184 return PyCmp_BAD;
2185 }
2186}
2187
2188static int
2189compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2190{
2191 switch (e->kind) {
2192 case UnaryOp_kind:
2193 if (e->v.UnaryOp.op == Not)
2194 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2195 /* fallback to general implementation */
2196 break;
2197 case BoolOp_kind: {
2198 asdl_seq *s = e->v.BoolOp.values;
2199 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2200 assert(n >= 0);
2201 int cond2 = e->v.BoolOp.op == Or;
2202 basicblock *next2 = next;
2203 if (!cond2 != !cond) {
2204 next2 = compiler_new_block(c);
2205 if (next2 == NULL)
2206 return 0;
2207 }
2208 for (i = 0; i < n; ++i) {
2209 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2210 return 0;
2211 }
2212 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2213 return 0;
2214 if (next2 != next)
2215 compiler_use_next_block(c, next2);
2216 return 1;
2217 }
2218 case IfExp_kind: {
2219 basicblock *end, *next2;
2220 end = compiler_new_block(c);
2221 if (end == NULL)
2222 return 0;
2223 next2 = compiler_new_block(c);
2224 if (next2 == NULL)
2225 return 0;
2226 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2227 return 0;
2228 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2229 return 0;
2230 ADDOP_JREL(c, JUMP_FORWARD, end);
2231 compiler_use_next_block(c, next2);
2232 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2233 return 0;
2234 compiler_use_next_block(c, end);
2235 return 1;
2236 }
2237 case Compare_kind: {
2238 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2239 if (n > 0) {
2240 basicblock *cleanup = compiler_new_block(c);
2241 if (cleanup == NULL)
2242 return 0;
2243 VISIT(c, expr, e->v.Compare.left);
2244 for (i = 0; i < n; i++) {
2245 VISIT(c, expr,
2246 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2247 ADDOP(c, DUP_TOP);
2248 ADDOP(c, ROT_THREE);
2249 ADDOP_I(c, COMPARE_OP,
2250 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2251 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2252 NEXT_BLOCK(c);
2253 }
2254 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2255 ADDOP_I(c, COMPARE_OP,
2256 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2257 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2258 basicblock *end = compiler_new_block(c);
2259 if (end == NULL)
2260 return 0;
2261 ADDOP_JREL(c, JUMP_FORWARD, end);
2262 compiler_use_next_block(c, cleanup);
2263 ADDOP(c, POP_TOP);
2264 if (!cond) {
2265 ADDOP_JREL(c, JUMP_FORWARD, next);
2266 }
2267 compiler_use_next_block(c, end);
2268 return 1;
2269 }
2270 /* fallback to general implementation */
2271 break;
2272 }
2273 default:
2274 /* fallback to general implementation */
2275 break;
2276 }
2277
2278 /* general implementation */
2279 VISIT(c, expr, e);
2280 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2281 return 1;
2282}
2283
2284static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002285compiler_ifexp(struct compiler *c, expr_ty e)
2286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 basicblock *end, *next;
2288
2289 assert(e->kind == IfExp_kind);
2290 end = compiler_new_block(c);
2291 if (end == NULL)
2292 return 0;
2293 next = compiler_new_block(c);
2294 if (next == NULL)
2295 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002296 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2297 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 VISIT(c, expr, e->v.IfExp.body);
2299 ADDOP_JREL(c, JUMP_FORWARD, end);
2300 compiler_use_next_block(c, next);
2301 VISIT(c, expr, e->v.IfExp.orelse);
2302 compiler_use_next_block(c, end);
2303 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002304}
2305
2306static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307compiler_lambda(struct compiler *c, expr_ty e)
2308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002310 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002312 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 arguments_ty args = e->v.Lambda.args;
2314 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 if (!name) {
2317 name = PyUnicode_InternFromString("<lambda>");
2318 if (!name)
2319 return 0;
2320 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002322 funcflags = compiler_default_arguments(c, args);
2323 if (funcflags == -1) {
2324 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002326
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002327 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002328 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* Make None the first constant, so the lambda can't have a
2332 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002333 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 c->u->u_argcount = asdl_seq_LEN(args->args);
2337 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2338 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2339 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002340 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 }
2342 else {
2343 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002344 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002346 qualname = c->u->u_qualname;
2347 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002349 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002352 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002353 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 Py_DECREF(co);
2355
2356 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357}
2358
2359static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360compiler_if(struct compiler *c, stmt_ty s)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 basicblock *end, *next;
2363 int constant;
2364 assert(s->kind == If_kind);
2365 end = compiler_new_block(c);
2366 if (end == NULL)
2367 return 0;
2368
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002369 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* constant = 0: "if 0"
2371 * constant = 1: "if 1", "if 2", ...
2372 * constant = -1: rest */
2373 if (constant == 0) {
2374 if (s->v.If.orelse)
2375 VISIT_SEQ(c, stmt, s->v.If.orelse);
2376 } else if (constant == 1) {
2377 VISIT_SEQ(c, stmt, s->v.If.body);
2378 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002379 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 next = compiler_new_block(c);
2381 if (next == NULL)
2382 return 0;
2383 }
2384 else
2385 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002386 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2387 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002389 if (asdl_seq_LEN(s->v.If.orelse)) {
2390 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 compiler_use_next_block(c, next);
2392 VISIT_SEQ(c, stmt, s->v.If.orelse);
2393 }
2394 }
2395 compiler_use_next_block(c, end);
2396 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397}
2398
2399static int
2400compiler_for(struct compiler *c, stmt_ty s)
2401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 start = compiler_new_block(c);
2405 cleanup = compiler_new_block(c);
2406 end = compiler_new_block(c);
2407 if (start == NULL || end == NULL || cleanup == NULL)
2408 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002409
2410 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 VISIT(c, expr, s->v.For.iter);
2414 ADDOP(c, GET_ITER);
2415 compiler_use_next_block(c, start);
2416 ADDOP_JREL(c, FOR_ITER, cleanup);
2417 VISIT(c, expr, s->v.For.target);
2418 VISIT_SEQ(c, stmt, s->v.For.body);
2419 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2420 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002421
2422 compiler_pop_fblock(c, FOR_LOOP, start);
2423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 VISIT_SEQ(c, stmt, s->v.For.orelse);
2425 compiler_use_next_block(c, end);
2426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427}
2428
Yury Selivanov75445082015-05-11 22:57:16 -04002429
2430static int
2431compiler_async_for(struct compiler *c, stmt_ty s)
2432{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002433 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002434 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2435 return compiler_error(c, "'async for' outside async function");
2436 }
2437
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002438 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002439 except = compiler_new_block(c);
2440 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002441
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002442 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002443 return 0;
2444
2445 VISIT(c, expr, s->v.AsyncFor.iter);
2446 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002447
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002448 compiler_use_next_block(c, start);
2449 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2450 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002451
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002452 /* SETUP_FINALLY to guard the __anext__ call */
2453 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002454 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002455 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002456 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002457 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002458
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002459 /* Success block for __anext__ */
2460 VISIT(c, expr, s->v.AsyncFor.target);
2461 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2462 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2463
2464 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002465
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002466 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002467 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002468 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002469
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002470 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002471 VISIT_SEQ(c, stmt, s->v.For.orelse);
2472
2473 compiler_use_next_block(c, end);
2474
2475 return 1;
2476}
2477
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478static int
2479compiler_while(struct compiler *c, stmt_ty s)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002482 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (constant == 0) {
2485 if (s->v.While.orelse)
2486 VISIT_SEQ(c, stmt, s->v.While.orelse);
2487 return 1;
2488 }
2489 loop = compiler_new_block(c);
2490 end = compiler_new_block(c);
2491 if (constant == -1) {
2492 anchor = compiler_new_block(c);
2493 if (anchor == NULL)
2494 return 0;
2495 }
2496 if (loop == NULL || end == NULL)
2497 return 0;
2498 if (s->v.While.orelse) {
2499 orelse = compiler_new_block(c);
2500 if (orelse == NULL)
2501 return 0;
2502 }
2503 else
2504 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002507 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 return 0;
2509 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002510 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2511 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 }
2513 VISIT_SEQ(c, stmt, s->v.While.body);
2514 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 /* XXX should the two POP instructions be in a separate block
2517 if there is no else clause ?
2518 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002520 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002522 compiler_pop_fblock(c, WHILE_LOOP, loop);
2523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (orelse != NULL) /* what if orelse is just pass? */
2525 VISIT_SEQ(c, stmt, s->v.While.orelse);
2526 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529}
2530
2531static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002532compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002534 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002535 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002536 if (c->u->u_ste->ste_type != FunctionBlock)
2537 return compiler_error(c, "'return' outside function");
2538 if (s->v.Return.value != NULL &&
2539 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2540 {
2541 return compiler_error(
2542 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002544 if (preserve_tos) {
2545 VISIT(c, expr, s->v.Return.value);
2546 }
2547 for (int depth = c->u->u_nfblocks; depth--;) {
2548 struct fblockinfo *info = &c->u->u_fblock[depth];
2549
2550 if (!compiler_unwind_fblock(c, info, preserve_tos))
2551 return 0;
2552 }
2553 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002554 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002555 }
2556 else if (!preserve_tos) {
2557 VISIT(c, expr, s->v.Return.value);
2558 }
2559 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562}
2563
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002564static int
2565compiler_break(struct compiler *c)
2566{
2567 for (int depth = c->u->u_nfblocks; depth--;) {
2568 struct fblockinfo *info = &c->u->u_fblock[depth];
2569
2570 if (!compiler_unwind_fblock(c, info, 0))
2571 return 0;
2572 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2573 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2574 return 1;
2575 }
2576 }
2577 return compiler_error(c, "'break' outside loop");
2578}
2579
2580static int
2581compiler_continue(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 (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2587 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2588 return 1;
2589 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002590 if (!compiler_unwind_fblock(c, info, 0))
2591 return 0;
2592 }
2593 return compiler_error(c, "'continue' not properly in loop");
2594}
2595
2596
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598
2599 SETUP_FINALLY L
2600 <code for body>
2601 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002602 BEGIN_FINALLY
2603 L:
2604 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 END_FINALLY
2606
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607 The special instructions use the block stack. Each block
2608 stack entry contains the instruction that created it (here
2609 SETUP_FINALLY), the level of the value stack at the time the
2610 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 Pushes the current value stack level and the label
2614 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002616 Pops en entry from the block stack.
2617 BEGIN_FINALLY
2618 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002620 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2621 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002624 when a SETUP_FINALLY entry is found, the raised and the caught
2625 exceptions are pushed onto the value stack (and the exception
2626 condition is cleared), and the interpreter jumps to the label
2627 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628*/
2629
2630static int
2631compiler_try_finally(struct compiler *c, stmt_ty s)
2632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 body = compiler_new_block(c);
2636 end = compiler_new_block(c);
2637 if (body == NULL || end == NULL)
2638 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002640 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 ADDOP_JREL(c, SETUP_FINALLY, end);
2642 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002643 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002645 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2646 if (!compiler_try_except(c, s))
2647 return 0;
2648 }
2649 else {
2650 VISIT_SEQ(c, stmt, s->v.Try.body);
2651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002653 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002656 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002658 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002660 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 ADDOP(c, END_FINALLY);
2662 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664}
2665
2666/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002667 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 (The contents of the value stack is shown in [], with the top
2669 at the right; 'tb' is trace-back info, 'val' the exception's
2670 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671
2672 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002673 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 [] <code for S>
2675 [] POP_BLOCK
2676 [] JUMP_FORWARD L0
2677
2678 [tb, val, exc] L1: DUP )
2679 [tb, val, exc, exc] <evaluate E1> )
2680 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2681 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2682 [tb, val, exc] POP
2683 [tb, val] <assign to V1> (or POP if no V1)
2684 [tb] POP
2685 [] <code for S1>
2686 JUMP_FORWARD L0
2687
2688 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 .............................etc.......................
2690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2692
2693 [] L0: <next statement>
2694
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695 Of course, parts are not generated if Vi or Ei is not present.
2696*/
2697static int
2698compiler_try_except(struct compiler *c, stmt_ty s)
2699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002701 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 body = compiler_new_block(c);
2704 except = compiler_new_block(c);
2705 orelse = compiler_new_block(c);
2706 end = compiler_new_block(c);
2707 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2708 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002709 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002711 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002713 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 ADDOP(c, POP_BLOCK);
2715 compiler_pop_fblock(c, EXCEPT, body);
2716 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002717 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 compiler_use_next_block(c, except);
2719 for (i = 0; i < n; i++) {
2720 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002721 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 if (!handler->v.ExceptHandler.type && i < n-1)
2723 return compiler_error(c, "default 'except:' must be last");
2724 c->u->u_lineno_set = 0;
2725 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002726 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 except = compiler_new_block(c);
2728 if (except == NULL)
2729 return 0;
2730 if (handler->v.ExceptHandler.type) {
2731 ADDOP(c, DUP_TOP);
2732 VISIT(c, expr, handler->v.ExceptHandler.type);
2733 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2734 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2735 }
2736 ADDOP(c, POP_TOP);
2737 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002738 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002739
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002740 cleanup_end = compiler_new_block(c);
2741 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002742 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002743 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002744 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002745
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002746 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2747 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002749 /*
2750 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002751 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002752 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002753 try:
2754 # body
2755 finally:
2756 name = None
2757 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002758 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002760 /* second try: */
2761 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2762 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002763 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002764 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002766 /* second # body */
2767 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2768 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002769 ADDOP(c, BEGIN_FINALLY);
2770 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002772 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002773 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002774 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002775 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002777 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002778 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002779 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002780 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002782 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002783 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002784 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 }
2786 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002787 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002789 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002790 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002791 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792
Guido van Rossumb940e112007-01-10 16:19:56 +00002793 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002794 ADDOP(c, POP_TOP);
2795 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002796 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002797 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002799 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002800 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 }
2802 ADDOP_JREL(c, JUMP_FORWARD, end);
2803 compiler_use_next_block(c, except);
2804 }
2805 ADDOP(c, END_FINALLY);
2806 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002807 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 compiler_use_next_block(c, end);
2809 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810}
2811
2812static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002813compiler_try(struct compiler *c, stmt_ty s) {
2814 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2815 return compiler_try_finally(c, s);
2816 else
2817 return compiler_try_except(c, s);
2818}
2819
2820
2821static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002822compiler_import_as(struct compiler *c, identifier name, identifier asname)
2823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 /* The IMPORT_NAME opcode was already generated. This function
2825 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002828 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002830 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2831 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002832 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002833 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002834 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002836 while (1) {
2837 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002839 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002840 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002841 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002842 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002844 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002845 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002846 if (dot == -1) {
2847 break;
2848 }
2849 ADDOP(c, ROT_TWO);
2850 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002852 if (!compiler_nameop(c, asname, Store)) {
2853 return 0;
2854 }
2855 ADDOP(c, POP_TOP);
2856 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 }
2858 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859}
2860
2861static int
2862compiler_import(struct compiler *c, stmt_ty s)
2863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 /* The Import node stores a module name like a.b.c as a single
2865 string. This is convenient for all cases except
2866 import a.b.c as d
2867 where we need to parse that string to extract the individual
2868 module names.
2869 XXX Perhaps change the representation to make this case simpler?
2870 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002871 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 for (i = 0; i < n; i++) {
2874 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2875 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002877 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2878 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 if (alias->asname) {
2882 r = compiler_import_as(c, alias->name, alias->asname);
2883 if (!r)
2884 return r;
2885 }
2886 else {
2887 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002888 Py_ssize_t dot = PyUnicode_FindChar(
2889 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002890 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002891 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002892 if (tmp == NULL)
2893 return 0;
2894 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002896 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 Py_DECREF(tmp);
2898 }
2899 if (!r)
2900 return r;
2901 }
2902 }
2903 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904}
2905
2906static int
2907compiler_from_import(struct compiler *c, stmt_ty s)
2908{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002909 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002910 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 if (!empty_string) {
2914 empty_string = PyUnicode_FromString("");
2915 if (!empty_string)
2916 return 0;
2917 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002919 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002920
2921 names = PyTuple_New(n);
2922 if (!names)
2923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 /* build up the names */
2926 for (i = 0; i < n; i++) {
2927 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2928 Py_INCREF(alias->name);
2929 PyTuple_SET_ITEM(names, i, alias->name);
2930 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002933 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 Py_DECREF(names);
2935 return compiler_error(c, "from __future__ imports must occur "
2936 "at the beginning of the file");
2937 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002938 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 if (s->v.ImportFrom.module) {
2941 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2942 }
2943 else {
2944 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2945 }
2946 for (i = 0; i < n; i++) {
2947 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2948 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002950 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 assert(n == 1);
2952 ADDOP(c, IMPORT_STAR);
2953 return 1;
2954 }
2955
2956 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2957 store_name = alias->name;
2958 if (alias->asname)
2959 store_name = alias->asname;
2960
2961 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 return 0;
2963 }
2964 }
2965 /* remove imported module */
2966 ADDOP(c, POP_TOP);
2967 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968}
2969
2970static int
2971compiler_assert(struct compiler *c, stmt_ty s)
2972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 static PyObject *assertion_error = NULL;
2974 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975
Georg Brandl8334fd92010-12-04 10:26:46 +00002976 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 return 1;
2978 if (assertion_error == NULL) {
2979 assertion_error = PyUnicode_InternFromString("AssertionError");
2980 if (assertion_error == NULL)
2981 return 0;
2982 }
2983 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03002984 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
2985 {
2986 if (!compiler_warn(c, "assertion is always true, "
2987 "perhaps remove parentheses?"))
2988 {
Victor Stinner14e461d2013-08-26 22:28:21 +02002989 return 0;
2990 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 end = compiler_new_block(c);
2993 if (end == NULL)
2994 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002995 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
2996 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2998 if (s->v.Assert.msg) {
2999 VISIT(c, expr, s->v.Assert.msg);
3000 ADDOP_I(c, CALL_FUNCTION, 1);
3001 }
3002 ADDOP_I(c, RAISE_VARARGS, 1);
3003 compiler_use_next_block(c, end);
3004 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005}
3006
3007static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003008compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3009{
3010 if (c->c_interactive && c->c_nestlevel <= 1) {
3011 VISIT(c, expr, value);
3012 ADDOP(c, PRINT_EXPR);
3013 return 1;
3014 }
3015
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003016 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003017 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003018 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003019 }
3020
3021 VISIT(c, expr, value);
3022 ADDOP(c, POP_TOP);
3023 return 1;
3024}
3025
3026static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027compiler_visit_stmt(struct compiler *c, stmt_ty s)
3028{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003029 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 /* Always assign a lineno to the next instruction for a stmt. */
3032 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003033 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 switch (s->kind) {
3037 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003038 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 case ClassDef_kind:
3040 return compiler_class(c, s);
3041 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003042 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 case Delete_kind:
3044 VISIT_SEQ(c, expr, s->v.Delete.targets)
3045 break;
3046 case Assign_kind:
3047 n = asdl_seq_LEN(s->v.Assign.targets);
3048 VISIT(c, expr, s->v.Assign.value);
3049 for (i = 0; i < n; i++) {
3050 if (i < n - 1)
3051 ADDOP(c, DUP_TOP);
3052 VISIT(c, expr,
3053 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3054 }
3055 break;
3056 case AugAssign_kind:
3057 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003058 case AnnAssign_kind:
3059 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 case For_kind:
3061 return compiler_for(c, s);
3062 case While_kind:
3063 return compiler_while(c, s);
3064 case If_kind:
3065 return compiler_if(c, s);
3066 case Raise_kind:
3067 n = 0;
3068 if (s->v.Raise.exc) {
3069 VISIT(c, expr, s->v.Raise.exc);
3070 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003071 if (s->v.Raise.cause) {
3072 VISIT(c, expr, s->v.Raise.cause);
3073 n++;
3074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003076 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003078 case Try_kind:
3079 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 case Assert_kind:
3081 return compiler_assert(c, s);
3082 case Import_kind:
3083 return compiler_import(c, s);
3084 case ImportFrom_kind:
3085 return compiler_from_import(c, s);
3086 case Global_kind:
3087 case Nonlocal_kind:
3088 break;
3089 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003090 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 case Pass_kind:
3092 break;
3093 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003094 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 case Continue_kind:
3096 return compiler_continue(c);
3097 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003098 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003099 case AsyncFunctionDef_kind:
3100 return compiler_function(c, s, 1);
3101 case AsyncWith_kind:
3102 return compiler_async_with(c, s, 0);
3103 case AsyncFor_kind:
3104 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 }
Yury Selivanov75445082015-05-11 22:57:16 -04003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108}
3109
3110static int
3111unaryop(unaryop_ty op)
3112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 switch (op) {
3114 case Invert:
3115 return UNARY_INVERT;
3116 case Not:
3117 return UNARY_NOT;
3118 case UAdd:
3119 return UNARY_POSITIVE;
3120 case USub:
3121 return UNARY_NEGATIVE;
3122 default:
3123 PyErr_Format(PyExc_SystemError,
3124 "unary op %d should not be possible", op);
3125 return 0;
3126 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127}
3128
3129static int
3130binop(struct compiler *c, operator_ty op)
3131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 switch (op) {
3133 case Add:
3134 return BINARY_ADD;
3135 case Sub:
3136 return BINARY_SUBTRACT;
3137 case Mult:
3138 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003139 case MatMult:
3140 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 case Div:
3142 return BINARY_TRUE_DIVIDE;
3143 case Mod:
3144 return BINARY_MODULO;
3145 case Pow:
3146 return BINARY_POWER;
3147 case LShift:
3148 return BINARY_LSHIFT;
3149 case RShift:
3150 return BINARY_RSHIFT;
3151 case BitOr:
3152 return BINARY_OR;
3153 case BitXor:
3154 return BINARY_XOR;
3155 case BitAnd:
3156 return BINARY_AND;
3157 case FloorDiv:
3158 return BINARY_FLOOR_DIVIDE;
3159 default:
3160 PyErr_Format(PyExc_SystemError,
3161 "binary op %d should not be possible", op);
3162 return 0;
3163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164}
3165
3166static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003167inplace_binop(struct compiler *c, operator_ty op)
3168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 switch (op) {
3170 case Add:
3171 return INPLACE_ADD;
3172 case Sub:
3173 return INPLACE_SUBTRACT;
3174 case Mult:
3175 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003176 case MatMult:
3177 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 case Div:
3179 return INPLACE_TRUE_DIVIDE;
3180 case Mod:
3181 return INPLACE_MODULO;
3182 case Pow:
3183 return INPLACE_POWER;
3184 case LShift:
3185 return INPLACE_LSHIFT;
3186 case RShift:
3187 return INPLACE_RSHIFT;
3188 case BitOr:
3189 return INPLACE_OR;
3190 case BitXor:
3191 return INPLACE_XOR;
3192 case BitAnd:
3193 return INPLACE_AND;
3194 case FloorDiv:
3195 return INPLACE_FLOOR_DIVIDE;
3196 default:
3197 PyErr_Format(PyExc_SystemError,
3198 "inplace binary op %d should not be possible", op);
3199 return 0;
3200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201}
3202
3203static int
3204compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3205{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003206 int op, scope;
3207 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 PyObject *dict = c->u->u_names;
3211 PyObject *mangled;
3212 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003214 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3215 !_PyUnicode_EqualToASCIIString(name, "True") &&
3216 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003217
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003218 mangled = _Py_Mangle(c->u->u_private, name);
3219 if (!mangled)
3220 return 0;
3221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 op = 0;
3223 optype = OP_NAME;
3224 scope = PyST_GetScope(c->u->u_ste, mangled);
3225 switch (scope) {
3226 case FREE:
3227 dict = c->u->u_freevars;
3228 optype = OP_DEREF;
3229 break;
3230 case CELL:
3231 dict = c->u->u_cellvars;
3232 optype = OP_DEREF;
3233 break;
3234 case LOCAL:
3235 if (c->u->u_ste->ste_type == FunctionBlock)
3236 optype = OP_FAST;
3237 break;
3238 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003239 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 optype = OP_GLOBAL;
3241 break;
3242 case GLOBAL_EXPLICIT:
3243 optype = OP_GLOBAL;
3244 break;
3245 default:
3246 /* scope can be 0 */
3247 break;
3248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003251 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 switch (optype) {
3254 case OP_DEREF:
3255 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003256 case Load:
3257 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3258 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 case Store: op = STORE_DEREF; break;
3260 case AugLoad:
3261 case AugStore:
3262 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003263 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 case Param:
3265 default:
3266 PyErr_SetString(PyExc_SystemError,
3267 "param invalid for deref variable");
3268 return 0;
3269 }
3270 break;
3271 case OP_FAST:
3272 switch (ctx) {
3273 case Load: op = LOAD_FAST; break;
3274 case Store: op = STORE_FAST; break;
3275 case Del: op = DELETE_FAST; break;
3276 case AugLoad:
3277 case AugStore:
3278 break;
3279 case Param:
3280 default:
3281 PyErr_SetString(PyExc_SystemError,
3282 "param invalid for local variable");
3283 return 0;
3284 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003285 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 return 1;
3287 case OP_GLOBAL:
3288 switch (ctx) {
3289 case Load: op = LOAD_GLOBAL; break;
3290 case Store: op = STORE_GLOBAL; break;
3291 case Del: op = DELETE_GLOBAL; break;
3292 case AugLoad:
3293 case AugStore:
3294 break;
3295 case Param:
3296 default:
3297 PyErr_SetString(PyExc_SystemError,
3298 "param invalid for global variable");
3299 return 0;
3300 }
3301 break;
3302 case OP_NAME:
3303 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003304 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 case Store: op = STORE_NAME; break;
3306 case Del: op = DELETE_NAME; break;
3307 case AugLoad:
3308 case AugStore:
3309 break;
3310 case Param:
3311 default:
3312 PyErr_SetString(PyExc_SystemError,
3313 "param invalid for name variable");
3314 return 0;
3315 }
3316 break;
3317 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 assert(op);
3320 arg = compiler_add_o(c, dict, mangled);
3321 Py_DECREF(mangled);
3322 if (arg < 0)
3323 return 0;
3324 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325}
3326
3327static int
3328compiler_boolop(struct compiler *c, expr_ty e)
3329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003331 int jumpi;
3332 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 assert(e->kind == BoolOp_kind);
3336 if (e->v.BoolOp.op == And)
3337 jumpi = JUMP_IF_FALSE_OR_POP;
3338 else
3339 jumpi = JUMP_IF_TRUE_OR_POP;
3340 end = compiler_new_block(c);
3341 if (end == NULL)
3342 return 0;
3343 s = e->v.BoolOp.values;
3344 n = asdl_seq_LEN(s) - 1;
3345 assert(n >= 0);
3346 for (i = 0; i < n; ++i) {
3347 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3348 ADDOP_JABS(c, jumpi, end);
3349 }
3350 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3351 compiler_use_next_block(c, end);
3352 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353}
3354
3355static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003356starunpack_helper(struct compiler *c, asdl_seq *elts,
3357 int single_op, int inner_op, int outer_op)
3358{
3359 Py_ssize_t n = asdl_seq_LEN(elts);
3360 Py_ssize_t i, nsubitems = 0, nseen = 0;
3361 for (i = 0; i < n; i++) {
3362 expr_ty elt = asdl_seq_GET(elts, i);
3363 if (elt->kind == Starred_kind) {
3364 if (nseen) {
3365 ADDOP_I(c, inner_op, nseen);
3366 nseen = 0;
3367 nsubitems++;
3368 }
3369 VISIT(c, expr, elt->v.Starred.value);
3370 nsubitems++;
3371 }
3372 else {
3373 VISIT(c, expr, elt);
3374 nseen++;
3375 }
3376 }
3377 if (nsubitems) {
3378 if (nseen) {
3379 ADDOP_I(c, inner_op, nseen);
3380 nsubitems++;
3381 }
3382 ADDOP_I(c, outer_op, nsubitems);
3383 }
3384 else
3385 ADDOP_I(c, single_op, nseen);
3386 return 1;
3387}
3388
3389static int
3390assignment_helper(struct compiler *c, asdl_seq *elts)
3391{
3392 Py_ssize_t n = asdl_seq_LEN(elts);
3393 Py_ssize_t i;
3394 int seen_star = 0;
3395 for (i = 0; i < n; i++) {
3396 expr_ty elt = asdl_seq_GET(elts, i);
3397 if (elt->kind == Starred_kind && !seen_star) {
3398 if ((i >= (1 << 8)) ||
3399 (n-i-1 >= (INT_MAX >> 8)))
3400 return compiler_error(c,
3401 "too many expressions in "
3402 "star-unpacking assignment");
3403 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3404 seen_star = 1;
3405 asdl_seq_SET(elts, i, elt->v.Starred.value);
3406 }
3407 else if (elt->kind == Starred_kind) {
3408 return compiler_error(c,
3409 "two starred expressions in assignment");
3410 }
3411 }
3412 if (!seen_star) {
3413 ADDOP_I(c, UNPACK_SEQUENCE, n);
3414 }
3415 VISIT_SEQ(c, expr, elts);
3416 return 1;
3417}
3418
3419static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420compiler_list(struct compiler *c, expr_ty e)
3421{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003422 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003424 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003426 else if (e->v.List.ctx == Load) {
3427 return starunpack_helper(c, elts,
3428 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003430 else
3431 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433}
3434
3435static int
3436compiler_tuple(struct compiler *c, expr_ty e)
3437{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003438 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003440 return assignment_helper(c, elts);
3441 }
3442 else if (e->v.Tuple.ctx == Load) {
3443 return starunpack_helper(c, elts,
3444 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3445 }
3446 else
3447 VISIT_SEQ(c, expr, elts);
3448 return 1;
3449}
3450
3451static int
3452compiler_set(struct compiler *c, expr_ty e)
3453{
3454 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3455 BUILD_SET, BUILD_SET_UNPACK);
3456}
3457
3458static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003459are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3460{
3461 Py_ssize_t i;
3462 for (i = begin; i < end; i++) {
3463 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003464 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003465 return 0;
3466 }
3467 return 1;
3468}
3469
3470static int
3471compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3472{
3473 Py_ssize_t i, n = end - begin;
3474 PyObject *keys, *key;
3475 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3476 for (i = begin; i < end; i++) {
3477 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3478 }
3479 keys = PyTuple_New(n);
3480 if (keys == NULL) {
3481 return 0;
3482 }
3483 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003484 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003485 Py_INCREF(key);
3486 PyTuple_SET_ITEM(keys, i - begin, key);
3487 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003488 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003489 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3490 }
3491 else {
3492 for (i = begin; i < end; i++) {
3493 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3494 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3495 }
3496 ADDOP_I(c, BUILD_MAP, n);
3497 }
3498 return 1;
3499}
3500
3501static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003502compiler_dict(struct compiler *c, expr_ty e)
3503{
Victor Stinner976bb402016-03-23 11:36:19 +01003504 Py_ssize_t i, n, elements;
3505 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003506 int is_unpacking = 0;
3507 n = asdl_seq_LEN(e->v.Dict.values);
3508 containers = 0;
3509 elements = 0;
3510 for (i = 0; i < n; i++) {
3511 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3512 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003513 if (!compiler_subdict(c, e, i - elements, i))
3514 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003515 containers++;
3516 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003518 if (is_unpacking) {
3519 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3520 containers++;
3521 }
3522 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003523 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 }
3525 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003526 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003527 if (!compiler_subdict(c, e, n - elements, n))
3528 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003529 containers++;
3530 }
3531 /* If there is more than one dict, they need to be merged into a new
3532 * dict. If there is one dict and it's an unpacking, then it needs
3533 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003534 if (containers > 1 || is_unpacking) {
3535 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 }
3537 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538}
3539
3540static int
3541compiler_compare(struct compiler *c, expr_ty e)
3542{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003543 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003546 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3547 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3548 if (n == 0) {
3549 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3550 ADDOP_I(c, COMPARE_OP,
3551 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3552 }
3553 else {
3554 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 if (cleanup == NULL)
3556 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003557 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 VISIT(c, expr,
3559 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003560 ADDOP(c, DUP_TOP);
3561 ADDOP(c, ROT_THREE);
3562 ADDOP_I(c, COMPARE_OP,
3563 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3564 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3565 NEXT_BLOCK(c);
3566 }
3567 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3568 ADDOP_I(c, COMPARE_OP,
3569 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 basicblock *end = compiler_new_block(c);
3571 if (end == NULL)
3572 return 0;
3573 ADDOP_JREL(c, JUMP_FORWARD, end);
3574 compiler_use_next_block(c, cleanup);
3575 ADDOP(c, ROT_TWO);
3576 ADDOP(c, POP_TOP);
3577 compiler_use_next_block(c, end);
3578 }
3579 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580}
3581
3582static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003583maybe_optimize_method_call(struct compiler *c, expr_ty e)
3584{
3585 Py_ssize_t argsl, i;
3586 expr_ty meth = e->v.Call.func;
3587 asdl_seq *args = e->v.Call.args;
3588
3589 /* Check that the call node is an attribute access, and that
3590 the call doesn't have keyword parameters. */
3591 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3592 asdl_seq_LEN(e->v.Call.keywords))
3593 return -1;
3594
3595 /* Check that there are no *varargs types of arguments. */
3596 argsl = asdl_seq_LEN(args);
3597 for (i = 0; i < argsl; i++) {
3598 expr_ty elt = asdl_seq_GET(args, i);
3599 if (elt->kind == Starred_kind) {
3600 return -1;
3601 }
3602 }
3603
3604 /* Alright, we can optimize the code. */
3605 VISIT(c, expr, meth->v.Attribute.value);
3606 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3607 VISIT_SEQ(c, expr, e->v.Call.args);
3608 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3609 return 1;
3610}
3611
3612static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613compiler_call(struct compiler *c, expr_ty e)
3614{
Yury Selivanovf2392132016-12-13 19:03:51 -05003615 if (maybe_optimize_method_call(c, e) > 0)
3616 return 1;
3617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 VISIT(c, expr, e->v.Call.func);
3619 return compiler_call_helper(c, 0,
3620 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003621 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003622}
3623
Eric V. Smith235a6f02015-09-19 14:51:32 -04003624static int
3625compiler_joined_str(struct compiler *c, expr_ty e)
3626{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003627 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003628 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3629 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003630 return 1;
3631}
3632
Eric V. Smitha78c7952015-11-03 12:45:05 -05003633/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003634static int
3635compiler_formatted_value(struct compiler *c, expr_ty e)
3636{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003637 /* Our oparg encodes 2 pieces of information: the conversion
3638 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003639
Eric V. Smitha78c7952015-11-03 12:45:05 -05003640 Convert the conversion char to 2 bits:
3641 None: 000 0x0 FVC_NONE
3642 !s : 001 0x1 FVC_STR
3643 !r : 010 0x2 FVC_REPR
3644 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003645
Eric V. Smitha78c7952015-11-03 12:45:05 -05003646 next bit is whether or not we have a format spec:
3647 yes : 100 0x4
3648 no : 000 0x0
3649 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003650
Eric V. Smitha78c7952015-11-03 12:45:05 -05003651 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003652
Eric V. Smitha78c7952015-11-03 12:45:05 -05003653 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003654 VISIT(c, expr, e->v.FormattedValue.value);
3655
Eric V. Smitha78c7952015-11-03 12:45:05 -05003656 switch (e->v.FormattedValue.conversion) {
3657 case 's': oparg = FVC_STR; break;
3658 case 'r': oparg = FVC_REPR; break;
3659 case 'a': oparg = FVC_ASCII; break;
3660 case -1: oparg = FVC_NONE; break;
3661 default:
3662 PyErr_SetString(PyExc_SystemError,
3663 "Unrecognized conversion character");
3664 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003665 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003666 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003667 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003668 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003669 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003670 }
3671
Eric V. Smitha78c7952015-11-03 12:45:05 -05003672 /* And push our opcode and oparg */
3673 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003674 return 1;
3675}
3676
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003677static int
3678compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3679{
3680 Py_ssize_t i, n = end - begin;
3681 keyword_ty kw;
3682 PyObject *keys, *key;
3683 assert(n > 0);
3684 if (n > 1) {
3685 for (i = begin; i < end; i++) {
3686 kw = asdl_seq_GET(keywords, i);
3687 VISIT(c, expr, kw->value);
3688 }
3689 keys = PyTuple_New(n);
3690 if (keys == NULL) {
3691 return 0;
3692 }
3693 for (i = begin; i < end; i++) {
3694 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3695 Py_INCREF(key);
3696 PyTuple_SET_ITEM(keys, i - begin, key);
3697 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003698 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003699 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3700 }
3701 else {
3702 /* a for loop only executes once */
3703 for (i = begin; i < end; i++) {
3704 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003705 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003706 VISIT(c, expr, kw->value);
3707 }
3708 ADDOP_I(c, BUILD_MAP, n);
3709 }
3710 return 1;
3711}
3712
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003713/* shared code between compiler_call and compiler_class */
3714static int
3715compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003716 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003717 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003718 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003719{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003720 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003721 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003722
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003723 /* the number of tuples and dictionaries on the stack */
3724 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3725
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003726 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003727 nkwelts = asdl_seq_LEN(keywords);
3728
3729 for (i = 0; i < nkwelts; i++) {
3730 keyword_ty kw = asdl_seq_GET(keywords, i);
3731 if (kw->arg == NULL) {
3732 mustdictunpack = 1;
3733 break;
3734 }
3735 }
3736
3737 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003738 for (i = 0; i < nelts; i++) {
3739 expr_ty elt = asdl_seq_GET(args, i);
3740 if (elt->kind == Starred_kind) {
3741 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003742 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003743 if (nseen) {
3744 ADDOP_I(c, BUILD_TUPLE, nseen);
3745 nseen = 0;
3746 nsubargs++;
3747 }
3748 VISIT(c, expr, elt->v.Starred.value);
3749 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003750 }
3751 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003752 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003753 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003754 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003756
3757 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003758 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003759 if (nseen) {
3760 /* Pack up any trailing positional arguments. */
3761 ADDOP_I(c, BUILD_TUPLE, nseen);
3762 nsubargs++;
3763 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003764 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003765 /* If we ended up with more than one stararg, we need
3766 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003767 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003768 }
3769 else if (nsubargs == 0) {
3770 ADDOP_I(c, BUILD_TUPLE, 0);
3771 }
3772 nseen = 0; /* the number of keyword arguments on the stack following */
3773 for (i = 0; i < nkwelts; i++) {
3774 keyword_ty kw = asdl_seq_GET(keywords, i);
3775 if (kw->arg == NULL) {
3776 /* A keyword argument unpacking. */
3777 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003778 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3779 return 0;
3780 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003781 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003782 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003783 VISIT(c, expr, kw->value);
3784 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003786 else {
3787 nseen++;
3788 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003790 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003791 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003792 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003793 return 0;
3794 nsubkwargs++;
3795 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003796 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003798 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003800 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3801 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003803 else if (nkwelts) {
3804 PyObject *names;
3805 VISIT_SEQ(c, keyword, keywords);
3806 names = PyTuple_New(nkwelts);
3807 if (names == NULL) {
3808 return 0;
3809 }
3810 for (i = 0; i < nkwelts; i++) {
3811 keyword_ty kw = asdl_seq_GET(keywords, i);
3812 Py_INCREF(kw->arg);
3813 PyTuple_SET_ITEM(names, i, kw->arg);
3814 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003815 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003816 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3817 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003819 else {
3820 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3821 return 1;
3822 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823}
3824
Nick Coghlan650f0d02007-04-15 12:05:43 +00003825
3826/* List and set comprehensions and generator expressions work by creating a
3827 nested function to perform the actual iteration. This means that the
3828 iteration variables don't leak into the current scope.
3829 The defined function is called immediately following its definition, with the
3830 result of that call being the result of the expression.
3831 The LC/SC version returns the populated container, while the GE version is
3832 flagged in symtable.c as a generator, so it returns the generator object
3833 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003834
3835 Possible cleanups:
3836 - iterate over the generator sequence instead of using recursion
3837*/
3838
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003839
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841compiler_comprehension_generator(struct compiler *c,
3842 asdl_seq *generators, int gen_index,
3843 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003845 comprehension_ty gen;
3846 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3847 if (gen->is_async) {
3848 return compiler_async_comprehension_generator(
3849 c, generators, gen_index, elt, val, type);
3850 } else {
3851 return compiler_sync_comprehension_generator(
3852 c, generators, gen_index, elt, val, type);
3853 }
3854}
3855
3856static int
3857compiler_sync_comprehension_generator(struct compiler *c,
3858 asdl_seq *generators, int gen_index,
3859 expr_ty elt, expr_ty val, int type)
3860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 /* generate code for the iterator, then each of the ifs,
3862 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 comprehension_ty gen;
3865 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003866 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 start = compiler_new_block(c);
3869 skip = compiler_new_block(c);
3870 if_cleanup = compiler_new_block(c);
3871 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3874 anchor == NULL)
3875 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 if (gen_index == 0) {
3880 /* Receive outermost iter as an implicit argument */
3881 c->u->u_argcount = 1;
3882 ADDOP_I(c, LOAD_FAST, 0);
3883 }
3884 else {
3885 /* Sub-iter - calculate on the fly */
3886 VISIT(c, expr, gen->iter);
3887 ADDOP(c, GET_ITER);
3888 }
3889 compiler_use_next_block(c, start);
3890 ADDOP_JREL(c, FOR_ITER, anchor);
3891 NEXT_BLOCK(c);
3892 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 /* XXX this needs to be cleaned up...a lot! */
3895 n = asdl_seq_LEN(gen->ifs);
3896 for (i = 0; i < n; i++) {
3897 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003898 if (!compiler_jump_if(c, e, if_cleanup, 0))
3899 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 NEXT_BLOCK(c);
3901 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (++gen_index < asdl_seq_LEN(generators))
3904 if (!compiler_comprehension_generator(c,
3905 generators, gen_index,
3906 elt, val, type))
3907 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 /* only append after the last for generator */
3910 if (gen_index >= asdl_seq_LEN(generators)) {
3911 /* comprehension specific code */
3912 switch (type) {
3913 case COMP_GENEXP:
3914 VISIT(c, expr, elt);
3915 ADDOP(c, YIELD_VALUE);
3916 ADDOP(c, POP_TOP);
3917 break;
3918 case COMP_LISTCOMP:
3919 VISIT(c, expr, elt);
3920 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3921 break;
3922 case COMP_SETCOMP:
3923 VISIT(c, expr, elt);
3924 ADDOP_I(c, SET_ADD, gen_index + 1);
3925 break;
3926 case COMP_DICTCOMP:
3927 /* With 'd[k] = v', v is evaluated before k, so we do
3928 the same. */
3929 VISIT(c, expr, val);
3930 VISIT(c, expr, elt);
3931 ADDOP_I(c, MAP_ADD, gen_index + 1);
3932 break;
3933 default:
3934 return 0;
3935 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 compiler_use_next_block(c, skip);
3938 }
3939 compiler_use_next_block(c, if_cleanup);
3940 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3941 compiler_use_next_block(c, anchor);
3942
3943 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944}
3945
3946static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003947compiler_async_comprehension_generator(struct compiler *c,
3948 asdl_seq *generators, int gen_index,
3949 expr_ty elt, expr_ty val, int type)
3950{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003951 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003952 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003953 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003954 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003955 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003956 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003957
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003958 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003959 return 0;
3960 }
3961
3962 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3963
3964 if (gen_index == 0) {
3965 /* Receive outermost iter as an implicit argument */
3966 c->u->u_argcount = 1;
3967 ADDOP_I(c, LOAD_FAST, 0);
3968 }
3969 else {
3970 /* Sub-iter - calculate on the fly */
3971 VISIT(c, expr, gen->iter);
3972 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003973 }
3974
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003975 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003976
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003977 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003978 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003979 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003980 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003981 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02003982 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003983
3984 n = asdl_seq_LEN(gen->ifs);
3985 for (i = 0; i < n; i++) {
3986 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003987 if (!compiler_jump_if(c, e, if_cleanup, 0))
3988 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003989 NEXT_BLOCK(c);
3990 }
3991
3992 if (++gen_index < asdl_seq_LEN(generators))
3993 if (!compiler_comprehension_generator(c,
3994 generators, gen_index,
3995 elt, val, type))
3996 return 0;
3997
3998 /* only append after the last for generator */
3999 if (gen_index >= asdl_seq_LEN(generators)) {
4000 /* comprehension specific code */
4001 switch (type) {
4002 case COMP_GENEXP:
4003 VISIT(c, expr, elt);
4004 ADDOP(c, YIELD_VALUE);
4005 ADDOP(c, POP_TOP);
4006 break;
4007 case COMP_LISTCOMP:
4008 VISIT(c, expr, elt);
4009 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4010 break;
4011 case COMP_SETCOMP:
4012 VISIT(c, expr, elt);
4013 ADDOP_I(c, SET_ADD, gen_index + 1);
4014 break;
4015 case COMP_DICTCOMP:
4016 /* With 'd[k] = v', v is evaluated before k, so we do
4017 the same. */
4018 VISIT(c, expr, val);
4019 VISIT(c, expr, elt);
4020 ADDOP_I(c, MAP_ADD, gen_index + 1);
4021 break;
4022 default:
4023 return 0;
4024 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004025 }
4026 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004027 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4028
4029 compiler_use_next_block(c, except);
4030 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004031
4032 return 1;
4033}
4034
4035static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004036compiler_comprehension(struct compiler *c, expr_ty e, int type,
4037 identifier name, asdl_seq *generators, expr_ty elt,
4038 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004041 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004042 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004043 int is_async_function = c->u->u_ste->ste_coroutine;
4044 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004045
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004046 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004047
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004048 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4049 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004050 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004052 }
4053
4054 is_async_generator = c->u->u_ste->ste_coroutine;
4055
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004056 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004057 compiler_error(c, "asynchronous comprehension outside of "
4058 "an asynchronous function");
4059 goto error_in_scope;
4060 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 if (type != COMP_GENEXP) {
4063 int op;
4064 switch (type) {
4065 case COMP_LISTCOMP:
4066 op = BUILD_LIST;
4067 break;
4068 case COMP_SETCOMP:
4069 op = BUILD_SET;
4070 break;
4071 case COMP_DICTCOMP:
4072 op = BUILD_MAP;
4073 break;
4074 default:
4075 PyErr_Format(PyExc_SystemError,
4076 "unknown comprehension type %d", type);
4077 goto error_in_scope;
4078 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 ADDOP_I(c, op, 0);
4081 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 if (!compiler_comprehension_generator(c, generators, 0, elt,
4084 val, type))
4085 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 if (type != COMP_GENEXP) {
4088 ADDOP(c, RETURN_VALUE);
4089 }
4090
4091 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004092 qualname = c->u->u_qualname;
4093 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004095 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 goto error;
4097
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004098 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004100 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 Py_DECREF(co);
4102
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004103 VISIT(c, expr, outermost->iter);
4104
4105 if (outermost->is_async) {
4106 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004107 } else {
4108 ADDOP(c, GET_ITER);
4109 }
4110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004112
4113 if (is_async_generator && type != COMP_GENEXP) {
4114 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004115 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004116 ADDOP(c, YIELD_FROM);
4117 }
4118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004120error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004122error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004123 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 Py_XDECREF(co);
4125 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004126}
4127
4128static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004129compiler_genexp(struct compiler *c, expr_ty e)
4130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 static identifier name;
4132 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004133 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 if (!name)
4135 return 0;
4136 }
4137 assert(e->kind == GeneratorExp_kind);
4138 return compiler_comprehension(c, e, COMP_GENEXP, name,
4139 e->v.GeneratorExp.generators,
4140 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141}
4142
4143static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004144compiler_listcomp(struct compiler *c, expr_ty e)
4145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 static identifier name;
4147 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004148 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (!name)
4150 return 0;
4151 }
4152 assert(e->kind == ListComp_kind);
4153 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4154 e->v.ListComp.generators,
4155 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004156}
4157
4158static int
4159compiler_setcomp(struct compiler *c, expr_ty e)
4160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 static identifier name;
4162 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004163 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 if (!name)
4165 return 0;
4166 }
4167 assert(e->kind == SetComp_kind);
4168 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4169 e->v.SetComp.generators,
4170 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004171}
4172
4173
4174static int
4175compiler_dictcomp(struct compiler *c, expr_ty e)
4176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 static identifier name;
4178 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004179 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 if (!name)
4181 return 0;
4182 }
4183 assert(e->kind == DictComp_kind);
4184 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4185 e->v.DictComp.generators,
4186 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004187}
4188
4189
4190static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191compiler_visit_keyword(struct compiler *c, keyword_ty k)
4192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 VISIT(c, expr, k->value);
4194 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195}
4196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198 whether they are true or false.
4199
4200 Return values: 1 for true, 0 for false, -1 for non-constant.
4201 */
4202
4203static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004204expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004206 if (e->kind == Constant_kind) {
4207 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004208 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004209 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004210}
4211
Yury Selivanov75445082015-05-11 22:57:16 -04004212
4213/*
4214 Implements the async with statement.
4215
4216 The semantics outlined in that PEP are as follows:
4217
4218 async with EXPR as VAR:
4219 BLOCK
4220
4221 It is implemented roughly as:
4222
4223 context = EXPR
4224 exit = context.__aexit__ # not calling it
4225 value = await context.__aenter__()
4226 try:
4227 VAR = value # if VAR present in the syntax
4228 BLOCK
4229 finally:
4230 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004231 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004232 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004233 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004234 if not (await exit(*exc)):
4235 raise
4236 */
4237static int
4238compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4239{
4240 basicblock *block, *finally;
4241 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4242
4243 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004244 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4245 return compiler_error(c, "'async with' outside async function");
4246 }
Yury Selivanov75445082015-05-11 22:57:16 -04004247
4248 block = compiler_new_block(c);
4249 finally = compiler_new_block(c);
4250 if (!block || !finally)
4251 return 0;
4252
4253 /* Evaluate EXPR */
4254 VISIT(c, expr, item->context_expr);
4255
4256 ADDOP(c, BEFORE_ASYNC_WITH);
4257 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004258 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004259 ADDOP(c, YIELD_FROM);
4260
4261 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4262
4263 /* SETUP_ASYNC_WITH pushes a finally block. */
4264 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004265 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004266 return 0;
4267 }
4268
4269 if (item->optional_vars) {
4270 VISIT(c, expr, item->optional_vars);
4271 }
4272 else {
4273 /* Discard result from context.__aenter__() */
4274 ADDOP(c, POP_TOP);
4275 }
4276
4277 pos++;
4278 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4279 /* BLOCK code */
4280 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4281 else if (!compiler_async_with(c, s, pos))
4282 return 0;
4283
4284 /* End of try block; start the finally block */
4285 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004286 ADDOP(c, BEGIN_FINALLY);
4287 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004288
Yury Selivanov75445082015-05-11 22:57:16 -04004289 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004290 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004291 return 0;
4292
4293 /* Finally block starts; context.__exit__ is on the stack under
4294 the exception or return information. Just issue our magic
4295 opcode. */
4296 ADDOP(c, WITH_CLEANUP_START);
4297
4298 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004299 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004300 ADDOP(c, YIELD_FROM);
4301
4302 ADDOP(c, WITH_CLEANUP_FINISH);
4303
4304 /* Finally block ends. */
4305 ADDOP(c, END_FINALLY);
4306 compiler_pop_fblock(c, FINALLY_END, finally);
4307 return 1;
4308}
4309
4310
Guido van Rossumc2e20742006-02-27 22:32:47 +00004311/*
4312 Implements the with statement from PEP 343.
4313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004315
4316 with EXPR as VAR:
4317 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318
Guido van Rossumc2e20742006-02-27 22:32:47 +00004319 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320
Thomas Wouters477c8d52006-05-27 19:21:47 +00004321 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004322 exit = context.__exit__ # not calling it
4323 value = context.__enter__()
4324 try:
4325 VAR = value # if VAR present in the syntax
4326 BLOCK
4327 finally:
4328 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004329 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004330 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004331 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004332 exit(*exc)
4333 */
4334static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004335compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004336{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004337 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004338 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004339
4340 assert(s->kind == With_kind);
4341
Guido van Rossumc2e20742006-02-27 22:32:47 +00004342 block = compiler_new_block(c);
4343 finally = compiler_new_block(c);
4344 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004345 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004346
Thomas Wouters477c8d52006-05-27 19:21:47 +00004347 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004348 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004349 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004350
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004351 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004352 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004353 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004354 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004355 }
4356
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004357 if (item->optional_vars) {
4358 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004359 }
4360 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004362 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004363 }
4364
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004365 pos++;
4366 if (pos == asdl_seq_LEN(s->v.With.items))
4367 /* BLOCK code */
4368 VISIT_SEQ(c, stmt, s->v.With.body)
4369 else if (!compiler_with(c, s, pos))
4370 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004371
4372 /* End of try block; start the finally block */
4373 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004374 ADDOP(c, BEGIN_FINALLY);
4375 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004376
Guido van Rossumc2e20742006-02-27 22:32:47 +00004377 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004378 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004379 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004380
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004381 /* Finally block starts; context.__exit__ is on the stack under
4382 the exception or return information. Just issue our magic
4383 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004384 ADDOP(c, WITH_CLEANUP_START);
4385 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004386
4387 /* Finally block ends. */
4388 ADDOP(c, END_FINALLY);
4389 compiler_pop_fblock(c, FINALLY_END, finally);
4390 return 1;
4391}
4392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004394compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 switch (e->kind) {
4397 case BoolOp_kind:
4398 return compiler_boolop(c, e);
4399 case BinOp_kind:
4400 VISIT(c, expr, e->v.BinOp.left);
4401 VISIT(c, expr, e->v.BinOp.right);
4402 ADDOP(c, binop(c, e->v.BinOp.op));
4403 break;
4404 case UnaryOp_kind:
4405 VISIT(c, expr, e->v.UnaryOp.operand);
4406 ADDOP(c, unaryop(e->v.UnaryOp.op));
4407 break;
4408 case Lambda_kind:
4409 return compiler_lambda(c, e);
4410 case IfExp_kind:
4411 return compiler_ifexp(c, e);
4412 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004413 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004415 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 case GeneratorExp_kind:
4417 return compiler_genexp(c, e);
4418 case ListComp_kind:
4419 return compiler_listcomp(c, e);
4420 case SetComp_kind:
4421 return compiler_setcomp(c, e);
4422 case DictComp_kind:
4423 return compiler_dictcomp(c, e);
4424 case Yield_kind:
4425 if (c->u->u_ste->ste_type != FunctionBlock)
4426 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004427 if (e->v.Yield.value) {
4428 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 }
4430 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004431 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004433 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004435 case YieldFrom_kind:
4436 if (c->u->u_ste->ste_type != FunctionBlock)
4437 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004438
4439 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4440 return compiler_error(c, "'yield from' inside async function");
4441
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004442 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004443 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004444 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004445 ADDOP(c, YIELD_FROM);
4446 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004447 case Await_kind:
4448 if (c->u->u_ste->ste_type != FunctionBlock)
4449 return compiler_error(c, "'await' outside function");
4450
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004451 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4452 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004453 return compiler_error(c, "'await' outside async function");
4454
4455 VISIT(c, expr, e->v.Await.value);
4456 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004457 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004458 ADDOP(c, YIELD_FROM);
4459 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 case Compare_kind:
4461 return compiler_compare(c, e);
4462 case Call_kind:
4463 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004464 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004465 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004466 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004467 case JoinedStr_kind:
4468 return compiler_joined_str(c, e);
4469 case FormattedValue_kind:
4470 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 /* The following exprs can be assignment targets. */
4472 case Attribute_kind:
4473 if (e->v.Attribute.ctx != AugStore)
4474 VISIT(c, expr, e->v.Attribute.value);
4475 switch (e->v.Attribute.ctx) {
4476 case AugLoad:
4477 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004478 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 case Load:
4480 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4481 break;
4482 case AugStore:
4483 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004484 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 case Store:
4486 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4487 break;
4488 case Del:
4489 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4490 break;
4491 case Param:
4492 default:
4493 PyErr_SetString(PyExc_SystemError,
4494 "param invalid in attribute expression");
4495 return 0;
4496 }
4497 break;
4498 case Subscript_kind:
4499 switch (e->v.Subscript.ctx) {
4500 case AugLoad:
4501 VISIT(c, expr, e->v.Subscript.value);
4502 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4503 break;
4504 case Load:
4505 VISIT(c, expr, e->v.Subscript.value);
4506 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4507 break;
4508 case AugStore:
4509 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4510 break;
4511 case Store:
4512 VISIT(c, expr, e->v.Subscript.value);
4513 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4514 break;
4515 case Del:
4516 VISIT(c, expr, e->v.Subscript.value);
4517 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4518 break;
4519 case Param:
4520 default:
4521 PyErr_SetString(PyExc_SystemError,
4522 "param invalid in subscript expression");
4523 return 0;
4524 }
4525 break;
4526 case Starred_kind:
4527 switch (e->v.Starred.ctx) {
4528 case Store:
4529 /* In all legitimate cases, the Starred node was already replaced
4530 * by compiler_list/compiler_tuple. XXX: is that okay? */
4531 return compiler_error(c,
4532 "starred assignment target must be in a list or tuple");
4533 default:
4534 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004535 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 }
4537 break;
4538 case Name_kind:
4539 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4540 /* child nodes of List and Tuple will have expr_context set */
4541 case List_kind:
4542 return compiler_list(c, e);
4543 case Tuple_kind:
4544 return compiler_tuple(c, e);
4545 }
4546 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004547}
4548
4549static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004550compiler_visit_expr(struct compiler *c, expr_ty e)
4551{
4552 /* If expr e has a different line number than the last expr/stmt,
4553 set a new line number for the next instruction.
4554 */
4555 int old_lineno = c->u->u_lineno;
4556 int old_col_offset = c->u->u_col_offset;
4557 if (e->lineno != c->u->u_lineno) {
4558 c->u->u_lineno = e->lineno;
4559 c->u->u_lineno_set = 0;
4560 }
4561 /* Updating the column offset is always harmless. */
4562 c->u->u_col_offset = e->col_offset;
4563
4564 int res = compiler_visit_expr1(c, e);
4565
4566 if (old_lineno != c->u->u_lineno) {
4567 c->u->u_lineno = old_lineno;
4568 c->u->u_lineno_set = 0;
4569 }
4570 c->u->u_col_offset = old_col_offset;
4571 return res;
4572}
4573
4574static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004575compiler_augassign(struct compiler *c, stmt_ty s)
4576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 expr_ty e = s->v.AugAssign.target;
4578 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 switch (e->kind) {
4583 case Attribute_kind:
4584 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4585 AugLoad, e->lineno, e->col_offset, c->c_arena);
4586 if (auge == NULL)
4587 return 0;
4588 VISIT(c, expr, auge);
4589 VISIT(c, expr, s->v.AugAssign.value);
4590 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4591 auge->v.Attribute.ctx = AugStore;
4592 VISIT(c, expr, auge);
4593 break;
4594 case Subscript_kind:
4595 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4596 AugLoad, e->lineno, e->col_offset, c->c_arena);
4597 if (auge == NULL)
4598 return 0;
4599 VISIT(c, expr, auge);
4600 VISIT(c, expr, s->v.AugAssign.value);
4601 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4602 auge->v.Subscript.ctx = AugStore;
4603 VISIT(c, expr, auge);
4604 break;
4605 case Name_kind:
4606 if (!compiler_nameop(c, e->v.Name.id, Load))
4607 return 0;
4608 VISIT(c, expr, s->v.AugAssign.value);
4609 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4610 return compiler_nameop(c, e->v.Name.id, Store);
4611 default:
4612 PyErr_Format(PyExc_SystemError,
4613 "invalid node type (%d) for augmented assignment",
4614 e->kind);
4615 return 0;
4616 }
4617 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004618}
4619
4620static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004621check_ann_expr(struct compiler *c, expr_ty e)
4622{
4623 VISIT(c, expr, e);
4624 ADDOP(c, POP_TOP);
4625 return 1;
4626}
4627
4628static int
4629check_annotation(struct compiler *c, stmt_ty s)
4630{
4631 /* Annotations are only evaluated in a module or class. */
4632 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4633 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4634 return check_ann_expr(c, s->v.AnnAssign.annotation);
4635 }
4636 return 1;
4637}
4638
4639static int
4640check_ann_slice(struct compiler *c, slice_ty sl)
4641{
4642 switch(sl->kind) {
4643 case Index_kind:
4644 return check_ann_expr(c, sl->v.Index.value);
4645 case Slice_kind:
4646 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4647 return 0;
4648 }
4649 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4650 return 0;
4651 }
4652 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4653 return 0;
4654 }
4655 break;
4656 default:
4657 PyErr_SetString(PyExc_SystemError,
4658 "unexpected slice kind");
4659 return 0;
4660 }
4661 return 1;
4662}
4663
4664static int
4665check_ann_subscr(struct compiler *c, slice_ty sl)
4666{
4667 /* We check that everything in a subscript is defined at runtime. */
4668 Py_ssize_t i, n;
4669
4670 switch (sl->kind) {
4671 case Index_kind:
4672 case Slice_kind:
4673 if (!check_ann_slice(c, sl)) {
4674 return 0;
4675 }
4676 break;
4677 case ExtSlice_kind:
4678 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4679 for (i = 0; i < n; i++) {
4680 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4681 switch (subsl->kind) {
4682 case Index_kind:
4683 case Slice_kind:
4684 if (!check_ann_slice(c, subsl)) {
4685 return 0;
4686 }
4687 break;
4688 case ExtSlice_kind:
4689 default:
4690 PyErr_SetString(PyExc_SystemError,
4691 "extended slice invalid in nested slice");
4692 return 0;
4693 }
4694 }
4695 break;
4696 default:
4697 PyErr_Format(PyExc_SystemError,
4698 "invalid subscript kind %d", sl->kind);
4699 return 0;
4700 }
4701 return 1;
4702}
4703
4704static int
4705compiler_annassign(struct compiler *c, stmt_ty s)
4706{
4707 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004708 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004709
4710 assert(s->kind == AnnAssign_kind);
4711
4712 /* We perform the actual assignment first. */
4713 if (s->v.AnnAssign.value) {
4714 VISIT(c, expr, s->v.AnnAssign.value);
4715 VISIT(c, expr, targ);
4716 }
4717 switch (targ->kind) {
4718 case Name_kind:
4719 /* If we have a simple name in a module or class, store annotation. */
4720 if (s->v.AnnAssign.simple &&
4721 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4722 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004723 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4724 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4725 }
4726 else {
4727 VISIT(c, expr, s->v.AnnAssign.annotation);
4728 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004729 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004730 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004731 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004732 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004733 }
4734 break;
4735 case Attribute_kind:
4736 if (!s->v.AnnAssign.value &&
4737 !check_ann_expr(c, targ->v.Attribute.value)) {
4738 return 0;
4739 }
4740 break;
4741 case Subscript_kind:
4742 if (!s->v.AnnAssign.value &&
4743 (!check_ann_expr(c, targ->v.Subscript.value) ||
4744 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4745 return 0;
4746 }
4747 break;
4748 default:
4749 PyErr_Format(PyExc_SystemError,
4750 "invalid node type (%d) for annotated assignment",
4751 targ->kind);
4752 return 0;
4753 }
4754 /* Annotation is evaluated last. */
4755 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4756 return 0;
4757 }
4758 return 1;
4759}
4760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004761/* Raises a SyntaxError and returns 0.
4762 If something goes wrong, a different exception may be raised.
4763*/
4764
4765static int
4766compiler_error(struct compiler *c, const char *errstr)
4767{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004768 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004770
Victor Stinner14e461d2013-08-26 22:28:21 +02004771 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 if (!loc) {
4773 Py_INCREF(Py_None);
4774 loc = Py_None;
4775 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004776 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004777 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778 if (!u)
4779 goto exit;
4780 v = Py_BuildValue("(zO)", errstr, u);
4781 if (!v)
4782 goto exit;
4783 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004784 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 Py_DECREF(loc);
4786 Py_XDECREF(u);
4787 Py_XDECREF(v);
4788 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004789}
4790
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004791/* Emits a SyntaxWarning and returns 1 on success.
4792 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4793 and returns 0.
4794*/
4795static int
4796compiler_warn(struct compiler *c, const char *errstr)
4797{
4798 PyObject *msg = PyUnicode_FromString(errstr);
4799 if (msg == NULL) {
4800 return 0;
4801 }
4802 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4803 c->u->u_lineno, NULL, NULL) < 0)
4804 {
4805 Py_DECREF(msg);
4806 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4807 PyErr_Clear();
4808 return compiler_error(c, errstr);
4809 }
4810 return 0;
4811 }
4812 Py_DECREF(msg);
4813 return 1;
4814}
4815
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004816static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817compiler_handle_subscr(struct compiler *c, const char *kind,
4818 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 /* XXX this code is duplicated */
4823 switch (ctx) {
4824 case AugLoad: /* fall through to Load */
4825 case Load: op = BINARY_SUBSCR; break;
4826 case AugStore:/* fall through to Store */
4827 case Store: op = STORE_SUBSCR; break;
4828 case Del: op = DELETE_SUBSCR; break;
4829 case Param:
4830 PyErr_Format(PyExc_SystemError,
4831 "invalid %s kind %d in subscript\n",
4832 kind, ctx);
4833 return 0;
4834 }
4835 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004836 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 }
4838 else if (ctx == AugStore) {
4839 ADDOP(c, ROT_THREE);
4840 }
4841 ADDOP(c, op);
4842 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004843}
4844
4845static int
4846compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 int n = 2;
4849 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 /* only handles the cases where BUILD_SLICE is emitted */
4852 if (s->v.Slice.lower) {
4853 VISIT(c, expr, s->v.Slice.lower);
4854 }
4855 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004856 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 if (s->v.Slice.upper) {
4860 VISIT(c, expr, s->v.Slice.upper);
4861 }
4862 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004863 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004864 }
4865
4866 if (s->v.Slice.step) {
4867 n++;
4868 VISIT(c, expr, s->v.Slice.step);
4869 }
4870 ADDOP_I(c, BUILD_SLICE, n);
4871 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004872}
4873
4874static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4876 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 switch (s->kind) {
4879 case Slice_kind:
4880 return compiler_slice(c, s, ctx);
4881 case Index_kind:
4882 VISIT(c, expr, s->v.Index.value);
4883 break;
4884 case ExtSlice_kind:
4885 default:
4886 PyErr_SetString(PyExc_SystemError,
4887 "extended slice invalid in nested slice");
4888 return 0;
4889 }
4890 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004891}
4892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004893static int
4894compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4895{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004896 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 switch (s->kind) {
4898 case Index_kind:
4899 kindname = "index";
4900 if (ctx != AugStore) {
4901 VISIT(c, expr, s->v.Index.value);
4902 }
4903 break;
4904 case Slice_kind:
4905 kindname = "slice";
4906 if (ctx != AugStore) {
4907 if (!compiler_slice(c, s, ctx))
4908 return 0;
4909 }
4910 break;
4911 case ExtSlice_kind:
4912 kindname = "extended slice";
4913 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004914 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 for (i = 0; i < n; i++) {
4916 slice_ty sub = (slice_ty)asdl_seq_GET(
4917 s->v.ExtSlice.dims, i);
4918 if (!compiler_visit_nested_slice(c, sub, ctx))
4919 return 0;
4920 }
4921 ADDOP_I(c, BUILD_TUPLE, n);
4922 }
4923 break;
4924 default:
4925 PyErr_Format(PyExc_SystemError,
4926 "invalid subscript kind %d", s->kind);
4927 return 0;
4928 }
4929 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004930}
4931
Thomas Wouters89f507f2006-12-13 04:49:30 +00004932/* End of the compiler section, beginning of the assembler section */
4933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004934/* do depth-first search of basic block graph, starting with block.
4935 post records the block indices in post-order.
4936
4937 XXX must handle implicit jumps from one block to next
4938*/
4939
Thomas Wouters89f507f2006-12-13 04:49:30 +00004940struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 PyObject *a_bytecode; /* string containing bytecode */
4942 int a_offset; /* offset into bytecode */
4943 int a_nblocks; /* number of reachable blocks */
4944 basicblock **a_postorder; /* list of blocks in dfs postorder */
4945 PyObject *a_lnotab; /* string containing lnotab */
4946 int a_lnotab_off; /* offset into lnotab */
4947 int a_lineno; /* last lineno of emitted instruction */
4948 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004949};
4950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004951static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004952dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004953{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004954 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004955
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004956 /* Get rid of recursion for normal control flow.
4957 Since the number of blocks is limited, unused space in a_postorder
4958 (from a_nblocks to end) can be used as a stack for still not ordered
4959 blocks. */
4960 for (j = end; b && !b->b_seen; b = b->b_next) {
4961 b->b_seen = 1;
4962 assert(a->a_nblocks < j);
4963 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004965 while (j < end) {
4966 b = a->a_postorder[j++];
4967 for (i = 0; i < b->b_iused; i++) {
4968 struct instr *instr = &b->b_instr[i];
4969 if (instr->i_jrel || instr->i_jabs)
4970 dfs(c, instr->i_target, a, j);
4971 }
4972 assert(a->a_nblocks < j);
4973 a->a_postorder[a->a_nblocks++] = b;
4974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004975}
4976
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004977Py_LOCAL_INLINE(void)
4978stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004979{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004980 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004981 if (b->b_startdepth < depth) {
4982 assert(b->b_startdepth < 0);
4983 b->b_startdepth = depth;
4984 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004985 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004986}
4987
4988/* Find the flow path that needs the largest stack. We assume that
4989 * cycles in the flow graph have no net effect on the stack depth.
4990 */
4991static int
4992stackdepth(struct compiler *c)
4993{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004994 basicblock *b, *entryblock = NULL;
4995 basicblock **stack, **sp;
4996 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 b->b_startdepth = INT_MIN;
4999 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005000 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 }
5002 if (!entryblock)
5003 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005004 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5005 if (!stack) {
5006 PyErr_NoMemory();
5007 return -1;
5008 }
5009
5010 sp = stack;
5011 stackdepth_push(&sp, entryblock, 0);
5012 while (sp != stack) {
5013 b = *--sp;
5014 int depth = b->b_startdepth;
5015 assert(depth >= 0);
5016 basicblock *next = b->b_next;
5017 for (int i = 0; i < b->b_iused; i++) {
5018 struct instr *instr = &b->b_instr[i];
5019 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5020 if (effect == PY_INVALID_STACK_EFFECT) {
5021 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5022 Py_FatalError("PyCompile_OpcodeStackEffect()");
5023 }
5024 int new_depth = depth + effect;
5025 if (new_depth > maxdepth) {
5026 maxdepth = new_depth;
5027 }
5028 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5029 if (instr->i_jrel || instr->i_jabs) {
5030 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5031 assert(effect != PY_INVALID_STACK_EFFECT);
5032 int target_depth = depth + effect;
5033 if (target_depth > maxdepth) {
5034 maxdepth = target_depth;
5035 }
5036 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005037 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005038 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005039 assert(instr->i_target->b_startdepth >= target_depth);
5040 depth = new_depth;
5041 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005042 }
5043 stackdepth_push(&sp, instr->i_target, target_depth);
5044 }
5045 depth = new_depth;
5046 if (instr->i_opcode == JUMP_ABSOLUTE ||
5047 instr->i_opcode == JUMP_FORWARD ||
5048 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005049 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005050 {
5051 /* remaining code is dead */
5052 next = NULL;
5053 break;
5054 }
5055 }
5056 if (next != NULL) {
5057 stackdepth_push(&sp, next, depth);
5058 }
5059 }
5060 PyObject_Free(stack);
5061 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005062}
5063
5064static int
5065assemble_init(struct assembler *a, int nblocks, int firstlineno)
5066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 memset(a, 0, sizeof(struct assembler));
5068 a->a_lineno = firstlineno;
5069 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5070 if (!a->a_bytecode)
5071 return 0;
5072 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5073 if (!a->a_lnotab)
5074 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005075 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 PyErr_NoMemory();
5077 return 0;
5078 }
5079 a->a_postorder = (basicblock **)PyObject_Malloc(
5080 sizeof(basicblock *) * nblocks);
5081 if (!a->a_postorder) {
5082 PyErr_NoMemory();
5083 return 0;
5084 }
5085 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005086}
5087
5088static void
5089assemble_free(struct assembler *a)
5090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 Py_XDECREF(a->a_bytecode);
5092 Py_XDECREF(a->a_lnotab);
5093 if (a->a_postorder)
5094 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095}
5096
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005097static int
5098blocksize(basicblock *b)
5099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 int i;
5101 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005104 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005106}
5107
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005108/* Appends a pair to the end of the line number table, a_lnotab, representing
5109 the instruction's bytecode offset and line number. See
5110 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005111
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005112static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005113assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005116 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005118
Serhiy Storchakaab874002016-09-11 13:48:15 +03005119 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 if(d_bytecode == 0 && d_lineno == 0)
5125 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 if (d_bytecode > 255) {
5128 int j, nbytes, ncodes = d_bytecode / 255;
5129 nbytes = a->a_lnotab_off + 2 * ncodes;
5130 len = PyBytes_GET_SIZE(a->a_lnotab);
5131 if (nbytes >= len) {
5132 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5133 len = nbytes;
5134 else if (len <= INT_MAX / 2)
5135 len *= 2;
5136 else {
5137 PyErr_NoMemory();
5138 return 0;
5139 }
5140 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5141 return 0;
5142 }
5143 lnotab = (unsigned char *)
5144 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5145 for (j = 0; j < ncodes; j++) {
5146 *lnotab++ = 255;
5147 *lnotab++ = 0;
5148 }
5149 d_bytecode -= ncodes * 255;
5150 a->a_lnotab_off += ncodes * 2;
5151 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005152 assert(0 <= d_bytecode && d_bytecode <= 255);
5153
5154 if (d_lineno < -128 || 127 < d_lineno) {
5155 int j, nbytes, ncodes, k;
5156 if (d_lineno < 0) {
5157 k = -128;
5158 /* use division on positive numbers */
5159 ncodes = (-d_lineno) / 128;
5160 }
5161 else {
5162 k = 127;
5163 ncodes = d_lineno / 127;
5164 }
5165 d_lineno -= ncodes * k;
5166 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 nbytes = a->a_lnotab_off + 2 * ncodes;
5168 len = PyBytes_GET_SIZE(a->a_lnotab);
5169 if (nbytes >= len) {
5170 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5171 len = nbytes;
5172 else if (len <= INT_MAX / 2)
5173 len *= 2;
5174 else {
5175 PyErr_NoMemory();
5176 return 0;
5177 }
5178 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5179 return 0;
5180 }
5181 lnotab = (unsigned char *)
5182 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5183 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005184 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 d_bytecode = 0;
5186 for (j = 1; j < ncodes; j++) {
5187 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005188 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 a->a_lnotab_off += ncodes * 2;
5191 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005192 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 len = PyBytes_GET_SIZE(a->a_lnotab);
5195 if (a->a_lnotab_off + 2 >= len) {
5196 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5197 return 0;
5198 }
5199 lnotab = (unsigned char *)
5200 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 a->a_lnotab_off += 2;
5203 if (d_bytecode) {
5204 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005205 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 }
5207 else { /* First line of a block; def stmt, etc. */
5208 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005209 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 }
5211 a->a_lineno = i->i_lineno;
5212 a->a_lineno_off = a->a_offset;
5213 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005214}
5215
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005216/* assemble_emit()
5217 Extend the bytecode with a new instruction.
5218 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005219*/
5220
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005221static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005222assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005223{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005224 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005226 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005227
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005228 arg = i->i_oparg;
5229 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 if (i->i_lineno && !assemble_lnotab(a, i))
5231 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005232 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 if (len > PY_SSIZE_T_MAX / 2)
5234 return 0;
5235 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5236 return 0;
5237 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005238 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005240 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005242}
5243
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005244static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005245assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005247 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005248 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 /* Compute the size of each block and fixup jump args.
5252 Replace block pointer with position in bytecode. */
5253 do {
5254 totsize = 0;
5255 for (i = a->a_nblocks - 1; i >= 0; i--) {
5256 b = a->a_postorder[i];
5257 bsize = blocksize(b);
5258 b->b_offset = totsize;
5259 totsize += bsize;
5260 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005261 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5263 bsize = b->b_offset;
5264 for (i = 0; i < b->b_iused; i++) {
5265 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005266 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 /* Relative jumps are computed relative to
5268 the instruction pointer after fetching
5269 the jump instruction.
5270 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005271 bsize += isize;
5272 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005274 if (instr->i_jrel) {
5275 instr->i_oparg -= bsize;
5276 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005277 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005278 if (instrsize(instr->i_oparg) != isize) {
5279 extended_arg_recompile = 1;
5280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 }
5283 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 /* XXX: This is an awful hack that could hurt performance, but
5286 on the bright side it should work until we come up
5287 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 The issue is that in the first loop blocksize() is called
5290 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005291 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 So we loop until we stop seeing new EXTENDED_ARGs.
5295 The only EXTENDED_ARGs that could be popping up are
5296 ones in jump instructions. So this should converge
5297 fairly quickly.
5298 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005299 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005300}
5301
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005302static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005303dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005306 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 tuple = PyTuple_New(size);
5309 if (tuple == NULL)
5310 return NULL;
5311 while (PyDict_Next(dict, &pos, &k, &v)) {
5312 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005313 Py_INCREF(k);
5314 assert((i - offset) < size);
5315 assert((i - offset) >= 0);
5316 PyTuple_SET_ITEM(tuple, i - offset, k);
5317 }
5318 return tuple;
5319}
5320
5321static PyObject *
5322consts_dict_keys_inorder(PyObject *dict)
5323{
5324 PyObject *consts, *k, *v;
5325 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5326
5327 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5328 if (consts == NULL)
5329 return NULL;
5330 while (PyDict_Next(dict, &pos, &k, &v)) {
5331 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005332 /* The keys of the dictionary can be tuples wrapping a contant.
5333 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5334 * the object we want is always second. */
5335 if (PyTuple_CheckExact(k)) {
5336 k = PyTuple_GET_ITEM(k, 1);
5337 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005339 assert(i < size);
5340 assert(i >= 0);
5341 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005343 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005344}
5345
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005346static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005347compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005350 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005352 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 if (ste->ste_nested)
5354 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005355 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005357 if (!ste->ste_generator && ste->ste_coroutine)
5358 flags |= CO_COROUTINE;
5359 if (ste->ste_generator && ste->ste_coroutine)
5360 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 if (ste->ste_varargs)
5362 flags |= CO_VARARGS;
5363 if (ste->ste_varkeywords)
5364 flags |= CO_VARKEYWORDS;
5365 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 /* (Only) inherit compilerflags in PyCF_MASK */
5368 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005371}
5372
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373static PyCodeObject *
5374makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 PyObject *tmp;
5377 PyCodeObject *co = NULL;
5378 PyObject *consts = NULL;
5379 PyObject *names = NULL;
5380 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 PyObject *name = NULL;
5382 PyObject *freevars = NULL;
5383 PyObject *cellvars = NULL;
5384 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005385 Py_ssize_t nlocals;
5386 int nlocals_int;
5387 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005388 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005389
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005390 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 names = dict_keys_inorder(c->u->u_names, 0);
5392 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5393 if (!consts || !names || !varnames)
5394 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5397 if (!cellvars)
5398 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005399 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 if (!freevars)
5401 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005402
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005403 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005404 assert(nlocals < INT_MAX);
5405 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 flags = compute_code_flags(c);
5408 if (flags < 0)
5409 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5412 if (!bytecode)
5413 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5416 if (!tmp)
5417 goto error;
5418 Py_DECREF(consts);
5419 consts = tmp;
5420
Victor Stinnerf8e32212013-11-19 23:56:34 +01005421 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5422 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005423 maxdepth = stackdepth(c);
5424 if (maxdepth < 0) {
5425 goto error;
5426 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005427 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005428 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 bytecode, consts, names, varnames,
5430 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005431 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 c->u->u_firstlineno,
5433 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005434 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 Py_XDECREF(consts);
5436 Py_XDECREF(names);
5437 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 Py_XDECREF(name);
5439 Py_XDECREF(freevars);
5440 Py_XDECREF(cellvars);
5441 Py_XDECREF(bytecode);
5442 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005443}
5444
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005445
5446/* For debugging purposes only */
5447#if 0
5448static void
5449dump_instr(const struct instr *i)
5450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 const char *jrel = i->i_jrel ? "jrel " : "";
5452 const char *jabs = i->i_jabs ? "jabs " : "";
5453 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005456 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5460 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005461}
5462
5463static void
5464dump_basicblock(const basicblock *b)
5465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 const char *seen = b->b_seen ? "seen " : "";
5467 const char *b_return = b->b_return ? "return " : "";
5468 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5469 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5470 if (b->b_instr) {
5471 int i;
5472 for (i = 0; i < b->b_iused; i++) {
5473 fprintf(stderr, " [%02d] ", i);
5474 dump_instr(b->b_instr + i);
5475 }
5476 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005477}
5478#endif
5479
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005480static PyCodeObject *
5481assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 basicblock *b, *entryblock;
5484 struct assembler a;
5485 int i, j, nblocks;
5486 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 /* Make sure every block that falls off the end returns None.
5489 XXX NEXT_BLOCK() isn't quite right, because if the last
5490 block ends with a jump or return b_next shouldn't set.
5491 */
5492 if (!c->u->u_curblock->b_return) {
5493 NEXT_BLOCK(c);
5494 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005495 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 ADDOP(c, RETURN_VALUE);
5497 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 nblocks = 0;
5500 entryblock = NULL;
5501 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5502 nblocks++;
5503 entryblock = b;
5504 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 /* Set firstlineno if it wasn't explicitly set. */
5507 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005508 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5510 else
5511 c->u->u_firstlineno = 1;
5512 }
5513 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5514 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005515 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 /* Can't modify the bytecode after computing jump offsets. */
5518 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 /* Emit code in reverse postorder from dfs. */
5521 for (i = a.a_nblocks - 1; i >= 0; i--) {
5522 b = a.a_postorder[i];
5523 for (j = 0; j < b->b_iused; j++)
5524 if (!assemble_emit(&a, &b->b_instr[j]))
5525 goto error;
5526 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5529 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005530 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005534 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 assemble_free(&a);
5536 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005537}
Georg Brandl8334fd92010-12-04 10:26:46 +00005538
5539#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005540PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005541PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5542 PyArena *arena)
5543{
5544 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5545}