blob: 45a8c573a5fffc9b48a577237b381e9a5c6b060a [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;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001953 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954
Yury Selivanov75445082015-05-11 22:57:16 -04001955 if (is_async) {
1956 assert(s->kind == AsyncFunctionDef_kind);
1957
1958 args = s->v.AsyncFunctionDef.args;
1959 returns = s->v.AsyncFunctionDef.returns;
1960 decos = s->v.AsyncFunctionDef.decorator_list;
1961 name = s->v.AsyncFunctionDef.name;
1962 body = s->v.AsyncFunctionDef.body;
1963
1964 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1965 } else {
1966 assert(s->kind == FunctionDef_kind);
1967
1968 args = s->v.FunctionDef.args;
1969 returns = s->v.FunctionDef.returns;
1970 decos = s->v.FunctionDef.decorator_list;
1971 name = s->v.FunctionDef.name;
1972 body = s->v.FunctionDef.body;
1973
1974 scope_type = COMPILER_SCOPE_FUNCTION;
1975 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (!compiler_decorators(c, decos))
1978 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001979
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001980 firstlineno = s->lineno;
1981 if (asdl_seq_LEN(decos)) {
1982 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
1983 }
1984
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001985 funcflags = compiler_default_arguments(c, args);
1986 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001988 }
1989
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 annotations = compiler_visit_annotations(c, args, returns);
1991 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001992 return 0;
1993 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001994 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001995 funcflags |= 0x04;
1996 }
1997
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001998 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001999 return 0;
2000 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001
INADA Naokicb41b272017-02-23 00:31:59 +09002002 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002003 if (c->c_optimize < 2) {
2004 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002005 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002006 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 compiler_exit_scope(c);
2008 return 0;
2009 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 c->u->u_argcount = asdl_seq_LEN(args->args);
2012 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002013 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002015 qualname = c->u->u_qualname;
2016 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002018 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002019 Py_XDECREF(qualname);
2020 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002022 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002024 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002025 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* decorators */
2029 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2030 ADDOP_I(c, CALL_FUNCTION, 1);
2031 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032
Yury Selivanov75445082015-05-11 22:57:16 -04002033 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
2036static int
2037compiler_class(struct compiler *c, stmt_ty s)
2038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyCodeObject *co;
2040 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002041 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 if (!compiler_decorators(c, decos))
2045 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002046
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002047 firstlineno = s->lineno;
2048 if (asdl_seq_LEN(decos)) {
2049 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2050 }
2051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* ultimately generate code for:
2053 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2054 where:
2055 <func> is a function/closure created from the class body;
2056 it has a single argument (__locals__) where the dict
2057 (or MutableSequence) representing the locals is passed
2058 <name> is the class name
2059 <bases> is the positional arguments and *varargs argument
2060 <keywords> is the keyword arguments and **kwds argument
2061 This borrows from compiler_call.
2062 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002065 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002066 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 return 0;
2068 /* this block represents what we do in the new scope */
2069 {
2070 /* use the class name for name mangling */
2071 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002072 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* load (global) __name__ ... */
2074 str = PyUnicode_InternFromString("__name__");
2075 if (!str || !compiler_nameop(c, str, Load)) {
2076 Py_XDECREF(str);
2077 compiler_exit_scope(c);
2078 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 Py_DECREF(str);
2081 /* ... and store it as __module__ */
2082 str = PyUnicode_InternFromString("__module__");
2083 if (!str || !compiler_nameop(c, str, Store)) {
2084 Py_XDECREF(str);
2085 compiler_exit_scope(c);
2086 return 0;
2087 }
2088 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002089 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002090 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002091 str = PyUnicode_InternFromString("__qualname__");
2092 if (!str || !compiler_nameop(c, str, Store)) {
2093 Py_XDECREF(str);
2094 compiler_exit_scope(c);
2095 return 0;
2096 }
2097 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002099 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 compiler_exit_scope(c);
2101 return 0;
2102 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002103 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002104 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002105 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002106 str = PyUnicode_InternFromString("__class__");
2107 if (str == NULL) {
2108 compiler_exit_scope(c);
2109 return 0;
2110 }
2111 i = compiler_lookup_arg(c->u->u_cellvars, str);
2112 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002113 if (i < 0) {
2114 compiler_exit_scope(c);
2115 return 0;
2116 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002117 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002120 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002121 str = PyUnicode_InternFromString("__classcell__");
2122 if (!str || !compiler_nameop(c, str, Store)) {
2123 Py_XDECREF(str);
2124 compiler_exit_scope(c);
2125 return 0;
2126 }
2127 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002129 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002130 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002131 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002132 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002133 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002134 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* create the code object */
2136 co = assemble(c, 1);
2137 }
2138 /* leave the new scope */
2139 compiler_exit_scope(c);
2140 if (co == NULL)
2141 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* 2. load the 'build_class' function */
2144 ADDOP(c, LOAD_BUILD_CLASS);
2145
2146 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002147 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 Py_DECREF(co);
2149
2150 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002151 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152
2153 /* 5. generate the rest of the code for the call */
2154 if (!compiler_call_helper(c, 2,
2155 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002156 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 return 0;
2158
2159 /* 6. apply decorators */
2160 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2161 ADDOP_I(c, CALL_FUNCTION, 1);
2162 }
2163
2164 /* 7. store into <name> */
2165 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2166 return 0;
2167 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168}
2169
2170static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002171cmpop(cmpop_ty op)
2172{
2173 switch (op) {
2174 case Eq:
2175 return PyCmp_EQ;
2176 case NotEq:
2177 return PyCmp_NE;
2178 case Lt:
2179 return PyCmp_LT;
2180 case LtE:
2181 return PyCmp_LE;
2182 case Gt:
2183 return PyCmp_GT;
2184 case GtE:
2185 return PyCmp_GE;
2186 case Is:
2187 return PyCmp_IS;
2188 case IsNot:
2189 return PyCmp_IS_NOT;
2190 case In:
2191 return PyCmp_IN;
2192 case NotIn:
2193 return PyCmp_NOT_IN;
2194 default:
2195 return PyCmp_BAD;
2196 }
2197}
2198
2199static int
2200compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2201{
2202 switch (e->kind) {
2203 case UnaryOp_kind:
2204 if (e->v.UnaryOp.op == Not)
2205 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2206 /* fallback to general implementation */
2207 break;
2208 case BoolOp_kind: {
2209 asdl_seq *s = e->v.BoolOp.values;
2210 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2211 assert(n >= 0);
2212 int cond2 = e->v.BoolOp.op == Or;
2213 basicblock *next2 = next;
2214 if (!cond2 != !cond) {
2215 next2 = compiler_new_block(c);
2216 if (next2 == NULL)
2217 return 0;
2218 }
2219 for (i = 0; i < n; ++i) {
2220 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2221 return 0;
2222 }
2223 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2224 return 0;
2225 if (next2 != next)
2226 compiler_use_next_block(c, next2);
2227 return 1;
2228 }
2229 case IfExp_kind: {
2230 basicblock *end, *next2;
2231 end = compiler_new_block(c);
2232 if (end == NULL)
2233 return 0;
2234 next2 = compiler_new_block(c);
2235 if (next2 == NULL)
2236 return 0;
2237 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2238 return 0;
2239 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2240 return 0;
2241 ADDOP_JREL(c, JUMP_FORWARD, end);
2242 compiler_use_next_block(c, next2);
2243 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2244 return 0;
2245 compiler_use_next_block(c, end);
2246 return 1;
2247 }
2248 case Compare_kind: {
2249 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2250 if (n > 0) {
2251 basicblock *cleanup = compiler_new_block(c);
2252 if (cleanup == NULL)
2253 return 0;
2254 VISIT(c, expr, e->v.Compare.left);
2255 for (i = 0; i < n; i++) {
2256 VISIT(c, expr,
2257 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2258 ADDOP(c, DUP_TOP);
2259 ADDOP(c, ROT_THREE);
2260 ADDOP_I(c, COMPARE_OP,
2261 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2262 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2263 NEXT_BLOCK(c);
2264 }
2265 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2266 ADDOP_I(c, COMPARE_OP,
2267 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2268 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2269 basicblock *end = compiler_new_block(c);
2270 if (end == NULL)
2271 return 0;
2272 ADDOP_JREL(c, JUMP_FORWARD, end);
2273 compiler_use_next_block(c, cleanup);
2274 ADDOP(c, POP_TOP);
2275 if (!cond) {
2276 ADDOP_JREL(c, JUMP_FORWARD, next);
2277 }
2278 compiler_use_next_block(c, end);
2279 return 1;
2280 }
2281 /* fallback to general implementation */
2282 break;
2283 }
2284 default:
2285 /* fallback to general implementation */
2286 break;
2287 }
2288
2289 /* general implementation */
2290 VISIT(c, expr, e);
2291 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2292 return 1;
2293}
2294
2295static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002296compiler_ifexp(struct compiler *c, expr_ty e)
2297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 basicblock *end, *next;
2299
2300 assert(e->kind == IfExp_kind);
2301 end = compiler_new_block(c);
2302 if (end == NULL)
2303 return 0;
2304 next = compiler_new_block(c);
2305 if (next == NULL)
2306 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002307 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2308 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 VISIT(c, expr, e->v.IfExp.body);
2310 ADDOP_JREL(c, JUMP_FORWARD, end);
2311 compiler_use_next_block(c, next);
2312 VISIT(c, expr, e->v.IfExp.orelse);
2313 compiler_use_next_block(c, end);
2314 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002315}
2316
2317static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318compiler_lambda(struct compiler *c, expr_ty e)
2319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002321 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002323 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 arguments_ty args = e->v.Lambda.args;
2325 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (!name) {
2328 name = PyUnicode_InternFromString("<lambda>");
2329 if (!name)
2330 return 0;
2331 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002333 funcflags = compiler_default_arguments(c, args);
2334 if (funcflags == -1) {
2335 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002337
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002338 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002339 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Make None the first constant, so the lambda can't have a
2343 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002344 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 c->u->u_argcount = asdl_seq_LEN(args->args);
2348 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2349 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2350 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002351 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
2353 else {
2354 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002355 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002357 qualname = c->u->u_qualname;
2358 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002360 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002363 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002364 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 Py_DECREF(co);
2366
2367 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368}
2369
2370static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371compiler_if(struct compiler *c, stmt_ty s)
2372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 basicblock *end, *next;
2374 int constant;
2375 assert(s->kind == If_kind);
2376 end = compiler_new_block(c);
2377 if (end == NULL)
2378 return 0;
2379
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002380 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* constant = 0: "if 0"
2382 * constant = 1: "if 1", "if 2", ...
2383 * constant = -1: rest */
2384 if (constant == 0) {
2385 if (s->v.If.orelse)
2386 VISIT_SEQ(c, stmt, s->v.If.orelse);
2387 } else if (constant == 1) {
2388 VISIT_SEQ(c, stmt, s->v.If.body);
2389 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002390 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 next = compiler_new_block(c);
2392 if (next == NULL)
2393 return 0;
2394 }
2395 else
2396 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002397 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2398 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002400 if (asdl_seq_LEN(s->v.If.orelse)) {
2401 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 compiler_use_next_block(c, next);
2403 VISIT_SEQ(c, stmt, s->v.If.orelse);
2404 }
2405 }
2406 compiler_use_next_block(c, end);
2407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408}
2409
2410static int
2411compiler_for(struct compiler *c, stmt_ty s)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 start = compiler_new_block(c);
2416 cleanup = compiler_new_block(c);
2417 end = compiler_new_block(c);
2418 if (start == NULL || end == NULL || cleanup == NULL)
2419 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002420
2421 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 VISIT(c, expr, s->v.For.iter);
2425 ADDOP(c, GET_ITER);
2426 compiler_use_next_block(c, start);
2427 ADDOP_JREL(c, FOR_ITER, cleanup);
2428 VISIT(c, expr, s->v.For.target);
2429 VISIT_SEQ(c, stmt, s->v.For.body);
2430 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2431 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002432
2433 compiler_pop_fblock(c, FOR_LOOP, start);
2434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 VISIT_SEQ(c, stmt, s->v.For.orelse);
2436 compiler_use_next_block(c, end);
2437 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438}
2439
Yury Selivanov75445082015-05-11 22:57:16 -04002440
2441static int
2442compiler_async_for(struct compiler *c, stmt_ty s)
2443{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002444 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002445 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2446 return compiler_error(c, "'async for' outside async function");
2447 }
2448
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002449 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002450 except = compiler_new_block(c);
2451 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002452
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002453 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002454 return 0;
2455
2456 VISIT(c, expr, s->v.AsyncFor.iter);
2457 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002458
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002459 compiler_use_next_block(c, start);
2460 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2461 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002462
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002463 /* SETUP_FINALLY to guard the __anext__ call */
2464 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002465 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002466 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002467 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002468 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002469
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002470 /* Success block for __anext__ */
2471 VISIT(c, expr, s->v.AsyncFor.target);
2472 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2473 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2474
2475 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002476
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002477 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002478 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002479 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002480
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002481 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002482 VISIT_SEQ(c, stmt, s->v.For.orelse);
2483
2484 compiler_use_next_block(c, end);
2485
2486 return 1;
2487}
2488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489static int
2490compiler_while(struct compiler *c, stmt_ty s)
2491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002493 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (constant == 0) {
2496 if (s->v.While.orelse)
2497 VISIT_SEQ(c, stmt, s->v.While.orelse);
2498 return 1;
2499 }
2500 loop = compiler_new_block(c);
2501 end = compiler_new_block(c);
2502 if (constant == -1) {
2503 anchor = compiler_new_block(c);
2504 if (anchor == NULL)
2505 return 0;
2506 }
2507 if (loop == NULL || end == NULL)
2508 return 0;
2509 if (s->v.While.orelse) {
2510 orelse = compiler_new_block(c);
2511 if (orelse == NULL)
2512 return 0;
2513 }
2514 else
2515 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002518 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return 0;
2520 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002521 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2522 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 }
2524 VISIT_SEQ(c, stmt, s->v.While.body);
2525 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* XXX should the two POP instructions be in a separate block
2528 if there is no else clause ?
2529 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002531 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002533 compiler_pop_fblock(c, WHILE_LOOP, loop);
2534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (orelse != NULL) /* what if orelse is just pass? */
2536 VISIT_SEQ(c, stmt, s->v.While.orelse);
2537 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540}
2541
2542static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002543compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002545 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002546 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002547 if (c->u->u_ste->ste_type != FunctionBlock)
2548 return compiler_error(c, "'return' outside function");
2549 if (s->v.Return.value != NULL &&
2550 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2551 {
2552 return compiler_error(
2553 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002555 if (preserve_tos) {
2556 VISIT(c, expr, s->v.Return.value);
2557 }
2558 for (int depth = c->u->u_nfblocks; depth--;) {
2559 struct fblockinfo *info = &c->u->u_fblock[depth];
2560
2561 if (!compiler_unwind_fblock(c, info, preserve_tos))
2562 return 0;
2563 }
2564 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002565 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002566 }
2567 else if (!preserve_tos) {
2568 VISIT(c, expr, s->v.Return.value);
2569 }
2570 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573}
2574
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002575static int
2576compiler_break(struct compiler *c)
2577{
2578 for (int depth = c->u->u_nfblocks; depth--;) {
2579 struct fblockinfo *info = &c->u->u_fblock[depth];
2580
2581 if (!compiler_unwind_fblock(c, info, 0))
2582 return 0;
2583 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2584 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2585 return 1;
2586 }
2587 }
2588 return compiler_error(c, "'break' outside loop");
2589}
2590
2591static int
2592compiler_continue(struct compiler *c)
2593{
2594 for (int depth = c->u->u_nfblocks; depth--;) {
2595 struct fblockinfo *info = &c->u->u_fblock[depth];
2596
2597 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2598 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2599 return 1;
2600 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002601 if (!compiler_unwind_fblock(c, info, 0))
2602 return 0;
2603 }
2604 return compiler_error(c, "'continue' not properly in loop");
2605}
2606
2607
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609
2610 SETUP_FINALLY L
2611 <code for body>
2612 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002613 BEGIN_FINALLY
2614 L:
2615 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 END_FINALLY
2617
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 The special instructions use the block stack. Each block
2619 stack entry contains the instruction that created it (here
2620 SETUP_FINALLY), the level of the value stack at the time the
2621 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 Pushes the current value stack level and the label
2625 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002627 Pops en entry from the block stack.
2628 BEGIN_FINALLY
2629 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002631 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2632 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002635 when a SETUP_FINALLY entry is found, the raised and the caught
2636 exceptions are pushed onto the value stack (and the exception
2637 condition is cleared), and the interpreter jumps to the label
2638 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639*/
2640
2641static int
2642compiler_try_finally(struct compiler *c, stmt_ty s)
2643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 body = compiler_new_block(c);
2647 end = compiler_new_block(c);
2648 if (body == NULL || end == NULL)
2649 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002651 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 ADDOP_JREL(c, SETUP_FINALLY, end);
2653 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002654 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002656 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2657 if (!compiler_try_except(c, s))
2658 return 0;
2659 }
2660 else {
2661 VISIT_SEQ(c, stmt, s->v.Try.body);
2662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002664 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002667 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002669 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002671 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 ADDOP(c, END_FINALLY);
2673 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675}
2676
2677/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002678 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 (The contents of the value stack is shown in [], with the top
2680 at the right; 'tb' is trace-back info, 'val' the exception's
2681 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682
2683 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002684 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 [] <code for S>
2686 [] POP_BLOCK
2687 [] JUMP_FORWARD L0
2688
2689 [tb, val, exc] L1: DUP )
2690 [tb, val, exc, exc] <evaluate E1> )
2691 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2692 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2693 [tb, val, exc] POP
2694 [tb, val] <assign to V1> (or POP if no V1)
2695 [tb] POP
2696 [] <code for S1>
2697 JUMP_FORWARD L0
2698
2699 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 .............................etc.......................
2701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2703
2704 [] L0: <next statement>
2705
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 Of course, parts are not generated if Vi or Ei is not present.
2707*/
2708static int
2709compiler_try_except(struct compiler *c, stmt_ty s)
2710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002712 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 body = compiler_new_block(c);
2715 except = compiler_new_block(c);
2716 orelse = compiler_new_block(c);
2717 end = compiler_new_block(c);
2718 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2719 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002720 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002722 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002724 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 ADDOP(c, POP_BLOCK);
2726 compiler_pop_fblock(c, EXCEPT, body);
2727 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002728 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 compiler_use_next_block(c, except);
2730 for (i = 0; i < n; i++) {
2731 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002732 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 if (!handler->v.ExceptHandler.type && i < n-1)
2734 return compiler_error(c, "default 'except:' must be last");
2735 c->u->u_lineno_set = 0;
2736 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002737 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 except = compiler_new_block(c);
2739 if (except == NULL)
2740 return 0;
2741 if (handler->v.ExceptHandler.type) {
2742 ADDOP(c, DUP_TOP);
2743 VISIT(c, expr, handler->v.ExceptHandler.type);
2744 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2745 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2746 }
2747 ADDOP(c, POP_TOP);
2748 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002749 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002750
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002751 cleanup_end = compiler_new_block(c);
2752 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002753 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002754 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002755 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002756
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002757 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2758 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002760 /*
2761 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002762 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002763 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002764 try:
2765 # body
2766 finally:
2767 name = None
2768 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002769 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002771 /* second try: */
2772 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2773 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002774 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002775 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002777 /* second # body */
2778 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2779 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002780 ADDOP(c, BEGIN_FINALLY);
2781 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002783 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002784 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002785 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002786 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002788 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002789 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002790 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002791 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002793 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002794 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002795 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 }
2797 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002798 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002800 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002801 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002802 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803
Guido van Rossumb940e112007-01-10 16:19:56 +00002804 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002805 ADDOP(c, POP_TOP);
2806 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002807 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002808 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002810 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 }
2813 ADDOP_JREL(c, JUMP_FORWARD, end);
2814 compiler_use_next_block(c, except);
2815 }
2816 ADDOP(c, END_FINALLY);
2817 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002818 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 compiler_use_next_block(c, end);
2820 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821}
2822
2823static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002824compiler_try(struct compiler *c, stmt_ty s) {
2825 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2826 return compiler_try_finally(c, s);
2827 else
2828 return compiler_try_except(c, s);
2829}
2830
2831
2832static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833compiler_import_as(struct compiler *c, identifier name, identifier asname)
2834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 /* The IMPORT_NAME opcode was already generated. This function
2836 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002839 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002841 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2842 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002843 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002844 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002847 while (1) {
2848 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002850 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002851 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002852 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002853 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002855 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002856 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002857 if (dot == -1) {
2858 break;
2859 }
2860 ADDOP(c, ROT_TWO);
2861 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002863 if (!compiler_nameop(c, asname, Store)) {
2864 return 0;
2865 }
2866 ADDOP(c, POP_TOP);
2867 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 }
2869 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870}
2871
2872static int
2873compiler_import(struct compiler *c, stmt_ty s)
2874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 /* The Import node stores a module name like a.b.c as a single
2876 string. This is convenient for all cases except
2877 import a.b.c as d
2878 where we need to parse that string to extract the individual
2879 module names.
2880 XXX Perhaps change the representation to make this case simpler?
2881 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002882 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 for (i = 0; i < n; i++) {
2885 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2886 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002888 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2889 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 if (alias->asname) {
2893 r = compiler_import_as(c, alias->name, alias->asname);
2894 if (!r)
2895 return r;
2896 }
2897 else {
2898 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002899 Py_ssize_t dot = PyUnicode_FindChar(
2900 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002901 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002902 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002903 if (tmp == NULL)
2904 return 0;
2905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002907 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 Py_DECREF(tmp);
2909 }
2910 if (!r)
2911 return r;
2912 }
2913 }
2914 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915}
2916
2917static int
2918compiler_from_import(struct compiler *c, stmt_ty s)
2919{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002920 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002921 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 if (!empty_string) {
2925 empty_string = PyUnicode_FromString("");
2926 if (!empty_string)
2927 return 0;
2928 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002930 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002931
2932 names = PyTuple_New(n);
2933 if (!names)
2934 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 /* build up the names */
2937 for (i = 0; i < n; i++) {
2938 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2939 Py_INCREF(alias->name);
2940 PyTuple_SET_ITEM(names, i, alias->name);
2941 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002944 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 Py_DECREF(names);
2946 return compiler_error(c, "from __future__ imports must occur "
2947 "at the beginning of the file");
2948 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002949 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 if (s->v.ImportFrom.module) {
2952 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2953 }
2954 else {
2955 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2956 }
2957 for (i = 0; i < n; i++) {
2958 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2959 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002961 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 assert(n == 1);
2963 ADDOP(c, IMPORT_STAR);
2964 return 1;
2965 }
2966
2967 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2968 store_name = alias->name;
2969 if (alias->asname)
2970 store_name = alias->asname;
2971
2972 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 return 0;
2974 }
2975 }
2976 /* remove imported module */
2977 ADDOP(c, POP_TOP);
2978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979}
2980
2981static int
2982compiler_assert(struct compiler *c, stmt_ty s)
2983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 static PyObject *assertion_error = NULL;
2985 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986
Georg Brandl8334fd92010-12-04 10:26:46 +00002987 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 return 1;
2989 if (assertion_error == NULL) {
2990 assertion_error = PyUnicode_InternFromString("AssertionError");
2991 if (assertion_error == NULL)
2992 return 0;
2993 }
2994 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03002995 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
2996 {
2997 if (!compiler_warn(c, "assertion is always true, "
2998 "perhaps remove parentheses?"))
2999 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003000 return 0;
3001 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 end = compiler_new_block(c);
3004 if (end == NULL)
3005 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003006 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3007 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3009 if (s->v.Assert.msg) {
3010 VISIT(c, expr, s->v.Assert.msg);
3011 ADDOP_I(c, CALL_FUNCTION, 1);
3012 }
3013 ADDOP_I(c, RAISE_VARARGS, 1);
3014 compiler_use_next_block(c, end);
3015 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016}
3017
3018static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003019compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3020{
3021 if (c->c_interactive && c->c_nestlevel <= 1) {
3022 VISIT(c, expr, value);
3023 ADDOP(c, PRINT_EXPR);
3024 return 1;
3025 }
3026
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003027 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003028 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003029 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003030 }
3031
3032 VISIT(c, expr, value);
3033 ADDOP(c, POP_TOP);
3034 return 1;
3035}
3036
3037static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038compiler_visit_stmt(struct compiler *c, stmt_ty s)
3039{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003040 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 /* Always assign a lineno to the next instruction for a stmt. */
3043 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003044 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 switch (s->kind) {
3048 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003049 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 case ClassDef_kind:
3051 return compiler_class(c, s);
3052 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003053 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 case Delete_kind:
3055 VISIT_SEQ(c, expr, s->v.Delete.targets)
3056 break;
3057 case Assign_kind:
3058 n = asdl_seq_LEN(s->v.Assign.targets);
3059 VISIT(c, expr, s->v.Assign.value);
3060 for (i = 0; i < n; i++) {
3061 if (i < n - 1)
3062 ADDOP(c, DUP_TOP);
3063 VISIT(c, expr,
3064 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3065 }
3066 break;
3067 case AugAssign_kind:
3068 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003069 case AnnAssign_kind:
3070 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 case For_kind:
3072 return compiler_for(c, s);
3073 case While_kind:
3074 return compiler_while(c, s);
3075 case If_kind:
3076 return compiler_if(c, s);
3077 case Raise_kind:
3078 n = 0;
3079 if (s->v.Raise.exc) {
3080 VISIT(c, expr, s->v.Raise.exc);
3081 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003082 if (s->v.Raise.cause) {
3083 VISIT(c, expr, s->v.Raise.cause);
3084 n++;
3085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003087 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003089 case Try_kind:
3090 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 case Assert_kind:
3092 return compiler_assert(c, s);
3093 case Import_kind:
3094 return compiler_import(c, s);
3095 case ImportFrom_kind:
3096 return compiler_from_import(c, s);
3097 case Global_kind:
3098 case Nonlocal_kind:
3099 break;
3100 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003101 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 case Pass_kind:
3103 break;
3104 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003105 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 case Continue_kind:
3107 return compiler_continue(c);
3108 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003109 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003110 case AsyncFunctionDef_kind:
3111 return compiler_function(c, s, 1);
3112 case AsyncWith_kind:
3113 return compiler_async_with(c, s, 0);
3114 case AsyncFor_kind:
3115 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
Yury Selivanov75445082015-05-11 22:57:16 -04003117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119}
3120
3121static int
3122unaryop(unaryop_ty op)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 switch (op) {
3125 case Invert:
3126 return UNARY_INVERT;
3127 case Not:
3128 return UNARY_NOT;
3129 case UAdd:
3130 return UNARY_POSITIVE;
3131 case USub:
3132 return UNARY_NEGATIVE;
3133 default:
3134 PyErr_Format(PyExc_SystemError,
3135 "unary op %d should not be possible", op);
3136 return 0;
3137 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138}
3139
3140static int
3141binop(struct compiler *c, operator_ty op)
3142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 switch (op) {
3144 case Add:
3145 return BINARY_ADD;
3146 case Sub:
3147 return BINARY_SUBTRACT;
3148 case Mult:
3149 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003150 case MatMult:
3151 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 case Div:
3153 return BINARY_TRUE_DIVIDE;
3154 case Mod:
3155 return BINARY_MODULO;
3156 case Pow:
3157 return BINARY_POWER;
3158 case LShift:
3159 return BINARY_LSHIFT;
3160 case RShift:
3161 return BINARY_RSHIFT;
3162 case BitOr:
3163 return BINARY_OR;
3164 case BitXor:
3165 return BINARY_XOR;
3166 case BitAnd:
3167 return BINARY_AND;
3168 case FloorDiv:
3169 return BINARY_FLOOR_DIVIDE;
3170 default:
3171 PyErr_Format(PyExc_SystemError,
3172 "binary op %d should not be possible", op);
3173 return 0;
3174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175}
3176
3177static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178inplace_binop(struct compiler *c, operator_ty op)
3179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 switch (op) {
3181 case Add:
3182 return INPLACE_ADD;
3183 case Sub:
3184 return INPLACE_SUBTRACT;
3185 case Mult:
3186 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003187 case MatMult:
3188 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 case Div:
3190 return INPLACE_TRUE_DIVIDE;
3191 case Mod:
3192 return INPLACE_MODULO;
3193 case Pow:
3194 return INPLACE_POWER;
3195 case LShift:
3196 return INPLACE_LSHIFT;
3197 case RShift:
3198 return INPLACE_RSHIFT;
3199 case BitOr:
3200 return INPLACE_OR;
3201 case BitXor:
3202 return INPLACE_XOR;
3203 case BitAnd:
3204 return INPLACE_AND;
3205 case FloorDiv:
3206 return INPLACE_FLOOR_DIVIDE;
3207 default:
3208 PyErr_Format(PyExc_SystemError,
3209 "inplace binary op %d should not be possible", op);
3210 return 0;
3211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212}
3213
3214static int
3215compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3216{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003217 int op, scope;
3218 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 PyObject *dict = c->u->u_names;
3222 PyObject *mangled;
3223 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003225 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3226 !_PyUnicode_EqualToASCIIString(name, "True") &&
3227 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003228
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003229 mangled = _Py_Mangle(c->u->u_private, name);
3230 if (!mangled)
3231 return 0;
3232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 op = 0;
3234 optype = OP_NAME;
3235 scope = PyST_GetScope(c->u->u_ste, mangled);
3236 switch (scope) {
3237 case FREE:
3238 dict = c->u->u_freevars;
3239 optype = OP_DEREF;
3240 break;
3241 case CELL:
3242 dict = c->u->u_cellvars;
3243 optype = OP_DEREF;
3244 break;
3245 case LOCAL:
3246 if (c->u->u_ste->ste_type == FunctionBlock)
3247 optype = OP_FAST;
3248 break;
3249 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003250 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 optype = OP_GLOBAL;
3252 break;
3253 case GLOBAL_EXPLICIT:
3254 optype = OP_GLOBAL;
3255 break;
3256 default:
3257 /* scope can be 0 */
3258 break;
3259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003262 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 switch (optype) {
3265 case OP_DEREF:
3266 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003267 case Load:
3268 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3269 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 case Store: op = STORE_DEREF; break;
3271 case AugLoad:
3272 case AugStore:
3273 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003274 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 case Param:
3276 default:
3277 PyErr_SetString(PyExc_SystemError,
3278 "param invalid for deref variable");
3279 return 0;
3280 }
3281 break;
3282 case OP_FAST:
3283 switch (ctx) {
3284 case Load: op = LOAD_FAST; break;
3285 case Store: op = STORE_FAST; break;
3286 case Del: op = DELETE_FAST; break;
3287 case AugLoad:
3288 case AugStore:
3289 break;
3290 case Param:
3291 default:
3292 PyErr_SetString(PyExc_SystemError,
3293 "param invalid for local variable");
3294 return 0;
3295 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003296 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 return 1;
3298 case OP_GLOBAL:
3299 switch (ctx) {
3300 case Load: op = LOAD_GLOBAL; break;
3301 case Store: op = STORE_GLOBAL; break;
3302 case Del: op = DELETE_GLOBAL; break;
3303 case AugLoad:
3304 case AugStore:
3305 break;
3306 case Param:
3307 default:
3308 PyErr_SetString(PyExc_SystemError,
3309 "param invalid for global variable");
3310 return 0;
3311 }
3312 break;
3313 case OP_NAME:
3314 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003315 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 case Store: op = STORE_NAME; break;
3317 case Del: op = DELETE_NAME; break;
3318 case AugLoad:
3319 case AugStore:
3320 break;
3321 case Param:
3322 default:
3323 PyErr_SetString(PyExc_SystemError,
3324 "param invalid for name variable");
3325 return 0;
3326 }
3327 break;
3328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 assert(op);
3331 arg = compiler_add_o(c, dict, mangled);
3332 Py_DECREF(mangled);
3333 if (arg < 0)
3334 return 0;
3335 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336}
3337
3338static int
3339compiler_boolop(struct compiler *c, expr_ty e)
3340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003342 int jumpi;
3343 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 assert(e->kind == BoolOp_kind);
3347 if (e->v.BoolOp.op == And)
3348 jumpi = JUMP_IF_FALSE_OR_POP;
3349 else
3350 jumpi = JUMP_IF_TRUE_OR_POP;
3351 end = compiler_new_block(c);
3352 if (end == NULL)
3353 return 0;
3354 s = e->v.BoolOp.values;
3355 n = asdl_seq_LEN(s) - 1;
3356 assert(n >= 0);
3357 for (i = 0; i < n; ++i) {
3358 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3359 ADDOP_JABS(c, jumpi, end);
3360 }
3361 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3362 compiler_use_next_block(c, end);
3363 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364}
3365
3366static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003367starunpack_helper(struct compiler *c, asdl_seq *elts,
3368 int single_op, int inner_op, int outer_op)
3369{
3370 Py_ssize_t n = asdl_seq_LEN(elts);
3371 Py_ssize_t i, nsubitems = 0, nseen = 0;
3372 for (i = 0; i < n; i++) {
3373 expr_ty elt = asdl_seq_GET(elts, i);
3374 if (elt->kind == Starred_kind) {
3375 if (nseen) {
3376 ADDOP_I(c, inner_op, nseen);
3377 nseen = 0;
3378 nsubitems++;
3379 }
3380 VISIT(c, expr, elt->v.Starred.value);
3381 nsubitems++;
3382 }
3383 else {
3384 VISIT(c, expr, elt);
3385 nseen++;
3386 }
3387 }
3388 if (nsubitems) {
3389 if (nseen) {
3390 ADDOP_I(c, inner_op, nseen);
3391 nsubitems++;
3392 }
3393 ADDOP_I(c, outer_op, nsubitems);
3394 }
3395 else
3396 ADDOP_I(c, single_op, nseen);
3397 return 1;
3398}
3399
3400static int
3401assignment_helper(struct compiler *c, asdl_seq *elts)
3402{
3403 Py_ssize_t n = asdl_seq_LEN(elts);
3404 Py_ssize_t i;
3405 int seen_star = 0;
3406 for (i = 0; i < n; i++) {
3407 expr_ty elt = asdl_seq_GET(elts, i);
3408 if (elt->kind == Starred_kind && !seen_star) {
3409 if ((i >= (1 << 8)) ||
3410 (n-i-1 >= (INT_MAX >> 8)))
3411 return compiler_error(c,
3412 "too many expressions in "
3413 "star-unpacking assignment");
3414 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3415 seen_star = 1;
3416 asdl_seq_SET(elts, i, elt->v.Starred.value);
3417 }
3418 else if (elt->kind == Starred_kind) {
3419 return compiler_error(c,
3420 "two starred expressions in assignment");
3421 }
3422 }
3423 if (!seen_star) {
3424 ADDOP_I(c, UNPACK_SEQUENCE, n);
3425 }
3426 VISIT_SEQ(c, expr, elts);
3427 return 1;
3428}
3429
3430static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431compiler_list(struct compiler *c, expr_ty e)
3432{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003433 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003435 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003437 else if (e->v.List.ctx == Load) {
3438 return starunpack_helper(c, elts,
3439 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003441 else
3442 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444}
3445
3446static int
3447compiler_tuple(struct compiler *c, expr_ty e)
3448{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003449 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003451 return assignment_helper(c, elts);
3452 }
3453 else if (e->v.Tuple.ctx == Load) {
3454 return starunpack_helper(c, elts,
3455 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3456 }
3457 else
3458 VISIT_SEQ(c, expr, elts);
3459 return 1;
3460}
3461
3462static int
3463compiler_set(struct compiler *c, expr_ty e)
3464{
3465 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3466 BUILD_SET, BUILD_SET_UNPACK);
3467}
3468
3469static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003470are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3471{
3472 Py_ssize_t i;
3473 for (i = begin; i < end; i++) {
3474 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003475 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003476 return 0;
3477 }
3478 return 1;
3479}
3480
3481static int
3482compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3483{
3484 Py_ssize_t i, n = end - begin;
3485 PyObject *keys, *key;
3486 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3487 for (i = begin; i < end; i++) {
3488 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3489 }
3490 keys = PyTuple_New(n);
3491 if (keys == NULL) {
3492 return 0;
3493 }
3494 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003495 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003496 Py_INCREF(key);
3497 PyTuple_SET_ITEM(keys, i - begin, key);
3498 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003499 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003500 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3501 }
3502 else {
3503 for (i = begin; i < end; i++) {
3504 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3505 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3506 }
3507 ADDOP_I(c, BUILD_MAP, n);
3508 }
3509 return 1;
3510}
3511
3512static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003513compiler_dict(struct compiler *c, expr_ty e)
3514{
Victor Stinner976bb402016-03-23 11:36:19 +01003515 Py_ssize_t i, n, elements;
3516 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003517 int is_unpacking = 0;
3518 n = asdl_seq_LEN(e->v.Dict.values);
3519 containers = 0;
3520 elements = 0;
3521 for (i = 0; i < n; i++) {
3522 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3523 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003524 if (!compiler_subdict(c, e, i - elements, i))
3525 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003526 containers++;
3527 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003529 if (is_unpacking) {
3530 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3531 containers++;
3532 }
3533 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003534 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 }
3536 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003538 if (!compiler_subdict(c, e, n - elements, n))
3539 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003540 containers++;
3541 }
3542 /* If there is more than one dict, they need to be merged into a new
3543 * dict. If there is one dict and it's an unpacking, then it needs
3544 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003545 if (containers > 1 || is_unpacking) {
3546 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 }
3548 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549}
3550
3551static int
3552compiler_compare(struct compiler *c, expr_ty e)
3553{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003554 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003557 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3558 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3559 if (n == 0) {
3560 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3561 ADDOP_I(c, COMPARE_OP,
3562 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3563 }
3564 else {
3565 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 if (cleanup == NULL)
3567 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003568 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 VISIT(c, expr,
3570 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003571 ADDOP(c, DUP_TOP);
3572 ADDOP(c, ROT_THREE);
3573 ADDOP_I(c, COMPARE_OP,
3574 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3575 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3576 NEXT_BLOCK(c);
3577 }
3578 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3579 ADDOP_I(c, COMPARE_OP,
3580 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 basicblock *end = compiler_new_block(c);
3582 if (end == NULL)
3583 return 0;
3584 ADDOP_JREL(c, JUMP_FORWARD, end);
3585 compiler_use_next_block(c, cleanup);
3586 ADDOP(c, ROT_TWO);
3587 ADDOP(c, POP_TOP);
3588 compiler_use_next_block(c, end);
3589 }
3590 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591}
3592
3593static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003594maybe_optimize_method_call(struct compiler *c, expr_ty e)
3595{
3596 Py_ssize_t argsl, i;
3597 expr_ty meth = e->v.Call.func;
3598 asdl_seq *args = e->v.Call.args;
3599
3600 /* Check that the call node is an attribute access, and that
3601 the call doesn't have keyword parameters. */
3602 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3603 asdl_seq_LEN(e->v.Call.keywords))
3604 return -1;
3605
3606 /* Check that there are no *varargs types of arguments. */
3607 argsl = asdl_seq_LEN(args);
3608 for (i = 0; i < argsl; i++) {
3609 expr_ty elt = asdl_seq_GET(args, i);
3610 if (elt->kind == Starred_kind) {
3611 return -1;
3612 }
3613 }
3614
3615 /* Alright, we can optimize the code. */
3616 VISIT(c, expr, meth->v.Attribute.value);
3617 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3618 VISIT_SEQ(c, expr, e->v.Call.args);
3619 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3620 return 1;
3621}
3622
3623static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624compiler_call(struct compiler *c, expr_ty e)
3625{
Yury Selivanovf2392132016-12-13 19:03:51 -05003626 if (maybe_optimize_method_call(c, e) > 0)
3627 return 1;
3628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 VISIT(c, expr, e->v.Call.func);
3630 return compiler_call_helper(c, 0,
3631 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003632 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003633}
3634
Eric V. Smith235a6f02015-09-19 14:51:32 -04003635static int
3636compiler_joined_str(struct compiler *c, expr_ty e)
3637{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003638 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003639 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3640 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003641 return 1;
3642}
3643
Eric V. Smitha78c7952015-11-03 12:45:05 -05003644/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003645static int
3646compiler_formatted_value(struct compiler *c, expr_ty e)
3647{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003648 /* Our oparg encodes 2 pieces of information: the conversion
3649 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003650
Eric V. Smitha78c7952015-11-03 12:45:05 -05003651 Convert the conversion char to 2 bits:
3652 None: 000 0x0 FVC_NONE
3653 !s : 001 0x1 FVC_STR
3654 !r : 010 0x2 FVC_REPR
3655 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003656
Eric V. Smitha78c7952015-11-03 12:45:05 -05003657 next bit is whether or not we have a format spec:
3658 yes : 100 0x4
3659 no : 000 0x0
3660 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003661
Eric V. Smitha78c7952015-11-03 12:45:05 -05003662 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003663
Eric V. Smitha78c7952015-11-03 12:45:05 -05003664 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003665 VISIT(c, expr, e->v.FormattedValue.value);
3666
Eric V. Smitha78c7952015-11-03 12:45:05 -05003667 switch (e->v.FormattedValue.conversion) {
3668 case 's': oparg = FVC_STR; break;
3669 case 'r': oparg = FVC_REPR; break;
3670 case 'a': oparg = FVC_ASCII; break;
3671 case -1: oparg = FVC_NONE; break;
3672 default:
3673 PyErr_SetString(PyExc_SystemError,
3674 "Unrecognized conversion character");
3675 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003676 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003677 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003678 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003679 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003680 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003681 }
3682
Eric V. Smitha78c7952015-11-03 12:45:05 -05003683 /* And push our opcode and oparg */
3684 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003685 return 1;
3686}
3687
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003688static int
3689compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3690{
3691 Py_ssize_t i, n = end - begin;
3692 keyword_ty kw;
3693 PyObject *keys, *key;
3694 assert(n > 0);
3695 if (n > 1) {
3696 for (i = begin; i < end; i++) {
3697 kw = asdl_seq_GET(keywords, i);
3698 VISIT(c, expr, kw->value);
3699 }
3700 keys = PyTuple_New(n);
3701 if (keys == NULL) {
3702 return 0;
3703 }
3704 for (i = begin; i < end; i++) {
3705 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3706 Py_INCREF(key);
3707 PyTuple_SET_ITEM(keys, i - begin, key);
3708 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003709 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003710 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3711 }
3712 else {
3713 /* a for loop only executes once */
3714 for (i = begin; i < end; i++) {
3715 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003716 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003717 VISIT(c, expr, kw->value);
3718 }
3719 ADDOP_I(c, BUILD_MAP, n);
3720 }
3721 return 1;
3722}
3723
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003724/* shared code between compiler_call and compiler_class */
3725static int
3726compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003727 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003728 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003730{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003731 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003732 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003733
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734 /* the number of tuples and dictionaries on the stack */
3735 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3736
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003738 nkwelts = asdl_seq_LEN(keywords);
3739
3740 for (i = 0; i < nkwelts; i++) {
3741 keyword_ty kw = asdl_seq_GET(keywords, i);
3742 if (kw->arg == NULL) {
3743 mustdictunpack = 1;
3744 break;
3745 }
3746 }
3747
3748 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 for (i = 0; i < nelts; i++) {
3750 expr_ty elt = asdl_seq_GET(args, i);
3751 if (elt->kind == Starred_kind) {
3752 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003753 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003754 if (nseen) {
3755 ADDOP_I(c, BUILD_TUPLE, nseen);
3756 nseen = 0;
3757 nsubargs++;
3758 }
3759 VISIT(c, expr, elt->v.Starred.value);
3760 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003761 }
3762 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003764 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003767
3768 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003769 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003770 if (nseen) {
3771 /* Pack up any trailing positional arguments. */
3772 ADDOP_I(c, BUILD_TUPLE, nseen);
3773 nsubargs++;
3774 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003775 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003776 /* If we ended up with more than one stararg, we need
3777 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003778 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003779 }
3780 else if (nsubargs == 0) {
3781 ADDOP_I(c, BUILD_TUPLE, 0);
3782 }
3783 nseen = 0; /* the number of keyword arguments on the stack following */
3784 for (i = 0; i < nkwelts; i++) {
3785 keyword_ty kw = asdl_seq_GET(keywords, i);
3786 if (kw->arg == NULL) {
3787 /* A keyword argument unpacking. */
3788 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003789 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3790 return 0;
3791 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003792 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003793 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003794 VISIT(c, expr, kw->value);
3795 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003796 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003797 else {
3798 nseen++;
3799 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003800 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003801 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003802 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003803 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003804 return 0;
3805 nsubkwargs++;
3806 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003807 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003808 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003809 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003811 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3812 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003814 else if (nkwelts) {
3815 PyObject *names;
3816 VISIT_SEQ(c, keyword, keywords);
3817 names = PyTuple_New(nkwelts);
3818 if (names == NULL) {
3819 return 0;
3820 }
3821 for (i = 0; i < nkwelts; i++) {
3822 keyword_ty kw = asdl_seq_GET(keywords, i);
3823 Py_INCREF(kw->arg);
3824 PyTuple_SET_ITEM(names, i, kw->arg);
3825 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003826 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003827 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3828 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003830 else {
3831 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3832 return 1;
3833 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003834}
3835
Nick Coghlan650f0d02007-04-15 12:05:43 +00003836
3837/* List and set comprehensions and generator expressions work by creating a
3838 nested function to perform the actual iteration. This means that the
3839 iteration variables don't leak into the current scope.
3840 The defined function is called immediately following its definition, with the
3841 result of that call being the result of the expression.
3842 The LC/SC version returns the populated container, while the GE version is
3843 flagged in symtable.c as a generator, so it returns the generator object
3844 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003845
3846 Possible cleanups:
3847 - iterate over the generator sequence instead of using recursion
3848*/
3849
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852compiler_comprehension_generator(struct compiler *c,
3853 asdl_seq *generators, int gen_index,
3854 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003856 comprehension_ty gen;
3857 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3858 if (gen->is_async) {
3859 return compiler_async_comprehension_generator(
3860 c, generators, gen_index, elt, val, type);
3861 } else {
3862 return compiler_sync_comprehension_generator(
3863 c, generators, gen_index, elt, val, type);
3864 }
3865}
3866
3867static int
3868compiler_sync_comprehension_generator(struct compiler *c,
3869 asdl_seq *generators, int gen_index,
3870 expr_ty elt, expr_ty val, int type)
3871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 /* generate code for the iterator, then each of the ifs,
3873 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 comprehension_ty gen;
3876 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003877 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 start = compiler_new_block(c);
3880 skip = compiler_new_block(c);
3881 if_cleanup = compiler_new_block(c);
3882 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3885 anchor == NULL)
3886 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 if (gen_index == 0) {
3891 /* Receive outermost iter as an implicit argument */
3892 c->u->u_argcount = 1;
3893 ADDOP_I(c, LOAD_FAST, 0);
3894 }
3895 else {
3896 /* Sub-iter - calculate on the fly */
3897 VISIT(c, expr, gen->iter);
3898 ADDOP(c, GET_ITER);
3899 }
3900 compiler_use_next_block(c, start);
3901 ADDOP_JREL(c, FOR_ITER, anchor);
3902 NEXT_BLOCK(c);
3903 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 /* XXX this needs to be cleaned up...a lot! */
3906 n = asdl_seq_LEN(gen->ifs);
3907 for (i = 0; i < n; i++) {
3908 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003909 if (!compiler_jump_if(c, e, if_cleanup, 0))
3910 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 NEXT_BLOCK(c);
3912 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 if (++gen_index < asdl_seq_LEN(generators))
3915 if (!compiler_comprehension_generator(c,
3916 generators, gen_index,
3917 elt, val, type))
3918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 /* only append after the last for generator */
3921 if (gen_index >= asdl_seq_LEN(generators)) {
3922 /* comprehension specific code */
3923 switch (type) {
3924 case COMP_GENEXP:
3925 VISIT(c, expr, elt);
3926 ADDOP(c, YIELD_VALUE);
3927 ADDOP(c, POP_TOP);
3928 break;
3929 case COMP_LISTCOMP:
3930 VISIT(c, expr, elt);
3931 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3932 break;
3933 case COMP_SETCOMP:
3934 VISIT(c, expr, elt);
3935 ADDOP_I(c, SET_ADD, gen_index + 1);
3936 break;
3937 case COMP_DICTCOMP:
3938 /* With 'd[k] = v', v is evaluated before k, so we do
3939 the same. */
3940 VISIT(c, expr, val);
3941 VISIT(c, expr, elt);
3942 ADDOP_I(c, MAP_ADD, gen_index + 1);
3943 break;
3944 default:
3945 return 0;
3946 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 compiler_use_next_block(c, skip);
3949 }
3950 compiler_use_next_block(c, if_cleanup);
3951 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3952 compiler_use_next_block(c, anchor);
3953
3954 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955}
3956
3957static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003958compiler_async_comprehension_generator(struct compiler *c,
3959 asdl_seq *generators, int gen_index,
3960 expr_ty elt, expr_ty val, int type)
3961{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003962 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003963 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003964 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003965 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003967 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003969 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003970 return 0;
3971 }
3972
3973 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3974
3975 if (gen_index == 0) {
3976 /* Receive outermost iter as an implicit argument */
3977 c->u->u_argcount = 1;
3978 ADDOP_I(c, LOAD_FAST, 0);
3979 }
3980 else {
3981 /* Sub-iter - calculate on the fly */
3982 VISIT(c, expr, gen->iter);
3983 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003984 }
3985
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003986 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003987
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003988 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003989 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003990 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003991 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003992 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02003993 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003994
3995 n = asdl_seq_LEN(gen->ifs);
3996 for (i = 0; i < n; i++) {
3997 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003998 if (!compiler_jump_if(c, e, if_cleanup, 0))
3999 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004000 NEXT_BLOCK(c);
4001 }
4002
4003 if (++gen_index < asdl_seq_LEN(generators))
4004 if (!compiler_comprehension_generator(c,
4005 generators, gen_index,
4006 elt, val, type))
4007 return 0;
4008
4009 /* only append after the last for generator */
4010 if (gen_index >= asdl_seq_LEN(generators)) {
4011 /* comprehension specific code */
4012 switch (type) {
4013 case COMP_GENEXP:
4014 VISIT(c, expr, elt);
4015 ADDOP(c, YIELD_VALUE);
4016 ADDOP(c, POP_TOP);
4017 break;
4018 case COMP_LISTCOMP:
4019 VISIT(c, expr, elt);
4020 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4021 break;
4022 case COMP_SETCOMP:
4023 VISIT(c, expr, elt);
4024 ADDOP_I(c, SET_ADD, gen_index + 1);
4025 break;
4026 case COMP_DICTCOMP:
4027 /* With 'd[k] = v', v is evaluated before k, so we do
4028 the same. */
4029 VISIT(c, expr, val);
4030 VISIT(c, expr, elt);
4031 ADDOP_I(c, MAP_ADD, gen_index + 1);
4032 break;
4033 default:
4034 return 0;
4035 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004036 }
4037 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004038 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4039
4040 compiler_use_next_block(c, except);
4041 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004042
4043 return 1;
4044}
4045
4046static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004047compiler_comprehension(struct compiler *c, expr_ty e, int type,
4048 identifier name, asdl_seq *generators, expr_ty elt,
4049 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004052 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004053 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004054 int is_async_function = c->u->u_ste->ste_coroutine;
4055 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004056
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004057 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004058
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004059 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4060 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004061 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004063 }
4064
4065 is_async_generator = c->u->u_ste->ste_coroutine;
4066
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004067 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004068 compiler_error(c, "asynchronous comprehension outside of "
4069 "an asynchronous function");
4070 goto error_in_scope;
4071 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 if (type != COMP_GENEXP) {
4074 int op;
4075 switch (type) {
4076 case COMP_LISTCOMP:
4077 op = BUILD_LIST;
4078 break;
4079 case COMP_SETCOMP:
4080 op = BUILD_SET;
4081 break;
4082 case COMP_DICTCOMP:
4083 op = BUILD_MAP;
4084 break;
4085 default:
4086 PyErr_Format(PyExc_SystemError,
4087 "unknown comprehension type %d", type);
4088 goto error_in_scope;
4089 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 ADDOP_I(c, op, 0);
4092 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 if (!compiler_comprehension_generator(c, generators, 0, elt,
4095 val, type))
4096 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 if (type != COMP_GENEXP) {
4099 ADDOP(c, RETURN_VALUE);
4100 }
4101
4102 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004103 qualname = c->u->u_qualname;
4104 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004106 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 goto error;
4108
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004109 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004111 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 Py_DECREF(co);
4113
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004114 VISIT(c, expr, outermost->iter);
4115
4116 if (outermost->is_async) {
4117 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004118 } else {
4119 ADDOP(c, GET_ITER);
4120 }
4121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004123
4124 if (is_async_generator && type != COMP_GENEXP) {
4125 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004126 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004127 ADDOP(c, YIELD_FROM);
4128 }
4129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004131error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004133error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004134 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 Py_XDECREF(co);
4136 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004137}
4138
4139static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004140compiler_genexp(struct compiler *c, expr_ty e)
4141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 static identifier name;
4143 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004144 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 if (!name)
4146 return 0;
4147 }
4148 assert(e->kind == GeneratorExp_kind);
4149 return compiler_comprehension(c, e, COMP_GENEXP, name,
4150 e->v.GeneratorExp.generators,
4151 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152}
4153
4154static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004155compiler_listcomp(struct compiler *c, expr_ty e)
4156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 static identifier name;
4158 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004159 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 if (!name)
4161 return 0;
4162 }
4163 assert(e->kind == ListComp_kind);
4164 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4165 e->v.ListComp.generators,
4166 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004167}
4168
4169static int
4170compiler_setcomp(struct compiler *c, expr_ty e)
4171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 static identifier name;
4173 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004174 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 if (!name)
4176 return 0;
4177 }
4178 assert(e->kind == SetComp_kind);
4179 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4180 e->v.SetComp.generators,
4181 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004182}
4183
4184
4185static int
4186compiler_dictcomp(struct compiler *c, expr_ty e)
4187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 static identifier name;
4189 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004190 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 if (!name)
4192 return 0;
4193 }
4194 assert(e->kind == DictComp_kind);
4195 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4196 e->v.DictComp.generators,
4197 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004198}
4199
4200
4201static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004202compiler_visit_keyword(struct compiler *c, keyword_ty k)
4203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 VISIT(c, expr, k->value);
4205 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206}
4207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004209 whether they are true or false.
4210
4211 Return values: 1 for true, 0 for false, -1 for non-constant.
4212 */
4213
4214static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004215expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004216{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004217 if (e->kind == Constant_kind) {
4218 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004219 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004220 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221}
4222
Yury Selivanov75445082015-05-11 22:57:16 -04004223
4224/*
4225 Implements the async with statement.
4226
4227 The semantics outlined in that PEP are as follows:
4228
4229 async with EXPR as VAR:
4230 BLOCK
4231
4232 It is implemented roughly as:
4233
4234 context = EXPR
4235 exit = context.__aexit__ # not calling it
4236 value = await context.__aenter__()
4237 try:
4238 VAR = value # if VAR present in the syntax
4239 BLOCK
4240 finally:
4241 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004242 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004243 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004244 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004245 if not (await exit(*exc)):
4246 raise
4247 */
4248static int
4249compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4250{
4251 basicblock *block, *finally;
4252 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4253
4254 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004255 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4256 return compiler_error(c, "'async with' outside async function");
4257 }
Yury Selivanov75445082015-05-11 22:57:16 -04004258
4259 block = compiler_new_block(c);
4260 finally = compiler_new_block(c);
4261 if (!block || !finally)
4262 return 0;
4263
4264 /* Evaluate EXPR */
4265 VISIT(c, expr, item->context_expr);
4266
4267 ADDOP(c, BEFORE_ASYNC_WITH);
4268 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004269 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004270 ADDOP(c, YIELD_FROM);
4271
4272 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4273
4274 /* SETUP_ASYNC_WITH pushes a finally block. */
4275 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004276 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004277 return 0;
4278 }
4279
4280 if (item->optional_vars) {
4281 VISIT(c, expr, item->optional_vars);
4282 }
4283 else {
4284 /* Discard result from context.__aenter__() */
4285 ADDOP(c, POP_TOP);
4286 }
4287
4288 pos++;
4289 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4290 /* BLOCK code */
4291 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4292 else if (!compiler_async_with(c, s, pos))
4293 return 0;
4294
4295 /* End of try block; start the finally block */
4296 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004297 ADDOP(c, BEGIN_FINALLY);
4298 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004299
Yury Selivanov75445082015-05-11 22:57:16 -04004300 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004301 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004302 return 0;
4303
4304 /* Finally block starts; context.__exit__ is on the stack under
4305 the exception or return information. Just issue our magic
4306 opcode. */
4307 ADDOP(c, WITH_CLEANUP_START);
4308
4309 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004310 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004311 ADDOP(c, YIELD_FROM);
4312
4313 ADDOP(c, WITH_CLEANUP_FINISH);
4314
4315 /* Finally block ends. */
4316 ADDOP(c, END_FINALLY);
4317 compiler_pop_fblock(c, FINALLY_END, finally);
4318 return 1;
4319}
4320
4321
Guido van Rossumc2e20742006-02-27 22:32:47 +00004322/*
4323 Implements the with statement from PEP 343.
4324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004326
4327 with EXPR as VAR:
4328 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329
Guido van Rossumc2e20742006-02-27 22:32:47 +00004330 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331
Thomas Wouters477c8d52006-05-27 19:21:47 +00004332 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004333 exit = context.__exit__ # not calling it
4334 value = context.__enter__()
4335 try:
4336 VAR = value # if VAR present in the syntax
4337 BLOCK
4338 finally:
4339 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004340 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004341 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004342 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004343 exit(*exc)
4344 */
4345static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004346compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004347{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004348 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004349 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004350
4351 assert(s->kind == With_kind);
4352
Guido van Rossumc2e20742006-02-27 22:32:47 +00004353 block = compiler_new_block(c);
4354 finally = compiler_new_block(c);
4355 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004356 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004357
Thomas Wouters477c8d52006-05-27 19:21:47 +00004358 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004359 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004360 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004361
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004362 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004363 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004364 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004365 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004366 }
4367
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004368 if (item->optional_vars) {
4369 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004370 }
4371 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004373 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004374 }
4375
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004376 pos++;
4377 if (pos == asdl_seq_LEN(s->v.With.items))
4378 /* BLOCK code */
4379 VISIT_SEQ(c, stmt, s->v.With.body)
4380 else if (!compiler_with(c, s, pos))
4381 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004382
4383 /* End of try block; start the finally block */
4384 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004385 ADDOP(c, BEGIN_FINALLY);
4386 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004387
Guido van Rossumc2e20742006-02-27 22:32:47 +00004388 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004389 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004390 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004391
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004392 /* Finally block starts; context.__exit__ is on the stack under
4393 the exception or return information. Just issue our magic
4394 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004395 ADDOP(c, WITH_CLEANUP_START);
4396 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004397
4398 /* Finally block ends. */
4399 ADDOP(c, END_FINALLY);
4400 compiler_pop_fblock(c, FINALLY_END, finally);
4401 return 1;
4402}
4403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004405compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 switch (e->kind) {
4408 case BoolOp_kind:
4409 return compiler_boolop(c, e);
4410 case BinOp_kind:
4411 VISIT(c, expr, e->v.BinOp.left);
4412 VISIT(c, expr, e->v.BinOp.right);
4413 ADDOP(c, binop(c, e->v.BinOp.op));
4414 break;
4415 case UnaryOp_kind:
4416 VISIT(c, expr, e->v.UnaryOp.operand);
4417 ADDOP(c, unaryop(e->v.UnaryOp.op));
4418 break;
4419 case Lambda_kind:
4420 return compiler_lambda(c, e);
4421 case IfExp_kind:
4422 return compiler_ifexp(c, e);
4423 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004424 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004426 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 case GeneratorExp_kind:
4428 return compiler_genexp(c, e);
4429 case ListComp_kind:
4430 return compiler_listcomp(c, e);
4431 case SetComp_kind:
4432 return compiler_setcomp(c, e);
4433 case DictComp_kind:
4434 return compiler_dictcomp(c, e);
4435 case Yield_kind:
4436 if (c->u->u_ste->ste_type != FunctionBlock)
4437 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004438 if (e->v.Yield.value) {
4439 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 }
4441 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004442 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004444 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004446 case YieldFrom_kind:
4447 if (c->u->u_ste->ste_type != FunctionBlock)
4448 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004449
4450 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4451 return compiler_error(c, "'yield from' inside async function");
4452
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004453 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004454 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004455 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004456 ADDOP(c, YIELD_FROM);
4457 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004458 case Await_kind:
4459 if (c->u->u_ste->ste_type != FunctionBlock)
4460 return compiler_error(c, "'await' outside function");
4461
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004462 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4463 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004464 return compiler_error(c, "'await' outside async function");
4465
4466 VISIT(c, expr, e->v.Await.value);
4467 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004468 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004469 ADDOP(c, YIELD_FROM);
4470 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 case Compare_kind:
4472 return compiler_compare(c, e);
4473 case Call_kind:
4474 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004475 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004476 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004477 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004478 case JoinedStr_kind:
4479 return compiler_joined_str(c, e);
4480 case FormattedValue_kind:
4481 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 /* The following exprs can be assignment targets. */
4483 case Attribute_kind:
4484 if (e->v.Attribute.ctx != AugStore)
4485 VISIT(c, expr, e->v.Attribute.value);
4486 switch (e->v.Attribute.ctx) {
4487 case AugLoad:
4488 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004489 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 case Load:
4491 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4492 break;
4493 case AugStore:
4494 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004495 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 case Store:
4497 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4498 break;
4499 case Del:
4500 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4501 break;
4502 case Param:
4503 default:
4504 PyErr_SetString(PyExc_SystemError,
4505 "param invalid in attribute expression");
4506 return 0;
4507 }
4508 break;
4509 case Subscript_kind:
4510 switch (e->v.Subscript.ctx) {
4511 case AugLoad:
4512 VISIT(c, expr, e->v.Subscript.value);
4513 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4514 break;
4515 case Load:
4516 VISIT(c, expr, e->v.Subscript.value);
4517 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4518 break;
4519 case AugStore:
4520 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4521 break;
4522 case Store:
4523 VISIT(c, expr, e->v.Subscript.value);
4524 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4525 break;
4526 case Del:
4527 VISIT(c, expr, e->v.Subscript.value);
4528 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4529 break;
4530 case Param:
4531 default:
4532 PyErr_SetString(PyExc_SystemError,
4533 "param invalid in subscript expression");
4534 return 0;
4535 }
4536 break;
4537 case Starred_kind:
4538 switch (e->v.Starred.ctx) {
4539 case Store:
4540 /* In all legitimate cases, the Starred node was already replaced
4541 * by compiler_list/compiler_tuple. XXX: is that okay? */
4542 return compiler_error(c,
4543 "starred assignment target must be in a list or tuple");
4544 default:
4545 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004546 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 }
4548 break;
4549 case Name_kind:
4550 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4551 /* child nodes of List and Tuple will have expr_context set */
4552 case List_kind:
4553 return compiler_list(c, e);
4554 case Tuple_kind:
4555 return compiler_tuple(c, e);
4556 }
4557 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004558}
4559
4560static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004561compiler_visit_expr(struct compiler *c, expr_ty e)
4562{
4563 /* If expr e has a different line number than the last expr/stmt,
4564 set a new line number for the next instruction.
4565 */
4566 int old_lineno = c->u->u_lineno;
4567 int old_col_offset = c->u->u_col_offset;
4568 if (e->lineno != c->u->u_lineno) {
4569 c->u->u_lineno = e->lineno;
4570 c->u->u_lineno_set = 0;
4571 }
4572 /* Updating the column offset is always harmless. */
4573 c->u->u_col_offset = e->col_offset;
4574
4575 int res = compiler_visit_expr1(c, e);
4576
4577 if (old_lineno != c->u->u_lineno) {
4578 c->u->u_lineno = old_lineno;
4579 c->u->u_lineno_set = 0;
4580 }
4581 c->u->u_col_offset = old_col_offset;
4582 return res;
4583}
4584
4585static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004586compiler_augassign(struct compiler *c, stmt_ty s)
4587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 expr_ty e = s->v.AugAssign.target;
4589 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 switch (e->kind) {
4594 case Attribute_kind:
4595 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
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.Attribute.ctx = AugStore;
4603 VISIT(c, expr, auge);
4604 break;
4605 case Subscript_kind:
4606 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4607 AugLoad, e->lineno, e->col_offset, c->c_arena);
4608 if (auge == NULL)
4609 return 0;
4610 VISIT(c, expr, auge);
4611 VISIT(c, expr, s->v.AugAssign.value);
4612 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4613 auge->v.Subscript.ctx = AugStore;
4614 VISIT(c, expr, auge);
4615 break;
4616 case Name_kind:
4617 if (!compiler_nameop(c, e->v.Name.id, Load))
4618 return 0;
4619 VISIT(c, expr, s->v.AugAssign.value);
4620 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4621 return compiler_nameop(c, e->v.Name.id, Store);
4622 default:
4623 PyErr_Format(PyExc_SystemError,
4624 "invalid node type (%d) for augmented assignment",
4625 e->kind);
4626 return 0;
4627 }
4628 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004629}
4630
4631static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004632check_ann_expr(struct compiler *c, expr_ty e)
4633{
4634 VISIT(c, expr, e);
4635 ADDOP(c, POP_TOP);
4636 return 1;
4637}
4638
4639static int
4640check_annotation(struct compiler *c, stmt_ty s)
4641{
4642 /* Annotations are only evaluated in a module or class. */
4643 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4644 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4645 return check_ann_expr(c, s->v.AnnAssign.annotation);
4646 }
4647 return 1;
4648}
4649
4650static int
4651check_ann_slice(struct compiler *c, slice_ty sl)
4652{
4653 switch(sl->kind) {
4654 case Index_kind:
4655 return check_ann_expr(c, sl->v.Index.value);
4656 case Slice_kind:
4657 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4658 return 0;
4659 }
4660 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4661 return 0;
4662 }
4663 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4664 return 0;
4665 }
4666 break;
4667 default:
4668 PyErr_SetString(PyExc_SystemError,
4669 "unexpected slice kind");
4670 return 0;
4671 }
4672 return 1;
4673}
4674
4675static int
4676check_ann_subscr(struct compiler *c, slice_ty sl)
4677{
4678 /* We check that everything in a subscript is defined at runtime. */
4679 Py_ssize_t i, n;
4680
4681 switch (sl->kind) {
4682 case Index_kind:
4683 case Slice_kind:
4684 if (!check_ann_slice(c, sl)) {
4685 return 0;
4686 }
4687 break;
4688 case ExtSlice_kind:
4689 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4690 for (i = 0; i < n; i++) {
4691 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4692 switch (subsl->kind) {
4693 case Index_kind:
4694 case Slice_kind:
4695 if (!check_ann_slice(c, subsl)) {
4696 return 0;
4697 }
4698 break;
4699 case ExtSlice_kind:
4700 default:
4701 PyErr_SetString(PyExc_SystemError,
4702 "extended slice invalid in nested slice");
4703 return 0;
4704 }
4705 }
4706 break;
4707 default:
4708 PyErr_Format(PyExc_SystemError,
4709 "invalid subscript kind %d", sl->kind);
4710 return 0;
4711 }
4712 return 1;
4713}
4714
4715static int
4716compiler_annassign(struct compiler *c, stmt_ty s)
4717{
4718 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004719 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004720
4721 assert(s->kind == AnnAssign_kind);
4722
4723 /* We perform the actual assignment first. */
4724 if (s->v.AnnAssign.value) {
4725 VISIT(c, expr, s->v.AnnAssign.value);
4726 VISIT(c, expr, targ);
4727 }
4728 switch (targ->kind) {
4729 case Name_kind:
4730 /* If we have a simple name in a module or class, store annotation. */
4731 if (s->v.AnnAssign.simple &&
4732 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4733 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004734 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4735 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4736 }
4737 else {
4738 VISIT(c, expr, s->v.AnnAssign.annotation);
4739 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004740 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004741 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004742 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004743 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004744 }
4745 break;
4746 case Attribute_kind:
4747 if (!s->v.AnnAssign.value &&
4748 !check_ann_expr(c, targ->v.Attribute.value)) {
4749 return 0;
4750 }
4751 break;
4752 case Subscript_kind:
4753 if (!s->v.AnnAssign.value &&
4754 (!check_ann_expr(c, targ->v.Subscript.value) ||
4755 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4756 return 0;
4757 }
4758 break;
4759 default:
4760 PyErr_Format(PyExc_SystemError,
4761 "invalid node type (%d) for annotated assignment",
4762 targ->kind);
4763 return 0;
4764 }
4765 /* Annotation is evaluated last. */
4766 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4767 return 0;
4768 }
4769 return 1;
4770}
4771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004772/* Raises a SyntaxError and returns 0.
4773 If something goes wrong, a different exception may be raised.
4774*/
4775
4776static int
4777compiler_error(struct compiler *c, const char *errstr)
4778{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004779 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004781
Victor Stinner14e461d2013-08-26 22:28:21 +02004782 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 if (!loc) {
4784 Py_INCREF(Py_None);
4785 loc = Py_None;
4786 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004787 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004788 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 if (!u)
4790 goto exit;
4791 v = Py_BuildValue("(zO)", errstr, u);
4792 if (!v)
4793 goto exit;
4794 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004795 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 Py_DECREF(loc);
4797 Py_XDECREF(u);
4798 Py_XDECREF(v);
4799 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004800}
4801
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004802/* Emits a SyntaxWarning and returns 1 on success.
4803 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4804 and returns 0.
4805*/
4806static int
4807compiler_warn(struct compiler *c, const char *errstr)
4808{
4809 PyObject *msg = PyUnicode_FromString(errstr);
4810 if (msg == NULL) {
4811 return 0;
4812 }
4813 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4814 c->u->u_lineno, NULL, NULL) < 0)
4815 {
4816 Py_DECREF(msg);
4817 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4818 PyErr_Clear();
4819 return compiler_error(c, errstr);
4820 }
4821 return 0;
4822 }
4823 Py_DECREF(msg);
4824 return 1;
4825}
4826
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004827static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828compiler_handle_subscr(struct compiler *c, const char *kind,
4829 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 /* XXX this code is duplicated */
4834 switch (ctx) {
4835 case AugLoad: /* fall through to Load */
4836 case Load: op = BINARY_SUBSCR; break;
4837 case AugStore:/* fall through to Store */
4838 case Store: op = STORE_SUBSCR; break;
4839 case Del: op = DELETE_SUBSCR; break;
4840 case Param:
4841 PyErr_Format(PyExc_SystemError,
4842 "invalid %s kind %d in subscript\n",
4843 kind, ctx);
4844 return 0;
4845 }
4846 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004847 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 }
4849 else if (ctx == AugStore) {
4850 ADDOP(c, ROT_THREE);
4851 }
4852 ADDOP(c, op);
4853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004854}
4855
4856static int
4857compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 int n = 2;
4860 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 /* only handles the cases where BUILD_SLICE is emitted */
4863 if (s->v.Slice.lower) {
4864 VISIT(c, expr, s->v.Slice.lower);
4865 }
4866 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004867 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 if (s->v.Slice.upper) {
4871 VISIT(c, expr, s->v.Slice.upper);
4872 }
4873 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004874 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 }
4876
4877 if (s->v.Slice.step) {
4878 n++;
4879 VISIT(c, expr, s->v.Slice.step);
4880 }
4881 ADDOP_I(c, BUILD_SLICE, n);
4882 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004883}
4884
4885static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4887 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 switch (s->kind) {
4890 case Slice_kind:
4891 return compiler_slice(c, s, ctx);
4892 case Index_kind:
4893 VISIT(c, expr, s->v.Index.value);
4894 break;
4895 case ExtSlice_kind:
4896 default:
4897 PyErr_SetString(PyExc_SystemError,
4898 "extended slice invalid in nested slice");
4899 return 0;
4900 }
4901 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004902}
4903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004904static int
4905compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4906{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004907 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 switch (s->kind) {
4909 case Index_kind:
4910 kindname = "index";
4911 if (ctx != AugStore) {
4912 VISIT(c, expr, s->v.Index.value);
4913 }
4914 break;
4915 case Slice_kind:
4916 kindname = "slice";
4917 if (ctx != AugStore) {
4918 if (!compiler_slice(c, s, ctx))
4919 return 0;
4920 }
4921 break;
4922 case ExtSlice_kind:
4923 kindname = "extended slice";
4924 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004925 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 for (i = 0; i < n; i++) {
4927 slice_ty sub = (slice_ty)asdl_seq_GET(
4928 s->v.ExtSlice.dims, i);
4929 if (!compiler_visit_nested_slice(c, sub, ctx))
4930 return 0;
4931 }
4932 ADDOP_I(c, BUILD_TUPLE, n);
4933 }
4934 break;
4935 default:
4936 PyErr_Format(PyExc_SystemError,
4937 "invalid subscript kind %d", s->kind);
4938 return 0;
4939 }
4940 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004941}
4942
Thomas Wouters89f507f2006-12-13 04:49:30 +00004943/* End of the compiler section, beginning of the assembler section */
4944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004945/* do depth-first search of basic block graph, starting with block.
4946 post records the block indices in post-order.
4947
4948 XXX must handle implicit jumps from one block to next
4949*/
4950
Thomas Wouters89f507f2006-12-13 04:49:30 +00004951struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 PyObject *a_bytecode; /* string containing bytecode */
4953 int a_offset; /* offset into bytecode */
4954 int a_nblocks; /* number of reachable blocks */
4955 basicblock **a_postorder; /* list of blocks in dfs postorder */
4956 PyObject *a_lnotab; /* string containing lnotab */
4957 int a_lnotab_off; /* offset into lnotab */
4958 int a_lineno; /* last lineno of emitted instruction */
4959 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004960};
4961
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004962static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004963dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004964{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004965 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004966
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004967 /* Get rid of recursion for normal control flow.
4968 Since the number of blocks is limited, unused space in a_postorder
4969 (from a_nblocks to end) can be used as a stack for still not ordered
4970 blocks. */
4971 for (j = end; b && !b->b_seen; b = b->b_next) {
4972 b->b_seen = 1;
4973 assert(a->a_nblocks < j);
4974 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004976 while (j < end) {
4977 b = a->a_postorder[j++];
4978 for (i = 0; i < b->b_iused; i++) {
4979 struct instr *instr = &b->b_instr[i];
4980 if (instr->i_jrel || instr->i_jabs)
4981 dfs(c, instr->i_target, a, j);
4982 }
4983 assert(a->a_nblocks < j);
4984 a->a_postorder[a->a_nblocks++] = b;
4985 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004986}
4987
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004988Py_LOCAL_INLINE(void)
4989stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004990{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004991 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004992 if (b->b_startdepth < depth) {
4993 assert(b->b_startdepth < 0);
4994 b->b_startdepth = depth;
4995 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004996 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004997}
4998
4999/* Find the flow path that needs the largest stack. We assume that
5000 * cycles in the flow graph have no net effect on the stack depth.
5001 */
5002static int
5003stackdepth(struct compiler *c)
5004{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005005 basicblock *b, *entryblock = NULL;
5006 basicblock **stack, **sp;
5007 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 b->b_startdepth = INT_MIN;
5010 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005011 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 }
5013 if (!entryblock)
5014 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005015 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5016 if (!stack) {
5017 PyErr_NoMemory();
5018 return -1;
5019 }
5020
5021 sp = stack;
5022 stackdepth_push(&sp, entryblock, 0);
5023 while (sp != stack) {
5024 b = *--sp;
5025 int depth = b->b_startdepth;
5026 assert(depth >= 0);
5027 basicblock *next = b->b_next;
5028 for (int i = 0; i < b->b_iused; i++) {
5029 struct instr *instr = &b->b_instr[i];
5030 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5031 if (effect == PY_INVALID_STACK_EFFECT) {
5032 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5033 Py_FatalError("PyCompile_OpcodeStackEffect()");
5034 }
5035 int new_depth = depth + effect;
5036 if (new_depth > maxdepth) {
5037 maxdepth = new_depth;
5038 }
5039 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5040 if (instr->i_jrel || instr->i_jabs) {
5041 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5042 assert(effect != PY_INVALID_STACK_EFFECT);
5043 int target_depth = depth + effect;
5044 if (target_depth > maxdepth) {
5045 maxdepth = target_depth;
5046 }
5047 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005048 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005049 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005050 assert(instr->i_target->b_startdepth >= target_depth);
5051 depth = new_depth;
5052 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005053 }
5054 stackdepth_push(&sp, instr->i_target, target_depth);
5055 }
5056 depth = new_depth;
5057 if (instr->i_opcode == JUMP_ABSOLUTE ||
5058 instr->i_opcode == JUMP_FORWARD ||
5059 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005060 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005061 {
5062 /* remaining code is dead */
5063 next = NULL;
5064 break;
5065 }
5066 }
5067 if (next != NULL) {
5068 stackdepth_push(&sp, next, depth);
5069 }
5070 }
5071 PyObject_Free(stack);
5072 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005073}
5074
5075static int
5076assemble_init(struct assembler *a, int nblocks, int firstlineno)
5077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 memset(a, 0, sizeof(struct assembler));
5079 a->a_lineno = firstlineno;
5080 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5081 if (!a->a_bytecode)
5082 return 0;
5083 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5084 if (!a->a_lnotab)
5085 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005086 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 PyErr_NoMemory();
5088 return 0;
5089 }
5090 a->a_postorder = (basicblock **)PyObject_Malloc(
5091 sizeof(basicblock *) * nblocks);
5092 if (!a->a_postorder) {
5093 PyErr_NoMemory();
5094 return 0;
5095 }
5096 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005097}
5098
5099static void
5100assemble_free(struct assembler *a)
5101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 Py_XDECREF(a->a_bytecode);
5103 Py_XDECREF(a->a_lnotab);
5104 if (a->a_postorder)
5105 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005106}
5107
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005108static int
5109blocksize(basicblock *b)
5110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 int i;
5112 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005115 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005117}
5118
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005119/* Appends a pair to the end of the line number table, a_lnotab, representing
5120 the instruction's bytecode offset and line number. See
5121 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005122
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005123static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005124assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005127 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005129
Serhiy Storchakaab874002016-09-11 13:48:15 +03005130 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 if(d_bytecode == 0 && d_lineno == 0)
5136 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 if (d_bytecode > 255) {
5139 int j, nbytes, ncodes = d_bytecode / 255;
5140 nbytes = a->a_lnotab_off + 2 * ncodes;
5141 len = PyBytes_GET_SIZE(a->a_lnotab);
5142 if (nbytes >= len) {
5143 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5144 len = nbytes;
5145 else if (len <= INT_MAX / 2)
5146 len *= 2;
5147 else {
5148 PyErr_NoMemory();
5149 return 0;
5150 }
5151 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5152 return 0;
5153 }
5154 lnotab = (unsigned char *)
5155 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5156 for (j = 0; j < ncodes; j++) {
5157 *lnotab++ = 255;
5158 *lnotab++ = 0;
5159 }
5160 d_bytecode -= ncodes * 255;
5161 a->a_lnotab_off += ncodes * 2;
5162 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005163 assert(0 <= d_bytecode && d_bytecode <= 255);
5164
5165 if (d_lineno < -128 || 127 < d_lineno) {
5166 int j, nbytes, ncodes, k;
5167 if (d_lineno < 0) {
5168 k = -128;
5169 /* use division on positive numbers */
5170 ncodes = (-d_lineno) / 128;
5171 }
5172 else {
5173 k = 127;
5174 ncodes = d_lineno / 127;
5175 }
5176 d_lineno -= ncodes * k;
5177 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 nbytes = a->a_lnotab_off + 2 * ncodes;
5179 len = PyBytes_GET_SIZE(a->a_lnotab);
5180 if (nbytes >= len) {
5181 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5182 len = nbytes;
5183 else if (len <= INT_MAX / 2)
5184 len *= 2;
5185 else {
5186 PyErr_NoMemory();
5187 return 0;
5188 }
5189 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5190 return 0;
5191 }
5192 lnotab = (unsigned char *)
5193 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5194 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005195 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 d_bytecode = 0;
5197 for (j = 1; j < ncodes; j++) {
5198 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005199 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005201 a->a_lnotab_off += ncodes * 2;
5202 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005203 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 len = PyBytes_GET_SIZE(a->a_lnotab);
5206 if (a->a_lnotab_off + 2 >= len) {
5207 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5208 return 0;
5209 }
5210 lnotab = (unsigned char *)
5211 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 a->a_lnotab_off += 2;
5214 if (d_bytecode) {
5215 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005216 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 }
5218 else { /* First line of a block; def stmt, etc. */
5219 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005220 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 }
5222 a->a_lineno = i->i_lineno;
5223 a->a_lineno_off = a->a_offset;
5224 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005225}
5226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005227/* assemble_emit()
5228 Extend the bytecode with a new instruction.
5229 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005230*/
5231
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005232static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005233assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005234{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005235 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005237 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005238
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005239 arg = i->i_oparg;
5240 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 if (i->i_lineno && !assemble_lnotab(a, i))
5242 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005243 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 if (len > PY_SSIZE_T_MAX / 2)
5245 return 0;
5246 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5247 return 0;
5248 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005249 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005251 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005253}
5254
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005255static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005256assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005259 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 /* Compute the size of each block and fixup jump args.
5263 Replace block pointer with position in bytecode. */
5264 do {
5265 totsize = 0;
5266 for (i = a->a_nblocks - 1; i >= 0; i--) {
5267 b = a->a_postorder[i];
5268 bsize = blocksize(b);
5269 b->b_offset = totsize;
5270 totsize += bsize;
5271 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005272 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5274 bsize = b->b_offset;
5275 for (i = 0; i < b->b_iused; i++) {
5276 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005277 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 /* Relative jumps are computed relative to
5279 the instruction pointer after fetching
5280 the jump instruction.
5281 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005282 bsize += isize;
5283 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005285 if (instr->i_jrel) {
5286 instr->i_oparg -= bsize;
5287 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005288 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005289 if (instrsize(instr->i_oparg) != isize) {
5290 extended_arg_recompile = 1;
5291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 }
5294 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 /* XXX: This is an awful hack that could hurt performance, but
5297 on the bright side it should work until we come up
5298 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 The issue is that in the first loop blocksize() is called
5301 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005302 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 So we loop until we stop seeing new EXTENDED_ARGs.
5306 The only EXTENDED_ARGs that could be popping up are
5307 ones in jump instructions. So this should converge
5308 fairly quickly.
5309 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005310 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005311}
5312
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005313static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005314dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005317 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 tuple = PyTuple_New(size);
5320 if (tuple == NULL)
5321 return NULL;
5322 while (PyDict_Next(dict, &pos, &k, &v)) {
5323 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005324 Py_INCREF(k);
5325 assert((i - offset) < size);
5326 assert((i - offset) >= 0);
5327 PyTuple_SET_ITEM(tuple, i - offset, k);
5328 }
5329 return tuple;
5330}
5331
5332static PyObject *
5333consts_dict_keys_inorder(PyObject *dict)
5334{
5335 PyObject *consts, *k, *v;
5336 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5337
5338 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5339 if (consts == NULL)
5340 return NULL;
5341 while (PyDict_Next(dict, &pos, &k, &v)) {
5342 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005343 /* The keys of the dictionary can be tuples wrapping a contant.
5344 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5345 * the object we want is always second. */
5346 if (PyTuple_CheckExact(k)) {
5347 k = PyTuple_GET_ITEM(k, 1);
5348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005350 assert(i < size);
5351 assert(i >= 0);
5352 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005354 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005355}
5356
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005357static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005358compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005361 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005363 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 if (ste->ste_nested)
5365 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005366 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005368 if (!ste->ste_generator && ste->ste_coroutine)
5369 flags |= CO_COROUTINE;
5370 if (ste->ste_generator && ste->ste_coroutine)
5371 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 if (ste->ste_varargs)
5373 flags |= CO_VARARGS;
5374 if (ste->ste_varkeywords)
5375 flags |= CO_VARKEYWORDS;
5376 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 /* (Only) inherit compilerflags in PyCF_MASK */
5379 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005382}
5383
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005384static PyCodeObject *
5385makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 PyObject *tmp;
5388 PyCodeObject *co = NULL;
5389 PyObject *consts = NULL;
5390 PyObject *names = NULL;
5391 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 PyObject *name = NULL;
5393 PyObject *freevars = NULL;
5394 PyObject *cellvars = NULL;
5395 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005396 Py_ssize_t nlocals;
5397 int nlocals_int;
5398 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005399 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005400
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005401 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 names = dict_keys_inorder(c->u->u_names, 0);
5403 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5404 if (!consts || !names || !varnames)
5405 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5408 if (!cellvars)
5409 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005410 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 if (!freevars)
5412 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005413
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005414 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005415 assert(nlocals < INT_MAX);
5416 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 flags = compute_code_flags(c);
5419 if (flags < 0)
5420 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005422 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5423 if (!bytecode)
5424 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5427 if (!tmp)
5428 goto error;
5429 Py_DECREF(consts);
5430 consts = tmp;
5431
Victor Stinnerf8e32212013-11-19 23:56:34 +01005432 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5433 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005434 maxdepth = stackdepth(c);
5435 if (maxdepth < 0) {
5436 goto error;
5437 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005438 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 bytecode, consts, names, varnames,
5441 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005442 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 c->u->u_firstlineno,
5444 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005445 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 Py_XDECREF(consts);
5447 Py_XDECREF(names);
5448 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 Py_XDECREF(name);
5450 Py_XDECREF(freevars);
5451 Py_XDECREF(cellvars);
5452 Py_XDECREF(bytecode);
5453 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005454}
5455
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005456
5457/* For debugging purposes only */
5458#if 0
5459static void
5460dump_instr(const struct instr *i)
5461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 const char *jrel = i->i_jrel ? "jrel " : "";
5463 const char *jabs = i->i_jabs ? "jabs " : "";
5464 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005467 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005469 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5471 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005472}
5473
5474static void
5475dump_basicblock(const basicblock *b)
5476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 const char *seen = b->b_seen ? "seen " : "";
5478 const char *b_return = b->b_return ? "return " : "";
5479 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5480 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5481 if (b->b_instr) {
5482 int i;
5483 for (i = 0; i < b->b_iused; i++) {
5484 fprintf(stderr, " [%02d] ", i);
5485 dump_instr(b->b_instr + i);
5486 }
5487 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005488}
5489#endif
5490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005491static PyCodeObject *
5492assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 basicblock *b, *entryblock;
5495 struct assembler a;
5496 int i, j, nblocks;
5497 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 /* Make sure every block that falls off the end returns None.
5500 XXX NEXT_BLOCK() isn't quite right, because if the last
5501 block ends with a jump or return b_next shouldn't set.
5502 */
5503 if (!c->u->u_curblock->b_return) {
5504 NEXT_BLOCK(c);
5505 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005506 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 ADDOP(c, RETURN_VALUE);
5508 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 nblocks = 0;
5511 entryblock = NULL;
5512 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5513 nblocks++;
5514 entryblock = b;
5515 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 /* Set firstlineno if it wasn't explicitly set. */
5518 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005519 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5521 else
5522 c->u->u_firstlineno = 1;
5523 }
5524 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5525 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005526 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 /* Can't modify the bytecode after computing jump offsets. */
5529 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 /* Emit code in reverse postorder from dfs. */
5532 for (i = a.a_nblocks - 1; i >= 0; i--) {
5533 b = a.a_postorder[i];
5534 for (j = 0; j < b->b_iused; j++)
5535 if (!assemble_emit(&a, &b->b_instr[j]))
5536 goto error;
5537 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5540 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005541 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005545 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 assemble_free(&a);
5547 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005548}
Georg Brandl8334fd92010-12-04 10:26:46 +00005549
5550#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005551PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005552PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5553 PyArena *arena)
5554{
5555 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5556}