blob: ff5522044338a96da83cd70accccf7422472b97b [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned i_jabs : 1;
47 unsigned i_jrel : 1;
48 unsigned i_hasarg : 1;
49 unsigned char i_opcode;
50 int i_oparg;
51 struct basicblock_ *i_target; /* target block (if jump instruction) */
52 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000053};
54
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000055typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056 /* Each basicblock in a compilation unit is linked via b_list in the
57 reverse order that the block are allocated. b_list points to the next
58 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 struct basicblock_ *b_list;
60 /* number of instructions used */
61 int b_iused;
62 /* length of instruction array (b_instr) */
63 int b_ialloc;
64 /* pointer to an array of instructions, initially NULL */
65 struct instr *b_instr;
66 /* If b_next is non-NULL, it is a pointer to the next
67 block reached by normal control flow. */
68 struct basicblock_ *b_next;
69 /* b_seen is used to perform a DFS of basicblocks. */
70 unsigned b_seen : 1;
71 /* b_return is true if a RETURN_VALUE opcode is inserted. */
72 unsigned b_return : 1;
73 /* depth of stack upon entry of block, computed by stackdepth() */
74 int b_startdepth;
75 /* instruction offset for block, computed by assemble_jump_offsets() */
76 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077} basicblock;
78
79/* fblockinfo tracks the current frame block.
80
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081A frame block is used to handle loops, try/except, and try/finally.
82It's called a frame block to distinguish it from a basic block in the
83compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084*/
85
86enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
87
88struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 enum fblocktype fb_type;
90 basicblock *fb_block;
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,
97 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 int u_argcount; /* number of arguments for block */
123 int u_kwonlyargcount; /* number of keyword only arguments for block */
124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144*/
145
146struct compiler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 const char *c_filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500148 PyObject *c_filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 struct symtable *c_st;
150 PyFutureFeatures *c_future; /* pointer to module's __future__ */
151 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152
Georg Brandl8334fd92010-12-04 10:26:46 +0000153 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 int c_interactive; /* true if in interactive mode */
155 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 struct compiler_unit *u; /* compiler state for current block */
158 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
159 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160};
161
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100162static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163static void compiler_free(struct compiler *);
164static basicblock *compiler_new_block(struct compiler *);
165static int compiler_next_instr(struct compiler *, basicblock *);
166static int compiler_addop(struct compiler *, int);
167static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
168static int compiler_addop_i(struct compiler *, int, int);
169static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170static basicblock *compiler_use_new_block(struct compiler *);
171static int compiler_error(struct compiler *, const char *);
172static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
173
174static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
175static int compiler_visit_stmt(struct compiler *, stmt_ty);
176static int compiler_visit_keyword(struct compiler *, keyword_ty);
177static int compiler_visit_expr(struct compiler *, expr_ty);
178static int compiler_augassign(struct compiler *, stmt_ty);
179static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181
182static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186/* Returns true if there is a loop on the fblock stack. */
187static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188
189static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000190static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500192static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000193static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 asdl_seq *args,
195 asdl_seq *keywords,
196 expr_ty starargs,
197 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500198static int compiler_try_except(struct compiler *, stmt_ty);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200static PyCodeObject *assemble(struct compiler *, int addNone);
201static PyObject *__doc__;
202
Benjamin Petersonb173f782009-05-05 22:31:58 +0000203#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* Name mangling: __private becomes _classname__private.
209 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200210 PyObject *result;
211 size_t nlen, plen, ipriv;
212 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyUnicode_READ_CHAR(ident, 0) != '_' ||
215 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 Py_INCREF(ident);
217 return ident;
218 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 nlen = PyUnicode_GET_LENGTH(ident);
220 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 The only time a name with a dot can occur is when
224 we are compiling an import statement that has a
225 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 TODO(jhylton): Decide whether we want to support
228 mangling of the module name, e.g. __M.X.
229 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200230 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
231 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
232 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 Py_INCREF(ident);
234 return ident; /* Don't mangle __whatever__ */
235 }
236 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200237 ipriv = 0;
238 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
239 ipriv++;
240 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_INCREF(ident);
242 return ident; /* Don't mangle if class is just underscores */
243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200244 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 assert(1 <= PY_SSIZE_T_MAX - nlen);
247 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
250 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
251 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
252
253 result = PyUnicode_New(1 + nlen + plen, maxchar);
254 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
257 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200258 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
259 Py_DECREF(result);
260 return NULL;
261 }
262 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
263 Py_DECREF(result);
264 return NULL;
265 }
Victor Stinner8f825062012-04-27 13:55:39 +0200266 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000268}
269
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270static int
271compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 c->c_stack = PyList_New(0);
276 if (!c->c_stack)
277 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280}
281
282PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000283PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
284 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 struct compiler c;
287 PyCodeObject *co = NULL;
288 PyCompilerFlags local_flags;
289 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (!__doc__) {
292 __doc__ = PyUnicode_InternFromString("__doc__");
293 if (!__doc__)
294 return NULL;
295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (!compiler_init(&c))
298 return NULL;
299 c.c_filename = filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500300 c.c_filename_obj = PyUnicode_DecodeFSDefault(filename);
301 if (!c.c_filename_obj)
302 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 c.c_arena = arena;
304 c.c_future = PyFuture_FromAST(mod, filename);
305 if (c.c_future == NULL)
306 goto finally;
307 if (!flags) {
308 local_flags.cf_flags = 0;
309 flags = &local_flags;
310 }
311 merged = c.c_future->ff_features | flags->cf_flags;
312 c.c_future->ff_features = merged;
313 flags->cf_flags = merged;
314 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000315 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_st = PySymtable_Build(mod, filename, c.c_future);
319 if (c.c_st == NULL) {
320 if (!PyErr_Occurred())
321 PyErr_SetString(PyExc_SystemError, "no symtable");
322 goto finally;
323 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326
Thomas Wouters1175c432006-02-27 22:49:54 +0000327 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 compiler_free(&c);
329 assert(co || PyErr_Occurred());
330 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331}
332
333PyCodeObject *
334PyNode_Compile(struct _node *n, const char *filename)
335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyCodeObject *co = NULL;
337 mod_ty mod;
338 PyArena *arena = PyArena_New();
339 if (!arena)
340 return NULL;
341 mod = PyAST_FromNode(n, NULL, filename, arena);
342 if (mod)
343 co = PyAST_Compile(mod, filename, NULL, arena);
344 PyArena_Free(arena);
345 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000346}
347
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000348static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (c->c_st)
352 PySymtable_Free(c->c_st);
353 if (c->c_future)
354 PyObject_Free(c->c_future);
Benjamin Peterson43b06862011-05-27 09:08:01 -0500355 if (c->c_filename_obj)
356 Py_DECREF(c->c_filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000358}
359
Guido van Rossum79f25d91997-04-29 20:08:16 +0000360static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 Py_ssize_t i, n;
364 PyObject *v, *k;
365 PyObject *dict = PyDict_New();
366 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 n = PyList_Size(list);
369 for (i = 0; i < n; i++) {
370 v = PyLong_FromLong(i);
371 if (!v) {
372 Py_DECREF(dict);
373 return NULL;
374 }
375 k = PyList_GET_ITEM(list, i);
376 k = PyTuple_Pack(2, k, k->ob_type);
377 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
378 Py_XDECREF(k);
379 Py_DECREF(v);
380 Py_DECREF(dict);
381 return NULL;
382 }
383 Py_DECREF(k);
384 Py_DECREF(v);
385 }
386 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387}
388
389/* Return new dict containing names from src that match scope(s).
390
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000393values are integers, starting at offset and increasing by one for
394each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395*/
396
397static PyObject *
398dictbytype(PyObject *src, int scope_type, int flag, int offset)
399{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700400 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500402 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 assert(offset >= 0);
405 if (dest == NULL)
406 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407
Meador Inge2ca63152012-07-18 14:20:11 -0500408 /* Sort the keys so that we have a deterministic order on the indexes
409 saved in the returned dictionary. These indexes are used as indexes
410 into the free and cell var storage. Therefore if they aren't
411 deterministic, then the generated bytecode is not deterministic.
412 */
413 sorted_keys = PyDict_Keys(src);
414 if (sorted_keys == NULL)
415 return NULL;
416 if (PyList_Sort(sorted_keys) != 0) {
417 Py_DECREF(sorted_keys);
418 return NULL;
419 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500420 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500421
422 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* XXX this should probably be a macro in symtable.h */
424 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500425 k = PyList_GET_ITEM(sorted_keys, key_i);
426 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 assert(PyLong_Check(v));
428 vi = PyLong_AS_LONG(v);
429 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (scope == scope_type || vi & flag) {
432 PyObject *tuple, *item = PyLong_FromLong(i);
433 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500434 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_DECREF(dest);
436 return NULL;
437 }
438 i++;
439 tuple = PyTuple_Pack(2, k, k->ob_type);
440 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500441 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 Py_DECREF(item);
443 Py_DECREF(dest);
444 Py_XDECREF(tuple);
445 return NULL;
446 }
447 Py_DECREF(item);
448 Py_DECREF(tuple);
449 }
450 }
Meador Inge2ca63152012-07-18 14:20:11 -0500451 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000453}
454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455static void
456compiler_unit_check(struct compiler_unit *u)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 basicblock *block;
459 for (block = u->u_blocks; block != NULL; block = block->b_list) {
460 assert((void *)block != (void *)0xcbcbcbcb);
461 assert((void *)block != (void *)0xfbfbfbfb);
462 assert((void *)block != (void *)0xdbdbdbdb);
463 if (block->b_instr != NULL) {
464 assert(block->b_ialloc > 0);
465 assert(block->b_iused > 0);
466 assert(block->b_ialloc >= block->b_iused);
467 }
468 else {
469 assert (block->b_iused == 0);
470 assert (block->b_ialloc == 0);
471 }
472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473}
474
475static void
476compiler_unit_free(struct compiler_unit *u)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 compiler_unit_check(u);
481 b = u->u_blocks;
482 while (b != NULL) {
483 if (b->b_instr)
484 PyObject_Free((void *)b->b_instr);
485 next = b->b_list;
486 PyObject_Free((void *)b);
487 b = next;
488 }
489 Py_CLEAR(u->u_ste);
490 Py_CLEAR(u->u_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100491 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_CLEAR(u->u_consts);
493 Py_CLEAR(u->u_names);
494 Py_CLEAR(u->u_varnames);
495 Py_CLEAR(u->u_freevars);
496 Py_CLEAR(u->u_cellvars);
497 Py_CLEAR(u->u_private);
498 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499}
500
501static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100502compiler_enter_scope(struct compiler *c, identifier name,
503 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
508 struct compiler_unit));
509 if (!u) {
510 PyErr_NoMemory();
511 return 0;
512 }
513 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100514 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 u->u_argcount = 0;
516 u->u_kwonlyargcount = 0;
517 u->u_ste = PySymtable_Lookup(c->c_st, key);
518 if (!u->u_ste) {
519 compiler_unit_free(u);
520 return 0;
521 }
522 Py_INCREF(name);
523 u->u_name = name;
524 u->u_varnames = list2dict(u->u_ste->ste_varnames);
525 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
526 if (!u->u_varnames || !u->u_cellvars) {
527 compiler_unit_free(u);
528 return 0;
529 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
532 PyDict_Size(u->u_cellvars));
533 if (!u->u_freevars) {
534 compiler_unit_free(u);
535 return 0;
536 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 u->u_blocks = NULL;
539 u->u_nfblocks = 0;
540 u->u_firstlineno = lineno;
541 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000542 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 u->u_lineno_set = 0;
544 u->u_consts = PyDict_New();
545 if (!u->u_consts) {
546 compiler_unit_free(u);
547 return 0;
548 }
549 u->u_names = PyDict_New();
550 if (!u->u_names) {
551 compiler_unit_free(u);
552 return 0;
553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 /* Push the old compiler_unit on the stack. */
558 if (c->u) {
559 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
560 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
561 Py_XDECREF(capsule);
562 compiler_unit_free(u);
563 return 0;
564 }
565 Py_DECREF(capsule);
566 u->u_private = c->u->u_private;
567 Py_XINCREF(u->u_private);
568 }
569 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 c->c_nestlevel++;
572 if (compiler_use_new_block(c) == NULL)
573 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000576}
577
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000578static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579compiler_exit_scope(struct compiler *c)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 int n;
582 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 c->c_nestlevel--;
585 compiler_unit_free(c->u);
586 /* Restore c->u to the parent unit. */
587 n = PyList_GET_SIZE(c->c_stack) - 1;
588 if (n >= 0) {
589 capsule = PyList_GET_ITEM(c->c_stack, n);
590 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
591 assert(c->u);
592 /* we are deleting from a list so this really shouldn't fail */
593 if (PySequence_DelItem(c->c_stack, n) < 0)
594 Py_FatalError("compiler_exit_scope()");
595 compiler_unit_check(c->u);
596 }
597 else
598 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600}
601
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100602static PyObject *
603compiler_scope_qualname(struct compiler *c)
604{
605 Py_ssize_t stack_size, i;
606 _Py_static_string(dot, ".");
607 _Py_static_string(locals, "<locals>");
608 struct compiler_unit *u;
609 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
610
611 u = c->u;
612 if (u->u_qualname != NULL) {
613 Py_INCREF(u->u_qualname);
614 return u->u_qualname;
615 }
616
617 seq = PyList_New(0);
618 if (seq == NULL)
619 return NULL;
620
621 stack_size = PyList_GET_SIZE(c->c_stack);
622 for (i = 0; i < stack_size; i++) {
623 capsule = PyList_GET_ITEM(c->c_stack, i);
624 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
625 assert(u);
626 if (u->u_scope_type == COMPILER_SCOPE_MODULE)
627 continue;
628 if (PyList_Append(seq, u->u_name))
629 goto _error;
630 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
631 locals_str = _PyUnicode_FromId(&locals);
632 if (locals_str == NULL)
633 goto _error;
634 if (PyList_Append(seq, locals_str))
635 goto _error;
636 }
637 }
638 u = c->u;
639 if (PyList_Append(seq, u->u_name))
640 goto _error;
641 dot_str = _PyUnicode_FromId(&dot);
642 if (dot_str == NULL)
643 goto _error;
644 name = PyUnicode_Join(dot_str, seq);
645 Py_DECREF(seq);
646 u->u_qualname = name;
647 Py_XINCREF(name);
648 return name;
649
650_error:
651 Py_XDECREF(seq);
652 return NULL;
653}
654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655/* Allocate a new block and return a pointer to it.
656 Returns NULL on error.
657*/
658
659static basicblock *
660compiler_new_block(struct compiler *c)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 basicblock *b;
663 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 u = c->u;
666 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
667 if (b == NULL) {
668 PyErr_NoMemory();
669 return NULL;
670 }
671 memset((void *)b, 0, sizeof(basicblock));
672 /* Extend the singly linked list of blocks with new block. */
673 b->b_list = u->u_blocks;
674 u->u_blocks = b;
675 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000678static basicblock *
679compiler_use_new_block(struct compiler *c)
680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 basicblock *block = compiler_new_block(c);
682 if (block == NULL)
683 return NULL;
684 c->u->u_curblock = block;
685 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686}
687
688static basicblock *
689compiler_next_block(struct compiler *c)
690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 basicblock *block = compiler_new_block(c);
692 if (block == NULL)
693 return NULL;
694 c->u->u_curblock->b_next = block;
695 c->u->u_curblock = block;
696 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000697}
698
699static basicblock *
700compiler_use_next_block(struct compiler *c, basicblock *block)
701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 assert(block != NULL);
703 c->u->u_curblock->b_next = block;
704 c->u->u_curblock = block;
705 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000706}
707
708/* Returns the offset of the next instruction in the current block's
709 b_instr array. Resizes the b_instr as necessary.
710 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000711*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000712
713static int
714compiler_next_instr(struct compiler *c, basicblock *b)
715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 assert(b != NULL);
717 if (b->b_instr == NULL) {
718 b->b_instr = (struct instr *)PyObject_Malloc(
719 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
720 if (b->b_instr == NULL) {
721 PyErr_NoMemory();
722 return -1;
723 }
724 b->b_ialloc = DEFAULT_BLOCK_SIZE;
725 memset((char *)b->b_instr, 0,
726 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
727 }
728 else if (b->b_iused == b->b_ialloc) {
729 struct instr *tmp;
730 size_t oldsize, newsize;
731 oldsize = b->b_ialloc * sizeof(struct instr);
732 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (oldsize > (PY_SIZE_MAX >> 1)) {
735 PyErr_NoMemory();
736 return -1;
737 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (newsize == 0) {
740 PyErr_NoMemory();
741 return -1;
742 }
743 b->b_ialloc <<= 1;
744 tmp = (struct instr *)PyObject_Realloc(
745 (void *)b->b_instr, newsize);
746 if (tmp == NULL) {
747 PyErr_NoMemory();
748 return -1;
749 }
750 b->b_instr = tmp;
751 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
752 }
753 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754}
755
Christian Heimes2202f872008-02-06 14:31:34 +0000756/* Set the i_lineno member of the instruction at offset off if the
757 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758 already been set. If it has been set, the call has no effect.
759
Christian Heimes2202f872008-02-06 14:31:34 +0000760 The line number is reset in the following cases:
761 - when entering a new scope
762 - on each statement
763 - on each expression that start a new line
764 - before the "except" clause
765 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000766*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768static void
769compiler_set_lineno(struct compiler *c, int off)
770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 basicblock *b;
772 if (c->u->u_lineno_set)
773 return;
774 c->u->u_lineno_set = 1;
775 b = c->u->u_curblock;
776 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777}
778
779static int
780opcode_stack_effect(int opcode, int oparg)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 switch (opcode) {
783 case POP_TOP:
784 return -1;
785 case ROT_TWO:
786 case ROT_THREE:
787 return 0;
788 case DUP_TOP:
789 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000790 case DUP_TOP_TWO:
791 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 case UNARY_POSITIVE:
794 case UNARY_NEGATIVE:
795 case UNARY_NOT:
796 case UNARY_INVERT:
797 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 case SET_ADD:
800 case LIST_APPEND:
801 return -1;
802 case MAP_ADD:
803 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 case BINARY_POWER:
806 case BINARY_MULTIPLY:
807 case BINARY_MODULO:
808 case BINARY_ADD:
809 case BINARY_SUBTRACT:
810 case BINARY_SUBSCR:
811 case BINARY_FLOOR_DIVIDE:
812 case BINARY_TRUE_DIVIDE:
813 return -1;
814 case INPLACE_FLOOR_DIVIDE:
815 case INPLACE_TRUE_DIVIDE:
816 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 case INPLACE_ADD:
819 case INPLACE_SUBTRACT:
820 case INPLACE_MULTIPLY:
821 case INPLACE_MODULO:
822 return -1;
823 case STORE_SUBSCR:
824 return -3;
825 case STORE_MAP:
826 return -2;
827 case DELETE_SUBSCR:
828 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 case BINARY_LSHIFT:
831 case BINARY_RSHIFT:
832 case BINARY_AND:
833 case BINARY_XOR:
834 case BINARY_OR:
835 return -1;
836 case INPLACE_POWER:
837 return -1;
838 case GET_ITER:
839 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 case PRINT_EXPR:
842 return -1;
843 case LOAD_BUILD_CLASS:
844 return 1;
845 case INPLACE_LSHIFT:
846 case INPLACE_RSHIFT:
847 case INPLACE_AND:
848 case INPLACE_XOR:
849 case INPLACE_OR:
850 return -1;
851 case BREAK_LOOP:
852 return 0;
853 case SETUP_WITH:
854 return 7;
855 case WITH_CLEANUP:
856 return -1; /* XXX Sometimes more */
857 case STORE_LOCALS:
858 return -1;
859 case RETURN_VALUE:
860 return -1;
861 case IMPORT_STAR:
862 return -1;
863 case YIELD_VALUE:
864 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500865 case YIELD_FROM:
866 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 case POP_BLOCK:
868 return 0;
869 case POP_EXCEPT:
870 return 0; /* -3 except if bad bytecode */
871 case END_FINALLY:
872 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 case STORE_NAME:
875 return -1;
876 case DELETE_NAME:
877 return 0;
878 case UNPACK_SEQUENCE:
879 return oparg-1;
880 case UNPACK_EX:
881 return (oparg&0xFF) + (oparg>>8);
882 case FOR_ITER:
883 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case STORE_ATTR:
886 return -2;
887 case DELETE_ATTR:
888 return -1;
889 case STORE_GLOBAL:
890 return -1;
891 case DELETE_GLOBAL:
892 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 case LOAD_CONST:
894 return 1;
895 case LOAD_NAME:
896 return 1;
897 case BUILD_TUPLE:
898 case BUILD_LIST:
899 case BUILD_SET:
900 return 1-oparg;
901 case BUILD_MAP:
902 return 1;
903 case LOAD_ATTR:
904 return 0;
905 case COMPARE_OP:
906 return -1;
907 case IMPORT_NAME:
908 return -1;
909 case IMPORT_FROM:
910 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 case JUMP_FORWARD:
913 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
914 case JUMP_IF_FALSE_OR_POP: /* "" */
915 case JUMP_ABSOLUTE:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case POP_JUMP_IF_FALSE:
919 case POP_JUMP_IF_TRUE:
920 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case LOAD_GLOBAL:
923 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case CONTINUE_LOOP:
926 return 0;
927 case SETUP_LOOP:
928 return 0;
929 case SETUP_EXCEPT:
930 case SETUP_FINALLY:
931 return 6; /* can push 3 values for the new exception
932 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case LOAD_FAST:
935 return 1;
936 case STORE_FAST:
937 return -1;
938 case DELETE_FAST:
939 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case RAISE_VARARGS:
942 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000943#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case CALL_FUNCTION:
945 return -NARGS(oparg);
946 case CALL_FUNCTION_VAR:
947 case CALL_FUNCTION_KW:
948 return -NARGS(oparg)-1;
949 case CALL_FUNCTION_VAR_KW:
950 return -NARGS(oparg)-2;
951 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100952 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100954 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000955#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case BUILD_SLICE:
957 if (oparg == 3)
958 return -2;
959 else
960 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 case LOAD_CLOSURE:
963 return 1;
964 case LOAD_DEREF:
965 return 1;
966 case STORE_DEREF:
967 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000968 case DELETE_DEREF:
969 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 default:
971 fprintf(stderr, "opcode = %d\n", opcode);
972 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
975 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976}
977
978/* Add an opcode with no argument.
979 Returns 0 on failure, 1 on success.
980*/
981
982static int
983compiler_addop(struct compiler *c, int opcode)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 basicblock *b;
986 struct instr *i;
987 int off;
988 off = compiler_next_instr(c, c->u->u_curblock);
989 if (off < 0)
990 return 0;
991 b = c->u->u_curblock;
992 i = &b->b_instr[off];
993 i->i_opcode = opcode;
994 i->i_hasarg = 0;
995 if (opcode == RETURN_VALUE)
996 b->b_return = 1;
997 compiler_set_lineno(c, off);
998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999}
1000
1001static int
1002compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject *t, *v;
1005 Py_ssize_t arg;
1006 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* necessary to make sure types aren't coerced (e.g., int and long) */
1009 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1010 if (PyFloat_Check(o)) {
1011 d = PyFloat_AS_DOUBLE(o);
1012 /* all we need is to make the tuple different in either the 0.0
1013 * or -0.0 case from all others, just to avoid the "coercion".
1014 */
1015 if (d == 0.0 && copysign(1.0, d) < 0.0)
1016 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1017 else
1018 t = PyTuple_Pack(2, o, o->ob_type);
1019 }
1020 else if (PyComplex_Check(o)) {
1021 Py_complex z;
1022 int real_negzero, imag_negzero;
1023 /* For the complex case we must make complex(x, 0.)
1024 different from complex(x, -0.) and complex(0., y)
1025 different from complex(-0., y), for any x and y.
1026 All four complex zeros must be distinguished.*/
1027 z = PyComplex_AsCComplex(o);
1028 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1029 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1030 if (real_negzero && imag_negzero) {
1031 t = PyTuple_Pack(5, o, o->ob_type,
1032 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001033 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 else if (imag_negzero) {
1035 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 else if (real_negzero) {
1038 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1039 }
1040 else {
1041 t = PyTuple_Pack(2, o, o->ob_type);
1042 }
1043 }
1044 else {
1045 t = PyTuple_Pack(2, o, o->ob_type);
1046 }
1047 if (t == NULL)
1048 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 v = PyDict_GetItem(dict, t);
1051 if (!v) {
1052 if (PyErr_Occurred())
1053 return -1;
1054 arg = PyDict_Size(dict);
1055 v = PyLong_FromLong(arg);
1056 if (!v) {
1057 Py_DECREF(t);
1058 return -1;
1059 }
1060 if (PyDict_SetItem(dict, t, v) < 0) {
1061 Py_DECREF(t);
1062 Py_DECREF(v);
1063 return -1;
1064 }
1065 Py_DECREF(v);
1066 }
1067 else
1068 arg = PyLong_AsLong(v);
1069 Py_DECREF(t);
1070 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073static int
1074compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076{
1077 int arg = compiler_add_o(c, dict, o);
1078 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001079 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080 return compiler_addop_i(c, opcode, arg);
1081}
1082
1083static int
1084compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086{
1087 int arg;
1088 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1089 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001090 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001091 arg = compiler_add_o(c, dict, mangled);
1092 Py_DECREF(mangled);
1093 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001094 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095 return compiler_addop_i(c, opcode, arg);
1096}
1097
1098/* Add an opcode with an integer argument.
1099 Returns 0 on failure, 1 on success.
1100*/
1101
1102static int
1103compiler_addop_i(struct compiler *c, int opcode, int oparg)
1104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 struct instr *i;
1106 int off;
1107 off = compiler_next_instr(c, c->u->u_curblock);
1108 if (off < 0)
1109 return 0;
1110 i = &c->u->u_curblock->b_instr[off];
1111 i->i_opcode = opcode;
1112 i->i_oparg = oparg;
1113 i->i_hasarg = 1;
1114 compiler_set_lineno(c, off);
1115 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116}
1117
1118static int
1119compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 struct instr *i;
1122 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 assert(b != NULL);
1125 off = compiler_next_instr(c, c->u->u_curblock);
1126 if (off < 0)
1127 return 0;
1128 i = &c->u->u_curblock->b_instr[off];
1129 i->i_opcode = opcode;
1130 i->i_target = b;
1131 i->i_hasarg = 1;
1132 if (absolute)
1133 i->i_jabs = 1;
1134 else
1135 i->i_jrel = 1;
1136 compiler_set_lineno(c, off);
1137 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138}
1139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1141 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142 it as the current block. NEXT_BLOCK() also creates an implicit jump
1143 from the current block to the new block.
1144*/
1145
Thomas Wouters89f507f2006-12-13 04:49:30 +00001146/* The returns inside these macros make it impossible to decref objects
1147 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148*/
1149
1150
1151#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (compiler_use_new_block((C)) == NULL) \
1153 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154}
1155
1156#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (compiler_next_block((C)) == NULL) \
1158 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159}
1160
1161#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (!compiler_addop((C), (OP))) \
1163 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001166#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (!compiler_addop((C), (OP))) { \
1168 compiler_exit_scope(c); \
1169 return 0; \
1170 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001171}
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1175 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176}
1177
1178#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1180 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181}
1182
1183#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (!compiler_addop_i((C), (OP), (O))) \
1185 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
1188#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (!compiler_addop_j((C), (OP), (O), 1)) \
1190 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191}
1192
1193#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (!compiler_addop_j((C), (OP), (O), 0)) \
1195 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1199 the ASDL name to synthesize the name of the C type and the visit function.
1200*/
1201
1202#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (!compiler_visit_ ## TYPE((C), (V))) \
1204 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205}
1206
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001207#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (!compiler_visit_ ## TYPE((C), (V))) { \
1209 compiler_exit_scope(c); \
1210 return 0; \
1211 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001212}
1213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (!compiler_visit_slice((C), (V), (CTX))) \
1216 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217}
1218
1219#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 int _i; \
1221 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1222 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1223 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1224 if (!compiler_visit_ ## TYPE((C), elt)) \
1225 return 0; \
1226 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227}
1228
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001229#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 int _i; \
1231 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1232 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1233 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1234 if (!compiler_visit_ ## TYPE((C), elt)) { \
1235 compiler_exit_scope(c); \
1236 return 0; \
1237 } \
1238 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001239}
1240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241static int
1242compiler_isdocstring(stmt_ty s)
1243{
1244 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001245 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 return s->v.Expr.value->kind == Str_kind;
1247}
1248
1249/* Compile a sequence of statements, checking for a docstring. */
1250
1251static int
1252compiler_body(struct compiler *c, asdl_seq *stmts)
1253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 int i = 0;
1255 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (!asdl_seq_LEN(stmts))
1258 return 1;
1259 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001260 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 /* don't generate docstrings if -OO */
1262 i = 1;
1263 VISIT(c, expr, st->v.Expr.value);
1264 if (!compiler_nameop(c, __doc__, Store))
1265 return 0;
1266 }
1267 for (; i < asdl_seq_LEN(stmts); i++)
1268 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1269 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270}
1271
1272static PyCodeObject *
1273compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyCodeObject *co;
1276 int addNone = 1;
1277 static PyObject *module;
1278 if (!module) {
1279 module = PyUnicode_InternFromString("<module>");
1280 if (!module)
1281 return NULL;
1282 }
1283 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001284 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return NULL;
1286 switch (mod->kind) {
1287 case Module_kind:
1288 if (!compiler_body(c, mod->v.Module.body)) {
1289 compiler_exit_scope(c);
1290 return 0;
1291 }
1292 break;
1293 case Interactive_kind:
1294 c->c_interactive = 1;
1295 VISIT_SEQ_IN_SCOPE(c, stmt,
1296 mod->v.Interactive.body);
1297 break;
1298 case Expression_kind:
1299 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1300 addNone = 0;
1301 break;
1302 case Suite_kind:
1303 PyErr_SetString(PyExc_SystemError,
1304 "suite should not be possible");
1305 return 0;
1306 default:
1307 PyErr_Format(PyExc_SystemError,
1308 "module kind %d should not be possible",
1309 mod->kind);
1310 return 0;
1311 }
1312 co = assemble(c, addNone);
1313 compiler_exit_scope(c);
1314 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001315}
1316
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317/* The test for LOCAL must come before the test for FREE in order to
1318 handle classes where name is both local and free. The local var is
1319 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001320*/
1321
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322static int
1323get_ref_type(struct compiler *c, PyObject *name)
1324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 int scope = PyST_GetScope(c->u->u_ste, name);
1326 if (scope == 0) {
1327 char buf[350];
1328 PyOS_snprintf(buf, sizeof(buf),
1329 "unknown scope for %.100s in %.100s(%s) in %s\n"
1330 "symbols: %s\nlocals: %s\nglobals: %s",
1331 PyBytes_AS_STRING(name),
1332 PyBytes_AS_STRING(c->u->u_name),
1333 PyObject_REPR(c->u->u_ste->ste_id),
1334 c->c_filename,
1335 PyObject_REPR(c->u->u_ste->ste_symbols),
1336 PyObject_REPR(c->u->u_varnames),
1337 PyObject_REPR(c->u->u_names)
1338 );
1339 Py_FatalError(buf);
1340 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343}
1344
1345static int
1346compiler_lookup_arg(PyObject *dict, PyObject *name)
1347{
1348 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001349 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001351 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001353 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001355 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001356 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357}
1358
1359static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001360compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001363 if (qualname == NULL)
1364 qualname = co->co_name;
1365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 if (free == 0) {
1367 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001368 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 ADDOP_I(c, MAKE_FUNCTION, args);
1370 return 1;
1371 }
1372 for (i = 0; i < free; ++i) {
1373 /* Bypass com_addop_varname because it will generate
1374 LOAD_DEREF but LOAD_CLOSURE is needed.
1375 */
1376 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1377 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* Special case: If a class contains a method with a
1380 free variable that has the same name as a method,
1381 the name will be considered free *and* local in the
1382 class. It should be handled by the closure, as
1383 well as by the normal name loookup logic.
1384 */
1385 reftype = get_ref_type(c, name);
1386 if (reftype == CELL)
1387 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1388 else /* (reftype == FREE) */
1389 arg = compiler_lookup_arg(c->u->u_freevars, name);
1390 if (arg == -1) {
1391 fprintf(stderr,
1392 "lookup %s in %s %d %d\n"
1393 "freevars of %s: %s\n",
1394 PyObject_REPR(name),
1395 PyBytes_AS_STRING(c->u->u_name),
1396 reftype, arg,
1397 _PyUnicode_AsString(co->co_name),
1398 PyObject_REPR(co->co_freevars));
1399 Py_FatalError("compiler_make_closure()");
1400 }
1401 ADDOP_I(c, LOAD_CLOSURE, arg);
1402 }
1403 ADDOP_I(c, BUILD_TUPLE, free);
1404 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001405 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 ADDOP_I(c, MAKE_CLOSURE, args);
1407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408}
1409
1410static int
1411compiler_decorators(struct compiler *c, asdl_seq* decos)
1412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (!decos)
1416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1419 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1420 }
1421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422}
1423
1424static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001425compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 int i, default_count = 0;
1429 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1430 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1431 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1432 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001433 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1434 if (!mangled)
1435 return -1;
1436 ADDOP_O(c, LOAD_CONST, mangled, consts);
1437 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (!compiler_visit_expr(c, default_)) {
1439 return -1;
1440 }
1441 default_count++;
1442 }
1443 }
1444 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001445}
1446
1447static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001448compiler_visit_argannotation(struct compiler *c, identifier id,
1449 expr_ty annotation, PyObject *names)
1450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (annotation) {
1452 VISIT(c, expr, annotation);
1453 if (PyList_Append(names, id))
1454 return -1;
1455 }
1456 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001457}
1458
1459static int
1460compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1461 PyObject *names)
1462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 int i, error;
1464 for (i = 0; i < asdl_seq_LEN(args); i++) {
1465 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1466 error = compiler_visit_argannotation(
1467 c,
1468 arg->arg,
1469 arg->annotation,
1470 names);
1471 if (error)
1472 return error;
1473 }
1474 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001475}
1476
1477static int
1478compiler_visit_annotations(struct compiler *c, arguments_ty args,
1479 expr_ty returns)
1480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 /* Push arg annotations and a list of the argument names. Return the #
1482 of items pushed. The expressions are evaluated out-of-order wrt the
1483 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1486 */
1487 static identifier return_str;
1488 PyObject *names;
1489 int len;
1490 names = PyList_New(0);
1491 if (!names)
1492 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (compiler_visit_argannotations(c, args->args, names))
1495 goto error;
1496 if (args->varargannotation &&
1497 compiler_visit_argannotation(c, args->vararg,
1498 args->varargannotation, names))
1499 goto error;
1500 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1501 goto error;
1502 if (args->kwargannotation &&
1503 compiler_visit_argannotation(c, args->kwarg,
1504 args->kwargannotation, names))
1505 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (!return_str) {
1508 return_str = PyUnicode_InternFromString("return");
1509 if (!return_str)
1510 goto error;
1511 }
1512 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1513 goto error;
1514 }
1515
1516 len = PyList_GET_SIZE(names);
1517 if (len > 65534) {
1518 /* len must fit in 16 bits, and len is incremented below */
1519 PyErr_SetString(PyExc_SyntaxError,
1520 "too many annotations");
1521 goto error;
1522 }
1523 if (len) {
1524 /* convert names to a tuple and place on stack */
1525 PyObject *elt;
1526 int i;
1527 PyObject *s = PyTuple_New(len);
1528 if (!s)
1529 goto error;
1530 for (i = 0; i < len; i++) {
1531 elt = PyList_GET_ITEM(names, i);
1532 Py_INCREF(elt);
1533 PyTuple_SET_ITEM(s, i, elt);
1534 }
1535 ADDOP_O(c, LOAD_CONST, s, consts);
1536 Py_DECREF(s);
1537 len++; /* include the just-pushed tuple */
1538 }
1539 Py_DECREF(names);
1540 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001541
1542error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_DECREF(names);
1544 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001545}
1546
1547static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548compiler_function(struct compiler *c, stmt_ty s)
1549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001551 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 arguments_ty args = s->v.FunctionDef.args;
1553 expr_ty returns = s->v.FunctionDef.returns;
1554 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1555 stmt_ty st;
1556 int i, n, docstring, kw_default_count = 0, arglength;
1557 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (!compiler_decorators(c, decos))
1562 return 0;
1563 if (args->kwonlyargs) {
1564 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1565 args->kw_defaults);
1566 if (res < 0)
1567 return 0;
1568 kw_default_count = res;
1569 }
1570 if (args->defaults)
1571 VISIT_SEQ(c, expr, args->defaults);
1572 num_annotations = compiler_visit_annotations(c, args, returns);
1573 if (num_annotations < 0)
1574 return 0;
1575 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001576
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001577 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1578 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 s->lineno))
1580 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1583 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001584 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 first_const = st->v.Expr.value->v.Str.s;
1586 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1587 compiler_exit_scope(c);
1588 return 0;
1589 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 c->u->u_argcount = asdl_seq_LEN(args->args);
1592 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1593 n = asdl_seq_LEN(s->v.FunctionDef.body);
1594 /* if there was a docstring, we need to skip the first statement */
1595 for (i = docstring; i < n; i++) {
1596 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1597 VISIT_IN_SCOPE(c, stmt, st);
1598 }
1599 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001600 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001602 if (qualname == NULL || co == NULL) {
1603 Py_XDECREF(qualname);
1604 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 arglength = asdl_seq_LEN(args->defaults);
1609 arglength |= kw_default_count << 8;
1610 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001611 compiler_make_closure(c, co, arglength, qualname);
1612 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 /* decorators */
1616 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1617 ADDOP_I(c, CALL_FUNCTION, 1);
1618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621}
1622
1623static int
1624compiler_class(struct compiler *c, stmt_ty s)
1625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyCodeObject *co;
1627 PyObject *str;
1628 int i;
1629 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (!compiler_decorators(c, decos))
1632 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 /* ultimately generate code for:
1635 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1636 where:
1637 <func> is a function/closure created from the class body;
1638 it has a single argument (__locals__) where the dict
1639 (or MutableSequence) representing the locals is passed
1640 <name> is the class name
1641 <bases> is the positional arguments and *varargs argument
1642 <keywords> is the keyword arguments and **kwds argument
1643 This borrows from compiler_call.
1644 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001647 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1648 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 return 0;
1650 /* this block represents what we do in the new scope */
1651 {
1652 /* use the class name for name mangling */
1653 Py_INCREF(s->v.ClassDef.name);
1654 Py_XDECREF(c->u->u_private);
1655 c->u->u_private = s->v.ClassDef.name;
1656 /* force it to have one mandatory argument */
1657 c->u->u_argcount = 1;
1658 /* load the first argument (__locals__) ... */
1659 ADDOP_I(c, LOAD_FAST, 0);
1660 /* ... and store it into f_locals */
1661 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1662 /* load (global) __name__ ... */
1663 str = PyUnicode_InternFromString("__name__");
1664 if (!str || !compiler_nameop(c, str, Load)) {
1665 Py_XDECREF(str);
1666 compiler_exit_scope(c);
1667 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 Py_DECREF(str);
1670 /* ... and store it as __module__ */
1671 str = PyUnicode_InternFromString("__module__");
1672 if (!str || !compiler_nameop(c, str, Store)) {
1673 Py_XDECREF(str);
1674 compiler_exit_scope(c);
1675 return 0;
1676 }
1677 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001678 /* store the __qualname__ */
1679 str = compiler_scope_qualname(c);
1680 if (!str) {
1681 compiler_exit_scope(c);
1682 return 0;
1683 }
1684 ADDOP_O(c, LOAD_CONST, str, consts);
1685 Py_DECREF(str);
1686 str = PyUnicode_InternFromString("__qualname__");
1687 if (!str || !compiler_nameop(c, str, Store)) {
1688 Py_XDECREF(str);
1689 compiler_exit_scope(c);
1690 return 0;
1691 }
1692 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 /* compile the body proper */
1694 if (!compiler_body(c, s->v.ClassDef.body)) {
1695 compiler_exit_scope(c);
1696 return 0;
1697 }
1698 /* return the (empty) __class__ cell */
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001699 str = PyUnicode_InternFromString("__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 if (str == NULL) {
1701 compiler_exit_scope(c);
1702 return 0;
1703 }
1704 i = compiler_lookup_arg(c->u->u_cellvars, str);
1705 Py_DECREF(str);
1706 if (i == -1) {
1707 /* This happens when nobody references the cell */
1708 PyErr_Clear();
1709 /* Return None */
1710 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1711 }
1712 else {
1713 /* Return the cell where to store __class__ */
1714 ADDOP_I(c, LOAD_CLOSURE, i);
1715 }
1716 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1717 /* create the code object */
1718 co = assemble(c, 1);
1719 }
1720 /* leave the new scope */
1721 compiler_exit_scope(c);
1722 if (co == NULL)
1723 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* 2. load the 'build_class' function */
1726 ADDOP(c, LOAD_BUILD_CLASS);
1727
1728 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001729 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 Py_DECREF(co);
1731
1732 /* 4. load class name */
1733 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1734
1735 /* 5. generate the rest of the code for the call */
1736 if (!compiler_call_helper(c, 2,
1737 s->v.ClassDef.bases,
1738 s->v.ClassDef.keywords,
1739 s->v.ClassDef.starargs,
1740 s->v.ClassDef.kwargs))
1741 return 0;
1742
1743 /* 6. apply decorators */
1744 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1745 ADDOP_I(c, CALL_FUNCTION, 1);
1746 }
1747
1748 /* 7. store into <name> */
1749 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1750 return 0;
1751 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752}
1753
1754static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001755compiler_ifexp(struct compiler *c, expr_ty e)
1756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 basicblock *end, *next;
1758
1759 assert(e->kind == IfExp_kind);
1760 end = compiler_new_block(c);
1761 if (end == NULL)
1762 return 0;
1763 next = compiler_new_block(c);
1764 if (next == NULL)
1765 return 0;
1766 VISIT(c, expr, e->v.IfExp.test);
1767 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1768 VISIT(c, expr, e->v.IfExp.body);
1769 ADDOP_JREL(c, JUMP_FORWARD, end);
1770 compiler_use_next_block(c, next);
1771 VISIT(c, expr, e->v.IfExp.orelse);
1772 compiler_use_next_block(c, end);
1773 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001774}
1775
1776static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777compiler_lambda(struct compiler *c, expr_ty e)
1778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001780 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 static identifier name;
1782 int kw_default_count = 0, arglength;
1783 arguments_ty args = e->v.Lambda.args;
1784 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (!name) {
1787 name = PyUnicode_InternFromString("<lambda>");
1788 if (!name)
1789 return 0;
1790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (args->kwonlyargs) {
1793 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1794 args->kw_defaults);
1795 if (res < 0) return 0;
1796 kw_default_count = res;
1797 }
1798 if (args->defaults)
1799 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001800 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1801 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Make None the first constant, so the lambda can't have a
1805 docstring. */
1806 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1807 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 c->u->u_argcount = asdl_seq_LEN(args->args);
1810 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1811 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1812 if (c->u->u_ste->ste_generator) {
1813 ADDOP_IN_SCOPE(c, POP_TOP);
1814 }
1815 else {
1816 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1817 }
1818 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001819 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001821 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 arglength = asdl_seq_LEN(args->defaults);
1825 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001826 compiler_make_closure(c, co, arglength, qualname);
1827 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 Py_DECREF(co);
1829
1830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831}
1832
1833static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834compiler_if(struct compiler *c, stmt_ty s)
1835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 basicblock *end, *next;
1837 int constant;
1838 assert(s->kind == If_kind);
1839 end = compiler_new_block(c);
1840 if (end == NULL)
1841 return 0;
1842
Georg Brandl8334fd92010-12-04 10:26:46 +00001843 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 /* constant = 0: "if 0"
1845 * constant = 1: "if 1", "if 2", ...
1846 * constant = -1: rest */
1847 if (constant == 0) {
1848 if (s->v.If.orelse)
1849 VISIT_SEQ(c, stmt, s->v.If.orelse);
1850 } else if (constant == 1) {
1851 VISIT_SEQ(c, stmt, s->v.If.body);
1852 } else {
1853 if (s->v.If.orelse) {
1854 next = compiler_new_block(c);
1855 if (next == NULL)
1856 return 0;
1857 }
1858 else
1859 next = end;
1860 VISIT(c, expr, s->v.If.test);
1861 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1862 VISIT_SEQ(c, stmt, s->v.If.body);
1863 ADDOP_JREL(c, JUMP_FORWARD, end);
1864 if (s->v.If.orelse) {
1865 compiler_use_next_block(c, next);
1866 VISIT_SEQ(c, stmt, s->v.If.orelse);
1867 }
1868 }
1869 compiler_use_next_block(c, end);
1870 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871}
1872
1873static int
1874compiler_for(struct compiler *c, stmt_ty s)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 start = compiler_new_block(c);
1879 cleanup = compiler_new_block(c);
1880 end = compiler_new_block(c);
1881 if (start == NULL || end == NULL || cleanup == NULL)
1882 return 0;
1883 ADDOP_JREL(c, SETUP_LOOP, end);
1884 if (!compiler_push_fblock(c, LOOP, start))
1885 return 0;
1886 VISIT(c, expr, s->v.For.iter);
1887 ADDOP(c, GET_ITER);
1888 compiler_use_next_block(c, start);
1889 ADDOP_JREL(c, FOR_ITER, cleanup);
1890 VISIT(c, expr, s->v.For.target);
1891 VISIT_SEQ(c, stmt, s->v.For.body);
1892 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1893 compiler_use_next_block(c, cleanup);
1894 ADDOP(c, POP_BLOCK);
1895 compiler_pop_fblock(c, LOOP, start);
1896 VISIT_SEQ(c, stmt, s->v.For.orelse);
1897 compiler_use_next_block(c, end);
1898 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899}
1900
1901static int
1902compiler_while(struct compiler *c, stmt_ty s)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001905 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 if (constant == 0) {
1908 if (s->v.While.orelse)
1909 VISIT_SEQ(c, stmt, s->v.While.orelse);
1910 return 1;
1911 }
1912 loop = compiler_new_block(c);
1913 end = compiler_new_block(c);
1914 if (constant == -1) {
1915 anchor = compiler_new_block(c);
1916 if (anchor == NULL)
1917 return 0;
1918 }
1919 if (loop == NULL || end == NULL)
1920 return 0;
1921 if (s->v.While.orelse) {
1922 orelse = compiler_new_block(c);
1923 if (orelse == NULL)
1924 return 0;
1925 }
1926 else
1927 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 ADDOP_JREL(c, SETUP_LOOP, end);
1930 compiler_use_next_block(c, loop);
1931 if (!compiler_push_fblock(c, LOOP, loop))
1932 return 0;
1933 if (constant == -1) {
1934 VISIT(c, expr, s->v.While.test);
1935 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1936 }
1937 VISIT_SEQ(c, stmt, s->v.While.body);
1938 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* XXX should the two POP instructions be in a separate block
1941 if there is no else clause ?
1942 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (constant == -1) {
1945 compiler_use_next_block(c, anchor);
1946 ADDOP(c, POP_BLOCK);
1947 }
1948 compiler_pop_fblock(c, LOOP, loop);
1949 if (orelse != NULL) /* what if orelse is just pass? */
1950 VISIT_SEQ(c, stmt, s->v.While.orelse);
1951 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954}
1955
1956static int
1957compiler_continue(struct compiler *c)
1958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1960 static const char IN_FINALLY_ERROR_MSG[] =
1961 "'continue' not supported inside 'finally' clause";
1962 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (!c->u->u_nfblocks)
1965 return compiler_error(c, LOOP_ERROR_MSG);
1966 i = c->u->u_nfblocks - 1;
1967 switch (c->u->u_fblock[i].fb_type) {
1968 case LOOP:
1969 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1970 break;
1971 case EXCEPT:
1972 case FINALLY_TRY:
1973 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1974 /* Prevent continue anywhere under a finally
1975 even if hidden in a sub-try or except. */
1976 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1977 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1978 }
1979 if (i == -1)
1980 return compiler_error(c, LOOP_ERROR_MSG);
1981 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1982 break;
1983 case FINALLY_END:
1984 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1985 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988}
1989
1990/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991
1992 SETUP_FINALLY L
1993 <code for body>
1994 POP_BLOCK
1995 LOAD_CONST <None>
1996 L: <code for finalbody>
1997 END_FINALLY
1998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 The special instructions use the block stack. Each block
2000 stack entry contains the instruction that created it (here
2001 SETUP_FINALLY), the level of the value stack at the time the
2002 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 Pushes the current value stack level and the label
2006 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 Pops en entry from the block stack, and pops the value
2009 stack until its level is the same as indicated on the
2010 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 Pops a variable number of entries from the *value* stack
2013 and re-raises the exception they specify. The number of
2014 entries popped depends on the (pseudo) exception type.
2015
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 The block stack is unwound when an exception is raised:
2017 when a SETUP_FINALLY entry is found, the exception is pushed
2018 onto the value stack (and the exception condition is cleared),
2019 and the interpreter jumps to the label gotten from the block
2020 stack.
2021*/
2022
2023static int
2024compiler_try_finally(struct compiler *c, stmt_ty s)
2025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 basicblock *body, *end;
2027 body = compiler_new_block(c);
2028 end = compiler_new_block(c);
2029 if (body == NULL || end == NULL)
2030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 ADDOP_JREL(c, SETUP_FINALLY, end);
2033 compiler_use_next_block(c, body);
2034 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2035 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002036 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2037 if (!compiler_try_except(c, s))
2038 return 0;
2039 }
2040 else {
2041 VISIT_SEQ(c, stmt, s->v.Try.body);
2042 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 ADDOP(c, POP_BLOCK);
2044 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2047 compiler_use_next_block(c, end);
2048 if (!compiler_push_fblock(c, FINALLY_END, end))
2049 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002050 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 ADDOP(c, END_FINALLY);
2052 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055}
2056
2057/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002058 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 (The contents of the value stack is shown in [], with the top
2060 at the right; 'tb' is trace-back info, 'val' the exception's
2061 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062
2063 Value stack Label Instruction Argument
2064 [] SETUP_EXCEPT L1
2065 [] <code for S>
2066 [] POP_BLOCK
2067 [] JUMP_FORWARD L0
2068
2069 [tb, val, exc] L1: DUP )
2070 [tb, val, exc, exc] <evaluate E1> )
2071 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2072 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2073 [tb, val, exc] POP
2074 [tb, val] <assign to V1> (or POP if no V1)
2075 [tb] POP
2076 [] <code for S1>
2077 JUMP_FORWARD L0
2078
2079 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 .............................etc.......................
2081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2083
2084 [] L0: <next statement>
2085
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 Of course, parts are not generated if Vi or Ei is not present.
2087*/
2088static int
2089compiler_try_except(struct compiler *c, stmt_ty s)
2090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 basicblock *body, *orelse, *except, *end;
2092 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 body = compiler_new_block(c);
2095 except = compiler_new_block(c);
2096 orelse = compiler_new_block(c);
2097 end = compiler_new_block(c);
2098 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2099 return 0;
2100 ADDOP_JREL(c, SETUP_EXCEPT, except);
2101 compiler_use_next_block(c, body);
2102 if (!compiler_push_fblock(c, EXCEPT, body))
2103 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002104 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 ADDOP(c, POP_BLOCK);
2106 compiler_pop_fblock(c, EXCEPT, body);
2107 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002108 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 compiler_use_next_block(c, except);
2110 for (i = 0; i < n; i++) {
2111 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002112 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (!handler->v.ExceptHandler.type && i < n-1)
2114 return compiler_error(c, "default 'except:' must be last");
2115 c->u->u_lineno_set = 0;
2116 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002117 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 except = compiler_new_block(c);
2119 if (except == NULL)
2120 return 0;
2121 if (handler->v.ExceptHandler.type) {
2122 ADDOP(c, DUP_TOP);
2123 VISIT(c, expr, handler->v.ExceptHandler.type);
2124 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2125 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2126 }
2127 ADDOP(c, POP_TOP);
2128 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002129 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002130
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002131 cleanup_end = compiler_new_block(c);
2132 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002133 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002134 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002135
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002136 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2137 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002139 /*
2140 try:
2141 # body
2142 except type as name:
2143 try:
2144 # body
2145 finally:
2146 name = None
2147 del name
2148 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002150 /* second try: */
2151 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2152 compiler_use_next_block(c, cleanup_body);
2153 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2154 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002156 /* second # body */
2157 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2158 ADDOP(c, POP_BLOCK);
2159 ADDOP(c, POP_EXCEPT);
2160 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002162 /* finally: */
2163 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2164 compiler_use_next_block(c, cleanup_end);
2165 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2166 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002168 /* name = None */
2169 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2170 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002172 /* del name */
2173 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002175 ADDOP(c, END_FINALLY);
2176 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 }
2178 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002179 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002181 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002182 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002183 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184
Guido van Rossumb940e112007-01-10 16:19:56 +00002185 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002186 ADDOP(c, POP_TOP);
2187 compiler_use_next_block(c, cleanup_body);
2188 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2189 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002191 ADDOP(c, POP_EXCEPT);
2192 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 }
2194 ADDOP_JREL(c, JUMP_FORWARD, end);
2195 compiler_use_next_block(c, except);
2196 }
2197 ADDOP(c, END_FINALLY);
2198 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002199 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 compiler_use_next_block(c, end);
2201 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202}
2203
2204static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002205compiler_try(struct compiler *c, stmt_ty s) {
2206 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2207 return compiler_try_finally(c, s);
2208 else
2209 return compiler_try_except(c, s);
2210}
2211
2212
2213static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214compiler_import_as(struct compiler *c, identifier name, identifier asname)
2215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* The IMPORT_NAME opcode was already generated. This function
2217 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 If there is a dot in name, we need to split it and emit a
2220 LOAD_ATTR for each name.
2221 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2223 PyUnicode_GET_LENGTH(name), 1);
2224 if (dot == -2)
2225 return -1;
2226 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002228 Py_ssize_t pos = dot + 1;
2229 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002231 dot = PyUnicode_FindChar(name, '.', pos,
2232 PyUnicode_GET_LENGTH(name), 1);
2233 if (dot == -2)
2234 return -1;
2235 attr = PyUnicode_Substring(name, pos,
2236 (dot != -1) ? dot :
2237 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (!attr)
2239 return -1;
2240 ADDOP_O(c, LOAD_ATTR, attr, names);
2241 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 }
2244 }
2245 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246}
2247
2248static int
2249compiler_import(struct compiler *c, stmt_ty s)
2250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* The Import node stores a module name like a.b.c as a single
2252 string. This is convenient for all cases except
2253 import a.b.c as d
2254 where we need to parse that string to extract the individual
2255 module names.
2256 XXX Perhaps change the representation to make this case simpler?
2257 */
2258 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 for (i = 0; i < n; i++) {
2261 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2262 int r;
2263 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 level = PyLong_FromLong(0);
2266 if (level == NULL)
2267 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 ADDOP_O(c, LOAD_CONST, level, consts);
2270 Py_DECREF(level);
2271 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2272 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (alias->asname) {
2275 r = compiler_import_as(c, alias->name, alias->asname);
2276 if (!r)
2277 return r;
2278 }
2279 else {
2280 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281 Py_ssize_t dot = PyUnicode_FindChar(
2282 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2283 if (dot != -1)
2284 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002286 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 Py_DECREF(tmp);
2288 }
2289 if (!r)
2290 return r;
2291 }
2292 }
2293 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294}
2295
2296static int
2297compiler_from_import(struct compiler *c, stmt_ty s)
2298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyObject *names = PyTuple_New(n);
2302 PyObject *level;
2303 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 if (!empty_string) {
2306 empty_string = PyUnicode_FromString("");
2307 if (!empty_string)
2308 return 0;
2309 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (!names)
2312 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 level = PyLong_FromLong(s->v.ImportFrom.level);
2315 if (!level) {
2316 Py_DECREF(names);
2317 return 0;
2318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* build up the names */
2321 for (i = 0; i < n; i++) {
2322 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2323 Py_INCREF(alias->name);
2324 PyTuple_SET_ITEM(names, i, alias->name);
2325 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2328 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2329 Py_DECREF(level);
2330 Py_DECREF(names);
2331 return compiler_error(c, "from __future__ imports must occur "
2332 "at the beginning of the file");
2333 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 ADDOP_O(c, LOAD_CONST, level, consts);
2336 Py_DECREF(level);
2337 ADDOP_O(c, LOAD_CONST, names, consts);
2338 Py_DECREF(names);
2339 if (s->v.ImportFrom.module) {
2340 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2341 }
2342 else {
2343 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2344 }
2345 for (i = 0; i < n; i++) {
2346 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2347 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002349 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 assert(n == 1);
2351 ADDOP(c, IMPORT_STAR);
2352 return 1;
2353 }
2354
2355 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2356 store_name = alias->name;
2357 if (alias->asname)
2358 store_name = alias->asname;
2359
2360 if (!compiler_nameop(c, store_name, Store)) {
2361 Py_DECREF(names);
2362 return 0;
2363 }
2364 }
2365 /* remove imported module */
2366 ADDOP(c, POP_TOP);
2367 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368}
2369
2370static int
2371compiler_assert(struct compiler *c, stmt_ty s)
2372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 static PyObject *assertion_error = NULL;
2374 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375
Georg Brandl8334fd92010-12-04 10:26:46 +00002376 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 return 1;
2378 if (assertion_error == NULL) {
2379 assertion_error = PyUnicode_InternFromString("AssertionError");
2380 if (assertion_error == NULL)
2381 return 0;
2382 }
2383 if (s->v.Assert.test->kind == Tuple_kind &&
2384 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2385 const char* msg =
2386 "assertion is always true, perhaps remove parentheses?";
2387 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2388 c->u->u_lineno, NULL, NULL) == -1)
2389 return 0;
2390 }
2391 VISIT(c, expr, s->v.Assert.test);
2392 end = compiler_new_block(c);
2393 if (end == NULL)
2394 return 0;
2395 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2396 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2397 if (s->v.Assert.msg) {
2398 VISIT(c, expr, s->v.Assert.msg);
2399 ADDOP_I(c, CALL_FUNCTION, 1);
2400 }
2401 ADDOP_I(c, RAISE_VARARGS, 1);
2402 compiler_use_next_block(c, end);
2403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404}
2405
2406static int
2407compiler_visit_stmt(struct compiler *c, stmt_ty s)
2408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* Always assign a lineno to the next instruction for a stmt. */
2412 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002413 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 switch (s->kind) {
2417 case FunctionDef_kind:
2418 return compiler_function(c, s);
2419 case ClassDef_kind:
2420 return compiler_class(c, s);
2421 case Return_kind:
2422 if (c->u->u_ste->ste_type != FunctionBlock)
2423 return compiler_error(c, "'return' outside function");
2424 if (s->v.Return.value) {
2425 VISIT(c, expr, s->v.Return.value);
2426 }
2427 else
2428 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2429 ADDOP(c, RETURN_VALUE);
2430 break;
2431 case Delete_kind:
2432 VISIT_SEQ(c, expr, s->v.Delete.targets)
2433 break;
2434 case Assign_kind:
2435 n = asdl_seq_LEN(s->v.Assign.targets);
2436 VISIT(c, expr, s->v.Assign.value);
2437 for (i = 0; i < n; i++) {
2438 if (i < n - 1)
2439 ADDOP(c, DUP_TOP);
2440 VISIT(c, expr,
2441 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2442 }
2443 break;
2444 case AugAssign_kind:
2445 return compiler_augassign(c, s);
2446 case For_kind:
2447 return compiler_for(c, s);
2448 case While_kind:
2449 return compiler_while(c, s);
2450 case If_kind:
2451 return compiler_if(c, s);
2452 case Raise_kind:
2453 n = 0;
2454 if (s->v.Raise.exc) {
2455 VISIT(c, expr, s->v.Raise.exc);
2456 n++;
2457 if (s->v.Raise.cause) {
2458 VISIT(c, expr, s->v.Raise.cause);
2459 n++;
2460 }
2461 }
2462 ADDOP_I(c, RAISE_VARARGS, n);
2463 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002464 case Try_kind:
2465 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 case Assert_kind:
2467 return compiler_assert(c, s);
2468 case Import_kind:
2469 return compiler_import(c, s);
2470 case ImportFrom_kind:
2471 return compiler_from_import(c, s);
2472 case Global_kind:
2473 case Nonlocal_kind:
2474 break;
2475 case Expr_kind:
2476 if (c->c_interactive && c->c_nestlevel <= 1) {
2477 VISIT(c, expr, s->v.Expr.value);
2478 ADDOP(c, PRINT_EXPR);
2479 }
2480 else if (s->v.Expr.value->kind != Str_kind &&
2481 s->v.Expr.value->kind != Num_kind) {
2482 VISIT(c, expr, s->v.Expr.value);
2483 ADDOP(c, POP_TOP);
2484 }
2485 break;
2486 case Pass_kind:
2487 break;
2488 case Break_kind:
2489 if (!compiler_in_loop(c))
2490 return compiler_error(c, "'break' outside loop");
2491 ADDOP(c, BREAK_LOOP);
2492 break;
2493 case Continue_kind:
2494 return compiler_continue(c);
2495 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002496 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 }
2498 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499}
2500
2501static int
2502unaryop(unaryop_ty op)
2503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 switch (op) {
2505 case Invert:
2506 return UNARY_INVERT;
2507 case Not:
2508 return UNARY_NOT;
2509 case UAdd:
2510 return UNARY_POSITIVE;
2511 case USub:
2512 return UNARY_NEGATIVE;
2513 default:
2514 PyErr_Format(PyExc_SystemError,
2515 "unary op %d should not be possible", op);
2516 return 0;
2517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518}
2519
2520static int
2521binop(struct compiler *c, operator_ty op)
2522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 switch (op) {
2524 case Add:
2525 return BINARY_ADD;
2526 case Sub:
2527 return BINARY_SUBTRACT;
2528 case Mult:
2529 return BINARY_MULTIPLY;
2530 case Div:
2531 return BINARY_TRUE_DIVIDE;
2532 case Mod:
2533 return BINARY_MODULO;
2534 case Pow:
2535 return BINARY_POWER;
2536 case LShift:
2537 return BINARY_LSHIFT;
2538 case RShift:
2539 return BINARY_RSHIFT;
2540 case BitOr:
2541 return BINARY_OR;
2542 case BitXor:
2543 return BINARY_XOR;
2544 case BitAnd:
2545 return BINARY_AND;
2546 case FloorDiv:
2547 return BINARY_FLOOR_DIVIDE;
2548 default:
2549 PyErr_Format(PyExc_SystemError,
2550 "binary op %d should not be possible", op);
2551 return 0;
2552 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553}
2554
2555static int
2556cmpop(cmpop_ty op)
2557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 switch (op) {
2559 case Eq:
2560 return PyCmp_EQ;
2561 case NotEq:
2562 return PyCmp_NE;
2563 case Lt:
2564 return PyCmp_LT;
2565 case LtE:
2566 return PyCmp_LE;
2567 case Gt:
2568 return PyCmp_GT;
2569 case GtE:
2570 return PyCmp_GE;
2571 case Is:
2572 return PyCmp_IS;
2573 case IsNot:
2574 return PyCmp_IS_NOT;
2575 case In:
2576 return PyCmp_IN;
2577 case NotIn:
2578 return PyCmp_NOT_IN;
2579 default:
2580 return PyCmp_BAD;
2581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582}
2583
2584static int
2585inplace_binop(struct compiler *c, operator_ty op)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 switch (op) {
2588 case Add:
2589 return INPLACE_ADD;
2590 case Sub:
2591 return INPLACE_SUBTRACT;
2592 case Mult:
2593 return INPLACE_MULTIPLY;
2594 case Div:
2595 return INPLACE_TRUE_DIVIDE;
2596 case Mod:
2597 return INPLACE_MODULO;
2598 case Pow:
2599 return INPLACE_POWER;
2600 case LShift:
2601 return INPLACE_LSHIFT;
2602 case RShift:
2603 return INPLACE_RSHIFT;
2604 case BitOr:
2605 return INPLACE_OR;
2606 case BitXor:
2607 return INPLACE_XOR;
2608 case BitAnd:
2609 return INPLACE_AND;
2610 case FloorDiv:
2611 return INPLACE_FLOOR_DIVIDE;
2612 default:
2613 PyErr_Format(PyExc_SystemError,
2614 "inplace binary op %d should not be possible", op);
2615 return 0;
2616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617}
2618
2619static int
2620compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 int op, scope, arg;
2623 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 PyObject *dict = c->u->u_names;
2626 PyObject *mangled;
2627 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 mangled = _Py_Mangle(c->u->u_private, name);
2630 if (!mangled)
2631 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 op = 0;
2634 optype = OP_NAME;
2635 scope = PyST_GetScope(c->u->u_ste, mangled);
2636 switch (scope) {
2637 case FREE:
2638 dict = c->u->u_freevars;
2639 optype = OP_DEREF;
2640 break;
2641 case CELL:
2642 dict = c->u->u_cellvars;
2643 optype = OP_DEREF;
2644 break;
2645 case LOCAL:
2646 if (c->u->u_ste->ste_type == FunctionBlock)
2647 optype = OP_FAST;
2648 break;
2649 case GLOBAL_IMPLICIT:
2650 if (c->u->u_ste->ste_type == FunctionBlock &&
2651 !c->u->u_ste->ste_unoptimized)
2652 optype = OP_GLOBAL;
2653 break;
2654 case GLOBAL_EXPLICIT:
2655 optype = OP_GLOBAL;
2656 break;
2657 default:
2658 /* scope can be 0 */
2659 break;
2660 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 switch (optype) {
2666 case OP_DEREF:
2667 switch (ctx) {
2668 case Load: op = LOAD_DEREF; break;
2669 case Store: op = STORE_DEREF; break;
2670 case AugLoad:
2671 case AugStore:
2672 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002673 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 case Param:
2675 default:
2676 PyErr_SetString(PyExc_SystemError,
2677 "param invalid for deref variable");
2678 return 0;
2679 }
2680 break;
2681 case OP_FAST:
2682 switch (ctx) {
2683 case Load: op = LOAD_FAST; break;
2684 case Store: op = STORE_FAST; break;
2685 case Del: op = DELETE_FAST; break;
2686 case AugLoad:
2687 case AugStore:
2688 break;
2689 case Param:
2690 default:
2691 PyErr_SetString(PyExc_SystemError,
2692 "param invalid for local variable");
2693 return 0;
2694 }
2695 ADDOP_O(c, op, mangled, varnames);
2696 Py_DECREF(mangled);
2697 return 1;
2698 case OP_GLOBAL:
2699 switch (ctx) {
2700 case Load: op = LOAD_GLOBAL; break;
2701 case Store: op = STORE_GLOBAL; break;
2702 case Del: op = DELETE_GLOBAL; break;
2703 case AugLoad:
2704 case AugStore:
2705 break;
2706 case Param:
2707 default:
2708 PyErr_SetString(PyExc_SystemError,
2709 "param invalid for global variable");
2710 return 0;
2711 }
2712 break;
2713 case OP_NAME:
2714 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002715 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 case Store: op = STORE_NAME; break;
2717 case Del: op = DELETE_NAME; break;
2718 case AugLoad:
2719 case AugStore:
2720 break;
2721 case Param:
2722 default:
2723 PyErr_SetString(PyExc_SystemError,
2724 "param invalid for name variable");
2725 return 0;
2726 }
2727 break;
2728 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 assert(op);
2731 arg = compiler_add_o(c, dict, mangled);
2732 Py_DECREF(mangled);
2733 if (arg < 0)
2734 return 0;
2735 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736}
2737
2738static int
2739compiler_boolop(struct compiler *c, expr_ty e)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 basicblock *end;
2742 int jumpi, i, n;
2743 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 assert(e->kind == BoolOp_kind);
2746 if (e->v.BoolOp.op == And)
2747 jumpi = JUMP_IF_FALSE_OR_POP;
2748 else
2749 jumpi = JUMP_IF_TRUE_OR_POP;
2750 end = compiler_new_block(c);
2751 if (end == NULL)
2752 return 0;
2753 s = e->v.BoolOp.values;
2754 n = asdl_seq_LEN(s) - 1;
2755 assert(n >= 0);
2756 for (i = 0; i < n; ++i) {
2757 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2758 ADDOP_JABS(c, jumpi, end);
2759 }
2760 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2761 compiler_use_next_block(c, end);
2762 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763}
2764
2765static int
2766compiler_list(struct compiler *c, expr_ty e)
2767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 int n = asdl_seq_LEN(e->v.List.elts);
2769 if (e->v.List.ctx == Store) {
2770 int i, seen_star = 0;
2771 for (i = 0; i < n; i++) {
2772 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2773 if (elt->kind == Starred_kind && !seen_star) {
2774 if ((i >= (1 << 8)) ||
2775 (n-i-1 >= (INT_MAX >> 8)))
2776 return compiler_error(c,
2777 "too many expressions in "
2778 "star-unpacking assignment");
2779 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2780 seen_star = 1;
2781 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2782 } else if (elt->kind == Starred_kind) {
2783 return compiler_error(c,
2784 "two starred expressions in assignment");
2785 }
2786 }
2787 if (!seen_star) {
2788 ADDOP_I(c, UNPACK_SEQUENCE, n);
2789 }
2790 }
2791 VISIT_SEQ(c, expr, e->v.List.elts);
2792 if (e->v.List.ctx == Load) {
2793 ADDOP_I(c, BUILD_LIST, n);
2794 }
2795 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796}
2797
2798static int
2799compiler_tuple(struct compiler *c, expr_ty e)
2800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 int n = asdl_seq_LEN(e->v.Tuple.elts);
2802 if (e->v.Tuple.ctx == Store) {
2803 int i, seen_star = 0;
2804 for (i = 0; i < n; i++) {
2805 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2806 if (elt->kind == Starred_kind && !seen_star) {
2807 if ((i >= (1 << 8)) ||
2808 (n-i-1 >= (INT_MAX >> 8)))
2809 return compiler_error(c,
2810 "too many expressions in "
2811 "star-unpacking assignment");
2812 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2813 seen_star = 1;
2814 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2815 } else if (elt->kind == Starred_kind) {
2816 return compiler_error(c,
2817 "two starred expressions in assignment");
2818 }
2819 }
2820 if (!seen_star) {
2821 ADDOP_I(c, UNPACK_SEQUENCE, n);
2822 }
2823 }
2824 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2825 if (e->v.Tuple.ctx == Load) {
2826 ADDOP_I(c, BUILD_TUPLE, n);
2827 }
2828 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829}
2830
2831static int
2832compiler_compare(struct compiler *c, expr_ty e)
2833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 int i, n;
2835 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2838 VISIT(c, expr, e->v.Compare.left);
2839 n = asdl_seq_LEN(e->v.Compare.ops);
2840 assert(n > 0);
2841 if (n > 1) {
2842 cleanup = compiler_new_block(c);
2843 if (cleanup == NULL)
2844 return 0;
2845 VISIT(c, expr,
2846 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2847 }
2848 for (i = 1; i < n; i++) {
2849 ADDOP(c, DUP_TOP);
2850 ADDOP(c, ROT_THREE);
2851 ADDOP_I(c, COMPARE_OP,
2852 cmpop((cmpop_ty)(asdl_seq_GET(
2853 e->v.Compare.ops, i - 1))));
2854 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2855 NEXT_BLOCK(c);
2856 if (i < (n - 1))
2857 VISIT(c, expr,
2858 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2859 }
2860 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2861 ADDOP_I(c, COMPARE_OP,
2862 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2863 if (n > 1) {
2864 basicblock *end = compiler_new_block(c);
2865 if (end == NULL)
2866 return 0;
2867 ADDOP_JREL(c, JUMP_FORWARD, end);
2868 compiler_use_next_block(c, cleanup);
2869 ADDOP(c, ROT_TWO);
2870 ADDOP(c, POP_TOP);
2871 compiler_use_next_block(c, end);
2872 }
2873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874}
2875
2876static int
2877compiler_call(struct compiler *c, expr_ty e)
2878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 VISIT(c, expr, e->v.Call.func);
2880 return compiler_call_helper(c, 0,
2881 e->v.Call.args,
2882 e->v.Call.keywords,
2883 e->v.Call.starargs,
2884 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002885}
2886
2887/* shared code between compiler_call and compiler_class */
2888static int
2889compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 int n, /* Args already pushed */
2891 asdl_seq *args,
2892 asdl_seq *keywords,
2893 expr_ty starargs,
2894 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 n += asdl_seq_LEN(args);
2899 VISIT_SEQ(c, expr, args);
2900 if (keywords) {
2901 VISIT_SEQ(c, keyword, keywords);
2902 n |= asdl_seq_LEN(keywords) << 8;
2903 }
2904 if (starargs) {
2905 VISIT(c, expr, starargs);
2906 code |= 1;
2907 }
2908 if (kwargs) {
2909 VISIT(c, expr, kwargs);
2910 code |= 2;
2911 }
2912 switch (code) {
2913 case 0:
2914 ADDOP_I(c, CALL_FUNCTION, n);
2915 break;
2916 case 1:
2917 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2918 break;
2919 case 2:
2920 ADDOP_I(c, CALL_FUNCTION_KW, n);
2921 break;
2922 case 3:
2923 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2924 break;
2925 }
2926 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927}
2928
Nick Coghlan650f0d02007-04-15 12:05:43 +00002929
2930/* List and set comprehensions and generator expressions work by creating a
2931 nested function to perform the actual iteration. This means that the
2932 iteration variables don't leak into the current scope.
2933 The defined function is called immediately following its definition, with the
2934 result of that call being the result of the expression.
2935 The LC/SC version returns the populated container, while the GE version is
2936 flagged in symtable.c as a generator, so it returns the generator object
2937 when the function is called.
2938 This code *knows* that the loop cannot contain break, continue, or return,
2939 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2940
2941 Possible cleanups:
2942 - iterate over the generator sequence instead of using recursion
2943*/
2944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946compiler_comprehension_generator(struct compiler *c,
2947 asdl_seq *generators, int gen_index,
2948 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 /* generate code for the iterator, then each of the ifs,
2951 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 comprehension_ty gen;
2954 basicblock *start, *anchor, *skip, *if_cleanup;
2955 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 start = compiler_new_block(c);
2958 skip = compiler_new_block(c);
2959 if_cleanup = compiler_new_block(c);
2960 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2963 anchor == NULL)
2964 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 if (gen_index == 0) {
2969 /* Receive outermost iter as an implicit argument */
2970 c->u->u_argcount = 1;
2971 ADDOP_I(c, LOAD_FAST, 0);
2972 }
2973 else {
2974 /* Sub-iter - calculate on the fly */
2975 VISIT(c, expr, gen->iter);
2976 ADDOP(c, GET_ITER);
2977 }
2978 compiler_use_next_block(c, start);
2979 ADDOP_JREL(c, FOR_ITER, anchor);
2980 NEXT_BLOCK(c);
2981 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 /* XXX this needs to be cleaned up...a lot! */
2984 n = asdl_seq_LEN(gen->ifs);
2985 for (i = 0; i < n; i++) {
2986 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2987 VISIT(c, expr, e);
2988 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2989 NEXT_BLOCK(c);
2990 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 if (++gen_index < asdl_seq_LEN(generators))
2993 if (!compiler_comprehension_generator(c,
2994 generators, gen_index,
2995 elt, val, type))
2996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 /* only append after the last for generator */
2999 if (gen_index >= asdl_seq_LEN(generators)) {
3000 /* comprehension specific code */
3001 switch (type) {
3002 case COMP_GENEXP:
3003 VISIT(c, expr, elt);
3004 ADDOP(c, YIELD_VALUE);
3005 ADDOP(c, POP_TOP);
3006 break;
3007 case COMP_LISTCOMP:
3008 VISIT(c, expr, elt);
3009 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3010 break;
3011 case COMP_SETCOMP:
3012 VISIT(c, expr, elt);
3013 ADDOP_I(c, SET_ADD, gen_index + 1);
3014 break;
3015 case COMP_DICTCOMP:
3016 /* With 'd[k] = v', v is evaluated before k, so we do
3017 the same. */
3018 VISIT(c, expr, val);
3019 VISIT(c, expr, elt);
3020 ADDOP_I(c, MAP_ADD, gen_index + 1);
3021 break;
3022 default:
3023 return 0;
3024 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 compiler_use_next_block(c, skip);
3027 }
3028 compiler_use_next_block(c, if_cleanup);
3029 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3030 compiler_use_next_block(c, anchor);
3031
3032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033}
3034
3035static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003036compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 PyCodeObject *co = NULL;
3040 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003041 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 outermost_iter = ((comprehension_ty)
3044 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003045
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003046 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3047 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 if (type != COMP_GENEXP) {
3051 int op;
3052 switch (type) {
3053 case COMP_LISTCOMP:
3054 op = BUILD_LIST;
3055 break;
3056 case COMP_SETCOMP:
3057 op = BUILD_SET;
3058 break;
3059 case COMP_DICTCOMP:
3060 op = BUILD_MAP;
3061 break;
3062 default:
3063 PyErr_Format(PyExc_SystemError,
3064 "unknown comprehension type %d", type);
3065 goto error_in_scope;
3066 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 ADDOP_I(c, op, 0);
3069 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 if (!compiler_comprehension_generator(c, generators, 0, elt,
3072 val, type))
3073 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (type != COMP_GENEXP) {
3076 ADDOP(c, RETURN_VALUE);
3077 }
3078
3079 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003080 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003082 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 goto error;
3084
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003085 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003087 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 Py_DECREF(co);
3089
3090 VISIT(c, expr, outermost_iter);
3091 ADDOP(c, GET_ITER);
3092 ADDOP_I(c, CALL_FUNCTION, 1);
3093 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003094error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003096error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003097 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 Py_XDECREF(co);
3099 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003100}
3101
3102static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103compiler_genexp(struct compiler *c, expr_ty e)
3104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 static identifier name;
3106 if (!name) {
3107 name = PyUnicode_FromString("<genexpr>");
3108 if (!name)
3109 return 0;
3110 }
3111 assert(e->kind == GeneratorExp_kind);
3112 return compiler_comprehension(c, e, COMP_GENEXP, name,
3113 e->v.GeneratorExp.generators,
3114 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115}
3116
3117static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003118compiler_listcomp(struct compiler *c, expr_ty e)
3119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 static identifier name;
3121 if (!name) {
3122 name = PyUnicode_FromString("<listcomp>");
3123 if (!name)
3124 return 0;
3125 }
3126 assert(e->kind == ListComp_kind);
3127 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3128 e->v.ListComp.generators,
3129 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003130}
3131
3132static int
3133compiler_setcomp(struct compiler *c, expr_ty e)
3134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 static identifier name;
3136 if (!name) {
3137 name = PyUnicode_FromString("<setcomp>");
3138 if (!name)
3139 return 0;
3140 }
3141 assert(e->kind == SetComp_kind);
3142 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3143 e->v.SetComp.generators,
3144 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003145}
3146
3147
3148static int
3149compiler_dictcomp(struct compiler *c, expr_ty e)
3150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 static identifier name;
3152 if (!name) {
3153 name = PyUnicode_FromString("<dictcomp>");
3154 if (!name)
3155 return 0;
3156 }
3157 assert(e->kind == DictComp_kind);
3158 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3159 e->v.DictComp.generators,
3160 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003161}
3162
3163
3164static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165compiler_visit_keyword(struct compiler *c, keyword_ty k)
3166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3168 VISIT(c, expr, k->value);
3169 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170}
3171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 whether they are true or false.
3174
3175 Return values: 1 for true, 0 for false, -1 for non-constant.
3176 */
3177
3178static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003179expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 char *id;
3182 switch (e->kind) {
3183 case Ellipsis_kind:
3184 return 1;
3185 case Num_kind:
3186 return PyObject_IsTrue(e->v.Num.n);
3187 case Str_kind:
3188 return PyObject_IsTrue(e->v.Str.s);
3189 case Name_kind:
3190 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003191 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 if (strcmp(id, "True") == 0) return 1;
3193 if (strcmp(id, "False") == 0) return 0;
3194 if (strcmp(id, "None") == 0) return 0;
3195 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003196 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 /* fall through */
3198 default:
3199 return -1;
3200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201}
3202
Guido van Rossumc2e20742006-02-27 22:32:47 +00003203/*
3204 Implements the with statement from PEP 343.
3205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003207
3208 with EXPR as VAR:
3209 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210
Guido van Rossumc2e20742006-02-27 22:32:47 +00003211 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212
Thomas Wouters477c8d52006-05-27 19:21:47 +00003213 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003214 exit = context.__exit__ # not calling it
3215 value = context.__enter__()
3216 try:
3217 VAR = value # if VAR present in the syntax
3218 BLOCK
3219 finally:
3220 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003222 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003224 exit(*exc)
3225 */
3226static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003227compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003228{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003229 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003230 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003231
3232 assert(s->kind == With_kind);
3233
Guido van Rossumc2e20742006-02-27 22:32:47 +00003234 block = compiler_new_block(c);
3235 finally = compiler_new_block(c);
3236 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003237 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003238
Thomas Wouters477c8d52006-05-27 19:21:47 +00003239 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003240 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003241 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003242
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003243 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003244 compiler_use_next_block(c, block);
3245 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003246 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003247 }
3248
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003249 if (item->optional_vars) {
3250 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003251 }
3252 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003254 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003255 }
3256
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003257 pos++;
3258 if (pos == asdl_seq_LEN(s->v.With.items))
3259 /* BLOCK code */
3260 VISIT_SEQ(c, stmt, s->v.With.body)
3261 else if (!compiler_with(c, s, pos))
3262 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003263
3264 /* End of try block; start the finally block */
3265 ADDOP(c, POP_BLOCK);
3266 compiler_pop_fblock(c, FINALLY_TRY, block);
3267
3268 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3269 compiler_use_next_block(c, finally);
3270 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003271 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003272
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003273 /* Finally block starts; context.__exit__ is on the stack under
3274 the exception or return information. Just issue our magic
3275 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003276 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003277
3278 /* Finally block ends. */
3279 ADDOP(c, END_FINALLY);
3280 compiler_pop_fblock(c, FINALLY_END, finally);
3281 return 1;
3282}
3283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284static int
3285compiler_visit_expr(struct compiler *c, expr_ty e)
3286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 /* If expr e has a different line number than the last expr/stmt,
3290 set a new line number for the next instruction.
3291 */
3292 if (e->lineno > c->u->u_lineno) {
3293 c->u->u_lineno = e->lineno;
3294 c->u->u_lineno_set = 0;
3295 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003296 /* Updating the column offset is always harmless. */
3297 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 switch (e->kind) {
3299 case BoolOp_kind:
3300 return compiler_boolop(c, e);
3301 case BinOp_kind:
3302 VISIT(c, expr, e->v.BinOp.left);
3303 VISIT(c, expr, e->v.BinOp.right);
3304 ADDOP(c, binop(c, e->v.BinOp.op));
3305 break;
3306 case UnaryOp_kind:
3307 VISIT(c, expr, e->v.UnaryOp.operand);
3308 ADDOP(c, unaryop(e->v.UnaryOp.op));
3309 break;
3310 case Lambda_kind:
3311 return compiler_lambda(c, e);
3312 case IfExp_kind:
3313 return compiler_ifexp(c, e);
3314 case Dict_kind:
3315 n = asdl_seq_LEN(e->v.Dict.values);
3316 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3317 for (i = 0; i < n; i++) {
3318 VISIT(c, expr,
3319 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3320 VISIT(c, expr,
3321 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3322 ADDOP(c, STORE_MAP);
3323 }
3324 break;
3325 case Set_kind:
3326 n = asdl_seq_LEN(e->v.Set.elts);
3327 VISIT_SEQ(c, expr, e->v.Set.elts);
3328 ADDOP_I(c, BUILD_SET, n);
3329 break;
3330 case GeneratorExp_kind:
3331 return compiler_genexp(c, e);
3332 case ListComp_kind:
3333 return compiler_listcomp(c, e);
3334 case SetComp_kind:
3335 return compiler_setcomp(c, e);
3336 case DictComp_kind:
3337 return compiler_dictcomp(c, e);
3338 case Yield_kind:
Benjamin Peterson527c6222012-01-14 08:58:23 -05003339 case YieldFrom_kind: {
3340 expr_ty value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 if (c->u->u_ste->ste_type != FunctionBlock)
3342 return compiler_error(c, "'yield' outside function");
Benjamin Peterson527c6222012-01-14 08:58:23 -05003343 value = (e->kind == YieldFrom_kind) ? e->v.YieldFrom.value : e->v.Yield.value;
3344 if (value) {
3345 VISIT(c, expr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 }
3347 else {
3348 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3349 }
Benjamin Peterson527c6222012-01-14 08:58:23 -05003350 if (e->kind == YieldFrom_kind) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05003351 ADDOP(c, GET_ITER);
3352 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Nick Coghlan1f7ce622012-01-13 21:43:40 +10003353 ADDOP(c, YIELD_FROM);
3354 }
3355 else {
3356 ADDOP(c, YIELD_VALUE);
3357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 break;
Benjamin Peterson527c6222012-01-14 08:58:23 -05003359 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 case Compare_kind:
3361 return compiler_compare(c, e);
3362 case Call_kind:
3363 return compiler_call(c, e);
3364 case Num_kind:
3365 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3366 break;
3367 case Str_kind:
3368 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3369 break;
3370 case Bytes_kind:
3371 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3372 break;
3373 case Ellipsis_kind:
3374 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3375 break;
3376 /* The following exprs can be assignment targets. */
3377 case Attribute_kind:
3378 if (e->v.Attribute.ctx != AugStore)
3379 VISIT(c, expr, e->v.Attribute.value);
3380 switch (e->v.Attribute.ctx) {
3381 case AugLoad:
3382 ADDOP(c, DUP_TOP);
3383 /* Fall through to load */
3384 case Load:
3385 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3386 break;
3387 case AugStore:
3388 ADDOP(c, ROT_TWO);
3389 /* Fall through to save */
3390 case Store:
3391 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3392 break;
3393 case Del:
3394 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3395 break;
3396 case Param:
3397 default:
3398 PyErr_SetString(PyExc_SystemError,
3399 "param invalid in attribute expression");
3400 return 0;
3401 }
3402 break;
3403 case Subscript_kind:
3404 switch (e->v.Subscript.ctx) {
3405 case AugLoad:
3406 VISIT(c, expr, e->v.Subscript.value);
3407 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3408 break;
3409 case Load:
3410 VISIT(c, expr, e->v.Subscript.value);
3411 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3412 break;
3413 case AugStore:
3414 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3415 break;
3416 case Store:
3417 VISIT(c, expr, e->v.Subscript.value);
3418 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3419 break;
3420 case Del:
3421 VISIT(c, expr, e->v.Subscript.value);
3422 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3423 break;
3424 case Param:
3425 default:
3426 PyErr_SetString(PyExc_SystemError,
3427 "param invalid in subscript expression");
3428 return 0;
3429 }
3430 break;
3431 case Starred_kind:
3432 switch (e->v.Starred.ctx) {
3433 case Store:
3434 /* In all legitimate cases, the Starred node was already replaced
3435 * by compiler_list/compiler_tuple. XXX: is that okay? */
3436 return compiler_error(c,
3437 "starred assignment target must be in a list or tuple");
3438 default:
3439 return compiler_error(c,
3440 "can use starred expression only as assignment target");
3441 }
3442 break;
3443 case Name_kind:
3444 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3445 /* child nodes of List and Tuple will have expr_context set */
3446 case List_kind:
3447 return compiler_list(c, e);
3448 case Tuple_kind:
3449 return compiler_tuple(c, e);
3450 }
3451 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452}
3453
3454static int
3455compiler_augassign(struct compiler *c, stmt_ty s)
3456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 expr_ty e = s->v.AugAssign.target;
3458 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 switch (e->kind) {
3463 case Attribute_kind:
3464 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3465 AugLoad, e->lineno, e->col_offset, c->c_arena);
3466 if (auge == NULL)
3467 return 0;
3468 VISIT(c, expr, auge);
3469 VISIT(c, expr, s->v.AugAssign.value);
3470 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3471 auge->v.Attribute.ctx = AugStore;
3472 VISIT(c, expr, auge);
3473 break;
3474 case Subscript_kind:
3475 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3476 AugLoad, e->lineno, e->col_offset, c->c_arena);
3477 if (auge == NULL)
3478 return 0;
3479 VISIT(c, expr, auge);
3480 VISIT(c, expr, s->v.AugAssign.value);
3481 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3482 auge->v.Subscript.ctx = AugStore;
3483 VISIT(c, expr, auge);
3484 break;
3485 case Name_kind:
3486 if (!compiler_nameop(c, e->v.Name.id, Load))
3487 return 0;
3488 VISIT(c, expr, s->v.AugAssign.value);
3489 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3490 return compiler_nameop(c, e->v.Name.id, Store);
3491 default:
3492 PyErr_Format(PyExc_SystemError,
3493 "invalid node type (%d) for augmented assignment",
3494 e->kind);
3495 return 0;
3496 }
3497 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498}
3499
3500static int
3501compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 struct fblockinfo *f;
3504 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3505 PyErr_SetString(PyExc_SystemError,
3506 "too many statically nested blocks");
3507 return 0;
3508 }
3509 f = &c->u->u_fblock[c->u->u_nfblocks++];
3510 f->fb_type = t;
3511 f->fb_block = b;
3512 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513}
3514
3515static void
3516compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 struct compiler_unit *u = c->u;
3519 assert(u->u_nfblocks > 0);
3520 u->u_nfblocks--;
3521 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3522 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523}
3524
Thomas Wouters89f507f2006-12-13 04:49:30 +00003525static int
3526compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 int i;
3528 struct compiler_unit *u = c->u;
3529 for (i = 0; i < u->u_nfblocks; ++i) {
3530 if (u->u_fblock[i].fb_type == LOOP)
3531 return 1;
3532 }
3533 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003534}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535/* Raises a SyntaxError and returns 0.
3536 If something goes wrong, a different exception may be raised.
3537*/
3538
3539static int
3540compiler_error(struct compiler *c, const char *errstr)
3541{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003542 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3546 if (!loc) {
3547 Py_INCREF(Py_None);
3548 loc = Py_None;
3549 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003550 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003551 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 if (!u)
3553 goto exit;
3554 v = Py_BuildValue("(zO)", errstr, u);
3555 if (!v)
3556 goto exit;
3557 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 Py_DECREF(loc);
3560 Py_XDECREF(u);
3561 Py_XDECREF(v);
3562 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563}
3564
3565static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566compiler_handle_subscr(struct compiler *c, const char *kind,
3567 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 /* XXX this code is duplicated */
3572 switch (ctx) {
3573 case AugLoad: /* fall through to Load */
3574 case Load: op = BINARY_SUBSCR; break;
3575 case AugStore:/* fall through to Store */
3576 case Store: op = STORE_SUBSCR; break;
3577 case Del: op = DELETE_SUBSCR; break;
3578 case Param:
3579 PyErr_Format(PyExc_SystemError,
3580 "invalid %s kind %d in subscript\n",
3581 kind, ctx);
3582 return 0;
3583 }
3584 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003585 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 }
3587 else if (ctx == AugStore) {
3588 ADDOP(c, ROT_THREE);
3589 }
3590 ADDOP(c, op);
3591 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592}
3593
3594static int
3595compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 int n = 2;
3598 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 /* only handles the cases where BUILD_SLICE is emitted */
3601 if (s->v.Slice.lower) {
3602 VISIT(c, expr, s->v.Slice.lower);
3603 }
3604 else {
3605 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 if (s->v.Slice.upper) {
3609 VISIT(c, expr, s->v.Slice.upper);
3610 }
3611 else {
3612 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3613 }
3614
3615 if (s->v.Slice.step) {
3616 n++;
3617 VISIT(c, expr, s->v.Slice.step);
3618 }
3619 ADDOP_I(c, BUILD_SLICE, n);
3620 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621}
3622
3623static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3625 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 switch (s->kind) {
3628 case Slice_kind:
3629 return compiler_slice(c, s, ctx);
3630 case Index_kind:
3631 VISIT(c, expr, s->v.Index.value);
3632 break;
3633 case ExtSlice_kind:
3634 default:
3635 PyErr_SetString(PyExc_SystemError,
3636 "extended slice invalid in nested slice");
3637 return 0;
3638 }
3639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640}
3641
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642static int
3643compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 char * kindname = NULL;
3646 switch (s->kind) {
3647 case Index_kind:
3648 kindname = "index";
3649 if (ctx != AugStore) {
3650 VISIT(c, expr, s->v.Index.value);
3651 }
3652 break;
3653 case Slice_kind:
3654 kindname = "slice";
3655 if (ctx != AugStore) {
3656 if (!compiler_slice(c, s, ctx))
3657 return 0;
3658 }
3659 break;
3660 case ExtSlice_kind:
3661 kindname = "extended slice";
3662 if (ctx != AugStore) {
3663 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3664 for (i = 0; i < n; i++) {
3665 slice_ty sub = (slice_ty)asdl_seq_GET(
3666 s->v.ExtSlice.dims, i);
3667 if (!compiler_visit_nested_slice(c, sub, ctx))
3668 return 0;
3669 }
3670 ADDOP_I(c, BUILD_TUPLE, n);
3671 }
3672 break;
3673 default:
3674 PyErr_Format(PyExc_SystemError,
3675 "invalid subscript kind %d", s->kind);
3676 return 0;
3677 }
3678 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679}
3680
Thomas Wouters89f507f2006-12-13 04:49:30 +00003681/* End of the compiler section, beginning of the assembler section */
3682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683/* do depth-first search of basic block graph, starting with block.
3684 post records the block indices in post-order.
3685
3686 XXX must handle implicit jumps from one block to next
3687*/
3688
Thomas Wouters89f507f2006-12-13 04:49:30 +00003689struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 PyObject *a_bytecode; /* string containing bytecode */
3691 int a_offset; /* offset into bytecode */
3692 int a_nblocks; /* number of reachable blocks */
3693 basicblock **a_postorder; /* list of blocks in dfs postorder */
3694 PyObject *a_lnotab; /* string containing lnotab */
3695 int a_lnotab_off; /* offset into lnotab */
3696 int a_lineno; /* last lineno of emitted instruction */
3697 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003698};
3699
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700static void
3701dfs(struct compiler *c, basicblock *b, struct assembler *a)
3702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 int i;
3704 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 if (b->b_seen)
3707 return;
3708 b->b_seen = 1;
3709 if (b->b_next != NULL)
3710 dfs(c, b->b_next, a);
3711 for (i = 0; i < b->b_iused; i++) {
3712 instr = &b->b_instr[i];
3713 if (instr->i_jrel || instr->i_jabs)
3714 dfs(c, instr->i_target, a);
3715 }
3716 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717}
3718
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003719static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 int i, target_depth;
3723 struct instr *instr;
3724 if (b->b_seen || b->b_startdepth >= depth)
3725 return maxdepth;
3726 b->b_seen = 1;
3727 b->b_startdepth = depth;
3728 for (i = 0; i < b->b_iused; i++) {
3729 instr = &b->b_instr[i];
3730 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3731 if (depth > maxdepth)
3732 maxdepth = depth;
3733 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3734 if (instr->i_jrel || instr->i_jabs) {
3735 target_depth = depth;
3736 if (instr->i_opcode == FOR_ITER) {
3737 target_depth = depth-2;
3738 } else if (instr->i_opcode == SETUP_FINALLY ||
3739 instr->i_opcode == SETUP_EXCEPT) {
3740 target_depth = depth+3;
3741 if (target_depth > maxdepth)
3742 maxdepth = target_depth;
3743 }
3744 maxdepth = stackdepth_walk(c, instr->i_target,
3745 target_depth, maxdepth);
3746 if (instr->i_opcode == JUMP_ABSOLUTE ||
3747 instr->i_opcode == JUMP_FORWARD) {
3748 goto out; /* remaining code is dead */
3749 }
3750 }
3751 }
3752 if (b->b_next)
3753 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 b->b_seen = 0;
3756 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757}
3758
3759/* Find the flow path that needs the largest stack. We assume that
3760 * cycles in the flow graph have no net effect on the stack depth.
3761 */
3762static int
3763stackdepth(struct compiler *c)
3764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 basicblock *b, *entryblock;
3766 entryblock = NULL;
3767 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3768 b->b_seen = 0;
3769 b->b_startdepth = INT_MIN;
3770 entryblock = b;
3771 }
3772 if (!entryblock)
3773 return 0;
3774 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775}
3776
3777static int
3778assemble_init(struct assembler *a, int nblocks, int firstlineno)
3779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 memset(a, 0, sizeof(struct assembler));
3781 a->a_lineno = firstlineno;
3782 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3783 if (!a->a_bytecode)
3784 return 0;
3785 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3786 if (!a->a_lnotab)
3787 return 0;
3788 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3789 PyErr_NoMemory();
3790 return 0;
3791 }
3792 a->a_postorder = (basicblock **)PyObject_Malloc(
3793 sizeof(basicblock *) * nblocks);
3794 if (!a->a_postorder) {
3795 PyErr_NoMemory();
3796 return 0;
3797 }
3798 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799}
3800
3801static void
3802assemble_free(struct assembler *a)
3803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 Py_XDECREF(a->a_bytecode);
3805 Py_XDECREF(a->a_lnotab);
3806 if (a->a_postorder)
3807 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808}
3809
3810/* Return the size of a basic block in bytes. */
3811
3812static int
3813instrsize(struct instr *instr)
3814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 if (!instr->i_hasarg)
3816 return 1; /* 1 byte for the opcode*/
3817 if (instr->i_oparg > 0xffff)
3818 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3819 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820}
3821
3822static int
3823blocksize(basicblock *b)
3824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 int i;
3826 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 for (i = 0; i < b->b_iused; i++)
3829 size += instrsize(&b->b_instr[i]);
3830 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003831}
3832
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003833/* Appends a pair to the end of the line number table, a_lnotab, representing
3834 the instruction's bytecode offset and line number. See
3835 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003836
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003837static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 int d_bytecode, d_lineno;
3841 int len;
3842 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 d_bytecode = a->a_offset - a->a_lineno_off;
3845 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 assert(d_bytecode >= 0);
3848 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if(d_bytecode == 0 && d_lineno == 0)
3851 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 if (d_bytecode > 255) {
3854 int j, nbytes, ncodes = d_bytecode / 255;
3855 nbytes = a->a_lnotab_off + 2 * ncodes;
3856 len = PyBytes_GET_SIZE(a->a_lnotab);
3857 if (nbytes >= len) {
3858 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3859 len = nbytes;
3860 else if (len <= INT_MAX / 2)
3861 len *= 2;
3862 else {
3863 PyErr_NoMemory();
3864 return 0;
3865 }
3866 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3867 return 0;
3868 }
3869 lnotab = (unsigned char *)
3870 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3871 for (j = 0; j < ncodes; j++) {
3872 *lnotab++ = 255;
3873 *lnotab++ = 0;
3874 }
3875 d_bytecode -= ncodes * 255;
3876 a->a_lnotab_off += ncodes * 2;
3877 }
3878 assert(d_bytecode <= 255);
3879 if (d_lineno > 255) {
3880 int j, nbytes, ncodes = d_lineno / 255;
3881 nbytes = a->a_lnotab_off + 2 * ncodes;
3882 len = PyBytes_GET_SIZE(a->a_lnotab);
3883 if (nbytes >= len) {
3884 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3885 len = nbytes;
3886 else if (len <= INT_MAX / 2)
3887 len *= 2;
3888 else {
3889 PyErr_NoMemory();
3890 return 0;
3891 }
3892 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3893 return 0;
3894 }
3895 lnotab = (unsigned char *)
3896 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3897 *lnotab++ = d_bytecode;
3898 *lnotab++ = 255;
3899 d_bytecode = 0;
3900 for (j = 1; j < ncodes; j++) {
3901 *lnotab++ = 0;
3902 *lnotab++ = 255;
3903 }
3904 d_lineno -= ncodes * 255;
3905 a->a_lnotab_off += ncodes * 2;
3906 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 len = PyBytes_GET_SIZE(a->a_lnotab);
3909 if (a->a_lnotab_off + 2 >= len) {
3910 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3911 return 0;
3912 }
3913 lnotab = (unsigned char *)
3914 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 a->a_lnotab_off += 2;
3917 if (d_bytecode) {
3918 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003919 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 }
3921 else { /* First line of a block; def stmt, etc. */
3922 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003923 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 }
3925 a->a_lineno = i->i_lineno;
3926 a->a_lineno_off = a->a_offset;
3927 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003928}
3929
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930/* assemble_emit()
3931 Extend the bytecode with a new instruction.
3932 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003933*/
3934
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003935static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 int size, arg = 0, ext = 0;
3939 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3940 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 size = instrsize(i);
3943 if (i->i_hasarg) {
3944 arg = i->i_oparg;
3945 ext = arg >> 16;
3946 }
3947 if (i->i_lineno && !assemble_lnotab(a, i))
3948 return 0;
3949 if (a->a_offset + size >= len) {
3950 if (len > PY_SSIZE_T_MAX / 2)
3951 return 0;
3952 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3953 return 0;
3954 }
3955 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3956 a->a_offset += size;
3957 if (size == 6) {
3958 assert(i->i_hasarg);
3959 *code++ = (char)EXTENDED_ARG;
3960 *code++ = ext & 0xff;
3961 *code++ = ext >> 8;
3962 arg &= 0xffff;
3963 }
3964 *code++ = i->i_opcode;
3965 if (i->i_hasarg) {
3966 assert(size == 3 || size == 6);
3967 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003968 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 }
3970 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003971}
3972
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003973static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003974assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 basicblock *b;
3977 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3978 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 /* Compute the size of each block and fixup jump args.
3981 Replace block pointer with position in bytecode. */
3982 do {
3983 totsize = 0;
3984 for (i = a->a_nblocks - 1; i >= 0; i--) {
3985 b = a->a_postorder[i];
3986 bsize = blocksize(b);
3987 b->b_offset = totsize;
3988 totsize += bsize;
3989 }
3990 last_extended_arg_count = extended_arg_count;
3991 extended_arg_count = 0;
3992 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3993 bsize = b->b_offset;
3994 for (i = 0; i < b->b_iused; i++) {
3995 struct instr *instr = &b->b_instr[i];
3996 /* Relative jumps are computed relative to
3997 the instruction pointer after fetching
3998 the jump instruction.
3999 */
4000 bsize += instrsize(instr);
4001 if (instr->i_jabs)
4002 instr->i_oparg = instr->i_target->b_offset;
4003 else if (instr->i_jrel) {
4004 int delta = instr->i_target->b_offset - bsize;
4005 instr->i_oparg = delta;
4006 }
4007 else
4008 continue;
4009 if (instr->i_oparg > 0xffff)
4010 extended_arg_count++;
4011 }
4012 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 /* XXX: This is an awful hack that could hurt performance, but
4015 on the bright side it should work until we come up
4016 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 The issue is that in the first loop blocksize() is called
4019 which calls instrsize() which requires i_oparg be set
4020 appropriately. There is a bootstrap problem because
4021 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 So we loop until we stop seeing new EXTENDED_ARGs.
4024 The only EXTENDED_ARGs that could be popping up are
4025 ones in jump instructions. So this should converge
4026 fairly quickly.
4027 */
4028 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004029}
4030
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004031static PyObject *
4032dict_keys_inorder(PyObject *dict, int offset)
4033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 PyObject *tuple, *k, *v;
4035 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 tuple = PyTuple_New(size);
4038 if (tuple == NULL)
4039 return NULL;
4040 while (PyDict_Next(dict, &pos, &k, &v)) {
4041 i = PyLong_AS_LONG(v);
4042 /* The keys of the dictionary are tuples. (see compiler_add_o)
4043 The object we want is always first, though. */
4044 k = PyTuple_GET_ITEM(k, 0);
4045 Py_INCREF(k);
4046 assert((i - offset) < size);
4047 assert((i - offset) >= 0);
4048 PyTuple_SET_ITEM(tuple, i - offset, k);
4049 }
4050 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004051}
4052
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004053static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004054compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 PySTEntryObject *ste = c->u->u_ste;
4057 int flags = 0, n;
4058 if (ste->ste_type != ModuleBlock)
4059 flags |= CO_NEWLOCALS;
4060 if (ste->ste_type == FunctionBlock) {
4061 if (!ste->ste_unoptimized)
4062 flags |= CO_OPTIMIZED;
4063 if (ste->ste_nested)
4064 flags |= CO_NESTED;
4065 if (ste->ste_generator)
4066 flags |= CO_GENERATOR;
4067 if (ste->ste_varargs)
4068 flags |= CO_VARARGS;
4069 if (ste->ste_varkeywords)
4070 flags |= CO_VARKEYWORDS;
4071 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 /* (Only) inherit compilerflags in PyCF_MASK */
4074 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 n = PyDict_Size(c->u->u_freevars);
4077 if (n < 0)
4078 return -1;
4079 if (n == 0) {
4080 n = PyDict_Size(c->u->u_cellvars);
4081 if (n < 0)
4082 return -1;
4083 if (n == 0) {
4084 flags |= CO_NOFREE;
4085 }
4086 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004089}
4090
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004091static PyCodeObject *
4092makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 PyObject *tmp;
4095 PyCodeObject *co = NULL;
4096 PyObject *consts = NULL;
4097 PyObject *names = NULL;
4098 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 PyObject *name = NULL;
4100 PyObject *freevars = NULL;
4101 PyObject *cellvars = NULL;
4102 PyObject *bytecode = NULL;
4103 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 tmp = dict_keys_inorder(c->u->u_consts, 0);
4106 if (!tmp)
4107 goto error;
4108 consts = PySequence_List(tmp); /* optimize_code requires a list */
4109 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 names = dict_keys_inorder(c->u->u_names, 0);
4112 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4113 if (!consts || !names || !varnames)
4114 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4117 if (!cellvars)
4118 goto error;
4119 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4120 if (!freevars)
4121 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 nlocals = PyDict_Size(c->u->u_varnames);
4123 flags = compute_code_flags(c);
4124 if (flags < 0)
4125 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4128 if (!bytecode)
4129 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4132 if (!tmp)
4133 goto error;
4134 Py_DECREF(consts);
4135 consts = tmp;
4136
4137 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4138 nlocals, stackdepth(c), flags,
4139 bytecode, consts, names, varnames,
4140 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004141 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 c->u->u_firstlineno,
4143 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 Py_XDECREF(consts);
4146 Py_XDECREF(names);
4147 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 Py_XDECREF(name);
4149 Py_XDECREF(freevars);
4150 Py_XDECREF(cellvars);
4151 Py_XDECREF(bytecode);
4152 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004153}
4154
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004155
4156/* For debugging purposes only */
4157#if 0
4158static void
4159dump_instr(const struct instr *i)
4160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 const char *jrel = i->i_jrel ? "jrel " : "";
4162 const char *jabs = i->i_jabs ? "jabs " : "";
4163 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 *arg = '\0';
4166 if (i->i_hasarg)
4167 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4170 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004171}
4172
4173static void
4174dump_basicblock(const basicblock *b)
4175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 const char *seen = b->b_seen ? "seen " : "";
4177 const char *b_return = b->b_return ? "return " : "";
4178 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4179 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4180 if (b->b_instr) {
4181 int i;
4182 for (i = 0; i < b->b_iused; i++) {
4183 fprintf(stderr, " [%02d] ", i);
4184 dump_instr(b->b_instr + i);
4185 }
4186 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004187}
4188#endif
4189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190static PyCodeObject *
4191assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 basicblock *b, *entryblock;
4194 struct assembler a;
4195 int i, j, nblocks;
4196 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 /* Make sure every block that falls off the end returns None.
4199 XXX NEXT_BLOCK() isn't quite right, because if the last
4200 block ends with a jump or return b_next shouldn't set.
4201 */
4202 if (!c->u->u_curblock->b_return) {
4203 NEXT_BLOCK(c);
4204 if (addNone)
4205 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4206 ADDOP(c, RETURN_VALUE);
4207 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 nblocks = 0;
4210 entryblock = NULL;
4211 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4212 nblocks++;
4213 entryblock = b;
4214 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 /* Set firstlineno if it wasn't explicitly set. */
4217 if (!c->u->u_firstlineno) {
4218 if (entryblock && entryblock->b_instr)
4219 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4220 else
4221 c->u->u_firstlineno = 1;
4222 }
4223 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4224 goto error;
4225 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 /* Can't modify the bytecode after computing jump offsets. */
4228 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 /* Emit code in reverse postorder from dfs. */
4231 for (i = a.a_nblocks - 1; i >= 0; i--) {
4232 b = a.a_postorder[i];
4233 for (j = 0; j < b->b_iused; j++)
4234 if (!assemble_emit(&a, &b->b_instr[j]))
4235 goto error;
4236 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4239 goto error;
4240 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4241 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004244 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 assemble_free(&a);
4246 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004247}
Georg Brandl8334fd92010-12-04 10:26:46 +00004248
4249#undef PyAST_Compile
4250PyAPI_FUNC(PyCodeObject *)
4251PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4252 PyArena *arena)
4253{
4254 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4255}
4256
4257