blob: 5f5e65383f9184933234ff4f187f47a9cf8ed01f [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
93
Antoine Pitrou86a36b52011-11-25 18:56:07 +010094enum {
95 COMPILER_SCOPE_MODULE,
96 COMPILER_SCOPE_CLASS,
97 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040098 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040099 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100 COMPILER_SCOPE_COMPREHENSION,
101};
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103/* The following items change on entry and exit of code blocks.
104 They must be saved and restored when returning to a block.
105*/
106struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400110 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100111 int u_scope_type;
112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 /* The following fields are dicts that map objects to
114 the index of them in co_XXX. The index is used as
115 the argument for opcodes that refer to those collections.
116 */
117 PyObject *u_consts; /* all constants */
118 PyObject *u_names; /* all names */
119 PyObject *u_varnames; /* local variables */
120 PyObject *u_cellvars; /* cell variables */
121 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Victor Stinnerf8e32212013-11-19 23:56:34 +0100125 Py_ssize_t u_argcount; /* number of arguments for block */
126 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 /* Pointer to the most recently allocated block. By following b_list
128 members, you can reach all early allocated blocks. */
129 basicblock *u_blocks;
130 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_nfblocks;
133 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_firstlineno; /* the first lineno of the block */
136 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000137 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_lineno_set; /* boolean to indicate whether instr
139 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140};
141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000147
148Note that we don't track recursion levels during compilation - the
149task of detecting and rejecting excessive levels of nesting is
150handled by the symbol analysis pass.
151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152*/
153
154struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200155 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 struct symtable *c_st;
157 PyFutureFeatures *c_future; /* pointer to module's __future__ */
158 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Georg Brandl8334fd92010-12-04 10:26:46 +0000160 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 int c_interactive; /* true if in interactive mode */
162 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 struct compiler_unit *u; /* compiler state for current block */
165 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
166 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167};
168
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100169static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170static void compiler_free(struct compiler *);
171static basicblock *compiler_new_block(struct compiler *);
172static int compiler_next_instr(struct compiler *, basicblock *);
173static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100174static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_error(struct compiler *, const char *);
177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700184static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200189static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500191static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400192static int compiler_async_with(struct compiler *, stmt_ty, int);
193static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100194static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400196 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500197static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400198static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000199
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700200static int compiler_sync_comprehension_generator(
201 struct compiler *c,
202 asdl_seq *generators, int gen_index,
203 expr_ty elt, expr_ty val, int type);
204
205static int compiler_async_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000211static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400213#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 /* Name mangling: __private becomes _classname__private.
219 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200220 PyObject *result;
221 size_t nlen, plen, ipriv;
222 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 PyUnicode_READ_CHAR(ident, 0) != '_' ||
225 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_INCREF(ident);
227 return ident;
228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 nlen = PyUnicode_GET_LENGTH(ident);
230 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 The only time a name with a dot can occur is when
234 we are compiling an import statement that has a
235 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 TODO(jhylton): Decide whether we want to support
238 mangling of the module name, e.g. __M.X.
239 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200240 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
241 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
242 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 Py_INCREF(ident);
244 return ident; /* Don't mangle __whatever__ */
245 }
246 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200247 ipriv = 0;
248 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
249 ipriv++;
250 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 Py_INCREF(ident);
252 return ident; /* Don't mangle if class is just underscores */
253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200254 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Antoine Pitrou55bff892013-04-06 21:21:04 +0200256 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
257 PyErr_SetString(PyExc_OverflowError,
258 "private identifier too large to be mangled");
259 return NULL;
260 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200262 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
263 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
264 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
265
266 result = PyUnicode_New(1 + nlen + plen, maxchar);
267 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200269 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
270 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200271 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
272 Py_DECREF(result);
273 return NULL;
274 }
275 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
276 Py_DECREF(result);
277 return NULL;
278 }
Victor Stinner8f825062012-04-27 13:55:39 +0200279 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000281}
282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283static int
284compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 c->c_stack = PyList_New(0);
289 if (!c->c_stack)
290 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293}
294
295PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200296PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
297 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 struct compiler c;
300 PyCodeObject *co = NULL;
301 PyCompilerFlags local_flags;
302 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!__doc__) {
305 __doc__ = PyUnicode_InternFromString("__doc__");
306 if (!__doc__)
307 return NULL;
308 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000309 if (!__annotations__) {
310 __annotations__ = PyUnicode_InternFromString("__annotations__");
311 if (!__annotations__)
312 return NULL;
313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!compiler_init(&c))
315 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200316 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 c.c_filename = filename;
318 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200319 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (c.c_future == NULL)
321 goto finally;
322 if (!flags) {
323 local_flags.cf_flags = 0;
324 flags = &local_flags;
325 }
326 merged = c.c_future->ff_features | flags->cf_flags;
327 c.c_future->ff_features = merged;
328 flags->cf_flags = merged;
329 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000330 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200333 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900334 goto finally;
335 }
336
Victor Stinner14e461d2013-08-26 22:28:21 +0200337 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (c.c_st == NULL) {
339 if (!PyErr_Occurred())
340 PyErr_SetString(PyExc_SystemError, "no symtable");
341 goto finally;
342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345
Thomas Wouters1175c432006-02-27 22:49:54 +0000346 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 compiler_free(&c);
348 assert(co || PyErr_Occurred());
349 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350}
351
352PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200353PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
354 int optimize, PyArena *arena)
355{
356 PyObject *filename;
357 PyCodeObject *co;
358 filename = PyUnicode_DecodeFSDefault(filename_str);
359 if (filename == NULL)
360 return NULL;
361 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
362 Py_DECREF(filename);
363 return co;
364
365}
366
367PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368PyNode_Compile(struct _node *n, const char *filename)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyCodeObject *co = NULL;
371 mod_ty mod;
372 PyArena *arena = PyArena_New();
373 if (!arena)
374 return NULL;
375 mod = PyAST_FromNode(n, NULL, filename, arena);
376 if (mod)
377 co = PyAST_Compile(mod, filename, NULL, arena);
378 PyArena_Free(arena);
379 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000380}
381
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000382static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (c->c_st)
386 PySymtable_Free(c->c_st);
387 if (c->c_future)
388 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200389 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391}
392
Guido van Rossum79f25d91997-04-29 20:08:16 +0000393static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 Py_ssize_t i, n;
397 PyObject *v, *k;
398 PyObject *dict = PyDict_New();
399 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 n = PyList_Size(list);
402 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100403 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (!v) {
405 Py_DECREF(dict);
406 return NULL;
407 }
408 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300409 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_DECREF(v);
411 Py_DECREF(dict);
412 return NULL;
413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300462 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300469 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_DECREF(item);
472 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return NULL;
474 }
475 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
477 }
Meador Inge2ca63152012-07-18 14:20:11 -0500478 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000480}
481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482static void
483compiler_unit_check(struct compiler_unit *u)
484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 basicblock *block;
486 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700487 assert((uintptr_t)block != 0xcbcbcbcbU);
488 assert((uintptr_t)block != 0xfbfbfbfbU);
489 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (block->b_instr != NULL) {
491 assert(block->b_ialloc > 0);
492 assert(block->b_iused > 0);
493 assert(block->b_ialloc >= block->b_iused);
494 }
495 else {
496 assert (block->b_iused == 0);
497 assert (block->b_ialloc == 0);
498 }
499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500}
501
502static void
503compiler_unit_free(struct compiler_unit *u)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 compiler_unit_check(u);
508 b = u->u_blocks;
509 while (b != NULL) {
510 if (b->b_instr)
511 PyObject_Free((void *)b->b_instr);
512 next = b->b_list;
513 PyObject_Free((void *)b);
514 b = next;
515 }
516 Py_CLEAR(u->u_ste);
517 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400518 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_CLEAR(u->u_consts);
520 Py_CLEAR(u->u_names);
521 Py_CLEAR(u->u_varnames);
522 Py_CLEAR(u->u_freevars);
523 Py_CLEAR(u->u_cellvars);
524 Py_CLEAR(u->u_private);
525 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526}
527
528static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100529compiler_enter_scope(struct compiler *c, identifier name,
530 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100533 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
536 struct compiler_unit));
537 if (!u) {
538 PyErr_NoMemory();
539 return 0;
540 }
541 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100542 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 u->u_argcount = 0;
544 u->u_kwonlyargcount = 0;
545 u->u_ste = PySymtable_Lookup(c->c_st, key);
546 if (!u->u_ste) {
547 compiler_unit_free(u);
548 return 0;
549 }
550 Py_INCREF(name);
551 u->u_name = name;
552 u->u_varnames = list2dict(u->u_ste->ste_varnames);
553 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
554 if (!u->u_varnames || !u->u_cellvars) {
555 compiler_unit_free(u);
556 return 0;
557 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500558 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000559 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500560 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300561 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500562 int res;
563 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200564 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 name = _PyUnicode_FromId(&PyId___class__);
566 if (!name) {
567 compiler_unit_free(u);
568 return 0;
569 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300570 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 if (res < 0) {
572 compiler_unit_free(u);
573 return 0;
574 }
575 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200578 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (!u->u_freevars) {
580 compiler_unit_free(u);
581 return 0;
582 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 u->u_blocks = NULL;
585 u->u_nfblocks = 0;
586 u->u_firstlineno = lineno;
587 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000588 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_lineno_set = 0;
590 u->u_consts = PyDict_New();
591 if (!u->u_consts) {
592 compiler_unit_free(u);
593 return 0;
594 }
595 u->u_names = PyDict_New();
596 if (!u->u_names) {
597 compiler_unit_free(u);
598 return 0;
599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 /* Push the old compiler_unit on the stack. */
604 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400605 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
607 Py_XDECREF(capsule);
608 compiler_unit_free(u);
609 return 0;
610 }
611 Py_DECREF(capsule);
612 u->u_private = c->u->u_private;
613 Py_XINCREF(u->u_private);
614 }
615 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100618
619 block = compiler_new_block(c);
620 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100622 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400624 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
625 if (!compiler_set_qualname(c))
626 return 0;
627 }
628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630}
631
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000632static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633compiler_exit_scope(struct compiler *c)
634{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100635 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 c->c_nestlevel--;
639 compiler_unit_free(c->u);
640 /* Restore c->u to the parent unit. */
641 n = PyList_GET_SIZE(c->c_stack) - 1;
642 if (n >= 0) {
643 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400644 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 assert(c->u);
646 /* we are deleting from a list so this really shouldn't fail */
647 if (PySequence_DelItem(c->c_stack, n) < 0)
648 Py_FatalError("compiler_exit_scope()");
649 compiler_unit_check(c->u);
650 }
651 else
652 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654}
655
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400656static int
657compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100658{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100659 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400660 _Py_static_string(dot_locals, ".<locals>");
661 Py_ssize_t stack_size;
662 struct compiler_unit *u = c->u;
663 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400667 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400668 if (stack_size > 1) {
669 int scope, force_global = 0;
670 struct compiler_unit *parent;
671 PyObject *mangled, *capsule;
672
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400673 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400674 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 assert(parent);
676
Yury Selivanov75445082015-05-11 22:57:16 -0400677 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
678 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
679 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 assert(u->u_name);
681 mangled = _Py_Mangle(parent->u_private, u->u_name);
682 if (!mangled)
683 return 0;
684 scope = PyST_GetScope(parent->u_ste, mangled);
685 Py_DECREF(mangled);
686 assert(scope != GLOBAL_IMPLICIT);
687 if (scope == GLOBAL_EXPLICIT)
688 force_global = 1;
689 }
690
691 if (!force_global) {
692 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400693 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
695 dot_locals_str = _PyUnicode_FromId(&dot_locals);
696 if (dot_locals_str == NULL)
697 return 0;
698 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
699 if (base == NULL)
700 return 0;
701 }
702 else {
703 Py_INCREF(parent->u_qualname);
704 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400705 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 }
707 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 if (base != NULL) {
710 dot_str = _PyUnicode_FromId(&dot);
711 if (dot_str == NULL) {
712 Py_DECREF(base);
713 return 0;
714 }
715 name = PyUnicode_Concat(base, dot_str);
716 Py_DECREF(base);
717 if (name == NULL)
718 return 0;
719 PyUnicode_Append(&name, u->u_name);
720 if (name == NULL)
721 return 0;
722 }
723 else {
724 Py_INCREF(u->u_name);
725 name = u->u_name;
726 }
727 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730}
731
Eric V. Smith235a6f02015-09-19 14:51:32 -0400732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733/* Allocate a new block and return a pointer to it.
734 Returns NULL on error.
735*/
736
737static basicblock *
738compiler_new_block(struct compiler *c)
739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 basicblock *b;
741 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 u = c->u;
744 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
745 if (b == NULL) {
746 PyErr_NoMemory();
747 return NULL;
748 }
749 memset((void *)b, 0, sizeof(basicblock));
750 /* Extend the singly linked list of blocks with new block. */
751 b->b_list = u->u_blocks;
752 u->u_blocks = b;
753 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754}
755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757compiler_next_block(struct compiler *c)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 basicblock *block = compiler_new_block(c);
760 if (block == NULL)
761 return NULL;
762 c->u->u_curblock->b_next = block;
763 c->u->u_curblock = block;
764 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
767static basicblock *
768compiler_use_next_block(struct compiler *c, basicblock *block)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 assert(block != NULL);
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776/* Returns the offset of the next instruction in the current block's
777 b_instr array. Resizes the b_instr as necessary.
778 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000779*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780
781static int
782compiler_next_instr(struct compiler *c, basicblock *b)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 assert(b != NULL);
785 if (b->b_instr == NULL) {
786 b->b_instr = (struct instr *)PyObject_Malloc(
787 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
788 if (b->b_instr == NULL) {
789 PyErr_NoMemory();
790 return -1;
791 }
792 b->b_ialloc = DEFAULT_BLOCK_SIZE;
793 memset((char *)b->b_instr, 0,
794 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
795 }
796 else if (b->b_iused == b->b_ialloc) {
797 struct instr *tmp;
798 size_t oldsize, newsize;
799 oldsize = b->b_ialloc * sizeof(struct instr);
800 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000801
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700802 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyErr_NoMemory();
804 return -1;
805 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (newsize == 0) {
808 PyErr_NoMemory();
809 return -1;
810 }
811 b->b_ialloc <<= 1;
812 tmp = (struct instr *)PyObject_Realloc(
813 (void *)b->b_instr, newsize);
814 if (tmp == NULL) {
815 PyErr_NoMemory();
816 return -1;
817 }
818 b->b_instr = tmp;
819 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
820 }
821 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822}
823
Christian Heimes2202f872008-02-06 14:31:34 +0000824/* Set the i_lineno member of the instruction at offset off if the
825 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 already been set. If it has been set, the call has no effect.
827
Christian Heimes2202f872008-02-06 14:31:34 +0000828 The line number is reset in the following cases:
829 - when entering a new scope
830 - on each statement
831 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200832 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000833 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836static void
837compiler_set_lineno(struct compiler *c, int off)
838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 basicblock *b;
840 if (c->u->u_lineno_set)
841 return;
842 c->u->u_lineno_set = 1;
843 b = c->u->u_curblock;
844 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845}
846
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200847/* Return the stack effect of opcode with argument oparg.
848
849 Some opcodes have different stack effect when jump to the target and
850 when not jump. The 'jump' parameter specifies the case:
851
852 * 0 -- when not jump
853 * 1 -- when jump
854 * -1 -- maximal
855 */
856/* XXX Make the stack effect of WITH_CLEANUP_START and
857 WITH_CLEANUP_FINISH deterministic. */
858static int
859stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 switch (opcode) {
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200862 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 case POP_TOP:
864 return -1;
865 case ROT_TWO:
866 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200867 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return 0;
869 case DUP_TOP:
870 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000871 case DUP_TOP_TWO:
872 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200874 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 case UNARY_POSITIVE:
876 case UNARY_NEGATIVE:
877 case UNARY_NOT:
878 case UNARY_INVERT:
879 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 case SET_ADD:
882 case LIST_APPEND:
883 return -1;
884 case MAP_ADD:
885 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000886
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200887 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case BINARY_POWER:
889 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400890 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 case BINARY_MODULO:
892 case BINARY_ADD:
893 case BINARY_SUBTRACT:
894 case BINARY_SUBSCR:
895 case BINARY_FLOOR_DIVIDE:
896 case BINARY_TRUE_DIVIDE:
897 return -1;
898 case INPLACE_FLOOR_DIVIDE:
899 case INPLACE_TRUE_DIVIDE:
900 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case INPLACE_ADD:
903 case INPLACE_SUBTRACT:
904 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400905 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case INPLACE_MODULO:
907 return -1;
908 case STORE_SUBSCR:
909 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case DELETE_SUBSCR:
911 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 case BINARY_LSHIFT:
914 case BINARY_RSHIFT:
915 case BINARY_AND:
916 case BINARY_XOR:
917 case BINARY_OR:
918 return -1;
919 case INPLACE_POWER:
920 return -1;
921 case GET_ITER:
922 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case PRINT_EXPR:
925 return -1;
926 case LOAD_BUILD_CLASS:
927 return 1;
928 case INPLACE_LSHIFT:
929 case INPLACE_RSHIFT:
930 case INPLACE_AND:
931 case INPLACE_XOR:
932 case INPLACE_OR:
933 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200936 /* 1 in the normal flow.
937 * Restore the stack position and push 6 values before jumping to
938 * the handler if an exception be raised. */
939 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400940 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200941 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400942 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200943 /* Pop a variable number of values pushed by WITH_CLEANUP_START
944 * + __exit__ or __aexit__. */
945 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case RETURN_VALUE:
947 return -1;
948 case IMPORT_STAR:
949 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700950 case SETUP_ANNOTATIONS:
951 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 case YIELD_VALUE:
953 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500954 case YIELD_FROM:
955 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case POP_BLOCK:
957 return 0;
958 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200959 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200961 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200962 /* Pop 6 values when an exception was raised. */
963 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case STORE_NAME:
966 return -1;
967 case DELETE_NAME:
968 return 0;
969 case UNPACK_SEQUENCE:
970 return oparg-1;
971 case UNPACK_EX:
972 return (oparg&0xFF) + (oparg>>8);
973 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200974 /* -1 at end of iterator, 1 if continue iterating. */
975 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case STORE_ATTR:
978 return -2;
979 case DELETE_ATTR:
980 return -1;
981 case STORE_GLOBAL:
982 return -1;
983 case DELETE_GLOBAL:
984 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 case LOAD_CONST:
986 return 1;
987 case LOAD_NAME:
988 return 1;
989 case BUILD_TUPLE:
990 case BUILD_LIST:
991 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300992 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400994 case BUILD_LIST_UNPACK:
995 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300996 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400997 case BUILD_SET_UNPACK:
998 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400999 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001000 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001002 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001003 case BUILD_CONST_KEY_MAP:
1004 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case LOAD_ATTR:
1006 return 0;
1007 case COMPARE_OP:
1008 return -1;
1009 case IMPORT_NAME:
1010 return -1;
1011 case IMPORT_FROM:
1012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001014 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case JUMP_ABSOLUTE:
1017 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001018
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001019 case JUMP_IF_TRUE_OR_POP:
1020 case JUMP_IF_FALSE_OR_POP:
1021 return jump ? 0 : -1;
1022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 case POP_JUMP_IF_FALSE:
1024 case POP_JUMP_IF_TRUE:
1025 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case LOAD_GLOBAL:
1028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001030 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001032 /* 0 in the normal flow.
1033 * Restore the stack position and push 6 values before jumping to
1034 * the handler if an exception be raised. */
1035 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001036 case BEGIN_FINALLY:
1037 /* Actually pushes 1 value, but count 6 for balancing with
1038 * END_FINALLY and POP_FINALLY.
1039 * This is the main reason of using this opcode instead of
1040 * "LOAD_CONST None". */
1041 return 6;
1042 case CALL_FINALLY:
1043 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case LOAD_FAST:
1046 return 1;
1047 case STORE_FAST:
1048 return -1;
1049 case DELETE_FAST:
1050 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 case RAISE_VARARGS:
1053 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001054
1055 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001057 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001058 case CALL_METHOD:
1059 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001061 return -oparg-1;
1062 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001063 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001064 case MAKE_FUNCTION:
1065 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1066 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case BUILD_SLICE:
1068 if (oparg == 3)
1069 return -2;
1070 else
1071 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001072
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001073 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 case LOAD_CLOSURE:
1075 return 1;
1076 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001077 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return 1;
1079 case STORE_DEREF:
1080 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001081 case DELETE_DEREF:
1082 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001083
1084 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001085 case GET_AWAITABLE:
1086 return 0;
1087 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001088 /* 0 in the normal flow.
1089 * Restore the stack position to the position before the result
1090 * of __aenter__ and push 6 values before jumping to the handler
1091 * if an exception be raised. */
1092 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001093 case BEFORE_ASYNC_WITH:
1094 return 1;
1095 case GET_AITER:
1096 return 0;
1097 case GET_ANEXT:
1098 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001099 case GET_YIELD_FROM_ITER:
1100 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001101 case END_ASYNC_FOR:
1102 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001103 case FORMAT_VALUE:
1104 /* If there's a fmt_spec on the stack, we go from 2->1,
1105 else 1->1. */
1106 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001107 case LOAD_METHOD:
1108 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001110 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 }
Larry Hastings3a907972013-11-23 14:49:22 -08001112 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113}
1114
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001115int
1116PyCompile_OpcodeStackEffect(int opcode, int oparg)
1117{
1118 return stack_effect(opcode, oparg, -1);
1119}
1120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121/* Add an opcode with no argument.
1122 Returns 0 on failure, 1 on success.
1123*/
1124
1125static int
1126compiler_addop(struct compiler *c, int opcode)
1127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 basicblock *b;
1129 struct instr *i;
1130 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001131 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 off = compiler_next_instr(c, c->u->u_curblock);
1133 if (off < 0)
1134 return 0;
1135 b = c->u->u_curblock;
1136 i = &b->b_instr[off];
1137 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001138 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (opcode == RETURN_VALUE)
1140 b->b_return = 1;
1141 compiler_set_lineno(c, off);
1142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143}
1144
Victor Stinnerf8e32212013-11-19 23:56:34 +01001145static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1147{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001148 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001151 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001153 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001155 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001156 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001157 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 return -1;
1160 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001161 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 Py_DECREF(v);
1163 return -1;
1164 }
1165 Py_DECREF(v);
1166 }
1167 else
1168 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001169 return arg;
1170}
1171
1172static Py_ssize_t
1173compiler_add_const(struct compiler *c, PyObject *o)
1174{
1175 PyObject *t;
1176 Py_ssize_t arg;
1177
1178 t = _PyCode_ConstantKey(o);
1179 if (t == NULL)
1180 return -1;
1181
1182 arg = compiler_add_o(c, c->u->u_consts, t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(t);
1184 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185}
1186
1187static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001188compiler_addop_load_const(struct compiler *c, PyObject *o)
1189{
1190 Py_ssize_t arg = compiler_add_const(c, o);
1191 if (arg < 0)
1192 return 0;
1193 return compiler_addop_i(c, LOAD_CONST, arg);
1194}
1195
1196static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001200 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001202 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 return compiler_addop_i(c, opcode, arg);
1204}
1205
1206static int
1207compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001210 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1212 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001213 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 arg = compiler_add_o(c, dict, mangled);
1215 Py_DECREF(mangled);
1216 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001217 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 return compiler_addop_i(c, opcode, arg);
1219}
1220
1221/* Add an opcode with an integer argument.
1222 Returns 0 on failure, 1 on success.
1223*/
1224
1225static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001226compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 struct instr *i;
1229 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001230
Victor Stinner2ad474b2016-03-01 23:34:47 +01001231 /* oparg value is unsigned, but a signed C int is usually used to store
1232 it in the C code (like Python/ceval.c).
1233
1234 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1235
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001236 The argument of a concrete bytecode instruction is limited to 8-bit.
1237 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1238 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001239 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 off = compiler_next_instr(c, c->u->u_curblock);
1242 if (off < 0)
1243 return 0;
1244 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001245 i->i_opcode = opcode;
1246 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 compiler_set_lineno(c, off);
1248 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251static int
1252compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 struct instr *i;
1255 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001257 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 assert(b != NULL);
1259 off = compiler_next_instr(c, c->u->u_curblock);
1260 if (off < 0)
1261 return 0;
1262 i = &c->u->u_curblock->b_instr[off];
1263 i->i_opcode = opcode;
1264 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (absolute)
1266 i->i_jabs = 1;
1267 else
1268 i->i_jrel = 1;
1269 compiler_set_lineno(c, off);
1270 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001273/* NEXT_BLOCK() creates an implicit jump from the current block
1274 to the new block.
1275
1276 The returns inside this macro make it impossible to decref objects
1277 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (compiler_next_block((C)) == NULL) \
1281 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
1284#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_addop((C), (OP))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001289#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!compiler_addop((C), (OP))) { \
1291 compiler_exit_scope(c); \
1292 return 0; \
1293 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001294}
1295
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001296#define ADDOP_LOAD_CONST(C, O) { \
1297 if (!compiler_addop_load_const((C), (O))) \
1298 return 0; \
1299}
1300
1301/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1302#define ADDOP_LOAD_CONST_NEW(C, O) { \
1303 PyObject *__new_const = (O); \
1304 if (__new_const == NULL) { \
1305 return 0; \
1306 } \
1307 if (!compiler_addop_load_const((C), __new_const)) { \
1308 Py_DECREF(__new_const); \
1309 return 0; \
1310 } \
1311 Py_DECREF(__new_const); \
1312}
1313
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1316 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317}
1318
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001319/* Same as ADDOP_O, but steals a reference. */
1320#define ADDOP_N(C, OP, O, TYPE) { \
1321 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1322 Py_DECREF((O)); \
1323 return 0; \
1324 } \
1325 Py_DECREF((O)); \
1326}
1327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1330 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331}
1332
1333#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (!compiler_addop_i((C), (OP), (O))) \
1335 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336}
1337
1338#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (!compiler_addop_j((C), (OP), (O), 1)) \
1340 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341}
1342
1343#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (!compiler_addop_j((C), (OP), (O), 0)) \
1345 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346}
1347
1348/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1349 the ASDL name to synthesize the name of the C type and the visit function.
1350*/
1351
1352#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (!compiler_visit_ ## TYPE((C), (V))) \
1354 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355}
1356
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001357#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (!compiler_visit_ ## TYPE((C), (V))) { \
1359 compiler_exit_scope(c); \
1360 return 0; \
1361 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001362}
1363
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (!compiler_visit_slice((C), (V), (CTX))) \
1366 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367}
1368
1369#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 int _i; \
1371 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1372 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1373 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1374 if (!compiler_visit_ ## TYPE((C), elt)) \
1375 return 0; \
1376 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377}
1378
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001379#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 int _i; \
1381 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1382 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1383 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1384 if (!compiler_visit_ ## TYPE((C), elt)) { \
1385 compiler_exit_scope(c); \
1386 return 0; \
1387 } \
1388 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001389}
1390
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001392is_const(expr_ty e)
1393{
1394 switch (e->kind) {
1395 case Constant_kind:
1396 case Num_kind:
1397 case Str_kind:
1398 case Bytes_kind:
1399 case Ellipsis_kind:
1400 case NameConstant_kind:
1401 return 1;
1402 default:
1403 return 0;
1404 }
1405}
1406
1407static PyObject *
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02001408get_const_value(expr_ty e)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001409{
1410 switch (e->kind) {
1411 case Constant_kind:
1412 return e->v.Constant.value;
1413 case Num_kind:
1414 return e->v.Num.n;
1415 case Str_kind:
1416 return e->v.Str.s;
1417 case Bytes_kind:
1418 return e->v.Bytes.s;
1419 case Ellipsis_kind:
1420 return Py_Ellipsis;
1421 case NameConstant_kind:
1422 return e->v.NameConstant.value;
1423 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001424 Py_UNREACHABLE();
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001425 }
1426}
1427
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001428/* Search if variable annotations are present statically in a block. */
1429
1430static int
1431find_ann(asdl_seq *stmts)
1432{
1433 int i, j, res = 0;
1434 stmt_ty st;
1435
1436 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1437 st = (stmt_ty)asdl_seq_GET(stmts, i);
1438 switch (st->kind) {
1439 case AnnAssign_kind:
1440 return 1;
1441 case For_kind:
1442 res = find_ann(st->v.For.body) ||
1443 find_ann(st->v.For.orelse);
1444 break;
1445 case AsyncFor_kind:
1446 res = find_ann(st->v.AsyncFor.body) ||
1447 find_ann(st->v.AsyncFor.orelse);
1448 break;
1449 case While_kind:
1450 res = find_ann(st->v.While.body) ||
1451 find_ann(st->v.While.orelse);
1452 break;
1453 case If_kind:
1454 res = find_ann(st->v.If.body) ||
1455 find_ann(st->v.If.orelse);
1456 break;
1457 case With_kind:
1458 res = find_ann(st->v.With.body);
1459 break;
1460 case AsyncWith_kind:
1461 res = find_ann(st->v.AsyncWith.body);
1462 break;
1463 case Try_kind:
1464 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1465 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1466 st->v.Try.handlers, j);
1467 if (find_ann(handler->v.ExceptHandler.body)) {
1468 return 1;
1469 }
1470 }
1471 res = find_ann(st->v.Try.body) ||
1472 find_ann(st->v.Try.finalbody) ||
1473 find_ann(st->v.Try.orelse);
1474 break;
1475 default:
1476 res = 0;
1477 }
1478 if (res) {
1479 break;
1480 }
1481 }
1482 return res;
1483}
1484
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001485/*
1486 * Frame block handling functions
1487 */
1488
1489static int
1490compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1491 basicblock *exit)
1492{
1493 struct fblockinfo *f;
1494 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1495 PyErr_SetString(PyExc_SyntaxError,
1496 "too many statically nested blocks");
1497 return 0;
1498 }
1499 f = &c->u->u_fblock[c->u->u_nfblocks++];
1500 f->fb_type = t;
1501 f->fb_block = b;
1502 f->fb_exit = exit;
1503 return 1;
1504}
1505
1506static void
1507compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1508{
1509 struct compiler_unit *u = c->u;
1510 assert(u->u_nfblocks > 0);
1511 u->u_nfblocks--;
1512 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1513 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1514}
1515
1516/* Unwind a frame block. If preserve_tos is true, the TOS before
1517 * popping the blocks will be restored afterwards.
1518 */
1519static int
1520compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1521 int preserve_tos)
1522{
1523 switch (info->fb_type) {
1524 case WHILE_LOOP:
1525 return 1;
1526
1527 case FINALLY_END:
1528 ADDOP_I(c, POP_FINALLY, preserve_tos);
1529 return 1;
1530
1531 case FOR_LOOP:
1532 /* Pop the iterator */
1533 if (preserve_tos) {
1534 ADDOP(c, ROT_TWO);
1535 }
1536 ADDOP(c, POP_TOP);
1537 return 1;
1538
1539 case EXCEPT:
1540 ADDOP(c, POP_BLOCK);
1541 return 1;
1542
1543 case FINALLY_TRY:
1544 ADDOP(c, POP_BLOCK);
1545 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1546 return 1;
1547
1548 case WITH:
1549 case ASYNC_WITH:
1550 ADDOP(c, POP_BLOCK);
1551 if (preserve_tos) {
1552 ADDOP(c, ROT_TWO);
1553 }
1554 ADDOP(c, BEGIN_FINALLY);
1555 ADDOP(c, WITH_CLEANUP_START);
1556 if (info->fb_type == ASYNC_WITH) {
1557 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001558 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001559 ADDOP(c, YIELD_FROM);
1560 }
1561 ADDOP(c, WITH_CLEANUP_FINISH);
1562 ADDOP_I(c, POP_FINALLY, 0);
1563 return 1;
1564
1565 case HANDLER_CLEANUP:
1566 if (preserve_tos) {
1567 ADDOP(c, ROT_FOUR);
1568 }
1569 if (info->fb_exit) {
1570 ADDOP(c, POP_BLOCK);
1571 ADDOP(c, POP_EXCEPT);
1572 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1573 }
1574 else {
1575 ADDOP(c, POP_EXCEPT);
1576 }
1577 return 1;
1578 }
1579 Py_UNREACHABLE();
1580}
1581
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001582/* Compile a sequence of statements, checking for a docstring
1583 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001584
1585static int
INADA Naokicb41b272017-02-23 00:31:59 +09001586compiler_body(struct compiler *c, asdl_seq *stmts, string docstring)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001588 /* Set current line number to the line number of first statement.
1589 This way line number for SETUP_ANNOTATIONS will always
1590 coincide with the line number of first "real" statement in module.
1591 If body is empy, then lineno will be set later in assemble. */
1592 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1593 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
INADA Naokicb41b272017-02-23 00:31:59 +09001594 stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001595 c->u->u_lineno = st->lineno;
1596 }
1597 /* Every annotated class and module should have __annotations__. */
1598 if (find_ann(stmts)) {
1599 ADDOP(c, SETUP_ANNOTATIONS);
1600 }
INADA Naokicb41b272017-02-23 00:31:59 +09001601 /* if not -OO mode, set docstring */
1602 if (c->c_optimize < 2 && docstring) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001603 ADDOP_LOAD_CONST(c, docstring);
INADA Naokicb41b272017-02-23 00:31:59 +09001604 ADDOP_NAME(c, STORE_NAME, __doc__, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 }
INADA Naokicb41b272017-02-23 00:31:59 +09001606 VISIT_SEQ(c, stmt, stmts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001608}
1609
1610static PyCodeObject *
1611compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 PyCodeObject *co;
1614 int addNone = 1;
1615 static PyObject *module;
1616 if (!module) {
1617 module = PyUnicode_InternFromString("<module>");
1618 if (!module)
1619 return NULL;
1620 }
1621 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001622 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 return NULL;
1624 switch (mod->kind) {
1625 case Module_kind:
INADA Naokicb41b272017-02-23 00:31:59 +09001626 if (!compiler_body(c, mod->v.Module.body, mod->v.Module.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 compiler_exit_scope(c);
1628 return 0;
1629 }
1630 break;
1631 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001632 if (find_ann(mod->v.Interactive.body)) {
1633 ADDOP(c, SETUP_ANNOTATIONS);
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 c->c_interactive = 1;
1636 VISIT_SEQ_IN_SCOPE(c, stmt,
1637 mod->v.Interactive.body);
1638 break;
1639 case Expression_kind:
1640 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1641 addNone = 0;
1642 break;
1643 case Suite_kind:
1644 PyErr_SetString(PyExc_SystemError,
1645 "suite should not be possible");
1646 return 0;
1647 default:
1648 PyErr_Format(PyExc_SystemError,
1649 "module kind %d should not be possible",
1650 mod->kind);
1651 return 0;
1652 }
1653 co = assemble(c, addNone);
1654 compiler_exit_scope(c);
1655 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001656}
1657
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658/* The test for LOCAL must come before the test for FREE in order to
1659 handle classes where name is both local and free. The local var is
1660 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001661*/
1662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663static int
1664get_ref_type(struct compiler *c, PyObject *name)
1665{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001666 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001667 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001668 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001669 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001670 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (scope == 0) {
1672 char buf[350];
1673 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001674 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001676 PyUnicode_AsUTF8(name),
1677 PyUnicode_AsUTF8(c->u->u_name),
1678 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1679 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1680 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1681 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 );
1683 Py_FatalError(buf);
1684 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687}
1688
1689static int
1690compiler_lookup_arg(PyObject *dict, PyObject *name)
1691{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001692 PyObject *v;
1693 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001695 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001696 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697}
1698
1699static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001700compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001702 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001703 if (qualname == NULL)
1704 qualname = co->co_name;
1705
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001706 if (free) {
1707 for (i = 0; i < free; ++i) {
1708 /* Bypass com_addop_varname because it will generate
1709 LOAD_DEREF but LOAD_CLOSURE is needed.
1710 */
1711 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1712 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001714 /* Special case: If a class contains a method with a
1715 free variable that has the same name as a method,
1716 the name will be considered free *and* local in the
1717 class. It should be handled by the closure, as
1718 well as by the normal name loookup logic.
1719 */
1720 reftype = get_ref_type(c, name);
1721 if (reftype == CELL)
1722 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1723 else /* (reftype == FREE) */
1724 arg = compiler_lookup_arg(c->u->u_freevars, name);
1725 if (arg == -1) {
1726 fprintf(stderr,
1727 "lookup %s in %s %d %d\n"
1728 "freevars of %s: %s\n",
1729 PyUnicode_AsUTF8(PyObject_Repr(name)),
1730 PyUnicode_AsUTF8(c->u->u_name),
1731 reftype, arg,
1732 PyUnicode_AsUTF8(co->co_name),
1733 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1734 Py_FatalError("compiler_make_closure()");
1735 }
1736 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001738 flags |= 0x08;
1739 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001741 ADDOP_LOAD_CONST(c, (PyObject*)co);
1742 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001743 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001745}
1746
1747static int
1748compiler_decorators(struct compiler *c, asdl_seq* decos)
1749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (!decos)
1753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1756 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1757 }
1758 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759}
1760
1761static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001762compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001764{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001765 /* Push a dict of keyword-only default values.
1766
1767 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1768 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001769 int i;
1770 PyObject *keys = NULL;
1771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1773 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1774 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1775 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001776 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001777 if (!mangled) {
1778 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001780 if (keys == NULL) {
1781 keys = PyList_New(1);
1782 if (keys == NULL) {
1783 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001784 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001785 }
1786 PyList_SET_ITEM(keys, 0, mangled);
1787 }
1788 else {
1789 int res = PyList_Append(keys, mangled);
1790 Py_DECREF(mangled);
1791 if (res == -1) {
1792 goto error;
1793 }
1794 }
1795 if (!compiler_visit_expr(c, default_)) {
1796 goto error;
1797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
1799 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001800 if (keys != NULL) {
1801 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1802 PyObject *keys_tuple = PyList_AsTuple(keys);
1803 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001804 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001805 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001806 assert(default_count > 0);
1807 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001808 }
1809 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001810 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001811 }
1812
1813error:
1814 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001815 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001816}
1817
1818static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001819compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1820{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001821 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation, 1));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001822 return 1;
1823}
1824
1825static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001826compiler_visit_argannotation(struct compiler *c, identifier id,
1827 expr_ty annotation, PyObject *names)
1828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001830 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001831 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1832 VISIT(c, annexpr, annotation)
1833 }
1834 else {
1835 VISIT(c, expr, annotation);
1836 }
Victor Stinner065efc32014-02-18 22:07:56 +01001837 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001838 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001839 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001840 if (PyList_Append(names, mangled) < 0) {
1841 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001842 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001843 }
1844 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001846 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001847}
1848
1849static int
1850compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1851 PyObject *names)
1852{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001853 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 for (i = 0; i < asdl_seq_LEN(args); i++) {
1855 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001856 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 c,
1858 arg->arg,
1859 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001860 names))
1861 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001863 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001864}
1865
1866static int
1867compiler_visit_annotations(struct compiler *c, arguments_ty args,
1868 expr_ty returns)
1869{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001870 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001871 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001872
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001873 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 */
1875 static identifier return_str;
1876 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001877 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 names = PyList_New(0);
1879 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001880 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001881
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001882 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001884 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001885 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001886 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001888 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001890 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001891 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001892 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (!return_str) {
1896 return_str = PyUnicode_InternFromString("return");
1897 if (!return_str)
1898 goto error;
1899 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001900 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 goto error;
1902 }
1903
1904 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001906 PyObject *keytuple = PyList_AsTuple(names);
1907 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001908 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001909 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001910 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001912 else {
1913 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001914 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001915 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001916
1917error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001919 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001920}
1921
1922static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001923compiler_visit_defaults(struct compiler *c, arguments_ty args)
1924{
1925 VISIT_SEQ(c, expr, args->defaults);
1926 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1927 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928}
1929
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001930static Py_ssize_t
1931compiler_default_arguments(struct compiler *c, arguments_ty args)
1932{
1933 Py_ssize_t funcflags = 0;
1934 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001935 if (!compiler_visit_defaults(c, args))
1936 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001937 funcflags |= 0x01;
1938 }
1939 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001940 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001942 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001943 return -1;
1944 }
1945 else if (res > 0) {
1946 funcflags |= 0x02;
1947 }
1948 }
1949 return funcflags;
1950}
1951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952static int
Yury Selivanov75445082015-05-11 22:57:16 -04001953compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 PyCodeObject *co;
INADA Naokicb41b272017-02-23 00:31:59 +09001956 PyObject *qualname, *docstring = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001957 arguments_ty args;
1958 expr_ty returns;
1959 identifier name;
1960 asdl_seq* decos;
1961 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001962 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001963 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001964 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965
Yury Selivanov75445082015-05-11 22:57:16 -04001966 if (is_async) {
1967 assert(s->kind == AsyncFunctionDef_kind);
1968
1969 args = s->v.AsyncFunctionDef.args;
1970 returns = s->v.AsyncFunctionDef.returns;
1971 decos = s->v.AsyncFunctionDef.decorator_list;
1972 name = s->v.AsyncFunctionDef.name;
1973 body = s->v.AsyncFunctionDef.body;
1974
1975 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1976 } else {
1977 assert(s->kind == FunctionDef_kind);
1978
1979 args = s->v.FunctionDef.args;
1980 returns = s->v.FunctionDef.returns;
1981 decos = s->v.FunctionDef.decorator_list;
1982 name = s->v.FunctionDef.name;
1983 body = s->v.FunctionDef.body;
1984
1985 scope_type = COMPILER_SCOPE_FUNCTION;
1986 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (!compiler_decorators(c, decos))
1989 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001990
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 funcflags = compiler_default_arguments(c, args);
1992 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001994 }
1995
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001996 annotations = compiler_visit_annotations(c, args, returns);
1997 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 return 0;
1999 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002000 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002001 funcflags |= 0x04;
2002 }
2003
2004 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
2005 return 0;
2006 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007
INADA Naokicb41b272017-02-23 00:31:59 +09002008 /* if not -OO mode, add docstring */
2009 if (c->c_optimize < 2 && s->v.FunctionDef.docstring)
2010 docstring = s->v.FunctionDef.docstring;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002011 if (compiler_add_const(c, docstring) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 compiler_exit_scope(c);
2013 return 0;
2014 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 c->u->u_argcount = asdl_seq_LEN(args->args);
2017 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* if there was a docstring, we need to skip the first statement */
INADA Naokicb41b272017-02-23 00:31:59 +09002019 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002021 qualname = c->u->u_qualname;
2022 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002024 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002025 Py_XDECREF(qualname);
2026 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002028 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002031 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 /* decorators */
2035 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2036 ADDOP_I(c, CALL_FUNCTION, 1);
2037 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038
Yury Selivanov75445082015-05-11 22:57:16 -04002039 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040}
2041
2042static int
2043compiler_class(struct compiler *c, stmt_ty s)
2044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 PyCodeObject *co;
2046 PyObject *str;
2047 int i;
2048 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (!compiler_decorators(c, decos))
2051 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 /* ultimately generate code for:
2054 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2055 where:
2056 <func> is a function/closure created from the class body;
2057 it has a single argument (__locals__) where the dict
2058 (or MutableSequence) representing the locals is passed
2059 <name> is the class name
2060 <bases> is the positional arguments and *varargs argument
2061 <keywords> is the keyword arguments and **kwds argument
2062 This borrows from compiler_call.
2063 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002066 if (!compiler_enter_scope(c, s->v.ClassDef.name,
2067 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 return 0;
2069 /* this block represents what we do in the new scope */
2070 {
2071 /* use the class name for name mangling */
2072 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002073 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 /* load (global) __name__ ... */
2075 str = PyUnicode_InternFromString("__name__");
2076 if (!str || !compiler_nameop(c, str, Load)) {
2077 Py_XDECREF(str);
2078 compiler_exit_scope(c);
2079 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002080 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 Py_DECREF(str);
2082 /* ... and store it as __module__ */
2083 str = PyUnicode_InternFromString("__module__");
2084 if (!str || !compiler_nameop(c, str, Store)) {
2085 Py_XDECREF(str);
2086 compiler_exit_scope(c);
2087 return 0;
2088 }
2089 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002090 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002091 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002092 str = PyUnicode_InternFromString("__qualname__");
2093 if (!str || !compiler_nameop(c, str, Store)) {
2094 Py_XDECREF(str);
2095 compiler_exit_scope(c);
2096 return 0;
2097 }
2098 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* compile the body proper */
INADA Naokicb41b272017-02-23 00:31:59 +09002100 if (!compiler_body(c, s->v.ClassDef.body, s->v.ClassDef.docstring)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 compiler_exit_scope(c);
2102 return 0;
2103 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002104 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002105 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002106 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002107 str = PyUnicode_InternFromString("__class__");
2108 if (str == NULL) {
2109 compiler_exit_scope(c);
2110 return 0;
2111 }
2112 i = compiler_lookup_arg(c->u->u_cellvars, str);
2113 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002114 if (i < 0) {
2115 compiler_exit_scope(c);
2116 return 0;
2117 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002118 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002121 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002122 str = PyUnicode_InternFromString("__classcell__");
2123 if (!str || !compiler_nameop(c, str, Store)) {
2124 Py_XDECREF(str);
2125 compiler_exit_scope(c);
2126 return 0;
2127 }
2128 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002130 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002131 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002132 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002133 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002134 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002135 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* create the code object */
2137 co = assemble(c, 1);
2138 }
2139 /* leave the new scope */
2140 compiler_exit_scope(c);
2141 if (co == NULL)
2142 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 /* 2. load the 'build_class' function */
2145 ADDOP(c, LOAD_BUILD_CLASS);
2146
2147 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002148 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_DECREF(co);
2150
2151 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002152 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153
2154 /* 5. generate the rest of the code for the call */
2155 if (!compiler_call_helper(c, 2,
2156 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002157 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 return 0;
2159
2160 /* 6. apply decorators */
2161 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2162 ADDOP_I(c, CALL_FUNCTION, 1);
2163 }
2164
2165 /* 7. store into <name> */
2166 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2167 return 0;
2168 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169}
2170
2171static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002172cmpop(cmpop_ty op)
2173{
2174 switch (op) {
2175 case Eq:
2176 return PyCmp_EQ;
2177 case NotEq:
2178 return PyCmp_NE;
2179 case Lt:
2180 return PyCmp_LT;
2181 case LtE:
2182 return PyCmp_LE;
2183 case Gt:
2184 return PyCmp_GT;
2185 case GtE:
2186 return PyCmp_GE;
2187 case Is:
2188 return PyCmp_IS;
2189 case IsNot:
2190 return PyCmp_IS_NOT;
2191 case In:
2192 return PyCmp_IN;
2193 case NotIn:
2194 return PyCmp_NOT_IN;
2195 default:
2196 return PyCmp_BAD;
2197 }
2198}
2199
2200static int
2201compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2202{
2203 switch (e->kind) {
2204 case UnaryOp_kind:
2205 if (e->v.UnaryOp.op == Not)
2206 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2207 /* fallback to general implementation */
2208 break;
2209 case BoolOp_kind: {
2210 asdl_seq *s = e->v.BoolOp.values;
2211 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2212 assert(n >= 0);
2213 int cond2 = e->v.BoolOp.op == Or;
2214 basicblock *next2 = next;
2215 if (!cond2 != !cond) {
2216 next2 = compiler_new_block(c);
2217 if (next2 == NULL)
2218 return 0;
2219 }
2220 for (i = 0; i < n; ++i) {
2221 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2222 return 0;
2223 }
2224 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2225 return 0;
2226 if (next2 != next)
2227 compiler_use_next_block(c, next2);
2228 return 1;
2229 }
2230 case IfExp_kind: {
2231 basicblock *end, *next2;
2232 end = compiler_new_block(c);
2233 if (end == NULL)
2234 return 0;
2235 next2 = compiler_new_block(c);
2236 if (next2 == NULL)
2237 return 0;
2238 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2239 return 0;
2240 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2241 return 0;
2242 ADDOP_JREL(c, JUMP_FORWARD, end);
2243 compiler_use_next_block(c, next2);
2244 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2245 return 0;
2246 compiler_use_next_block(c, end);
2247 return 1;
2248 }
2249 case Compare_kind: {
2250 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2251 if (n > 0) {
2252 basicblock *cleanup = compiler_new_block(c);
2253 if (cleanup == NULL)
2254 return 0;
2255 VISIT(c, expr, e->v.Compare.left);
2256 for (i = 0; i < n; i++) {
2257 VISIT(c, expr,
2258 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2259 ADDOP(c, DUP_TOP);
2260 ADDOP(c, ROT_THREE);
2261 ADDOP_I(c, COMPARE_OP,
2262 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2263 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2264 NEXT_BLOCK(c);
2265 }
2266 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2267 ADDOP_I(c, COMPARE_OP,
2268 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2269 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2270 basicblock *end = compiler_new_block(c);
2271 if (end == NULL)
2272 return 0;
2273 ADDOP_JREL(c, JUMP_FORWARD, end);
2274 compiler_use_next_block(c, cleanup);
2275 ADDOP(c, POP_TOP);
2276 if (!cond) {
2277 ADDOP_JREL(c, JUMP_FORWARD, next);
2278 }
2279 compiler_use_next_block(c, end);
2280 return 1;
2281 }
2282 /* fallback to general implementation */
2283 break;
2284 }
2285 default:
2286 /* fallback to general implementation */
2287 break;
2288 }
2289
2290 /* general implementation */
2291 VISIT(c, expr, e);
2292 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2293 return 1;
2294}
2295
2296static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002297compiler_ifexp(struct compiler *c, expr_ty e)
2298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 basicblock *end, *next;
2300
2301 assert(e->kind == IfExp_kind);
2302 end = compiler_new_block(c);
2303 if (end == NULL)
2304 return 0;
2305 next = compiler_new_block(c);
2306 if (next == NULL)
2307 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002308 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2309 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 VISIT(c, expr, e->v.IfExp.body);
2311 ADDOP_JREL(c, JUMP_FORWARD, end);
2312 compiler_use_next_block(c, next);
2313 VISIT(c, expr, e->v.IfExp.orelse);
2314 compiler_use_next_block(c, end);
2315 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002316}
2317
2318static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319compiler_lambda(struct compiler *c, expr_ty e)
2320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002322 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002324 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 arguments_ty args = e->v.Lambda.args;
2326 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (!name) {
2329 name = PyUnicode_InternFromString("<lambda>");
2330 if (!name)
2331 return 0;
2332 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002334 funcflags = compiler_default_arguments(c, args);
2335 if (funcflags == -1) {
2336 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002338
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002339 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002340 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Make None the first constant, so the lambda can't have a
2344 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002345 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 c->u->u_argcount = asdl_seq_LEN(args->args);
2349 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2350 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2351 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002352 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 }
2354 else {
2355 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002356 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002358 qualname = c->u->u_qualname;
2359 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002361 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002364 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002365 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Py_DECREF(co);
2367
2368 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369}
2370
2371static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372compiler_if(struct compiler *c, stmt_ty s)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 basicblock *end, *next;
2375 int constant;
2376 assert(s->kind == If_kind);
2377 end = compiler_new_block(c);
2378 if (end == NULL)
2379 return 0;
2380
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002381 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* constant = 0: "if 0"
2383 * constant = 1: "if 1", "if 2", ...
2384 * constant = -1: rest */
2385 if (constant == 0) {
2386 if (s->v.If.orelse)
2387 VISIT_SEQ(c, stmt, s->v.If.orelse);
2388 } else if (constant == 1) {
2389 VISIT_SEQ(c, stmt, s->v.If.body);
2390 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002391 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 next = compiler_new_block(c);
2393 if (next == NULL)
2394 return 0;
2395 }
2396 else
2397 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002398 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2399 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002401 if (asdl_seq_LEN(s->v.If.orelse)) {
2402 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 compiler_use_next_block(c, next);
2404 VISIT_SEQ(c, stmt, s->v.If.orelse);
2405 }
2406 }
2407 compiler_use_next_block(c, end);
2408 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409}
2410
2411static int
2412compiler_for(struct compiler *c, stmt_ty s)
2413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 start = compiler_new_block(c);
2417 cleanup = compiler_new_block(c);
2418 end = compiler_new_block(c);
2419 if (start == NULL || end == NULL || cleanup == NULL)
2420 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002421
2422 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 VISIT(c, expr, s->v.For.iter);
2426 ADDOP(c, GET_ITER);
2427 compiler_use_next_block(c, start);
2428 ADDOP_JREL(c, FOR_ITER, cleanup);
2429 VISIT(c, expr, s->v.For.target);
2430 VISIT_SEQ(c, stmt, s->v.For.body);
2431 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2432 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002433
2434 compiler_pop_fblock(c, FOR_LOOP, start);
2435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 VISIT_SEQ(c, stmt, s->v.For.orelse);
2437 compiler_use_next_block(c, end);
2438 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439}
2440
Yury Selivanov75445082015-05-11 22:57:16 -04002441
2442static int
2443compiler_async_for(struct compiler *c, stmt_ty s)
2444{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002445 basicblock *start, *except, *end;
2446 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002447 except = compiler_new_block(c);
2448 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002449
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002450 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002451 return 0;
2452
2453 VISIT(c, expr, s->v.AsyncFor.iter);
2454 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002455
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002456 compiler_use_next_block(c, start);
2457 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2458 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002459
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002460 /* SETUP_FINALLY to guard the __anext__ call */
2461 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002462 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002463 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002464 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002465 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002466
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002467 /* Success block for __anext__ */
2468 VISIT(c, expr, s->v.AsyncFor.target);
2469 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2470 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2471
2472 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002473
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002474 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002475 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002476 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002477
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002478 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002479 VISIT_SEQ(c, stmt, s->v.For.orelse);
2480
2481 compiler_use_next_block(c, end);
2482
2483 return 1;
2484}
2485
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486static int
2487compiler_while(struct compiler *c, stmt_ty s)
2488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002490 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (constant == 0) {
2493 if (s->v.While.orelse)
2494 VISIT_SEQ(c, stmt, s->v.While.orelse);
2495 return 1;
2496 }
2497 loop = compiler_new_block(c);
2498 end = compiler_new_block(c);
2499 if (constant == -1) {
2500 anchor = compiler_new_block(c);
2501 if (anchor == NULL)
2502 return 0;
2503 }
2504 if (loop == NULL || end == NULL)
2505 return 0;
2506 if (s->v.While.orelse) {
2507 orelse = compiler_new_block(c);
2508 if (orelse == NULL)
2509 return 0;
2510 }
2511 else
2512 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002515 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return 0;
2517 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002518 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2519 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 }
2521 VISIT_SEQ(c, stmt, s->v.While.body);
2522 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 /* XXX should the two POP instructions be in a separate block
2525 if there is no else clause ?
2526 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002528 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002530 compiler_pop_fblock(c, WHILE_LOOP, loop);
2531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 if (orelse != NULL) /* what if orelse is just pass? */
2533 VISIT_SEQ(c, stmt, s->v.While.orelse);
2534 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537}
2538
2539static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002540compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002542 int preserve_tos = ((s->v.Return.value != NULL) &&
2543 !is_const(s->v.Return.value));
2544 if (c->u->u_ste->ste_type != FunctionBlock)
2545 return compiler_error(c, "'return' outside function");
2546 if (s->v.Return.value != NULL &&
2547 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2548 {
2549 return compiler_error(
2550 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002552 if (preserve_tos) {
2553 VISIT(c, expr, s->v.Return.value);
2554 }
2555 for (int depth = c->u->u_nfblocks; depth--;) {
2556 struct fblockinfo *info = &c->u->u_fblock[depth];
2557
2558 if (!compiler_unwind_fblock(c, info, preserve_tos))
2559 return 0;
2560 }
2561 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002562 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002563 }
2564 else if (!preserve_tos) {
2565 VISIT(c, expr, s->v.Return.value);
2566 }
2567 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570}
2571
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002572static int
2573compiler_break(struct compiler *c)
2574{
2575 for (int depth = c->u->u_nfblocks; depth--;) {
2576 struct fblockinfo *info = &c->u->u_fblock[depth];
2577
2578 if (!compiler_unwind_fblock(c, info, 0))
2579 return 0;
2580 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2581 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2582 return 1;
2583 }
2584 }
2585 return compiler_error(c, "'break' outside loop");
2586}
2587
2588static int
2589compiler_continue(struct compiler *c)
2590{
2591 for (int depth = c->u->u_nfblocks; depth--;) {
2592 struct fblockinfo *info = &c->u->u_fblock[depth];
2593
2594 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2595 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2596 return 1;
2597 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002598 if (!compiler_unwind_fblock(c, info, 0))
2599 return 0;
2600 }
2601 return compiler_error(c, "'continue' not properly in loop");
2602}
2603
2604
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606
2607 SETUP_FINALLY L
2608 <code for body>
2609 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002610 BEGIN_FINALLY
2611 L:
2612 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 END_FINALLY
2614
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 The special instructions use the block stack. Each block
2616 stack entry contains the instruction that created it (here
2617 SETUP_FINALLY), the level of the value stack at the time the
2618 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 Pushes the current value stack level and the label
2622 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002624 Pops en entry from the block stack.
2625 BEGIN_FINALLY
2626 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002628 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2629 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002632 when a SETUP_FINALLY entry is found, the raised and the caught
2633 exceptions are pushed onto the value stack (and the exception
2634 condition is cleared), and the interpreter jumps to the label
2635 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636*/
2637
2638static int
2639compiler_try_finally(struct compiler *c, stmt_ty s)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 body = compiler_new_block(c);
2644 end = compiler_new_block(c);
2645 if (body == NULL || end == NULL)
2646 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002648 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 ADDOP_JREL(c, SETUP_FINALLY, end);
2650 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002651 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002653 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2654 if (!compiler_try_except(c, s))
2655 return 0;
2656 }
2657 else {
2658 VISIT_SEQ(c, stmt, s->v.Try.body);
2659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002661 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002664 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002666 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002668 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 ADDOP(c, END_FINALLY);
2670 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672}
2673
2674/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002675 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 (The contents of the value stack is shown in [], with the top
2677 at the right; 'tb' is trace-back info, 'val' the exception's
2678 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679
2680 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002681 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 [] <code for S>
2683 [] POP_BLOCK
2684 [] JUMP_FORWARD L0
2685
2686 [tb, val, exc] L1: DUP )
2687 [tb, val, exc, exc] <evaluate E1> )
2688 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2689 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2690 [tb, val, exc] POP
2691 [tb, val] <assign to V1> (or POP if no V1)
2692 [tb] POP
2693 [] <code for S1>
2694 JUMP_FORWARD L0
2695
2696 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 .............................etc.......................
2698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2700
2701 [] L0: <next statement>
2702
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 Of course, parts are not generated if Vi or Ei is not present.
2704*/
2705static int
2706compiler_try_except(struct compiler *c, stmt_ty s)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002709 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 body = compiler_new_block(c);
2712 except = compiler_new_block(c);
2713 orelse = compiler_new_block(c);
2714 end = compiler_new_block(c);
2715 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2716 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002717 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002719 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002721 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 ADDOP(c, POP_BLOCK);
2723 compiler_pop_fblock(c, EXCEPT, body);
2724 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002725 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 compiler_use_next_block(c, except);
2727 for (i = 0; i < n; i++) {
2728 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002729 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 if (!handler->v.ExceptHandler.type && i < n-1)
2731 return compiler_error(c, "default 'except:' must be last");
2732 c->u->u_lineno_set = 0;
2733 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002734 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 except = compiler_new_block(c);
2736 if (except == NULL)
2737 return 0;
2738 if (handler->v.ExceptHandler.type) {
2739 ADDOP(c, DUP_TOP);
2740 VISIT(c, expr, handler->v.ExceptHandler.type);
2741 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2742 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2743 }
2744 ADDOP(c, POP_TOP);
2745 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002746 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002747
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002748 cleanup_end = compiler_new_block(c);
2749 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002750 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002751 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002752
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002753 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2754 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002756 /*
2757 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002758 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002759 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002760 try:
2761 # body
2762 finally:
2763 name = None
2764 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002765 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002767 /* second try: */
2768 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2769 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002770 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002771 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002773 /* second # body */
2774 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2775 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002776 ADDOP(c, BEGIN_FINALLY);
2777 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002779 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002780 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002781 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002782 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002785 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002786 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002787 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002789 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002790 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002791 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 }
2793 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002794 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002796 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002797 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002798 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799
Guido van Rossumb940e112007-01-10 16:19:56 +00002800 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002801 ADDOP(c, POP_TOP);
2802 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002804 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002806 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002807 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 }
2809 ADDOP_JREL(c, JUMP_FORWARD, end);
2810 compiler_use_next_block(c, except);
2811 }
2812 ADDOP(c, END_FINALLY);
2813 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002814 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 compiler_use_next_block(c, end);
2816 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817}
2818
2819static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002820compiler_try(struct compiler *c, stmt_ty s) {
2821 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2822 return compiler_try_finally(c, s);
2823 else
2824 return compiler_try_except(c, s);
2825}
2826
2827
2828static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829compiler_import_as(struct compiler *c, identifier name, identifier asname)
2830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 /* The IMPORT_NAME opcode was already generated. This function
2832 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002835 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002837 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2838 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002839 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002840 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002843 while (1) {
2844 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002846 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002847 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002848 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002849 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002851 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002852 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002853 if (dot == -1) {
2854 break;
2855 }
2856 ADDOP(c, ROT_TWO);
2857 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002859 if (!compiler_nameop(c, asname, Store)) {
2860 return 0;
2861 }
2862 ADDOP(c, POP_TOP);
2863 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 }
2865 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866}
2867
2868static int
2869compiler_import(struct compiler *c, stmt_ty s)
2870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 /* The Import node stores a module name like a.b.c as a single
2872 string. This is convenient for all cases except
2873 import a.b.c as d
2874 where we need to parse that string to extract the individual
2875 module names.
2876 XXX Perhaps change the representation to make this case simpler?
2877 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002878 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 for (i = 0; i < n; i++) {
2881 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2882 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002884 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2885 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (alias->asname) {
2889 r = compiler_import_as(c, alias->name, alias->asname);
2890 if (!r)
2891 return r;
2892 }
2893 else {
2894 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002895 Py_ssize_t dot = PyUnicode_FindChar(
2896 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002897 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002898 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002899 if (tmp == NULL)
2900 return 0;
2901 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002903 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 Py_DECREF(tmp);
2905 }
2906 if (!r)
2907 return r;
2908 }
2909 }
2910 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911}
2912
2913static int
2914compiler_from_import(struct compiler *c, stmt_ty s)
2915{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002916 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002917 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 if (!empty_string) {
2921 empty_string = PyUnicode_FromString("");
2922 if (!empty_string)
2923 return 0;
2924 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002926 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002927
2928 names = PyTuple_New(n);
2929 if (!names)
2930 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 /* build up the names */
2933 for (i = 0; i < n; i++) {
2934 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2935 Py_INCREF(alias->name);
2936 PyTuple_SET_ITEM(names, i, alias->name);
2937 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002940 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 Py_DECREF(names);
2942 return compiler_error(c, "from __future__ imports must occur "
2943 "at the beginning of the file");
2944 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002945 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 if (s->v.ImportFrom.module) {
2948 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2949 }
2950 else {
2951 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2952 }
2953 for (i = 0; i < n; i++) {
2954 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2955 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 assert(n == 1);
2959 ADDOP(c, IMPORT_STAR);
2960 return 1;
2961 }
2962
2963 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2964 store_name = alias->name;
2965 if (alias->asname)
2966 store_name = alias->asname;
2967
2968 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 return 0;
2970 }
2971 }
2972 /* remove imported module */
2973 ADDOP(c, POP_TOP);
2974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975}
2976
2977static int
2978compiler_assert(struct compiler *c, stmt_ty s)
2979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 static PyObject *assertion_error = NULL;
2981 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002982 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983
Georg Brandl8334fd92010-12-04 10:26:46 +00002984 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 return 1;
2986 if (assertion_error == NULL) {
2987 assertion_error = PyUnicode_InternFromString("AssertionError");
2988 if (assertion_error == NULL)
2989 return 0;
2990 }
2991 if (s->v.Assert.test->kind == Tuple_kind &&
2992 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002993 msg = PyUnicode_FromString("assertion is always true, "
2994 "perhaps remove parentheses?");
2995 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002997 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2998 c->c_filename, c->u->u_lineno,
2999 NULL, NULL) == -1) {
3000 Py_DECREF(msg);
3001 return 0;
3002 }
3003 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 end = compiler_new_block(c);
3006 if (end == NULL)
3007 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003008 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3009 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3011 if (s->v.Assert.msg) {
3012 VISIT(c, expr, s->v.Assert.msg);
3013 ADDOP_I(c, CALL_FUNCTION, 1);
3014 }
3015 ADDOP_I(c, RAISE_VARARGS, 1);
3016 compiler_use_next_block(c, end);
3017 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018}
3019
3020static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003021compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3022{
3023 if (c->c_interactive && c->c_nestlevel <= 1) {
3024 VISIT(c, expr, value);
3025 ADDOP(c, PRINT_EXPR);
3026 return 1;
3027 }
3028
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003029 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01003030 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003031 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003032 }
3033
3034 VISIT(c, expr, value);
3035 ADDOP(c, POP_TOP);
3036 return 1;
3037}
3038
3039static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040compiler_visit_stmt(struct compiler *c, stmt_ty s)
3041{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003042 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 /* Always assign a lineno to the next instruction for a stmt. */
3045 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003046 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 switch (s->kind) {
3050 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003051 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 case ClassDef_kind:
3053 return compiler_class(c, s);
3054 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003055 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 case Delete_kind:
3057 VISIT_SEQ(c, expr, s->v.Delete.targets)
3058 break;
3059 case Assign_kind:
3060 n = asdl_seq_LEN(s->v.Assign.targets);
3061 VISIT(c, expr, s->v.Assign.value);
3062 for (i = 0; i < n; i++) {
3063 if (i < n - 1)
3064 ADDOP(c, DUP_TOP);
3065 VISIT(c, expr,
3066 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3067 }
3068 break;
3069 case AugAssign_kind:
3070 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003071 case AnnAssign_kind:
3072 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 case For_kind:
3074 return compiler_for(c, s);
3075 case While_kind:
3076 return compiler_while(c, s);
3077 case If_kind:
3078 return compiler_if(c, s);
3079 case Raise_kind:
3080 n = 0;
3081 if (s->v.Raise.exc) {
3082 VISIT(c, expr, s->v.Raise.exc);
3083 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003084 if (s->v.Raise.cause) {
3085 VISIT(c, expr, s->v.Raise.cause);
3086 n++;
3087 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003089 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003091 case Try_kind:
3092 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 case Assert_kind:
3094 return compiler_assert(c, s);
3095 case Import_kind:
3096 return compiler_import(c, s);
3097 case ImportFrom_kind:
3098 return compiler_from_import(c, s);
3099 case Global_kind:
3100 case Nonlocal_kind:
3101 break;
3102 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003103 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 case Pass_kind:
3105 break;
3106 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003107 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 case Continue_kind:
3109 return compiler_continue(c);
3110 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003111 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003112 case AsyncFunctionDef_kind:
3113 return compiler_function(c, s, 1);
3114 case AsyncWith_kind:
3115 return compiler_async_with(c, s, 0);
3116 case AsyncFor_kind:
3117 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 }
Yury Selivanov75445082015-05-11 22:57:16 -04003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121}
3122
3123static int
3124unaryop(unaryop_ty op)
3125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 switch (op) {
3127 case Invert:
3128 return UNARY_INVERT;
3129 case Not:
3130 return UNARY_NOT;
3131 case UAdd:
3132 return UNARY_POSITIVE;
3133 case USub:
3134 return UNARY_NEGATIVE;
3135 default:
3136 PyErr_Format(PyExc_SystemError,
3137 "unary op %d should not be possible", op);
3138 return 0;
3139 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140}
3141
3142static int
3143binop(struct compiler *c, operator_ty op)
3144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 switch (op) {
3146 case Add:
3147 return BINARY_ADD;
3148 case Sub:
3149 return BINARY_SUBTRACT;
3150 case Mult:
3151 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003152 case MatMult:
3153 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 case Div:
3155 return BINARY_TRUE_DIVIDE;
3156 case Mod:
3157 return BINARY_MODULO;
3158 case Pow:
3159 return BINARY_POWER;
3160 case LShift:
3161 return BINARY_LSHIFT;
3162 case RShift:
3163 return BINARY_RSHIFT;
3164 case BitOr:
3165 return BINARY_OR;
3166 case BitXor:
3167 return BINARY_XOR;
3168 case BitAnd:
3169 return BINARY_AND;
3170 case FloorDiv:
3171 return BINARY_FLOOR_DIVIDE;
3172 default:
3173 PyErr_Format(PyExc_SystemError,
3174 "binary op %d should not be possible", op);
3175 return 0;
3176 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177}
3178
3179static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180inplace_binop(struct compiler *c, operator_ty op)
3181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 switch (op) {
3183 case Add:
3184 return INPLACE_ADD;
3185 case Sub:
3186 return INPLACE_SUBTRACT;
3187 case Mult:
3188 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003189 case MatMult:
3190 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 case Div:
3192 return INPLACE_TRUE_DIVIDE;
3193 case Mod:
3194 return INPLACE_MODULO;
3195 case Pow:
3196 return INPLACE_POWER;
3197 case LShift:
3198 return INPLACE_LSHIFT;
3199 case RShift:
3200 return INPLACE_RSHIFT;
3201 case BitOr:
3202 return INPLACE_OR;
3203 case BitXor:
3204 return INPLACE_XOR;
3205 case BitAnd:
3206 return INPLACE_AND;
3207 case FloorDiv:
3208 return INPLACE_FLOOR_DIVIDE;
3209 default:
3210 PyErr_Format(PyExc_SystemError,
3211 "inplace binary op %d should not be possible", op);
3212 return 0;
3213 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214}
3215
3216static int
3217compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3218{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003219 int op, scope;
3220 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 PyObject *dict = c->u->u_names;
3224 PyObject *mangled;
3225 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003227 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3228 !_PyUnicode_EqualToASCIIString(name, "True") &&
3229 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003230
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003231 mangled = _Py_Mangle(c->u->u_private, name);
3232 if (!mangled)
3233 return 0;
3234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 op = 0;
3236 optype = OP_NAME;
3237 scope = PyST_GetScope(c->u->u_ste, mangled);
3238 switch (scope) {
3239 case FREE:
3240 dict = c->u->u_freevars;
3241 optype = OP_DEREF;
3242 break;
3243 case CELL:
3244 dict = c->u->u_cellvars;
3245 optype = OP_DEREF;
3246 break;
3247 case LOCAL:
3248 if (c->u->u_ste->ste_type == FunctionBlock)
3249 optype = OP_FAST;
3250 break;
3251 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003252 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 optype = OP_GLOBAL;
3254 break;
3255 case GLOBAL_EXPLICIT:
3256 optype = OP_GLOBAL;
3257 break;
3258 default:
3259 /* scope can be 0 */
3260 break;
3261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003264 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 switch (optype) {
3267 case OP_DEREF:
3268 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003269 case Load:
3270 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3271 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 case Store: op = STORE_DEREF; break;
3273 case AugLoad:
3274 case AugStore:
3275 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003276 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 case Param:
3278 default:
3279 PyErr_SetString(PyExc_SystemError,
3280 "param invalid for deref variable");
3281 return 0;
3282 }
3283 break;
3284 case OP_FAST:
3285 switch (ctx) {
3286 case Load: op = LOAD_FAST; break;
3287 case Store: op = STORE_FAST; break;
3288 case Del: op = DELETE_FAST; break;
3289 case AugLoad:
3290 case AugStore:
3291 break;
3292 case Param:
3293 default:
3294 PyErr_SetString(PyExc_SystemError,
3295 "param invalid for local variable");
3296 return 0;
3297 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003298 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 return 1;
3300 case OP_GLOBAL:
3301 switch (ctx) {
3302 case Load: op = LOAD_GLOBAL; break;
3303 case Store: op = STORE_GLOBAL; break;
3304 case Del: op = DELETE_GLOBAL; break;
3305 case AugLoad:
3306 case AugStore:
3307 break;
3308 case Param:
3309 default:
3310 PyErr_SetString(PyExc_SystemError,
3311 "param invalid for global variable");
3312 return 0;
3313 }
3314 break;
3315 case OP_NAME:
3316 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003317 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 case Store: op = STORE_NAME; break;
3319 case Del: op = DELETE_NAME; break;
3320 case AugLoad:
3321 case AugStore:
3322 break;
3323 case Param:
3324 default:
3325 PyErr_SetString(PyExc_SystemError,
3326 "param invalid for name variable");
3327 return 0;
3328 }
3329 break;
3330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 assert(op);
3333 arg = compiler_add_o(c, dict, mangled);
3334 Py_DECREF(mangled);
3335 if (arg < 0)
3336 return 0;
3337 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338}
3339
3340static int
3341compiler_boolop(struct compiler *c, expr_ty e)
3342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003344 int jumpi;
3345 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 assert(e->kind == BoolOp_kind);
3349 if (e->v.BoolOp.op == And)
3350 jumpi = JUMP_IF_FALSE_OR_POP;
3351 else
3352 jumpi = JUMP_IF_TRUE_OR_POP;
3353 end = compiler_new_block(c);
3354 if (end == NULL)
3355 return 0;
3356 s = e->v.BoolOp.values;
3357 n = asdl_seq_LEN(s) - 1;
3358 assert(n >= 0);
3359 for (i = 0; i < n; ++i) {
3360 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3361 ADDOP_JABS(c, jumpi, end);
3362 }
3363 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3364 compiler_use_next_block(c, end);
3365 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366}
3367
3368static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003369starunpack_helper(struct compiler *c, asdl_seq *elts,
3370 int single_op, int inner_op, int outer_op)
3371{
3372 Py_ssize_t n = asdl_seq_LEN(elts);
3373 Py_ssize_t i, nsubitems = 0, nseen = 0;
3374 for (i = 0; i < n; i++) {
3375 expr_ty elt = asdl_seq_GET(elts, i);
3376 if (elt->kind == Starred_kind) {
3377 if (nseen) {
3378 ADDOP_I(c, inner_op, nseen);
3379 nseen = 0;
3380 nsubitems++;
3381 }
3382 VISIT(c, expr, elt->v.Starred.value);
3383 nsubitems++;
3384 }
3385 else {
3386 VISIT(c, expr, elt);
3387 nseen++;
3388 }
3389 }
3390 if (nsubitems) {
3391 if (nseen) {
3392 ADDOP_I(c, inner_op, nseen);
3393 nsubitems++;
3394 }
3395 ADDOP_I(c, outer_op, nsubitems);
3396 }
3397 else
3398 ADDOP_I(c, single_op, nseen);
3399 return 1;
3400}
3401
3402static int
3403assignment_helper(struct compiler *c, asdl_seq *elts)
3404{
3405 Py_ssize_t n = asdl_seq_LEN(elts);
3406 Py_ssize_t i;
3407 int seen_star = 0;
3408 for (i = 0; i < n; i++) {
3409 expr_ty elt = asdl_seq_GET(elts, i);
3410 if (elt->kind == Starred_kind && !seen_star) {
3411 if ((i >= (1 << 8)) ||
3412 (n-i-1 >= (INT_MAX >> 8)))
3413 return compiler_error(c,
3414 "too many expressions in "
3415 "star-unpacking assignment");
3416 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3417 seen_star = 1;
3418 asdl_seq_SET(elts, i, elt->v.Starred.value);
3419 }
3420 else if (elt->kind == Starred_kind) {
3421 return compiler_error(c,
3422 "two starred expressions in assignment");
3423 }
3424 }
3425 if (!seen_star) {
3426 ADDOP_I(c, UNPACK_SEQUENCE, n);
3427 }
3428 VISIT_SEQ(c, expr, elts);
3429 return 1;
3430}
3431
3432static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433compiler_list(struct compiler *c, expr_ty e)
3434{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003435 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003437 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003439 else if (e->v.List.ctx == Load) {
3440 return starunpack_helper(c, elts,
3441 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003443 else
3444 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446}
3447
3448static int
3449compiler_tuple(struct compiler *c, expr_ty e)
3450{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003451 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003453 return assignment_helper(c, elts);
3454 }
3455 else if (e->v.Tuple.ctx == Load) {
3456 return starunpack_helper(c, elts,
3457 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3458 }
3459 else
3460 VISIT_SEQ(c, expr, elts);
3461 return 1;
3462}
3463
3464static int
3465compiler_set(struct compiler *c, expr_ty e)
3466{
3467 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3468 BUILD_SET, BUILD_SET_UNPACK);
3469}
3470
3471static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003472are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3473{
3474 Py_ssize_t i;
3475 for (i = begin; i < end; i++) {
3476 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3477 if (key == NULL || !is_const(key))
3478 return 0;
3479 }
3480 return 1;
3481}
3482
3483static int
3484compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3485{
3486 Py_ssize_t i, n = end - begin;
3487 PyObject *keys, *key;
3488 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3489 for (i = begin; i < end; i++) {
3490 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3491 }
3492 keys = PyTuple_New(n);
3493 if (keys == NULL) {
3494 return 0;
3495 }
3496 for (i = begin; i < end; i++) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02003497 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003498 Py_INCREF(key);
3499 PyTuple_SET_ITEM(keys, i - begin, key);
3500 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003501 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003502 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3503 }
3504 else {
3505 for (i = begin; i < end; i++) {
3506 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3507 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3508 }
3509 ADDOP_I(c, BUILD_MAP, n);
3510 }
3511 return 1;
3512}
3513
3514static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003515compiler_dict(struct compiler *c, expr_ty e)
3516{
Victor Stinner976bb402016-03-23 11:36:19 +01003517 Py_ssize_t i, n, elements;
3518 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003519 int is_unpacking = 0;
3520 n = asdl_seq_LEN(e->v.Dict.values);
3521 containers = 0;
3522 elements = 0;
3523 for (i = 0; i < n; i++) {
3524 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3525 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003526 if (!compiler_subdict(c, e, i - elements, i))
3527 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003528 containers++;
3529 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003531 if (is_unpacking) {
3532 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3533 containers++;
3534 }
3535 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003536 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 }
3538 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003539 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003540 if (!compiler_subdict(c, e, n - elements, n))
3541 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003542 containers++;
3543 }
3544 /* If there is more than one dict, they need to be merged into a new
3545 * dict. If there is one dict and it's an unpacking, then it needs
3546 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003547 if (containers > 1 || is_unpacking) {
3548 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 }
3550 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551}
3552
3553static int
3554compiler_compare(struct compiler *c, expr_ty e)
3555{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003556 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003559 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3560 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3561 if (n == 0) {
3562 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3563 ADDOP_I(c, COMPARE_OP,
3564 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3565 }
3566 else {
3567 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 if (cleanup == NULL)
3569 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003570 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 VISIT(c, expr,
3572 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003573 ADDOP(c, DUP_TOP);
3574 ADDOP(c, ROT_THREE);
3575 ADDOP_I(c, COMPARE_OP,
3576 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3577 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3578 NEXT_BLOCK(c);
3579 }
3580 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3581 ADDOP_I(c, COMPARE_OP,
3582 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 basicblock *end = compiler_new_block(c);
3584 if (end == NULL)
3585 return 0;
3586 ADDOP_JREL(c, JUMP_FORWARD, end);
3587 compiler_use_next_block(c, cleanup);
3588 ADDOP(c, ROT_TWO);
3589 ADDOP(c, POP_TOP);
3590 compiler_use_next_block(c, end);
3591 }
3592 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593}
3594
3595static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003596maybe_optimize_method_call(struct compiler *c, expr_ty e)
3597{
3598 Py_ssize_t argsl, i;
3599 expr_ty meth = e->v.Call.func;
3600 asdl_seq *args = e->v.Call.args;
3601
3602 /* Check that the call node is an attribute access, and that
3603 the call doesn't have keyword parameters. */
3604 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3605 asdl_seq_LEN(e->v.Call.keywords))
3606 return -1;
3607
3608 /* Check that there are no *varargs types of arguments. */
3609 argsl = asdl_seq_LEN(args);
3610 for (i = 0; i < argsl; i++) {
3611 expr_ty elt = asdl_seq_GET(args, i);
3612 if (elt->kind == Starred_kind) {
3613 return -1;
3614 }
3615 }
3616
3617 /* Alright, we can optimize the code. */
3618 VISIT(c, expr, meth->v.Attribute.value);
3619 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3620 VISIT_SEQ(c, expr, e->v.Call.args);
3621 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3622 return 1;
3623}
3624
3625static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626compiler_call(struct compiler *c, expr_ty e)
3627{
Yury Selivanovf2392132016-12-13 19:03:51 -05003628 if (maybe_optimize_method_call(c, e) > 0)
3629 return 1;
3630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 VISIT(c, expr, e->v.Call.func);
3632 return compiler_call_helper(c, 0,
3633 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003634 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003635}
3636
Eric V. Smith235a6f02015-09-19 14:51:32 -04003637static int
3638compiler_joined_str(struct compiler *c, expr_ty e)
3639{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003640 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003641 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3642 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003643 return 1;
3644}
3645
Eric V. Smitha78c7952015-11-03 12:45:05 -05003646/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003647static int
3648compiler_formatted_value(struct compiler *c, expr_ty e)
3649{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003650 /* Our oparg encodes 2 pieces of information: the conversion
3651 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003652
Eric V. Smitha78c7952015-11-03 12:45:05 -05003653 Convert the conversion char to 2 bits:
3654 None: 000 0x0 FVC_NONE
3655 !s : 001 0x1 FVC_STR
3656 !r : 010 0x2 FVC_REPR
3657 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003658
Eric V. Smitha78c7952015-11-03 12:45:05 -05003659 next bit is whether or not we have a format spec:
3660 yes : 100 0x4
3661 no : 000 0x0
3662 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003663
Eric V. Smitha78c7952015-11-03 12:45:05 -05003664 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003665
Eric V. Smitha78c7952015-11-03 12:45:05 -05003666 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003667 VISIT(c, expr, e->v.FormattedValue.value);
3668
Eric V. Smitha78c7952015-11-03 12:45:05 -05003669 switch (e->v.FormattedValue.conversion) {
3670 case 's': oparg = FVC_STR; break;
3671 case 'r': oparg = FVC_REPR; break;
3672 case 'a': oparg = FVC_ASCII; break;
3673 case -1: oparg = FVC_NONE; break;
3674 default:
3675 PyErr_SetString(PyExc_SystemError,
3676 "Unrecognized conversion character");
3677 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003678 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003679 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003680 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003681 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003682 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003683 }
3684
Eric V. Smitha78c7952015-11-03 12:45:05 -05003685 /* And push our opcode and oparg */
3686 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003687 return 1;
3688}
3689
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003690static int
3691compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3692{
3693 Py_ssize_t i, n = end - begin;
3694 keyword_ty kw;
3695 PyObject *keys, *key;
3696 assert(n > 0);
3697 if (n > 1) {
3698 for (i = begin; i < end; i++) {
3699 kw = asdl_seq_GET(keywords, i);
3700 VISIT(c, expr, kw->value);
3701 }
3702 keys = PyTuple_New(n);
3703 if (keys == NULL) {
3704 return 0;
3705 }
3706 for (i = begin; i < end; i++) {
3707 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3708 Py_INCREF(key);
3709 PyTuple_SET_ITEM(keys, i - begin, key);
3710 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003711 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003712 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3713 }
3714 else {
3715 /* a for loop only executes once */
3716 for (i = begin; i < end; i++) {
3717 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003718 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003719 VISIT(c, expr, kw->value);
3720 }
3721 ADDOP_I(c, BUILD_MAP, n);
3722 }
3723 return 1;
3724}
3725
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003726/* shared code between compiler_call and compiler_class */
3727static int
3728compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003729 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003730 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003732{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003733 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003734 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003735
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 /* the number of tuples and dictionaries on the stack */
3737 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3738
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003740 nkwelts = asdl_seq_LEN(keywords);
3741
3742 for (i = 0; i < nkwelts; i++) {
3743 keyword_ty kw = asdl_seq_GET(keywords, i);
3744 if (kw->arg == NULL) {
3745 mustdictunpack = 1;
3746 break;
3747 }
3748 }
3749
3750 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 for (i = 0; i < nelts; i++) {
3752 expr_ty elt = asdl_seq_GET(args, i);
3753 if (elt->kind == Starred_kind) {
3754 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003755 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003756 if (nseen) {
3757 ADDOP_I(c, BUILD_TUPLE, nseen);
3758 nseen = 0;
3759 nsubargs++;
3760 }
3761 VISIT(c, expr, elt->v.Starred.value);
3762 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 }
3764 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003766 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003767 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769
3770 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003771 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003772 if (nseen) {
3773 /* Pack up any trailing positional arguments. */
3774 ADDOP_I(c, BUILD_TUPLE, nseen);
3775 nsubargs++;
3776 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003777 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003778 /* If we ended up with more than one stararg, we need
3779 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003780 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003781 }
3782 else if (nsubargs == 0) {
3783 ADDOP_I(c, BUILD_TUPLE, 0);
3784 }
3785 nseen = 0; /* the number of keyword arguments on the stack following */
3786 for (i = 0; i < nkwelts; i++) {
3787 keyword_ty kw = asdl_seq_GET(keywords, i);
3788 if (kw->arg == NULL) {
3789 /* A keyword argument unpacking. */
3790 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003791 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3792 return 0;
3793 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003794 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003795 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003796 VISIT(c, expr, kw->value);
3797 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003798 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003799 else {
3800 nseen++;
3801 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003802 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003803 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003804 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003805 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003806 return 0;
3807 nsubkwargs++;
3808 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003809 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003811 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003812 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003813 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3814 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003816 else if (nkwelts) {
3817 PyObject *names;
3818 VISIT_SEQ(c, keyword, keywords);
3819 names = PyTuple_New(nkwelts);
3820 if (names == NULL) {
3821 return 0;
3822 }
3823 for (i = 0; i < nkwelts; i++) {
3824 keyword_ty kw = asdl_seq_GET(keywords, i);
3825 Py_INCREF(kw->arg);
3826 PyTuple_SET_ITEM(names, i, kw->arg);
3827 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003828 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003829 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3830 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003832 else {
3833 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3834 return 1;
3835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836}
3837
Nick Coghlan650f0d02007-04-15 12:05:43 +00003838
3839/* List and set comprehensions and generator expressions work by creating a
3840 nested function to perform the actual iteration. This means that the
3841 iteration variables don't leak into the current scope.
3842 The defined function is called immediately following its definition, with the
3843 result of that call being the result of the expression.
3844 The LC/SC version returns the populated container, while the GE version is
3845 flagged in symtable.c as a generator, so it returns the generator object
3846 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003847
3848 Possible cleanups:
3849 - iterate over the generator sequence instead of using recursion
3850*/
3851
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854compiler_comprehension_generator(struct compiler *c,
3855 asdl_seq *generators, int gen_index,
3856 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003858 comprehension_ty gen;
3859 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3860 if (gen->is_async) {
3861 return compiler_async_comprehension_generator(
3862 c, generators, gen_index, elt, val, type);
3863 } else {
3864 return compiler_sync_comprehension_generator(
3865 c, generators, gen_index, elt, val, type);
3866 }
3867}
3868
3869static int
3870compiler_sync_comprehension_generator(struct compiler *c,
3871 asdl_seq *generators, int gen_index,
3872 expr_ty elt, expr_ty val, int type)
3873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 /* generate code for the iterator, then each of the ifs,
3875 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 comprehension_ty gen;
3878 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003879 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 start = compiler_new_block(c);
3882 skip = compiler_new_block(c);
3883 if_cleanup = compiler_new_block(c);
3884 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3887 anchor == NULL)
3888 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 if (gen_index == 0) {
3893 /* Receive outermost iter as an implicit argument */
3894 c->u->u_argcount = 1;
3895 ADDOP_I(c, LOAD_FAST, 0);
3896 }
3897 else {
3898 /* Sub-iter - calculate on the fly */
3899 VISIT(c, expr, gen->iter);
3900 ADDOP(c, GET_ITER);
3901 }
3902 compiler_use_next_block(c, start);
3903 ADDOP_JREL(c, FOR_ITER, anchor);
3904 NEXT_BLOCK(c);
3905 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 /* XXX this needs to be cleaned up...a lot! */
3908 n = asdl_seq_LEN(gen->ifs);
3909 for (i = 0; i < n; i++) {
3910 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003911 if (!compiler_jump_if(c, e, if_cleanup, 0))
3912 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 NEXT_BLOCK(c);
3914 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 if (++gen_index < asdl_seq_LEN(generators))
3917 if (!compiler_comprehension_generator(c,
3918 generators, gen_index,
3919 elt, val, type))
3920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* only append after the last for generator */
3923 if (gen_index >= asdl_seq_LEN(generators)) {
3924 /* comprehension specific code */
3925 switch (type) {
3926 case COMP_GENEXP:
3927 VISIT(c, expr, elt);
3928 ADDOP(c, YIELD_VALUE);
3929 ADDOP(c, POP_TOP);
3930 break;
3931 case COMP_LISTCOMP:
3932 VISIT(c, expr, elt);
3933 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3934 break;
3935 case COMP_SETCOMP:
3936 VISIT(c, expr, elt);
3937 ADDOP_I(c, SET_ADD, gen_index + 1);
3938 break;
3939 case COMP_DICTCOMP:
3940 /* With 'd[k] = v', v is evaluated before k, so we do
3941 the same. */
3942 VISIT(c, expr, val);
3943 VISIT(c, expr, elt);
3944 ADDOP_I(c, MAP_ADD, gen_index + 1);
3945 break;
3946 default:
3947 return 0;
3948 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 compiler_use_next_block(c, skip);
3951 }
3952 compiler_use_next_block(c, if_cleanup);
3953 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3954 compiler_use_next_block(c, anchor);
3955
3956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957}
3958
3959static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003960compiler_async_comprehension_generator(struct compiler *c,
3961 asdl_seq *generators, int gen_index,
3962 expr_ty elt, expr_ty val, int type)
3963{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003964 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003965 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003967 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003968 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003969 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003970
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003971 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003972 return 0;
3973 }
3974
3975 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3976
3977 if (gen_index == 0) {
3978 /* Receive outermost iter as an implicit argument */
3979 c->u->u_argcount = 1;
3980 ADDOP_I(c, LOAD_FAST, 0);
3981 }
3982 else {
3983 /* Sub-iter - calculate on the fly */
3984 VISIT(c, expr, gen->iter);
3985 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003986 }
3987
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003988 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003989
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003990 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003991 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003992 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003993 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003994 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02003995 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003996
3997 n = asdl_seq_LEN(gen->ifs);
3998 for (i = 0; i < n; i++) {
3999 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004000 if (!compiler_jump_if(c, e, if_cleanup, 0))
4001 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004002 NEXT_BLOCK(c);
4003 }
4004
4005 if (++gen_index < asdl_seq_LEN(generators))
4006 if (!compiler_comprehension_generator(c,
4007 generators, gen_index,
4008 elt, val, type))
4009 return 0;
4010
4011 /* only append after the last for generator */
4012 if (gen_index >= asdl_seq_LEN(generators)) {
4013 /* comprehension specific code */
4014 switch (type) {
4015 case COMP_GENEXP:
4016 VISIT(c, expr, elt);
4017 ADDOP(c, YIELD_VALUE);
4018 ADDOP(c, POP_TOP);
4019 break;
4020 case COMP_LISTCOMP:
4021 VISIT(c, expr, elt);
4022 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4023 break;
4024 case COMP_SETCOMP:
4025 VISIT(c, expr, elt);
4026 ADDOP_I(c, SET_ADD, gen_index + 1);
4027 break;
4028 case COMP_DICTCOMP:
4029 /* With 'd[k] = v', v is evaluated before k, so we do
4030 the same. */
4031 VISIT(c, expr, val);
4032 VISIT(c, expr, elt);
4033 ADDOP_I(c, MAP_ADD, gen_index + 1);
4034 break;
4035 default:
4036 return 0;
4037 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004038 }
4039 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004040 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4041
4042 compiler_use_next_block(c, except);
4043 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004044
4045 return 1;
4046}
4047
4048static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004049compiler_comprehension(struct compiler *c, expr_ty e, int type,
4050 identifier name, asdl_seq *generators, expr_ty elt,
4051 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004054 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004055 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004056 int is_async_function = c->u->u_ste->ste_coroutine;
4057 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004058
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004059 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004060
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004061 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4062 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004063 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004065 }
4066
4067 is_async_generator = c->u->u_ste->ste_coroutine;
4068
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004069 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004070 if (e->lineno > c->u->u_lineno) {
4071 c->u->u_lineno = e->lineno;
4072 c->u->u_lineno_set = 0;
4073 }
4074 compiler_error(c, "asynchronous comprehension outside of "
4075 "an asynchronous function");
4076 goto error_in_scope;
4077 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 if (type != COMP_GENEXP) {
4080 int op;
4081 switch (type) {
4082 case COMP_LISTCOMP:
4083 op = BUILD_LIST;
4084 break;
4085 case COMP_SETCOMP:
4086 op = BUILD_SET;
4087 break;
4088 case COMP_DICTCOMP:
4089 op = BUILD_MAP;
4090 break;
4091 default:
4092 PyErr_Format(PyExc_SystemError,
4093 "unknown comprehension type %d", type);
4094 goto error_in_scope;
4095 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 ADDOP_I(c, op, 0);
4098 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 if (!compiler_comprehension_generator(c, generators, 0, elt,
4101 val, type))
4102 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 if (type != COMP_GENEXP) {
4105 ADDOP(c, RETURN_VALUE);
4106 }
4107
4108 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004109 qualname = c->u->u_qualname;
4110 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004112 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 goto error;
4114
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004115 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004117 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 Py_DECREF(co);
4119
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004120 VISIT(c, expr, outermost->iter);
4121
4122 if (outermost->is_async) {
4123 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004124 } else {
4125 ADDOP(c, GET_ITER);
4126 }
4127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004129
4130 if (is_async_generator && type != COMP_GENEXP) {
4131 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004132 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004133 ADDOP(c, YIELD_FROM);
4134 }
4135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004137error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004139error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004140 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 Py_XDECREF(co);
4142 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004143}
4144
4145static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146compiler_genexp(struct compiler *c, expr_ty e)
4147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 static identifier name;
4149 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004150 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 if (!name)
4152 return 0;
4153 }
4154 assert(e->kind == GeneratorExp_kind);
4155 return compiler_comprehension(c, e, COMP_GENEXP, name,
4156 e->v.GeneratorExp.generators,
4157 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158}
4159
4160static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004161compiler_listcomp(struct compiler *c, expr_ty e)
4162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 static identifier name;
4164 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004165 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 if (!name)
4167 return 0;
4168 }
4169 assert(e->kind == ListComp_kind);
4170 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4171 e->v.ListComp.generators,
4172 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004173}
4174
4175static int
4176compiler_setcomp(struct compiler *c, expr_ty e)
4177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 static identifier name;
4179 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004180 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 if (!name)
4182 return 0;
4183 }
4184 assert(e->kind == SetComp_kind);
4185 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4186 e->v.SetComp.generators,
4187 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004188}
4189
4190
4191static int
4192compiler_dictcomp(struct compiler *c, expr_ty e)
4193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 static identifier name;
4195 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004196 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 if (!name)
4198 return 0;
4199 }
4200 assert(e->kind == DictComp_kind);
4201 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4202 e->v.DictComp.generators,
4203 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004204}
4205
4206
4207static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208compiler_visit_keyword(struct compiler *c, keyword_ty k)
4209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 VISIT(c, expr, k->value);
4211 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212}
4213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 whether they are true or false.
4216
4217 Return values: 1 for true, 0 for false, -1 for non-constant.
4218 */
4219
4220static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004221expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004222{
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004223 if (is_const(e)) {
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004224 return PyObject_IsTrue(get_const_value(e));
Benjamin Peterson442f2092012-12-06 17:41:04 -05004225 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004226 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004227}
4228
Yury Selivanov75445082015-05-11 22:57:16 -04004229
4230/*
4231 Implements the async with statement.
4232
4233 The semantics outlined in that PEP are as follows:
4234
4235 async with EXPR as VAR:
4236 BLOCK
4237
4238 It is implemented roughly as:
4239
4240 context = EXPR
4241 exit = context.__aexit__ # not calling it
4242 value = await context.__aenter__()
4243 try:
4244 VAR = value # if VAR present in the syntax
4245 BLOCK
4246 finally:
4247 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004248 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004249 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004250 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004251 if not (await exit(*exc)):
4252 raise
4253 */
4254static int
4255compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4256{
4257 basicblock *block, *finally;
4258 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4259
4260 assert(s->kind == AsyncWith_kind);
4261
4262 block = compiler_new_block(c);
4263 finally = compiler_new_block(c);
4264 if (!block || !finally)
4265 return 0;
4266
4267 /* Evaluate EXPR */
4268 VISIT(c, expr, item->context_expr);
4269
4270 ADDOP(c, BEFORE_ASYNC_WITH);
4271 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004272 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004273 ADDOP(c, YIELD_FROM);
4274
4275 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4276
4277 /* SETUP_ASYNC_WITH pushes a finally block. */
4278 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004279 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004280 return 0;
4281 }
4282
4283 if (item->optional_vars) {
4284 VISIT(c, expr, item->optional_vars);
4285 }
4286 else {
4287 /* Discard result from context.__aenter__() */
4288 ADDOP(c, POP_TOP);
4289 }
4290
4291 pos++;
4292 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4293 /* BLOCK code */
4294 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4295 else if (!compiler_async_with(c, s, pos))
4296 return 0;
4297
4298 /* End of try block; start the finally block */
4299 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004300 ADDOP(c, BEGIN_FINALLY);
4301 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004302
Yury Selivanov75445082015-05-11 22:57:16 -04004303 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004304 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004305 return 0;
4306
4307 /* Finally block starts; context.__exit__ is on the stack under
4308 the exception or return information. Just issue our magic
4309 opcode. */
4310 ADDOP(c, WITH_CLEANUP_START);
4311
4312 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004313 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004314 ADDOP(c, YIELD_FROM);
4315
4316 ADDOP(c, WITH_CLEANUP_FINISH);
4317
4318 /* Finally block ends. */
4319 ADDOP(c, END_FINALLY);
4320 compiler_pop_fblock(c, FINALLY_END, finally);
4321 return 1;
4322}
4323
4324
Guido van Rossumc2e20742006-02-27 22:32:47 +00004325/*
4326 Implements the with statement from PEP 343.
4327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004329
4330 with EXPR as VAR:
4331 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332
Guido van Rossumc2e20742006-02-27 22:32:47 +00004333 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334
Thomas Wouters477c8d52006-05-27 19:21:47 +00004335 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004336 exit = context.__exit__ # not calling it
4337 value = context.__enter__()
4338 try:
4339 VAR = value # if VAR present in the syntax
4340 BLOCK
4341 finally:
4342 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004343 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004344 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004345 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004346 exit(*exc)
4347 */
4348static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004349compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004350{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004351 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004352 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004353
4354 assert(s->kind == With_kind);
4355
Guido van Rossumc2e20742006-02-27 22:32:47 +00004356 block = compiler_new_block(c);
4357 finally = compiler_new_block(c);
4358 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004359 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004360
Thomas Wouters477c8d52006-05-27 19:21:47 +00004361 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004362 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004363 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004364
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004365 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004366 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004367 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004368 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004369 }
4370
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004371 if (item->optional_vars) {
4372 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004373 }
4374 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004376 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004377 }
4378
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004379 pos++;
4380 if (pos == asdl_seq_LEN(s->v.With.items))
4381 /* BLOCK code */
4382 VISIT_SEQ(c, stmt, s->v.With.body)
4383 else if (!compiler_with(c, s, pos))
4384 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004385
4386 /* End of try block; start the finally block */
4387 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004388 ADDOP(c, BEGIN_FINALLY);
4389 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004390
Guido van Rossumc2e20742006-02-27 22:32:47 +00004391 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004392 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004393 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004394
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004395 /* Finally block starts; context.__exit__ is on the stack under
4396 the exception or return information. Just issue our magic
4397 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004398 ADDOP(c, WITH_CLEANUP_START);
4399 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004400
4401 /* Finally block ends. */
4402 ADDOP(c, END_FINALLY);
4403 compiler_pop_fblock(c, FINALLY_END, finally);
4404 return 1;
4405}
4406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004407static int
4408compiler_visit_expr(struct compiler *c, expr_ty e)
4409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 /* If expr e has a different line number than the last expr/stmt,
4411 set a new line number for the next instruction.
4412 */
4413 if (e->lineno > c->u->u_lineno) {
4414 c->u->u_lineno = e->lineno;
4415 c->u->u_lineno_set = 0;
4416 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004417 /* Updating the column offset is always harmless. */
4418 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 switch (e->kind) {
4420 case BoolOp_kind:
4421 return compiler_boolop(c, e);
4422 case BinOp_kind:
4423 VISIT(c, expr, e->v.BinOp.left);
4424 VISIT(c, expr, e->v.BinOp.right);
4425 ADDOP(c, binop(c, e->v.BinOp.op));
4426 break;
4427 case UnaryOp_kind:
4428 VISIT(c, expr, e->v.UnaryOp.operand);
4429 ADDOP(c, unaryop(e->v.UnaryOp.op));
4430 break;
4431 case Lambda_kind:
4432 return compiler_lambda(c, e);
4433 case IfExp_kind:
4434 return compiler_ifexp(c, e);
4435 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004436 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004438 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 case GeneratorExp_kind:
4440 return compiler_genexp(c, e);
4441 case ListComp_kind:
4442 return compiler_listcomp(c, e);
4443 case SetComp_kind:
4444 return compiler_setcomp(c, e);
4445 case DictComp_kind:
4446 return compiler_dictcomp(c, e);
4447 case Yield_kind:
4448 if (c->u->u_ste->ste_type != FunctionBlock)
4449 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004450 if (e->v.Yield.value) {
4451 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 }
4453 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004454 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004456 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004458 case YieldFrom_kind:
4459 if (c->u->u_ste->ste_type != FunctionBlock)
4460 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004461
4462 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4463 return compiler_error(c, "'yield from' inside async function");
4464
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004465 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004466 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004467 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004468 ADDOP(c, YIELD_FROM);
4469 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004470 case Await_kind:
4471 if (c->u->u_ste->ste_type != FunctionBlock)
4472 return compiler_error(c, "'await' outside function");
4473
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004474 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4475 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004476 return compiler_error(c, "'await' outside async function");
4477
4478 VISIT(c, expr, e->v.Await.value);
4479 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004480 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004481 ADDOP(c, YIELD_FROM);
4482 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 case Compare_kind:
4484 return compiler_compare(c, e);
4485 case Call_kind:
4486 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004487 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004488 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004489 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 case Num_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004491 ADDOP_LOAD_CONST(c, e->v.Num.n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 break;
4493 case Str_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004494 ADDOP_LOAD_CONST(c, e->v.Str.s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004496 case JoinedStr_kind:
4497 return compiler_joined_str(c, e);
4498 case FormattedValue_kind:
4499 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 case Bytes_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004501 ADDOP_LOAD_CONST(c, e->v.Bytes.s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 break;
4503 case Ellipsis_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004504 ADDOP_LOAD_CONST(c, Py_Ellipsis);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004506 case NameConstant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004507 ADDOP_LOAD_CONST(c, e->v.NameConstant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004508 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 /* The following exprs can be assignment targets. */
4510 case Attribute_kind:
4511 if (e->v.Attribute.ctx != AugStore)
4512 VISIT(c, expr, e->v.Attribute.value);
4513 switch (e->v.Attribute.ctx) {
4514 case AugLoad:
4515 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004516 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 case Load:
4518 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4519 break;
4520 case AugStore:
4521 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004522 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 case Store:
4524 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4525 break;
4526 case Del:
4527 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4528 break;
4529 case Param:
4530 default:
4531 PyErr_SetString(PyExc_SystemError,
4532 "param invalid in attribute expression");
4533 return 0;
4534 }
4535 break;
4536 case Subscript_kind:
4537 switch (e->v.Subscript.ctx) {
4538 case AugLoad:
4539 VISIT(c, expr, e->v.Subscript.value);
4540 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4541 break;
4542 case Load:
4543 VISIT(c, expr, e->v.Subscript.value);
4544 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4545 break;
4546 case AugStore:
4547 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4548 break;
4549 case Store:
4550 VISIT(c, expr, e->v.Subscript.value);
4551 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4552 break;
4553 case Del:
4554 VISIT(c, expr, e->v.Subscript.value);
4555 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4556 break;
4557 case Param:
4558 default:
4559 PyErr_SetString(PyExc_SystemError,
4560 "param invalid in subscript expression");
4561 return 0;
4562 }
4563 break;
4564 case Starred_kind:
4565 switch (e->v.Starred.ctx) {
4566 case Store:
4567 /* In all legitimate cases, the Starred node was already replaced
4568 * by compiler_list/compiler_tuple. XXX: is that okay? */
4569 return compiler_error(c,
4570 "starred assignment target must be in a list or tuple");
4571 default:
4572 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004573 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 }
4575 break;
4576 case Name_kind:
4577 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4578 /* child nodes of List and Tuple will have expr_context set */
4579 case List_kind:
4580 return compiler_list(c, e);
4581 case Tuple_kind:
4582 return compiler_tuple(c, e);
4583 }
4584 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004585}
4586
4587static int
4588compiler_augassign(struct compiler *c, stmt_ty s)
4589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 expr_ty e = s->v.AugAssign.target;
4591 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 switch (e->kind) {
4596 case Attribute_kind:
4597 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4598 AugLoad, e->lineno, e->col_offset, c->c_arena);
4599 if (auge == NULL)
4600 return 0;
4601 VISIT(c, expr, auge);
4602 VISIT(c, expr, s->v.AugAssign.value);
4603 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4604 auge->v.Attribute.ctx = AugStore;
4605 VISIT(c, expr, auge);
4606 break;
4607 case Subscript_kind:
4608 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4609 AugLoad, e->lineno, e->col_offset, c->c_arena);
4610 if (auge == NULL)
4611 return 0;
4612 VISIT(c, expr, auge);
4613 VISIT(c, expr, s->v.AugAssign.value);
4614 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4615 auge->v.Subscript.ctx = AugStore;
4616 VISIT(c, expr, auge);
4617 break;
4618 case Name_kind:
4619 if (!compiler_nameop(c, e->v.Name.id, Load))
4620 return 0;
4621 VISIT(c, expr, s->v.AugAssign.value);
4622 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4623 return compiler_nameop(c, e->v.Name.id, Store);
4624 default:
4625 PyErr_Format(PyExc_SystemError,
4626 "invalid node type (%d) for augmented assignment",
4627 e->kind);
4628 return 0;
4629 }
4630 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004631}
4632
4633static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004634check_ann_expr(struct compiler *c, expr_ty e)
4635{
4636 VISIT(c, expr, e);
4637 ADDOP(c, POP_TOP);
4638 return 1;
4639}
4640
4641static int
4642check_annotation(struct compiler *c, stmt_ty s)
4643{
4644 /* Annotations are only evaluated in a module or class. */
4645 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4646 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4647 return check_ann_expr(c, s->v.AnnAssign.annotation);
4648 }
4649 return 1;
4650}
4651
4652static int
4653check_ann_slice(struct compiler *c, slice_ty sl)
4654{
4655 switch(sl->kind) {
4656 case Index_kind:
4657 return check_ann_expr(c, sl->v.Index.value);
4658 case Slice_kind:
4659 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4660 return 0;
4661 }
4662 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4663 return 0;
4664 }
4665 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4666 return 0;
4667 }
4668 break;
4669 default:
4670 PyErr_SetString(PyExc_SystemError,
4671 "unexpected slice kind");
4672 return 0;
4673 }
4674 return 1;
4675}
4676
4677static int
4678check_ann_subscr(struct compiler *c, slice_ty sl)
4679{
4680 /* We check that everything in a subscript is defined at runtime. */
4681 Py_ssize_t i, n;
4682
4683 switch (sl->kind) {
4684 case Index_kind:
4685 case Slice_kind:
4686 if (!check_ann_slice(c, sl)) {
4687 return 0;
4688 }
4689 break;
4690 case ExtSlice_kind:
4691 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4692 for (i = 0; i < n; i++) {
4693 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4694 switch (subsl->kind) {
4695 case Index_kind:
4696 case Slice_kind:
4697 if (!check_ann_slice(c, subsl)) {
4698 return 0;
4699 }
4700 break;
4701 case ExtSlice_kind:
4702 default:
4703 PyErr_SetString(PyExc_SystemError,
4704 "extended slice invalid in nested slice");
4705 return 0;
4706 }
4707 }
4708 break;
4709 default:
4710 PyErr_Format(PyExc_SystemError,
4711 "invalid subscript kind %d", sl->kind);
4712 return 0;
4713 }
4714 return 1;
4715}
4716
4717static int
4718compiler_annassign(struct compiler *c, stmt_ty s)
4719{
4720 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004721 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004722
4723 assert(s->kind == AnnAssign_kind);
4724
4725 /* We perform the actual assignment first. */
4726 if (s->v.AnnAssign.value) {
4727 VISIT(c, expr, s->v.AnnAssign.value);
4728 VISIT(c, expr, targ);
4729 }
4730 switch (targ->kind) {
4731 case Name_kind:
4732 /* If we have a simple name in a module or class, store annotation. */
4733 if (s->v.AnnAssign.simple &&
4734 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4735 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004736 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4737 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4738 }
4739 else {
4740 VISIT(c, expr, s->v.AnnAssign.annotation);
4741 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004742 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004743 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004744 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004745 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004746 }
4747 break;
4748 case Attribute_kind:
4749 if (!s->v.AnnAssign.value &&
4750 !check_ann_expr(c, targ->v.Attribute.value)) {
4751 return 0;
4752 }
4753 break;
4754 case Subscript_kind:
4755 if (!s->v.AnnAssign.value &&
4756 (!check_ann_expr(c, targ->v.Subscript.value) ||
4757 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4758 return 0;
4759 }
4760 break;
4761 default:
4762 PyErr_Format(PyExc_SystemError,
4763 "invalid node type (%d) for annotated assignment",
4764 targ->kind);
4765 return 0;
4766 }
4767 /* Annotation is evaluated last. */
4768 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4769 return 0;
4770 }
4771 return 1;
4772}
4773
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004774/* Raises a SyntaxError and returns 0.
4775 If something goes wrong, a different exception may be raised.
4776*/
4777
4778static int
4779compiler_error(struct compiler *c, const char *errstr)
4780{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004781 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004782 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004783
Victor Stinner14e461d2013-08-26 22:28:21 +02004784 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 if (!loc) {
4786 Py_INCREF(Py_None);
4787 loc = Py_None;
4788 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004789 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004790 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 if (!u)
4792 goto exit;
4793 v = Py_BuildValue("(zO)", errstr, u);
4794 if (!v)
4795 goto exit;
4796 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004797 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 Py_DECREF(loc);
4799 Py_XDECREF(u);
4800 Py_XDECREF(v);
4801 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004802}
4803
4804static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805compiler_handle_subscr(struct compiler *c, const char *kind,
4806 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 /* XXX this code is duplicated */
4811 switch (ctx) {
4812 case AugLoad: /* fall through to Load */
4813 case Load: op = BINARY_SUBSCR; break;
4814 case AugStore:/* fall through to Store */
4815 case Store: op = STORE_SUBSCR; break;
4816 case Del: op = DELETE_SUBSCR; break;
4817 case Param:
4818 PyErr_Format(PyExc_SystemError,
4819 "invalid %s kind %d in subscript\n",
4820 kind, ctx);
4821 return 0;
4822 }
4823 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004824 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 }
4826 else if (ctx == AugStore) {
4827 ADDOP(c, ROT_THREE);
4828 }
4829 ADDOP(c, op);
4830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004831}
4832
4833static int
4834compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 int n = 2;
4837 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 /* only handles the cases where BUILD_SLICE is emitted */
4840 if (s->v.Slice.lower) {
4841 VISIT(c, expr, s->v.Slice.lower);
4842 }
4843 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004844 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 if (s->v.Slice.upper) {
4848 VISIT(c, expr, s->v.Slice.upper);
4849 }
4850 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004851 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 }
4853
4854 if (s->v.Slice.step) {
4855 n++;
4856 VISIT(c, expr, s->v.Slice.step);
4857 }
4858 ADDOP_I(c, BUILD_SLICE, n);
4859 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004860}
4861
4862static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4864 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 switch (s->kind) {
4867 case Slice_kind:
4868 return compiler_slice(c, s, ctx);
4869 case Index_kind:
4870 VISIT(c, expr, s->v.Index.value);
4871 break;
4872 case ExtSlice_kind:
4873 default:
4874 PyErr_SetString(PyExc_SystemError,
4875 "extended slice invalid in nested slice");
4876 return 0;
4877 }
4878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004879}
4880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004881static int
4882compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4883{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004884 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 switch (s->kind) {
4886 case Index_kind:
4887 kindname = "index";
4888 if (ctx != AugStore) {
4889 VISIT(c, expr, s->v.Index.value);
4890 }
4891 break;
4892 case Slice_kind:
4893 kindname = "slice";
4894 if (ctx != AugStore) {
4895 if (!compiler_slice(c, s, ctx))
4896 return 0;
4897 }
4898 break;
4899 case ExtSlice_kind:
4900 kindname = "extended slice";
4901 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004902 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 for (i = 0; i < n; i++) {
4904 slice_ty sub = (slice_ty)asdl_seq_GET(
4905 s->v.ExtSlice.dims, i);
4906 if (!compiler_visit_nested_slice(c, sub, ctx))
4907 return 0;
4908 }
4909 ADDOP_I(c, BUILD_TUPLE, n);
4910 }
4911 break;
4912 default:
4913 PyErr_Format(PyExc_SystemError,
4914 "invalid subscript kind %d", s->kind);
4915 return 0;
4916 }
4917 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004918}
4919
Thomas Wouters89f507f2006-12-13 04:49:30 +00004920/* End of the compiler section, beginning of the assembler section */
4921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004922/* do depth-first search of basic block graph, starting with block.
4923 post records the block indices in post-order.
4924
4925 XXX must handle implicit jumps from one block to next
4926*/
4927
Thomas Wouters89f507f2006-12-13 04:49:30 +00004928struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 PyObject *a_bytecode; /* string containing bytecode */
4930 int a_offset; /* offset into bytecode */
4931 int a_nblocks; /* number of reachable blocks */
4932 basicblock **a_postorder; /* list of blocks in dfs postorder */
4933 PyObject *a_lnotab; /* string containing lnotab */
4934 int a_lnotab_off; /* offset into lnotab */
4935 int a_lineno; /* last lineno of emitted instruction */
4936 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004937};
4938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004939static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004940dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004941{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004942 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004943
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004944 /* Get rid of recursion for normal control flow.
4945 Since the number of blocks is limited, unused space in a_postorder
4946 (from a_nblocks to end) can be used as a stack for still not ordered
4947 blocks. */
4948 for (j = end; b && !b->b_seen; b = b->b_next) {
4949 b->b_seen = 1;
4950 assert(a->a_nblocks < j);
4951 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004953 while (j < end) {
4954 b = a->a_postorder[j++];
4955 for (i = 0; i < b->b_iused; i++) {
4956 struct instr *instr = &b->b_instr[i];
4957 if (instr->i_jrel || instr->i_jabs)
4958 dfs(c, instr->i_target, a, j);
4959 }
4960 assert(a->a_nblocks < j);
4961 a->a_postorder[a->a_nblocks++] = b;
4962 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004963}
4964
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004965Py_LOCAL_INLINE(void)
4966stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004967{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004968 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004969 if (b->b_startdepth < depth) {
4970 assert(b->b_startdepth < 0);
4971 b->b_startdepth = depth;
4972 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004973 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004974}
4975
4976/* Find the flow path that needs the largest stack. We assume that
4977 * cycles in the flow graph have no net effect on the stack depth.
4978 */
4979static int
4980stackdepth(struct compiler *c)
4981{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004982 basicblock *b, *entryblock = NULL;
4983 basicblock **stack, **sp;
4984 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 b->b_startdepth = INT_MIN;
4987 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004988 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 }
4990 if (!entryblock)
4991 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004992 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
4993 if (!stack) {
4994 PyErr_NoMemory();
4995 return -1;
4996 }
4997
4998 sp = stack;
4999 stackdepth_push(&sp, entryblock, 0);
5000 while (sp != stack) {
5001 b = *--sp;
5002 int depth = b->b_startdepth;
5003 assert(depth >= 0);
5004 basicblock *next = b->b_next;
5005 for (int i = 0; i < b->b_iused; i++) {
5006 struct instr *instr = &b->b_instr[i];
5007 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5008 if (effect == PY_INVALID_STACK_EFFECT) {
5009 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5010 Py_FatalError("PyCompile_OpcodeStackEffect()");
5011 }
5012 int new_depth = depth + effect;
5013 if (new_depth > maxdepth) {
5014 maxdepth = new_depth;
5015 }
5016 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5017 if (instr->i_jrel || instr->i_jabs) {
5018 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5019 assert(effect != PY_INVALID_STACK_EFFECT);
5020 int target_depth = depth + effect;
5021 if (target_depth > maxdepth) {
5022 maxdepth = target_depth;
5023 }
5024 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005025 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005026 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005027 assert(instr->i_target->b_startdepth >= target_depth);
5028 depth = new_depth;
5029 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005030 }
5031 stackdepth_push(&sp, instr->i_target, target_depth);
5032 }
5033 depth = new_depth;
5034 if (instr->i_opcode == JUMP_ABSOLUTE ||
5035 instr->i_opcode == JUMP_FORWARD ||
5036 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005037 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005038 {
5039 /* remaining code is dead */
5040 next = NULL;
5041 break;
5042 }
5043 }
5044 if (next != NULL) {
5045 stackdepth_push(&sp, next, depth);
5046 }
5047 }
5048 PyObject_Free(stack);
5049 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005050}
5051
5052static int
5053assemble_init(struct assembler *a, int nblocks, int firstlineno)
5054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 memset(a, 0, sizeof(struct assembler));
5056 a->a_lineno = firstlineno;
5057 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5058 if (!a->a_bytecode)
5059 return 0;
5060 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5061 if (!a->a_lnotab)
5062 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005063 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 PyErr_NoMemory();
5065 return 0;
5066 }
5067 a->a_postorder = (basicblock **)PyObject_Malloc(
5068 sizeof(basicblock *) * nblocks);
5069 if (!a->a_postorder) {
5070 PyErr_NoMemory();
5071 return 0;
5072 }
5073 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005074}
5075
5076static void
5077assemble_free(struct assembler *a)
5078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 Py_XDECREF(a->a_bytecode);
5080 Py_XDECREF(a->a_lnotab);
5081 if (a->a_postorder)
5082 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005083}
5084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005085static int
5086blocksize(basicblock *b)
5087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 int i;
5089 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005092 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005094}
5095
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005096/* Appends a pair to the end of the line number table, a_lnotab, representing
5097 the instruction's bytecode offset and line number. See
5098 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005099
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005100static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005101assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005104 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005106
Serhiy Storchakaab874002016-09-11 13:48:15 +03005107 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 if(d_bytecode == 0 && d_lineno == 0)
5113 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 if (d_bytecode > 255) {
5116 int j, nbytes, ncodes = d_bytecode / 255;
5117 nbytes = a->a_lnotab_off + 2 * ncodes;
5118 len = PyBytes_GET_SIZE(a->a_lnotab);
5119 if (nbytes >= len) {
5120 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5121 len = nbytes;
5122 else if (len <= INT_MAX / 2)
5123 len *= 2;
5124 else {
5125 PyErr_NoMemory();
5126 return 0;
5127 }
5128 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5129 return 0;
5130 }
5131 lnotab = (unsigned char *)
5132 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5133 for (j = 0; j < ncodes; j++) {
5134 *lnotab++ = 255;
5135 *lnotab++ = 0;
5136 }
5137 d_bytecode -= ncodes * 255;
5138 a->a_lnotab_off += ncodes * 2;
5139 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005140 assert(0 <= d_bytecode && d_bytecode <= 255);
5141
5142 if (d_lineno < -128 || 127 < d_lineno) {
5143 int j, nbytes, ncodes, k;
5144 if (d_lineno < 0) {
5145 k = -128;
5146 /* use division on positive numbers */
5147 ncodes = (-d_lineno) / 128;
5148 }
5149 else {
5150 k = 127;
5151 ncodes = d_lineno / 127;
5152 }
5153 d_lineno -= ncodes * k;
5154 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 nbytes = a->a_lnotab_off + 2 * ncodes;
5156 len = PyBytes_GET_SIZE(a->a_lnotab);
5157 if (nbytes >= len) {
5158 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5159 len = nbytes;
5160 else if (len <= INT_MAX / 2)
5161 len *= 2;
5162 else {
5163 PyErr_NoMemory();
5164 return 0;
5165 }
5166 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5167 return 0;
5168 }
5169 lnotab = (unsigned char *)
5170 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5171 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005172 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 d_bytecode = 0;
5174 for (j = 1; j < ncodes; j++) {
5175 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005176 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 a->a_lnotab_off += ncodes * 2;
5179 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005180 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 len = PyBytes_GET_SIZE(a->a_lnotab);
5183 if (a->a_lnotab_off + 2 >= len) {
5184 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5185 return 0;
5186 }
5187 lnotab = (unsigned char *)
5188 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005190 a->a_lnotab_off += 2;
5191 if (d_bytecode) {
5192 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005193 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 }
5195 else { /* First line of a block; def stmt, etc. */
5196 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005197 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 }
5199 a->a_lineno = i->i_lineno;
5200 a->a_lineno_off = a->a_offset;
5201 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005202}
5203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005204/* assemble_emit()
5205 Extend the bytecode with a new instruction.
5206 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005207*/
5208
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005209static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005210assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005211{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005212 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005214 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005215
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005216 arg = i->i_oparg;
5217 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 if (i->i_lineno && !assemble_lnotab(a, i))
5219 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005220 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 if (len > PY_SSIZE_T_MAX / 2)
5222 return 0;
5223 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5224 return 0;
5225 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005226 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005228 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005230}
5231
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005232static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005233assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005236 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005237 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 /* Compute the size of each block and fixup jump args.
5240 Replace block pointer with position in bytecode. */
5241 do {
5242 totsize = 0;
5243 for (i = a->a_nblocks - 1; i >= 0; i--) {
5244 b = a->a_postorder[i];
5245 bsize = blocksize(b);
5246 b->b_offset = totsize;
5247 totsize += bsize;
5248 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005249 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5251 bsize = b->b_offset;
5252 for (i = 0; i < b->b_iused; i++) {
5253 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005254 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 /* Relative jumps are computed relative to
5256 the instruction pointer after fetching
5257 the jump instruction.
5258 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005259 bsize += isize;
5260 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005262 if (instr->i_jrel) {
5263 instr->i_oparg -= bsize;
5264 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005265 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005266 if (instrsize(instr->i_oparg) != isize) {
5267 extended_arg_recompile = 1;
5268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 }
5271 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 /* XXX: This is an awful hack that could hurt performance, but
5274 on the bright side it should work until we come up
5275 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 The issue is that in the first loop blocksize() is called
5278 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005279 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 So we loop until we stop seeing new EXTENDED_ARGs.
5283 The only EXTENDED_ARGs that could be popping up are
5284 ones in jump instructions. So this should converge
5285 fairly quickly.
5286 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005287 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005288}
5289
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005290static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005291dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005294 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 tuple = PyTuple_New(size);
5297 if (tuple == NULL)
5298 return NULL;
5299 while (PyDict_Next(dict, &pos, &k, &v)) {
5300 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005301 Py_INCREF(k);
5302 assert((i - offset) < size);
5303 assert((i - offset) >= 0);
5304 PyTuple_SET_ITEM(tuple, i - offset, k);
5305 }
5306 return tuple;
5307}
5308
5309static PyObject *
5310consts_dict_keys_inorder(PyObject *dict)
5311{
5312 PyObject *consts, *k, *v;
5313 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5314
5315 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5316 if (consts == NULL)
5317 return NULL;
5318 while (PyDict_Next(dict, &pos, &k, &v)) {
5319 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005320 /* The keys of the dictionary can be tuples wrapping a contant.
5321 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5322 * the object we want is always second. */
5323 if (PyTuple_CheckExact(k)) {
5324 k = PyTuple_GET_ITEM(k, 1);
5325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005327 assert(i < size);
5328 assert(i >= 0);
5329 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005331 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005332}
5333
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005334static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005335compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005338 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005340 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 if (ste->ste_nested)
5342 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005343 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005345 if (!ste->ste_generator && ste->ste_coroutine)
5346 flags |= CO_COROUTINE;
5347 if (ste->ste_generator && ste->ste_coroutine)
5348 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 if (ste->ste_varargs)
5350 flags |= CO_VARARGS;
5351 if (ste->ste_varkeywords)
5352 flags |= CO_VARKEYWORDS;
5353 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 /* (Only) inherit compilerflags in PyCF_MASK */
5356 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005359}
5360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005361static PyCodeObject *
5362makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 PyObject *tmp;
5365 PyCodeObject *co = NULL;
5366 PyObject *consts = NULL;
5367 PyObject *names = NULL;
5368 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 PyObject *name = NULL;
5370 PyObject *freevars = NULL;
5371 PyObject *cellvars = NULL;
5372 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005373 Py_ssize_t nlocals;
5374 int nlocals_int;
5375 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005376 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005377
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005378 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 names = dict_keys_inorder(c->u->u_names, 0);
5380 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5381 if (!consts || !names || !varnames)
5382 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5385 if (!cellvars)
5386 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005387 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 if (!freevars)
5389 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005390
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005391 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005392 assert(nlocals < INT_MAX);
5393 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 flags = compute_code_flags(c);
5396 if (flags < 0)
5397 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5400 if (!bytecode)
5401 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5404 if (!tmp)
5405 goto error;
5406 Py_DECREF(consts);
5407 consts = tmp;
5408
Victor Stinnerf8e32212013-11-19 23:56:34 +01005409 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5410 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005411 maxdepth = stackdepth(c);
5412 if (maxdepth < 0) {
5413 goto error;
5414 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005415 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005416 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 bytecode, consts, names, varnames,
5418 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005419 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 c->u->u_firstlineno,
5421 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005422 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 Py_XDECREF(consts);
5424 Py_XDECREF(names);
5425 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 Py_XDECREF(name);
5427 Py_XDECREF(freevars);
5428 Py_XDECREF(cellvars);
5429 Py_XDECREF(bytecode);
5430 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005431}
5432
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005433
5434/* For debugging purposes only */
5435#if 0
5436static void
5437dump_instr(const struct instr *i)
5438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 const char *jrel = i->i_jrel ? "jrel " : "";
5440 const char *jabs = i->i_jabs ? "jabs " : "";
5441 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005444 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5448 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005449}
5450
5451static void
5452dump_basicblock(const basicblock *b)
5453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 const char *seen = b->b_seen ? "seen " : "";
5455 const char *b_return = b->b_return ? "return " : "";
5456 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5457 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5458 if (b->b_instr) {
5459 int i;
5460 for (i = 0; i < b->b_iused; i++) {
5461 fprintf(stderr, " [%02d] ", i);
5462 dump_instr(b->b_instr + i);
5463 }
5464 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005465}
5466#endif
5467
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005468static PyCodeObject *
5469assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 basicblock *b, *entryblock;
5472 struct assembler a;
5473 int i, j, nblocks;
5474 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 /* Make sure every block that falls off the end returns None.
5477 XXX NEXT_BLOCK() isn't quite right, because if the last
5478 block ends with a jump or return b_next shouldn't set.
5479 */
5480 if (!c->u->u_curblock->b_return) {
5481 NEXT_BLOCK(c);
5482 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005483 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 ADDOP(c, RETURN_VALUE);
5485 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 nblocks = 0;
5488 entryblock = NULL;
5489 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5490 nblocks++;
5491 entryblock = b;
5492 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 /* Set firstlineno if it wasn't explicitly set. */
5495 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005496 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5498 else
5499 c->u->u_firstlineno = 1;
5500 }
5501 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5502 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005503 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 /* Can't modify the bytecode after computing jump offsets. */
5506 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 /* Emit code in reverse postorder from dfs. */
5509 for (i = a.a_nblocks - 1; i >= 0; i--) {
5510 b = a.a_postorder[i];
5511 for (j = 0; j < b->b_iused; j++)
5512 if (!assemble_emit(&a, &b->b_instr[j]))
5513 goto error;
5514 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5517 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005518 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005522 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 assemble_free(&a);
5524 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005525}
Georg Brandl8334fd92010-12-04 10:26:46 +00005526
5527#undef PyAST_Compile
5528PyAPI_FUNC(PyCodeObject *)
5529PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5530 PyArena *arena)
5531{
5532 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5533}