# 八、编译器

完成解析任务后，解释器拥有了一棵抽象语法树，其包含 Python 代码的操作、函数、类以及命名空间。

\*\*编译器（compiler）\*\*的任务是将抽象语法树转换为 CPU 能理解的指令：

**图片翻译**：File Input: 文件输入，IO Stream Input：文件流输入，String Input：字符串输入，Reader：阅读器，Parser：解析器，Compiler：编译器

此编译任务会被分成两个组件：

1. **编译器**：遍历抽象语法树并创建一个**控制流图(CFG)**，此图表示执行的逻辑顺序；
2. **汇编器**：将 CFG 中的节点转换为能按顺序执行的语句，被大家称为：**字节码（bytecode）**。

下图是编译过程的可视化展示：

**图片翻译**：Parser：解析器，AST：抽象语法树，CFG：控制流图，Assembler：汇编器，ByteCode：字节码，Execution：执行

{% hint style="info" %}
**重要**

在本章中，请牢记 CPython 的编译单元是一个模块。本章中涉及的编译步骤和过程将为项目中的每一个模块执行一次。
{% endhint %}

在本章节中，你将会重点关注抽象语法树是如何被编译成一个 `code object` 。

`PyAST_CompileObject()` 是 CPython 编译器的主要入口之一。其将 Python 抽象语法树模块作为主要形参，其他形参还包括文件名和解释器早期创建的全局变量、局部变量和 `PyArena` 。

{% hint style="info" %}
**注**

你现在开始要深入了解 CPython 编译器的核心，其背后是几十年的开发演进以及计算机科学理论体系。不要被规模和复杂度吓坏。一旦你把编译器分解成逻辑模块，就不那么难理解了。
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hai-shi.gitbook.io/cpython-internals/8-compiler.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
