AST 到 字节码
以后都在 github 更新,请戳 AST 到 字节码
目录
相关位置文件
-
Python/compile.c
-
Python/pythonrun.c
-
Python/symtable.c
-
Include/symtable.h
-
Python/ast_opt.c
我们来尝试从之前的 语法树 中生成对应的字节码
前面提到过的 pythonrun
的调用栈如下
这次关注的是 PyAST_CompileObject
这个函数
PyCodeObject *
PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
int optimize, PyArena *arena)
{
struct compiler c;
PyCodeObject *co = NULL;
PyCompilerFlags local_flags;
int merged;
// ... 忽略 ...
if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
goto finally;
}
c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
if (c.c_st == NULL) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_SystemError, "no symtable");
goto finally;
}
co = compiler_mod(&c, mod);
finally:
compiler_free(&c);
assert(co || PyErr_Occurred());
return co;
}
optimize
_PyAST_Optimize
会针对AST做一些优化, 比如常量折叠