blob: beceeea86b12d03c44921e328102d7a48c4c08a7 [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"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000029#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030031#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
67 unsigned b_seen : 1;
68 /* b_return is true if a RETURN_VALUE opcode is inserted. */
69 unsigned b_return : 1;
70 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
73 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020083enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
84 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020089 /* (optional) type-specific exit or cleanup block */
90 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
Antoine Pitrou86a36b52011-11-25 18:56:07 +010093enum {
94 COMPILER_SCOPE_MODULE,
95 COMPILER_SCOPE_CLASS,
96 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040097 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040098 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010099 COMPILER_SCOPE_COMPREHENSION,
100};
101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000102/* The following items change on entry and exit of code blocks.
103 They must be saved and restored when returning to a block.
104*/
105struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400109 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100110 int u_scope_type;
111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /* The following fields are dicts that map objects to
113 the index of them in co_XXX. The index is used as
114 the argument for opcodes that refer to those collections.
115 */
116 PyObject *u_consts; /* all constants */
117 PyObject *u_names; /* all names */
118 PyObject *u_varnames; /* local variables */
119 PyObject *u_cellvars; /* cell variables */
120 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
Victor Stinnerf8e32212013-11-19 23:56:34 +0100124 Py_ssize_t u_argcount; /* number of arguments for block */
125 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 /* Pointer to the most recently allocated block. By following b_list
127 members, you can reach all early allocated blocks. */
128 basicblock *u_blocks;
129 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int u_nfblocks;
132 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 int u_firstlineno; /* the first lineno of the block */
135 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000136 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 int u_lineno_set; /* boolean to indicate whether instr
138 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139};
140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000146
147Note that we don't track recursion levels during compilation - the
148task of detecting and rejecting excessive levels of nesting is
149handled by the symbol analysis pass.
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151*/
152
153struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200154 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 struct symtable *c_st;
156 PyFutureFeatures *c_future; /* pointer to module's __future__ */
157 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Georg Brandl8334fd92010-12-04 10:26:46 +0000159 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 int c_interactive; /* true if in interactive mode */
161 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 struct compiler_unit *u; /* compiler state for current block */
164 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
165 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166};
167
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100168static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169static void compiler_free(struct compiler *);
170static basicblock *compiler_new_block(struct compiler *);
171static int compiler_next_instr(struct compiler *, basicblock *);
172static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100173static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static int compiler_error(struct compiler *, const char *);
Serhiy Storchakad31e7732018-10-21 10:09:39 +0300176static int compiler_warn(struct compiler *, const char *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700184static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200189static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500191static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400192static int compiler_async_with(struct compiler *, stmt_ty, int);
193static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100194static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400196 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500197static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400198static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000199
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700200static int compiler_sync_comprehension_generator(
201 struct compiler *c,
202 asdl_seq *generators, int gen_index,
203 expr_ty elt, expr_ty val, int type);
204
205static int compiler_async_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000211static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400213#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 /* Name mangling: __private becomes _classname__private.
219 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200220 PyObject *result;
221 size_t nlen, plen, ipriv;
222 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 PyUnicode_READ_CHAR(ident, 0) != '_' ||
225 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_INCREF(ident);
227 return ident;
228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 nlen = PyUnicode_GET_LENGTH(ident);
230 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 The only time a name with a dot can occur is when
234 we are compiling an import statement that has a
235 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 TODO(jhylton): Decide whether we want to support
238 mangling of the module name, e.g. __M.X.
239 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200240 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
241 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
242 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 Py_INCREF(ident);
244 return ident; /* Don't mangle __whatever__ */
245 }
246 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200247 ipriv = 0;
248 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
249 ipriv++;
250 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 Py_INCREF(ident);
252 return ident; /* Don't mangle if class is just underscores */
253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200254 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Antoine Pitrou55bff892013-04-06 21:21:04 +0200256 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
257 PyErr_SetString(PyExc_OverflowError,
258 "private identifier too large to be mangled");
259 return NULL;
260 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200262 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
263 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
264 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
265
266 result = PyUnicode_New(1 + nlen + plen, maxchar);
267 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200269 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
270 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200271 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
272 Py_DECREF(result);
273 return NULL;
274 }
275 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
276 Py_DECREF(result);
277 return NULL;
278 }
Victor Stinner8f825062012-04-27 13:55:39 +0200279 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000281}
282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283static int
284compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 c->c_stack = PyList_New(0);
289 if (!c->c_stack)
290 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293}
294
295PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200296PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
297 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 struct compiler c;
300 PyCodeObject *co = NULL;
301 PyCompilerFlags local_flags;
302 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!__doc__) {
305 __doc__ = PyUnicode_InternFromString("__doc__");
306 if (!__doc__)
307 return NULL;
308 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000309 if (!__annotations__) {
310 __annotations__ = PyUnicode_InternFromString("__annotations__");
311 if (!__annotations__)
312 return NULL;
313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!compiler_init(&c))
315 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200316 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 c.c_filename = filename;
318 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200319 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (c.c_future == NULL)
321 goto finally;
322 if (!flags) {
323 local_flags.cf_flags = 0;
324 flags = &local_flags;
325 }
326 merged = c.c_future->ff_features | flags->cf_flags;
327 c.c_future->ff_features = merged;
328 flags->cf_flags = merged;
329 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000330 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200333 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900334 goto finally;
335 }
336
Victor Stinner14e461d2013-08-26 22:28:21 +0200337 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (c.c_st == NULL) {
339 if (!PyErr_Occurred())
340 PyErr_SetString(PyExc_SystemError, "no symtable");
341 goto finally;
342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345
Thomas Wouters1175c432006-02-27 22:49:54 +0000346 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 compiler_free(&c);
348 assert(co || PyErr_Occurred());
349 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350}
351
352PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200353PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
354 int optimize, PyArena *arena)
355{
356 PyObject *filename;
357 PyCodeObject *co;
358 filename = PyUnicode_DecodeFSDefault(filename_str);
359 if (filename == NULL)
360 return NULL;
361 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
362 Py_DECREF(filename);
363 return co;
364
365}
366
367PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368PyNode_Compile(struct _node *n, const char *filename)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyCodeObject *co = NULL;
371 mod_ty mod;
372 PyArena *arena = PyArena_New();
373 if (!arena)
374 return NULL;
375 mod = PyAST_FromNode(n, NULL, filename, arena);
376 if (mod)
377 co = PyAST_Compile(mod, filename, NULL, arena);
378 PyArena_Free(arena);
379 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000380}
381
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000382static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (c->c_st)
386 PySymtable_Free(c->c_st);
387 if (c->c_future)
388 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200389 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391}
392
Guido van Rossum79f25d91997-04-29 20:08:16 +0000393static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 Py_ssize_t i, n;
397 PyObject *v, *k;
398 PyObject *dict = PyDict_New();
399 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 n = PyList_Size(list);
402 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100403 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (!v) {
405 Py_DECREF(dict);
406 return NULL;
407 }
408 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300409 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_DECREF(v);
411 Py_DECREF(dict);
412 return NULL;
413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300462 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300469 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_DECREF(item);
472 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return NULL;
474 }
475 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
477 }
Meador Inge2ca63152012-07-18 14:20:11 -0500478 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000480}
481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482static void
483compiler_unit_check(struct compiler_unit *u)
484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 basicblock *block;
486 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700487 assert((uintptr_t)block != 0xcbcbcbcbU);
488 assert((uintptr_t)block != 0xfbfbfbfbU);
489 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (block->b_instr != NULL) {
491 assert(block->b_ialloc > 0);
492 assert(block->b_iused > 0);
493 assert(block->b_ialloc >= block->b_iused);
494 }
495 else {
496 assert (block->b_iused == 0);
497 assert (block->b_ialloc == 0);
498 }
499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500}
501
502static void
503compiler_unit_free(struct compiler_unit *u)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 compiler_unit_check(u);
508 b = u->u_blocks;
509 while (b != NULL) {
510 if (b->b_instr)
511 PyObject_Free((void *)b->b_instr);
512 next = b->b_list;
513 PyObject_Free((void *)b);
514 b = next;
515 }
516 Py_CLEAR(u->u_ste);
517 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400518 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_CLEAR(u->u_consts);
520 Py_CLEAR(u->u_names);
521 Py_CLEAR(u->u_varnames);
522 Py_CLEAR(u->u_freevars);
523 Py_CLEAR(u->u_cellvars);
524 Py_CLEAR(u->u_private);
525 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526}
527
528static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100529compiler_enter_scope(struct compiler *c, identifier name,
530 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100533 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
536 struct compiler_unit));
537 if (!u) {
538 PyErr_NoMemory();
539 return 0;
540 }
541 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100542 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 u->u_argcount = 0;
544 u->u_kwonlyargcount = 0;
545 u->u_ste = PySymtable_Lookup(c->c_st, key);
546 if (!u->u_ste) {
547 compiler_unit_free(u);
548 return 0;
549 }
550 Py_INCREF(name);
551 u->u_name = name;
552 u->u_varnames = list2dict(u->u_ste->ste_varnames);
553 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
554 if (!u->u_varnames || !u->u_cellvars) {
555 compiler_unit_free(u);
556 return 0;
557 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500558 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000559 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500560 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300561 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500562 int res;
563 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200564 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500565 name = _PyUnicode_FromId(&PyId___class__);
566 if (!name) {
567 compiler_unit_free(u);
568 return 0;
569 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300570 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 if (res < 0) {
572 compiler_unit_free(u);
573 return 0;
574 }
575 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200578 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (!u->u_freevars) {
580 compiler_unit_free(u);
581 return 0;
582 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 u->u_blocks = NULL;
585 u->u_nfblocks = 0;
586 u->u_firstlineno = lineno;
587 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000588 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_lineno_set = 0;
590 u->u_consts = PyDict_New();
591 if (!u->u_consts) {
592 compiler_unit_free(u);
593 return 0;
594 }
595 u->u_names = PyDict_New();
596 if (!u->u_names) {
597 compiler_unit_free(u);
598 return 0;
599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 /* Push the old compiler_unit on the stack. */
604 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400605 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
607 Py_XDECREF(capsule);
608 compiler_unit_free(u);
609 return 0;
610 }
611 Py_DECREF(capsule);
612 u->u_private = c->u->u_private;
613 Py_XINCREF(u->u_private);
614 }
615 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100618
619 block = compiler_new_block(c);
620 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100622 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400624 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
625 if (!compiler_set_qualname(c))
626 return 0;
627 }
628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630}
631
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000632static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633compiler_exit_scope(struct compiler *c)
634{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100635 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 c->c_nestlevel--;
639 compiler_unit_free(c->u);
640 /* Restore c->u to the parent unit. */
641 n = PyList_GET_SIZE(c->c_stack) - 1;
642 if (n >= 0) {
643 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400644 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 assert(c->u);
646 /* we are deleting from a list so this really shouldn't fail */
647 if (PySequence_DelItem(c->c_stack, n) < 0)
648 Py_FatalError("compiler_exit_scope()");
649 compiler_unit_check(c->u);
650 }
651 else
652 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654}
655
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400656static int
657compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100658{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100659 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400660 _Py_static_string(dot_locals, ".<locals>");
661 Py_ssize_t stack_size;
662 struct compiler_unit *u = c->u;
663 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100666 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400667 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400668 if (stack_size > 1) {
669 int scope, force_global = 0;
670 struct compiler_unit *parent;
671 PyObject *mangled, *capsule;
672
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400673 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400674 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 assert(parent);
676
Yury Selivanov75445082015-05-11 22:57:16 -0400677 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
678 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
679 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680 assert(u->u_name);
681 mangled = _Py_Mangle(parent->u_private, u->u_name);
682 if (!mangled)
683 return 0;
684 scope = PyST_GetScope(parent->u_ste, mangled);
685 Py_DECREF(mangled);
686 assert(scope != GLOBAL_IMPLICIT);
687 if (scope == GLOBAL_EXPLICIT)
688 force_global = 1;
689 }
690
691 if (!force_global) {
692 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400693 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
695 dot_locals_str = _PyUnicode_FromId(&dot_locals);
696 if (dot_locals_str == NULL)
697 return 0;
698 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
699 if (base == NULL)
700 return 0;
701 }
702 else {
703 Py_INCREF(parent->u_qualname);
704 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400705 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 }
707 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 if (base != NULL) {
710 dot_str = _PyUnicode_FromId(&dot);
711 if (dot_str == NULL) {
712 Py_DECREF(base);
713 return 0;
714 }
715 name = PyUnicode_Concat(base, dot_str);
716 Py_DECREF(base);
717 if (name == NULL)
718 return 0;
719 PyUnicode_Append(&name, u->u_name);
720 if (name == NULL)
721 return 0;
722 }
723 else {
724 Py_INCREF(u->u_name);
725 name = u->u_name;
726 }
727 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730}
731
Eric V. Smith235a6f02015-09-19 14:51:32 -0400732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733/* Allocate a new block and return a pointer to it.
734 Returns NULL on error.
735*/
736
737static basicblock *
738compiler_new_block(struct compiler *c)
739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 basicblock *b;
741 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 u = c->u;
744 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
745 if (b == NULL) {
746 PyErr_NoMemory();
747 return NULL;
748 }
749 memset((void *)b, 0, sizeof(basicblock));
750 /* Extend the singly linked list of blocks with new block. */
751 b->b_list = u->u_blocks;
752 u->u_blocks = b;
753 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754}
755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757compiler_next_block(struct compiler *c)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 basicblock *block = compiler_new_block(c);
760 if (block == NULL)
761 return NULL;
762 c->u->u_curblock->b_next = block;
763 c->u->u_curblock = block;
764 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
767static basicblock *
768compiler_use_next_block(struct compiler *c, basicblock *block)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 assert(block != NULL);
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776/* Returns the offset of the next instruction in the current block's
777 b_instr array. Resizes the b_instr as necessary.
778 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000779*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780
781static int
782compiler_next_instr(struct compiler *c, basicblock *b)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 assert(b != NULL);
785 if (b->b_instr == NULL) {
786 b->b_instr = (struct instr *)PyObject_Malloc(
787 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
788 if (b->b_instr == NULL) {
789 PyErr_NoMemory();
790 return -1;
791 }
792 b->b_ialloc = DEFAULT_BLOCK_SIZE;
793 memset((char *)b->b_instr, 0,
794 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
795 }
796 else if (b->b_iused == b->b_ialloc) {
797 struct instr *tmp;
798 size_t oldsize, newsize;
799 oldsize = b->b_ialloc * sizeof(struct instr);
800 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000801
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700802 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyErr_NoMemory();
804 return -1;
805 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (newsize == 0) {
808 PyErr_NoMemory();
809 return -1;
810 }
811 b->b_ialloc <<= 1;
812 tmp = (struct instr *)PyObject_Realloc(
813 (void *)b->b_instr, newsize);
814 if (tmp == NULL) {
815 PyErr_NoMemory();
816 return -1;
817 }
818 b->b_instr = tmp;
819 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
820 }
821 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822}
823
Christian Heimes2202f872008-02-06 14:31:34 +0000824/* Set the i_lineno member of the instruction at offset off if the
825 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 already been set. If it has been set, the call has no effect.
827
Christian Heimes2202f872008-02-06 14:31:34 +0000828 The line number is reset in the following cases:
829 - when entering a new scope
830 - on each statement
831 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200832 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000833 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836static void
837compiler_set_lineno(struct compiler *c, int off)
838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 basicblock *b;
840 if (c->u->u_lineno_set)
841 return;
842 c->u->u_lineno_set = 1;
843 b = c->u->u_curblock;
844 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845}
846
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200847/* Return the stack effect of opcode with argument oparg.
848
849 Some opcodes have different stack effect when jump to the target and
850 when not jump. The 'jump' parameter specifies the case:
851
852 * 0 -- when not jump
853 * 1 -- when jump
854 * -1 -- maximal
855 */
856/* XXX Make the stack effect of WITH_CLEANUP_START and
857 WITH_CLEANUP_FINISH deterministic. */
858static int
859stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300862 case NOP:
863 case EXTENDED_ARG:
864 return 0;
865
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200866 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 case POP_TOP:
868 return -1;
869 case ROT_TWO:
870 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200871 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return 0;
873 case DUP_TOP:
874 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000875 case DUP_TOP_TWO:
876 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200878 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 case UNARY_POSITIVE:
880 case UNARY_NEGATIVE:
881 case UNARY_NOT:
882 case UNARY_INVERT:
883 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case SET_ADD:
886 case LIST_APPEND:
887 return -1;
888 case MAP_ADD:
889 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000890
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200891 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case BINARY_POWER:
893 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400894 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case BINARY_MODULO:
896 case BINARY_ADD:
897 case BINARY_SUBTRACT:
898 case BINARY_SUBSCR:
899 case BINARY_FLOOR_DIVIDE:
900 case BINARY_TRUE_DIVIDE:
901 return -1;
902 case INPLACE_FLOOR_DIVIDE:
903 case INPLACE_TRUE_DIVIDE:
904 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case INPLACE_ADD:
907 case INPLACE_SUBTRACT:
908 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400909 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case INPLACE_MODULO:
911 return -1;
912 case STORE_SUBSCR:
913 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case DELETE_SUBSCR:
915 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case BINARY_LSHIFT:
918 case BINARY_RSHIFT:
919 case BINARY_AND:
920 case BINARY_XOR:
921 case BINARY_OR:
922 return -1;
923 case INPLACE_POWER:
924 return -1;
925 case GET_ITER:
926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case PRINT_EXPR:
929 return -1;
930 case LOAD_BUILD_CLASS:
931 return 1;
932 case INPLACE_LSHIFT:
933 case INPLACE_RSHIFT:
934 case INPLACE_AND:
935 case INPLACE_XOR:
936 case INPLACE_OR:
937 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200940 /* 1 in the normal flow.
941 * Restore the stack position and push 6 values before jumping to
942 * the handler if an exception be raised. */
943 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400944 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200945 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400946 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200947 /* Pop a variable number of values pushed by WITH_CLEANUP_START
948 * + __exit__ or __aexit__. */
949 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case RETURN_VALUE:
951 return -1;
952 case IMPORT_STAR:
953 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700954 case SETUP_ANNOTATIONS:
955 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case YIELD_VALUE:
957 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500958 case YIELD_FROM:
959 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case POP_BLOCK:
961 return 0;
962 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200963 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200965 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200966 /* Pop 6 values when an exception was raised. */
967 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case STORE_NAME:
970 return -1;
971 case DELETE_NAME:
972 return 0;
973 case UNPACK_SEQUENCE:
974 return oparg-1;
975 case UNPACK_EX:
976 return (oparg&0xFF) + (oparg>>8);
977 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200978 /* -1 at end of iterator, 1 if continue iterating. */
979 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_ATTR:
982 return -2;
983 case DELETE_ATTR:
984 return -1;
985 case STORE_GLOBAL:
986 return -1;
987 case DELETE_GLOBAL:
988 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case LOAD_CONST:
990 return 1;
991 case LOAD_NAME:
992 return 1;
993 case BUILD_TUPLE:
994 case BUILD_LIST:
995 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300996 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400998 case BUILD_LIST_UNPACK:
999 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001000 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001001 case BUILD_SET_UNPACK:
1002 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001003 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001004 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001006 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001007 case BUILD_CONST_KEY_MAP:
1008 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_ATTR:
1010 return 0;
1011 case COMPARE_OP:
1012 return -1;
1013 case IMPORT_NAME:
1014 return -1;
1015 case IMPORT_FROM:
1016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001018 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case JUMP_ABSOLUTE:
1021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001023 case JUMP_IF_TRUE_OR_POP:
1024 case JUMP_IF_FALSE_OR_POP:
1025 return jump ? 0 : -1;
1026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case POP_JUMP_IF_FALSE:
1028 case POP_JUMP_IF_TRUE:
1029 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case LOAD_GLOBAL:
1032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001034 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001036 /* 0 in the normal flow.
1037 * Restore the stack position and push 6 values before jumping to
1038 * the handler if an exception be raised. */
1039 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001040 case BEGIN_FINALLY:
1041 /* Actually pushes 1 value, but count 6 for balancing with
1042 * END_FINALLY and POP_FINALLY.
1043 * This is the main reason of using this opcode instead of
1044 * "LOAD_CONST None". */
1045 return 6;
1046 case CALL_FINALLY:
1047 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case LOAD_FAST:
1050 return 1;
1051 case STORE_FAST:
1052 return -1;
1053 case DELETE_FAST:
1054 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case RAISE_VARARGS:
1057 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001058
1059 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001061 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001062 case CALL_METHOD:
1063 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001065 return -oparg-1;
1066 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001067 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001068 case MAKE_FUNCTION:
1069 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1070 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case BUILD_SLICE:
1072 if (oparg == 3)
1073 return -2;
1074 else
1075 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001077 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 case LOAD_CLOSURE:
1079 return 1;
1080 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001081 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return 1;
1083 case STORE_DEREF:
1084 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001085 case DELETE_DEREF:
1086 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001087
1088 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001089 case GET_AWAITABLE:
1090 return 0;
1091 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001092 /* 0 in the normal flow.
1093 * Restore the stack position to the position before the result
1094 * of __aenter__ and push 6 values before jumping to the handler
1095 * if an exception be raised. */
1096 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001097 case BEFORE_ASYNC_WITH:
1098 return 1;
1099 case GET_AITER:
1100 return 0;
1101 case GET_ANEXT:
1102 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001103 case GET_YIELD_FROM_ITER:
1104 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001105 case END_ASYNC_FOR:
1106 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001107 case FORMAT_VALUE:
1108 /* If there's a fmt_spec on the stack, we go from 2->1,
1109 else 1->1. */
1110 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001111 case LOAD_METHOD:
1112 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001114 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 }
Larry Hastings3a907972013-11-23 14:49:22 -08001116 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117}
1118
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001119int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001120PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1121{
1122 return stack_effect(opcode, oparg, jump);
1123}
1124
1125int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001126PyCompile_OpcodeStackEffect(int opcode, int oparg)
1127{
1128 return stack_effect(opcode, oparg, -1);
1129}
1130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131/* Add an opcode with no argument.
1132 Returns 0 on failure, 1 on success.
1133*/
1134
1135static int
1136compiler_addop(struct compiler *c, int opcode)
1137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 basicblock *b;
1139 struct instr *i;
1140 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001141 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 off = compiler_next_instr(c, c->u->u_curblock);
1143 if (off < 0)
1144 return 0;
1145 b = c->u->u_curblock;
1146 i = &b->b_instr[off];
1147 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001148 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (opcode == RETURN_VALUE)
1150 b->b_return = 1;
1151 compiler_set_lineno(c, off);
1152 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153}
1154
Victor Stinnerf8e32212013-11-19 23:56:34 +01001155static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1157{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001158 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001161 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001163 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001165 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001166 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001167 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return -1;
1170 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 Py_DECREF(v);
1173 return -1;
1174 }
1175 Py_DECREF(v);
1176 }
1177 else
1178 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001179 return arg;
1180}
1181
1182static Py_ssize_t
1183compiler_add_const(struct compiler *c, PyObject *o)
1184{
1185 PyObject *t;
1186 Py_ssize_t arg;
1187
1188 t = _PyCode_ConstantKey(o);
1189 if (t == NULL)
1190 return -1;
1191
1192 arg = compiler_add_o(c, c->u->u_consts, t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 Py_DECREF(t);
1194 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195}
1196
1197static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001198compiler_addop_load_const(struct compiler *c, PyObject *o)
1199{
1200 Py_ssize_t arg = compiler_add_const(c, o);
1201 if (arg < 0)
1202 return 0;
1203 return compiler_addop_i(c, LOAD_CONST, arg);
1204}
1205
1206static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207compiler_addop_o(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 = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 return compiler_addop_i(c, opcode, arg);
1214}
1215
1216static int
1217compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001220 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1222 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224 arg = compiler_add_o(c, dict, mangled);
1225 Py_DECREF(mangled);
1226 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001227 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228 return compiler_addop_i(c, opcode, arg);
1229}
1230
1231/* Add an opcode with an integer argument.
1232 Returns 0 on failure, 1 on success.
1233*/
1234
1235static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001236compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 struct instr *i;
1239 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001240
Victor Stinner2ad474b2016-03-01 23:34:47 +01001241 /* oparg value is unsigned, but a signed C int is usually used to store
1242 it in the C code (like Python/ceval.c).
1243
1244 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1245
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001246 The argument of a concrete bytecode instruction is limited to 8-bit.
1247 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1248 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001249 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 off = compiler_next_instr(c, c->u->u_curblock);
1252 if (off < 0)
1253 return 0;
1254 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001255 i->i_opcode = opcode;
1256 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 compiler_set_lineno(c, off);
1258 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259}
1260
1261static int
1262compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 struct instr *i;
1265 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001267 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 assert(b != NULL);
1269 off = compiler_next_instr(c, c->u->u_curblock);
1270 if (off < 0)
1271 return 0;
1272 i = &c->u->u_curblock->b_instr[off];
1273 i->i_opcode = opcode;
1274 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (absolute)
1276 i->i_jabs = 1;
1277 else
1278 i->i_jrel = 1;
1279 compiler_set_lineno(c, off);
1280 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001283/* NEXT_BLOCK() creates an implicit jump from the current block
1284 to the new block.
1285
1286 The returns inside this macro make it impossible to decref objects
1287 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (compiler_next_block((C)) == NULL) \
1291 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292}
1293
1294#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!compiler_addop((C), (OP))) \
1296 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001299#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (!compiler_addop((C), (OP))) { \
1301 compiler_exit_scope(c); \
1302 return 0; \
1303 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001304}
1305
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001306#define ADDOP_LOAD_CONST(C, O) { \
1307 if (!compiler_addop_load_const((C), (O))) \
1308 return 0; \
1309}
1310
1311/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1312#define ADDOP_LOAD_CONST_NEW(C, O) { \
1313 PyObject *__new_const = (O); \
1314 if (__new_const == NULL) { \
1315 return 0; \
1316 } \
1317 if (!compiler_addop_load_const((C), __new_const)) { \
1318 Py_DECREF(__new_const); \
1319 return 0; \
1320 } \
1321 Py_DECREF(__new_const); \
1322}
1323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1326 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327}
1328
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001329/* Same as ADDOP_O, but steals a reference. */
1330#define ADDOP_N(C, OP, O, TYPE) { \
1331 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1332 Py_DECREF((O)); \
1333 return 0; \
1334 } \
1335 Py_DECREF((O)); \
1336}
1337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1340 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341}
1342
1343#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (!compiler_addop_i((C), (OP), (O))) \
1345 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346}
1347
1348#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (!compiler_addop_j((C), (OP), (O), 1)) \
1350 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351}
1352
1353#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 if (!compiler_addop_j((C), (OP), (O), 0)) \
1355 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356}
1357
1358/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1359 the ASDL name to synthesize the name of the C type and the visit function.
1360*/
1361
1362#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 if (!compiler_visit_ ## TYPE((C), (V))) \
1364 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365}
1366
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001367#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!compiler_visit_ ## TYPE((C), (V))) { \
1369 compiler_exit_scope(c); \
1370 return 0; \
1371 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001372}
1373
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001374#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (!compiler_visit_slice((C), (V), (CTX))) \
1376 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377}
1378
1379#define VISIT_SEQ(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 return 0; \
1386 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387}
1388
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001389#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 int _i; \
1391 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1392 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1393 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1394 if (!compiler_visit_ ## TYPE((C), elt)) { \
1395 compiler_exit_scope(c); \
1396 return 0; \
1397 } \
1398 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001399}
1400
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001401/* Search if variable annotations are present statically in a block. */
1402
1403static int
1404find_ann(asdl_seq *stmts)
1405{
1406 int i, j, res = 0;
1407 stmt_ty st;
1408
1409 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1410 st = (stmt_ty)asdl_seq_GET(stmts, i);
1411 switch (st->kind) {
1412 case AnnAssign_kind:
1413 return 1;
1414 case For_kind:
1415 res = find_ann(st->v.For.body) ||
1416 find_ann(st->v.For.orelse);
1417 break;
1418 case AsyncFor_kind:
1419 res = find_ann(st->v.AsyncFor.body) ||
1420 find_ann(st->v.AsyncFor.orelse);
1421 break;
1422 case While_kind:
1423 res = find_ann(st->v.While.body) ||
1424 find_ann(st->v.While.orelse);
1425 break;
1426 case If_kind:
1427 res = find_ann(st->v.If.body) ||
1428 find_ann(st->v.If.orelse);
1429 break;
1430 case With_kind:
1431 res = find_ann(st->v.With.body);
1432 break;
1433 case AsyncWith_kind:
1434 res = find_ann(st->v.AsyncWith.body);
1435 break;
1436 case Try_kind:
1437 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1438 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1439 st->v.Try.handlers, j);
1440 if (find_ann(handler->v.ExceptHandler.body)) {
1441 return 1;
1442 }
1443 }
1444 res = find_ann(st->v.Try.body) ||
1445 find_ann(st->v.Try.finalbody) ||
1446 find_ann(st->v.Try.orelse);
1447 break;
1448 default:
1449 res = 0;
1450 }
1451 if (res) {
1452 break;
1453 }
1454 }
1455 return res;
1456}
1457
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001458/*
1459 * Frame block handling functions
1460 */
1461
1462static int
1463compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1464 basicblock *exit)
1465{
1466 struct fblockinfo *f;
1467 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1468 PyErr_SetString(PyExc_SyntaxError,
1469 "too many statically nested blocks");
1470 return 0;
1471 }
1472 f = &c->u->u_fblock[c->u->u_nfblocks++];
1473 f->fb_type = t;
1474 f->fb_block = b;
1475 f->fb_exit = exit;
1476 return 1;
1477}
1478
1479static void
1480compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1481{
1482 struct compiler_unit *u = c->u;
1483 assert(u->u_nfblocks > 0);
1484 u->u_nfblocks--;
1485 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1486 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1487}
1488
1489/* Unwind a frame block. If preserve_tos is true, the TOS before
1490 * popping the blocks will be restored afterwards.
1491 */
1492static int
1493compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1494 int preserve_tos)
1495{
1496 switch (info->fb_type) {
1497 case WHILE_LOOP:
1498 return 1;
1499
1500 case FINALLY_END:
1501 ADDOP_I(c, POP_FINALLY, preserve_tos);
1502 return 1;
1503
1504 case FOR_LOOP:
1505 /* Pop the iterator */
1506 if (preserve_tos) {
1507 ADDOP(c, ROT_TWO);
1508 }
1509 ADDOP(c, POP_TOP);
1510 return 1;
1511
1512 case EXCEPT:
1513 ADDOP(c, POP_BLOCK);
1514 return 1;
1515
1516 case FINALLY_TRY:
1517 ADDOP(c, POP_BLOCK);
1518 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1519 return 1;
1520
1521 case WITH:
1522 case ASYNC_WITH:
1523 ADDOP(c, POP_BLOCK);
1524 if (preserve_tos) {
1525 ADDOP(c, ROT_TWO);
1526 }
1527 ADDOP(c, BEGIN_FINALLY);
1528 ADDOP(c, WITH_CLEANUP_START);
1529 if (info->fb_type == ASYNC_WITH) {
1530 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001531 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001532 ADDOP(c, YIELD_FROM);
1533 }
1534 ADDOP(c, WITH_CLEANUP_FINISH);
1535 ADDOP_I(c, POP_FINALLY, 0);
1536 return 1;
1537
1538 case HANDLER_CLEANUP:
1539 if (preserve_tos) {
1540 ADDOP(c, ROT_FOUR);
1541 }
1542 if (info->fb_exit) {
1543 ADDOP(c, POP_BLOCK);
1544 ADDOP(c, POP_EXCEPT);
1545 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1546 }
1547 else {
1548 ADDOP(c, POP_EXCEPT);
1549 }
1550 return 1;
1551 }
1552 Py_UNREACHABLE();
1553}
1554
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001555/* Compile a sequence of statements, checking for a docstring
1556 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557
1558static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001559compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001560{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001561 int i = 0;
1562 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001563 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001564
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001565 /* Set current line number to the line number of first statement.
1566 This way line number for SETUP_ANNOTATIONS will always
1567 coincide with the line number of first "real" statement in module.
1568 If body is empy, then lineno will be set later in assemble. */
1569 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1570 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001571 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001572 c->u->u_lineno = st->lineno;
1573 }
1574 /* Every annotated class and module should have __annotations__. */
1575 if (find_ann(stmts)) {
1576 ADDOP(c, SETUP_ANNOTATIONS);
1577 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001578 if (!asdl_seq_LEN(stmts))
1579 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001580 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001581 if (c->c_optimize < 2) {
1582 docstring = _PyAST_GetDocString(stmts);
1583 if (docstring) {
1584 i = 1;
1585 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1586 assert(st->kind == Expr_kind);
1587 VISIT(c, expr, st->v.Expr.value);
1588 if (!compiler_nameop(c, __doc__, Store))
1589 return 0;
1590 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001592 for (; i < asdl_seq_LEN(stmts); i++)
1593 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595}
1596
1597static PyCodeObject *
1598compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 PyCodeObject *co;
1601 int addNone = 1;
1602 static PyObject *module;
1603 if (!module) {
1604 module = PyUnicode_InternFromString("<module>");
1605 if (!module)
1606 return NULL;
1607 }
1608 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001609 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 return NULL;
1611 switch (mod->kind) {
1612 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001613 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 compiler_exit_scope(c);
1615 return 0;
1616 }
1617 break;
1618 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001619 if (find_ann(mod->v.Interactive.body)) {
1620 ADDOP(c, SETUP_ANNOTATIONS);
1621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 c->c_interactive = 1;
1623 VISIT_SEQ_IN_SCOPE(c, stmt,
1624 mod->v.Interactive.body);
1625 break;
1626 case Expression_kind:
1627 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1628 addNone = 0;
1629 break;
1630 case Suite_kind:
1631 PyErr_SetString(PyExc_SystemError,
1632 "suite should not be possible");
1633 return 0;
1634 default:
1635 PyErr_Format(PyExc_SystemError,
1636 "module kind %d should not be possible",
1637 mod->kind);
1638 return 0;
1639 }
1640 co = assemble(c, addNone);
1641 compiler_exit_scope(c);
1642 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001643}
1644
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001645/* The test for LOCAL must come before the test for FREE in order to
1646 handle classes where name is both local and free. The local var is
1647 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001648*/
1649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001650static int
1651get_ref_type(struct compiler *c, PyObject *name)
1652{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001653 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001654 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001655 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001656 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001657 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (scope == 0) {
1659 char buf[350];
1660 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001661 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001663 PyUnicode_AsUTF8(name),
1664 PyUnicode_AsUTF8(c->u->u_name),
1665 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1666 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1667 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1668 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 );
1670 Py_FatalError(buf);
1671 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674}
1675
1676static int
1677compiler_lookup_arg(PyObject *dict, PyObject *name)
1678{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001679 PyObject *v;
1680 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001682 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001683 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684}
1685
1686static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001687compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001689 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001690 if (qualname == NULL)
1691 qualname = co->co_name;
1692
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001693 if (free) {
1694 for (i = 0; i < free; ++i) {
1695 /* Bypass com_addop_varname because it will generate
1696 LOAD_DEREF but LOAD_CLOSURE is needed.
1697 */
1698 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1699 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001701 /* Special case: If a class contains a method with a
1702 free variable that has the same name as a method,
1703 the name will be considered free *and* local in the
1704 class. It should be handled by the closure, as
1705 well as by the normal name loookup logic.
1706 */
1707 reftype = get_ref_type(c, name);
1708 if (reftype == CELL)
1709 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1710 else /* (reftype == FREE) */
1711 arg = compiler_lookup_arg(c->u->u_freevars, name);
1712 if (arg == -1) {
1713 fprintf(stderr,
1714 "lookup %s in %s %d %d\n"
1715 "freevars of %s: %s\n",
1716 PyUnicode_AsUTF8(PyObject_Repr(name)),
1717 PyUnicode_AsUTF8(c->u->u_name),
1718 reftype, arg,
1719 PyUnicode_AsUTF8(co->co_name),
1720 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1721 Py_FatalError("compiler_make_closure()");
1722 }
1723 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001725 flags |= 0x08;
1726 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001728 ADDOP_LOAD_CONST(c, (PyObject*)co);
1729 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001730 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732}
1733
1734static int
1735compiler_decorators(struct compiler *c, asdl_seq* decos)
1736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (!decos)
1740 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1743 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1744 }
1745 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001746}
1747
1748static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001749compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001751{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001752 /* Push a dict of keyword-only default values.
1753
1754 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1755 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001756 int i;
1757 PyObject *keys = NULL;
1758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1760 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1761 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1762 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001763 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001764 if (!mangled) {
1765 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001767 if (keys == NULL) {
1768 keys = PyList_New(1);
1769 if (keys == NULL) {
1770 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001771 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001772 }
1773 PyList_SET_ITEM(keys, 0, mangled);
1774 }
1775 else {
1776 int res = PyList_Append(keys, mangled);
1777 Py_DECREF(mangled);
1778 if (res == -1) {
1779 goto error;
1780 }
1781 }
1782 if (!compiler_visit_expr(c, default_)) {
1783 goto error;
1784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 }
1786 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001787 if (keys != NULL) {
1788 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1789 PyObject *keys_tuple = PyList_AsTuple(keys);
1790 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001791 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001792 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001793 assert(default_count > 0);
1794 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001795 }
1796 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001797 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001798 }
1799
1800error:
1801 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001802 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001803}
1804
1805static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001806compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1807{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001808 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001809 return 1;
1810}
1811
1812static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001813compiler_visit_argannotation(struct compiler *c, identifier id,
1814 expr_ty annotation, PyObject *names)
1815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001817 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001818 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1819 VISIT(c, annexpr, annotation)
1820 }
1821 else {
1822 VISIT(c, expr, annotation);
1823 }
Victor Stinner065efc32014-02-18 22:07:56 +01001824 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001825 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001826 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001827 if (PyList_Append(names, mangled) < 0) {
1828 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001829 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001830 }
1831 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001833 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001834}
1835
1836static int
1837compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1838 PyObject *names)
1839{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001840 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 for (i = 0; i < asdl_seq_LEN(args); i++) {
1842 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001843 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 c,
1845 arg->arg,
1846 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001847 names))
1848 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001850 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001851}
1852
1853static int
1854compiler_visit_annotations(struct compiler *c, arguments_ty args,
1855 expr_ty returns)
1856{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001857 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001858 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001859
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001860 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 */
1862 static identifier return_str;
1863 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001864 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 names = PyList_New(0);
1866 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001867 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001868
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001869 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001871 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001872 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001873 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001875 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001877 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001878 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001879 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (!return_str) {
1883 return_str = PyUnicode_InternFromString("return");
1884 if (!return_str)
1885 goto error;
1886 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001887 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 goto error;
1889 }
1890
1891 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001893 PyObject *keytuple = PyList_AsTuple(names);
1894 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001895 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001896 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001897 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001899 else {
1900 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001901 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001902 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001903
1904error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001906 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001907}
1908
1909static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001910compiler_visit_defaults(struct compiler *c, arguments_ty args)
1911{
1912 VISIT_SEQ(c, expr, args->defaults);
1913 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1914 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915}
1916
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001917static Py_ssize_t
1918compiler_default_arguments(struct compiler *c, arguments_ty args)
1919{
1920 Py_ssize_t funcflags = 0;
1921 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001922 if (!compiler_visit_defaults(c, args))
1923 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 funcflags |= 0x01;
1925 }
1926 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001927 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001928 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001929 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001930 return -1;
1931 }
1932 else if (res > 0) {
1933 funcflags |= 0x02;
1934 }
1935 }
1936 return funcflags;
1937}
1938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939static int
Yury Selivanov75445082015-05-11 22:57:16 -04001940compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001943 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04001944 arguments_ty args;
1945 expr_ty returns;
1946 identifier name;
1947 asdl_seq* decos;
1948 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09001949 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001950 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001951 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001952 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953
Yury Selivanov75445082015-05-11 22:57:16 -04001954 if (is_async) {
1955 assert(s->kind == AsyncFunctionDef_kind);
1956
1957 args = s->v.AsyncFunctionDef.args;
1958 returns = s->v.AsyncFunctionDef.returns;
1959 decos = s->v.AsyncFunctionDef.decorator_list;
1960 name = s->v.AsyncFunctionDef.name;
1961 body = s->v.AsyncFunctionDef.body;
1962
1963 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1964 } else {
1965 assert(s->kind == FunctionDef_kind);
1966
1967 args = s->v.FunctionDef.args;
1968 returns = s->v.FunctionDef.returns;
1969 decos = s->v.FunctionDef.decorator_list;
1970 name = s->v.FunctionDef.name;
1971 body = s->v.FunctionDef.body;
1972
1973 scope_type = COMPILER_SCOPE_FUNCTION;
1974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (!compiler_decorators(c, decos))
1977 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001978
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001979 firstlineno = s->lineno;
1980 if (asdl_seq_LEN(decos)) {
1981 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
1982 }
1983
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001984 funcflags = compiler_default_arguments(c, args);
1985 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001987 }
1988
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001989 annotations = compiler_visit_annotations(c, args, returns);
1990 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 return 0;
1992 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001993 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001994 funcflags |= 0x04;
1995 }
1996
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001997 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 return 0;
1999 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000
INADA Naokicb41b272017-02-23 00:31:59 +09002001 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002002 if (c->c_optimize < 2) {
2003 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002004 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002005 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 compiler_exit_scope(c);
2007 return 0;
2008 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 c->u->u_argcount = asdl_seq_LEN(args->args);
2011 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002012 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002014 qualname = c->u->u_qualname;
2015 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002017 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002018 Py_XDECREF(qualname);
2019 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002021 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002023 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002024 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* decorators */
2028 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2029 ADDOP_I(c, CALL_FUNCTION, 1);
2030 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031
Yury Selivanov75445082015-05-11 22:57:16 -04002032 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033}
2034
2035static int
2036compiler_class(struct compiler *c, stmt_ty s)
2037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 PyCodeObject *co;
2039 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002040 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if (!compiler_decorators(c, decos))
2044 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002045
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002046 firstlineno = s->lineno;
2047 if (asdl_seq_LEN(decos)) {
2048 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2049 }
2050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 /* ultimately generate code for:
2052 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2053 where:
2054 <func> is a function/closure created from the class body;
2055 it has a single argument (__locals__) where the dict
2056 (or MutableSequence) representing the locals is passed
2057 <name> is the class name
2058 <bases> is the positional arguments and *varargs argument
2059 <keywords> is the keyword arguments and **kwds argument
2060 This borrows from compiler_call.
2061 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002064 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002065 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 return 0;
2067 /* this block represents what we do in the new scope */
2068 {
2069 /* use the class name for name mangling */
2070 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002071 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 /* load (global) __name__ ... */
2073 str = PyUnicode_InternFromString("__name__");
2074 if (!str || !compiler_nameop(c, str, Load)) {
2075 Py_XDECREF(str);
2076 compiler_exit_scope(c);
2077 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 Py_DECREF(str);
2080 /* ... and store it as __module__ */
2081 str = PyUnicode_InternFromString("__module__");
2082 if (!str || !compiler_nameop(c, str, Store)) {
2083 Py_XDECREF(str);
2084 compiler_exit_scope(c);
2085 return 0;
2086 }
2087 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002088 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002089 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002090 str = PyUnicode_InternFromString("__qualname__");
2091 if (!str || !compiler_nameop(c, str, Store)) {
2092 Py_XDECREF(str);
2093 compiler_exit_scope(c);
2094 return 0;
2095 }
2096 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002098 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 compiler_exit_scope(c);
2100 return 0;
2101 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002102 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002103 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002104 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002105 str = PyUnicode_InternFromString("__class__");
2106 if (str == NULL) {
2107 compiler_exit_scope(c);
2108 return 0;
2109 }
2110 i = compiler_lookup_arg(c->u->u_cellvars, str);
2111 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002112 if (i < 0) {
2113 compiler_exit_scope(c);
2114 return 0;
2115 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002116 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002119 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002120 str = PyUnicode_InternFromString("__classcell__");
2121 if (!str || !compiler_nameop(c, str, Store)) {
2122 Py_XDECREF(str);
2123 compiler_exit_scope(c);
2124 return 0;
2125 }
2126 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002128 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002129 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002130 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002131 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002132 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002133 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 /* create the code object */
2135 co = assemble(c, 1);
2136 }
2137 /* leave the new scope */
2138 compiler_exit_scope(c);
2139 if (co == NULL)
2140 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 /* 2. load the 'build_class' function */
2143 ADDOP(c, LOAD_BUILD_CLASS);
2144
2145 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002146 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 Py_DECREF(co);
2148
2149 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002150 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151
2152 /* 5. generate the rest of the code for the call */
2153 if (!compiler_call_helper(c, 2,
2154 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002155 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 return 0;
2157
2158 /* 6. apply decorators */
2159 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2160 ADDOP_I(c, CALL_FUNCTION, 1);
2161 }
2162
2163 /* 7. store into <name> */
2164 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2165 return 0;
2166 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167}
2168
2169static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002170cmpop(cmpop_ty op)
2171{
2172 switch (op) {
2173 case Eq:
2174 return PyCmp_EQ;
2175 case NotEq:
2176 return PyCmp_NE;
2177 case Lt:
2178 return PyCmp_LT;
2179 case LtE:
2180 return PyCmp_LE;
2181 case Gt:
2182 return PyCmp_GT;
2183 case GtE:
2184 return PyCmp_GE;
2185 case Is:
2186 return PyCmp_IS;
2187 case IsNot:
2188 return PyCmp_IS_NOT;
2189 case In:
2190 return PyCmp_IN;
2191 case NotIn:
2192 return PyCmp_NOT_IN;
2193 default:
2194 return PyCmp_BAD;
2195 }
2196}
2197
2198static int
2199compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2200{
2201 switch (e->kind) {
2202 case UnaryOp_kind:
2203 if (e->v.UnaryOp.op == Not)
2204 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2205 /* fallback to general implementation */
2206 break;
2207 case BoolOp_kind: {
2208 asdl_seq *s = e->v.BoolOp.values;
2209 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2210 assert(n >= 0);
2211 int cond2 = e->v.BoolOp.op == Or;
2212 basicblock *next2 = next;
2213 if (!cond2 != !cond) {
2214 next2 = compiler_new_block(c);
2215 if (next2 == NULL)
2216 return 0;
2217 }
2218 for (i = 0; i < n; ++i) {
2219 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2220 return 0;
2221 }
2222 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2223 return 0;
2224 if (next2 != next)
2225 compiler_use_next_block(c, next2);
2226 return 1;
2227 }
2228 case IfExp_kind: {
2229 basicblock *end, *next2;
2230 end = compiler_new_block(c);
2231 if (end == NULL)
2232 return 0;
2233 next2 = compiler_new_block(c);
2234 if (next2 == NULL)
2235 return 0;
2236 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2237 return 0;
2238 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2239 return 0;
2240 ADDOP_JREL(c, JUMP_FORWARD, end);
2241 compiler_use_next_block(c, next2);
2242 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2243 return 0;
2244 compiler_use_next_block(c, end);
2245 return 1;
2246 }
2247 case Compare_kind: {
2248 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2249 if (n > 0) {
2250 basicblock *cleanup = compiler_new_block(c);
2251 if (cleanup == NULL)
2252 return 0;
2253 VISIT(c, expr, e->v.Compare.left);
2254 for (i = 0; i < n; i++) {
2255 VISIT(c, expr,
2256 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2257 ADDOP(c, DUP_TOP);
2258 ADDOP(c, ROT_THREE);
2259 ADDOP_I(c, COMPARE_OP,
2260 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2261 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2262 NEXT_BLOCK(c);
2263 }
2264 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2265 ADDOP_I(c, COMPARE_OP,
2266 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2267 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2268 basicblock *end = compiler_new_block(c);
2269 if (end == NULL)
2270 return 0;
2271 ADDOP_JREL(c, JUMP_FORWARD, end);
2272 compiler_use_next_block(c, cleanup);
2273 ADDOP(c, POP_TOP);
2274 if (!cond) {
2275 ADDOP_JREL(c, JUMP_FORWARD, next);
2276 }
2277 compiler_use_next_block(c, end);
2278 return 1;
2279 }
2280 /* fallback to general implementation */
2281 break;
2282 }
2283 default:
2284 /* fallback to general implementation */
2285 break;
2286 }
2287
2288 /* general implementation */
2289 VISIT(c, expr, e);
2290 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2291 return 1;
2292}
2293
2294static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002295compiler_ifexp(struct compiler *c, expr_ty e)
2296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 basicblock *end, *next;
2298
2299 assert(e->kind == IfExp_kind);
2300 end = compiler_new_block(c);
2301 if (end == NULL)
2302 return 0;
2303 next = compiler_new_block(c);
2304 if (next == NULL)
2305 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002306 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2307 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 VISIT(c, expr, e->v.IfExp.body);
2309 ADDOP_JREL(c, JUMP_FORWARD, end);
2310 compiler_use_next_block(c, next);
2311 VISIT(c, expr, e->v.IfExp.orelse);
2312 compiler_use_next_block(c, end);
2313 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002314}
2315
2316static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317compiler_lambda(struct compiler *c, expr_ty e)
2318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002320 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002322 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 arguments_ty args = e->v.Lambda.args;
2324 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (!name) {
2327 name = PyUnicode_InternFromString("<lambda>");
2328 if (!name)
2329 return 0;
2330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002332 funcflags = compiler_default_arguments(c, args);
2333 if (funcflags == -1) {
2334 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002336
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002337 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002338 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Make None the first constant, so the lambda can't have a
2342 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002343 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 c->u->u_argcount = asdl_seq_LEN(args->args);
2347 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2348 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2349 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002350 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 }
2352 else {
2353 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002354 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002356 qualname = c->u->u_qualname;
2357 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002359 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002362 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002363 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 Py_DECREF(co);
2365
2366 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367}
2368
2369static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370compiler_if(struct compiler *c, stmt_ty s)
2371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 basicblock *end, *next;
2373 int constant;
2374 assert(s->kind == If_kind);
2375 end = compiler_new_block(c);
2376 if (end == NULL)
2377 return 0;
2378
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002379 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* constant = 0: "if 0"
2381 * constant = 1: "if 1", "if 2", ...
2382 * constant = -1: rest */
2383 if (constant == 0) {
2384 if (s->v.If.orelse)
2385 VISIT_SEQ(c, stmt, s->v.If.orelse);
2386 } else if (constant == 1) {
2387 VISIT_SEQ(c, stmt, s->v.If.body);
2388 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002389 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 next = compiler_new_block(c);
2391 if (next == NULL)
2392 return 0;
2393 }
2394 else
2395 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002396 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2397 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002399 if (asdl_seq_LEN(s->v.If.orelse)) {
2400 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 compiler_use_next_block(c, next);
2402 VISIT_SEQ(c, stmt, s->v.If.orelse);
2403 }
2404 }
2405 compiler_use_next_block(c, end);
2406 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407}
2408
2409static int
2410compiler_for(struct compiler *c, stmt_ty s)
2411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 start = compiler_new_block(c);
2415 cleanup = compiler_new_block(c);
2416 end = compiler_new_block(c);
2417 if (start == NULL || end == NULL || cleanup == NULL)
2418 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002419
2420 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 VISIT(c, expr, s->v.For.iter);
2424 ADDOP(c, GET_ITER);
2425 compiler_use_next_block(c, start);
2426 ADDOP_JREL(c, FOR_ITER, cleanup);
2427 VISIT(c, expr, s->v.For.target);
2428 VISIT_SEQ(c, stmt, s->v.For.body);
2429 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2430 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002431
2432 compiler_pop_fblock(c, FOR_LOOP, start);
2433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 VISIT_SEQ(c, stmt, s->v.For.orelse);
2435 compiler_use_next_block(c, end);
2436 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437}
2438
Yury Selivanov75445082015-05-11 22:57:16 -04002439
2440static int
2441compiler_async_for(struct compiler *c, stmt_ty s)
2442{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002443 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002444 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2445 return compiler_error(c, "'async for' outside async function");
2446 }
2447
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002448 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002449 except = compiler_new_block(c);
2450 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002451
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002452 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002453 return 0;
2454
2455 VISIT(c, expr, s->v.AsyncFor.iter);
2456 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002457
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002458 compiler_use_next_block(c, start);
2459 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2460 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002461
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002462 /* SETUP_FINALLY to guard the __anext__ call */
2463 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002464 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002465 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002466 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002467 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002468
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002469 /* Success block for __anext__ */
2470 VISIT(c, expr, s->v.AsyncFor.target);
2471 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2472 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2473
2474 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002475
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002476 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002477 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002478 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002479
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002480 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002481 VISIT_SEQ(c, stmt, s->v.For.orelse);
2482
2483 compiler_use_next_block(c, end);
2484
2485 return 1;
2486}
2487
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488static int
2489compiler_while(struct compiler *c, stmt_ty s)
2490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002492 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (constant == 0) {
2495 if (s->v.While.orelse)
2496 VISIT_SEQ(c, stmt, s->v.While.orelse);
2497 return 1;
2498 }
2499 loop = compiler_new_block(c);
2500 end = compiler_new_block(c);
2501 if (constant == -1) {
2502 anchor = compiler_new_block(c);
2503 if (anchor == NULL)
2504 return 0;
2505 }
2506 if (loop == NULL || end == NULL)
2507 return 0;
2508 if (s->v.While.orelse) {
2509 orelse = compiler_new_block(c);
2510 if (orelse == NULL)
2511 return 0;
2512 }
2513 else
2514 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002517 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 return 0;
2519 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002520 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2521 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 }
2523 VISIT_SEQ(c, stmt, s->v.While.body);
2524 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 /* XXX should the two POP instructions be in a separate block
2527 if there is no else clause ?
2528 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002530 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002532 compiler_pop_fblock(c, WHILE_LOOP, loop);
2533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (orelse != NULL) /* what if orelse is just pass? */
2535 VISIT_SEQ(c, stmt, s->v.While.orelse);
2536 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539}
2540
2541static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002542compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002544 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002545 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002546 if (c->u->u_ste->ste_type != FunctionBlock)
2547 return compiler_error(c, "'return' outside function");
2548 if (s->v.Return.value != NULL &&
2549 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2550 {
2551 return compiler_error(
2552 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002554 if (preserve_tos) {
2555 VISIT(c, expr, s->v.Return.value);
2556 }
2557 for (int depth = c->u->u_nfblocks; depth--;) {
2558 struct fblockinfo *info = &c->u->u_fblock[depth];
2559
2560 if (!compiler_unwind_fblock(c, info, preserve_tos))
2561 return 0;
2562 }
2563 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002564 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002565 }
2566 else if (!preserve_tos) {
2567 VISIT(c, expr, s->v.Return.value);
2568 }
2569 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572}
2573
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002574static int
2575compiler_break(struct compiler *c)
2576{
2577 for (int depth = c->u->u_nfblocks; depth--;) {
2578 struct fblockinfo *info = &c->u->u_fblock[depth];
2579
2580 if (!compiler_unwind_fblock(c, info, 0))
2581 return 0;
2582 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2583 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2584 return 1;
2585 }
2586 }
2587 return compiler_error(c, "'break' outside loop");
2588}
2589
2590static int
2591compiler_continue(struct compiler *c)
2592{
2593 for (int depth = c->u->u_nfblocks; depth--;) {
2594 struct fblockinfo *info = &c->u->u_fblock[depth];
2595
2596 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2597 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2598 return 1;
2599 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002600 if (!compiler_unwind_fblock(c, info, 0))
2601 return 0;
2602 }
2603 return compiler_error(c, "'continue' not properly in loop");
2604}
2605
2606
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608
2609 SETUP_FINALLY L
2610 <code for body>
2611 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002612 BEGIN_FINALLY
2613 L:
2614 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 END_FINALLY
2616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 The special instructions use the block stack. Each block
2618 stack entry contains the instruction that created it (here
2619 SETUP_FINALLY), the level of the value stack at the time the
2620 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 Pushes the current value stack level and the label
2624 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002626 Pops en entry from the block stack.
2627 BEGIN_FINALLY
2628 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002630 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2631 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002634 when a SETUP_FINALLY entry is found, the raised and the caught
2635 exceptions are pushed onto the value stack (and the exception
2636 condition is cleared), and the interpreter jumps to the label
2637 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638*/
2639
2640static int
2641compiler_try_finally(struct compiler *c, stmt_ty s)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 body = compiler_new_block(c);
2646 end = compiler_new_block(c);
2647 if (body == NULL || end == NULL)
2648 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002650 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 ADDOP_JREL(c, SETUP_FINALLY, end);
2652 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002653 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002655 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2656 if (!compiler_try_except(c, s))
2657 return 0;
2658 }
2659 else {
2660 VISIT_SEQ(c, stmt, s->v.Try.body);
2661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002663 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002666 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002668 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002670 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 ADDOP(c, END_FINALLY);
2672 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674}
2675
2676/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002677 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 (The contents of the value stack is shown in [], with the top
2679 at the right; 'tb' is trace-back info, 'val' the exception's
2680 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681
2682 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002683 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 [] <code for S>
2685 [] POP_BLOCK
2686 [] JUMP_FORWARD L0
2687
2688 [tb, val, exc] L1: DUP )
2689 [tb, val, exc, exc] <evaluate E1> )
2690 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2691 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2692 [tb, val, exc] POP
2693 [tb, val] <assign to V1> (or POP if no V1)
2694 [tb] POP
2695 [] <code for S1>
2696 JUMP_FORWARD L0
2697
2698 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 .............................etc.......................
2700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2702
2703 [] L0: <next statement>
2704
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 Of course, parts are not generated if Vi or Ei is not present.
2706*/
2707static int
2708compiler_try_except(struct compiler *c, stmt_ty s)
2709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002711 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 body = compiler_new_block(c);
2714 except = compiler_new_block(c);
2715 orelse = compiler_new_block(c);
2716 end = compiler_new_block(c);
2717 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2718 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002719 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002721 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002723 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 ADDOP(c, POP_BLOCK);
2725 compiler_pop_fblock(c, EXCEPT, body);
2726 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002727 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 compiler_use_next_block(c, except);
2729 for (i = 0; i < n; i++) {
2730 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002731 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 if (!handler->v.ExceptHandler.type && i < n-1)
2733 return compiler_error(c, "default 'except:' must be last");
2734 c->u->u_lineno_set = 0;
2735 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002736 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 except = compiler_new_block(c);
2738 if (except == NULL)
2739 return 0;
2740 if (handler->v.ExceptHandler.type) {
2741 ADDOP(c, DUP_TOP);
2742 VISIT(c, expr, handler->v.ExceptHandler.type);
2743 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2744 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2745 }
2746 ADDOP(c, POP_TOP);
2747 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002748 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002749
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002750 cleanup_end = compiler_new_block(c);
2751 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002752 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002753 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002754 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002755
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002756 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2757 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002759 /*
2760 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002761 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002762 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002763 try:
2764 # body
2765 finally:
2766 name = None
2767 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002768 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002770 /* second try: */
2771 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2772 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002773 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002774 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002776 /* second # body */
2777 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2778 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002779 ADDOP(c, BEGIN_FINALLY);
2780 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002782 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002783 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002785 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002787 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002788 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002789 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002790 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002792 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002793 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002794 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 }
2796 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002797 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002799 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002800 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002801 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802
Guido van Rossumb940e112007-01-10 16:19:56 +00002803 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002804 ADDOP(c, POP_TOP);
2805 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002807 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002809 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002810 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 }
2812 ADDOP_JREL(c, JUMP_FORWARD, end);
2813 compiler_use_next_block(c, except);
2814 }
2815 ADDOP(c, END_FINALLY);
2816 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002817 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 compiler_use_next_block(c, end);
2819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820}
2821
2822static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002823compiler_try(struct compiler *c, stmt_ty s) {
2824 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2825 return compiler_try_finally(c, s);
2826 else
2827 return compiler_try_except(c, s);
2828}
2829
2830
2831static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832compiler_import_as(struct compiler *c, identifier name, identifier asname)
2833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 /* The IMPORT_NAME opcode was already generated. This function
2835 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03002838 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002840 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2841 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002842 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002843 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002844 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002846 while (1) {
2847 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002849 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002851 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002852 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002854 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03002855 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002856 if (dot == -1) {
2857 break;
2858 }
2859 ADDOP(c, ROT_TWO);
2860 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03002862 if (!compiler_nameop(c, asname, Store)) {
2863 return 0;
2864 }
2865 ADDOP(c, POP_TOP);
2866 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 }
2868 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869}
2870
2871static int
2872compiler_import(struct compiler *c, stmt_ty s)
2873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 /* The Import node stores a module name like a.b.c as a single
2875 string. This is convenient for all cases except
2876 import a.b.c as d
2877 where we need to parse that string to extract the individual
2878 module names.
2879 XXX Perhaps change the representation to make this case simpler?
2880 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002881 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 for (i = 0; i < n; i++) {
2884 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2885 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002887 ADDOP_LOAD_CONST(c, _PyLong_Zero);
2888 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (alias->asname) {
2892 r = compiler_import_as(c, alias->name, alias->asname);
2893 if (!r)
2894 return r;
2895 }
2896 else {
2897 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002898 Py_ssize_t dot = PyUnicode_FindChar(
2899 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002900 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002901 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002902 if (tmp == NULL)
2903 return 0;
2904 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002906 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 Py_DECREF(tmp);
2908 }
2909 if (!r)
2910 return r;
2911 }
2912 }
2913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914}
2915
2916static int
2917compiler_from_import(struct compiler *c, stmt_ty s)
2918{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002919 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002920 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 if (!empty_string) {
2924 empty_string = PyUnicode_FromString("");
2925 if (!empty_string)
2926 return 0;
2927 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002929 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02002930
2931 names = PyTuple_New(n);
2932 if (!names)
2933 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 /* build up the names */
2936 for (i = 0; i < n; i++) {
2937 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2938 Py_INCREF(alias->name);
2939 PyTuple_SET_ITEM(names, i, alias->name);
2940 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002943 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 Py_DECREF(names);
2945 return compiler_error(c, "from __future__ imports must occur "
2946 "at the beginning of the file");
2947 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002948 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 if (s->v.ImportFrom.module) {
2951 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2952 }
2953 else {
2954 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2955 }
2956 for (i = 0; i < n; i++) {
2957 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2958 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002960 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 assert(n == 1);
2962 ADDOP(c, IMPORT_STAR);
2963 return 1;
2964 }
2965
2966 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2967 store_name = alias->name;
2968 if (alias->asname)
2969 store_name = alias->asname;
2970
2971 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 return 0;
2973 }
2974 }
2975 /* remove imported module */
2976 ADDOP(c, POP_TOP);
2977 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978}
2979
2980static int
2981compiler_assert(struct compiler *c, stmt_ty s)
2982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 static PyObject *assertion_error = NULL;
2984 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985
Georg Brandl8334fd92010-12-04 10:26:46 +00002986 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 return 1;
2988 if (assertion_error == NULL) {
2989 assertion_error = PyUnicode_InternFromString("AssertionError");
2990 if (assertion_error == NULL)
2991 return 0;
2992 }
2993 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03002994 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
2995 {
2996 if (!compiler_warn(c, "assertion is always true, "
2997 "perhaps remove parentheses?"))
2998 {
Victor Stinner14e461d2013-08-26 22:28:21 +02002999 return 0;
3000 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 end = compiler_new_block(c);
3003 if (end == NULL)
3004 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003005 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3006 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3008 if (s->v.Assert.msg) {
3009 VISIT(c, expr, s->v.Assert.msg);
3010 ADDOP_I(c, CALL_FUNCTION, 1);
3011 }
3012 ADDOP_I(c, RAISE_VARARGS, 1);
3013 compiler_use_next_block(c, end);
3014 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015}
3016
3017static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003018compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3019{
3020 if (c->c_interactive && c->c_nestlevel <= 1) {
3021 VISIT(c, expr, value);
3022 ADDOP(c, PRINT_EXPR);
3023 return 1;
3024 }
3025
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003026 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003027 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003028 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003029 }
3030
3031 VISIT(c, expr, value);
3032 ADDOP(c, POP_TOP);
3033 return 1;
3034}
3035
3036static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037compiler_visit_stmt(struct compiler *c, stmt_ty s)
3038{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003039 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 /* Always assign a lineno to the next instruction for a stmt. */
3042 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003043 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 switch (s->kind) {
3047 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003048 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 case ClassDef_kind:
3050 return compiler_class(c, s);
3051 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003052 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 case Delete_kind:
3054 VISIT_SEQ(c, expr, s->v.Delete.targets)
3055 break;
3056 case Assign_kind:
3057 n = asdl_seq_LEN(s->v.Assign.targets);
3058 VISIT(c, expr, s->v.Assign.value);
3059 for (i = 0; i < n; i++) {
3060 if (i < n - 1)
3061 ADDOP(c, DUP_TOP);
3062 VISIT(c, expr,
3063 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3064 }
3065 break;
3066 case AugAssign_kind:
3067 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003068 case AnnAssign_kind:
3069 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 case For_kind:
3071 return compiler_for(c, s);
3072 case While_kind:
3073 return compiler_while(c, s);
3074 case If_kind:
3075 return compiler_if(c, s);
3076 case Raise_kind:
3077 n = 0;
3078 if (s->v.Raise.exc) {
3079 VISIT(c, expr, s->v.Raise.exc);
3080 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003081 if (s->v.Raise.cause) {
3082 VISIT(c, expr, s->v.Raise.cause);
3083 n++;
3084 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003086 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003088 case Try_kind:
3089 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 case Assert_kind:
3091 return compiler_assert(c, s);
3092 case Import_kind:
3093 return compiler_import(c, s);
3094 case ImportFrom_kind:
3095 return compiler_from_import(c, s);
3096 case Global_kind:
3097 case Nonlocal_kind:
3098 break;
3099 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003100 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 case Pass_kind:
3102 break;
3103 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003104 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 case Continue_kind:
3106 return compiler_continue(c);
3107 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003108 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003109 case AsyncFunctionDef_kind:
3110 return compiler_function(c, s, 1);
3111 case AsyncWith_kind:
3112 return compiler_async_with(c, s, 0);
3113 case AsyncFor_kind:
3114 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 }
Yury Selivanov75445082015-05-11 22:57:16 -04003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118}
3119
3120static int
3121unaryop(unaryop_ty op)
3122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 switch (op) {
3124 case Invert:
3125 return UNARY_INVERT;
3126 case Not:
3127 return UNARY_NOT;
3128 case UAdd:
3129 return UNARY_POSITIVE;
3130 case USub:
3131 return UNARY_NEGATIVE;
3132 default:
3133 PyErr_Format(PyExc_SystemError,
3134 "unary op %d should not be possible", op);
3135 return 0;
3136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137}
3138
3139static int
3140binop(struct compiler *c, operator_ty op)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 switch (op) {
3143 case Add:
3144 return BINARY_ADD;
3145 case Sub:
3146 return BINARY_SUBTRACT;
3147 case Mult:
3148 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003149 case MatMult:
3150 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 case Div:
3152 return BINARY_TRUE_DIVIDE;
3153 case Mod:
3154 return BINARY_MODULO;
3155 case Pow:
3156 return BINARY_POWER;
3157 case LShift:
3158 return BINARY_LSHIFT;
3159 case RShift:
3160 return BINARY_RSHIFT;
3161 case BitOr:
3162 return BINARY_OR;
3163 case BitXor:
3164 return BINARY_XOR;
3165 case BitAnd:
3166 return BINARY_AND;
3167 case FloorDiv:
3168 return BINARY_FLOOR_DIVIDE;
3169 default:
3170 PyErr_Format(PyExc_SystemError,
3171 "binary op %d should not be possible", op);
3172 return 0;
3173 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003174}
3175
3176static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177inplace_binop(struct compiler *c, operator_ty op)
3178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 switch (op) {
3180 case Add:
3181 return INPLACE_ADD;
3182 case Sub:
3183 return INPLACE_SUBTRACT;
3184 case Mult:
3185 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003186 case MatMult:
3187 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 case Div:
3189 return INPLACE_TRUE_DIVIDE;
3190 case Mod:
3191 return INPLACE_MODULO;
3192 case Pow:
3193 return INPLACE_POWER;
3194 case LShift:
3195 return INPLACE_LSHIFT;
3196 case RShift:
3197 return INPLACE_RSHIFT;
3198 case BitOr:
3199 return INPLACE_OR;
3200 case BitXor:
3201 return INPLACE_XOR;
3202 case BitAnd:
3203 return INPLACE_AND;
3204 case FloorDiv:
3205 return INPLACE_FLOOR_DIVIDE;
3206 default:
3207 PyErr_Format(PyExc_SystemError,
3208 "inplace binary op %d should not be possible", op);
3209 return 0;
3210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211}
3212
3213static int
3214compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3215{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003216 int op, scope;
3217 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 PyObject *dict = c->u->u_names;
3221 PyObject *mangled;
3222 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003224 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3225 !_PyUnicode_EqualToASCIIString(name, "True") &&
3226 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003227
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003228 mangled = _Py_Mangle(c->u->u_private, name);
3229 if (!mangled)
3230 return 0;
3231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 op = 0;
3233 optype = OP_NAME;
3234 scope = PyST_GetScope(c->u->u_ste, mangled);
3235 switch (scope) {
3236 case FREE:
3237 dict = c->u->u_freevars;
3238 optype = OP_DEREF;
3239 break;
3240 case CELL:
3241 dict = c->u->u_cellvars;
3242 optype = OP_DEREF;
3243 break;
3244 case LOCAL:
3245 if (c->u->u_ste->ste_type == FunctionBlock)
3246 optype = OP_FAST;
3247 break;
3248 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003249 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 optype = OP_GLOBAL;
3251 break;
3252 case GLOBAL_EXPLICIT:
3253 optype = OP_GLOBAL;
3254 break;
3255 default:
3256 /* scope can be 0 */
3257 break;
3258 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003261 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 switch (optype) {
3264 case OP_DEREF:
3265 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003266 case Load:
3267 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3268 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 case Store: op = STORE_DEREF; break;
3270 case AugLoad:
3271 case AugStore:
3272 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003273 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 case Param:
3275 default:
3276 PyErr_SetString(PyExc_SystemError,
3277 "param invalid for deref variable");
3278 return 0;
3279 }
3280 break;
3281 case OP_FAST:
3282 switch (ctx) {
3283 case Load: op = LOAD_FAST; break;
3284 case Store: op = STORE_FAST; break;
3285 case Del: op = DELETE_FAST; break;
3286 case AugLoad:
3287 case AugStore:
3288 break;
3289 case Param:
3290 default:
3291 PyErr_SetString(PyExc_SystemError,
3292 "param invalid for local variable");
3293 return 0;
3294 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003295 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return 1;
3297 case OP_GLOBAL:
3298 switch (ctx) {
3299 case Load: op = LOAD_GLOBAL; break;
3300 case Store: op = STORE_GLOBAL; break;
3301 case Del: op = DELETE_GLOBAL; break;
3302 case AugLoad:
3303 case AugStore:
3304 break;
3305 case Param:
3306 default:
3307 PyErr_SetString(PyExc_SystemError,
3308 "param invalid for global variable");
3309 return 0;
3310 }
3311 break;
3312 case OP_NAME:
3313 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003314 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 case Store: op = STORE_NAME; break;
3316 case Del: op = DELETE_NAME; break;
3317 case AugLoad:
3318 case AugStore:
3319 break;
3320 case Param:
3321 default:
3322 PyErr_SetString(PyExc_SystemError,
3323 "param invalid for name variable");
3324 return 0;
3325 }
3326 break;
3327 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 assert(op);
3330 arg = compiler_add_o(c, dict, mangled);
3331 Py_DECREF(mangled);
3332 if (arg < 0)
3333 return 0;
3334 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335}
3336
3337static int
3338compiler_boolop(struct compiler *c, expr_ty e)
3339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003341 int jumpi;
3342 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 assert(e->kind == BoolOp_kind);
3346 if (e->v.BoolOp.op == And)
3347 jumpi = JUMP_IF_FALSE_OR_POP;
3348 else
3349 jumpi = JUMP_IF_TRUE_OR_POP;
3350 end = compiler_new_block(c);
3351 if (end == NULL)
3352 return 0;
3353 s = e->v.BoolOp.values;
3354 n = asdl_seq_LEN(s) - 1;
3355 assert(n >= 0);
3356 for (i = 0; i < n; ++i) {
3357 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3358 ADDOP_JABS(c, jumpi, end);
3359 }
3360 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3361 compiler_use_next_block(c, end);
3362 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363}
3364
3365static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003366starunpack_helper(struct compiler *c, asdl_seq *elts,
3367 int single_op, int inner_op, int outer_op)
3368{
3369 Py_ssize_t n = asdl_seq_LEN(elts);
3370 Py_ssize_t i, nsubitems = 0, nseen = 0;
3371 for (i = 0; i < n; i++) {
3372 expr_ty elt = asdl_seq_GET(elts, i);
3373 if (elt->kind == Starred_kind) {
3374 if (nseen) {
3375 ADDOP_I(c, inner_op, nseen);
3376 nseen = 0;
3377 nsubitems++;
3378 }
3379 VISIT(c, expr, elt->v.Starred.value);
3380 nsubitems++;
3381 }
3382 else {
3383 VISIT(c, expr, elt);
3384 nseen++;
3385 }
3386 }
3387 if (nsubitems) {
3388 if (nseen) {
3389 ADDOP_I(c, inner_op, nseen);
3390 nsubitems++;
3391 }
3392 ADDOP_I(c, outer_op, nsubitems);
3393 }
3394 else
3395 ADDOP_I(c, single_op, nseen);
3396 return 1;
3397}
3398
3399static int
3400assignment_helper(struct compiler *c, asdl_seq *elts)
3401{
3402 Py_ssize_t n = asdl_seq_LEN(elts);
3403 Py_ssize_t i;
3404 int seen_star = 0;
3405 for (i = 0; i < n; i++) {
3406 expr_ty elt = asdl_seq_GET(elts, i);
3407 if (elt->kind == Starred_kind && !seen_star) {
3408 if ((i >= (1 << 8)) ||
3409 (n-i-1 >= (INT_MAX >> 8)))
3410 return compiler_error(c,
3411 "too many expressions in "
3412 "star-unpacking assignment");
3413 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3414 seen_star = 1;
3415 asdl_seq_SET(elts, i, elt->v.Starred.value);
3416 }
3417 else if (elt->kind == Starred_kind) {
3418 return compiler_error(c,
3419 "two starred expressions in assignment");
3420 }
3421 }
3422 if (!seen_star) {
3423 ADDOP_I(c, UNPACK_SEQUENCE, n);
3424 }
3425 VISIT_SEQ(c, expr, elts);
3426 return 1;
3427}
3428
3429static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430compiler_list(struct compiler *c, expr_ty e)
3431{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003432 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003434 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003436 else if (e->v.List.ctx == Load) {
3437 return starunpack_helper(c, elts,
3438 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003440 else
3441 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
3446compiler_tuple(struct compiler *c, expr_ty e)
3447{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003448 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003450 return assignment_helper(c, elts);
3451 }
3452 else if (e->v.Tuple.ctx == Load) {
3453 return starunpack_helper(c, elts,
3454 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3455 }
3456 else
3457 VISIT_SEQ(c, expr, elts);
3458 return 1;
3459}
3460
3461static int
3462compiler_set(struct compiler *c, expr_ty e)
3463{
3464 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3465 BUILD_SET, BUILD_SET_UNPACK);
3466}
3467
3468static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003469are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3470{
3471 Py_ssize_t i;
3472 for (i = begin; i < end; i++) {
3473 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003474 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003475 return 0;
3476 }
3477 return 1;
3478}
3479
3480static int
3481compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3482{
3483 Py_ssize_t i, n = end - begin;
3484 PyObject *keys, *key;
3485 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3486 for (i = begin; i < end; i++) {
3487 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3488 }
3489 keys = PyTuple_New(n);
3490 if (keys == NULL) {
3491 return 0;
3492 }
3493 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003494 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003495 Py_INCREF(key);
3496 PyTuple_SET_ITEM(keys, i - begin, key);
3497 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003498 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003499 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3500 }
3501 else {
3502 for (i = begin; i < end; i++) {
3503 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3504 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3505 }
3506 ADDOP_I(c, BUILD_MAP, n);
3507 }
3508 return 1;
3509}
3510
3511static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003512compiler_dict(struct compiler *c, expr_ty e)
3513{
Victor Stinner976bb402016-03-23 11:36:19 +01003514 Py_ssize_t i, n, elements;
3515 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003516 int is_unpacking = 0;
3517 n = asdl_seq_LEN(e->v.Dict.values);
3518 containers = 0;
3519 elements = 0;
3520 for (i = 0; i < n; i++) {
3521 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3522 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003523 if (!compiler_subdict(c, e, i - elements, i))
3524 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003525 containers++;
3526 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003528 if (is_unpacking) {
3529 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3530 containers++;
3531 }
3532 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003533 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 }
3535 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003536 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003537 if (!compiler_subdict(c, e, n - elements, n))
3538 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003539 containers++;
3540 }
3541 /* If there is more than one dict, they need to be merged into a new
3542 * dict. If there is one dict and it's an unpacking, then it needs
3543 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003544 if (containers > 1 || is_unpacking) {
3545 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 }
3547 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548}
3549
3550static int
3551compiler_compare(struct compiler *c, expr_ty e)
3552{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003553 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003556 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3557 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3558 if (n == 0) {
3559 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3560 ADDOP_I(c, COMPARE_OP,
3561 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3562 }
3563 else {
3564 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 if (cleanup == NULL)
3566 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003567 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 VISIT(c, expr,
3569 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003570 ADDOP(c, DUP_TOP);
3571 ADDOP(c, ROT_THREE);
3572 ADDOP_I(c, COMPARE_OP,
3573 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3574 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3575 NEXT_BLOCK(c);
3576 }
3577 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3578 ADDOP_I(c, COMPARE_OP,
3579 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 basicblock *end = compiler_new_block(c);
3581 if (end == NULL)
3582 return 0;
3583 ADDOP_JREL(c, JUMP_FORWARD, end);
3584 compiler_use_next_block(c, cleanup);
3585 ADDOP(c, ROT_TWO);
3586 ADDOP(c, POP_TOP);
3587 compiler_use_next_block(c, end);
3588 }
3589 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590}
3591
3592static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003593maybe_optimize_method_call(struct compiler *c, expr_ty e)
3594{
3595 Py_ssize_t argsl, i;
3596 expr_ty meth = e->v.Call.func;
3597 asdl_seq *args = e->v.Call.args;
3598
3599 /* Check that the call node is an attribute access, and that
3600 the call doesn't have keyword parameters. */
3601 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3602 asdl_seq_LEN(e->v.Call.keywords))
3603 return -1;
3604
3605 /* Check that there are no *varargs types of arguments. */
3606 argsl = asdl_seq_LEN(args);
3607 for (i = 0; i < argsl; i++) {
3608 expr_ty elt = asdl_seq_GET(args, i);
3609 if (elt->kind == Starred_kind) {
3610 return -1;
3611 }
3612 }
3613
3614 /* Alright, we can optimize the code. */
3615 VISIT(c, expr, meth->v.Attribute.value);
3616 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3617 VISIT_SEQ(c, expr, e->v.Call.args);
3618 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3619 return 1;
3620}
3621
3622static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623compiler_call(struct compiler *c, expr_ty e)
3624{
Yury Selivanovf2392132016-12-13 19:03:51 -05003625 if (maybe_optimize_method_call(c, e) > 0)
3626 return 1;
3627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 VISIT(c, expr, e->v.Call.func);
3629 return compiler_call_helper(c, 0,
3630 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003631 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003632}
3633
Eric V. Smith235a6f02015-09-19 14:51:32 -04003634static int
3635compiler_joined_str(struct compiler *c, expr_ty e)
3636{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003637 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003638 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3639 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003640 return 1;
3641}
3642
Eric V. Smitha78c7952015-11-03 12:45:05 -05003643/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003644static int
3645compiler_formatted_value(struct compiler *c, expr_ty e)
3646{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003647 /* Our oparg encodes 2 pieces of information: the conversion
3648 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003649
Eric V. Smitha78c7952015-11-03 12:45:05 -05003650 Convert the conversion char to 2 bits:
3651 None: 000 0x0 FVC_NONE
3652 !s : 001 0x1 FVC_STR
3653 !r : 010 0x2 FVC_REPR
3654 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003655
Eric V. Smitha78c7952015-11-03 12:45:05 -05003656 next bit is whether or not we have a format spec:
3657 yes : 100 0x4
3658 no : 000 0x0
3659 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003660
Eric V. Smitha78c7952015-11-03 12:45:05 -05003661 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003662
Eric V. Smitha78c7952015-11-03 12:45:05 -05003663 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003664 VISIT(c, expr, e->v.FormattedValue.value);
3665
Eric V. Smitha78c7952015-11-03 12:45:05 -05003666 switch (e->v.FormattedValue.conversion) {
3667 case 's': oparg = FVC_STR; break;
3668 case 'r': oparg = FVC_REPR; break;
3669 case 'a': oparg = FVC_ASCII; break;
3670 case -1: oparg = FVC_NONE; break;
3671 default:
3672 PyErr_SetString(PyExc_SystemError,
3673 "Unrecognized conversion character");
3674 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003675 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003676 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003677 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003678 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003679 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003680 }
3681
Eric V. Smitha78c7952015-11-03 12:45:05 -05003682 /* And push our opcode and oparg */
3683 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003684 return 1;
3685}
3686
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003687static int
3688compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3689{
3690 Py_ssize_t i, n = end - begin;
3691 keyword_ty kw;
3692 PyObject *keys, *key;
3693 assert(n > 0);
3694 if (n > 1) {
3695 for (i = begin; i < end; i++) {
3696 kw = asdl_seq_GET(keywords, i);
3697 VISIT(c, expr, kw->value);
3698 }
3699 keys = PyTuple_New(n);
3700 if (keys == NULL) {
3701 return 0;
3702 }
3703 for (i = begin; i < end; i++) {
3704 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3705 Py_INCREF(key);
3706 PyTuple_SET_ITEM(keys, i - begin, key);
3707 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003708 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003709 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3710 }
3711 else {
3712 /* a for loop only executes once */
3713 for (i = begin; i < end; i++) {
3714 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003715 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003716 VISIT(c, expr, kw->value);
3717 }
3718 ADDOP_I(c, BUILD_MAP, n);
3719 }
3720 return 1;
3721}
3722
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003723/* shared code between compiler_call and compiler_class */
3724static int
3725compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003726 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003727 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003728 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003729{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003730 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003731 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003732
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 /* the number of tuples and dictionaries on the stack */
3734 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3735
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003737 nkwelts = asdl_seq_LEN(keywords);
3738
3739 for (i = 0; i < nkwelts; i++) {
3740 keyword_ty kw = asdl_seq_GET(keywords, i);
3741 if (kw->arg == NULL) {
3742 mustdictunpack = 1;
3743 break;
3744 }
3745 }
3746
3747 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003748 for (i = 0; i < nelts; i++) {
3749 expr_ty elt = asdl_seq_GET(args, i);
3750 if (elt->kind == Starred_kind) {
3751 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003752 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 if (nseen) {
3754 ADDOP_I(c, BUILD_TUPLE, nseen);
3755 nseen = 0;
3756 nsubargs++;
3757 }
3758 VISIT(c, expr, elt->v.Starred.value);
3759 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003760 }
3761 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003763 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003764 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003766
3767 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003768 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003769 if (nseen) {
3770 /* Pack up any trailing positional arguments. */
3771 ADDOP_I(c, BUILD_TUPLE, nseen);
3772 nsubargs++;
3773 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003774 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003775 /* If we ended up with more than one stararg, we need
3776 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003777 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003778 }
3779 else if (nsubargs == 0) {
3780 ADDOP_I(c, BUILD_TUPLE, 0);
3781 }
3782 nseen = 0; /* the number of keyword arguments on the stack following */
3783 for (i = 0; i < nkwelts; i++) {
3784 keyword_ty kw = asdl_seq_GET(keywords, i);
3785 if (kw->arg == NULL) {
3786 /* A keyword argument unpacking. */
3787 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003788 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3789 return 0;
3790 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003791 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003792 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003793 VISIT(c, expr, kw->value);
3794 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003796 else {
3797 nseen++;
3798 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003800 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003801 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003802 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003803 return 0;
3804 nsubkwargs++;
3805 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003806 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003807 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003808 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003810 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3811 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003813 else if (nkwelts) {
3814 PyObject *names;
3815 VISIT_SEQ(c, keyword, keywords);
3816 names = PyTuple_New(nkwelts);
3817 if (names == NULL) {
3818 return 0;
3819 }
3820 for (i = 0; i < nkwelts; i++) {
3821 keyword_ty kw = asdl_seq_GET(keywords, i);
3822 Py_INCREF(kw->arg);
3823 PyTuple_SET_ITEM(names, i, kw->arg);
3824 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003825 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003826 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3827 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003829 else {
3830 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3831 return 1;
3832 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833}
3834
Nick Coghlan650f0d02007-04-15 12:05:43 +00003835
3836/* List and set comprehensions and generator expressions work by creating a
3837 nested function to perform the actual iteration. This means that the
3838 iteration variables don't leak into the current scope.
3839 The defined function is called immediately following its definition, with the
3840 result of that call being the result of the expression.
3841 The LC/SC version returns the populated container, while the GE version is
3842 flagged in symtable.c as a generator, so it returns the generator object
3843 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00003844
3845 Possible cleanups:
3846 - iterate over the generator sequence instead of using recursion
3847*/
3848
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851compiler_comprehension_generator(struct compiler *c,
3852 asdl_seq *generators, int gen_index,
3853 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003855 comprehension_ty gen;
3856 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3857 if (gen->is_async) {
3858 return compiler_async_comprehension_generator(
3859 c, generators, gen_index, elt, val, type);
3860 } else {
3861 return compiler_sync_comprehension_generator(
3862 c, generators, gen_index, elt, val, type);
3863 }
3864}
3865
3866static int
3867compiler_sync_comprehension_generator(struct compiler *c,
3868 asdl_seq *generators, int gen_index,
3869 expr_ty elt, expr_ty val, int type)
3870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 /* generate code for the iterator, then each of the ifs,
3872 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 comprehension_ty gen;
3875 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003876 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 start = compiler_new_block(c);
3879 skip = compiler_new_block(c);
3880 if_cleanup = compiler_new_block(c);
3881 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3884 anchor == NULL)
3885 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 if (gen_index == 0) {
3890 /* Receive outermost iter as an implicit argument */
3891 c->u->u_argcount = 1;
3892 ADDOP_I(c, LOAD_FAST, 0);
3893 }
3894 else {
3895 /* Sub-iter - calculate on the fly */
3896 VISIT(c, expr, gen->iter);
3897 ADDOP(c, GET_ITER);
3898 }
3899 compiler_use_next_block(c, start);
3900 ADDOP_JREL(c, FOR_ITER, anchor);
3901 NEXT_BLOCK(c);
3902 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 /* XXX this needs to be cleaned up...a lot! */
3905 n = asdl_seq_LEN(gen->ifs);
3906 for (i = 0; i < n; i++) {
3907 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003908 if (!compiler_jump_if(c, e, if_cleanup, 0))
3909 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 NEXT_BLOCK(c);
3911 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 if (++gen_index < asdl_seq_LEN(generators))
3914 if (!compiler_comprehension_generator(c,
3915 generators, gen_index,
3916 elt, val, type))
3917 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 /* only append after the last for generator */
3920 if (gen_index >= asdl_seq_LEN(generators)) {
3921 /* comprehension specific code */
3922 switch (type) {
3923 case COMP_GENEXP:
3924 VISIT(c, expr, elt);
3925 ADDOP(c, YIELD_VALUE);
3926 ADDOP(c, POP_TOP);
3927 break;
3928 case COMP_LISTCOMP:
3929 VISIT(c, expr, elt);
3930 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3931 break;
3932 case COMP_SETCOMP:
3933 VISIT(c, expr, elt);
3934 ADDOP_I(c, SET_ADD, gen_index + 1);
3935 break;
3936 case COMP_DICTCOMP:
3937 /* With 'd[k] = v', v is evaluated before k, so we do
3938 the same. */
3939 VISIT(c, expr, val);
3940 VISIT(c, expr, elt);
3941 ADDOP_I(c, MAP_ADD, gen_index + 1);
3942 break;
3943 default:
3944 return 0;
3945 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 compiler_use_next_block(c, skip);
3948 }
3949 compiler_use_next_block(c, if_cleanup);
3950 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3951 compiler_use_next_block(c, anchor);
3952
3953 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003954}
3955
3956static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003957compiler_async_comprehension_generator(struct compiler *c,
3958 asdl_seq *generators, int gen_index,
3959 expr_ty elt, expr_ty val, int type)
3960{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003961 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003962 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003963 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003964 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003965 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003966 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003967
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003968 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003969 return 0;
3970 }
3971
3972 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3973
3974 if (gen_index == 0) {
3975 /* Receive outermost iter as an implicit argument */
3976 c->u->u_argcount = 1;
3977 ADDOP_I(c, LOAD_FAST, 0);
3978 }
3979 else {
3980 /* Sub-iter - calculate on the fly */
3981 VISIT(c, expr, gen->iter);
3982 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003983 }
3984
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02003985 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003986
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003987 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003988 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003989 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003990 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003991 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02003992 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003993
3994 n = asdl_seq_LEN(gen->ifs);
3995 for (i = 0; i < n; i++) {
3996 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003997 if (!compiler_jump_if(c, e, if_cleanup, 0))
3998 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003999 NEXT_BLOCK(c);
4000 }
4001
4002 if (++gen_index < asdl_seq_LEN(generators))
4003 if (!compiler_comprehension_generator(c,
4004 generators, gen_index,
4005 elt, val, type))
4006 return 0;
4007
4008 /* only append after the last for generator */
4009 if (gen_index >= asdl_seq_LEN(generators)) {
4010 /* comprehension specific code */
4011 switch (type) {
4012 case COMP_GENEXP:
4013 VISIT(c, expr, elt);
4014 ADDOP(c, YIELD_VALUE);
4015 ADDOP(c, POP_TOP);
4016 break;
4017 case COMP_LISTCOMP:
4018 VISIT(c, expr, elt);
4019 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4020 break;
4021 case COMP_SETCOMP:
4022 VISIT(c, expr, elt);
4023 ADDOP_I(c, SET_ADD, gen_index + 1);
4024 break;
4025 case COMP_DICTCOMP:
4026 /* With 'd[k] = v', v is evaluated before k, so we do
4027 the same. */
4028 VISIT(c, expr, val);
4029 VISIT(c, expr, elt);
4030 ADDOP_I(c, MAP_ADD, gen_index + 1);
4031 break;
4032 default:
4033 return 0;
4034 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004035 }
4036 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004037 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4038
4039 compiler_use_next_block(c, except);
4040 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004041
4042 return 1;
4043}
4044
4045static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004046compiler_comprehension(struct compiler *c, expr_ty e, int type,
4047 identifier name, asdl_seq *generators, expr_ty elt,
4048 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004051 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004052 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004053 int is_async_function = c->u->u_ste->ste_coroutine;
4054 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004055
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004056 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004057
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004058 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4059 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004060 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004062 }
4063
4064 is_async_generator = c->u->u_ste->ste_coroutine;
4065
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004066 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004067 compiler_error(c, "asynchronous comprehension outside of "
4068 "an asynchronous function");
4069 goto error_in_scope;
4070 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 if (type != COMP_GENEXP) {
4073 int op;
4074 switch (type) {
4075 case COMP_LISTCOMP:
4076 op = BUILD_LIST;
4077 break;
4078 case COMP_SETCOMP:
4079 op = BUILD_SET;
4080 break;
4081 case COMP_DICTCOMP:
4082 op = BUILD_MAP;
4083 break;
4084 default:
4085 PyErr_Format(PyExc_SystemError,
4086 "unknown comprehension type %d", type);
4087 goto error_in_scope;
4088 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 ADDOP_I(c, op, 0);
4091 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 if (!compiler_comprehension_generator(c, generators, 0, elt,
4094 val, type))
4095 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 if (type != COMP_GENEXP) {
4098 ADDOP(c, RETURN_VALUE);
4099 }
4100
4101 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004102 qualname = c->u->u_qualname;
4103 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004105 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 goto error;
4107
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004108 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004110 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 Py_DECREF(co);
4112
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004113 VISIT(c, expr, outermost->iter);
4114
4115 if (outermost->is_async) {
4116 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004117 } else {
4118 ADDOP(c, GET_ITER);
4119 }
4120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004122
4123 if (is_async_generator && type != COMP_GENEXP) {
4124 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004125 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004126 ADDOP(c, YIELD_FROM);
4127 }
4128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004130error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004132error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004133 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 Py_XDECREF(co);
4135 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004136}
4137
4138static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139compiler_genexp(struct compiler *c, expr_ty e)
4140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 static identifier name;
4142 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004143 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 if (!name)
4145 return 0;
4146 }
4147 assert(e->kind == GeneratorExp_kind);
4148 return compiler_comprehension(c, e, COMP_GENEXP, name,
4149 e->v.GeneratorExp.generators,
4150 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151}
4152
4153static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004154compiler_listcomp(struct compiler *c, expr_ty e)
4155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 static identifier name;
4157 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004158 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 if (!name)
4160 return 0;
4161 }
4162 assert(e->kind == ListComp_kind);
4163 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4164 e->v.ListComp.generators,
4165 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004166}
4167
4168static int
4169compiler_setcomp(struct compiler *c, expr_ty e)
4170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 static identifier name;
4172 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004173 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 if (!name)
4175 return 0;
4176 }
4177 assert(e->kind == SetComp_kind);
4178 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4179 e->v.SetComp.generators,
4180 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004181}
4182
4183
4184static int
4185compiler_dictcomp(struct compiler *c, expr_ty e)
4186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 static identifier name;
4188 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004189 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 if (!name)
4191 return 0;
4192 }
4193 assert(e->kind == DictComp_kind);
4194 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4195 e->v.DictComp.generators,
4196 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004197}
4198
4199
4200static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201compiler_visit_keyword(struct compiler *c, keyword_ty k)
4202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 VISIT(c, expr, k->value);
4204 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205}
4206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208 whether they are true or false.
4209
4210 Return values: 1 for true, 0 for false, -1 for non-constant.
4211 */
4212
4213static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004214expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004216 if (e->kind == Constant_kind) {
4217 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004218 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004219 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220}
4221
Yury Selivanov75445082015-05-11 22:57:16 -04004222
4223/*
4224 Implements the async with statement.
4225
4226 The semantics outlined in that PEP are as follows:
4227
4228 async with EXPR as VAR:
4229 BLOCK
4230
4231 It is implemented roughly as:
4232
4233 context = EXPR
4234 exit = context.__aexit__ # not calling it
4235 value = await context.__aenter__()
4236 try:
4237 VAR = value # if VAR present in the syntax
4238 BLOCK
4239 finally:
4240 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004241 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004242 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004243 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004244 if not (await exit(*exc)):
4245 raise
4246 */
4247static int
4248compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4249{
4250 basicblock *block, *finally;
4251 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4252
4253 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004254 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4255 return compiler_error(c, "'async with' outside async function");
4256 }
Yury Selivanov75445082015-05-11 22:57:16 -04004257
4258 block = compiler_new_block(c);
4259 finally = compiler_new_block(c);
4260 if (!block || !finally)
4261 return 0;
4262
4263 /* Evaluate EXPR */
4264 VISIT(c, expr, item->context_expr);
4265
4266 ADDOP(c, BEFORE_ASYNC_WITH);
4267 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004268 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004269 ADDOP(c, YIELD_FROM);
4270
4271 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4272
4273 /* SETUP_ASYNC_WITH pushes a finally block. */
4274 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004275 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004276 return 0;
4277 }
4278
4279 if (item->optional_vars) {
4280 VISIT(c, expr, item->optional_vars);
4281 }
4282 else {
4283 /* Discard result from context.__aenter__() */
4284 ADDOP(c, POP_TOP);
4285 }
4286
4287 pos++;
4288 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4289 /* BLOCK code */
4290 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4291 else if (!compiler_async_with(c, s, pos))
4292 return 0;
4293
4294 /* End of try block; start the finally block */
4295 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004296 ADDOP(c, BEGIN_FINALLY);
4297 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004298
Yury Selivanov75445082015-05-11 22:57:16 -04004299 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004300 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004301 return 0;
4302
4303 /* Finally block starts; context.__exit__ is on the stack under
4304 the exception or return information. Just issue our magic
4305 opcode. */
4306 ADDOP(c, WITH_CLEANUP_START);
4307
4308 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004309 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004310 ADDOP(c, YIELD_FROM);
4311
4312 ADDOP(c, WITH_CLEANUP_FINISH);
4313
4314 /* Finally block ends. */
4315 ADDOP(c, END_FINALLY);
4316 compiler_pop_fblock(c, FINALLY_END, finally);
4317 return 1;
4318}
4319
4320
Guido van Rossumc2e20742006-02-27 22:32:47 +00004321/*
4322 Implements the with statement from PEP 343.
4323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004325
4326 with EXPR as VAR:
4327 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328
Guido van Rossumc2e20742006-02-27 22:32:47 +00004329 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330
Thomas Wouters477c8d52006-05-27 19:21:47 +00004331 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004332 exit = context.__exit__ # not calling it
4333 value = context.__enter__()
4334 try:
4335 VAR = value # if VAR present in the syntax
4336 BLOCK
4337 finally:
4338 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004339 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004340 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004341 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004342 exit(*exc)
4343 */
4344static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004345compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004346{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004347 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004348 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004349
4350 assert(s->kind == With_kind);
4351
Guido van Rossumc2e20742006-02-27 22:32:47 +00004352 block = compiler_new_block(c);
4353 finally = compiler_new_block(c);
4354 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004355 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004356
Thomas Wouters477c8d52006-05-27 19:21:47 +00004357 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004358 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004359 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004360
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004361 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004362 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004363 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004364 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004365 }
4366
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004367 if (item->optional_vars) {
4368 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004369 }
4370 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004372 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004373 }
4374
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004375 pos++;
4376 if (pos == asdl_seq_LEN(s->v.With.items))
4377 /* BLOCK code */
4378 VISIT_SEQ(c, stmt, s->v.With.body)
4379 else if (!compiler_with(c, s, pos))
4380 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004381
4382 /* End of try block; start the finally block */
4383 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004384 ADDOP(c, BEGIN_FINALLY);
4385 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004386
Guido van Rossumc2e20742006-02-27 22:32:47 +00004387 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004388 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004389 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004390
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004391 /* Finally block starts; context.__exit__ is on the stack under
4392 the exception or return information. Just issue our magic
4393 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004394 ADDOP(c, WITH_CLEANUP_START);
4395 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004396
4397 /* Finally block ends. */
4398 ADDOP(c, END_FINALLY);
4399 compiler_pop_fblock(c, FINALLY_END, finally);
4400 return 1;
4401}
4402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004403static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004404compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 switch (e->kind) {
4407 case BoolOp_kind:
4408 return compiler_boolop(c, e);
4409 case BinOp_kind:
4410 VISIT(c, expr, e->v.BinOp.left);
4411 VISIT(c, expr, e->v.BinOp.right);
4412 ADDOP(c, binop(c, e->v.BinOp.op));
4413 break;
4414 case UnaryOp_kind:
4415 VISIT(c, expr, e->v.UnaryOp.operand);
4416 ADDOP(c, unaryop(e->v.UnaryOp.op));
4417 break;
4418 case Lambda_kind:
4419 return compiler_lambda(c, e);
4420 case IfExp_kind:
4421 return compiler_ifexp(c, e);
4422 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004423 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004425 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 case GeneratorExp_kind:
4427 return compiler_genexp(c, e);
4428 case ListComp_kind:
4429 return compiler_listcomp(c, e);
4430 case SetComp_kind:
4431 return compiler_setcomp(c, e);
4432 case DictComp_kind:
4433 return compiler_dictcomp(c, e);
4434 case Yield_kind:
4435 if (c->u->u_ste->ste_type != FunctionBlock)
4436 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004437 if (e->v.Yield.value) {
4438 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 }
4440 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004441 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004443 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004445 case YieldFrom_kind:
4446 if (c->u->u_ste->ste_type != FunctionBlock)
4447 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004448
4449 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4450 return compiler_error(c, "'yield from' inside async function");
4451
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004452 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004453 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004454 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004455 ADDOP(c, YIELD_FROM);
4456 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004457 case Await_kind:
4458 if (c->u->u_ste->ste_type != FunctionBlock)
4459 return compiler_error(c, "'await' outside function");
4460
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004461 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4462 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004463 return compiler_error(c, "'await' outside async function");
4464
4465 VISIT(c, expr, e->v.Await.value);
4466 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004467 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004468 ADDOP(c, YIELD_FROM);
4469 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 case Compare_kind:
4471 return compiler_compare(c, e);
4472 case Call_kind:
4473 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004474 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004475 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004476 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004477 case JoinedStr_kind:
4478 return compiler_joined_str(c, e);
4479 case FormattedValue_kind:
4480 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 /* The following exprs can be assignment targets. */
4482 case Attribute_kind:
4483 if (e->v.Attribute.ctx != AugStore)
4484 VISIT(c, expr, e->v.Attribute.value);
4485 switch (e->v.Attribute.ctx) {
4486 case AugLoad:
4487 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004488 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 case Load:
4490 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4491 break;
4492 case AugStore:
4493 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004494 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 case Store:
4496 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4497 break;
4498 case Del:
4499 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4500 break;
4501 case Param:
4502 default:
4503 PyErr_SetString(PyExc_SystemError,
4504 "param invalid in attribute expression");
4505 return 0;
4506 }
4507 break;
4508 case Subscript_kind:
4509 switch (e->v.Subscript.ctx) {
4510 case AugLoad:
4511 VISIT(c, expr, e->v.Subscript.value);
4512 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4513 break;
4514 case Load:
4515 VISIT(c, expr, e->v.Subscript.value);
4516 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4517 break;
4518 case AugStore:
4519 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4520 break;
4521 case Store:
4522 VISIT(c, expr, e->v.Subscript.value);
4523 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4524 break;
4525 case Del:
4526 VISIT(c, expr, e->v.Subscript.value);
4527 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4528 break;
4529 case Param:
4530 default:
4531 PyErr_SetString(PyExc_SystemError,
4532 "param invalid in subscript expression");
4533 return 0;
4534 }
4535 break;
4536 case Starred_kind:
4537 switch (e->v.Starred.ctx) {
4538 case Store:
4539 /* In all legitimate cases, the Starred node was already replaced
4540 * by compiler_list/compiler_tuple. XXX: is that okay? */
4541 return compiler_error(c,
4542 "starred assignment target must be in a list or tuple");
4543 default:
4544 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004545 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 }
4547 break;
4548 case Name_kind:
4549 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4550 /* child nodes of List and Tuple will have expr_context set */
4551 case List_kind:
4552 return compiler_list(c, e);
4553 case Tuple_kind:
4554 return compiler_tuple(c, e);
4555 }
4556 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004557}
4558
4559static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004560compiler_visit_expr(struct compiler *c, expr_ty e)
4561{
4562 /* If expr e has a different line number than the last expr/stmt,
4563 set a new line number for the next instruction.
4564 */
4565 int old_lineno = c->u->u_lineno;
4566 int old_col_offset = c->u->u_col_offset;
4567 if (e->lineno != c->u->u_lineno) {
4568 c->u->u_lineno = e->lineno;
4569 c->u->u_lineno_set = 0;
4570 }
4571 /* Updating the column offset is always harmless. */
4572 c->u->u_col_offset = e->col_offset;
4573
4574 int res = compiler_visit_expr1(c, e);
4575
4576 if (old_lineno != c->u->u_lineno) {
4577 c->u->u_lineno = old_lineno;
4578 c->u->u_lineno_set = 0;
4579 }
4580 c->u->u_col_offset = old_col_offset;
4581 return res;
4582}
4583
4584static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004585compiler_augassign(struct compiler *c, stmt_ty s)
4586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 expr_ty e = s->v.AugAssign.target;
4588 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 switch (e->kind) {
4593 case Attribute_kind:
4594 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4595 AugLoad, e->lineno, e->col_offset, c->c_arena);
4596 if (auge == NULL)
4597 return 0;
4598 VISIT(c, expr, auge);
4599 VISIT(c, expr, s->v.AugAssign.value);
4600 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4601 auge->v.Attribute.ctx = AugStore;
4602 VISIT(c, expr, auge);
4603 break;
4604 case Subscript_kind:
4605 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4606 AugLoad, e->lineno, e->col_offset, c->c_arena);
4607 if (auge == NULL)
4608 return 0;
4609 VISIT(c, expr, auge);
4610 VISIT(c, expr, s->v.AugAssign.value);
4611 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4612 auge->v.Subscript.ctx = AugStore;
4613 VISIT(c, expr, auge);
4614 break;
4615 case Name_kind:
4616 if (!compiler_nameop(c, e->v.Name.id, Load))
4617 return 0;
4618 VISIT(c, expr, s->v.AugAssign.value);
4619 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4620 return compiler_nameop(c, e->v.Name.id, Store);
4621 default:
4622 PyErr_Format(PyExc_SystemError,
4623 "invalid node type (%d) for augmented assignment",
4624 e->kind);
4625 return 0;
4626 }
4627 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004628}
4629
4630static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004631check_ann_expr(struct compiler *c, expr_ty e)
4632{
4633 VISIT(c, expr, e);
4634 ADDOP(c, POP_TOP);
4635 return 1;
4636}
4637
4638static int
4639check_annotation(struct compiler *c, stmt_ty s)
4640{
4641 /* Annotations are only evaluated in a module or class. */
4642 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4643 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4644 return check_ann_expr(c, s->v.AnnAssign.annotation);
4645 }
4646 return 1;
4647}
4648
4649static int
4650check_ann_slice(struct compiler *c, slice_ty sl)
4651{
4652 switch(sl->kind) {
4653 case Index_kind:
4654 return check_ann_expr(c, sl->v.Index.value);
4655 case Slice_kind:
4656 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4657 return 0;
4658 }
4659 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4660 return 0;
4661 }
4662 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4663 return 0;
4664 }
4665 break;
4666 default:
4667 PyErr_SetString(PyExc_SystemError,
4668 "unexpected slice kind");
4669 return 0;
4670 }
4671 return 1;
4672}
4673
4674static int
4675check_ann_subscr(struct compiler *c, slice_ty sl)
4676{
4677 /* We check that everything in a subscript is defined at runtime. */
4678 Py_ssize_t i, n;
4679
4680 switch (sl->kind) {
4681 case Index_kind:
4682 case Slice_kind:
4683 if (!check_ann_slice(c, sl)) {
4684 return 0;
4685 }
4686 break;
4687 case ExtSlice_kind:
4688 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4689 for (i = 0; i < n; i++) {
4690 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4691 switch (subsl->kind) {
4692 case Index_kind:
4693 case Slice_kind:
4694 if (!check_ann_slice(c, subsl)) {
4695 return 0;
4696 }
4697 break;
4698 case ExtSlice_kind:
4699 default:
4700 PyErr_SetString(PyExc_SystemError,
4701 "extended slice invalid in nested slice");
4702 return 0;
4703 }
4704 }
4705 break;
4706 default:
4707 PyErr_Format(PyExc_SystemError,
4708 "invalid subscript kind %d", sl->kind);
4709 return 0;
4710 }
4711 return 1;
4712}
4713
4714static int
4715compiler_annassign(struct compiler *c, stmt_ty s)
4716{
4717 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004718 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004719
4720 assert(s->kind == AnnAssign_kind);
4721
4722 /* We perform the actual assignment first. */
4723 if (s->v.AnnAssign.value) {
4724 VISIT(c, expr, s->v.AnnAssign.value);
4725 VISIT(c, expr, targ);
4726 }
4727 switch (targ->kind) {
4728 case Name_kind:
4729 /* If we have a simple name in a module or class, store annotation. */
4730 if (s->v.AnnAssign.simple &&
4731 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4732 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08004733 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
4734 VISIT(c, annexpr, s->v.AnnAssign.annotation)
4735 }
4736 else {
4737 VISIT(c, expr, s->v.AnnAssign.annotation);
4738 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00004739 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02004740 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004741 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00004742 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004743 }
4744 break;
4745 case Attribute_kind:
4746 if (!s->v.AnnAssign.value &&
4747 !check_ann_expr(c, targ->v.Attribute.value)) {
4748 return 0;
4749 }
4750 break;
4751 case Subscript_kind:
4752 if (!s->v.AnnAssign.value &&
4753 (!check_ann_expr(c, targ->v.Subscript.value) ||
4754 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4755 return 0;
4756 }
4757 break;
4758 default:
4759 PyErr_Format(PyExc_SystemError,
4760 "invalid node type (%d) for annotated assignment",
4761 targ->kind);
4762 return 0;
4763 }
4764 /* Annotation is evaluated last. */
4765 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4766 return 0;
4767 }
4768 return 1;
4769}
4770
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004771/* Raises a SyntaxError and returns 0.
4772 If something goes wrong, a different exception may be raised.
4773*/
4774
4775static int
4776compiler_error(struct compiler *c, const char *errstr)
4777{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004778 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004780
Victor Stinner14e461d2013-08-26 22:28:21 +02004781 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004782 if (!loc) {
4783 Py_INCREF(Py_None);
4784 loc = Py_None;
4785 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004786 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04004787 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 if (!u)
4789 goto exit;
4790 v = Py_BuildValue("(zO)", errstr, u);
4791 if (!v)
4792 goto exit;
4793 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004794 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 Py_DECREF(loc);
4796 Py_XDECREF(u);
4797 Py_XDECREF(v);
4798 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004799}
4800
Serhiy Storchakad31e7732018-10-21 10:09:39 +03004801/* Emits a SyntaxWarning and returns 1 on success.
4802 If a SyntaxWarning raised as error, replaces it with a SyntaxError
4803 and returns 0.
4804*/
4805static int
4806compiler_warn(struct compiler *c, const char *errstr)
4807{
4808 PyObject *msg = PyUnicode_FromString(errstr);
4809 if (msg == NULL) {
4810 return 0;
4811 }
4812 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
4813 c->u->u_lineno, NULL, NULL) < 0)
4814 {
4815 Py_DECREF(msg);
4816 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
4817 PyErr_Clear();
4818 return compiler_error(c, errstr);
4819 }
4820 return 0;
4821 }
4822 Py_DECREF(msg);
4823 return 1;
4824}
4825
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004826static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827compiler_handle_subscr(struct compiler *c, const char *kind,
4828 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 /* XXX this code is duplicated */
4833 switch (ctx) {
4834 case AugLoad: /* fall through to Load */
4835 case Load: op = BINARY_SUBSCR; break;
4836 case AugStore:/* fall through to Store */
4837 case Store: op = STORE_SUBSCR; break;
4838 case Del: op = DELETE_SUBSCR; break;
4839 case Param:
4840 PyErr_Format(PyExc_SystemError,
4841 "invalid %s kind %d in subscript\n",
4842 kind, ctx);
4843 return 0;
4844 }
4845 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004846 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 }
4848 else if (ctx == AugStore) {
4849 ADDOP(c, ROT_THREE);
4850 }
4851 ADDOP(c, op);
4852 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004853}
4854
4855static int
4856compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 int n = 2;
4859 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 /* only handles the cases where BUILD_SLICE is emitted */
4862 if (s->v.Slice.lower) {
4863 VISIT(c, expr, s->v.Slice.lower);
4864 }
4865 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004866 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 if (s->v.Slice.upper) {
4870 VISIT(c, expr, s->v.Slice.upper);
4871 }
4872 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004873 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 }
4875
4876 if (s->v.Slice.step) {
4877 n++;
4878 VISIT(c, expr, s->v.Slice.step);
4879 }
4880 ADDOP_I(c, BUILD_SLICE, n);
4881 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004882}
4883
4884static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4886 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 switch (s->kind) {
4889 case Slice_kind:
4890 return compiler_slice(c, s, ctx);
4891 case Index_kind:
4892 VISIT(c, expr, s->v.Index.value);
4893 break;
4894 case ExtSlice_kind:
4895 default:
4896 PyErr_SetString(PyExc_SystemError,
4897 "extended slice invalid in nested slice");
4898 return 0;
4899 }
4900 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004901}
4902
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004903static int
4904compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4905{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02004906 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 switch (s->kind) {
4908 case Index_kind:
4909 kindname = "index";
4910 if (ctx != AugStore) {
4911 VISIT(c, expr, s->v.Index.value);
4912 }
4913 break;
4914 case Slice_kind:
4915 kindname = "slice";
4916 if (ctx != AugStore) {
4917 if (!compiler_slice(c, s, ctx))
4918 return 0;
4919 }
4920 break;
4921 case ExtSlice_kind:
4922 kindname = "extended slice";
4923 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004924 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 for (i = 0; i < n; i++) {
4926 slice_ty sub = (slice_ty)asdl_seq_GET(
4927 s->v.ExtSlice.dims, i);
4928 if (!compiler_visit_nested_slice(c, sub, ctx))
4929 return 0;
4930 }
4931 ADDOP_I(c, BUILD_TUPLE, n);
4932 }
4933 break;
4934 default:
4935 PyErr_Format(PyExc_SystemError,
4936 "invalid subscript kind %d", s->kind);
4937 return 0;
4938 }
4939 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004940}
4941
Thomas Wouters89f507f2006-12-13 04:49:30 +00004942/* End of the compiler section, beginning of the assembler section */
4943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004944/* do depth-first search of basic block graph, starting with block.
4945 post records the block indices in post-order.
4946
4947 XXX must handle implicit jumps from one block to next
4948*/
4949
Thomas Wouters89f507f2006-12-13 04:49:30 +00004950struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 PyObject *a_bytecode; /* string containing bytecode */
4952 int a_offset; /* offset into bytecode */
4953 int a_nblocks; /* number of reachable blocks */
4954 basicblock **a_postorder; /* list of blocks in dfs postorder */
4955 PyObject *a_lnotab; /* string containing lnotab */
4956 int a_lnotab_off; /* offset into lnotab */
4957 int a_lineno; /* last lineno of emitted instruction */
4958 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004959};
4960
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004961static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004962dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004963{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004964 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004965
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004966 /* Get rid of recursion for normal control flow.
4967 Since the number of blocks is limited, unused space in a_postorder
4968 (from a_nblocks to end) can be used as a stack for still not ordered
4969 blocks. */
4970 for (j = end; b && !b->b_seen; b = b->b_next) {
4971 b->b_seen = 1;
4972 assert(a->a_nblocks < j);
4973 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004975 while (j < end) {
4976 b = a->a_postorder[j++];
4977 for (i = 0; i < b->b_iused; i++) {
4978 struct instr *instr = &b->b_instr[i];
4979 if (instr->i_jrel || instr->i_jabs)
4980 dfs(c, instr->i_target, a, j);
4981 }
4982 assert(a->a_nblocks < j);
4983 a->a_postorder[a->a_nblocks++] = b;
4984 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004985}
4986
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004987Py_LOCAL_INLINE(void)
4988stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004989{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004990 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02004991 if (b->b_startdepth < depth) {
4992 assert(b->b_startdepth < 0);
4993 b->b_startdepth = depth;
4994 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02004995 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004996}
4997
4998/* Find the flow path that needs the largest stack. We assume that
4999 * cycles in the flow graph have no net effect on the stack depth.
5000 */
5001static int
5002stackdepth(struct compiler *c)
5003{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005004 basicblock *b, *entryblock = NULL;
5005 basicblock **stack, **sp;
5006 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 b->b_startdepth = INT_MIN;
5009 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005010 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 }
5012 if (!entryblock)
5013 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005014 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5015 if (!stack) {
5016 PyErr_NoMemory();
5017 return -1;
5018 }
5019
5020 sp = stack;
5021 stackdepth_push(&sp, entryblock, 0);
5022 while (sp != stack) {
5023 b = *--sp;
5024 int depth = b->b_startdepth;
5025 assert(depth >= 0);
5026 basicblock *next = b->b_next;
5027 for (int i = 0; i < b->b_iused; i++) {
5028 struct instr *instr = &b->b_instr[i];
5029 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5030 if (effect == PY_INVALID_STACK_EFFECT) {
5031 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5032 Py_FatalError("PyCompile_OpcodeStackEffect()");
5033 }
5034 int new_depth = depth + effect;
5035 if (new_depth > maxdepth) {
5036 maxdepth = new_depth;
5037 }
5038 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5039 if (instr->i_jrel || instr->i_jabs) {
5040 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5041 assert(effect != PY_INVALID_STACK_EFFECT);
5042 int target_depth = depth + effect;
5043 if (target_depth > maxdepth) {
5044 maxdepth = target_depth;
5045 }
5046 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005047 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005048 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005049 assert(instr->i_target->b_startdepth >= target_depth);
5050 depth = new_depth;
5051 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005052 }
5053 stackdepth_push(&sp, instr->i_target, target_depth);
5054 }
5055 depth = new_depth;
5056 if (instr->i_opcode == JUMP_ABSOLUTE ||
5057 instr->i_opcode == JUMP_FORWARD ||
5058 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005059 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005060 {
5061 /* remaining code is dead */
5062 next = NULL;
5063 break;
5064 }
5065 }
5066 if (next != NULL) {
5067 stackdepth_push(&sp, next, depth);
5068 }
5069 }
5070 PyObject_Free(stack);
5071 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005072}
5073
5074static int
5075assemble_init(struct assembler *a, int nblocks, int firstlineno)
5076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 memset(a, 0, sizeof(struct assembler));
5078 a->a_lineno = firstlineno;
5079 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5080 if (!a->a_bytecode)
5081 return 0;
5082 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5083 if (!a->a_lnotab)
5084 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005085 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 PyErr_NoMemory();
5087 return 0;
5088 }
5089 a->a_postorder = (basicblock **)PyObject_Malloc(
5090 sizeof(basicblock *) * nblocks);
5091 if (!a->a_postorder) {
5092 PyErr_NoMemory();
5093 return 0;
5094 }
5095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005096}
5097
5098static void
5099assemble_free(struct assembler *a)
5100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 Py_XDECREF(a->a_bytecode);
5102 Py_XDECREF(a->a_lnotab);
5103 if (a->a_postorder)
5104 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005105}
5106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107static int
5108blocksize(basicblock *b)
5109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 int i;
5111 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005114 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005116}
5117
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005118/* Appends a pair to the end of the line number table, a_lnotab, representing
5119 the instruction's bytecode offset and line number. See
5120 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005121
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005122static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005126 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005128
Serhiy Storchakaab874002016-09-11 13:48:15 +03005129 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 if(d_bytecode == 0 && d_lineno == 0)
5135 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 if (d_bytecode > 255) {
5138 int j, nbytes, ncodes = d_bytecode / 255;
5139 nbytes = a->a_lnotab_off + 2 * ncodes;
5140 len = PyBytes_GET_SIZE(a->a_lnotab);
5141 if (nbytes >= len) {
5142 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5143 len = nbytes;
5144 else if (len <= INT_MAX / 2)
5145 len *= 2;
5146 else {
5147 PyErr_NoMemory();
5148 return 0;
5149 }
5150 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5151 return 0;
5152 }
5153 lnotab = (unsigned char *)
5154 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5155 for (j = 0; j < ncodes; j++) {
5156 *lnotab++ = 255;
5157 *lnotab++ = 0;
5158 }
5159 d_bytecode -= ncodes * 255;
5160 a->a_lnotab_off += ncodes * 2;
5161 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005162 assert(0 <= d_bytecode && d_bytecode <= 255);
5163
5164 if (d_lineno < -128 || 127 < d_lineno) {
5165 int j, nbytes, ncodes, k;
5166 if (d_lineno < 0) {
5167 k = -128;
5168 /* use division on positive numbers */
5169 ncodes = (-d_lineno) / 128;
5170 }
5171 else {
5172 k = 127;
5173 ncodes = d_lineno / 127;
5174 }
5175 d_lineno -= ncodes * k;
5176 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 nbytes = a->a_lnotab_off + 2 * ncodes;
5178 len = PyBytes_GET_SIZE(a->a_lnotab);
5179 if (nbytes >= len) {
5180 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5181 len = nbytes;
5182 else if (len <= INT_MAX / 2)
5183 len *= 2;
5184 else {
5185 PyErr_NoMemory();
5186 return 0;
5187 }
5188 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5189 return 0;
5190 }
5191 lnotab = (unsigned char *)
5192 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5193 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005194 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 d_bytecode = 0;
5196 for (j = 1; j < ncodes; j++) {
5197 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005198 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 a->a_lnotab_off += ncodes * 2;
5201 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005202 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 len = PyBytes_GET_SIZE(a->a_lnotab);
5205 if (a->a_lnotab_off + 2 >= len) {
5206 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5207 return 0;
5208 }
5209 lnotab = (unsigned char *)
5210 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005212 a->a_lnotab_off += 2;
5213 if (d_bytecode) {
5214 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005215 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 }
5217 else { /* First line of a block; def stmt, etc. */
5218 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005219 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 }
5221 a->a_lineno = i->i_lineno;
5222 a->a_lineno_off = a->a_offset;
5223 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005224}
5225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005226/* assemble_emit()
5227 Extend the bytecode with a new instruction.
5228 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005229*/
5230
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005231static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005232assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005233{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005234 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005236 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005237
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005238 arg = i->i_oparg;
5239 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 if (i->i_lineno && !assemble_lnotab(a, i))
5241 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005242 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 if (len > PY_SSIZE_T_MAX / 2)
5244 return 0;
5245 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5246 return 0;
5247 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005248 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005250 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005252}
5253
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005254static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005255assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005258 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 /* Compute the size of each block and fixup jump args.
5262 Replace block pointer with position in bytecode. */
5263 do {
5264 totsize = 0;
5265 for (i = a->a_nblocks - 1; i >= 0; i--) {
5266 b = a->a_postorder[i];
5267 bsize = blocksize(b);
5268 b->b_offset = totsize;
5269 totsize += bsize;
5270 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005271 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5273 bsize = b->b_offset;
5274 for (i = 0; i < b->b_iused; i++) {
5275 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005276 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 /* Relative jumps are computed relative to
5278 the instruction pointer after fetching
5279 the jump instruction.
5280 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005281 bsize += isize;
5282 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005284 if (instr->i_jrel) {
5285 instr->i_oparg -= bsize;
5286 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005287 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005288 if (instrsize(instr->i_oparg) != isize) {
5289 extended_arg_recompile = 1;
5290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 }
5293 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 /* XXX: This is an awful hack that could hurt performance, but
5296 on the bright side it should work until we come up
5297 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 The issue is that in the first loop blocksize() is called
5300 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005301 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 So we loop until we stop seeing new EXTENDED_ARGs.
5305 The only EXTENDED_ARGs that could be popping up are
5306 ones in jump instructions. So this should converge
5307 fairly quickly.
5308 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005309 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005310}
5311
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005312static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005313dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005315 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005316 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 tuple = PyTuple_New(size);
5319 if (tuple == NULL)
5320 return NULL;
5321 while (PyDict_Next(dict, &pos, &k, &v)) {
5322 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005323 Py_INCREF(k);
5324 assert((i - offset) < size);
5325 assert((i - offset) >= 0);
5326 PyTuple_SET_ITEM(tuple, i - offset, k);
5327 }
5328 return tuple;
5329}
5330
5331static PyObject *
5332consts_dict_keys_inorder(PyObject *dict)
5333{
5334 PyObject *consts, *k, *v;
5335 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5336
5337 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5338 if (consts == NULL)
5339 return NULL;
5340 while (PyDict_Next(dict, &pos, &k, &v)) {
5341 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005342 /* The keys of the dictionary can be tuples wrapping a contant.
5343 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5344 * the object we want is always second. */
5345 if (PyTuple_CheckExact(k)) {
5346 k = PyTuple_GET_ITEM(k, 1);
5347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005349 assert(i < size);
5350 assert(i >= 0);
5351 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005353 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005354}
5355
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005356static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005357compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005360 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005362 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 if (ste->ste_nested)
5364 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005365 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005367 if (!ste->ste_generator && ste->ste_coroutine)
5368 flags |= CO_COROUTINE;
5369 if (ste->ste_generator && ste->ste_coroutine)
5370 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 if (ste->ste_varargs)
5372 flags |= CO_VARARGS;
5373 if (ste->ste_varkeywords)
5374 flags |= CO_VARKEYWORDS;
5375 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 /* (Only) inherit compilerflags in PyCF_MASK */
5378 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005381}
5382
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005383static PyCodeObject *
5384makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 PyObject *tmp;
5387 PyCodeObject *co = NULL;
5388 PyObject *consts = NULL;
5389 PyObject *names = NULL;
5390 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 PyObject *name = NULL;
5392 PyObject *freevars = NULL;
5393 PyObject *cellvars = NULL;
5394 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005395 Py_ssize_t nlocals;
5396 int nlocals_int;
5397 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005398 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005399
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005400 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 names = dict_keys_inorder(c->u->u_names, 0);
5402 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5403 if (!consts || !names || !varnames)
5404 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5407 if (!cellvars)
5408 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005409 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 if (!freevars)
5411 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005412
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005413 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005414 assert(nlocals < INT_MAX);
5415 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 flags = compute_code_flags(c);
5418 if (flags < 0)
5419 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5422 if (!bytecode)
5423 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5426 if (!tmp)
5427 goto error;
5428 Py_DECREF(consts);
5429 consts = tmp;
5430
Victor Stinnerf8e32212013-11-19 23:56:34 +01005431 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5432 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005433 maxdepth = stackdepth(c);
5434 if (maxdepth < 0) {
5435 goto error;
5436 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005437 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005438 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 bytecode, consts, names, varnames,
5440 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005441 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 c->u->u_firstlineno,
5443 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005444 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 Py_XDECREF(consts);
5446 Py_XDECREF(names);
5447 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 Py_XDECREF(name);
5449 Py_XDECREF(freevars);
5450 Py_XDECREF(cellvars);
5451 Py_XDECREF(bytecode);
5452 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005453}
5454
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005455
5456/* For debugging purposes only */
5457#if 0
5458static void
5459dump_instr(const struct instr *i)
5460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 const char *jrel = i->i_jrel ? "jrel " : "";
5462 const char *jabs = i->i_jabs ? "jabs " : "";
5463 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005466 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5470 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005471}
5472
5473static void
5474dump_basicblock(const basicblock *b)
5475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 const char *seen = b->b_seen ? "seen " : "";
5477 const char *b_return = b->b_return ? "return " : "";
5478 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5479 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5480 if (b->b_instr) {
5481 int i;
5482 for (i = 0; i < b->b_iused; i++) {
5483 fprintf(stderr, " [%02d] ", i);
5484 dump_instr(b->b_instr + i);
5485 }
5486 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005487}
5488#endif
5489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005490static PyCodeObject *
5491assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 basicblock *b, *entryblock;
5494 struct assembler a;
5495 int i, j, nblocks;
5496 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 /* Make sure every block that falls off the end returns None.
5499 XXX NEXT_BLOCK() isn't quite right, because if the last
5500 block ends with a jump or return b_next shouldn't set.
5501 */
5502 if (!c->u->u_curblock->b_return) {
5503 NEXT_BLOCK(c);
5504 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005505 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 ADDOP(c, RETURN_VALUE);
5507 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 nblocks = 0;
5510 entryblock = NULL;
5511 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5512 nblocks++;
5513 entryblock = b;
5514 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 /* Set firstlineno if it wasn't explicitly set. */
5517 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005518 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5520 else
5521 c->u->u_firstlineno = 1;
5522 }
5523 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5524 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005525 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 /* Can't modify the bytecode after computing jump offsets. */
5528 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 /* Emit code in reverse postorder from dfs. */
5531 for (i = a.a_nblocks - 1; i >= 0; i--) {
5532 b = a.a_postorder[i];
5533 for (j = 0; j < b->b_iused; j++)
5534 if (!assemble_emit(&a, &b->b_instr[j]))
5535 goto error;
5536 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5539 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005540 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005544 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 assemble_free(&a);
5546 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005547}
Georg Brandl8334fd92010-12-04 10:26:46 +00005548
5549#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005550PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005551PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5552 PyArena *arena)
5553{
5554 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5555}