Python 编译阶段 -- 从 AST 到 字节码

AST 到 字节码

以后都在 github 更新,请戳 AST 到 字节码

目录

相关位置文件

  • Python/compile.c

  • Python/pythonrun.c

  • Python/symtable.c

  • Include/symtable.h

  • Python/ast_opt.c

我们来尝试从之前的 语法树 中生成对应的字节码

前面提到过的 pythonrun 的调用栈如下

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做一些优化, 比如常量折叠

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值