+++ /dev/null
-/*\r
- * This file compiles an abstract syntax tree (AST) into Python bytecode.\r
- *\r
- * The primary entry point is PyAST_Compile(), which returns a\r
- * PyCodeObject. The compiler makes several passes to build the code\r
- * object:\r
- * 1. Checks for future statements. See future.c\r
- * 2. Builds a symbol table. See symtable.c.\r
- * 3. Generate code for basic blocks. See compiler_mod() in this file.\r
- * 4. Assemble the basic blocks into final code. See assemble() in\r
- * this file.\r
- * 5. Optimize the byte code (peephole optimizations). See peephole.c\r
- *\r
- * Note that compiler_mod() suggests module, but the module ast type\r
- * (mod_ty) has cases for expressions and interactive statements.\r
- *\r
- * CAUTION: The VISIT_* macros abort the current function when they\r
- * encounter a problem. So don't invoke them when there is memory\r
- * which needs to be released. Code blocks are OK, as the compiler\r
- * structure takes care of releasing those. Use the arena to manage\r
- * objects.\r
- */\r
-\r
-#include "Python.h"\r
-\r
-#include "Python-ast.h"\r
-#include "node.h"\r
-#include "pyarena.h"\r
-#include "ast.h"\r
-#include "code.h"\r
-#include "compile.h"\r
-#include "symtable.h"\r
-#include "opcode.h"\r
-\r
-int Py_OptimizeFlag = 0;\r
-\r
-#define DEFAULT_BLOCK_SIZE 16\r
-#define DEFAULT_BLOCKS 8\r
-#define DEFAULT_CODE_SIZE 128\r
-#define DEFAULT_LNOTAB_SIZE 16\r
-\r
-#define COMP_GENEXP 0\r
-#define COMP_SETCOMP 1\r
-#define COMP_DICTCOMP 2\r
-\r
-struct instr {\r
- unsigned i_jabs : 1;\r
- unsigned i_jrel : 1;\r
- unsigned i_hasarg : 1;\r
- unsigned char i_opcode;\r
- int i_oparg;\r
- struct basicblock_ *i_target; /* target block (if jump instruction) */\r
- int i_lineno;\r
-};\r
-\r
-typedef struct basicblock_ {\r
- /* Each basicblock in a compilation unit is linked via b_list in the\r
- reverse order that the block are allocated. b_list points to the next\r
- block, not to be confused with b_next, which is next by control flow. */\r
- struct basicblock_ *b_list;\r
- /* number of instructions used */\r
- int b_iused;\r
- /* length of instruction array (b_instr) */\r
- int b_ialloc;\r
- /* pointer to an array of instructions, initially NULL */\r
- struct instr *b_instr;\r
- /* If b_next is non-NULL, it is a pointer to the next\r
- block reached by normal control flow. */\r
- struct basicblock_ *b_next;\r
- /* b_seen is used to perform a DFS of basicblocks. */\r
- unsigned b_seen : 1;\r
- /* b_return is true if a RETURN_VALUE opcode is inserted. */\r
- unsigned b_return : 1;\r
- /* depth of stack upon entry of block, computed by stackdepth() */\r
- int b_startdepth;\r
- /* instruction offset for block, computed by assemble_jump_offsets() */\r
- int b_offset;\r
-} basicblock;\r
-\r
-/* fblockinfo tracks the current frame block.\r
-\r
-A frame block is used to handle loops, try/except, and try/finally.\r
-It's called a frame block to distinguish it from a basic block in the\r
-compiler IR.\r
-*/\r
-\r
-enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };\r
-\r
-struct fblockinfo {\r
- enum fblocktype fb_type;\r
- basicblock *fb_block;\r
-};\r
-\r
-/* The following items change on entry and exit of code blocks.\r
- They must be saved and restored when returning to a block.\r
-*/\r
-struct compiler_unit {\r
- PySTEntryObject *u_ste;\r
-\r
- PyObject *u_name;\r
- /* The following fields are dicts that map objects to\r
- the index of them in co_XXX. The index is used as\r
- the argument for opcodes that refer to those collections.\r
- */\r
- PyObject *u_consts; /* all constants */\r
- PyObject *u_names; /* all names */\r
- PyObject *u_varnames; /* local variables */\r
- PyObject *u_cellvars; /* cell variables */\r
- PyObject *u_freevars; /* free variables */\r
-\r
- PyObject *u_private; /* for private name mangling */\r
-\r
- int u_argcount; /* number of arguments for block */\r
- /* Pointer to the most recently allocated block. By following b_list\r
- members, you can reach all early allocated blocks. */\r
- basicblock *u_blocks;\r
- basicblock *u_curblock; /* pointer to current block */\r
-\r
- int u_nfblocks;\r
- struct fblockinfo u_fblock[CO_MAXBLOCKS];\r
-\r
- int u_firstlineno; /* the first lineno of the block */\r
- int u_lineno; /* the lineno for the current stmt */\r
- bool u_lineno_set; /* boolean to indicate whether instr\r
- has been generated with current lineno */\r
-};\r
-\r
-/* This struct captures the global state of a compilation.\r
-\r
-The u pointer points to the current compilation unit, while units\r
-for enclosing blocks are stored in c_stack. The u and c_stack are\r
-managed by compiler_enter_scope() and compiler_exit_scope().\r
-*/\r
-\r
-struct compiler {\r
- const char *c_filename;\r
- struct symtable *c_st;\r
- PyFutureFeatures *c_future; /* pointer to module's __future__ */\r
- PyCompilerFlags *c_flags;\r
-\r
- int c_interactive; /* true if in interactive mode */\r
- int c_nestlevel;\r
-\r
- struct compiler_unit *u; /* compiler state for current block */\r
- PyObject *c_stack; /* Python list holding compiler_unit ptrs */\r
- PyArena *c_arena; /* pointer to memory allocation arena */\r
-};\r
-\r
-static int compiler_enter_scope(struct compiler *, identifier, void *, int);\r
-static void compiler_free(struct compiler *);\r
-static basicblock *compiler_new_block(struct compiler *);\r
-static int compiler_next_instr(struct compiler *, basicblock *);\r
-static int compiler_addop(struct compiler *, int);\r
-static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);\r
-static int compiler_addop_i(struct compiler *, int, int);\r
-static int compiler_addop_j(struct compiler *, int, basicblock *, int);\r
-static basicblock *compiler_use_new_block(struct compiler *);\r
-static int compiler_error(struct compiler *, const char *);\r
-static int compiler_nameop(struct compiler *, identifier, expr_context_ty);\r
-\r
-static PyCodeObject *compiler_mod(struct compiler *, mod_ty);\r
-static int compiler_visit_stmt(struct compiler *, stmt_ty);\r
-static int compiler_visit_keyword(struct compiler *, keyword_ty);\r
-static int compiler_visit_expr(struct compiler *, expr_ty);\r
-static int compiler_augassign(struct compiler *, stmt_ty);\r
-static int compiler_visit_slice(struct compiler *, slice_ty,\r
- expr_context_ty);\r
-\r
-static int compiler_push_fblock(struct compiler *, enum fblocktype,\r
- basicblock *);\r
-static void compiler_pop_fblock(struct compiler *, enum fblocktype,\r
- basicblock *);\r
-/* Returns true if there is a loop on the fblock stack. */\r
-static int compiler_in_loop(struct compiler *);\r
-\r
-static int inplace_binop(struct compiler *, operator_ty);\r
-static int expr_constant(expr_ty e);\r
-\r
-static int compiler_with(struct compiler *, stmt_ty);\r
-\r
-static PyCodeObject *assemble(struct compiler *, int addNone);\r
-static PyObject *__doc__;\r
-\r
-#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"\r
-\r
-PyObject *\r
-_Py_Mangle(PyObject *privateobj, PyObject *ident)\r
-{\r
- /* Name mangling: __private becomes _classname__private.\r
- This is independent from how the name is used. */\r
- const char *p, *name = PyString_AsString(ident);\r
- char *buffer;\r
- size_t nlen, plen;\r
- if (privateobj == NULL || !PyString_Check(privateobj) ||\r
- name == NULL || name[0] != '_' || name[1] != '_') {\r
- Py_INCREF(ident);\r
- return ident;\r
- }\r
- p = PyString_AsString(privateobj);\r
- nlen = strlen(name);\r
- /* Don't mangle __id__ or names with dots.\r
-\r
- The only time a name with a dot can occur is when\r
- we are compiling an import statement that has a\r
- package name.\r
-\r
- TODO(jhylton): Decide whether we want to support\r
- mangling of the module name, e.g. __M.X.\r
- */\r
- if ((name[nlen-1] == '_' && name[nlen-2] == '_')\r
- || strchr(name, '.')) {\r
- Py_INCREF(ident);\r
- return ident; /* Don't mangle __whatever__ */\r
- }\r
- /* Strip leading underscores from class name */\r
- while (*p == '_')\r
- p++;\r
- if (*p == '\0') {\r
- Py_INCREF(ident);\r
- return ident; /* Don't mangle if class is just underscores */\r
- }\r
- plen = strlen(p);\r
-\r
- assert(1 <= PY_SSIZE_T_MAX - nlen);\r
- assert(1 + nlen <= PY_SSIZE_T_MAX - plen);\r
-\r
- ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);\r
- if (!ident)\r
- return 0;\r
- /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */\r
- buffer = PyString_AS_STRING(ident);\r
- buffer[0] = '_';\r
- strncpy(buffer+1, p, plen);\r
- strcpy(buffer+1+plen, name);\r
- return ident;\r
-}\r
-\r
-static int\r
-compiler_init(struct compiler *c)\r
-{\r
- memset(c, 0, sizeof(struct compiler));\r
-\r
- c->c_stack = PyList_New(0);\r
- if (!c->c_stack)\r
- return 0;\r
-\r
- return 1;\r
-}\r
-\r
-PyCodeObject *\r
-PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,\r
- PyArena *arena)\r
-{\r
- struct compiler c;\r
- PyCodeObject *co = NULL;\r
- PyCompilerFlags local_flags;\r
- int merged;\r
-\r
- if (!__doc__) {\r
- __doc__ = PyString_InternFromString("__doc__");\r
- if (!__doc__)\r
- return NULL;\r
- }\r
-\r
- if (!compiler_init(&c))\r
- return NULL;\r
- c.c_filename = filename;\r
- c.c_arena = arena;\r
- c.c_future = PyFuture_FromAST(mod, filename);\r
- if (c.c_future == NULL)\r
- goto finally;\r
- if (!flags) {\r
- local_flags.cf_flags = 0;\r
- flags = &local_flags;\r
- }\r
- merged = c.c_future->ff_features | flags->cf_flags;\r
- c.c_future->ff_features = merged;\r
- flags->cf_flags = merged;\r
- c.c_flags = flags;\r
- c.c_nestlevel = 0;\r
-\r
- c.c_st = PySymtable_Build(mod, filename, c.c_future);\r
- if (c.c_st == NULL) {\r
- if (!PyErr_Occurred())\r
- PyErr_SetString(PyExc_SystemError, "no symtable");\r
- goto finally;\r
- }\r
-\r
- co = compiler_mod(&c, mod);\r
-\r
- finally:\r
- compiler_free(&c);\r
- assert(co || PyErr_Occurred());\r
- return co;\r
-}\r
-\r
-PyCodeObject *\r
-PyNode_Compile(struct _node *n, const char *filename)\r
-{\r
- PyCodeObject *co = NULL;\r
- mod_ty mod;\r
- PyArena *arena = PyArena_New();\r
- if (!arena)\r
- return NULL;\r
- mod = PyAST_FromNode(n, NULL, filename, arena);\r
- if (mod)\r
- co = PyAST_Compile(mod, filename, NULL, arena);\r
- PyArena_Free(arena);\r
- return co;\r
-}\r
-\r
-static void\r
-compiler_free(struct compiler *c)\r
-{\r
- if (c->c_st)\r
- PySymtable_Free(c->c_st);\r
- if (c->c_future)\r
- PyObject_Free(c->c_future);\r
- Py_DECREF(c->c_stack);\r
-}\r
-\r
-static PyObject *\r
-list2dict(PyObject *list)\r
-{\r
- Py_ssize_t i, n;\r
- PyObject *v, *k;\r
- PyObject *dict = PyDict_New();\r
- if (!dict) return NULL;\r
-\r
- n = PyList_Size(list);\r
- for (i = 0; i < n; i++) {\r
- v = PyInt_FromLong(i);\r
- if (!v) {\r
- Py_DECREF(dict);\r
- return NULL;\r
- }\r
- k = PyList_GET_ITEM(list, i);\r
- k = PyTuple_Pack(2, k, k->ob_type);\r
- if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {\r
- Py_XDECREF(k);\r
- Py_DECREF(v);\r
- Py_DECREF(dict);\r
- return NULL;\r
- }\r
- Py_DECREF(k);\r
- Py_DECREF(v);\r
- }\r
- return dict;\r
-}\r
-\r
-/* Return new dict containing names from src that match scope(s).\r
-\r
-src is a symbol table dictionary. If the scope of a name matches\r
-either scope_type or flag is set, insert it into the new dict. The\r
-values are integers, starting at offset and increasing by one for\r
-each key.\r
-*/\r
-\r
-static PyObject *\r
-dictbytype(PyObject *src, int scope_type, int flag, int offset)\r
-{\r
- Py_ssize_t pos = 0, i = offset, scope;\r
- PyObject *k, *v, *dest = PyDict_New();\r
-\r
- assert(offset >= 0);\r
- if (dest == NULL)\r
- return NULL;\r
-\r
- while (PyDict_Next(src, &pos, &k, &v)) {\r
- /* XXX this should probably be a macro in symtable.h */\r
- assert(PyInt_Check(v));\r
- scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;\r
-\r
- if (scope == scope_type || PyInt_AS_LONG(v) & flag) {\r
- PyObject *tuple, *item = PyInt_FromLong(i);\r
- if (item == NULL) {\r
- Py_DECREF(dest);\r
- return NULL;\r
- }\r
- i++;\r
- tuple = PyTuple_Pack(2, k, k->ob_type);\r
- if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {\r
- Py_DECREF(item);\r
- Py_DECREF(dest);\r
- Py_XDECREF(tuple);\r
- return NULL;\r
- }\r
- Py_DECREF(item);\r
- Py_DECREF(tuple);\r
- }\r
- }\r
- return dest;\r
-}\r
-\r
-static void\r
-compiler_unit_check(struct compiler_unit *u)\r
-{\r
- basicblock *block;\r
- for (block = u->u_blocks; block != NULL; block = block->b_list) {\r
- assert((void *)block != (void *)0xcbcbcbcb);\r
- assert((void *)block != (void *)0xfbfbfbfb);\r
- assert((void *)block != (void *)0xdbdbdbdb);\r
- if (block->b_instr != NULL) {\r
- assert(block->b_ialloc > 0);\r
- assert(block->b_iused > 0);\r
- assert(block->b_ialloc >= block->b_iused);\r
- }\r
- else {\r
- assert (block->b_iused == 0);\r
- assert (block->b_ialloc == 0);\r
- }\r
- }\r
-}\r
-\r
-static void\r
-compiler_unit_free(struct compiler_unit *u)\r
-{\r
- basicblock *b, *next;\r
-\r
- compiler_unit_check(u);\r
- b = u->u_blocks;\r
- while (b != NULL) {\r
- if (b->b_instr)\r
- PyObject_Free((void *)b->b_instr);\r
- next = b->b_list;\r
- PyObject_Free((void *)b);\r
- b = next;\r
- }\r
- Py_CLEAR(u->u_ste);\r
- Py_CLEAR(u->u_name);\r
- Py_CLEAR(u->u_consts);\r
- Py_CLEAR(u->u_names);\r
- Py_CLEAR(u->u_varnames);\r
- Py_CLEAR(u->u_freevars);\r
- Py_CLEAR(u->u_cellvars);\r
- Py_CLEAR(u->u_private);\r
- PyObject_Free(u);\r
-}\r
-\r
-static int\r
-compiler_enter_scope(struct compiler *c, identifier name, void *key,\r
- int lineno)\r
-{\r
- struct compiler_unit *u;\r
-\r
- u = (struct compiler_unit *)PyObject_Malloc(sizeof(\r
- struct compiler_unit));\r
- if (!u) {\r
- PyErr_NoMemory();\r
- return 0;\r
- }\r
- memset(u, 0, sizeof(struct compiler_unit));\r
- u->u_argcount = 0;\r
- u->u_ste = PySymtable_Lookup(c->c_st, key);\r
- if (!u->u_ste) {\r
- compiler_unit_free(u);\r
- return 0;\r
- }\r
- Py_INCREF(name);\r
- u->u_name = name;\r
- u->u_varnames = list2dict(u->u_ste->ste_varnames);\r
- u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);\r
- if (!u->u_varnames || !u->u_cellvars) {\r
- compiler_unit_free(u);\r
- return 0;\r
- }\r
-\r
- u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,\r
- PyDict_Size(u->u_cellvars));\r
- if (!u->u_freevars) {\r
- compiler_unit_free(u);\r
- return 0;\r
- }\r
-\r
- u->u_blocks = NULL;\r
- u->u_nfblocks = 0;\r
- u->u_firstlineno = lineno;\r
- u->u_lineno = 0;\r
- u->u_lineno_set = false;\r
- u->u_consts = PyDict_New();\r
- if (!u->u_consts) {\r
- compiler_unit_free(u);\r
- return 0;\r
- }\r
- u->u_names = PyDict_New();\r
- if (!u->u_names) {\r
- compiler_unit_free(u);\r
- return 0;\r
- }\r
-\r
- u->u_private = NULL;\r
-\r
- /* Push the old compiler_unit on the stack. */\r
- if (c->u) {\r
- PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);\r
- if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {\r
- Py_XDECREF(capsule);\r
- compiler_unit_free(u);\r
- return 0;\r
- }\r
- Py_DECREF(capsule);\r
- u->u_private = c->u->u_private;\r
- Py_XINCREF(u->u_private);\r
- }\r
- c->u = u;\r
-\r
- c->c_nestlevel++;\r
- if (compiler_use_new_block(c) == NULL)\r
- return 0;\r
-\r
- return 1;\r
-}\r
-\r
-static void\r
-compiler_exit_scope(struct compiler *c)\r
-{\r
- int n;\r
- PyObject *capsule;\r
-\r
- c->c_nestlevel--;\r
- compiler_unit_free(c->u);\r
- /* Restore c->u to the parent unit. */\r
- n = PyList_GET_SIZE(c->c_stack) - 1;\r
- if (n >= 0) {\r
- capsule = PyList_GET_ITEM(c->c_stack, n);\r
- c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);\r
- assert(c->u);\r
- /* we are deleting from a list so this really shouldn't fail */\r
- if (PySequence_DelItem(c->c_stack, n) < 0)\r
- Py_FatalError("compiler_exit_scope()");\r
- compiler_unit_check(c->u);\r
- }\r
- else\r
- c->u = NULL;\r
-\r
-}\r
-\r
-/* Allocate a new block and return a pointer to it.\r
- Returns NULL on error.\r
-*/\r
-\r
-static basicblock *\r
-compiler_new_block(struct compiler *c)\r
-{\r
- basicblock *b;\r
- struct compiler_unit *u;\r
-\r
- u = c->u;\r
- b = (basicblock *)PyObject_Malloc(sizeof(basicblock));\r
- if (b == NULL) {\r
- PyErr_NoMemory();\r
- return NULL;\r
- }\r
- memset((void *)b, 0, sizeof(basicblock));\r
- /* Extend the singly linked list of blocks with new block. */\r
- b->b_list = u->u_blocks;\r
- u->u_blocks = b;\r
- return b;\r
-}\r
-\r
-static basicblock *\r
-compiler_use_new_block(struct compiler *c)\r
-{\r
- basicblock *block = compiler_new_block(c);\r
- if (block == NULL)\r
- return NULL;\r
- c->u->u_curblock = block;\r
- return block;\r
-}\r
-\r
-static basicblock *\r
-compiler_next_block(struct compiler *c)\r
-{\r
- basicblock *block = compiler_new_block(c);\r
- if (block == NULL)\r
- return NULL;\r
- c->u->u_curblock->b_next = block;\r
- c->u->u_curblock = block;\r
- return block;\r
-}\r
-\r
-static basicblock *\r
-compiler_use_next_block(struct compiler *c, basicblock *block)\r
-{\r
- assert(block != NULL);\r
- c->u->u_curblock->b_next = block;\r
- c->u->u_curblock = block;\r
- return block;\r
-}\r
-\r
-/* Returns the offset of the next instruction in the current block's\r
- b_instr array. Resizes the b_instr as necessary.\r
- Returns -1 on failure.\r
-*/\r
-\r
-static int\r
-compiler_next_instr(struct compiler *c, basicblock *b)\r
-{\r
- assert(b != NULL);\r
- if (b->b_instr == NULL) {\r
- b->b_instr = (struct instr *)PyObject_Malloc(\r
- sizeof(struct instr) * DEFAULT_BLOCK_SIZE);\r
- if (b->b_instr == NULL) {\r
- PyErr_NoMemory();\r
- return -1;\r
- }\r
- b->b_ialloc = DEFAULT_BLOCK_SIZE;\r
- memset((char *)b->b_instr, 0,\r
- sizeof(struct instr) * DEFAULT_BLOCK_SIZE);\r
- }\r
- else if (b->b_iused == b->b_ialloc) {\r
- struct instr *tmp;\r
- size_t oldsize, newsize;\r
- oldsize = b->b_ialloc * sizeof(struct instr);\r
- newsize = oldsize << 1;\r
-\r
- if (oldsize > (PY_SIZE_MAX >> 1)) {\r
- PyErr_NoMemory();\r
- return -1;\r
- }\r
-\r
- if (newsize == 0) {\r
- PyErr_NoMemory();\r
- return -1;\r
- }\r
- b->b_ialloc <<= 1;\r
- tmp = (struct instr *)PyObject_Realloc(\r
- (void *)b->b_instr, newsize);\r
- if (tmp == NULL) {\r
- PyErr_NoMemory();\r
- return -1;\r
- }\r
- b->b_instr = tmp;\r
- memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);\r
- }\r
- return b->b_iused++;\r
-}\r
-\r
-/* Set the i_lineno member of the instruction at offset off if the\r
- line number for the current expression/statement has not\r
- already been set. If it has been set, the call has no effect.\r
-\r
- The line number is reset in the following cases:\r
- - when entering a new scope\r
- - on each statement\r
- - on each expression that start a new line\r
- - before the "except" clause\r
- - before the "for" and "while" expressions\r
-*/\r
-\r
-static void\r
-compiler_set_lineno(struct compiler *c, int off)\r
-{\r
- basicblock *b;\r
- if (c->u->u_lineno_set)\r
- return;\r
- c->u->u_lineno_set = true;\r
- b = c->u->u_curblock;\r
- b->b_instr[off].i_lineno = c->u->u_lineno;\r
-}\r
-\r
-static int\r
-opcode_stack_effect(int opcode, int oparg)\r
-{\r
- switch (opcode) {\r
- case POP_TOP:\r
- return -1;\r
- case ROT_TWO:\r
- case ROT_THREE:\r
- return 0;\r
- case DUP_TOP:\r
- return 1;\r
- case ROT_FOUR:\r
- return 0;\r
-\r
- case UNARY_POSITIVE:\r
- case UNARY_NEGATIVE:\r
- case UNARY_NOT:\r
- case UNARY_CONVERT:\r
- case UNARY_INVERT:\r
- return 0;\r
-\r
- case SET_ADD:\r
- case LIST_APPEND:\r
- return -1;\r
-\r
- case MAP_ADD:\r
- return -2;\r
-\r
- case BINARY_POWER:\r
- case BINARY_MULTIPLY:\r
- case BINARY_DIVIDE:\r
- case BINARY_MODULO:\r
- case BINARY_ADD:\r
- case BINARY_SUBTRACT:\r
- case BINARY_SUBSCR:\r
- case BINARY_FLOOR_DIVIDE:\r
- case BINARY_TRUE_DIVIDE:\r
- return -1;\r
- case INPLACE_FLOOR_DIVIDE:\r
- case INPLACE_TRUE_DIVIDE:\r
- return -1;\r
-\r
- case SLICE+0:\r
- return 0;\r
- case SLICE+1:\r
- return -1;\r
- case SLICE+2:\r
- return -1;\r
- case SLICE+3:\r
- return -2;\r
-\r
- case STORE_SLICE+0:\r
- return -2;\r
- case STORE_SLICE+1:\r
- return -3;\r
- case STORE_SLICE+2:\r
- return -3;\r
- case STORE_SLICE+3:\r
- return -4;\r
-\r
- case DELETE_SLICE+0:\r
- return -1;\r
- case DELETE_SLICE+1:\r
- return -2;\r
- case DELETE_SLICE+2:\r
- return -2;\r
- case DELETE_SLICE+3:\r
- return -3;\r
-\r
- case INPLACE_ADD:\r
- case INPLACE_SUBTRACT:\r
- case INPLACE_MULTIPLY:\r
- case INPLACE_DIVIDE:\r
- case INPLACE_MODULO:\r
- return -1;\r
- case STORE_SUBSCR:\r
- return -3;\r
- case STORE_MAP:\r
- return -2;\r
- case DELETE_SUBSCR:\r
- return -2;\r
-\r
- case BINARY_LSHIFT:\r
- case BINARY_RSHIFT:\r
- case BINARY_AND:\r
- case BINARY_XOR:\r
- case BINARY_OR:\r
- return -1;\r
- case INPLACE_POWER:\r
- return -1;\r
- case GET_ITER:\r
- return 0;\r
-\r
- case PRINT_EXPR:\r
- return -1;\r
- case PRINT_ITEM:\r
- return -1;\r
- case PRINT_NEWLINE:\r
- return 0;\r
- case PRINT_ITEM_TO:\r
- return -2;\r
- case PRINT_NEWLINE_TO:\r
- return -1;\r
- case INPLACE_LSHIFT:\r
- case INPLACE_RSHIFT:\r
- case INPLACE_AND:\r
- case INPLACE_XOR:\r
- case INPLACE_OR:\r
- return -1;\r
- case BREAK_LOOP:\r
- return 0;\r
- case SETUP_WITH:\r
- return 4;\r
- case WITH_CLEANUP:\r
- return -1; /* XXX Sometimes more */\r
- case LOAD_LOCALS:\r
- return 1;\r
- case RETURN_VALUE:\r
- return -1;\r
- case IMPORT_STAR:\r
- return -1;\r
- case EXEC_STMT:\r
- return -3;\r
- case YIELD_VALUE:\r
- return 0;\r
-\r
- case POP_BLOCK:\r
- return 0;\r
- case END_FINALLY:\r
- return -3; /* or -1 or -2 if no exception occurred or\r
- return/break/continue */\r
- case BUILD_CLASS:\r
- return -2;\r
-\r
- case STORE_NAME:\r
- return -1;\r
- case DELETE_NAME:\r
- return 0;\r
- case UNPACK_SEQUENCE:\r
- return oparg-1;\r
- case FOR_ITER:\r
- return 1; /* or -1, at end of iterator */\r
-\r
- case STORE_ATTR:\r
- return -2;\r
- case DELETE_ATTR:\r
- return -1;\r
- case STORE_GLOBAL:\r
- return -1;\r
- case DELETE_GLOBAL:\r
- return 0;\r
- case DUP_TOPX:\r
- return oparg;\r
- case LOAD_CONST:\r
- return 1;\r
- case LOAD_NAME:\r
- return 1;\r
- case BUILD_TUPLE:\r
- case BUILD_LIST:\r
- case BUILD_SET:\r
- return 1-oparg;\r
- case BUILD_MAP:\r
- return 1;\r
- case LOAD_ATTR:\r
- return 0;\r
- case COMPARE_OP:\r
- return -1;\r
- case IMPORT_NAME:\r
- return -1;\r
- case IMPORT_FROM:\r
- return 1;\r
-\r
- case JUMP_FORWARD:\r
- case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */\r
- case JUMP_IF_FALSE_OR_POP: /* "" */\r
- case JUMP_ABSOLUTE:\r
- return 0;\r
-\r
- case POP_JUMP_IF_FALSE:\r
- case POP_JUMP_IF_TRUE:\r
- return -1;\r
-\r
- case LOAD_GLOBAL:\r
- return 1;\r
-\r
- case CONTINUE_LOOP:\r
- return 0;\r
- case SETUP_LOOP:\r
- case SETUP_EXCEPT:\r
- case SETUP_FINALLY:\r
- return 0;\r
-\r
- case LOAD_FAST:\r
- return 1;\r
- case STORE_FAST:\r
- return -1;\r
- case DELETE_FAST:\r
- return 0;\r
-\r
- case RAISE_VARARGS:\r
- return -oparg;\r
-#define NARGS(o) (((o) % 256) + 2*((o) / 256))\r
- case CALL_FUNCTION:\r
- return -NARGS(oparg);\r
- case CALL_FUNCTION_VAR:\r
- case CALL_FUNCTION_KW:\r
- return -NARGS(oparg)-1;\r
- case CALL_FUNCTION_VAR_KW:\r
- return -NARGS(oparg)-2;\r
-#undef NARGS\r
- case MAKE_FUNCTION:\r
- return -oparg;\r
- case BUILD_SLICE:\r
- if (oparg == 3)\r
- return -2;\r
- else\r
- return -1;\r
-\r
- case MAKE_CLOSURE:\r
- return -oparg-1;\r
- case LOAD_CLOSURE:\r
- return 1;\r
- case LOAD_DEREF:\r
- return 1;\r
- case STORE_DEREF:\r
- return -1;\r
- default:\r
- fprintf(stderr, "opcode = %d\n", opcode);\r
- Py_FatalError("opcode_stack_effect()");\r
-\r
- }\r
- return 0; /* not reachable */\r
-}\r
-\r
-/* Add an opcode with no argument.\r
- Returns 0 on failure, 1 on success.\r
-*/\r
-\r
-static int\r
-compiler_addop(struct compiler *c, int opcode)\r
-{\r
- basicblock *b;\r
- struct instr *i;\r
- int off;\r
- off = compiler_next_instr(c, c->u->u_curblock);\r
- if (off < 0)\r
- return 0;\r
- b = c->u->u_curblock;\r
- i = &b->b_instr[off];\r
- i->i_opcode = opcode;\r
- i->i_hasarg = 0;\r
- if (opcode == RETURN_VALUE)\r
- b->b_return = 1;\r
- compiler_set_lineno(c, off);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)\r
-{\r
- PyObject *t, *v;\r
- Py_ssize_t arg;\r
- double d;\r
-\r
- /* necessary to make sure types aren't coerced (e.g., int and long) */\r
- /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */\r
- if (PyFloat_Check(o)) {\r
- d = PyFloat_AS_DOUBLE(o);\r
- /* all we need is to make the tuple different in either the 0.0\r
- * or -0.0 case from all others, just to avoid the "coercion".\r
- */\r
- if (d == 0.0 && copysign(1.0, d) < 0.0)\r
- t = PyTuple_Pack(3, o, o->ob_type, Py_None);\r
- else\r
- t = PyTuple_Pack(2, o, o->ob_type);\r
- }\r
-#ifndef WITHOUT_COMPLEX\r
- else if (PyComplex_Check(o)) {\r
- Py_complex z;\r
- int real_negzero, imag_negzero;\r
- /* For the complex case we must make complex(x, 0.)\r
- different from complex(x, -0.) and complex(0., y)\r
- different from complex(-0., y), for any x and y.\r
- All four complex zeros must be distinguished.*/\r
- z = PyComplex_AsCComplex(o);\r
- real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;\r
- imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;\r
- if (real_negzero && imag_negzero) {\r
- t = PyTuple_Pack(5, o, o->ob_type,\r
- Py_None, Py_None, Py_None);\r
- }\r
- else if (imag_negzero) {\r
- t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);\r
- }\r
- else if (real_negzero) {\r
- t = PyTuple_Pack(3, o, o->ob_type, Py_None);\r
- }\r
- else {\r
- t = PyTuple_Pack(2, o, o->ob_type);\r
- }\r
- }\r
-#endif /* WITHOUT_COMPLEX */\r
- else {\r
- t = PyTuple_Pack(2, o, o->ob_type);\r
- }\r
- if (t == NULL)\r
- return -1;\r
-\r
- v = PyDict_GetItem(dict, t);\r
- if (!v) {\r
- arg = PyDict_Size(dict);\r
- v = PyInt_FromLong(arg);\r
- if (!v) {\r
- Py_DECREF(t);\r
- return -1;\r
- }\r
- if (PyDict_SetItem(dict, t, v) < 0) {\r
- Py_DECREF(t);\r
- Py_DECREF(v);\r
- return -1;\r
- }\r
- Py_DECREF(v);\r
- }\r
- else\r
- arg = PyInt_AsLong(v);\r
- Py_DECREF(t);\r
- return arg;\r
-}\r
-\r
-static int\r
-compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,\r
- PyObject *o)\r
-{\r
- int arg = compiler_add_o(c, dict, o);\r
- if (arg < 0)\r
- return 0;\r
- return compiler_addop_i(c, opcode, arg);\r
-}\r
-\r
-static int\r
-compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,\r
- PyObject *o)\r
-{\r
- int arg;\r
- PyObject *mangled = _Py_Mangle(c->u->u_private, o);\r
- if (!mangled)\r
- return 0;\r
- arg = compiler_add_o(c, dict, mangled);\r
- Py_DECREF(mangled);\r
- if (arg < 0)\r
- return 0;\r
- return compiler_addop_i(c, opcode, arg);\r
-}\r
-\r
-/* Add an opcode with an integer argument.\r
- Returns 0 on failure, 1 on success.\r
-*/\r
-\r
-static int\r
-compiler_addop_i(struct compiler *c, int opcode, int oparg)\r
-{\r
- struct instr *i;\r
- int off;\r
- off = compiler_next_instr(c, c->u->u_curblock);\r
- if (off < 0)\r
- return 0;\r
- i = &c->u->u_curblock->b_instr[off];\r
- i->i_opcode = opcode;\r
- i->i_oparg = oparg;\r
- i->i_hasarg = 1;\r
- compiler_set_lineno(c, off);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)\r
-{\r
- struct instr *i;\r
- int off;\r
-\r
- assert(b != NULL);\r
- off = compiler_next_instr(c, c->u->u_curblock);\r
- if (off < 0)\r
- return 0;\r
- i = &c->u->u_curblock->b_instr[off];\r
- i->i_opcode = opcode;\r
- i->i_target = b;\r
- i->i_hasarg = 1;\r
- if (absolute)\r
- i->i_jabs = 1;\r
- else\r
- i->i_jrel = 1;\r
- compiler_set_lineno(c, off);\r
- return 1;\r
-}\r
-\r
-/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd\r
- like to find better names.) NEW_BLOCK() creates a new block and sets\r
- it as the current block. NEXT_BLOCK() also creates an implicit jump\r
- from the current block to the new block.\r
-*/\r
-\r
-/* The returns inside these macros make it impossible to decref objects\r
- created in the local function. Local objects should use the arena.\r
-*/\r
-\r
-\r
-#define NEW_BLOCK(C) { \\r
- if (compiler_use_new_block((C)) == NULL) \\r
- return 0; \\r
-}\r
-\r
-#define NEXT_BLOCK(C) { \\r
- if (compiler_next_block((C)) == NULL) \\r
- return 0; \\r
-}\r
-\r
-#define ADDOP(C, OP) { \\r
- if (!compiler_addop((C), (OP))) \\r
- return 0; \\r
-}\r
-\r
-#define ADDOP_IN_SCOPE(C, OP) { \\r
- if (!compiler_addop((C), (OP))) { \\r
- compiler_exit_scope(c); \\r
- return 0; \\r
- } \\r
-}\r
-\r
-#define ADDOP_O(C, OP, O, TYPE) { \\r
- if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \\r
- return 0; \\r
-}\r
-\r
-#define ADDOP_NAME(C, OP, O, TYPE) { \\r
- if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \\r
- return 0; \\r
-}\r
-\r
-#define ADDOP_I(C, OP, O) { \\r
- if (!compiler_addop_i((C), (OP), (O))) \\r
- return 0; \\r
-}\r
-\r
-#define ADDOP_JABS(C, OP, O) { \\r
- if (!compiler_addop_j((C), (OP), (O), 1)) \\r
- return 0; \\r
-}\r
-\r
-#define ADDOP_JREL(C, OP, O) { \\r
- if (!compiler_addop_j((C), (OP), (O), 0)) \\r
- return 0; \\r
-}\r
-\r
-/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use\r
- the ASDL name to synthesize the name of the C type and the visit function.\r
-*/\r
-\r
-#define VISIT(C, TYPE, V) {\\r
- if (!compiler_visit_ ## TYPE((C), (V))) \\r
- return 0; \\r
-}\r
-\r
-#define VISIT_IN_SCOPE(C, TYPE, V) {\\r
- if (!compiler_visit_ ## TYPE((C), (V))) { \\r
- compiler_exit_scope(c); \\r
- return 0; \\r
- } \\r
-}\r
-\r
-#define VISIT_SLICE(C, V, CTX) {\\r
- if (!compiler_visit_slice((C), (V), (CTX))) \\r
- return 0; \\r
-}\r
-\r
-#define VISIT_SEQ(C, TYPE, SEQ) { \\r
- int _i; \\r
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \\r
- for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \\r
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \\r
- if (!compiler_visit_ ## TYPE((C), elt)) \\r
- return 0; \\r
- } \\r
-}\r
-\r
-#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \\r
- int _i; \\r
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \\r
- for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \\r
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \\r
- if (!compiler_visit_ ## TYPE((C), elt)) { \\r
- compiler_exit_scope(c); \\r
- return 0; \\r
- } \\r
- } \\r
-}\r
-\r
-static int\r
-compiler_isdocstring(stmt_ty s)\r
-{\r
- if (s->kind != Expr_kind)\r
- return 0;\r
- return s->v.Expr.value->kind == Str_kind;\r
-}\r
-\r
-/* Compile a sequence of statements, checking for a docstring. */\r
-\r
-static int\r
-compiler_body(struct compiler *c, asdl_seq *stmts)\r
-{\r
- int i = 0;\r
- stmt_ty st;\r
-\r
- if (!asdl_seq_LEN(stmts))\r
- return 1;\r
- st = (stmt_ty)asdl_seq_GET(stmts, 0);\r
- if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {\r
- /* don't generate docstrings if -OO */\r
- i = 1;\r
- VISIT(c, expr, st->v.Expr.value);\r
- if (!compiler_nameop(c, __doc__, Store))\r
- return 0;\r
- }\r
- for (; i < asdl_seq_LEN(stmts); i++)\r
- VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));\r
- return 1;\r
-}\r
-\r
-static PyCodeObject *\r
-compiler_mod(struct compiler *c, mod_ty mod)\r
-{\r
- PyCodeObject *co;\r
- int addNone = 1;\r
- static PyObject *module;\r
- if (!module) {\r
- module = PyString_InternFromString("<module>");\r
- if (!module)\r
- return NULL;\r
- }\r
- /* Use 0 for firstlineno initially, will fixup in assemble(). */\r
- if (!compiler_enter_scope(c, module, mod, 0))\r
- return NULL;\r
- switch (mod->kind) {\r
- case Module_kind:\r
- if (!compiler_body(c, mod->v.Module.body)) {\r
- compiler_exit_scope(c);\r
- return 0;\r
- }\r
- break;\r
- case Interactive_kind:\r
- c->c_interactive = 1;\r
- VISIT_SEQ_IN_SCOPE(c, stmt,\r
- mod->v.Interactive.body);\r
- break;\r
- case Expression_kind:\r
- VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);\r
- addNone = 0;\r
- break;\r
- case Suite_kind:\r
- PyErr_SetString(PyExc_SystemError,\r
- "suite should not be possible");\r
- return 0;\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "module kind %d should not be possible",\r
- mod->kind);\r
- return 0;\r
- }\r
- co = assemble(c, addNone);\r
- compiler_exit_scope(c);\r
- return co;\r
-}\r
-\r
-/* The test for LOCAL must come before the test for FREE in order to\r
- handle classes where name is both local and free. The local var is\r
- a method and the free var is a free var referenced within a method.\r
-*/\r
-\r
-static int\r
-get_ref_type(struct compiler *c, PyObject *name)\r
-{\r
- int scope = PyST_GetScope(c->u->u_ste, name);\r
- if (scope == 0) {\r
- char buf[350];\r
- PyOS_snprintf(buf, sizeof(buf),\r
- "unknown scope for %.100s in %.100s(%s) in %s\n"\r
- "symbols: %s\nlocals: %s\nglobals: %s",\r
- PyString_AS_STRING(name),\r
- PyString_AS_STRING(c->u->u_name),\r
- PyObject_REPR(c->u->u_ste->ste_id),\r
- c->c_filename,\r
- PyObject_REPR(c->u->u_ste->ste_symbols),\r
- PyObject_REPR(c->u->u_varnames),\r
- PyObject_REPR(c->u->u_names)\r
- );\r
- Py_FatalError(buf);\r
- }\r
-\r
- return scope;\r
-}\r
-\r
-static int\r
-compiler_lookup_arg(PyObject *dict, PyObject *name)\r
-{\r
- PyObject *k, *v;\r
- k = PyTuple_Pack(2, name, name->ob_type);\r
- if (k == NULL)\r
- return -1;\r
- v = PyDict_GetItem(dict, k);\r
- Py_DECREF(k);\r
- if (v == NULL)\r
- return -1;\r
- return PyInt_AS_LONG(v);\r
-}\r
-\r
-static int\r
-compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)\r
-{\r
- int i, free = PyCode_GetNumFree(co);\r
- if (free == 0) {\r
- ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);\r
- ADDOP_I(c, MAKE_FUNCTION, args);\r
- return 1;\r
- }\r
- for (i = 0; i < free; ++i) {\r
- /* Bypass com_addop_varname because it will generate\r
- LOAD_DEREF but LOAD_CLOSURE is needed.\r
- */\r
- PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);\r
- int arg, reftype;\r
-\r
- /* Special case: If a class contains a method with a\r
- free variable that has the same name as a method,\r
- the name will be considered free *and* local in the\r
- class. It should be handled by the closure, as\r
- well as by the normal name loookup logic.\r
- */\r
- reftype = get_ref_type(c, name);\r
- if (reftype == CELL)\r
- arg = compiler_lookup_arg(c->u->u_cellvars, name);\r
- else /* (reftype == FREE) */\r
- arg = compiler_lookup_arg(c->u->u_freevars, name);\r
- if (arg == -1) {\r
- printf("lookup %s in %s %d %d\n"\r
- "freevars of %s: %s\n",\r
- PyObject_REPR(name),\r
- PyString_AS_STRING(c->u->u_name),\r
- reftype, arg,\r
- PyString_AS_STRING(co->co_name),\r
- PyObject_REPR(co->co_freevars));\r
- Py_FatalError("compiler_make_closure()");\r
- }\r
- ADDOP_I(c, LOAD_CLOSURE, arg);\r
- }\r
- ADDOP_I(c, BUILD_TUPLE, free);\r
- ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);\r
- ADDOP_I(c, MAKE_CLOSURE, args);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_decorators(struct compiler *c, asdl_seq* decos)\r
-{\r
- int i;\r
-\r
- if (!decos)\r
- return 1;\r
-\r
- for (i = 0; i < asdl_seq_LEN(decos); i++) {\r
- VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_arguments(struct compiler *c, arguments_ty args)\r
-{\r
- int i;\r
- int n = asdl_seq_LEN(args->args);\r
- /* Correctly handle nested argument lists */\r
- for (i = 0; i < n; i++) {\r
- expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);\r
- if (arg->kind == Tuple_kind) {\r
- PyObject *id = PyString_FromFormat(".%d", i);\r
- if (id == NULL) {\r
- return 0;\r
- }\r
- if (!compiler_nameop(c, id, Load)) {\r
- Py_DECREF(id);\r
- return 0;\r
- }\r
- Py_DECREF(id);\r
- VISIT(c, expr, arg);\r
- }\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_function(struct compiler *c, stmt_ty s)\r
-{\r
- PyCodeObject *co;\r
- PyObject *first_const = Py_None;\r
- arguments_ty args = s->v.FunctionDef.args;\r
- asdl_seq* decos = s->v.FunctionDef.decorator_list;\r
- stmt_ty st;\r
- int i, n, docstring;\r
-\r
- assert(s->kind == FunctionDef_kind);\r
-\r
- if (!compiler_decorators(c, decos))\r
- return 0;\r
- if (args->defaults)\r
- VISIT_SEQ(c, expr, args->defaults);\r
- if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,\r
- s->lineno))\r
- return 0;\r
-\r
- st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);\r
- docstring = compiler_isdocstring(st);\r
- if (docstring && Py_OptimizeFlag < 2)\r
- first_const = st->v.Expr.value->v.Str.s;\r
- if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {\r
- compiler_exit_scope(c);\r
- return 0;\r
- }\r
-\r
- /* unpack nested arguments */\r
- compiler_arguments(c, args);\r
-\r
- c->u->u_argcount = asdl_seq_LEN(args->args);\r
- n = asdl_seq_LEN(s->v.FunctionDef.body);\r
- /* if there was a docstring, we need to skip the first statement */\r
- for (i = docstring; i < n; i++) {\r
- st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);\r
- VISIT_IN_SCOPE(c, stmt, st);\r
- }\r
- co = assemble(c, 1);\r
- compiler_exit_scope(c);\r
- if (co == NULL)\r
- return 0;\r
-\r
- compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));\r
- Py_DECREF(co);\r
-\r
- for (i = 0; i < asdl_seq_LEN(decos); i++) {\r
- ADDOP_I(c, CALL_FUNCTION, 1);\r
- }\r
-\r
- return compiler_nameop(c, s->v.FunctionDef.name, Store);\r
-}\r
-\r
-static int\r
-compiler_class(struct compiler *c, stmt_ty s)\r
-{\r
- int n, i;\r
- PyCodeObject *co;\r
- PyObject *str;\r
- asdl_seq* decos = s->v.ClassDef.decorator_list;\r
-\r
- if (!compiler_decorators(c, decos))\r
- return 0;\r
-\r
- /* push class name on stack, needed by BUILD_CLASS */\r
- ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);\r
- /* push the tuple of base classes on the stack */\r
- n = asdl_seq_LEN(s->v.ClassDef.bases);\r
- if (n > 0)\r
- VISIT_SEQ(c, expr, s->v.ClassDef.bases);\r
- ADDOP_I(c, BUILD_TUPLE, n);\r
- if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,\r
- s->lineno))\r
- return 0;\r
- Py_XDECREF(c->u->u_private);\r
- c->u->u_private = s->v.ClassDef.name;\r
- Py_INCREF(c->u->u_private);\r
- str = PyString_InternFromString("__name__");\r
- if (!str || !compiler_nameop(c, str, Load)) {\r
- Py_XDECREF(str);\r
- compiler_exit_scope(c);\r
- return 0;\r
- }\r
-\r
- Py_DECREF(str);\r
- str = PyString_InternFromString("__module__");\r
- if (!str || !compiler_nameop(c, str, Store)) {\r
- Py_XDECREF(str);\r
- compiler_exit_scope(c);\r
- return 0;\r
- }\r
- Py_DECREF(str);\r
-\r
- if (!compiler_body(c, s->v.ClassDef.body)) {\r
- compiler_exit_scope(c);\r
- return 0;\r
- }\r
-\r
- ADDOP_IN_SCOPE(c, LOAD_LOCALS);\r
- ADDOP_IN_SCOPE(c, RETURN_VALUE);\r
- co = assemble(c, 1);\r
- compiler_exit_scope(c);\r
- if (co == NULL)\r
- return 0;\r
-\r
- compiler_make_closure(c, co, 0);\r
- Py_DECREF(co);\r
-\r
- ADDOP_I(c, CALL_FUNCTION, 0);\r
- ADDOP(c, BUILD_CLASS);\r
- /* apply decorators */\r
- for (i = 0; i < asdl_seq_LEN(decos); i++) {\r
- ADDOP_I(c, CALL_FUNCTION, 1);\r
- }\r
- if (!compiler_nameop(c, s->v.ClassDef.name, Store))\r
- return 0;\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_ifexp(struct compiler *c, expr_ty e)\r
-{\r
- basicblock *end, *next;\r
-\r
- assert(e->kind == IfExp_kind);\r
- end = compiler_new_block(c);\r
- if (end == NULL)\r
- return 0;\r
- next = compiler_new_block(c);\r
- if (next == NULL)\r
- return 0;\r
- VISIT(c, expr, e->v.IfExp.test);\r
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);\r
- VISIT(c, expr, e->v.IfExp.body);\r
- ADDOP_JREL(c, JUMP_FORWARD, end);\r
- compiler_use_next_block(c, next);\r
- VISIT(c, expr, e->v.IfExp.orelse);\r
- compiler_use_next_block(c, end);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_lambda(struct compiler *c, expr_ty e)\r
-{\r
- PyCodeObject *co;\r
- static identifier name;\r
- arguments_ty args = e->v.Lambda.args;\r
- assert(e->kind == Lambda_kind);\r
-\r
- if (!name) {\r
- name = PyString_InternFromString("<lambda>");\r
- if (!name)\r
- return 0;\r
- }\r
-\r
- if (args->defaults)\r
- VISIT_SEQ(c, expr, args->defaults);\r
- if (!compiler_enter_scope(c, name, (void *)e, e->lineno))\r
- return 0;\r
-\r
- /* unpack nested arguments */\r
- compiler_arguments(c, args);\r
-\r
- /* Make None the first constant, so the lambda can't have a\r
- docstring. */\r
- if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)\r
- return 0;\r
-\r
- c->u->u_argcount = asdl_seq_LEN(args->args);\r
- VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);\r
- if (c->u->u_ste->ste_generator) {\r
- ADDOP_IN_SCOPE(c, POP_TOP);\r
- }\r
- else {\r
- ADDOP_IN_SCOPE(c, RETURN_VALUE);\r
- }\r
- co = assemble(c, 1);\r
- compiler_exit_scope(c);\r
- if (co == NULL)\r
- return 0;\r
-\r
- compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));\r
- Py_DECREF(co);\r
-\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_print(struct compiler *c, stmt_ty s)\r
-{\r
- int i, n;\r
- bool dest;\r
-\r
- assert(s->kind == Print_kind);\r
- n = asdl_seq_LEN(s->v.Print.values);\r
- dest = false;\r
- if (s->v.Print.dest) {\r
- VISIT(c, expr, s->v.Print.dest);\r
- dest = true;\r
- }\r
- for (i = 0; i < n; i++) {\r
- expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);\r
- if (dest) {\r
- ADDOP(c, DUP_TOP);\r
- VISIT(c, expr, e);\r
- ADDOP(c, ROT_TWO);\r
- ADDOP(c, PRINT_ITEM_TO);\r
- }\r
- else {\r
- VISIT(c, expr, e);\r
- ADDOP(c, PRINT_ITEM);\r
- }\r
- }\r
- if (s->v.Print.nl) {\r
- if (dest)\r
- ADDOP(c, PRINT_NEWLINE_TO)\r
- else\r
- ADDOP(c, PRINT_NEWLINE)\r
- }\r
- else if (dest)\r
- ADDOP(c, POP_TOP);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_if(struct compiler *c, stmt_ty s)\r
-{\r
- basicblock *end, *next;\r
- int constant;\r
- assert(s->kind == If_kind);\r
- end = compiler_new_block(c);\r
- if (end == NULL)\r
- return 0;\r
-\r
- constant = expr_constant(s->v.If.test);\r
- /* constant = 0: "if 0"\r
- * constant = 1: "if 1", "if 2", ...\r
- * constant = -1: rest */\r
- if (constant == 0) {\r
- if (s->v.If.orelse)\r
- VISIT_SEQ(c, stmt, s->v.If.orelse);\r
- } else if (constant == 1) {\r
- VISIT_SEQ(c, stmt, s->v.If.body);\r
- } else {\r
- if (s->v.If.orelse) {\r
- next = compiler_new_block(c);\r
- if (next == NULL)\r
- return 0;\r
- }\r
- else\r
- next = end;\r
- VISIT(c, expr, s->v.If.test);\r
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);\r
- VISIT_SEQ(c, stmt, s->v.If.body);\r
- ADDOP_JREL(c, JUMP_FORWARD, end);\r
- if (s->v.If.orelse) {\r
- compiler_use_next_block(c, next);\r
- VISIT_SEQ(c, stmt, s->v.If.orelse);\r
- }\r
- }\r
- compiler_use_next_block(c, end);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_for(struct compiler *c, stmt_ty s)\r
-{\r
- basicblock *start, *cleanup, *end;\r
-\r
- start = compiler_new_block(c);\r
- cleanup = compiler_new_block(c);\r
- end = compiler_new_block(c);\r
- if (start == NULL || end == NULL || cleanup == NULL)\r
- return 0;\r
- ADDOP_JREL(c, SETUP_LOOP, end);\r
- if (!compiler_push_fblock(c, LOOP, start))\r
- return 0;\r
- VISIT(c, expr, s->v.For.iter);\r
- ADDOP(c, GET_ITER);\r
- compiler_use_next_block(c, start);\r
- ADDOP_JREL(c, FOR_ITER, cleanup);\r
- VISIT(c, expr, s->v.For.target);\r
- VISIT_SEQ(c, stmt, s->v.For.body);\r
- ADDOP_JABS(c, JUMP_ABSOLUTE, start);\r
- compiler_use_next_block(c, cleanup);\r
- ADDOP(c, POP_BLOCK);\r
- compiler_pop_fblock(c, LOOP, start);\r
- VISIT_SEQ(c, stmt, s->v.For.orelse);\r
- compiler_use_next_block(c, end);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_while(struct compiler *c, stmt_ty s)\r
-{\r
- basicblock *loop, *orelse, *end, *anchor = NULL;\r
- int constant = expr_constant(s->v.While.test);\r
-\r
- if (constant == 0) {\r
- if (s->v.While.orelse)\r
- VISIT_SEQ(c, stmt, s->v.While.orelse);\r
- return 1;\r
- }\r
- loop = compiler_new_block(c);\r
- end = compiler_new_block(c);\r
- if (constant == -1) {\r
- anchor = compiler_new_block(c);\r
- if (anchor == NULL)\r
- return 0;\r
- }\r
- if (loop == NULL || end == NULL)\r
- return 0;\r
- if (s->v.While.orelse) {\r
- orelse = compiler_new_block(c);\r
- if (orelse == NULL)\r
- return 0;\r
- }\r
- else\r
- orelse = NULL;\r
-\r
- ADDOP_JREL(c, SETUP_LOOP, end);\r
- compiler_use_next_block(c, loop);\r
- if (!compiler_push_fblock(c, LOOP, loop))\r
- return 0;\r
- if (constant == -1) {\r
- VISIT(c, expr, s->v.While.test);\r
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);\r
- }\r
- VISIT_SEQ(c, stmt, s->v.While.body);\r
- ADDOP_JABS(c, JUMP_ABSOLUTE, loop);\r
-\r
- /* XXX should the two POP instructions be in a separate block\r
- if there is no else clause ?\r
- */\r
-\r
- if (constant == -1) {\r
- compiler_use_next_block(c, anchor);\r
- ADDOP(c, POP_BLOCK);\r
- }\r
- compiler_pop_fblock(c, LOOP, loop);\r
- if (orelse != NULL) /* what if orelse is just pass? */\r
- VISIT_SEQ(c, stmt, s->v.While.orelse);\r
- compiler_use_next_block(c, end);\r
-\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_continue(struct compiler *c)\r
-{\r
- static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";\r
- static const char IN_FINALLY_ERROR_MSG[] =\r
- "'continue' not supported inside 'finally' clause";\r
- int i;\r
-\r
- if (!c->u->u_nfblocks)\r
- return compiler_error(c, LOOP_ERROR_MSG);\r
- i = c->u->u_nfblocks - 1;\r
- switch (c->u->u_fblock[i].fb_type) {\r
- case LOOP:\r
- ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);\r
- break;\r
- case EXCEPT:\r
- case FINALLY_TRY:\r
- while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {\r
- /* Prevent continue anywhere under a finally\r
- even if hidden in a sub-try or except. */\r
- if (c->u->u_fblock[i].fb_type == FINALLY_END)\r
- return compiler_error(c, IN_FINALLY_ERROR_MSG);\r
- }\r
- if (i == -1)\r
- return compiler_error(c, LOOP_ERROR_MSG);\r
- ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);\r
- break;\r
- case FINALLY_END:\r
- return compiler_error(c, IN_FINALLY_ERROR_MSG);\r
- }\r
-\r
- return 1;\r
-}\r
-\r
-/* Code generated for "try: <body> finally: <finalbody>" is as follows:\r
-\r
- SETUP_FINALLY L\r
- <code for body>\r
- POP_BLOCK\r
- LOAD_CONST <None>\r
- L: <code for finalbody>\r
- END_FINALLY\r
-\r
- The special instructions use the block stack. Each block\r
- stack entry contains the instruction that created it (here\r
- SETUP_FINALLY), the level of the value stack at the time the\r
- block stack entry was created, and a label (here L).\r
-\r
- SETUP_FINALLY:\r
- Pushes the current value stack level and the label\r
- onto the block stack.\r
- POP_BLOCK:\r
- Pops en entry from the block stack, and pops the value\r
- stack until its level is the same as indicated on the\r
- block stack. (The label is ignored.)\r
- END_FINALLY:\r
- Pops a variable number of entries from the *value* stack\r
- and re-raises the exception they specify. The number of\r
- entries popped depends on the (pseudo) exception type.\r
-\r
- The block stack is unwound when an exception is raised:\r
- when a SETUP_FINALLY entry is found, the exception is pushed\r
- onto the value stack (and the exception condition is cleared),\r
- and the interpreter jumps to the label gotten from the block\r
- stack.\r
-*/\r
-\r
-static int\r
-compiler_try_finally(struct compiler *c, stmt_ty s)\r
-{\r
- basicblock *body, *end;\r
- body = compiler_new_block(c);\r
- end = compiler_new_block(c);\r
- if (body == NULL || end == NULL)\r
- return 0;\r
-\r
- ADDOP_JREL(c, SETUP_FINALLY, end);\r
- compiler_use_next_block(c, body);\r
- if (!compiler_push_fblock(c, FINALLY_TRY, body))\r
- return 0;\r
- VISIT_SEQ(c, stmt, s->v.TryFinally.body);\r
- ADDOP(c, POP_BLOCK);\r
- compiler_pop_fblock(c, FINALLY_TRY, body);\r
-\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- compiler_use_next_block(c, end);\r
- if (!compiler_push_fblock(c, FINALLY_END, end))\r
- return 0;\r
- VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);\r
- ADDOP(c, END_FINALLY);\r
- compiler_pop_fblock(c, FINALLY_END, end);\r
-\r
- return 1;\r
-}\r
-\r
-/*\r
- Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":\r
- (The contents of the value stack is shown in [], with the top\r
- at the right; 'tb' is trace-back info, 'val' the exception's\r
- associated value, and 'exc' the exception.)\r
-\r
- Value stack Label Instruction Argument\r
- [] SETUP_EXCEPT L1\r
- [] <code for S>\r
- [] POP_BLOCK\r
- [] JUMP_FORWARD L0\r
-\r
- [tb, val, exc] L1: DUP )\r
- [tb, val, exc, exc] <evaluate E1> )\r
- [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1\r
- [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )\r
- [tb, val, exc] POP\r
- [tb, val] <assign to V1> (or POP if no V1)\r
- [tb] POP\r
- [] <code for S1>\r
- JUMP_FORWARD L0\r
-\r
- [tb, val, exc] L2: DUP\r
- .............................etc.......................\r
-\r
- [tb, val, exc] Ln+1: END_FINALLY # re-raise exception\r
-\r
- [] L0: <next statement>\r
-\r
- Of course, parts are not generated if Vi or Ei is not present.\r
-*/\r
-static int\r
-compiler_try_except(struct compiler *c, stmt_ty s)\r
-{\r
- basicblock *body, *orelse, *except, *end;\r
- int i, n;\r
-\r
- body = compiler_new_block(c);\r
- except = compiler_new_block(c);\r
- orelse = compiler_new_block(c);\r
- end = compiler_new_block(c);\r
- if (body == NULL || except == NULL || orelse == NULL || end == NULL)\r
- return 0;\r
- ADDOP_JREL(c, SETUP_EXCEPT, except);\r
- compiler_use_next_block(c, body);\r
- if (!compiler_push_fblock(c, EXCEPT, body))\r
- return 0;\r
- VISIT_SEQ(c, stmt, s->v.TryExcept.body);\r
- ADDOP(c, POP_BLOCK);\r
- compiler_pop_fblock(c, EXCEPT, body);\r
- ADDOP_JREL(c, JUMP_FORWARD, orelse);\r
- n = asdl_seq_LEN(s->v.TryExcept.handlers);\r
- compiler_use_next_block(c, except);\r
- for (i = 0; i < n; i++) {\r
- excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(\r
- s->v.TryExcept.handlers, i);\r
- if (!handler->v.ExceptHandler.type && i < n-1)\r
- return compiler_error(c, "default 'except:' must be last");\r
- c->u->u_lineno_set = false;\r
- c->u->u_lineno = handler->lineno;\r
- except = compiler_new_block(c);\r
- if (except == NULL)\r
- return 0;\r
- if (handler->v.ExceptHandler.type) {\r
- ADDOP(c, DUP_TOP);\r
- VISIT(c, expr, handler->v.ExceptHandler.type);\r
- ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);\r
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);\r
- }\r
- ADDOP(c, POP_TOP);\r
- if (handler->v.ExceptHandler.name) {\r
- VISIT(c, expr, handler->v.ExceptHandler.name);\r
- }\r
- else {\r
- ADDOP(c, POP_TOP);\r
- }\r
- ADDOP(c, POP_TOP);\r
- VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);\r
- ADDOP_JREL(c, JUMP_FORWARD, end);\r
- compiler_use_next_block(c, except);\r
- }\r
- ADDOP(c, END_FINALLY);\r
- compiler_use_next_block(c, orelse);\r
- VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);\r
- compiler_use_next_block(c, end);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_import_as(struct compiler *c, identifier name, identifier asname)\r
-{\r
- /* The IMPORT_NAME opcode was already generated. This function\r
- merely needs to bind the result to a name.\r
-\r
- If there is a dot in name, we need to split it and emit a\r
- LOAD_ATTR for each name.\r
- */\r
- const char *src = PyString_AS_STRING(name);\r
- const char *dot = strchr(src, '.');\r
- if (dot) {\r
- /* Consume the base module name to get the first attribute */\r
- src = dot + 1;\r
- while (dot) {\r
- /* NB src is only defined when dot != NULL */\r
- PyObject *attr;\r
- dot = strchr(src, '.');\r
- attr = PyString_FromStringAndSize(src,\r
- dot ? dot - src : strlen(src));\r
- if (!attr)\r
- return -1;\r
- ADDOP_O(c, LOAD_ATTR, attr, names);\r
- Py_DECREF(attr);\r
- src = dot + 1;\r
- }\r
- }\r
- return compiler_nameop(c, asname, Store);\r
-}\r
-\r
-static int\r
-compiler_import(struct compiler *c, stmt_ty s)\r
-{\r
- /* The Import node stores a module name like a.b.c as a single\r
- string. This is convenient for all cases except\r
- import a.b.c as d\r
- where we need to parse that string to extract the individual\r
- module names.\r
- XXX Perhaps change the representation to make this case simpler?\r
- */\r
- int i, n = asdl_seq_LEN(s->v.Import.names);\r
-\r
- for (i = 0; i < n; i++) {\r
- alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);\r
- int r;\r
- PyObject *level;\r
-\r
- if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))\r
- level = PyInt_FromLong(0);\r
- else\r
- level = PyInt_FromLong(-1);\r
-\r
- if (level == NULL)\r
- return 0;\r
-\r
- ADDOP_O(c, LOAD_CONST, level, consts);\r
- Py_DECREF(level);\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- ADDOP_NAME(c, IMPORT_NAME, alias->name, names);\r
-\r
- if (alias->asname) {\r
- r = compiler_import_as(c, alias->name, alias->asname);\r
- if (!r)\r
- return r;\r
- }\r
- else {\r
- identifier tmp = alias->name;\r
- const char *base = PyString_AS_STRING(alias->name);\r
- char *dot = strchr(base, '.');\r
- if (dot)\r
- tmp = PyString_FromStringAndSize(base,\r
- dot - base);\r
- r = compiler_nameop(c, tmp, Store);\r
- if (dot) {\r
- Py_DECREF(tmp);\r
- }\r
- if (!r)\r
- return r;\r
- }\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_from_import(struct compiler *c, stmt_ty s)\r
-{\r
- int i, n = asdl_seq_LEN(s->v.ImportFrom.names);\r
-\r
- PyObject *names = PyTuple_New(n);\r
- PyObject *level;\r
- static PyObject *empty_string;\r
-\r
- if (!empty_string) {\r
- empty_string = PyString_FromString("");\r
- if (!empty_string)\r
- return 0;\r
- }\r
-\r
- if (!names)\r
- return 0;\r
-\r
- if (s->v.ImportFrom.level == 0 && c->c_flags &&\r
- !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))\r
- level = PyInt_FromLong(-1);\r
- else\r
- level = PyInt_FromLong(s->v.ImportFrom.level);\r
-\r
- if (!level) {\r
- Py_DECREF(names);\r
- return 0;\r
- }\r
-\r
- /* build up the names */\r
- for (i = 0; i < n; i++) {\r
- alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);\r
- Py_INCREF(alias->name);\r
- PyTuple_SET_ITEM(names, i, alias->name);\r
- }\r
-\r
- if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&\r
- !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {\r
- Py_DECREF(level);\r
- Py_DECREF(names);\r
- return compiler_error(c, "from __future__ imports must occur "\r
- "at the beginning of the file");\r
- }\r
-\r
- ADDOP_O(c, LOAD_CONST, level, consts);\r
- Py_DECREF(level);\r
- ADDOP_O(c, LOAD_CONST, names, consts);\r
- Py_DECREF(names);\r
- if (s->v.ImportFrom.module) {\r
- ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);\r
- }\r
- else {\r
- ADDOP_NAME(c, IMPORT_NAME, empty_string, names);\r
- }\r
- for (i = 0; i < n; i++) {\r
- alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);\r
- identifier store_name;\r
-\r
- if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {\r
- assert(n == 1);\r
- ADDOP(c, IMPORT_STAR);\r
- return 1;\r
- }\r
-\r
- ADDOP_NAME(c, IMPORT_FROM, alias->name, names);\r
- store_name = alias->name;\r
- if (alias->asname)\r
- store_name = alias->asname;\r
-\r
- if (!compiler_nameop(c, store_name, Store)) {\r
- Py_DECREF(names);\r
- return 0;\r
- }\r
- }\r
- /* remove imported module */\r
- ADDOP(c, POP_TOP);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_assert(struct compiler *c, stmt_ty s)\r
-{\r
- static PyObject *assertion_error = NULL;\r
- basicblock *end;\r
-\r
- if (Py_OptimizeFlag)\r
- return 1;\r
- if (assertion_error == NULL) {\r
- assertion_error = PyString_InternFromString("AssertionError");\r
- if (assertion_error == NULL)\r
- return 0;\r
- }\r
- if (s->v.Assert.test->kind == Tuple_kind &&\r
- asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {\r
- const char* msg =\r
- "assertion is always true, perhaps remove parentheses?";\r
- if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,\r
- c->u->u_lineno, NULL, NULL) == -1)\r
- return 0;\r
- }\r
- VISIT(c, expr, s->v.Assert.test);\r
- end = compiler_new_block(c);\r
- if (end == NULL)\r
- return 0;\r
- ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);\r
- ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);\r
- if (s->v.Assert.msg) {\r
- VISIT(c, expr, s->v.Assert.msg);\r
- ADDOP_I(c, RAISE_VARARGS, 2);\r
- }\r
- else {\r
- ADDOP_I(c, RAISE_VARARGS, 1);\r
- }\r
- compiler_use_next_block(c, end);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_visit_stmt(struct compiler *c, stmt_ty s)\r
-{\r
- int i, n;\r
-\r
- /* Always assign a lineno to the next instruction for a stmt. */\r
- c->u->u_lineno = s->lineno;\r
- c->u->u_lineno_set = false;\r
-\r
- switch (s->kind) {\r
- case FunctionDef_kind:\r
- return compiler_function(c, s);\r
- case ClassDef_kind:\r
- return compiler_class(c, s);\r
- case Return_kind:\r
- if (c->u->u_ste->ste_type != FunctionBlock)\r
- return compiler_error(c, "'return' outside function");\r
- if (s->v.Return.value) {\r
- VISIT(c, expr, s->v.Return.value);\r
- }\r
- else\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- ADDOP(c, RETURN_VALUE);\r
- break;\r
- case Delete_kind:\r
- VISIT_SEQ(c, expr, s->v.Delete.targets)\r
- break;\r
- case Assign_kind:\r
- n = asdl_seq_LEN(s->v.Assign.targets);\r
- VISIT(c, expr, s->v.Assign.value);\r
- for (i = 0; i < n; i++) {\r
- if (i < n - 1)\r
- ADDOP(c, DUP_TOP);\r
- VISIT(c, expr,\r
- (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));\r
- }\r
- break;\r
- case AugAssign_kind:\r
- return compiler_augassign(c, s);\r
- case Print_kind:\r
- return compiler_print(c, s);\r
- case For_kind:\r
- return compiler_for(c, s);\r
- case While_kind:\r
- return compiler_while(c, s);\r
- case If_kind:\r
- return compiler_if(c, s);\r
- case Raise_kind:\r
- n = 0;\r
- if (s->v.Raise.type) {\r
- VISIT(c, expr, s->v.Raise.type);\r
- n++;\r
- if (s->v.Raise.inst) {\r
- VISIT(c, expr, s->v.Raise.inst);\r
- n++;\r
- if (s->v.Raise.tback) {\r
- VISIT(c, expr, s->v.Raise.tback);\r
- n++;\r
- }\r
- }\r
- }\r
- ADDOP_I(c, RAISE_VARARGS, n);\r
- break;\r
- case TryExcept_kind:\r
- return compiler_try_except(c, s);\r
- case TryFinally_kind:\r
- return compiler_try_finally(c, s);\r
- case Assert_kind:\r
- return compiler_assert(c, s);\r
- case Import_kind:\r
- return compiler_import(c, s);\r
- case ImportFrom_kind:\r
- return compiler_from_import(c, s);\r
- case Exec_kind:\r
- VISIT(c, expr, s->v.Exec.body);\r
- if (s->v.Exec.globals) {\r
- VISIT(c, expr, s->v.Exec.globals);\r
- if (s->v.Exec.locals) {\r
- VISIT(c, expr, s->v.Exec.locals);\r
- } else {\r
- ADDOP(c, DUP_TOP);\r
- }\r
- } else {\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- ADDOP(c, DUP_TOP);\r
- }\r
- ADDOP(c, EXEC_STMT);\r
- break;\r
- case Global_kind:\r
- break;\r
- case Expr_kind:\r
- if (c->c_interactive && c->c_nestlevel <= 1) {\r
- VISIT(c, expr, s->v.Expr.value);\r
- ADDOP(c, PRINT_EXPR);\r
- }\r
- else if (s->v.Expr.value->kind != Str_kind &&\r
- s->v.Expr.value->kind != Num_kind) {\r
- VISIT(c, expr, s->v.Expr.value);\r
- ADDOP(c, POP_TOP);\r
- }\r
- break;\r
- case Pass_kind:\r
- break;\r
- case Break_kind:\r
- if (!compiler_in_loop(c))\r
- return compiler_error(c, "'break' outside loop");\r
- ADDOP(c, BREAK_LOOP);\r
- break;\r
- case Continue_kind:\r
- return compiler_continue(c);\r
- case With_kind:\r
- return compiler_with(c, s);\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-unaryop(unaryop_ty op)\r
-{\r
- switch (op) {\r
- case Invert:\r
- return UNARY_INVERT;\r
- case Not:\r
- return UNARY_NOT;\r
- case UAdd:\r
- return UNARY_POSITIVE;\r
- case USub:\r
- return UNARY_NEGATIVE;\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "unary op %d should not be possible", op);\r
- return 0;\r
- }\r
-}\r
-\r
-static int\r
-binop(struct compiler *c, operator_ty op)\r
-{\r
- switch (op) {\r
- case Add:\r
- return BINARY_ADD;\r
- case Sub:\r
- return BINARY_SUBTRACT;\r
- case Mult:\r
- return BINARY_MULTIPLY;\r
- case Div:\r
- if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)\r
- return BINARY_TRUE_DIVIDE;\r
- else\r
- return BINARY_DIVIDE;\r
- case Mod:\r
- return BINARY_MODULO;\r
- case Pow:\r
- return BINARY_POWER;\r
- case LShift:\r
- return BINARY_LSHIFT;\r
- case RShift:\r
- return BINARY_RSHIFT;\r
- case BitOr:\r
- return BINARY_OR;\r
- case BitXor:\r
- return BINARY_XOR;\r
- case BitAnd:\r
- return BINARY_AND;\r
- case FloorDiv:\r
- return BINARY_FLOOR_DIVIDE;\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "binary op %d should not be possible", op);\r
- return 0;\r
- }\r
-}\r
-\r
-static int\r
-cmpop(cmpop_ty op)\r
-{\r
- switch (op) {\r
- case Eq:\r
- return PyCmp_EQ;\r
- case NotEq:\r
- return PyCmp_NE;\r
- case Lt:\r
- return PyCmp_LT;\r
- case LtE:\r
- return PyCmp_LE;\r
- case Gt:\r
- return PyCmp_GT;\r
- case GtE:\r
- return PyCmp_GE;\r
- case Is:\r
- return PyCmp_IS;\r
- case IsNot:\r
- return PyCmp_IS_NOT;\r
- case In:\r
- return PyCmp_IN;\r
- case NotIn:\r
- return PyCmp_NOT_IN;\r
- default:\r
- return PyCmp_BAD;\r
- }\r
-}\r
-\r
-static int\r
-inplace_binop(struct compiler *c, operator_ty op)\r
-{\r
- switch (op) {\r
- case Add:\r
- return INPLACE_ADD;\r
- case Sub:\r
- return INPLACE_SUBTRACT;\r
- case Mult:\r
- return INPLACE_MULTIPLY;\r
- case Div:\r
- if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)\r
- return INPLACE_TRUE_DIVIDE;\r
- else\r
- return INPLACE_DIVIDE;\r
- case Mod:\r
- return INPLACE_MODULO;\r
- case Pow:\r
- return INPLACE_POWER;\r
- case LShift:\r
- return INPLACE_LSHIFT;\r
- case RShift:\r
- return INPLACE_RSHIFT;\r
- case BitOr:\r
- return INPLACE_OR;\r
- case BitXor:\r
- return INPLACE_XOR;\r
- case BitAnd:\r
- return INPLACE_AND;\r
- case FloorDiv:\r
- return INPLACE_FLOOR_DIVIDE;\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "inplace binary op %d should not be possible", op);\r
- return 0;\r
- }\r
-}\r
-\r
-static int\r
-compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)\r
-{\r
- int op, scope, arg;\r
- enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;\r
-\r
- PyObject *dict = c->u->u_names;\r
- PyObject *mangled;\r
- /* XXX AugStore isn't used anywhere! */\r
-\r
- mangled = _Py_Mangle(c->u->u_private, name);\r
- if (!mangled)\r
- return 0;\r
-\r
- op = 0;\r
- optype = OP_NAME;\r
- scope = PyST_GetScope(c->u->u_ste, mangled);\r
- switch (scope) {\r
- case FREE:\r
- dict = c->u->u_freevars;\r
- optype = OP_DEREF;\r
- break;\r
- case CELL:\r
- dict = c->u->u_cellvars;\r
- optype = OP_DEREF;\r
- break;\r
- case LOCAL:\r
- if (c->u->u_ste->ste_type == FunctionBlock)\r
- optype = OP_FAST;\r
- break;\r
- case GLOBAL_IMPLICIT:\r
- if (c->u->u_ste->ste_type == FunctionBlock &&\r
- !c->u->u_ste->ste_unoptimized)\r
- optype = OP_GLOBAL;\r
- break;\r
- case GLOBAL_EXPLICIT:\r
- optype = OP_GLOBAL;\r
- break;\r
- default:\r
- /* scope can be 0 */\r
- break;\r
- }\r
-\r
- /* XXX Leave assert here, but handle __doc__ and the like better */\r
- assert(scope || PyString_AS_STRING(name)[0] == '_');\r
-\r
- switch (optype) {\r
- case OP_DEREF:\r
- switch (ctx) {\r
- case Load: op = LOAD_DEREF; break;\r
- case Store: op = STORE_DEREF; break;\r
- case AugLoad:\r
- case AugStore:\r
- break;\r
- case Del:\r
- PyErr_Format(PyExc_SyntaxError,\r
- "can not delete variable '%s' referenced "\r
- "in nested scope",\r
- PyString_AS_STRING(name));\r
- Py_DECREF(mangled);\r
- return 0;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid for deref variable");\r
- return 0;\r
- }\r
- break;\r
- case OP_FAST:\r
- switch (ctx) {\r
- case Load: op = LOAD_FAST; break;\r
- case Store: op = STORE_FAST; break;\r
- case Del: op = DELETE_FAST; break;\r
- case AugLoad:\r
- case AugStore:\r
- break;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid for local variable");\r
- return 0;\r
- }\r
- ADDOP_O(c, op, mangled, varnames);\r
- Py_DECREF(mangled);\r
- return 1;\r
- case OP_GLOBAL:\r
- switch (ctx) {\r
- case Load: op = LOAD_GLOBAL; break;\r
- case Store: op = STORE_GLOBAL; break;\r
- case Del: op = DELETE_GLOBAL; break;\r
- case AugLoad:\r
- case AugStore:\r
- break;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid for global variable");\r
- return 0;\r
- }\r
- break;\r
- case OP_NAME:\r
- switch (ctx) {\r
- case Load: op = LOAD_NAME; break;\r
- case Store: op = STORE_NAME; break;\r
- case Del: op = DELETE_NAME; break;\r
- case AugLoad:\r
- case AugStore:\r
- break;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid for name variable");\r
- return 0;\r
- }\r
- break;\r
- }\r
-\r
- assert(op);\r
- arg = compiler_add_o(c, dict, mangled);\r
- Py_DECREF(mangled);\r
- if (arg < 0)\r
- return 0;\r
- return compiler_addop_i(c, op, arg);\r
-}\r
-\r
-static int\r
-compiler_boolop(struct compiler *c, expr_ty e)\r
-{\r
- basicblock *end;\r
- int jumpi, i, n;\r
- asdl_seq *s;\r
-\r
- assert(e->kind == BoolOp_kind);\r
- if (e->v.BoolOp.op == And)\r
- jumpi = JUMP_IF_FALSE_OR_POP;\r
- else\r
- jumpi = JUMP_IF_TRUE_OR_POP;\r
- end = compiler_new_block(c);\r
- if (end == NULL)\r
- return 0;\r
- s = e->v.BoolOp.values;\r
- n = asdl_seq_LEN(s) - 1;\r
- assert(n >= 0);\r
- for (i = 0; i < n; ++i) {\r
- VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));\r
- ADDOP_JABS(c, jumpi, end);\r
- }\r
- VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));\r
- compiler_use_next_block(c, end);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_list(struct compiler *c, expr_ty e)\r
-{\r
- int n = asdl_seq_LEN(e->v.List.elts);\r
- if (e->v.List.ctx == Store) {\r
- ADDOP_I(c, UNPACK_SEQUENCE, n);\r
- }\r
- VISIT_SEQ(c, expr, e->v.List.elts);\r
- if (e->v.List.ctx == Load) {\r
- ADDOP_I(c, BUILD_LIST, n);\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_tuple(struct compiler *c, expr_ty e)\r
-{\r
- int n = asdl_seq_LEN(e->v.Tuple.elts);\r
- if (e->v.Tuple.ctx == Store) {\r
- ADDOP_I(c, UNPACK_SEQUENCE, n);\r
- }\r
- VISIT_SEQ(c, expr, e->v.Tuple.elts);\r
- if (e->v.Tuple.ctx == Load) {\r
- ADDOP_I(c, BUILD_TUPLE, n);\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_compare(struct compiler *c, expr_ty e)\r
-{\r
- int i, n;\r
- basicblock *cleanup = NULL;\r
-\r
- /* XXX the logic can be cleaned up for 1 or multiple comparisons */\r
- VISIT(c, expr, e->v.Compare.left);\r
- n = asdl_seq_LEN(e->v.Compare.ops);\r
- assert(n > 0);\r
- if (n > 1) {\r
- cleanup = compiler_new_block(c);\r
- if (cleanup == NULL)\r
- return 0;\r
- VISIT(c, expr,\r
- (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));\r
- }\r
- for (i = 1; i < n; i++) {\r
- ADDOP(c, DUP_TOP);\r
- ADDOP(c, ROT_THREE);\r
- ADDOP_I(c, COMPARE_OP,\r
- cmpop((cmpop_ty)(asdl_seq_GET(\r
- e->v.Compare.ops, i - 1))));\r
- ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);\r
- NEXT_BLOCK(c);\r
- if (i < (n - 1))\r
- VISIT(c, expr,\r
- (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));\r
- }\r
- VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));\r
- ADDOP_I(c, COMPARE_OP,\r
- cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));\r
- if (n > 1) {\r
- basicblock *end = compiler_new_block(c);\r
- if (end == NULL)\r
- return 0;\r
- ADDOP_JREL(c, JUMP_FORWARD, end);\r
- compiler_use_next_block(c, cleanup);\r
- ADDOP(c, ROT_TWO);\r
- ADDOP(c, POP_TOP);\r
- compiler_use_next_block(c, end);\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_call(struct compiler *c, expr_ty e)\r
-{\r
- int n, code = 0;\r
-\r
- VISIT(c, expr, e->v.Call.func);\r
- n = asdl_seq_LEN(e->v.Call.args);\r
- VISIT_SEQ(c, expr, e->v.Call.args);\r
- if (e->v.Call.keywords) {\r
- VISIT_SEQ(c, keyword, e->v.Call.keywords);\r
- n |= asdl_seq_LEN(e->v.Call.keywords) << 8;\r
- }\r
- if (e->v.Call.starargs) {\r
- VISIT(c, expr, e->v.Call.starargs);\r
- code |= 1;\r
- }\r
- if (e->v.Call.kwargs) {\r
- VISIT(c, expr, e->v.Call.kwargs);\r
- code |= 2;\r
- }\r
- switch (code) {\r
- case 0:\r
- ADDOP_I(c, CALL_FUNCTION, n);\r
- break;\r
- case 1:\r
- ADDOP_I(c, CALL_FUNCTION_VAR, n);\r
- break;\r
- case 2:\r
- ADDOP_I(c, CALL_FUNCTION_KW, n);\r
- break;\r
- case 3:\r
- ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);\r
- break;\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,\r
- int gen_index, expr_ty elt)\r
-{\r
- /* generate code for the iterator, then each of the ifs,\r
- and then write to the element */\r
-\r
- comprehension_ty l;\r
- basicblock *start, *anchor, *skip, *if_cleanup;\r
- int i, n;\r
-\r
- start = compiler_new_block(c);\r
- skip = compiler_new_block(c);\r
- if_cleanup = compiler_new_block(c);\r
- anchor = compiler_new_block(c);\r
-\r
- if (start == NULL || skip == NULL || if_cleanup == NULL ||\r
- anchor == NULL)\r
- return 0;\r
-\r
- l = (comprehension_ty)asdl_seq_GET(generators, gen_index);\r
- VISIT(c, expr, l->iter);\r
- ADDOP(c, GET_ITER);\r
- compiler_use_next_block(c, start);\r
- ADDOP_JREL(c, FOR_ITER, anchor);\r
- NEXT_BLOCK(c);\r
- VISIT(c, expr, l->target);\r
-\r
- /* XXX this needs to be cleaned up...a lot! */\r
- n = asdl_seq_LEN(l->ifs);\r
- for (i = 0; i < n; i++) {\r
- expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);\r
- VISIT(c, expr, e);\r
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);\r
- NEXT_BLOCK(c);\r
- }\r
-\r
- if (++gen_index < asdl_seq_LEN(generators))\r
- if (!compiler_listcomp_generator(c, generators, gen_index, elt))\r
- return 0;\r
-\r
- /* only append after the last for generator */\r
- if (gen_index >= asdl_seq_LEN(generators)) {\r
- VISIT(c, expr, elt);\r
- ADDOP_I(c, LIST_APPEND, gen_index+1);\r
-\r
- compiler_use_next_block(c, skip);\r
- }\r
- compiler_use_next_block(c, if_cleanup);\r
- ADDOP_JABS(c, JUMP_ABSOLUTE, start);\r
- compiler_use_next_block(c, anchor);\r
-\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_listcomp(struct compiler *c, expr_ty e)\r
-{\r
- assert(e->kind == ListComp_kind);\r
- ADDOP_I(c, BUILD_LIST, 0);\r
- return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,\r
- e->v.ListComp.elt);\r
-}\r
-\r
-/* Dict and set comprehensions and generator expressions work by creating a\r
- nested function to perform the actual iteration. This means that the\r
- iteration variables don't leak into the current scope.\r
- The defined function is called immediately following its definition, with the\r
- result of that call being the result of the expression.\r
- The LC/SC version returns the populated container, while the GE version is\r
- flagged in symtable.c as a generator, so it returns the generator object\r
- when the function is called.\r
- This code *knows* that the loop cannot contain break, continue, or return,\r
- so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.\r
-\r
- Possible cleanups:\r
- - iterate over the generator sequence instead of using recursion\r
-*/\r
-\r
-static int\r
-compiler_comprehension_generator(struct compiler *c,\r
- asdl_seq *generators, int gen_index,\r
- expr_ty elt, expr_ty val, int type)\r
-{\r
- /* generate code for the iterator, then each of the ifs,\r
- and then write to the element */\r
-\r
- comprehension_ty gen;\r
- basicblock *start, *anchor, *skip, *if_cleanup;\r
- int i, n;\r
-\r
- start = compiler_new_block(c);\r
- skip = compiler_new_block(c);\r
- if_cleanup = compiler_new_block(c);\r
- anchor = compiler_new_block(c);\r
-\r
- if (start == NULL || skip == NULL || if_cleanup == NULL ||\r
- anchor == NULL)\r
- return 0;\r
-\r
- gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);\r
-\r
- if (gen_index == 0) {\r
- /* Receive outermost iter as an implicit argument */\r
- c->u->u_argcount = 1;\r
- ADDOP_I(c, LOAD_FAST, 0);\r
- }\r
- else {\r
- /* Sub-iter - calculate on the fly */\r
- VISIT(c, expr, gen->iter);\r
- ADDOP(c, GET_ITER);\r
- }\r
- compiler_use_next_block(c, start);\r
- ADDOP_JREL(c, FOR_ITER, anchor);\r
- NEXT_BLOCK(c);\r
- VISIT(c, expr, gen->target);\r
-\r
- /* XXX this needs to be cleaned up...a lot! */\r
- n = asdl_seq_LEN(gen->ifs);\r
- for (i = 0; i < n; i++) {\r
- expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);\r
- VISIT(c, expr, e);\r
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);\r
- NEXT_BLOCK(c);\r
- }\r
-\r
- if (++gen_index < asdl_seq_LEN(generators))\r
- if (!compiler_comprehension_generator(c,\r
- generators, gen_index,\r
- elt, val, type))\r
- return 0;\r
-\r
- /* only append after the last for generator */\r
- if (gen_index >= asdl_seq_LEN(generators)) {\r
- /* comprehension specific code */\r
- switch (type) {\r
- case COMP_GENEXP:\r
- VISIT(c, expr, elt);\r
- ADDOP(c, YIELD_VALUE);\r
- ADDOP(c, POP_TOP);\r
- break;\r
- case COMP_SETCOMP:\r
- VISIT(c, expr, elt);\r
- ADDOP_I(c, SET_ADD, gen_index + 1);\r
- break;\r
- case COMP_DICTCOMP:\r
- /* With 'd[k] = v', v is evaluated before k, so we do\r
- the same. */\r
- VISIT(c, expr, val);\r
- VISIT(c, expr, elt);\r
- ADDOP_I(c, MAP_ADD, gen_index + 1);\r
- break;\r
- default:\r
- return 0;\r
- }\r
-\r
- compiler_use_next_block(c, skip);\r
- }\r
- compiler_use_next_block(c, if_cleanup);\r
- ADDOP_JABS(c, JUMP_ABSOLUTE, start);\r
- compiler_use_next_block(c, anchor);\r
-\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,\r
- asdl_seq *generators, expr_ty elt, expr_ty val)\r
-{\r
- PyCodeObject *co = NULL;\r
- expr_ty outermost_iter;\r
-\r
- outermost_iter = ((comprehension_ty)\r
- asdl_seq_GET(generators, 0))->iter;\r
-\r
- if (!compiler_enter_scope(c, name, (void *)e, e->lineno))\r
- goto error;\r
-\r
- if (type != COMP_GENEXP) {\r
- int op;\r
- switch (type) {\r
- case COMP_SETCOMP:\r
- op = BUILD_SET;\r
- break;\r
- case COMP_DICTCOMP:\r
- op = BUILD_MAP;\r
- break;\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "unknown comprehension type %d", type);\r
- goto error_in_scope;\r
- }\r
-\r
- ADDOP_I(c, op, 0);\r
- }\r
-\r
- if (!compiler_comprehension_generator(c, generators, 0, elt,\r
- val, type))\r
- goto error_in_scope;\r
-\r
- if (type != COMP_GENEXP) {\r
- ADDOP(c, RETURN_VALUE);\r
- }\r
-\r
- co = assemble(c, 1);\r
- compiler_exit_scope(c);\r
- if (co == NULL)\r
- goto error;\r
-\r
- if (!compiler_make_closure(c, co, 0))\r
- goto error;\r
- Py_DECREF(co);\r
-\r
- VISIT(c, expr, outermost_iter);\r
- ADDOP(c, GET_ITER);\r
- ADDOP_I(c, CALL_FUNCTION, 1);\r
- return 1;\r
-error_in_scope:\r
- compiler_exit_scope(c);\r
-error:\r
- Py_XDECREF(co);\r
- return 0;\r
-}\r
-\r
-static int\r
-compiler_genexp(struct compiler *c, expr_ty e)\r
-{\r
- static identifier name;\r
- if (!name) {\r
- name = PyString_FromString("<genexpr>");\r
- if (!name)\r
- return 0;\r
- }\r
- assert(e->kind == GeneratorExp_kind);\r
- return compiler_comprehension(c, e, COMP_GENEXP, name,\r
- e->v.GeneratorExp.generators,\r
- e->v.GeneratorExp.elt, NULL);\r
-}\r
-\r
-static int\r
-compiler_setcomp(struct compiler *c, expr_ty e)\r
-{\r
- static identifier name;\r
- if (!name) {\r
- name = PyString_FromString("<setcomp>");\r
- if (!name)\r
- return 0;\r
- }\r
- assert(e->kind == SetComp_kind);\r
- return compiler_comprehension(c, e, COMP_SETCOMP, name,\r
- e->v.SetComp.generators,\r
- e->v.SetComp.elt, NULL);\r
-}\r
-\r
-static int\r
-compiler_dictcomp(struct compiler *c, expr_ty e)\r
-{\r
- static identifier name;\r
- if (!name) {\r
- name = PyString_FromString("<dictcomp>");\r
- if (!name)\r
- return 0;\r
- }\r
- assert(e->kind == DictComp_kind);\r
- return compiler_comprehension(c, e, COMP_DICTCOMP, name,\r
- e->v.DictComp.generators,\r
- e->v.DictComp.key, e->v.DictComp.value);\r
-}\r
-\r
-static int\r
-compiler_visit_keyword(struct compiler *c, keyword_ty k)\r
-{\r
- ADDOP_O(c, LOAD_CONST, k->arg, consts);\r
- VISIT(c, expr, k->value);\r
- return 1;\r
-}\r
-\r
-/* Test whether expression is constant. For constants, report\r
- whether they are true or false.\r
-\r
- Return values: 1 for true, 0 for false, -1 for non-constant.\r
- */\r
-\r
-static int\r
-expr_constant(expr_ty e)\r
-{\r
- switch (e->kind) {\r
- case Num_kind:\r
- return PyObject_IsTrue(e->v.Num.n);\r
- case Str_kind:\r
- return PyObject_IsTrue(e->v.Str.s);\r
- case Name_kind:\r
- /* __debug__ is not assignable, so we can optimize\r
- * it away in if and while statements */\r
- if (strcmp(PyString_AS_STRING(e->v.Name.id),\r
- "__debug__") == 0)\r
- return ! Py_OptimizeFlag;\r
- /* fall through */\r
- default:\r
- return -1;\r
- }\r
-}\r
-\r
-/*\r
- Implements the with statement from PEP 343.\r
-\r
- The semantics outlined in that PEP are as follows:\r
-\r
- with EXPR as VAR:\r
- BLOCK\r
-\r
- It is implemented roughly as:\r
-\r
- context = EXPR\r
- exit = context.__exit__ # not calling it\r
- value = context.__enter__()\r
- try:\r
- VAR = value # if VAR present in the syntax\r
- BLOCK\r
- finally:\r
- if an exception was raised:\r
- exc = copy of (exception, instance, traceback)\r
- else:\r
- exc = (None, None, None)\r
- exit(*exc)\r
- */\r
-static int\r
-compiler_with(struct compiler *c, stmt_ty s)\r
-{\r
- basicblock *block, *finally;\r
-\r
- assert(s->kind == With_kind);\r
-\r
- block = compiler_new_block(c);\r
- finally = compiler_new_block(c);\r
- if (!block || !finally)\r
- return 0;\r
-\r
- /* Evaluate EXPR */\r
- VISIT(c, expr, s->v.With.context_expr);\r
- ADDOP_JREL(c, SETUP_WITH, finally);\r
-\r
- /* SETUP_WITH pushes a finally block. */\r
- compiler_use_next_block(c, block);\r
- /* Note that the block is actually called SETUP_WITH in ceval.c, but\r
- functions the same as SETUP_FINALLY except that exceptions are\r
- normalized. */\r
- if (!compiler_push_fblock(c, FINALLY_TRY, block)) {\r
- return 0;\r
- }\r
-\r
- if (s->v.With.optional_vars) {\r
- VISIT(c, expr, s->v.With.optional_vars);\r
- }\r
- else {\r
- /* Discard result from context.__enter__() */\r
- ADDOP(c, POP_TOP);\r
- }\r
-\r
- /* BLOCK code */\r
- VISIT_SEQ(c, stmt, s->v.With.body);\r
-\r
- /* End of try block; start the finally block */\r
- ADDOP(c, POP_BLOCK);\r
- compiler_pop_fblock(c, FINALLY_TRY, block);\r
-\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- compiler_use_next_block(c, finally);\r
- if (!compiler_push_fblock(c, FINALLY_END, finally))\r
- return 0;\r
-\r
- /* Finally block starts; context.__exit__ is on the stack under\r
- the exception or return information. Just issue our magic\r
- opcode. */\r
- ADDOP(c, WITH_CLEANUP);\r
-\r
- /* Finally block ends. */\r
- ADDOP(c, END_FINALLY);\r
- compiler_pop_fblock(c, FINALLY_END, finally);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_visit_expr(struct compiler *c, expr_ty e)\r
-{\r
- int i, n;\r
-\r
- /* If expr e has a different line number than the last expr/stmt,\r
- set a new line number for the next instruction.\r
- */\r
- if (e->lineno > c->u->u_lineno) {\r
- c->u->u_lineno = e->lineno;\r
- c->u->u_lineno_set = false;\r
- }\r
- switch (e->kind) {\r
- case BoolOp_kind:\r
- return compiler_boolop(c, e);\r
- case BinOp_kind:\r
- VISIT(c, expr, e->v.BinOp.left);\r
- VISIT(c, expr, e->v.BinOp.right);\r
- ADDOP(c, binop(c, e->v.BinOp.op));\r
- break;\r
- case UnaryOp_kind:\r
- VISIT(c, expr, e->v.UnaryOp.operand);\r
- ADDOP(c, unaryop(e->v.UnaryOp.op));\r
- break;\r
- case Lambda_kind:\r
- return compiler_lambda(c, e);\r
- case IfExp_kind:\r
- return compiler_ifexp(c, e);\r
- case Dict_kind:\r
- n = asdl_seq_LEN(e->v.Dict.values);\r
- ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));\r
- for (i = 0; i < n; i++) {\r
- VISIT(c, expr,\r
- (expr_ty)asdl_seq_GET(e->v.Dict.values, i));\r
- VISIT(c, expr,\r
- (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));\r
- ADDOP(c, STORE_MAP);\r
- }\r
- break;\r
- case Set_kind:\r
- n = asdl_seq_LEN(e->v.Set.elts);\r
- VISIT_SEQ(c, expr, e->v.Set.elts);\r
- ADDOP_I(c, BUILD_SET, n);\r
- break;\r
- case ListComp_kind:\r
- return compiler_listcomp(c, e);\r
- case SetComp_kind:\r
- return compiler_setcomp(c, e);\r
- case DictComp_kind:\r
- return compiler_dictcomp(c, e);\r
- case GeneratorExp_kind:\r
- return compiler_genexp(c, e);\r
- case Yield_kind:\r
- if (c->u->u_ste->ste_type != FunctionBlock)\r
- return compiler_error(c, "'yield' outside function");\r
- if (e->v.Yield.value) {\r
- VISIT(c, expr, e->v.Yield.value);\r
- }\r
- else {\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- }\r
- ADDOP(c, YIELD_VALUE);\r
- break;\r
- case Compare_kind:\r
- return compiler_compare(c, e);\r
- case Call_kind:\r
- return compiler_call(c, e);\r
- case Repr_kind:\r
- VISIT(c, expr, e->v.Repr.value);\r
- ADDOP(c, UNARY_CONVERT);\r
- break;\r
- case Num_kind:\r
- ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);\r
- break;\r
- case Str_kind:\r
- ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);\r
- break;\r
- /* The following exprs can be assignment targets. */\r
- case Attribute_kind:\r
- if (e->v.Attribute.ctx != AugStore)\r
- VISIT(c, expr, e->v.Attribute.value);\r
- switch (e->v.Attribute.ctx) {\r
- case AugLoad:\r
- ADDOP(c, DUP_TOP);\r
- /* Fall through to load */\r
- case Load:\r
- ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);\r
- break;\r
- case AugStore:\r
- ADDOP(c, ROT_TWO);\r
- /* Fall through to save */\r
- case Store:\r
- ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);\r
- break;\r
- case Del:\r
- ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);\r
- break;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid in attribute expression");\r
- return 0;\r
- }\r
- break;\r
- case Subscript_kind:\r
- switch (e->v.Subscript.ctx) {\r
- case AugLoad:\r
- VISIT(c, expr, e->v.Subscript.value);\r
- VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);\r
- break;\r
- case Load:\r
- VISIT(c, expr, e->v.Subscript.value);\r
- VISIT_SLICE(c, e->v.Subscript.slice, Load);\r
- break;\r
- case AugStore:\r
- VISIT_SLICE(c, e->v.Subscript.slice, AugStore);\r
- break;\r
- case Store:\r
- VISIT(c, expr, e->v.Subscript.value);\r
- VISIT_SLICE(c, e->v.Subscript.slice, Store);\r
- break;\r
- case Del:\r
- VISIT(c, expr, e->v.Subscript.value);\r
- VISIT_SLICE(c, e->v.Subscript.slice, Del);\r
- break;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid in subscript expression");\r
- return 0;\r
- }\r
- break;\r
- case Name_kind:\r
- return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);\r
- /* child nodes of List and Tuple will have expr_context set */\r
- case List_kind:\r
- return compiler_list(c, e);\r
- case Tuple_kind:\r
- return compiler_tuple(c, e);\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_augassign(struct compiler *c, stmt_ty s)\r
-{\r
- expr_ty e = s->v.AugAssign.target;\r
- expr_ty auge;\r
-\r
- assert(s->kind == AugAssign_kind);\r
-\r
- switch (e->kind) {\r
- case Attribute_kind:\r
- auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,\r
- AugLoad, e->lineno, e->col_offset, c->c_arena);\r
- if (auge == NULL)\r
- return 0;\r
- VISIT(c, expr, auge);\r
- VISIT(c, expr, s->v.AugAssign.value);\r
- ADDOP(c, inplace_binop(c, s->v.AugAssign.op));\r
- auge->v.Attribute.ctx = AugStore;\r
- VISIT(c, expr, auge);\r
- break;\r
- case Subscript_kind:\r
- auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,\r
- AugLoad, e->lineno, e->col_offset, c->c_arena);\r
- if (auge == NULL)\r
- return 0;\r
- VISIT(c, expr, auge);\r
- VISIT(c, expr, s->v.AugAssign.value);\r
- ADDOP(c, inplace_binop(c, s->v.AugAssign.op));\r
- auge->v.Subscript.ctx = AugStore;\r
- VISIT(c, expr, auge);\r
- break;\r
- case Name_kind:\r
- if (!compiler_nameop(c, e->v.Name.id, Load))\r
- return 0;\r
- VISIT(c, expr, s->v.AugAssign.value);\r
- ADDOP(c, inplace_binop(c, s->v.AugAssign.op));\r
- return compiler_nameop(c, e->v.Name.id, Store);\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "invalid node type (%d) for augmented assignment",\r
- e->kind);\r
- return 0;\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)\r
-{\r
- struct fblockinfo *f;\r
- if (c->u->u_nfblocks >= CO_MAXBLOCKS) {\r
- PyErr_SetString(PyExc_SystemError,\r
- "too many statically nested blocks");\r
- return 0;\r
- }\r
- f = &c->u->u_fblock[c->u->u_nfblocks++];\r
- f->fb_type = t;\r
- f->fb_block = b;\r
- return 1;\r
-}\r
-\r
-static void\r
-compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)\r
-{\r
- struct compiler_unit *u = c->u;\r
- assert(u->u_nfblocks > 0);\r
- u->u_nfblocks--;\r
- assert(u->u_fblock[u->u_nfblocks].fb_type == t);\r
- assert(u->u_fblock[u->u_nfblocks].fb_block == b);\r
-}\r
-\r
-static int\r
-compiler_in_loop(struct compiler *c) {\r
- int i;\r
- struct compiler_unit *u = c->u;\r
- for (i = 0; i < u->u_nfblocks; ++i) {\r
- if (u->u_fblock[i].fb_type == LOOP)\r
- return 1;\r
- }\r
- return 0;\r
-}\r
-/* Raises a SyntaxError and returns 0.\r
- If something goes wrong, a different exception may be raised.\r
-*/\r
-\r
-static int\r
-compiler_error(struct compiler *c, const char *errstr)\r
-{\r
- PyObject *loc;\r
- PyObject *u = NULL, *v = NULL;\r
-\r
- loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);\r
- if (!loc) {\r
- Py_INCREF(Py_None);\r
- loc = Py_None;\r
- }\r
- u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,\r
- Py_None, loc);\r
- if (!u)\r
- goto exit;\r
- v = Py_BuildValue("(zO)", errstr, u);\r
- if (!v)\r
- goto exit;\r
- PyErr_SetObject(PyExc_SyntaxError, v);\r
- exit:\r
- Py_DECREF(loc);\r
- Py_XDECREF(u);\r
- Py_XDECREF(v);\r
- return 0;\r
-}\r
-\r
-static int\r
-compiler_handle_subscr(struct compiler *c, const char *kind,\r
- expr_context_ty ctx)\r
-{\r
- int op = 0;\r
-\r
- /* XXX this code is duplicated */\r
- switch (ctx) {\r
- case AugLoad: /* fall through to Load */\r
- case Load: op = BINARY_SUBSCR; break;\r
- case AugStore:/* fall through to Store */\r
- case Store: op = STORE_SUBSCR; break;\r
- case Del: op = DELETE_SUBSCR; break;\r
- case Param:\r
- PyErr_Format(PyExc_SystemError,\r
- "invalid %s kind %d in subscript\n",\r
- kind, ctx);\r
- return 0;\r
- }\r
- if (ctx == AugLoad) {\r
- ADDOP_I(c, DUP_TOPX, 2);\r
- }\r
- else if (ctx == AugStore) {\r
- ADDOP(c, ROT_THREE);\r
- }\r
- ADDOP(c, op);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)\r
-{\r
- int n = 2;\r
- assert(s->kind == Slice_kind);\r
-\r
- /* only handles the cases where BUILD_SLICE is emitted */\r
- if (s->v.Slice.lower) {\r
- VISIT(c, expr, s->v.Slice.lower);\r
- }\r
- else {\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- }\r
-\r
- if (s->v.Slice.upper) {\r
- VISIT(c, expr, s->v.Slice.upper);\r
- }\r
- else {\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- }\r
-\r
- if (s->v.Slice.step) {\r
- n++;\r
- VISIT(c, expr, s->v.Slice.step);\r
- }\r
- ADDOP_I(c, BUILD_SLICE, n);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)\r
-{\r
- int op = 0, slice_offset = 0, stack_count = 0;\r
-\r
- assert(s->v.Slice.step == NULL);\r
- if (s->v.Slice.lower) {\r
- slice_offset++;\r
- stack_count++;\r
- if (ctx != AugStore)\r
- VISIT(c, expr, s->v.Slice.lower);\r
- }\r
- if (s->v.Slice.upper) {\r
- slice_offset += 2;\r
- stack_count++;\r
- if (ctx != AugStore)\r
- VISIT(c, expr, s->v.Slice.upper);\r
- }\r
-\r
- if (ctx == AugLoad) {\r
- switch (stack_count) {\r
- case 0: ADDOP(c, DUP_TOP); break;\r
- case 1: ADDOP_I(c, DUP_TOPX, 2); break;\r
- case 2: ADDOP_I(c, DUP_TOPX, 3); break;\r
- }\r
- }\r
- else if (ctx == AugStore) {\r
- switch (stack_count) {\r
- case 0: ADDOP(c, ROT_TWO); break;\r
- case 1: ADDOP(c, ROT_THREE); break;\r
- case 2: ADDOP(c, ROT_FOUR); break;\r
- }\r
- }\r
-\r
- switch (ctx) {\r
- case AugLoad: /* fall through to Load */\r
- case Load: op = SLICE; break;\r
- case AugStore:/* fall through to Store */\r
- case Store: op = STORE_SLICE; break;\r
- case Del: op = DELETE_SLICE; break;\r
- case Param:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "param invalid in simple slice");\r
- return 0;\r
- }\r
-\r
- ADDOP(c, op + slice_offset);\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_visit_nested_slice(struct compiler *c, slice_ty s,\r
- expr_context_ty ctx)\r
-{\r
- switch (s->kind) {\r
- case Ellipsis_kind:\r
- ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);\r
- break;\r
- case Slice_kind:\r
- return compiler_slice(c, s, ctx);\r
- case Index_kind:\r
- VISIT(c, expr, s->v.Index.value);\r
- break;\r
- case ExtSlice_kind:\r
- default:\r
- PyErr_SetString(PyExc_SystemError,\r
- "extended slice invalid in nested slice");\r
- return 0;\r
- }\r
- return 1;\r
-}\r
-\r
-static int\r
-compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)\r
-{\r
- char * kindname = NULL;\r
- switch (s->kind) {\r
- case Index_kind:\r
- kindname = "index";\r
- if (ctx != AugStore) {\r
- VISIT(c, expr, s->v.Index.value);\r
- }\r
- break;\r
- case Ellipsis_kind:\r
- kindname = "ellipsis";\r
- if (ctx != AugStore) {\r
- ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);\r
- }\r
- break;\r
- case Slice_kind:\r
- kindname = "slice";\r
- if (!s->v.Slice.step)\r
- return compiler_simple_slice(c, s, ctx);\r
- if (ctx != AugStore) {\r
- if (!compiler_slice(c, s, ctx))\r
- return 0;\r
- }\r
- break;\r
- case ExtSlice_kind:\r
- kindname = "extended slice";\r
- if (ctx != AugStore) {\r
- int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);\r
- for (i = 0; i < n; i++) {\r
- slice_ty sub = (slice_ty)asdl_seq_GET(\r
- s->v.ExtSlice.dims, i);\r
- if (!compiler_visit_nested_slice(c, sub, ctx))\r
- return 0;\r
- }\r
- ADDOP_I(c, BUILD_TUPLE, n);\r
- }\r
- break;\r
- default:\r
- PyErr_Format(PyExc_SystemError,\r
- "invalid subscript kind %d", s->kind);\r
- return 0;\r
- }\r
- return compiler_handle_subscr(c, kindname, ctx);\r
-}\r
-\r
-\r
-/* End of the compiler section, beginning of the assembler section */\r
-\r
-/* do depth-first search of basic block graph, starting with block.\r
- post records the block indices in post-order.\r
-\r
- XXX must handle implicit jumps from one block to next\r
-*/\r
-\r
-struct assembler {\r
- PyObject *a_bytecode; /* string containing bytecode */\r
- int a_offset; /* offset into bytecode */\r
- int a_nblocks; /* number of reachable blocks */\r
- basicblock **a_postorder; /* list of blocks in dfs postorder */\r
- PyObject *a_lnotab; /* string containing lnotab */\r
- int a_lnotab_off; /* offset into lnotab */\r
- int a_lineno; /* last lineno of emitted instruction */\r
- int a_lineno_off; /* bytecode offset of last lineno */\r
-};\r
-\r
-static void\r
-dfs(struct compiler *c, basicblock *b, struct assembler *a)\r
-{\r
- int i;\r
- struct instr *instr = NULL;\r
-\r
- if (b->b_seen)\r
- return;\r
- b->b_seen = 1;\r
- if (b->b_next != NULL)\r
- dfs(c, b->b_next, a);\r
- for (i = 0; i < b->b_iused; i++) {\r
- instr = &b->b_instr[i];\r
- if (instr->i_jrel || instr->i_jabs)\r
- dfs(c, instr->i_target, a);\r
- }\r
- a->a_postorder[a->a_nblocks++] = b;\r
-}\r
-\r
-static int\r
-stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)\r
-{\r
- int i, target_depth;\r
- struct instr *instr;\r
- if (b->b_seen || b->b_startdepth >= depth)\r
- return maxdepth;\r
- b->b_seen = 1;\r
- b->b_startdepth = depth;\r
- for (i = 0; i < b->b_iused; i++) {\r
- instr = &b->b_instr[i];\r
- depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);\r
- if (depth > maxdepth)\r
- maxdepth = depth;\r
- assert(depth >= 0); /* invalid code or bug in stackdepth() */\r
- if (instr->i_jrel || instr->i_jabs) {\r
- target_depth = depth;\r
- if (instr->i_opcode == FOR_ITER) {\r
- target_depth = depth-2;\r
- } else if (instr->i_opcode == SETUP_FINALLY ||\r
- instr->i_opcode == SETUP_EXCEPT) {\r
- target_depth = depth+3;\r
- if (target_depth > maxdepth)\r
- maxdepth = target_depth;\r
- }\r
- maxdepth = stackdepth_walk(c, instr->i_target,\r
- target_depth, maxdepth);\r
- if (instr->i_opcode == JUMP_ABSOLUTE ||\r
- instr->i_opcode == JUMP_FORWARD) {\r
- goto out; /* remaining code is dead */\r
- }\r
- }\r
- }\r
- if (b->b_next)\r
- maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);\r
-out:\r
- b->b_seen = 0;\r
- return maxdepth;\r
-}\r
-\r
-/* Find the flow path that needs the largest stack. We assume that\r
- * cycles in the flow graph have no net effect on the stack depth.\r
- */\r
-static int\r
-stackdepth(struct compiler *c)\r
-{\r
- basicblock *b, *entryblock;\r
- entryblock = NULL;\r
- for (b = c->u->u_blocks; b != NULL; b = b->b_list) {\r
- b->b_seen = 0;\r
- b->b_startdepth = INT_MIN;\r
- entryblock = b;\r
- }\r
- if (!entryblock)\r
- return 0;\r
- return stackdepth_walk(c, entryblock, 0, 0);\r
-}\r
-\r
-static int\r
-assemble_init(struct assembler *a, int nblocks, int firstlineno)\r
-{\r
- memset(a, 0, sizeof(struct assembler));\r
- a->a_lineno = firstlineno;\r
- a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);\r
- if (!a->a_bytecode)\r
- return 0;\r
- a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);\r
- if (!a->a_lnotab)\r
- return 0;\r
- if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {\r
- PyErr_NoMemory();\r
- return 0;\r
- }\r
- a->a_postorder = (basicblock **)PyObject_Malloc(\r
- sizeof(basicblock *) * nblocks);\r
- if (!a->a_postorder) {\r
- PyErr_NoMemory();\r
- return 0;\r
- }\r
- return 1;\r
-}\r
-\r
-static void\r
-assemble_free(struct assembler *a)\r
-{\r
- Py_XDECREF(a->a_bytecode);\r
- Py_XDECREF(a->a_lnotab);\r
- if (a->a_postorder)\r
- PyObject_Free(a->a_postorder);\r
-}\r
-\r
-/* Return the size of a basic block in bytes. */\r
-\r
-static int\r
-instrsize(struct instr *instr)\r
-{\r
- if (!instr->i_hasarg)\r
- return 1; /* 1 byte for the opcode*/\r
- if (instr->i_oparg > 0xffff)\r
- return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */\r
- return 3; /* 1 (opcode) + 2 (oparg) */\r
-}\r
-\r
-static int\r
-blocksize(basicblock *b)\r
-{\r
- int i;\r
- int size = 0;\r
-\r
- for (i = 0; i < b->b_iused; i++)\r
- size += instrsize(&b->b_instr[i]);\r
- return size;\r
-}\r
-\r
-/* Appends a pair to the end of the line number table, a_lnotab, representing\r
- the instruction's bytecode offset and line number. See\r
- Objects/lnotab_notes.txt for the description of the line number table. */\r
-\r
-static int\r
-assemble_lnotab(struct assembler *a, struct instr *i)\r
-{\r
- int d_bytecode, d_lineno;\r
- int len;\r
- unsigned char *lnotab;\r
-\r
- d_bytecode = a->a_offset - a->a_lineno_off;\r
- d_lineno = i->i_lineno - a->a_lineno;\r
-\r
- assert(d_bytecode >= 0);\r
- assert(d_lineno >= 0);\r
-\r
- if(d_bytecode == 0 && d_lineno == 0)\r
- return 1;\r
-\r
- if (d_bytecode > 255) {\r
- int j, nbytes, ncodes = d_bytecode / 255;\r
- nbytes = a->a_lnotab_off + 2 * ncodes;\r
- len = PyString_GET_SIZE(a->a_lnotab);\r
- if (nbytes >= len) {\r
- if ((len <= INT_MAX / 2) && (len * 2 < nbytes))\r
- len = nbytes;\r
- else if (len <= INT_MAX / 2)\r
- len *= 2;\r
- else {\r
- PyErr_NoMemory();\r
- return 0;\r
- }\r
- if (_PyString_Resize(&a->a_lnotab, len) < 0)\r
- return 0;\r
- }\r
- lnotab = (unsigned char *)\r
- PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;\r
- for (j = 0; j < ncodes; j++) {\r
- *lnotab++ = 255;\r
- *lnotab++ = 0;\r
- }\r
- d_bytecode -= ncodes * 255;\r
- a->a_lnotab_off += ncodes * 2;\r
- }\r
- assert(d_bytecode <= 255);\r
- if (d_lineno > 255) {\r
- int j, nbytes, ncodes = d_lineno / 255;\r
- nbytes = a->a_lnotab_off + 2 * ncodes;\r
- len = PyString_GET_SIZE(a->a_lnotab);\r
- if (nbytes >= len) {\r
- if ((len <= INT_MAX / 2) && len * 2 < nbytes)\r
- len = nbytes;\r
- else if (len <= INT_MAX / 2)\r
- len *= 2;\r
- else {\r
- PyErr_NoMemory();\r
- return 0;\r
- }\r
- if (_PyString_Resize(&a->a_lnotab, len) < 0)\r
- return 0;\r
- }\r
- lnotab = (unsigned char *)\r
- PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;\r
- *lnotab++ = d_bytecode;\r
- *lnotab++ = 255;\r
- d_bytecode = 0;\r
- for (j = 1; j < ncodes; j++) {\r
- *lnotab++ = 0;\r
- *lnotab++ = 255;\r
- }\r
- d_lineno -= ncodes * 255;\r
- a->a_lnotab_off += ncodes * 2;\r
- }\r
-\r
- len = PyString_GET_SIZE(a->a_lnotab);\r
- if (a->a_lnotab_off + 2 >= len) {\r
- if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)\r
- return 0;\r
- }\r
- lnotab = (unsigned char *)\r
- PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;\r
-\r
- a->a_lnotab_off += 2;\r
- if (d_bytecode) {\r
- *lnotab++ = d_bytecode;\r
- *lnotab++ = d_lineno;\r
- }\r
- else { /* First line of a block; def stmt, etc. */\r
- *lnotab++ = 0;\r
- *lnotab++ = d_lineno;\r
- }\r
- a->a_lineno = i->i_lineno;\r
- a->a_lineno_off = a->a_offset;\r
- return 1;\r
-}\r
-\r
-/* assemble_emit()\r
- Extend the bytecode with a new instruction.\r
- Update lnotab if necessary.\r
-*/\r
-\r
-static int\r
-assemble_emit(struct assembler *a, struct instr *i)\r
-{\r
- int size, arg = 0, ext = 0;\r
- Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);\r
- char *code;\r
-\r
- size = instrsize(i);\r
- if (i->i_hasarg) {\r
- arg = i->i_oparg;\r
- ext = arg >> 16;\r
- }\r
- if (i->i_lineno && !assemble_lnotab(a, i))\r
- return 0;\r
- if (a->a_offset + size >= len) {\r
- if (len > PY_SSIZE_T_MAX / 2)\r
- return 0;\r
- if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)\r
- return 0;\r
- }\r
- code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;\r
- a->a_offset += size;\r
- if (size == 6) {\r
- assert(i->i_hasarg);\r
- *code++ = (char)EXTENDED_ARG;\r
- *code++ = ext & 0xff;\r
- *code++ = ext >> 8;\r
- arg &= 0xffff;\r
- }\r
- *code++ = i->i_opcode;\r
- if (i->i_hasarg) {\r
- assert(size == 3 || size == 6);\r
- *code++ = arg & 0xff;\r
- *code++ = arg >> 8;\r
- }\r
- return 1;\r
-}\r
-\r
-static void\r
-assemble_jump_offsets(struct assembler *a, struct compiler *c)\r
-{\r
- basicblock *b;\r
- int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;\r
- int i;\r
-\r
- /* Compute the size of each block and fixup jump args.\r
- Replace block pointer with position in bytecode. */\r
- do {\r
- totsize = 0;\r
- for (i = a->a_nblocks - 1; i >= 0; i--) {\r
- b = a->a_postorder[i];\r
- bsize = blocksize(b);\r
- b->b_offset = totsize;\r
- totsize += bsize;\r
- }\r
- last_extended_arg_count = extended_arg_count;\r
- extended_arg_count = 0;\r
- for (b = c->u->u_blocks; b != NULL; b = b->b_list) {\r
- bsize = b->b_offset;\r
- for (i = 0; i < b->b_iused; i++) {\r
- struct instr *instr = &b->b_instr[i];\r
- /* Relative jumps are computed relative to\r
- the instruction pointer after fetching\r
- the jump instruction.\r
- */\r
- bsize += instrsize(instr);\r
- if (instr->i_jabs)\r
- instr->i_oparg = instr->i_target->b_offset;\r
- else if (instr->i_jrel) {\r
- int delta = instr->i_target->b_offset - bsize;\r
- instr->i_oparg = delta;\r
- }\r
- else\r
- continue;\r
- if (instr->i_oparg > 0xffff)\r
- extended_arg_count++;\r
- }\r
- }\r
-\r
- /* XXX: This is an awful hack that could hurt performance, but\r
- on the bright side it should work until we come up\r
- with a better solution.\r
-\r
- The issue is that in the first loop blocksize() is called\r
- which calls instrsize() which requires i_oparg be set\r
- appropriately. There is a bootstrap problem because\r
- i_oparg is calculated in the second loop above.\r
-\r
- So we loop until we stop seeing new EXTENDED_ARGs.\r
- The only EXTENDED_ARGs that could be popping up are\r
- ones in jump instructions. So this should converge\r
- fairly quickly.\r
- */\r
- } while (last_extended_arg_count != extended_arg_count);\r
-}\r
-\r
-static PyObject *\r
-dict_keys_inorder(PyObject *dict, int offset)\r
-{\r
- PyObject *tuple, *k, *v;\r
- Py_ssize_t i, pos = 0, size = PyDict_Size(dict);\r
-\r
- tuple = PyTuple_New(size);\r
- if (tuple == NULL)\r
- return NULL;\r
- while (PyDict_Next(dict, &pos, &k, &v)) {\r
- i = PyInt_AS_LONG(v);\r
- /* The keys of the dictionary are tuples. (see compiler_add_o)\r
- The object we want is always first, though. */\r
- k = PyTuple_GET_ITEM(k, 0);\r
- Py_INCREF(k);\r
- assert((i - offset) < size);\r
- assert((i - offset) >= 0);\r
- PyTuple_SET_ITEM(tuple, i - offset, k);\r
- }\r
- return tuple;\r
-}\r
-\r
-static int\r
-compute_code_flags(struct compiler *c)\r
-{\r
- PySTEntryObject *ste = c->u->u_ste;\r
- int flags = 0, n;\r
- if (ste->ste_type != ModuleBlock)\r
- flags |= CO_NEWLOCALS;\r
- if (ste->ste_type == FunctionBlock) {\r
- if (!ste->ste_unoptimized)\r
- flags |= CO_OPTIMIZED;\r
- if (ste->ste_nested)\r
- flags |= CO_NESTED;\r
- if (ste->ste_generator)\r
- flags |= CO_GENERATOR;\r
- if (ste->ste_varargs)\r
- flags |= CO_VARARGS;\r
- if (ste->ste_varkeywords)\r
- flags |= CO_VARKEYWORDS;\r
- }\r
-\r
- /* (Only) inherit compilerflags in PyCF_MASK */\r
- flags |= (c->c_flags->cf_flags & PyCF_MASK);\r
-\r
- n = PyDict_Size(c->u->u_freevars);\r
- if (n < 0)\r
- return -1;\r
- if (n == 0) {\r
- n = PyDict_Size(c->u->u_cellvars);\r
- if (n < 0)\r
- return -1;\r
- if (n == 0) {\r
- flags |= CO_NOFREE;\r
- }\r
- }\r
-\r
- return flags;\r
-}\r
-\r
-static PyCodeObject *\r
-makecode(struct compiler *c, struct assembler *a)\r
-{\r
- PyObject *tmp;\r
- PyCodeObject *co = NULL;\r
- PyObject *consts = NULL;\r
- PyObject *names = NULL;\r
- PyObject *varnames = NULL;\r
- PyObject *filename = NULL;\r
- PyObject *name = NULL;\r
- PyObject *freevars = NULL;\r
- PyObject *cellvars = NULL;\r
- PyObject *bytecode = NULL;\r
- int nlocals, flags;\r
-\r
- tmp = dict_keys_inorder(c->u->u_consts, 0);\r
- if (!tmp)\r
- goto error;\r
- consts = PySequence_List(tmp); /* optimize_code requires a list */\r
- Py_DECREF(tmp);\r
-\r
- names = dict_keys_inorder(c->u->u_names, 0);\r
- varnames = dict_keys_inorder(c->u->u_varnames, 0);\r
- if (!consts || !names || !varnames)\r
- goto error;\r
-\r
- cellvars = dict_keys_inorder(c->u->u_cellvars, 0);\r
- if (!cellvars)\r
- goto error;\r
- freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));\r
- if (!freevars)\r
- goto error;\r
- filename = PyString_FromString(c->c_filename);\r
- if (!filename)\r
- goto error;\r
-\r
- nlocals = PyDict_Size(c->u->u_varnames);\r
- flags = compute_code_flags(c);\r
- if (flags < 0)\r
- goto error;\r
-\r
- bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);\r
- if (!bytecode)\r
- goto error;\r
-\r
- tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */\r
- if (!tmp)\r
- goto error;\r
- Py_DECREF(consts);\r
- consts = tmp;\r
-\r
- co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,\r
- bytecode, consts, names, varnames,\r
- freevars, cellvars,\r
- filename, c->u->u_name,\r
- c->u->u_firstlineno,\r
- a->a_lnotab);\r
- error:\r
- Py_XDECREF(consts);\r
- Py_XDECREF(names);\r
- Py_XDECREF(varnames);\r
- Py_XDECREF(filename);\r
- Py_XDECREF(name);\r
- Py_XDECREF(freevars);\r
- Py_XDECREF(cellvars);\r
- Py_XDECREF(bytecode);\r
- return co;\r
-}\r
-\r
-\r
-/* For debugging purposes only */\r
-#if 0\r
-static void\r
-dump_instr(const struct instr *i)\r
-{\r
- const char *jrel = i->i_jrel ? "jrel " : "";\r
- const char *jabs = i->i_jabs ? "jabs " : "";\r
- char arg[128];\r
-\r
- *arg = '\0';\r
- if (i->i_hasarg)\r
- sprintf(arg, "arg: %d ", i->i_oparg);\r
-\r
- fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",\r
- i->i_lineno, i->i_opcode, arg, jabs, jrel);\r
-}\r
-\r
-static void\r
-dump_basicblock(const basicblock *b)\r
-{\r
- const char *seen = b->b_seen ? "seen " : "";\r
- const char *b_return = b->b_return ? "return " : "";\r
- fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",\r
- b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);\r
- if (b->b_instr) {\r
- int i;\r
- for (i = 0; i < b->b_iused; i++) {\r
- fprintf(stderr, " [%02d] ", i);\r
- dump_instr(b->b_instr + i);\r
- }\r
- }\r
-}\r
-#endif\r
-\r
-static PyCodeObject *\r
-assemble(struct compiler *c, int addNone)\r
-{\r
- basicblock *b, *entryblock;\r
- struct assembler a;\r
- int i, j, nblocks;\r
- PyCodeObject *co = NULL;\r
-\r
- /* Make sure every block that falls off the end returns None.\r
- XXX NEXT_BLOCK() isn't quite right, because if the last\r
- block ends with a jump or return b_next shouldn't set.\r
- */\r
- if (!c->u->u_curblock->b_return) {\r
- NEXT_BLOCK(c);\r
- if (addNone)\r
- ADDOP_O(c, LOAD_CONST, Py_None, consts);\r
- ADDOP(c, RETURN_VALUE);\r
- }\r
-\r
- nblocks = 0;\r
- entryblock = NULL;\r
- for (b = c->u->u_blocks; b != NULL; b = b->b_list) {\r
- nblocks++;\r
- entryblock = b;\r
- }\r
-\r
- /* Set firstlineno if it wasn't explicitly set. */\r
- if (!c->u->u_firstlineno) {\r
- if (entryblock && entryblock->b_instr)\r
- c->u->u_firstlineno = entryblock->b_instr->i_lineno;\r
- else\r
- c->u->u_firstlineno = 1;\r
- }\r
- if (!assemble_init(&a, nblocks, c->u->u_firstlineno))\r
- goto error;\r
- dfs(c, entryblock, &a);\r
-\r
- /* Can't modify the bytecode after computing jump offsets. */\r
- assemble_jump_offsets(&a, c);\r
-\r
- /* Emit code in reverse postorder from dfs. */\r
- for (i = a.a_nblocks - 1; i >= 0; i--) {\r
- b = a.a_postorder[i];\r
- for (j = 0; j < b->b_iused; j++)\r
- if (!assemble_emit(&a, &b->b_instr[j]))\r
- goto error;\r
- }\r
-\r
- if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)\r
- goto error;\r
- if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)\r
- goto error;\r
-\r
- co = makecode(c, &a);\r
- error:\r
- assemble_free(&a);\r
- return co;\r
-}\r