blob: c3ffaae8ce206201b3d731df77f6bbe8f8b088f8 [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);
174static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100175static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_error(struct compiler *, const char *);
178static 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);
Victor Stinnerefb24132016-01-22 12:33:12 +0100410 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
412 Py_XDECREF(k);
413 Py_DECREF(v);
414 Py_DECREF(dict);
415 return NULL;
416 }
417 Py_DECREF(k);
418 Py_DECREF(v);
419 }
420 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421}
422
423/* Return new dict containing names from src that match scope(s).
424
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000425src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000427values are integers, starting at offset and increasing by one for
428each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429*/
430
431static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100432dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700434 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500436 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 assert(offset >= 0);
439 if (dest == NULL)
440 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441
Meador Inge2ca63152012-07-18 14:20:11 -0500442 /* Sort the keys so that we have a deterministic order on the indexes
443 saved in the returned dictionary. These indexes are used as indexes
444 into the free and cell var storage. Therefore if they aren't
445 deterministic, then the generated bytecode is not deterministic.
446 */
447 sorted_keys = PyDict_Keys(src);
448 if (sorted_keys == NULL)
449 return NULL;
450 if (PyList_Sort(sorted_keys) != 0) {
451 Py_DECREF(sorted_keys);
452 return NULL;
453 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500454 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500455
456 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* XXX this should probably be a macro in symtable.h */
458 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500459 k = PyList_GET_ITEM(sorted_keys, key_i);
460 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 assert(PyLong_Check(v));
462 vi = PyLong_AS_LONG(v);
463 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100466 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500468 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_DECREF(dest);
470 return NULL;
471 }
472 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100473 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500475 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(item);
477 Py_DECREF(dest);
478 Py_XDECREF(tuple);
479 return NULL;
480 }
481 Py_DECREF(item);
482 Py_DECREF(tuple);
483 }
484 }
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000487}
488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000489static void
490compiler_unit_check(struct compiler_unit *u)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 basicblock *block;
493 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700494 assert((uintptr_t)block != 0xcbcbcbcbU);
495 assert((uintptr_t)block != 0xfbfbfbfbU);
496 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (block->b_instr != NULL) {
498 assert(block->b_ialloc > 0);
499 assert(block->b_iused > 0);
500 assert(block->b_ialloc >= block->b_iused);
501 }
502 else {
503 assert (block->b_iused == 0);
504 assert (block->b_ialloc == 0);
505 }
506 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507}
508
509static void
510compiler_unit_free(struct compiler_unit *u)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 compiler_unit_check(u);
515 b = u->u_blocks;
516 while (b != NULL) {
517 if (b->b_instr)
518 PyObject_Free((void *)b->b_instr);
519 next = b->b_list;
520 PyObject_Free((void *)b);
521 b = next;
522 }
523 Py_CLEAR(u->u_ste);
524 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400525 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 Py_CLEAR(u->u_consts);
527 Py_CLEAR(u->u_names);
528 Py_CLEAR(u->u_varnames);
529 Py_CLEAR(u->u_freevars);
530 Py_CLEAR(u->u_cellvars);
531 Py_CLEAR(u->u_private);
532 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533}
534
535static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100536compiler_enter_scope(struct compiler *c, identifier name,
537 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100540 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
543 struct compiler_unit));
544 if (!u) {
545 PyErr_NoMemory();
546 return 0;
547 }
548 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100549 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 u->u_argcount = 0;
551 u->u_kwonlyargcount = 0;
552 u->u_ste = PySymtable_Lookup(c->c_st, key);
553 if (!u->u_ste) {
554 compiler_unit_free(u);
555 return 0;
556 }
557 Py_INCREF(name);
558 u->u_name = name;
559 u->u_varnames = list2dict(u->u_ste->ste_varnames);
560 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
561 if (!u->u_varnames || !u->u_cellvars) {
562 compiler_unit_free(u);
563 return 0;
564 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000566 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500567 _Py_IDENTIFIER(__class__);
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300568 PyObject *tuple, *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 int res;
570 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200571 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 name = _PyUnicode_FromId(&PyId___class__);
573 if (!name) {
574 compiler_unit_free(u);
575 return 0;
576 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100577 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500578 if (!tuple) {
579 compiler_unit_free(u);
580 return 0;
581 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300582 res = PyDict_SetItem(u->u_cellvars, tuple, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500583 Py_DECREF(tuple);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 if (res < 0) {
585 compiler_unit_free(u);
586 return 0;
587 }
588 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200591 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (!u->u_freevars) {
593 compiler_unit_free(u);
594 return 0;
595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 u->u_blocks = NULL;
598 u->u_nfblocks = 0;
599 u->u_firstlineno = lineno;
600 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000601 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 u->u_lineno_set = 0;
603 u->u_consts = PyDict_New();
604 if (!u->u_consts) {
605 compiler_unit_free(u);
606 return 0;
607 }
608 u->u_names = PyDict_New();
609 if (!u->u_names) {
610 compiler_unit_free(u);
611 return 0;
612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Push the old compiler_unit on the stack. */
617 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400618 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
620 Py_XDECREF(capsule);
621 compiler_unit_free(u);
622 return 0;
623 }
624 Py_DECREF(capsule);
625 u->u_private = c->u->u_private;
626 Py_XINCREF(u->u_private);
627 }
628 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631
632 block = compiler_new_block(c);
633 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100635 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400637 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
638 if (!compiler_set_qualname(c))
639 return 0;
640 }
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643}
644
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000645static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646compiler_exit_scope(struct compiler *c)
647{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100648 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c->c_nestlevel--;
652 compiler_unit_free(c->u);
653 /* Restore c->u to the parent unit. */
654 n = PyList_GET_SIZE(c->c_stack) - 1;
655 if (n >= 0) {
656 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400657 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 assert(c->u);
659 /* we are deleting from a list so this really shouldn't fail */
660 if (PySequence_DelItem(c->c_stack, n) < 0)
661 Py_FatalError("compiler_exit_scope()");
662 compiler_unit_check(c->u);
663 }
664 else
665 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667}
668
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669static int
670compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100672 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 _Py_static_string(dot_locals, ".<locals>");
674 Py_ssize_t stack_size;
675 struct compiler_unit *u = c->u;
676 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400680 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 if (stack_size > 1) {
682 int scope, force_global = 0;
683 struct compiler_unit *parent;
684 PyObject *mangled, *capsule;
685
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400686 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400687 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400688 assert(parent);
689
Yury Selivanov75445082015-05-11 22:57:16 -0400690 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
691 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
692 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400693 assert(u->u_name);
694 mangled = _Py_Mangle(parent->u_private, u->u_name);
695 if (!mangled)
696 return 0;
697 scope = PyST_GetScope(parent->u_ste, mangled);
698 Py_DECREF(mangled);
699 assert(scope != GLOBAL_IMPLICIT);
700 if (scope == GLOBAL_EXPLICIT)
701 force_global = 1;
702 }
703
704 if (!force_global) {
705 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400706 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400707 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
708 dot_locals_str = _PyUnicode_FromId(&dot_locals);
709 if (dot_locals_str == NULL)
710 return 0;
711 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
712 if (base == NULL)
713 return 0;
714 }
715 else {
716 Py_INCREF(parent->u_qualname);
717 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100719 }
720 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400721
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400722 if (base != NULL) {
723 dot_str = _PyUnicode_FromId(&dot);
724 if (dot_str == NULL) {
725 Py_DECREF(base);
726 return 0;
727 }
728 name = PyUnicode_Concat(base, dot_str);
729 Py_DECREF(base);
730 if (name == NULL)
731 return 0;
732 PyUnicode_Append(&name, u->u_name);
733 if (name == NULL)
734 return 0;
735 }
736 else {
737 Py_INCREF(u->u_name);
738 name = u->u_name;
739 }
740 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400742 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100743}
744
Eric V. Smith235a6f02015-09-19 14:51:32 -0400745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000746/* Allocate a new block and return a pointer to it.
747 Returns NULL on error.
748*/
749
750static basicblock *
751compiler_new_block(struct compiler *c)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 basicblock *b;
754 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 u = c->u;
757 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
758 if (b == NULL) {
759 PyErr_NoMemory();
760 return NULL;
761 }
762 memset((void *)b, 0, sizeof(basicblock));
763 /* Extend the singly linked list of blocks with new block. */
764 b->b_list = u->u_blocks;
765 u->u_blocks = b;
766 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767}
768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770compiler_next_block(struct compiler *c)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 basicblock *block = compiler_new_block(c);
773 if (block == NULL)
774 return NULL;
775 c->u->u_curblock->b_next = block;
776 c->u->u_curblock = block;
777 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778}
779
780static basicblock *
781compiler_use_next_block(struct compiler *c, basicblock *block)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 assert(block != NULL);
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789/* Returns the offset of the next instruction in the current block's
790 b_instr array. Resizes the b_instr as necessary.
791 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793
794static int
795compiler_next_instr(struct compiler *c, basicblock *b)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 assert(b != NULL);
798 if (b->b_instr == NULL) {
799 b->b_instr = (struct instr *)PyObject_Malloc(
800 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
801 if (b->b_instr == NULL) {
802 PyErr_NoMemory();
803 return -1;
804 }
805 b->b_ialloc = DEFAULT_BLOCK_SIZE;
806 memset((char *)b->b_instr, 0,
807 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
808 }
809 else if (b->b_iused == b->b_ialloc) {
810 struct instr *tmp;
811 size_t oldsize, newsize;
812 oldsize = b->b_ialloc * sizeof(struct instr);
813 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000814
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700815 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyErr_NoMemory();
817 return -1;
818 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (newsize == 0) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 b->b_ialloc <<= 1;
825 tmp = (struct instr *)PyObject_Realloc(
826 (void *)b->b_instr, newsize);
827 if (tmp == NULL) {
828 PyErr_NoMemory();
829 return -1;
830 }
831 b->b_instr = tmp;
832 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
833 }
834 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835}
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837/* Set the i_lineno member of the instruction at offset off if the
838 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 already been set. If it has been set, the call has no effect.
840
Christian Heimes2202f872008-02-06 14:31:34 +0000841 The line number is reset in the following cases:
842 - when entering a new scope
843 - on each statement
844 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200845 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000846 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849static void
850compiler_set_lineno(struct compiler *c, int off)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 basicblock *b;
853 if (c->u->u_lineno_set)
854 return;
855 c->u->u_lineno_set = 1;
856 b = c->u->u_curblock;
857 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858}
859
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200860/* Return the stack effect of opcode with argument oparg.
861
862 Some opcodes have different stack effect when jump to the target and
863 when not jump. The 'jump' parameter specifies the case:
864
865 * 0 -- when not jump
866 * 1 -- when jump
867 * -1 -- maximal
868 */
869/* XXX Make the stack effect of WITH_CLEANUP_START and
870 WITH_CLEANUP_FINISH deterministic. */
871static int
872stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 switch (opcode) {
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200875 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case POP_TOP:
877 return -1;
878 case ROT_TWO:
879 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200880 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return 0;
882 case DUP_TOP:
883 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000884 case DUP_TOP_TWO:
885 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000886
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200887 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case UNARY_POSITIVE:
889 case UNARY_NEGATIVE:
890 case UNARY_NOT:
891 case UNARY_INVERT:
892 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case SET_ADD:
895 case LIST_APPEND:
896 return -1;
897 case MAP_ADD:
898 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000899
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case BINARY_POWER:
902 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400903 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case BINARY_MODULO:
905 case BINARY_ADD:
906 case BINARY_SUBTRACT:
907 case BINARY_SUBSCR:
908 case BINARY_FLOOR_DIVIDE:
909 case BINARY_TRUE_DIVIDE:
910 return -1;
911 case INPLACE_FLOOR_DIVIDE:
912 case INPLACE_TRUE_DIVIDE:
913 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case INPLACE_ADD:
916 case INPLACE_SUBTRACT:
917 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400918 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case INPLACE_MODULO:
920 return -1;
921 case STORE_SUBSCR:
922 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 case DELETE_SUBSCR:
924 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 case BINARY_LSHIFT:
927 case BINARY_RSHIFT:
928 case BINARY_AND:
929 case BINARY_XOR:
930 case BINARY_OR:
931 return -1;
932 case INPLACE_POWER:
933 return -1;
934 case GET_ITER:
935 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case PRINT_EXPR:
938 return -1;
939 case LOAD_BUILD_CLASS:
940 return 1;
941 case INPLACE_LSHIFT:
942 case INPLACE_RSHIFT:
943 case INPLACE_AND:
944 case INPLACE_XOR:
945 case INPLACE_OR:
946 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200949 /* 1 in the normal flow.
950 * Restore the stack position and push 6 values before jumping to
951 * the handler if an exception be raised. */
952 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400953 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200954 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400955 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200956 /* Pop a variable number of values pushed by WITH_CLEANUP_START
957 * + __exit__ or __aexit__. */
958 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case RETURN_VALUE:
960 return -1;
961 case IMPORT_STAR:
962 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700963 case SETUP_ANNOTATIONS:
964 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case YIELD_VALUE:
966 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500967 case YIELD_FROM:
968 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case POP_BLOCK:
970 return 0;
971 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200972 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200974 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200975 /* Pop 6 values when an exception was raised. */
976 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case STORE_NAME:
979 return -1;
980 case DELETE_NAME:
981 return 0;
982 case UNPACK_SEQUENCE:
983 return oparg-1;
984 case UNPACK_EX:
985 return (oparg&0xFF) + (oparg>>8);
986 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200987 /* -1 at end of iterator, 1 if continue iterating. */
988 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case STORE_ATTR:
991 return -2;
992 case DELETE_ATTR:
993 return -1;
994 case STORE_GLOBAL:
995 return -1;
996 case DELETE_GLOBAL:
997 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case LOAD_CONST:
999 return 1;
1000 case LOAD_NAME:
1001 return 1;
1002 case BUILD_TUPLE:
1003 case BUILD_LIST:
1004 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001005 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001007 case BUILD_LIST_UNPACK:
1008 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001009 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001010 case BUILD_SET_UNPACK:
1011 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001012 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001013 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001015 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001016 case BUILD_CONST_KEY_MAP:
1017 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case LOAD_ATTR:
1019 return 0;
1020 case COMPARE_OP:
1021 return -1;
1022 case IMPORT_NAME:
1023 return -1;
1024 case IMPORT_FROM:
1025 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001027 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case JUMP_ABSOLUTE:
1030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001032 case JUMP_IF_TRUE_OR_POP:
1033 case JUMP_IF_FALSE_OR_POP:
1034 return jump ? 0 : -1;
1035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case POP_JUMP_IF_FALSE:
1037 case POP_JUMP_IF_TRUE:
1038 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case LOAD_GLOBAL:
1041 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001043 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001045 /* 0 in the normal flow.
1046 * Restore the stack position and push 6 values before jumping to
1047 * the handler if an exception be raised. */
1048 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001049 case BEGIN_FINALLY:
1050 /* Actually pushes 1 value, but count 6 for balancing with
1051 * END_FINALLY and POP_FINALLY.
1052 * This is the main reason of using this opcode instead of
1053 * "LOAD_CONST None". */
1054 return 6;
1055 case CALL_FINALLY:
1056 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_FAST:
1059 return 1;
1060 case STORE_FAST:
1061 return -1;
1062 case DELETE_FAST:
1063 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case RAISE_VARARGS:
1066 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001067
1068 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001070 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001071 case CALL_METHOD:
1072 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg-1;
1075 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001076 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001077 case MAKE_FUNCTION:
1078 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1079 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 case BUILD_SLICE:
1081 if (oparg == 3)
1082 return -2;
1083 else
1084 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001086 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case LOAD_CLOSURE:
1088 return 1;
1089 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001090 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 return 1;
1092 case STORE_DEREF:
1093 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001094 case DELETE_DEREF:
1095 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096
1097 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001098 case GET_AWAITABLE:
1099 return 0;
1100 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001101 /* 0 in the normal flow.
1102 * Restore the stack position to the position before the result
1103 * of __aenter__ and push 6 values before jumping to the handler
1104 * if an exception be raised. */
1105 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001106 case BEFORE_ASYNC_WITH:
1107 return 1;
1108 case GET_AITER:
1109 return 0;
1110 case GET_ANEXT:
1111 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001112 case GET_YIELD_FROM_ITER:
1113 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001114 case FORMAT_VALUE:
1115 /* If there's a fmt_spec on the stack, we go from 2->1,
1116 else 1->1. */
1117 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001118 case LOAD_METHOD:
1119 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001121 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 }
Larry Hastings3a907972013-11-23 14:49:22 -08001123 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124}
1125
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001126int
1127PyCompile_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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *t, *v;
1160 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161
Victor Stinnerefb24132016-01-22 12:33:12 +01001162 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (t == NULL)
1164 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 v = PyDict_GetItem(dict, t);
1167 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001168 if (PyErr_Occurred()) {
1169 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001171 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001172 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001173 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (!v) {
1175 Py_DECREF(t);
1176 return -1;
1177 }
1178 if (PyDict_SetItem(dict, t, v) < 0) {
1179 Py_DECREF(t);
1180 Py_DECREF(v);
1181 return -1;
1182 }
1183 Py_DECREF(v);
1184 }
1185 else
1186 arg = PyLong_AsLong(v);
1187 Py_DECREF(t);
1188 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189}
1190
1191static int
1192compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001195 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001197 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 return compiler_addop_i(c, opcode, arg);
1199}
1200
1201static int
1202compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001205 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1207 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001208 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 arg = compiler_add_o(c, dict, mangled);
1210 Py_DECREF(mangled);
1211 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 return compiler_addop_i(c, opcode, arg);
1214}
1215
1216/* Add an opcode with an integer argument.
1217 Returns 0 on failure, 1 on success.
1218*/
1219
1220static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001221compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 struct instr *i;
1224 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001225
Victor Stinner2ad474b2016-03-01 23:34:47 +01001226 /* oparg value is unsigned, but a signed C int is usually used to store
1227 it in the C code (like Python/ceval.c).
1228
1229 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1230
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001231 The argument of a concrete bytecode instruction is limited to 8-bit.
1232 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1233 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001234 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 off = compiler_next_instr(c, c->u->u_curblock);
1237 if (off < 0)
1238 return 0;
1239 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001240 i->i_opcode = opcode;
1241 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 compiler_set_lineno(c, off);
1243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244}
1245
1246static int
1247compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 struct instr *i;
1250 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001252 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 assert(b != NULL);
1254 off = compiler_next_instr(c, c->u->u_curblock);
1255 if (off < 0)
1256 return 0;
1257 i = &c->u->u_curblock->b_instr[off];
1258 i->i_opcode = opcode;
1259 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (absolute)
1261 i->i_jabs = 1;
1262 else
1263 i->i_jrel = 1;
1264 compiler_set_lineno(c, off);
1265 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001268/* NEXT_BLOCK() creates an implicit jump from the current block
1269 to the new block.
1270
1271 The returns inside this macro make it impossible to decref objects
1272 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (compiler_next_block((C)) == NULL) \
1276 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (!compiler_addop((C), (OP))) \
1281 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001284#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_addop((C), (OP))) { \
1286 compiler_exit_scope(c); \
1287 return 0; \
1288 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001289}
1290
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1293 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294}
1295
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001296/* Same as ADDOP_O, but steals a reference. */
1297#define ADDOP_N(C, OP, O, TYPE) { \
1298 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1299 Py_DECREF((O)); \
1300 return 0; \
1301 } \
1302 Py_DECREF((O)); \
1303}
1304
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1307 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308}
1309
1310#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (!compiler_addop_i((C), (OP), (O))) \
1312 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
1315#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (!compiler_addop_j((C), (OP), (O), 1)) \
1317 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318}
1319
1320#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!compiler_addop_j((C), (OP), (O), 0)) \
1322 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323}
1324
1325/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1326 the ASDL name to synthesize the name of the C type and the visit function.
1327*/
1328
1329#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (!compiler_visit_ ## TYPE((C), (V))) \
1331 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332}
1333
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001334#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (!compiler_visit_ ## TYPE((C), (V))) { \
1336 compiler_exit_scope(c); \
1337 return 0; \
1338 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001339}
1340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (!compiler_visit_slice((C), (V), (CTX))) \
1343 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344}
1345
1346#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 int _i; \
1348 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1349 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1350 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1351 if (!compiler_visit_ ## TYPE((C), elt)) \
1352 return 0; \
1353 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354}
1355
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001356#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 int _i; \
1358 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1359 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1360 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1361 if (!compiler_visit_ ## TYPE((C), elt)) { \
1362 compiler_exit_scope(c); \
1363 return 0; \
1364 } \
1365 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001366}
1367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001369is_const(expr_ty e)
1370{
1371 switch (e->kind) {
1372 case Constant_kind:
1373 case Num_kind:
1374 case Str_kind:
1375 case Bytes_kind:
1376 case Ellipsis_kind:
1377 case NameConstant_kind:
1378 return 1;
1379 default:
1380 return 0;
1381 }
1382}
1383
1384static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001385get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001386{
1387 switch (e->kind) {
1388 case Constant_kind:
1389 return e->v.Constant.value;
1390 case Num_kind:
1391 return e->v.Num.n;
1392 case Str_kind:
1393 return e->v.Str.s;
1394 case Bytes_kind:
1395 return e->v.Bytes.s;
1396 case Ellipsis_kind:
1397 return Py_Ellipsis;
1398 case NameConstant_kind:
1399 return e->v.NameConstant.value;
1400 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001401 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001402 }
1403}
1404
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001405/* Search if variable annotations are present statically in a block. */
1406
1407static int
1408find_ann(asdl_seq *stmts)
1409{
1410 int i, j, res = 0;
1411 stmt_ty st;
1412
1413 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1414 st = (stmt_ty)asdl_seq_GET(stmts, i);
1415 switch (st->kind) {
1416 case AnnAssign_kind:
1417 return 1;
1418 case For_kind:
1419 res = find_ann(st->v.For.body) ||
1420 find_ann(st->v.For.orelse);
1421 break;
1422 case AsyncFor_kind:
1423 res = find_ann(st->v.AsyncFor.body) ||
1424 find_ann(st->v.AsyncFor.orelse);
1425 break;
1426 case While_kind:
1427 res = find_ann(st->v.While.body) ||
1428 find_ann(st->v.While.orelse);
1429 break;
1430 case If_kind:
1431 res = find_ann(st->v.If.body) ||
1432 find_ann(st->v.If.orelse);
1433 break;
1434 case With_kind:
1435 res = find_ann(st->v.With.body);
1436 break;
1437 case AsyncWith_kind:
1438 res = find_ann(st->v.AsyncWith.body);
1439 break;
1440 case Try_kind:
1441 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1442 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1443 st->v.Try.handlers, j);
1444 if (find_ann(handler->v.ExceptHandler.body)) {
1445 return 1;
1446 }
1447 }
1448 res = find_ann(st->v.Try.body) ||
1449 find_ann(st->v.Try.finalbody) ||
1450 find_ann(st->v.Try.orelse);
1451 break;
1452 default:
1453 res = 0;
1454 }
1455 if (res) {
1456 break;
1457 }
1458 }
1459 return res;
1460}
1461
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001462/*
1463 * Frame block handling functions
1464 */
1465
1466static int
1467compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1468 basicblock *exit)
1469{
1470 struct fblockinfo *f;
1471 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1472 PyErr_SetString(PyExc_SyntaxError,
1473 "too many statically nested blocks");
1474 return 0;
1475 }
1476 f = &c->u->u_fblock[c->u->u_nfblocks++];
1477 f->fb_type = t;
1478 f->fb_block = b;
1479 f->fb_exit = exit;
1480 return 1;
1481}
1482
1483static void
1484compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1485{
1486 struct compiler_unit *u = c->u;
1487 assert(u->u_nfblocks > 0);
1488 u->u_nfblocks--;
1489 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1490 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1491}
1492
1493/* Unwind a frame block. If preserve_tos is true, the TOS before
1494 * popping the blocks will be restored afterwards.
1495 */
1496static int
1497compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1498 int preserve_tos)
1499{
1500 switch (info->fb_type) {
1501 case WHILE_LOOP:
1502 return 1;
1503
1504 case FINALLY_END:
1505 ADDOP_I(c, POP_FINALLY, preserve_tos);
1506 return 1;
1507
1508 case FOR_LOOP:
1509 /* Pop the iterator */
1510 if (preserve_tos) {
1511 ADDOP(c, ROT_TWO);
1512 }
1513 ADDOP(c, POP_TOP);
1514 return 1;
1515
1516 case EXCEPT:
1517 ADDOP(c, POP_BLOCK);
1518 return 1;
1519
1520 case FINALLY_TRY:
1521 ADDOP(c, POP_BLOCK);
1522 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1523 return 1;
1524
1525 case WITH:
1526 case ASYNC_WITH:
1527 ADDOP(c, POP_BLOCK);
1528 if (preserve_tos) {
1529 ADDOP(c, ROT_TWO);
1530 }
1531 ADDOP(c, BEGIN_FINALLY);
1532 ADDOP(c, WITH_CLEANUP_START);
1533 if (info->fb_type == ASYNC_WITH) {
1534 ADDOP(c, GET_AWAITABLE);
1535 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1536 ADDOP(c, YIELD_FROM);
1537 }
1538 ADDOP(c, WITH_CLEANUP_FINISH);
1539 ADDOP_I(c, POP_FINALLY, 0);
1540 return 1;
1541
1542 case HANDLER_CLEANUP:
1543 if (preserve_tos) {
1544 ADDOP(c, ROT_FOUR);
1545 }
1546 if (info->fb_exit) {
1547 ADDOP(c, POP_BLOCK);
1548 ADDOP(c, POP_EXCEPT);
1549 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1550 }
1551 else {
1552 ADDOP(c, POP_EXCEPT);
1553 }
1554 return 1;
1555 }
1556 Py_UNREACHABLE();
1557}
1558
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001559/* Compile a sequence of statements, checking for a docstring
1560 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561
1562static int
INADA Naokicb41b272017-02-23 00:31:59 +09001563compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001564{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001565 /* Set current line number to the line number of first statement.
1566 This way line number for SETUP_ANNOTATIONS will always
1567 coincide with the line number of first "real" statement in module.
1568 If body is empy, then lineno will be set later in assemble. */
1569 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1570 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001571 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001572 c->u->u_lineno = st->lineno;
1573 }
1574 /* Every annotated class and module should have __annotations__. */
1575 if (find_ann(stmts)) {
1576 ADDOP(c, SETUP_ANNOTATIONS);
1577 }
INADA Naokicb41b272017-02-23 00:31:59 +09001578 /* if not -OO mode, set docstring */
1579 if (c->c_optimize < 2 && docstring) {
1580 ADDOP_O(c, LOAD_CONST, docstring, consts);
1581 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 }
INADA Naokicb41b272017-02-23 00:31:59 +09001583 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001585}
1586
1587static PyCodeObject *
1588compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 PyCodeObject *co;
1591 int addNone = 1;
1592 static PyObject *module;
1593 if (!module) {
1594 module = PyUnicode_InternFromString("<module>");
1595 if (!module)
1596 return NULL;
1597 }
1598 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001599 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return NULL;
1601 switch (mod->kind) {
1602 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001603 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 compiler_exit_scope(c);
1605 return 0;
1606 }
1607 break;
1608 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001609 if (find_ann(mod->v.Interactive.body)) {
1610 ADDOP(c, SETUP_ANNOTATIONS);
1611 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 c->c_interactive = 1;
1613 VISIT_SEQ_IN_SCOPE(c, stmt,
1614 mod->v.Interactive.body);
1615 break;
1616 case Expression_kind:
1617 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1618 addNone = 0;
1619 break;
1620 case Suite_kind:
1621 PyErr_SetString(PyExc_SystemError,
1622 "suite should not be possible");
1623 return 0;
1624 default:
1625 PyErr_Format(PyExc_SystemError,
1626 "module kind %d should not be possible",
1627 mod->kind);
1628 return 0;
1629 }
1630 co = assemble(c, addNone);
1631 compiler_exit_scope(c);
1632 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001633}
1634
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635/* The test for LOCAL must come before the test for FREE in order to
1636 handle classes where name is both local and free. The local var is
1637 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001638*/
1639
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640static int
1641get_ref_type(struct compiler *c, PyObject *name)
1642{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001643 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001644 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001645 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001646 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001647 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (scope == 0) {
1649 char buf[350];
1650 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001651 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001653 PyUnicode_AsUTF8(name),
1654 PyUnicode_AsUTF8(c->u->u_name),
1655 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1656 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1657 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1658 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 );
1660 Py_FatalError(buf);
1661 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001664}
1665
1666static int
1667compiler_lookup_arg(PyObject *dict, PyObject *name)
1668{
1669 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001670 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001672 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001674 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001676 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001677 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678}
1679
1680static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001681compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001683 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001684 if (qualname == NULL)
1685 qualname = co->co_name;
1686
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001687 if (free) {
1688 for (i = 0; i < free; ++i) {
1689 /* Bypass com_addop_varname because it will generate
1690 LOAD_DEREF but LOAD_CLOSURE is needed.
1691 */
1692 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1693 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001695 /* Special case: If a class contains a method with a
1696 free variable that has the same name as a method,
1697 the name will be considered free *and* local in the
1698 class. It should be handled by the closure, as
1699 well as by the normal name loookup logic.
1700 */
1701 reftype = get_ref_type(c, name);
1702 if (reftype == CELL)
1703 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1704 else /* (reftype == FREE) */
1705 arg = compiler_lookup_arg(c->u->u_freevars, name);
1706 if (arg == -1) {
1707 fprintf(stderr,
1708 "lookup %s in %s %d %d\n"
1709 "freevars of %s: %s\n",
1710 PyUnicode_AsUTF8(PyObject_Repr(name)),
1711 PyUnicode_AsUTF8(c->u->u_name),
1712 reftype, arg,
1713 PyUnicode_AsUTF8(co->co_name),
1714 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1715 Py_FatalError("compiler_make_closure()");
1716 }
1717 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001719 flags |= 0x08;
1720 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001723 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001724 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726}
1727
1728static int
1729compiler_decorators(struct compiler *c, asdl_seq* decos)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (!decos)
1734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1737 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1738 }
1739 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001740}
1741
1742static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001743compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001745{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001746 /* Push a dict of keyword-only default values.
1747
1748 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1749 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001750 int i;
1751 PyObject *keys = NULL;
1752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1754 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1755 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1756 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001757 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001758 if (!mangled) {
1759 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001761 if (keys == NULL) {
1762 keys = PyList_New(1);
1763 if (keys == NULL) {
1764 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001765 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001766 }
1767 PyList_SET_ITEM(keys, 0, mangled);
1768 }
1769 else {
1770 int res = PyList_Append(keys, mangled);
1771 Py_DECREF(mangled);
1772 if (res == -1) {
1773 goto error;
1774 }
1775 }
1776 if (!compiler_visit_expr(c, default_)) {
1777 goto error;
1778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 }
1780 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001781 if (keys != NULL) {
1782 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1783 PyObject *keys_tuple = PyList_AsTuple(keys);
1784 Py_DECREF(keys);
1785 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001786 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001787 }
1788 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1789 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001790 assert(default_count > 0);
1791 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001792 }
1793 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001794 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001795 }
1796
1797error:
1798 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001799 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001800}
1801
1802static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001803compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1804{
1805 PyObject *ann_as_str;
1806 ann_as_str = _PyAST_ExprAsUnicode(annotation, 1);
1807 if (!ann_as_str) {
1808 return 0;
1809 }
1810 ADDOP_N(c, LOAD_CONST, ann_as_str, consts);
1811 return 1;
1812}
1813
1814static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001815compiler_visit_argannotation(struct compiler *c, identifier id,
1816 expr_ty annotation, PyObject *names)
1817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001819 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001820 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1821 VISIT(c, annexpr, annotation)
1822 }
1823 else {
1824 VISIT(c, expr, annotation);
1825 }
Victor Stinner065efc32014-02-18 22:07:56 +01001826 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001827 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001828 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001829 if (PyList_Append(names, mangled) < 0) {
1830 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001831 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001832 }
1833 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001835 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001836}
1837
1838static int
1839compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1840 PyObject *names)
1841{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001842 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 for (i = 0; i < asdl_seq_LEN(args); i++) {
1844 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001845 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 c,
1847 arg->arg,
1848 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001849 names))
1850 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001852 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001853}
1854
1855static int
1856compiler_visit_annotations(struct compiler *c, arguments_ty args,
1857 expr_ty returns)
1858{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001859 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001860 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001861
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001862 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 */
1864 static identifier return_str;
1865 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001866 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 names = PyList_New(0);
1868 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001869 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001870
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001871 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001873 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001874 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001875 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001877 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001879 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001880 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001881 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (!return_str) {
1885 return_str = PyUnicode_InternFromString("return");
1886 if (!return_str)
1887 goto error;
1888 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001889 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 goto error;
1891 }
1892
1893 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001895 PyObject *keytuple = PyList_AsTuple(names);
1896 Py_DECREF(names);
1897 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001898 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001900 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1901 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001902 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001904 else {
1905 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001906 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001907 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001908
1909error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001911 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001912}
1913
1914static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001915compiler_visit_defaults(struct compiler *c, arguments_ty args)
1916{
1917 VISIT_SEQ(c, expr, args->defaults);
1918 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1919 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920}
1921
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922static Py_ssize_t
1923compiler_default_arguments(struct compiler *c, arguments_ty args)
1924{
1925 Py_ssize_t funcflags = 0;
1926 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001927 if (!compiler_visit_defaults(c, args))
1928 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001929 funcflags |= 0x01;
1930 }
1931 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001932 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001933 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001934 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001935 return -1;
1936 }
1937 else if (res > 0) {
1938 funcflags |= 0x02;
1939 }
1940 }
1941 return funcflags;
1942}
1943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944static int
Yury Selivanov75445082015-05-11 22:57:16 -04001945compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001948 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001949 arguments_ty args;
1950 expr_ty returns;
1951 identifier name;
1952 asdl_seq* decos;
1953 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001954 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001955 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001956 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Yury Selivanov75445082015-05-11 22:57:16 -04001958 if (is_async) {
1959 assert(s->kind == AsyncFunctionDef_kind);
1960
1961 args = s->v.AsyncFunctionDef.args;
1962 returns = s->v.AsyncFunctionDef.returns;
1963 decos = s->v.AsyncFunctionDef.decorator_list;
1964 name = s->v.AsyncFunctionDef.name;
1965 body = s->v.AsyncFunctionDef.body;
1966
1967 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1968 } else {
1969 assert(s->kind == FunctionDef_kind);
1970
1971 args = s->v.FunctionDef.args;
1972 returns = s->v.FunctionDef.returns;
1973 decos = s->v.FunctionDef.decorator_list;
1974 name = s->v.FunctionDef.name;
1975 body = s->v.FunctionDef.body;
1976
1977 scope_type = COMPILER_SCOPE_FUNCTION;
1978 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (!compiler_decorators(c, decos))
1981 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001982
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001983 funcflags = compiler_default_arguments(c, args);
1984 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 }
1987
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001988 annotations = compiler_visit_annotations(c, args, returns);
1989 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 return 0;
1991 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001992 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001993 funcflags |= 0x04;
1994 }
1995
1996 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1997 return 0;
1998 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999
INADA Naokicb41b272017-02-23 00:31:59 +09002000 /* if not -OO mode, add docstring */
2001 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
2002 docstring = s->v.FunctionDef.docstring;
2003 if (compiler_add_o(c, c->u->u_consts, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 compiler_exit_scope(c);
2005 return 0;
2006 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 c->u->u_argcount = asdl_seq_LEN(args->args);
2009 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09002011 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002013 qualname = c->u->u_qualname;
2014 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002016 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002017 Py_XDECREF(qualname);
2018 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002020 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002022 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002023 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 /* decorators */
2027 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2028 ADDOP_I(c, CALL_FUNCTION, 1);
2029 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030
Yury Selivanov75445082015-05-11 22:57:16 -04002031 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032}
2033
2034static int
2035compiler_class(struct compiler *c, stmt_ty s)
2036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 PyCodeObject *co;
2038 PyObject *str;
2039 int i;
2040 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (!compiler_decorators(c, decos))
2043 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 /* ultimately generate code for:
2046 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2047 where:
2048 <func> is a function/closure created from the class body;
2049 it has a single argument (__locals__) where the dict
2050 (or MutableSequence) representing the locals is passed
2051 <name> is the class name
2052 <bases> is the positional arguments and *varargs argument
2053 <keywords> is the keyword arguments and **kwds argument
2054 This borrows from compiler_call.
2055 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002058 if (!compiler_enter_scope(c, s->v.ClassDef.name,
2059 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 return 0;
2061 /* this block represents what we do in the new scope */
2062 {
2063 /* use the class name for name mangling */
2064 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002065 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* load (global) __name__ ... */
2067 str = PyUnicode_InternFromString("__name__");
2068 if (!str || !compiler_nameop(c, str, Load)) {
2069 Py_XDECREF(str);
2070 compiler_exit_scope(c);
2071 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002072 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 Py_DECREF(str);
2074 /* ... and store it as __module__ */
2075 str = PyUnicode_InternFromString("__module__");
2076 if (!str || !compiler_nameop(c, str, Store)) {
2077 Py_XDECREF(str);
2078 compiler_exit_scope(c);
2079 return 0;
2080 }
2081 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002082 assert(c->u->u_qualname);
2083 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002084 str = PyUnicode_InternFromString("__qualname__");
2085 if (!str || !compiler_nameop(c, str, Store)) {
2086 Py_XDECREF(str);
2087 compiler_exit_scope(c);
2088 return 0;
2089 }
2090 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09002092 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 compiler_exit_scope(c);
2094 return 0;
2095 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002096 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002097 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002098 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002099 str = PyUnicode_InternFromString("__class__");
2100 if (str == NULL) {
2101 compiler_exit_scope(c);
2102 return 0;
2103 }
2104 i = compiler_lookup_arg(c->u->u_cellvars, str);
2105 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002106 if (i < 0) {
2107 compiler_exit_scope(c);
2108 return 0;
2109 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002110 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002113 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002114 str = PyUnicode_InternFromString("__classcell__");
2115 if (!str || !compiler_nameop(c, str, Store)) {
2116 Py_XDECREF(str);
2117 compiler_exit_scope(c);
2118 return 0;
2119 }
2120 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002122 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002123 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002124 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10002125 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002126 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002127 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* create the code object */
2129 co = assemble(c, 1);
2130 }
2131 /* leave the new scope */
2132 compiler_exit_scope(c);
2133 if (co == NULL)
2134 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* 2. load the 'build_class' function */
2137 ADDOP(c, LOAD_BUILD_CLASS);
2138
2139 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002140 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 Py_DECREF(co);
2142
2143 /* 4. load class name */
2144 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2145
2146 /* 5. generate the rest of the code for the call */
2147 if (!compiler_call_helper(c, 2,
2148 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002149 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 return 0;
2151
2152 /* 6. apply decorators */
2153 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2154 ADDOP_I(c, CALL_FUNCTION, 1);
2155 }
2156
2157 /* 7. store into <name> */
2158 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2159 return 0;
2160 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161}
2162
2163static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002164cmpop(cmpop_ty op)
2165{
2166 switch (op) {
2167 case Eq:
2168 return PyCmp_EQ;
2169 case NotEq:
2170 return PyCmp_NE;
2171 case Lt:
2172 return PyCmp_LT;
2173 case LtE:
2174 return PyCmp_LE;
2175 case Gt:
2176 return PyCmp_GT;
2177 case GtE:
2178 return PyCmp_GE;
2179 case Is:
2180 return PyCmp_IS;
2181 case IsNot:
2182 return PyCmp_IS_NOT;
2183 case In:
2184 return PyCmp_IN;
2185 case NotIn:
2186 return PyCmp_NOT_IN;
2187 default:
2188 return PyCmp_BAD;
2189 }
2190}
2191
2192static int
2193compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2194{
2195 switch (e->kind) {
2196 case UnaryOp_kind:
2197 if (e->v.UnaryOp.op == Not)
2198 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2199 /* fallback to general implementation */
2200 break;
2201 case BoolOp_kind: {
2202 asdl_seq *s = e->v.BoolOp.values;
2203 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2204 assert(n >= 0);
2205 int cond2 = e->v.BoolOp.op == Or;
2206 basicblock *next2 = next;
2207 if (!cond2 != !cond) {
2208 next2 = compiler_new_block(c);
2209 if (next2 == NULL)
2210 return 0;
2211 }
2212 for (i = 0; i < n; ++i) {
2213 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2214 return 0;
2215 }
2216 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2217 return 0;
2218 if (next2 != next)
2219 compiler_use_next_block(c, next2);
2220 return 1;
2221 }
2222 case IfExp_kind: {
2223 basicblock *end, *next2;
2224 end = compiler_new_block(c);
2225 if (end == NULL)
2226 return 0;
2227 next2 = compiler_new_block(c);
2228 if (next2 == NULL)
2229 return 0;
2230 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2231 return 0;
2232 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2233 return 0;
2234 ADDOP_JREL(c, JUMP_FORWARD, end);
2235 compiler_use_next_block(c, next2);
2236 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2237 return 0;
2238 compiler_use_next_block(c, end);
2239 return 1;
2240 }
2241 case Compare_kind: {
2242 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2243 if (n > 0) {
2244 basicblock *cleanup = compiler_new_block(c);
2245 if (cleanup == NULL)
2246 return 0;
2247 VISIT(c, expr, e->v.Compare.left);
2248 for (i = 0; i < n; i++) {
2249 VISIT(c, expr,
2250 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2251 ADDOP(c, DUP_TOP);
2252 ADDOP(c, ROT_THREE);
2253 ADDOP_I(c, COMPARE_OP,
2254 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2255 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2256 NEXT_BLOCK(c);
2257 }
2258 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2259 ADDOP_I(c, COMPARE_OP,
2260 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2261 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2262 basicblock *end = compiler_new_block(c);
2263 if (end == NULL)
2264 return 0;
2265 ADDOP_JREL(c, JUMP_FORWARD, end);
2266 compiler_use_next_block(c, cleanup);
2267 ADDOP(c, POP_TOP);
2268 if (!cond) {
2269 ADDOP_JREL(c, JUMP_FORWARD, next);
2270 }
2271 compiler_use_next_block(c, end);
2272 return 1;
2273 }
2274 /* fallback to general implementation */
2275 break;
2276 }
2277 default:
2278 /* fallback to general implementation */
2279 break;
2280 }
2281
2282 /* general implementation */
2283 VISIT(c, expr, e);
2284 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2285 return 1;
2286}
2287
2288static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002289compiler_ifexp(struct compiler *c, expr_ty e)
2290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 basicblock *end, *next;
2292
2293 assert(e->kind == IfExp_kind);
2294 end = compiler_new_block(c);
2295 if (end == NULL)
2296 return 0;
2297 next = compiler_new_block(c);
2298 if (next == NULL)
2299 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002300 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2301 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 VISIT(c, expr, e->v.IfExp.body);
2303 ADDOP_JREL(c, JUMP_FORWARD, end);
2304 compiler_use_next_block(c, next);
2305 VISIT(c, expr, e->v.IfExp.orelse);
2306 compiler_use_next_block(c, end);
2307 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002308}
2309
2310static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311compiler_lambda(struct compiler *c, expr_ty e)
2312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002314 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002316 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 arguments_ty args = e->v.Lambda.args;
2318 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 if (!name) {
2321 name = PyUnicode_InternFromString("<lambda>");
2322 if (!name)
2323 return 0;
2324 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002326 funcflags = compiler_default_arguments(c, args);
2327 if (funcflags == -1) {
2328 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002330
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002331 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002332 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* Make None the first constant, so the lambda can't have a
2336 docstring. */
2337 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2338 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 c->u->u_argcount = asdl_seq_LEN(args->args);
2341 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2342 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2343 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002344 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 }
2346 else {
2347 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002348 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002350 qualname = c->u->u_qualname;
2351 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002353 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002356 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002357 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 Py_DECREF(co);
2359
2360 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361}
2362
2363static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364compiler_if(struct compiler *c, stmt_ty s)
2365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 basicblock *end, *next;
2367 int constant;
2368 assert(s->kind == If_kind);
2369 end = compiler_new_block(c);
2370 if (end == NULL)
2371 return 0;
2372
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002373 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* constant = 0: "if 0"
2375 * constant = 1: "if 1", "if 2", ...
2376 * constant = -1: rest */
2377 if (constant == 0) {
2378 if (s->v.If.orelse)
2379 VISIT_SEQ(c, stmt, s->v.If.orelse);
2380 } else if (constant == 1) {
2381 VISIT_SEQ(c, stmt, s->v.If.body);
2382 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002383 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 next = compiler_new_block(c);
2385 if (next == NULL)
2386 return 0;
2387 }
2388 else
2389 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002390 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2391 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002393 if (asdl_seq_LEN(s->v.If.orelse)) {
2394 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 compiler_use_next_block(c, next);
2396 VISIT_SEQ(c, stmt, s->v.If.orelse);
2397 }
2398 }
2399 compiler_use_next_block(c, end);
2400 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401}
2402
2403static int
2404compiler_for(struct compiler *c, stmt_ty s)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 start = compiler_new_block(c);
2409 cleanup = compiler_new_block(c);
2410 end = compiler_new_block(c);
2411 if (start == NULL || end == NULL || cleanup == NULL)
2412 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002413
2414 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 VISIT(c, expr, s->v.For.iter);
2418 ADDOP(c, GET_ITER);
2419 compiler_use_next_block(c, start);
2420 ADDOP_JREL(c, FOR_ITER, cleanup);
2421 VISIT(c, expr, s->v.For.target);
2422 VISIT_SEQ(c, stmt, s->v.For.body);
2423 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2424 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002425
2426 compiler_pop_fblock(c, FOR_LOOP, start);
2427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 VISIT_SEQ(c, stmt, s->v.For.orelse);
2429 compiler_use_next_block(c, end);
2430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431}
2432
Yury Selivanov75445082015-05-11 22:57:16 -04002433
2434static int
2435compiler_async_for(struct compiler *c, stmt_ty s)
2436{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002437 _Py_IDENTIFIER(StopAsyncIteration);
2438
Yury Selivanov75445082015-05-11 22:57:16 -04002439 basicblock *try, *except, *end, *after_try, *try_cleanup,
Serhiy Storchaka67ee0772018-03-10 18:49:26 +02002440 *after_loop_else;
Yury Selivanov75445082015-05-11 22:57:16 -04002441
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002442 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2443 if (stop_aiter_error == NULL) {
2444 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002445 }
2446
2447 try = compiler_new_block(c);
2448 except = compiler_new_block(c);
2449 end = compiler_new_block(c);
2450 after_try = compiler_new_block(c);
2451 try_cleanup = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002452 after_loop_else = compiler_new_block(c);
2453
2454 if (try == NULL || except == NULL || end == NULL
Serhiy Storchaka67ee0772018-03-10 18:49:26 +02002455 || after_try == NULL || try_cleanup == NULL
2456 || after_loop_else == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002457 return 0;
2458
Serhiy Storchaka67ee0772018-03-10 18:49:26 +02002459 if (!compiler_push_fblock(c, FOR_LOOP, try, end))
Yury Selivanov75445082015-05-11 22:57:16 -04002460 return 0;
2461
2462 VISIT(c, expr, s->v.AsyncFor.iter);
2463 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002464
2465 compiler_use_next_block(c, try);
2466
2467
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002468 /* SETUP_FINALLY to guard the __anext__ call */
2469 ADDOP_JREL(c, SETUP_FINALLY, except);
2470 if (!compiler_push_fblock(c, EXCEPT, try, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04002471 return 0;
2472
2473 ADDOP(c, GET_ANEXT);
2474 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2475 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002476 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Serhiy Storchaka24d32012018-03-10 18:22:34 +02002477 VISIT(c, expr, s->v.AsyncFor.target);
Yury Selivanov75445082015-05-11 22:57:16 -04002478 compiler_pop_fblock(c, EXCEPT, try);
2479 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2480
2481
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002482 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002483 compiler_use_next_block(c, except);
2484 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002485 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002486 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2487 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2488
2489 ADDOP(c, POP_TOP);
2490 ADDOP(c, POP_TOP);
2491 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002492 ADDOP(c, POP_EXCEPT); /* for SETUP_FINALLY */
2493 ADDOP(c, POP_TOP); /* pop iterator from stack */
Yury Selivanov75445082015-05-11 22:57:16 -04002494 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2495
2496
2497 compiler_use_next_block(c, try_cleanup);
2498 ADDOP(c, END_FINALLY);
2499
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002500 /* Success block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002501 compiler_use_next_block(c, after_try);
2502 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2503 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2504
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002505 compiler_pop_fblock(c, FOR_LOOP, try);
Yury Selivanov75445082015-05-11 22:57:16 -04002506
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002507 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002508 compiler_use_next_block(c, after_loop_else);
2509 VISIT_SEQ(c, stmt, s->v.For.orelse);
2510
2511 compiler_use_next_block(c, end);
2512
2513 return 1;
2514}
2515
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516static int
2517compiler_while(struct compiler *c, stmt_ty s)
2518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002520 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (constant == 0) {
2523 if (s->v.While.orelse)
2524 VISIT_SEQ(c, stmt, s->v.While.orelse);
2525 return 1;
2526 }
2527 loop = compiler_new_block(c);
2528 end = compiler_new_block(c);
2529 if (constant == -1) {
2530 anchor = compiler_new_block(c);
2531 if (anchor == NULL)
2532 return 0;
2533 }
2534 if (loop == NULL || end == NULL)
2535 return 0;
2536 if (s->v.While.orelse) {
2537 orelse = compiler_new_block(c);
2538 if (orelse == NULL)
2539 return 0;
2540 }
2541 else
2542 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002545 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 return 0;
2547 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002548 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2549 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 }
2551 VISIT_SEQ(c, stmt, s->v.While.body);
2552 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* XXX should the two POP instructions be in a separate block
2555 if there is no else clause ?
2556 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002558 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002560 compiler_pop_fblock(c, WHILE_LOOP, loop);
2561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (orelse != NULL) /* what if orelse is just pass? */
2563 VISIT_SEQ(c, stmt, s->v.While.orelse);
2564 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567}
2568
2569static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002570compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002572 int preserve_tos = ((s->v.Return.value != NULL) &&
2573 !is_const(s->v.Return.value));
2574 if (c->u->u_ste->ste_type != FunctionBlock)
2575 return compiler_error(c, "'return' outside function");
2576 if (s->v.Return.value != NULL &&
2577 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2578 {
2579 return compiler_error(
2580 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002582 if (preserve_tos) {
2583 VISIT(c, expr, s->v.Return.value);
2584 }
2585 for (int depth = c->u->u_nfblocks; depth--;) {
2586 struct fblockinfo *info = &c->u->u_fblock[depth];
2587
2588 if (!compiler_unwind_fblock(c, info, preserve_tos))
2589 return 0;
2590 }
2591 if (s->v.Return.value == NULL) {
2592 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2593 }
2594 else if (!preserve_tos) {
2595 VISIT(c, expr, s->v.Return.value);
2596 }
2597 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600}
2601
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002602static int
2603compiler_break(struct compiler *c)
2604{
2605 for (int depth = c->u->u_nfblocks; depth--;) {
2606 struct fblockinfo *info = &c->u->u_fblock[depth];
2607
2608 if (!compiler_unwind_fblock(c, info, 0))
2609 return 0;
2610 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2611 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2612 return 1;
2613 }
2614 }
2615 return compiler_error(c, "'break' outside loop");
2616}
2617
2618static int
2619compiler_continue(struct compiler *c)
2620{
2621 for (int depth = c->u->u_nfblocks; depth--;) {
2622 struct fblockinfo *info = &c->u->u_fblock[depth];
2623
2624 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2625 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2626 return 1;
2627 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002628 if (!compiler_unwind_fblock(c, info, 0))
2629 return 0;
2630 }
2631 return compiler_error(c, "'continue' not properly in loop");
2632}
2633
2634
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636
2637 SETUP_FINALLY L
2638 <code for body>
2639 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002640 BEGIN_FINALLY
2641 L:
2642 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 END_FINALLY
2644
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 The special instructions use the block stack. Each block
2646 stack entry contains the instruction that created it (here
2647 SETUP_FINALLY), the level of the value stack at the time the
2648 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 Pushes the current value stack level and the label
2652 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002654 Pops en entry from the block stack.
2655 BEGIN_FINALLY
2656 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002658 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2659 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002662 when a SETUP_FINALLY entry is found, the raised and the caught
2663 exceptions are pushed onto the value stack (and the exception
2664 condition is cleared), and the interpreter jumps to the label
2665 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666*/
2667
2668static int
2669compiler_try_finally(struct compiler *c, stmt_ty s)
2670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 body = compiler_new_block(c);
2674 end = compiler_new_block(c);
2675 if (body == NULL || end == NULL)
2676 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002678 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 ADDOP_JREL(c, SETUP_FINALLY, end);
2680 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002681 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002683 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2684 if (!compiler_try_except(c, s))
2685 return 0;
2686 }
2687 else {
2688 VISIT_SEQ(c, stmt, s->v.Try.body);
2689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002691 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002694 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002696 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002698 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 ADDOP(c, END_FINALLY);
2700 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702}
2703
2704/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002705 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 (The contents of the value stack is shown in [], with the top
2707 at the right; 'tb' is trace-back info, 'val' the exception's
2708 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709
2710 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002711 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 [] <code for S>
2713 [] POP_BLOCK
2714 [] JUMP_FORWARD L0
2715
2716 [tb, val, exc] L1: DUP )
2717 [tb, val, exc, exc] <evaluate E1> )
2718 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2719 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2720 [tb, val, exc] POP
2721 [tb, val] <assign to V1> (or POP if no V1)
2722 [tb] POP
2723 [] <code for S1>
2724 JUMP_FORWARD L0
2725
2726 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727 .............................etc.......................
2728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2730
2731 [] L0: <next statement>
2732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 Of course, parts are not generated if Vi or Ei is not present.
2734*/
2735static int
2736compiler_try_except(struct compiler *c, stmt_ty s)
2737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002739 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 body = compiler_new_block(c);
2742 except = compiler_new_block(c);
2743 orelse = compiler_new_block(c);
2744 end = compiler_new_block(c);
2745 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2746 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002747 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002749 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002751 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 ADDOP(c, POP_BLOCK);
2753 compiler_pop_fblock(c, EXCEPT, body);
2754 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002755 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 compiler_use_next_block(c, except);
2757 for (i = 0; i < n; i++) {
2758 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002759 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (!handler->v.ExceptHandler.type && i < n-1)
2761 return compiler_error(c, "default 'except:' must be last");
2762 c->u->u_lineno_set = 0;
2763 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002764 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 except = compiler_new_block(c);
2766 if (except == NULL)
2767 return 0;
2768 if (handler->v.ExceptHandler.type) {
2769 ADDOP(c, DUP_TOP);
2770 VISIT(c, expr, handler->v.ExceptHandler.type);
2771 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2772 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2773 }
2774 ADDOP(c, POP_TOP);
2775 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002776 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002777
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002778 cleanup_end = compiler_new_block(c);
2779 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002780 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002781 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002782
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002783 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2784 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002786 /*
2787 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002788 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002789 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002790 try:
2791 # body
2792 finally:
2793 name = None
2794 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002795 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002797 /* second try: */
2798 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2799 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002800 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002801 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002803 /* second # body */
2804 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2805 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806 ADDOP(c, BEGIN_FINALLY);
2807 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002809 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002810 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002812 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002814 /* name = None; del name */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002815 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2816 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002817 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002819 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002820 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002821 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 }
2823 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002824 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002826 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002827 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002828 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829
Guido van Rossumb940e112007-01-10 16:19:56 +00002830 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002831 ADDOP(c, POP_TOP);
2832 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002833 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002834 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002836 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002837 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 }
2839 ADDOP_JREL(c, JUMP_FORWARD, end);
2840 compiler_use_next_block(c, except);
2841 }
2842 ADDOP(c, END_FINALLY);
2843 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002844 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 compiler_use_next_block(c, end);
2846 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847}
2848
2849static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002850compiler_try(struct compiler *c, stmt_ty s) {
2851 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2852 return compiler_try_finally(c, s);
2853 else
2854 return compiler_try_except(c, s);
2855}
2856
2857
2858static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859compiler_import_as(struct compiler *c, identifier name, identifier asname)
2860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 /* The IMPORT_NAME opcode was already generated. This function
2862 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002865 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002867 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2868 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002869 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002870 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002871 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002873 while (1) {
2874 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002876 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002877 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002878 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002879 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002881 return 0;
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002882 ADDOP_O(c, IMPORT_FROM, attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 Py_DECREF(attr);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002884 if (dot == -1) {
2885 break;
2886 }
2887 ADDOP(c, ROT_TWO);
2888 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002890 if (!compiler_nameop(c, asname, Store)) {
2891 return 0;
2892 }
2893 ADDOP(c, POP_TOP);
2894 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 }
2896 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897}
2898
2899static int
2900compiler_import(struct compiler *c, stmt_ty s)
2901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 /* The Import node stores a module name like a.b.c as a single
2903 string. This is convenient for all cases except
2904 import a.b.c as d
2905 where we need to parse that string to extract the individual
2906 module names.
2907 XXX Perhaps change the representation to make this case simpler?
2908 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002909 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 for (i = 0; i < n; i++) {
2912 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2913 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002915 ADDOP_O(c, LOAD_CONST, _PyLong_Zero, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2917 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (alias->asname) {
2920 r = compiler_import_as(c, alias->name, alias->asname);
2921 if (!r)
2922 return r;
2923 }
2924 else {
2925 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002926 Py_ssize_t dot = PyUnicode_FindChar(
2927 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002928 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002929 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002930 if (tmp == NULL)
2931 return 0;
2932 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002934 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 Py_DECREF(tmp);
2936 }
2937 if (!r)
2938 return r;
2939 }
2940 }
2941 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942}
2943
2944static int
2945compiler_from_import(struct compiler *c, stmt_ty s)
2946{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002947 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 PyObject *names = PyTuple_New(n);
2950 PyObject *level;
2951 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 if (!empty_string) {
2954 empty_string = PyUnicode_FromString("");
2955 if (!empty_string)
2956 return 0;
2957 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 if (!names)
2960 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 level = PyLong_FromLong(s->v.ImportFrom.level);
2963 if (!level) {
2964 Py_DECREF(names);
2965 return 0;
2966 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 /* build up the names */
2969 for (i = 0; i < n; i++) {
2970 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2971 Py_INCREF(alias->name);
2972 PyTuple_SET_ITEM(names, i, alias->name);
2973 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002976 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 Py_DECREF(level);
2978 Py_DECREF(names);
2979 return compiler_error(c, "from __future__ imports must occur "
2980 "at the beginning of the file");
2981 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 ADDOP_O(c, LOAD_CONST, level, consts);
2984 Py_DECREF(level);
2985 ADDOP_O(c, LOAD_CONST, names, consts);
2986 Py_DECREF(names);
2987 if (s->v.ImportFrom.module) {
2988 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2989 }
2990 else {
2991 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2992 }
2993 for (i = 0; i < n; i++) {
2994 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2995 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002997 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 assert(n == 1);
2999 ADDOP(c, IMPORT_STAR);
3000 return 1;
3001 }
3002
3003 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3004 store_name = alias->name;
3005 if (alias->asname)
3006 store_name = alias->asname;
3007
3008 if (!compiler_nameop(c, store_name, Store)) {
3009 Py_DECREF(names);
3010 return 0;
3011 }
3012 }
3013 /* remove imported module */
3014 ADDOP(c, POP_TOP);
3015 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016}
3017
3018static int
3019compiler_assert(struct compiler *c, stmt_ty s)
3020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 static PyObject *assertion_error = NULL;
3022 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02003023 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024
Georg Brandl8334fd92010-12-04 10:26:46 +00003025 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 return 1;
3027 if (assertion_error == NULL) {
3028 assertion_error = PyUnicode_InternFromString("AssertionError");
3029 if (assertion_error == NULL)
3030 return 0;
3031 }
3032 if (s->v.Assert.test->kind == Tuple_kind &&
3033 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02003034 msg = PyUnicode_FromString("assertion is always true, "
3035 "perhaps remove parentheses?");
3036 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02003038 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
3039 c->c_filename, c->u->u_lineno,
3040 NULL, NULL) == -1) {
3041 Py_DECREF(msg);
3042 return 0;
3043 }
3044 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 end = compiler_new_block(c);
3047 if (end == NULL)
3048 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003049 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3050 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3052 if (s->v.Assert.msg) {
3053 VISIT(c, expr, s->v.Assert.msg);
3054 ADDOP_I(c, CALL_FUNCTION, 1);
3055 }
3056 ADDOP_I(c, RAISE_VARARGS, 1);
3057 compiler_use_next_block(c, end);
3058 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059}
3060
3061static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003062compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3063{
3064 if (c->c_interactive && c->c_nestlevel <= 1) {
3065 VISIT(c, expr, value);
3066 ADDOP(c, PRINT_EXPR);
3067 return 1;
3068 }
3069
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003070 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003071 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003072 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003073 }
3074
3075 VISIT(c, expr, value);
3076 ADDOP(c, POP_TOP);
3077 return 1;
3078}
3079
3080static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003081compiler_visit_stmt(struct compiler *c, stmt_ty s)
3082{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003083 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 /* Always assign a lineno to the next instruction for a stmt. */
3086 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003087 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 switch (s->kind) {
3091 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003092 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 case ClassDef_kind:
3094 return compiler_class(c, s);
3095 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003096 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 case Delete_kind:
3098 VISIT_SEQ(c, expr, s->v.Delete.targets)
3099 break;
3100 case Assign_kind:
3101 n = asdl_seq_LEN(s->v.Assign.targets);
3102 VISIT(c, expr, s->v.Assign.value);
3103 for (i = 0; i < n; i++) {
3104 if (i < n - 1)
3105 ADDOP(c, DUP_TOP);
3106 VISIT(c, expr,
3107 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3108 }
3109 break;
3110 case AugAssign_kind:
3111 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003112 case AnnAssign_kind:
3113 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 case For_kind:
3115 return compiler_for(c, s);
3116 case While_kind:
3117 return compiler_while(c, s);
3118 case If_kind:
3119 return compiler_if(c, s);
3120 case Raise_kind:
3121 n = 0;
3122 if (s->v.Raise.exc) {
3123 VISIT(c, expr, s->v.Raise.exc);
3124 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003125 if (s->v.Raise.cause) {
3126 VISIT(c, expr, s->v.Raise.cause);
3127 n++;
3128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003130 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003132 case Try_kind:
3133 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 case Assert_kind:
3135 return compiler_assert(c, s);
3136 case Import_kind:
3137 return compiler_import(c, s);
3138 case ImportFrom_kind:
3139 return compiler_from_import(c, s);
3140 case Global_kind:
3141 case Nonlocal_kind:
3142 break;
3143 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003144 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 case Pass_kind:
3146 break;
3147 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003148 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 case Continue_kind:
3150 return compiler_continue(c);
3151 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003152 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003153 case AsyncFunctionDef_kind:
3154 return compiler_function(c, s, 1);
3155 case AsyncWith_kind:
3156 return compiler_async_with(c, s, 0);
3157 case AsyncFor_kind:
3158 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 }
Yury Selivanov75445082015-05-11 22:57:16 -04003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162}
3163
3164static int
3165unaryop(unaryop_ty op)
3166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 switch (op) {
3168 case Invert:
3169 return UNARY_INVERT;
3170 case Not:
3171 return UNARY_NOT;
3172 case UAdd:
3173 return UNARY_POSITIVE;
3174 case USub:
3175 return UNARY_NEGATIVE;
3176 default:
3177 PyErr_Format(PyExc_SystemError,
3178 "unary op %d should not be possible", op);
3179 return 0;
3180 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
3183static int
3184binop(struct compiler *c, operator_ty op)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 switch (op) {
3187 case Add:
3188 return BINARY_ADD;
3189 case Sub:
3190 return BINARY_SUBTRACT;
3191 case Mult:
3192 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003193 case MatMult:
3194 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 case Div:
3196 return BINARY_TRUE_DIVIDE;
3197 case Mod:
3198 return BINARY_MODULO;
3199 case Pow:
3200 return BINARY_POWER;
3201 case LShift:
3202 return BINARY_LSHIFT;
3203 case RShift:
3204 return BINARY_RSHIFT;
3205 case BitOr:
3206 return BINARY_OR;
3207 case BitXor:
3208 return BINARY_XOR;
3209 case BitAnd:
3210 return BINARY_AND;
3211 case FloorDiv:
3212 return BINARY_FLOOR_DIVIDE;
3213 default:
3214 PyErr_Format(PyExc_SystemError,
3215 "binary op %d should not be possible", op);
3216 return 0;
3217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218}
3219
3220static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221inplace_binop(struct compiler *c, operator_ty op)
3222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 switch (op) {
3224 case Add:
3225 return INPLACE_ADD;
3226 case Sub:
3227 return INPLACE_SUBTRACT;
3228 case Mult:
3229 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003230 case MatMult:
3231 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 case Div:
3233 return INPLACE_TRUE_DIVIDE;
3234 case Mod:
3235 return INPLACE_MODULO;
3236 case Pow:
3237 return INPLACE_POWER;
3238 case LShift:
3239 return INPLACE_LSHIFT;
3240 case RShift:
3241 return INPLACE_RSHIFT;
3242 case BitOr:
3243 return INPLACE_OR;
3244 case BitXor:
3245 return INPLACE_XOR;
3246 case BitAnd:
3247 return INPLACE_AND;
3248 case FloorDiv:
3249 return INPLACE_FLOOR_DIVIDE;
3250 default:
3251 PyErr_Format(PyExc_SystemError,
3252 "inplace binary op %d should not be possible", op);
3253 return 0;
3254 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255}
3256
3257static int
3258compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3259{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003260 int op, scope;
3261 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 PyObject *dict = c->u->u_names;
3265 PyObject *mangled;
3266 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003268 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3269 !_PyUnicode_EqualToASCIIString(name, "True") &&
3270 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003271
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003272 mangled = _Py_Mangle(c->u->u_private, name);
3273 if (!mangled)
3274 return 0;
3275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 op = 0;
3277 optype = OP_NAME;
3278 scope = PyST_GetScope(c->u->u_ste, mangled);
3279 switch (scope) {
3280 case FREE:
3281 dict = c->u->u_freevars;
3282 optype = OP_DEREF;
3283 break;
3284 case CELL:
3285 dict = c->u->u_cellvars;
3286 optype = OP_DEREF;
3287 break;
3288 case LOCAL:
3289 if (c->u->u_ste->ste_type == FunctionBlock)
3290 optype = OP_FAST;
3291 break;
3292 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003293 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 optype = OP_GLOBAL;
3295 break;
3296 case GLOBAL_EXPLICIT:
3297 optype = OP_GLOBAL;
3298 break;
3299 default:
3300 /* scope can be 0 */
3301 break;
3302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003305 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 switch (optype) {
3308 case OP_DEREF:
3309 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003310 case Load:
3311 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3312 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 case Store: op = STORE_DEREF; break;
3314 case AugLoad:
3315 case AugStore:
3316 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003317 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 case Param:
3319 default:
3320 PyErr_SetString(PyExc_SystemError,
3321 "param invalid for deref variable");
3322 return 0;
3323 }
3324 break;
3325 case OP_FAST:
3326 switch (ctx) {
3327 case Load: op = LOAD_FAST; break;
3328 case Store: op = STORE_FAST; break;
3329 case Del: op = DELETE_FAST; break;
3330 case AugLoad:
3331 case AugStore:
3332 break;
3333 case Param:
3334 default:
3335 PyErr_SetString(PyExc_SystemError,
3336 "param invalid for local variable");
3337 return 0;
3338 }
3339 ADDOP_O(c, op, mangled, varnames);
3340 Py_DECREF(mangled);
3341 return 1;
3342 case OP_GLOBAL:
3343 switch (ctx) {
3344 case Load: op = LOAD_GLOBAL; break;
3345 case Store: op = STORE_GLOBAL; break;
3346 case Del: op = DELETE_GLOBAL; break;
3347 case AugLoad:
3348 case AugStore:
3349 break;
3350 case Param:
3351 default:
3352 PyErr_SetString(PyExc_SystemError,
3353 "param invalid for global variable");
3354 return 0;
3355 }
3356 break;
3357 case OP_NAME:
3358 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003359 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 case Store: op = STORE_NAME; break;
3361 case Del: op = DELETE_NAME; break;
3362 case AugLoad:
3363 case AugStore:
3364 break;
3365 case Param:
3366 default:
3367 PyErr_SetString(PyExc_SystemError,
3368 "param invalid for name variable");
3369 return 0;
3370 }
3371 break;
3372 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 assert(op);
3375 arg = compiler_add_o(c, dict, mangled);
3376 Py_DECREF(mangled);
3377 if (arg < 0)
3378 return 0;
3379 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380}
3381
3382static int
3383compiler_boolop(struct compiler *c, expr_ty e)
3384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003386 int jumpi;
3387 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 assert(e->kind == BoolOp_kind);
3391 if (e->v.BoolOp.op == And)
3392 jumpi = JUMP_IF_FALSE_OR_POP;
3393 else
3394 jumpi = JUMP_IF_TRUE_OR_POP;
3395 end = compiler_new_block(c);
3396 if (end == NULL)
3397 return 0;
3398 s = e->v.BoolOp.values;
3399 n = asdl_seq_LEN(s) - 1;
3400 assert(n >= 0);
3401 for (i = 0; i < n; ++i) {
3402 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3403 ADDOP_JABS(c, jumpi, end);
3404 }
3405 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3406 compiler_use_next_block(c, end);
3407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408}
3409
3410static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003411starunpack_helper(struct compiler *c, asdl_seq *elts,
3412 int single_op, int inner_op, int outer_op)
3413{
3414 Py_ssize_t n = asdl_seq_LEN(elts);
3415 Py_ssize_t i, nsubitems = 0, nseen = 0;
3416 for (i = 0; i < n; i++) {
3417 expr_ty elt = asdl_seq_GET(elts, i);
3418 if (elt->kind == Starred_kind) {
3419 if (nseen) {
3420 ADDOP_I(c, inner_op, nseen);
3421 nseen = 0;
3422 nsubitems++;
3423 }
3424 VISIT(c, expr, elt->v.Starred.value);
3425 nsubitems++;
3426 }
3427 else {
3428 VISIT(c, expr, elt);
3429 nseen++;
3430 }
3431 }
3432 if (nsubitems) {
3433 if (nseen) {
3434 ADDOP_I(c, inner_op, nseen);
3435 nsubitems++;
3436 }
3437 ADDOP_I(c, outer_op, nsubitems);
3438 }
3439 else
3440 ADDOP_I(c, single_op, nseen);
3441 return 1;
3442}
3443
3444static int
3445assignment_helper(struct compiler *c, asdl_seq *elts)
3446{
3447 Py_ssize_t n = asdl_seq_LEN(elts);
3448 Py_ssize_t i;
3449 int seen_star = 0;
3450 for (i = 0; i < n; i++) {
3451 expr_ty elt = asdl_seq_GET(elts, i);
3452 if (elt->kind == Starred_kind && !seen_star) {
3453 if ((i >= (1 << 8)) ||
3454 (n-i-1 >= (INT_MAX >> 8)))
3455 return compiler_error(c,
3456 "too many expressions in "
3457 "star-unpacking assignment");
3458 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3459 seen_star = 1;
3460 asdl_seq_SET(elts, i, elt->v.Starred.value);
3461 }
3462 else if (elt->kind == Starred_kind) {
3463 return compiler_error(c,
3464 "two starred expressions in assignment");
3465 }
3466 }
3467 if (!seen_star) {
3468 ADDOP_I(c, UNPACK_SEQUENCE, n);
3469 }
3470 VISIT_SEQ(c, expr, elts);
3471 return 1;
3472}
3473
3474static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003475compiler_list(struct compiler *c, expr_ty e)
3476{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003477 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003479 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003481 else if (e->v.List.ctx == Load) {
3482 return starunpack_helper(c, elts,
3483 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003485 else
3486 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488}
3489
3490static int
3491compiler_tuple(struct compiler *c, expr_ty e)
3492{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003493 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003495 return assignment_helper(c, elts);
3496 }
3497 else if (e->v.Tuple.ctx == Load) {
3498 return starunpack_helper(c, elts,
3499 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3500 }
3501 else
3502 VISIT_SEQ(c, expr, elts);
3503 return 1;
3504}
3505
3506static int
3507compiler_set(struct compiler *c, expr_ty e)
3508{
3509 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3510 BUILD_SET, BUILD_SET_UNPACK);
3511}
3512
3513static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003514are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3515{
3516 Py_ssize_t i;
3517 for (i = begin; i < end; i++) {
3518 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3519 if (key == NULL || !is_const(key))
3520 return 0;
3521 }
3522 return 1;
3523}
3524
3525static int
3526compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3527{
3528 Py_ssize_t i, n = end - begin;
3529 PyObject *keys, *key;
3530 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3531 for (i = begin; i < end; i++) {
3532 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3533 }
3534 keys = PyTuple_New(n);
3535 if (keys == NULL) {
3536 return 0;
3537 }
3538 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003539 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003540 Py_INCREF(key);
3541 PyTuple_SET_ITEM(keys, i - begin, key);
3542 }
3543 ADDOP_N(c, LOAD_CONST, keys, consts);
3544 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3545 }
3546 else {
3547 for (i = begin; i < end; i++) {
3548 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3549 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3550 }
3551 ADDOP_I(c, BUILD_MAP, n);
3552 }
3553 return 1;
3554}
3555
3556static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003557compiler_dict(struct compiler *c, expr_ty e)
3558{
Victor Stinner976bb402016-03-23 11:36:19 +01003559 Py_ssize_t i, n, elements;
3560 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003561 int is_unpacking = 0;
3562 n = asdl_seq_LEN(e->v.Dict.values);
3563 containers = 0;
3564 elements = 0;
3565 for (i = 0; i < n; i++) {
3566 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3567 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003568 if (!compiler_subdict(c, e, i - elements, i))
3569 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003570 containers++;
3571 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003573 if (is_unpacking) {
3574 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3575 containers++;
3576 }
3577 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003578 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 }
3580 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003581 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003582 if (!compiler_subdict(c, e, n - elements, n))
3583 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003584 containers++;
3585 }
3586 /* If there is more than one dict, they need to be merged into a new
3587 * dict. If there is one dict and it's an unpacking, then it needs
3588 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003589 if (containers > 1 || is_unpacking) {
3590 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 }
3592 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593}
3594
3595static int
3596compiler_compare(struct compiler *c, expr_ty e)
3597{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003598 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003601 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3602 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3603 if (n == 0) {
3604 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3605 ADDOP_I(c, COMPARE_OP,
3606 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3607 }
3608 else {
3609 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 if (cleanup == NULL)
3611 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003612 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 VISIT(c, expr,
3614 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003615 ADDOP(c, DUP_TOP);
3616 ADDOP(c, ROT_THREE);
3617 ADDOP_I(c, COMPARE_OP,
3618 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3619 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3620 NEXT_BLOCK(c);
3621 }
3622 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3623 ADDOP_I(c, COMPARE_OP,
3624 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 basicblock *end = compiler_new_block(c);
3626 if (end == NULL)
3627 return 0;
3628 ADDOP_JREL(c, JUMP_FORWARD, end);
3629 compiler_use_next_block(c, cleanup);
3630 ADDOP(c, ROT_TWO);
3631 ADDOP(c, POP_TOP);
3632 compiler_use_next_block(c, end);
3633 }
3634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635}
3636
3637static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003638maybe_optimize_method_call(struct compiler *c, expr_ty e)
3639{
3640 Py_ssize_t argsl, i;
3641 expr_ty meth = e->v.Call.func;
3642 asdl_seq *args = e->v.Call.args;
3643
3644 /* Check that the call node is an attribute access, and that
3645 the call doesn't have keyword parameters. */
3646 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3647 asdl_seq_LEN(e->v.Call.keywords))
3648 return -1;
3649
3650 /* Check that there are no *varargs types of arguments. */
3651 argsl = asdl_seq_LEN(args);
3652 for (i = 0; i < argsl; i++) {
3653 expr_ty elt = asdl_seq_GET(args, i);
3654 if (elt->kind == Starred_kind) {
3655 return -1;
3656 }
3657 }
3658
3659 /* Alright, we can optimize the code. */
3660 VISIT(c, expr, meth->v.Attribute.value);
3661 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3662 VISIT_SEQ(c, expr, e->v.Call.args);
3663 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3664 return 1;
3665}
3666
3667static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668compiler_call(struct compiler *c, expr_ty e)
3669{
Yury Selivanovf2392132016-12-13 19:03:51 -05003670 if (maybe_optimize_method_call(c, e) > 0)
3671 return 1;
3672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 VISIT(c, expr, e->v.Call.func);
3674 return compiler_call_helper(c, 0,
3675 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003676 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003677}
3678
Eric V. Smith235a6f02015-09-19 14:51:32 -04003679static int
3680compiler_joined_str(struct compiler *c, expr_ty e)
3681{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003682 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003683 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3684 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003685 return 1;
3686}
3687
Eric V. Smitha78c7952015-11-03 12:45:05 -05003688/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003689static int
3690compiler_formatted_value(struct compiler *c, expr_ty e)
3691{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003692 /* Our oparg encodes 2 pieces of information: the conversion
3693 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003694
Eric V. Smitha78c7952015-11-03 12:45:05 -05003695 Convert the conversion char to 2 bits:
3696 None: 000 0x0 FVC_NONE
3697 !s : 001 0x1 FVC_STR
3698 !r : 010 0x2 FVC_REPR
3699 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003700
Eric V. Smitha78c7952015-11-03 12:45:05 -05003701 next bit is whether or not we have a format spec:
3702 yes : 100 0x4
3703 no : 000 0x0
3704 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003705
Eric V. Smitha78c7952015-11-03 12:45:05 -05003706 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003707
Eric V. Smitha78c7952015-11-03 12:45:05 -05003708 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003709 VISIT(c, expr, e->v.FormattedValue.value);
3710
Eric V. Smitha78c7952015-11-03 12:45:05 -05003711 switch (e->v.FormattedValue.conversion) {
3712 case 's': oparg = FVC_STR; break;
3713 case 'r': oparg = FVC_REPR; break;
3714 case 'a': oparg = FVC_ASCII; break;
3715 case -1: oparg = FVC_NONE; break;
3716 default:
3717 PyErr_SetString(PyExc_SystemError,
3718 "Unrecognized conversion character");
3719 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003720 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003721 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003722 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003723 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003724 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003725 }
3726
Eric V. Smitha78c7952015-11-03 12:45:05 -05003727 /* And push our opcode and oparg */
3728 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003729 return 1;
3730}
3731
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003732static int
3733compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3734{
3735 Py_ssize_t i, n = end - begin;
3736 keyword_ty kw;
3737 PyObject *keys, *key;
3738 assert(n > 0);
3739 if (n > 1) {
3740 for (i = begin; i < end; i++) {
3741 kw = asdl_seq_GET(keywords, i);
3742 VISIT(c, expr, kw->value);
3743 }
3744 keys = PyTuple_New(n);
3745 if (keys == NULL) {
3746 return 0;
3747 }
3748 for (i = begin; i < end; i++) {
3749 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3750 Py_INCREF(key);
3751 PyTuple_SET_ITEM(keys, i - begin, key);
3752 }
3753 ADDOP_N(c, LOAD_CONST, keys, consts);
3754 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3755 }
3756 else {
3757 /* a for loop only executes once */
3758 for (i = begin; i < end; i++) {
3759 kw = asdl_seq_GET(keywords, i);
3760 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3761 VISIT(c, expr, kw->value);
3762 }
3763 ADDOP_I(c, BUILD_MAP, n);
3764 }
3765 return 1;
3766}
3767
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003768/* shared code between compiler_call and compiler_class */
3769static int
3770compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003771 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003772 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003774{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003775 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003776 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003777
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003778 /* the number of tuples and dictionaries on the stack */
3779 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3780
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003782 nkwelts = asdl_seq_LEN(keywords);
3783
3784 for (i = 0; i < nkwelts; i++) {
3785 keyword_ty kw = asdl_seq_GET(keywords, i);
3786 if (kw->arg == NULL) {
3787 mustdictunpack = 1;
3788 break;
3789 }
3790 }
3791
3792 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003793 for (i = 0; i < nelts; i++) {
3794 expr_ty elt = asdl_seq_GET(args, i);
3795 if (elt->kind == Starred_kind) {
3796 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003797 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003798 if (nseen) {
3799 ADDOP_I(c, BUILD_TUPLE, nseen);
3800 nseen = 0;
3801 nsubargs++;
3802 }
3803 VISIT(c, expr, elt->v.Starred.value);
3804 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805 }
3806 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003807 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003808 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003811
3812 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003813 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003814 if (nseen) {
3815 /* Pack up any trailing positional arguments. */
3816 ADDOP_I(c, BUILD_TUPLE, nseen);
3817 nsubargs++;
3818 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003819 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003820 /* If we ended up with more than one stararg, we need
3821 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003822 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003823 }
3824 else if (nsubargs == 0) {
3825 ADDOP_I(c, BUILD_TUPLE, 0);
3826 }
3827 nseen = 0; /* the number of keyword arguments on the stack following */
3828 for (i = 0; i < nkwelts; i++) {
3829 keyword_ty kw = asdl_seq_GET(keywords, i);
3830 if (kw->arg == NULL) {
3831 /* A keyword argument unpacking. */
3832 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003833 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3834 return 0;
3835 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003836 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003837 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003838 VISIT(c, expr, kw->value);
3839 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003840 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003841 else {
3842 nseen++;
3843 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003844 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003845 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003846 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003847 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003848 return 0;
3849 nsubkwargs++;
3850 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003851 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003852 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003853 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003854 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003855 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3856 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003858 else if (nkwelts) {
3859 PyObject *names;
3860 VISIT_SEQ(c, keyword, keywords);
3861 names = PyTuple_New(nkwelts);
3862 if (names == NULL) {
3863 return 0;
3864 }
3865 for (i = 0; i < nkwelts; i++) {
3866 keyword_ty kw = asdl_seq_GET(keywords, i);
3867 Py_INCREF(kw->arg);
3868 PyTuple_SET_ITEM(names, i, kw->arg);
3869 }
3870 ADDOP_N(c, LOAD_CONST, names, consts);
3871 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3872 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003874 else {
3875 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3876 return 1;
3877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878}
3879
Nick Coghlan650f0d02007-04-15 12:05:43 +00003880
3881/* List and set comprehensions and generator expressions work by creating a
3882 nested function to perform the actual iteration. This means that the
3883 iteration variables don't leak into the current scope.
3884 The defined function is called immediately following its definition, with the
3885 result of that call being the result of the expression.
3886 The LC/SC version returns the populated container, while the GE version is
3887 flagged in symtable.c as a generator, so it returns the generator object
3888 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003889
3890 Possible cleanups:
3891 - iterate over the generator sequence instead of using recursion
3892*/
3893
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003894
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896compiler_comprehension_generator(struct compiler *c,
3897 asdl_seq *generators, int gen_index,
3898 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003900 comprehension_ty gen;
3901 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3902 if (gen->is_async) {
3903 return compiler_async_comprehension_generator(
3904 c, generators, gen_index, elt, val, type);
3905 } else {
3906 return compiler_sync_comprehension_generator(
3907 c, generators, gen_index, elt, val, type);
3908 }
3909}
3910
3911static int
3912compiler_sync_comprehension_generator(struct compiler *c,
3913 asdl_seq *generators, int gen_index,
3914 expr_ty elt, expr_ty val, int type)
3915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 /* generate code for the iterator, then each of the ifs,
3917 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 comprehension_ty gen;
3920 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003921 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 start = compiler_new_block(c);
3924 skip = compiler_new_block(c);
3925 if_cleanup = compiler_new_block(c);
3926 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3929 anchor == NULL)
3930 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 if (gen_index == 0) {
3935 /* Receive outermost iter as an implicit argument */
3936 c->u->u_argcount = 1;
3937 ADDOP_I(c, LOAD_FAST, 0);
3938 }
3939 else {
3940 /* Sub-iter - calculate on the fly */
3941 VISIT(c, expr, gen->iter);
3942 ADDOP(c, GET_ITER);
3943 }
3944 compiler_use_next_block(c, start);
3945 ADDOP_JREL(c, FOR_ITER, anchor);
3946 NEXT_BLOCK(c);
3947 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 /* XXX this needs to be cleaned up...a lot! */
3950 n = asdl_seq_LEN(gen->ifs);
3951 for (i = 0; i < n; i++) {
3952 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003953 if (!compiler_jump_if(c, e, if_cleanup, 0))
3954 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 NEXT_BLOCK(c);
3956 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 if (++gen_index < asdl_seq_LEN(generators))
3959 if (!compiler_comprehension_generator(c,
3960 generators, gen_index,
3961 elt, val, type))
3962 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 /* only append after the last for generator */
3965 if (gen_index >= asdl_seq_LEN(generators)) {
3966 /* comprehension specific code */
3967 switch (type) {
3968 case COMP_GENEXP:
3969 VISIT(c, expr, elt);
3970 ADDOP(c, YIELD_VALUE);
3971 ADDOP(c, POP_TOP);
3972 break;
3973 case COMP_LISTCOMP:
3974 VISIT(c, expr, elt);
3975 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3976 break;
3977 case COMP_SETCOMP:
3978 VISIT(c, expr, elt);
3979 ADDOP_I(c, SET_ADD, gen_index + 1);
3980 break;
3981 case COMP_DICTCOMP:
3982 /* With 'd[k] = v', v is evaluated before k, so we do
3983 the same. */
3984 VISIT(c, expr, val);
3985 VISIT(c, expr, elt);
3986 ADDOP_I(c, MAP_ADD, gen_index + 1);
3987 break;
3988 default:
3989 return 0;
3990 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 compiler_use_next_block(c, skip);
3993 }
3994 compiler_use_next_block(c, if_cleanup);
3995 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3996 compiler_use_next_block(c, anchor);
3997
3998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003999}
4000
4001static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004002compiler_async_comprehension_generator(struct compiler *c,
4003 asdl_seq *generators, int gen_index,
4004 expr_ty elt, expr_ty val, int type)
4005{
4006 _Py_IDENTIFIER(StopAsyncIteration);
4007
4008 comprehension_ty gen;
Serhiy Storchaka67ee0772018-03-10 18:49:26 +02004009 basicblock *anchor, *if_cleanup, *try,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004010 *after_try, *except, *try_cleanup;
4011 Py_ssize_t i, n;
4012
4013 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
4014 if (stop_aiter_error == NULL) {
4015 return 0;
4016 }
4017
4018 try = compiler_new_block(c);
4019 after_try = compiler_new_block(c);
4020 try_cleanup = compiler_new_block(c);
4021 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004022 if_cleanup = compiler_new_block(c);
4023 anchor = compiler_new_block(c);
4024
Serhiy Storchaka67ee0772018-03-10 18:49:26 +02004025 if (if_cleanup == NULL || anchor == NULL ||
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004026 try == NULL || after_try == NULL ||
Serhiy Storchaka67ee0772018-03-10 18:49:26 +02004027 except == NULL || try_cleanup == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004028 return 0;
4029 }
4030
4031 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4032
4033 if (gen_index == 0) {
4034 /* Receive outermost iter as an implicit argument */
4035 c->u->u_argcount = 1;
4036 ADDOP_I(c, LOAD_FAST, 0);
4037 }
4038 else {
4039 /* Sub-iter - calculate on the fly */
4040 VISIT(c, expr, gen->iter);
4041 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004042 }
4043
4044 compiler_use_next_block(c, try);
4045
4046
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004047 ADDOP_JREL(c, SETUP_FINALLY, except);
4048 if (!compiler_push_fblock(c, EXCEPT, try, NULL))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004049 return 0;
4050
4051 ADDOP(c, GET_ANEXT);
4052 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4053 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004054 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004055 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004056 compiler_pop_fblock(c, EXCEPT, try);
4057 ADDOP_JREL(c, JUMP_FORWARD, after_try);
4058
4059
4060 compiler_use_next_block(c, except);
4061 ADDOP(c, DUP_TOP);
4062 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
4063 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
4064 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
4065
4066 ADDOP(c, POP_TOP);
4067 ADDOP(c, POP_TOP);
4068 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004069 ADDOP(c, POP_EXCEPT); /* for SETUP_FINALLY */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004070 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
4071
4072
4073 compiler_use_next_block(c, try_cleanup);
4074 ADDOP(c, END_FINALLY);
4075
4076 compiler_use_next_block(c, after_try);
4077
4078 n = asdl_seq_LEN(gen->ifs);
4079 for (i = 0; i < n; i++) {
4080 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004081 if (!compiler_jump_if(c, e, if_cleanup, 0))
4082 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004083 NEXT_BLOCK(c);
4084 }
4085
4086 if (++gen_index < asdl_seq_LEN(generators))
4087 if (!compiler_comprehension_generator(c,
4088 generators, gen_index,
4089 elt, val, type))
4090 return 0;
4091
4092 /* only append after the last for generator */
4093 if (gen_index >= asdl_seq_LEN(generators)) {
4094 /* comprehension specific code */
4095 switch (type) {
4096 case COMP_GENEXP:
4097 VISIT(c, expr, elt);
4098 ADDOP(c, YIELD_VALUE);
4099 ADDOP(c, POP_TOP);
4100 break;
4101 case COMP_LISTCOMP:
4102 VISIT(c, expr, elt);
4103 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4104 break;
4105 case COMP_SETCOMP:
4106 VISIT(c, expr, elt);
4107 ADDOP_I(c, SET_ADD, gen_index + 1);
4108 break;
4109 case COMP_DICTCOMP:
4110 /* With 'd[k] = v', v is evaluated before k, so we do
4111 the same. */
4112 VISIT(c, expr, val);
4113 VISIT(c, expr, elt);
4114 ADDOP_I(c, MAP_ADD, gen_index + 1);
4115 break;
4116 default:
4117 return 0;
4118 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004119 }
4120 compiler_use_next_block(c, if_cleanup);
4121 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
4122 compiler_use_next_block(c, anchor);
4123 ADDOP(c, POP_TOP);
4124
4125 return 1;
4126}
4127
4128static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004129compiler_comprehension(struct compiler *c, expr_ty e, int type,
4130 identifier name, asdl_seq *generators, expr_ty elt,
4131 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004134 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004135 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004136 int is_async_function = c->u->u_ste->ste_coroutine;
4137 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004138
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004139 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004140
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004141 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4142 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004143 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004145 }
4146
4147 is_async_generator = c->u->u_ste->ste_coroutine;
4148
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004149 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004150 if (e->lineno > c->u->u_lineno) {
4151 c->u->u_lineno = e->lineno;
4152 c->u->u_lineno_set = 0;
4153 }
4154 compiler_error(c, "asynchronous comprehension outside of "
4155 "an asynchronous function");
4156 goto error_in_scope;
4157 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 if (type != COMP_GENEXP) {
4160 int op;
4161 switch (type) {
4162 case COMP_LISTCOMP:
4163 op = BUILD_LIST;
4164 break;
4165 case COMP_SETCOMP:
4166 op = BUILD_SET;
4167 break;
4168 case COMP_DICTCOMP:
4169 op = BUILD_MAP;
4170 break;
4171 default:
4172 PyErr_Format(PyExc_SystemError,
4173 "unknown comprehension type %d", type);
4174 goto error_in_scope;
4175 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 ADDOP_I(c, op, 0);
4178 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 if (!compiler_comprehension_generator(c, generators, 0, elt,
4181 val, type))
4182 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 if (type != COMP_GENEXP) {
4185 ADDOP(c, RETURN_VALUE);
4186 }
4187
4188 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004189 qualname = c->u->u_qualname;
4190 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004192 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 goto error;
4194
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004195 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004197 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 Py_DECREF(co);
4199
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004200 VISIT(c, expr, outermost->iter);
4201
4202 if (outermost->is_async) {
4203 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004204 } else {
4205 ADDOP(c, GET_ITER);
4206 }
4207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004209
4210 if (is_async_generator && type != COMP_GENEXP) {
4211 ADDOP(c, GET_AWAITABLE);
4212 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4213 ADDOP(c, YIELD_FROM);
4214 }
4215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004217error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004219error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004220 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 Py_XDECREF(co);
4222 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004223}
4224
4225static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226compiler_genexp(struct compiler *c, expr_ty e)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 static identifier name;
4229 if (!name) {
4230 name = PyUnicode_FromString("<genexpr>");
4231 if (!name)
4232 return 0;
4233 }
4234 assert(e->kind == GeneratorExp_kind);
4235 return compiler_comprehension(c, e, COMP_GENEXP, name,
4236 e->v.GeneratorExp.generators,
4237 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004238}
4239
4240static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004241compiler_listcomp(struct compiler *c, expr_ty e)
4242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 static identifier name;
4244 if (!name) {
4245 name = PyUnicode_FromString("<listcomp>");
4246 if (!name)
4247 return 0;
4248 }
4249 assert(e->kind == ListComp_kind);
4250 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4251 e->v.ListComp.generators,
4252 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004253}
4254
4255static int
4256compiler_setcomp(struct compiler *c, expr_ty e)
4257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 static identifier name;
4259 if (!name) {
4260 name = PyUnicode_FromString("<setcomp>");
4261 if (!name)
4262 return 0;
4263 }
4264 assert(e->kind == SetComp_kind);
4265 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4266 e->v.SetComp.generators,
4267 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004268}
4269
4270
4271static int
4272compiler_dictcomp(struct compiler *c, expr_ty e)
4273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 static identifier name;
4275 if (!name) {
4276 name = PyUnicode_FromString("<dictcomp>");
4277 if (!name)
4278 return 0;
4279 }
4280 assert(e->kind == DictComp_kind);
4281 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4282 e->v.DictComp.generators,
4283 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004284}
4285
4286
4287static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004288compiler_visit_keyword(struct compiler *c, keyword_ty k)
4289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 VISIT(c, expr, k->value);
4291 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292}
4293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295 whether they are true or false.
4296
4297 Return values: 1 for true, 0 for false, -1 for non-constant.
4298 */
4299
4300static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004301expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004302{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004303 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004304 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004305 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004306 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004307}
4308
Yury Selivanov75445082015-05-11 22:57:16 -04004309
4310/*
4311 Implements the async with statement.
4312
4313 The semantics outlined in that PEP are as follows:
4314
4315 async with EXPR as VAR:
4316 BLOCK
4317
4318 It is implemented roughly as:
4319
4320 context = EXPR
4321 exit = context.__aexit__ # not calling it
4322 value = await context.__aenter__()
4323 try:
4324 VAR = value # if VAR present in the syntax
4325 BLOCK
4326 finally:
4327 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004328 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004329 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004330 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004331 if not (await exit(*exc)):
4332 raise
4333 */
4334static int
4335compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4336{
4337 basicblock *block, *finally;
4338 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4339
4340 assert(s->kind == AsyncWith_kind);
4341
4342 block = compiler_new_block(c);
4343 finally = compiler_new_block(c);
4344 if (!block || !finally)
4345 return 0;
4346
4347 /* Evaluate EXPR */
4348 VISIT(c, expr, item->context_expr);
4349
4350 ADDOP(c, BEFORE_ASYNC_WITH);
4351 ADDOP(c, GET_AWAITABLE);
4352 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4353 ADDOP(c, YIELD_FROM);
4354
4355 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4356
4357 /* SETUP_ASYNC_WITH pushes a finally block. */
4358 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004359 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004360 return 0;
4361 }
4362
4363 if (item->optional_vars) {
4364 VISIT(c, expr, item->optional_vars);
4365 }
4366 else {
4367 /* Discard result from context.__aenter__() */
4368 ADDOP(c, POP_TOP);
4369 }
4370
4371 pos++;
4372 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4373 /* BLOCK code */
4374 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4375 else if (!compiler_async_with(c, s, pos))
4376 return 0;
4377
4378 /* End of try block; start the finally block */
4379 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004380 ADDOP(c, BEGIN_FINALLY);
4381 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004382
Yury Selivanov75445082015-05-11 22:57:16 -04004383 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004384 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004385 return 0;
4386
4387 /* Finally block starts; context.__exit__ is on the stack under
4388 the exception or return information. Just issue our magic
4389 opcode. */
4390 ADDOP(c, WITH_CLEANUP_START);
4391
4392 ADDOP(c, GET_AWAITABLE);
4393 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4394 ADDOP(c, YIELD_FROM);
4395
4396 ADDOP(c, WITH_CLEANUP_FINISH);
4397
4398 /* Finally block ends. */
4399 ADDOP(c, END_FINALLY);
4400 compiler_pop_fblock(c, FINALLY_END, finally);
4401 return 1;
4402}
4403
4404
Guido van Rossumc2e20742006-02-27 22:32:47 +00004405/*
4406 Implements the with statement from PEP 343.
4407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004409
4410 with EXPR as VAR:
4411 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412
Guido van Rossumc2e20742006-02-27 22:32:47 +00004413 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414
Thomas Wouters477c8d52006-05-27 19:21:47 +00004415 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004416 exit = context.__exit__ # not calling it
4417 value = context.__enter__()
4418 try:
4419 VAR = value # if VAR present in the syntax
4420 BLOCK
4421 finally:
4422 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004423 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004424 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004425 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004426 exit(*exc)
4427 */
4428static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004429compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004430{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004431 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004432 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004433
4434 assert(s->kind == With_kind);
4435
Guido van Rossumc2e20742006-02-27 22:32:47 +00004436 block = compiler_new_block(c);
4437 finally = compiler_new_block(c);
4438 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004439 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004440
Thomas Wouters477c8d52006-05-27 19:21:47 +00004441 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004442 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004443 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004444
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004445 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004446 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004447 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004448 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004449 }
4450
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004451 if (item->optional_vars) {
4452 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004453 }
4454 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004456 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004457 }
4458
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004459 pos++;
4460 if (pos == asdl_seq_LEN(s->v.With.items))
4461 /* BLOCK code */
4462 VISIT_SEQ(c, stmt, s->v.With.body)
4463 else if (!compiler_with(c, s, pos))
4464 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004465
4466 /* End of try block; start the finally block */
4467 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004468 ADDOP(c, BEGIN_FINALLY);
4469 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004470
Guido van Rossumc2e20742006-02-27 22:32:47 +00004471 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004472 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004473 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004474
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004475 /* Finally block starts; context.__exit__ is on the stack under
4476 the exception or return information. Just issue our magic
4477 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004478 ADDOP(c, WITH_CLEANUP_START);
4479 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004480
4481 /* Finally block ends. */
4482 ADDOP(c, END_FINALLY);
4483 compiler_pop_fblock(c, FINALLY_END, finally);
4484 return 1;
4485}
4486
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004487static int
4488compiler_visit_expr(struct compiler *c, expr_ty e)
4489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 /* If expr e has a different line number than the last expr/stmt,
4491 set a new line number for the next instruction.
4492 */
4493 if (e->lineno > c->u->u_lineno) {
4494 c->u->u_lineno = e->lineno;
4495 c->u->u_lineno_set = 0;
4496 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004497 /* Updating the column offset is always harmless. */
4498 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 switch (e->kind) {
4500 case BoolOp_kind:
4501 return compiler_boolop(c, e);
4502 case BinOp_kind:
4503 VISIT(c, expr, e->v.BinOp.left);
4504 VISIT(c, expr, e->v.BinOp.right);
4505 ADDOP(c, binop(c, e->v.BinOp.op));
4506 break;
4507 case UnaryOp_kind:
4508 VISIT(c, expr, e->v.UnaryOp.operand);
4509 ADDOP(c, unaryop(e->v.UnaryOp.op));
4510 break;
4511 case Lambda_kind:
4512 return compiler_lambda(c, e);
4513 case IfExp_kind:
4514 return compiler_ifexp(c, e);
4515 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004516 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004518 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 case GeneratorExp_kind:
4520 return compiler_genexp(c, e);
4521 case ListComp_kind:
4522 return compiler_listcomp(c, e);
4523 case SetComp_kind:
4524 return compiler_setcomp(c, e);
4525 case DictComp_kind:
4526 return compiler_dictcomp(c, e);
4527 case Yield_kind:
4528 if (c->u->u_ste->ste_type != FunctionBlock)
4529 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004530 if (e->v.Yield.value) {
4531 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 }
4533 else {
4534 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4535 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004536 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004538 case YieldFrom_kind:
4539 if (c->u->u_ste->ste_type != FunctionBlock)
4540 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004541
4542 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4543 return compiler_error(c, "'yield from' inside async function");
4544
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004545 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004546 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004547 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4548 ADDOP(c, YIELD_FROM);
4549 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004550 case Await_kind:
4551 if (c->u->u_ste->ste_type != FunctionBlock)
4552 return compiler_error(c, "'await' outside function");
4553
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4555 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004556 return compiler_error(c, "'await' outside async function");
4557
4558 VISIT(c, expr, e->v.Await.value);
4559 ADDOP(c, GET_AWAITABLE);
4560 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4561 ADDOP(c, YIELD_FROM);
4562 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 case Compare_kind:
4564 return compiler_compare(c, e);
4565 case Call_kind:
4566 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004567 case Constant_kind:
4568 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4569 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 case Num_kind:
4571 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4572 break;
4573 case Str_kind:
4574 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4575 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004576 case JoinedStr_kind:
4577 return compiler_joined_str(c, e);
4578 case FormattedValue_kind:
4579 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 case Bytes_kind:
4581 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4582 break;
4583 case Ellipsis_kind:
4584 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4585 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004586 case NameConstant_kind:
4587 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4588 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 /* The following exprs can be assignment targets. */
4590 case Attribute_kind:
4591 if (e->v.Attribute.ctx != AugStore)
4592 VISIT(c, expr, e->v.Attribute.value);
4593 switch (e->v.Attribute.ctx) {
4594 case AugLoad:
4595 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004596 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 case Load:
4598 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4599 break;
4600 case AugStore:
4601 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004602 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 case Store:
4604 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4605 break;
4606 case Del:
4607 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4608 break;
4609 case Param:
4610 default:
4611 PyErr_SetString(PyExc_SystemError,
4612 "param invalid in attribute expression");
4613 return 0;
4614 }
4615 break;
4616 case Subscript_kind:
4617 switch (e->v.Subscript.ctx) {
4618 case AugLoad:
4619 VISIT(c, expr, e->v.Subscript.value);
4620 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4621 break;
4622 case Load:
4623 VISIT(c, expr, e->v.Subscript.value);
4624 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4625 break;
4626 case AugStore:
4627 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4628 break;
4629 case Store:
4630 VISIT(c, expr, e->v.Subscript.value);
4631 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4632 break;
4633 case Del:
4634 VISIT(c, expr, e->v.Subscript.value);
4635 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4636 break;
4637 case Param:
4638 default:
4639 PyErr_SetString(PyExc_SystemError,
4640 "param invalid in subscript expression");
4641 return 0;
4642 }
4643 break;
4644 case Starred_kind:
4645 switch (e->v.Starred.ctx) {
4646 case Store:
4647 /* In all legitimate cases, the Starred node was already replaced
4648 * by compiler_list/compiler_tuple. XXX: is that okay? */
4649 return compiler_error(c,
4650 "starred assignment target must be in a list or tuple");
4651 default:
4652 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004653 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 }
4655 break;
4656 case Name_kind:
4657 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4658 /* child nodes of List and Tuple will have expr_context set */
4659 case List_kind:
4660 return compiler_list(c, e);
4661 case Tuple_kind:
4662 return compiler_tuple(c, e);
4663 }
4664 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004665}
4666
4667static int
4668compiler_augassign(struct compiler *c, stmt_ty s)
4669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 expr_ty e = s->v.AugAssign.target;
4671 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 switch (e->kind) {
4676 case Attribute_kind:
4677 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4678 AugLoad, e->lineno, e->col_offset, c->c_arena);
4679 if (auge == NULL)
4680 return 0;
4681 VISIT(c, expr, auge);
4682 VISIT(c, expr, s->v.AugAssign.value);
4683 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4684 auge->v.Attribute.ctx = AugStore;
4685 VISIT(c, expr, auge);
4686 break;
4687 case Subscript_kind:
4688 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4689 AugLoad, e->lineno, e->col_offset, c->c_arena);
4690 if (auge == NULL)
4691 return 0;
4692 VISIT(c, expr, auge);
4693 VISIT(c, expr, s->v.AugAssign.value);
4694 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4695 auge->v.Subscript.ctx = AugStore;
4696 VISIT(c, expr, auge);
4697 break;
4698 case Name_kind:
4699 if (!compiler_nameop(c, e->v.Name.id, Load))
4700 return 0;
4701 VISIT(c, expr, s->v.AugAssign.value);
4702 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4703 return compiler_nameop(c, e->v.Name.id, Store);
4704 default:
4705 PyErr_Format(PyExc_SystemError,
4706 "invalid node type (%d) for augmented assignment",
4707 e->kind);
4708 return 0;
4709 }
4710 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711}
4712
4713static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004714check_ann_expr(struct compiler *c, expr_ty e)
4715{
4716 VISIT(c, expr, e);
4717 ADDOP(c, POP_TOP);
4718 return 1;
4719}
4720
4721static int
4722check_annotation(struct compiler *c, stmt_ty s)
4723{
4724 /* Annotations are only evaluated in a module or class. */
4725 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4726 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4727 return check_ann_expr(c, s->v.AnnAssign.annotation);
4728 }
4729 return 1;
4730}
4731
4732static int
4733check_ann_slice(struct compiler *c, slice_ty sl)
4734{
4735 switch(sl->kind) {
4736 case Index_kind:
4737 return check_ann_expr(c, sl->v.Index.value);
4738 case Slice_kind:
4739 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4740 return 0;
4741 }
4742 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4743 return 0;
4744 }
4745 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4746 return 0;
4747 }
4748 break;
4749 default:
4750 PyErr_SetString(PyExc_SystemError,
4751 "unexpected slice kind");
4752 return 0;
4753 }
4754 return 1;
4755}
4756
4757static int
4758check_ann_subscr(struct compiler *c, slice_ty sl)
4759{
4760 /* We check that everything in a subscript is defined at runtime. */
4761 Py_ssize_t i, n;
4762
4763 switch (sl->kind) {
4764 case Index_kind:
4765 case Slice_kind:
4766 if (!check_ann_slice(c, sl)) {
4767 return 0;
4768 }
4769 break;
4770 case ExtSlice_kind:
4771 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4772 for (i = 0; i < n; i++) {
4773 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4774 switch (subsl->kind) {
4775 case Index_kind:
4776 case Slice_kind:
4777 if (!check_ann_slice(c, subsl)) {
4778 return 0;
4779 }
4780 break;
4781 case ExtSlice_kind:
4782 default:
4783 PyErr_SetString(PyExc_SystemError,
4784 "extended slice invalid in nested slice");
4785 return 0;
4786 }
4787 }
4788 break;
4789 default:
4790 PyErr_Format(PyExc_SystemError,
4791 "invalid subscript kind %d", sl->kind);
4792 return 0;
4793 }
4794 return 1;
4795}
4796
4797static int
4798compiler_annassign(struct compiler *c, stmt_ty s)
4799{
4800 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004801 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004802
4803 assert(s->kind == AnnAssign_kind);
4804
4805 /* We perform the actual assignment first. */
4806 if (s->v.AnnAssign.value) {
4807 VISIT(c, expr, s->v.AnnAssign.value);
4808 VISIT(c, expr, targ);
4809 }
4810 switch (targ->kind) {
4811 case Name_kind:
4812 /* If we have a simple name in a module or class, store annotation. */
4813 if (s->v.AnnAssign.simple &&
4814 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4815 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004816 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4817 if (!mangled) {
4818 return 0;
4819 }
Guido van Rossum95e4d582018-01-26 08:20:18 -08004820 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4821 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4822 }
4823 else {
4824 VISIT(c, expr, s->v.AnnAssign.annotation);
4825 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004826 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
4827 ADDOP_O(c, LOAD_CONST, mangled, consts);
4828 Py_DECREF(mangled);
4829 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004830 }
4831 break;
4832 case Attribute_kind:
4833 if (!s->v.AnnAssign.value &&
4834 !check_ann_expr(c, targ->v.Attribute.value)) {
4835 return 0;
4836 }
4837 break;
4838 case Subscript_kind:
4839 if (!s->v.AnnAssign.value &&
4840 (!check_ann_expr(c, targ->v.Subscript.value) ||
4841 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4842 return 0;
4843 }
4844 break;
4845 default:
4846 PyErr_Format(PyExc_SystemError,
4847 "invalid node type (%d) for annotated assignment",
4848 targ->kind);
4849 return 0;
4850 }
4851 /* Annotation is evaluated last. */
4852 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4853 return 0;
4854 }
4855 return 1;
4856}
4857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004858/* Raises a SyntaxError and returns 0.
4859 If something goes wrong, a different exception may be raised.
4860*/
4861
4862static int
4863compiler_error(struct compiler *c, const char *errstr)
4864{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004865 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004867
Victor Stinner14e461d2013-08-26 22:28:21 +02004868 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 if (!loc) {
4870 Py_INCREF(Py_None);
4871 loc = Py_None;
4872 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004873 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004874 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 if (!u)
4876 goto exit;
4877 v = Py_BuildValue("(zO)", errstr, u);
4878 if (!v)
4879 goto exit;
4880 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004881 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 Py_DECREF(loc);
4883 Py_XDECREF(u);
4884 Py_XDECREF(v);
4885 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004886}
4887
4888static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889compiler_handle_subscr(struct compiler *c, const char *kind,
4890 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 /* XXX this code is duplicated */
4895 switch (ctx) {
4896 case AugLoad: /* fall through to Load */
4897 case Load: op = BINARY_SUBSCR; break;
4898 case AugStore:/* fall through to Store */
4899 case Store: op = STORE_SUBSCR; break;
4900 case Del: op = DELETE_SUBSCR; break;
4901 case Param:
4902 PyErr_Format(PyExc_SystemError,
4903 "invalid %s kind %d in subscript\n",
4904 kind, ctx);
4905 return 0;
4906 }
4907 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004908 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 }
4910 else if (ctx == AugStore) {
4911 ADDOP(c, ROT_THREE);
4912 }
4913 ADDOP(c, op);
4914 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004915}
4916
4917static int
4918compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 int n = 2;
4921 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004923 /* only handles the cases where BUILD_SLICE is emitted */
4924 if (s->v.Slice.lower) {
4925 VISIT(c, expr, s->v.Slice.lower);
4926 }
4927 else {
4928 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4929 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 if (s->v.Slice.upper) {
4932 VISIT(c, expr, s->v.Slice.upper);
4933 }
4934 else {
4935 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4936 }
4937
4938 if (s->v.Slice.step) {
4939 n++;
4940 VISIT(c, expr, s->v.Slice.step);
4941 }
4942 ADDOP_I(c, BUILD_SLICE, n);
4943 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944}
4945
4946static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4948 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 switch (s->kind) {
4951 case Slice_kind:
4952 return compiler_slice(c, s, ctx);
4953 case Index_kind:
4954 VISIT(c, expr, s->v.Index.value);
4955 break;
4956 case ExtSlice_kind:
4957 default:
4958 PyErr_SetString(PyExc_SystemError,
4959 "extended slice invalid in nested slice");
4960 return 0;
4961 }
4962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004963}
4964
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004965static int
4966compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4967{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004968 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 switch (s->kind) {
4970 case Index_kind:
4971 kindname = "index";
4972 if (ctx != AugStore) {
4973 VISIT(c, expr, s->v.Index.value);
4974 }
4975 break;
4976 case Slice_kind:
4977 kindname = "slice";
4978 if (ctx != AugStore) {
4979 if (!compiler_slice(c, s, ctx))
4980 return 0;
4981 }
4982 break;
4983 case ExtSlice_kind:
4984 kindname = "extended slice";
4985 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004986 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 for (i = 0; i < n; i++) {
4988 slice_ty sub = (slice_ty)asdl_seq_GET(
4989 s->v.ExtSlice.dims, i);
4990 if (!compiler_visit_nested_slice(c, sub, ctx))
4991 return 0;
4992 }
4993 ADDOP_I(c, BUILD_TUPLE, n);
4994 }
4995 break;
4996 default:
4997 PyErr_Format(PyExc_SystemError,
4998 "invalid subscript kind %d", s->kind);
4999 return 0;
5000 }
5001 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005002}
5003
Thomas Wouters89f507f2006-12-13 04:49:30 +00005004/* End of the compiler section, beginning of the assembler section */
5005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005006/* do depth-first search of basic block graph, starting with block.
5007 post records the block indices in post-order.
5008
5009 XXX must handle implicit jumps from one block to next
5010*/
5011
Thomas Wouters89f507f2006-12-13 04:49:30 +00005012struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 PyObject *a_bytecode; /* string containing bytecode */
5014 int a_offset; /* offset into bytecode */
5015 int a_nblocks; /* number of reachable blocks */
5016 basicblock **a_postorder; /* list of blocks in dfs postorder */
5017 PyObject *a_lnotab; /* string containing lnotab */
5018 int a_lnotab_off; /* offset into lnotab */
5019 int a_lineno; /* last lineno of emitted instruction */
5020 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005021};
5022
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005023static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005024dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005025{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005026 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005027
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005028 /* Get rid of recursion for normal control flow.
5029 Since the number of blocks is limited, unused space in a_postorder
5030 (from a_nblocks to end) can be used as a stack for still not ordered
5031 blocks. */
5032 for (j = end; b && !b->b_seen; b = b->b_next) {
5033 b->b_seen = 1;
5034 assert(a->a_nblocks < j);
5035 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005037 while (j < end) {
5038 b = a->a_postorder[j++];
5039 for (i = 0; i < b->b_iused; i++) {
5040 struct instr *instr = &b->b_instr[i];
5041 if (instr->i_jrel || instr->i_jabs)
5042 dfs(c, instr->i_target, a, j);
5043 }
5044 assert(a->a_nblocks < j);
5045 a->a_postorder[a->a_nblocks++] = b;
5046 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005047}
5048
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005049Py_LOCAL_INLINE(void)
5050stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005051{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005052 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005053 if (b->b_startdepth < depth) {
5054 assert(b->b_startdepth < 0);
5055 b->b_startdepth = depth;
5056 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005057 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005058}
5059
5060/* Find the flow path that needs the largest stack. We assume that
5061 * cycles in the flow graph have no net effect on the stack depth.
5062 */
5063static int
5064stackdepth(struct compiler *c)
5065{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005066 basicblock *b, *entryblock = NULL;
5067 basicblock **stack, **sp;
5068 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 b->b_startdepth = INT_MIN;
5071 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005072 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 }
5074 if (!entryblock)
5075 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005076 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5077 if (!stack) {
5078 PyErr_NoMemory();
5079 return -1;
5080 }
5081
5082 sp = stack;
5083 stackdepth_push(&sp, entryblock, 0);
5084 while (sp != stack) {
5085 b = *--sp;
5086 int depth = b->b_startdepth;
5087 assert(depth >= 0);
5088 basicblock *next = b->b_next;
5089 for (int i = 0; i < b->b_iused; i++) {
5090 struct instr *instr = &b->b_instr[i];
5091 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5092 if (effect == PY_INVALID_STACK_EFFECT) {
5093 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5094 Py_FatalError("PyCompile_OpcodeStackEffect()");
5095 }
5096 int new_depth = depth + effect;
5097 if (new_depth > maxdepth) {
5098 maxdepth = new_depth;
5099 }
5100 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5101 if (instr->i_jrel || instr->i_jabs) {
5102 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5103 assert(effect != PY_INVALID_STACK_EFFECT);
5104 int target_depth = depth + effect;
5105 if (target_depth > maxdepth) {
5106 maxdepth = target_depth;
5107 }
5108 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005109 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005110 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005111 assert(instr->i_target->b_startdepth >= target_depth);
5112 depth = new_depth;
5113 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005114 }
5115 stackdepth_push(&sp, instr->i_target, target_depth);
5116 }
5117 depth = new_depth;
5118 if (instr->i_opcode == JUMP_ABSOLUTE ||
5119 instr->i_opcode == JUMP_FORWARD ||
5120 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005121 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005122 {
5123 /* remaining code is dead */
5124 next = NULL;
5125 break;
5126 }
5127 }
5128 if (next != NULL) {
5129 stackdepth_push(&sp, next, depth);
5130 }
5131 }
5132 PyObject_Free(stack);
5133 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005134}
5135
5136static int
5137assemble_init(struct assembler *a, int nblocks, int firstlineno)
5138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 memset(a, 0, sizeof(struct assembler));
5140 a->a_lineno = firstlineno;
5141 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5142 if (!a->a_bytecode)
5143 return 0;
5144 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5145 if (!a->a_lnotab)
5146 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005147 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 PyErr_NoMemory();
5149 return 0;
5150 }
5151 a->a_postorder = (basicblock **)PyObject_Malloc(
5152 sizeof(basicblock *) * nblocks);
5153 if (!a->a_postorder) {
5154 PyErr_NoMemory();
5155 return 0;
5156 }
5157 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005158}
5159
5160static void
5161assemble_free(struct assembler *a)
5162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 Py_XDECREF(a->a_bytecode);
5164 Py_XDECREF(a->a_lnotab);
5165 if (a->a_postorder)
5166 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005167}
5168
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005169static int
5170blocksize(basicblock *b)
5171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 int i;
5173 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005176 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005178}
5179
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005180/* Appends a pair to the end of the line number table, a_lnotab, representing
5181 the instruction's bytecode offset and line number. See
5182 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005183
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005184static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005185assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005188 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005190
Serhiy Storchakaab874002016-09-11 13:48:15 +03005191 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 if(d_bytecode == 0 && d_lineno == 0)
5197 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 if (d_bytecode > 255) {
5200 int j, nbytes, ncodes = d_bytecode / 255;
5201 nbytes = a->a_lnotab_off + 2 * ncodes;
5202 len = PyBytes_GET_SIZE(a->a_lnotab);
5203 if (nbytes >= len) {
5204 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5205 len = nbytes;
5206 else if (len <= INT_MAX / 2)
5207 len *= 2;
5208 else {
5209 PyErr_NoMemory();
5210 return 0;
5211 }
5212 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5213 return 0;
5214 }
5215 lnotab = (unsigned char *)
5216 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5217 for (j = 0; j < ncodes; j++) {
5218 *lnotab++ = 255;
5219 *lnotab++ = 0;
5220 }
5221 d_bytecode -= ncodes * 255;
5222 a->a_lnotab_off += ncodes * 2;
5223 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005224 assert(0 <= d_bytecode && d_bytecode <= 255);
5225
5226 if (d_lineno < -128 || 127 < d_lineno) {
5227 int j, nbytes, ncodes, k;
5228 if (d_lineno < 0) {
5229 k = -128;
5230 /* use division on positive numbers */
5231 ncodes = (-d_lineno) / 128;
5232 }
5233 else {
5234 k = 127;
5235 ncodes = d_lineno / 127;
5236 }
5237 d_lineno -= ncodes * k;
5238 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 nbytes = a->a_lnotab_off + 2 * ncodes;
5240 len = PyBytes_GET_SIZE(a->a_lnotab);
5241 if (nbytes >= len) {
5242 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5243 len = nbytes;
5244 else if (len <= INT_MAX / 2)
5245 len *= 2;
5246 else {
5247 PyErr_NoMemory();
5248 return 0;
5249 }
5250 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5251 return 0;
5252 }
5253 lnotab = (unsigned char *)
5254 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5255 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005256 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 d_bytecode = 0;
5258 for (j = 1; j < ncodes; j++) {
5259 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005260 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 a->a_lnotab_off += ncodes * 2;
5263 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005264 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 len = PyBytes_GET_SIZE(a->a_lnotab);
5267 if (a->a_lnotab_off + 2 >= len) {
5268 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5269 return 0;
5270 }
5271 lnotab = (unsigned char *)
5272 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 a->a_lnotab_off += 2;
5275 if (d_bytecode) {
5276 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005277 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 }
5279 else { /* First line of a block; def stmt, etc. */
5280 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005281 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 }
5283 a->a_lineno = i->i_lineno;
5284 a->a_lineno_off = a->a_offset;
5285 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005286}
5287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005288/* assemble_emit()
5289 Extend the bytecode with a new instruction.
5290 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005291*/
5292
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005293static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005294assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005295{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005296 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005298 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005300 arg = i->i_oparg;
5301 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 if (i->i_lineno && !assemble_lnotab(a, i))
5303 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005304 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 if (len > PY_SSIZE_T_MAX / 2)
5306 return 0;
5307 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5308 return 0;
5309 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005310 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005312 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005314}
5315
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005316static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005320 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005321 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 /* Compute the size of each block and fixup jump args.
5324 Replace block pointer with position in bytecode. */
5325 do {
5326 totsize = 0;
5327 for (i = a->a_nblocks - 1; i >= 0; i--) {
5328 b = a->a_postorder[i];
5329 bsize = blocksize(b);
5330 b->b_offset = totsize;
5331 totsize += bsize;
5332 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005333 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5335 bsize = b->b_offset;
5336 for (i = 0; i < b->b_iused; i++) {
5337 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005338 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 /* Relative jumps are computed relative to
5340 the instruction pointer after fetching
5341 the jump instruction.
5342 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005343 bsize += isize;
5344 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005346 if (instr->i_jrel) {
5347 instr->i_oparg -= bsize;
5348 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005349 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005350 if (instrsize(instr->i_oparg) != isize) {
5351 extended_arg_recompile = 1;
5352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 }
5355 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 /* XXX: This is an awful hack that could hurt performance, but
5358 on the bright side it should work until we come up
5359 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 The issue is that in the first loop blocksize() is called
5362 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005363 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 So we loop until we stop seeing new EXTENDED_ARGs.
5367 The only EXTENDED_ARGs that could be popping up are
5368 ones in jump instructions. So this should converge
5369 fairly quickly.
5370 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005371 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005372}
5373
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005374static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005375dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005378 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 tuple = PyTuple_New(size);
5381 if (tuple == NULL)
5382 return NULL;
5383 while (PyDict_Next(dict, &pos, &k, &v)) {
5384 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005385 /* The keys of the dictionary are tuples. (see compiler_add_o
5386 * and _PyCode_ConstantKey). The object we want is always second,
5387 * though. */
5388 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 Py_INCREF(k);
5390 assert((i - offset) < size);
5391 assert((i - offset) >= 0);
5392 PyTuple_SET_ITEM(tuple, i - offset, k);
5393 }
5394 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005395}
5396
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005397static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005401 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005403 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 if (ste->ste_nested)
5405 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005406 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005408 if (!ste->ste_generator && ste->ste_coroutine)
5409 flags |= CO_COROUTINE;
5410 if (ste->ste_generator && ste->ste_coroutine)
5411 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 if (ste->ste_varargs)
5413 flags |= CO_VARARGS;
5414 if (ste->ste_varkeywords)
5415 flags |= CO_VARKEYWORDS;
5416 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 /* (Only) inherit compilerflags in PyCF_MASK */
5419 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005422}
5423
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005424static PyCodeObject *
5425makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 PyObject *tmp;
5428 PyCodeObject *co = NULL;
5429 PyObject *consts = NULL;
5430 PyObject *names = NULL;
5431 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 PyObject *name = NULL;
5433 PyObject *freevars = NULL;
5434 PyObject *cellvars = NULL;
5435 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005436 Py_ssize_t nlocals;
5437 int nlocals_int;
5438 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 tmp = dict_keys_inorder(c->u->u_consts, 0);
5442 if (!tmp)
5443 goto error;
5444 consts = PySequence_List(tmp); /* optimize_code requires a list */
5445 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 names = dict_keys_inorder(c->u->u_names, 0);
5448 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5449 if (!consts || !names || !varnames)
5450 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5453 if (!cellvars)
5454 goto error;
5455 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5456 if (!freevars)
5457 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005458
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005459 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005460 assert(nlocals < INT_MAX);
5461 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 flags = compute_code_flags(c);
5464 if (flags < 0)
5465 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5468 if (!bytecode)
5469 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5472 if (!tmp)
5473 goto error;
5474 Py_DECREF(consts);
5475 consts = tmp;
5476
Victor Stinnerf8e32212013-11-19 23:56:34 +01005477 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5478 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005479 maxdepth = stackdepth(c);
5480 if (maxdepth < 0) {
5481 goto error;
5482 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005483 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005484 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 bytecode, consts, names, varnames,
5486 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005487 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 c->u->u_firstlineno,
5489 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005490 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 Py_XDECREF(consts);
5492 Py_XDECREF(names);
5493 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 Py_XDECREF(name);
5495 Py_XDECREF(freevars);
5496 Py_XDECREF(cellvars);
5497 Py_XDECREF(bytecode);
5498 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005499}
5500
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005501
5502/* For debugging purposes only */
5503#if 0
5504static void
5505dump_instr(const struct instr *i)
5506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 const char *jrel = i->i_jrel ? "jrel " : "";
5508 const char *jabs = i->i_jabs ? "jabs " : "";
5509 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005512 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5516 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005517}
5518
5519static void
5520dump_basicblock(const basicblock *b)
5521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 const char *seen = b->b_seen ? "seen " : "";
5523 const char *b_return = b->b_return ? "return " : "";
5524 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5525 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5526 if (b->b_instr) {
5527 int i;
5528 for (i = 0; i < b->b_iused; i++) {
5529 fprintf(stderr, " [%02d] ", i);
5530 dump_instr(b->b_instr + i);
5531 }
5532 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005533}
5534#endif
5535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536static PyCodeObject *
5537assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 basicblock *b, *entryblock;
5540 struct assembler a;
5541 int i, j, nblocks;
5542 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 /* Make sure every block that falls off the end returns None.
5545 XXX NEXT_BLOCK() isn't quite right, because if the last
5546 block ends with a jump or return b_next shouldn't set.
5547 */
5548 if (!c->u->u_curblock->b_return) {
5549 NEXT_BLOCK(c);
5550 if (addNone)
5551 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5552 ADDOP(c, RETURN_VALUE);
5553 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 nblocks = 0;
5556 entryblock = NULL;
5557 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5558 nblocks++;
5559 entryblock = b;
5560 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 /* Set firstlineno if it wasn't explicitly set. */
5563 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005564 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5566 else
5567 c->u->u_firstlineno = 1;
5568 }
5569 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5570 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005571 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 /* Can't modify the bytecode after computing jump offsets. */
5574 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 /* Emit code in reverse postorder from dfs. */
5577 for (i = a.a_nblocks - 1; i >= 0; i--) {
5578 b = a.a_postorder[i];
5579 for (j = 0; j < b->b_iused; j++)
5580 if (!assemble_emit(&a, &b->b_instr[j]))
5581 goto error;
5582 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5585 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005586 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005590 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 assemble_free(&a);
5592 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005593}
Georg Brandl8334fd92010-12-04 10:26:46 +00005594
5595#undef PyAST_Compile
5596PyAPI_FUNC(PyCodeObject *)
5597PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5598 PyArena *arena)
5599{
5600 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5601}