Skip to content

Commit 1315e20

Browse files
committed
diagram
1 parent d14676b commit 1315e20

File tree

2 files changed

+2
-65
lines changed

2 files changed

+2
-65
lines changed

assets/images/zig-compiler.svg

Lines changed: 1 addition & 0 deletions
Loading

content/post/2026-01-26-zig-compiler-deep-dive.smd

Lines changed: 1 addition & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
.date = @date("2026-01-26T09:49:51+0800"),
44
.author = "jiacai2050",
55
.layout = "post.shtml",
6-
.custom = {
7-
.mermaid = true
8-
},
96
---
107

118
## **摘要**
@@ -50,68 +47,7 @@ Zig 的编译管线可以抽象为一系列数据变换阶段。每一个阶段
5047

5148
为了满足“流程图”的需求,以下是 Zig 编译器核心控制流的结构化描述:
5249

53-
```=html
54-
<pre class="mermaid">
55-
graph TD
56-
Start((启动编译器)) --> Init[初始化 Zcu 编译单元]
57-
Init --> Discovery
58-
Discovery --> Src
59-
60-
subgraph Frontend ["前端处理 (Per File)"]
61-
Src["源文件 (Source Files)"] --> Tokenizer
62-
Tokenizer --> Parser
63-
Parser --> AST
64-
AST --> CacheCheck{Hash 缓存命中?}
65-
CacheCheck -- Yes --> LoadZIR
66-
CacheCheck -- No --> AstGen
67-
AstGen --> ZIR
68-
ZIR --> SaveCache[存入缓存]
69-
end
70-
71-
Discovery --> AnalyzeRoot
72-
AnalyzeRoot --> SemaLoop{Sema 解释器循环}
73-
74-
subgraph Sema["语义分析 (Sema)"]
75-
SemaLoop --> FetchInst
76-
FetchInst --> ResolveOps["解析操作数 (Values/Insts)"]
77-
ResolveOps --> CheckComptime{编译期已知?}
78-
79-
CheckComptime -- Yes (Comptime) --> ExecCTFE
80-
ExecCTFE --> InternPool["存入 InternPool (Values)"]
81-
InternPool --> UpdateMap["更新映射 (Values)"]
82-
UpdateMap --> SemaLoop
83-
84-
CheckComptime -- No (Runtime) --> EmitAIR
85-
EmitAIR --> Liveness[活跃度分析 Liveness]
86-
Liveness --> UpdateMapAIR["更新映射 (AIR)"]
87-
UpdateMapAIR --> SemaLoop
88-
89-
FetchInst --> CheckDep{引用其他声明?}
90-
CheckDep -- Yes --> Pause[挂起当前分析]
91-
Pause --> Recurse[递归分析被引用的声明]
92-
Recurse --> Resume[恢复当前分析]
93-
Resume --> SemaLoop
94-
end
95-
96-
Sema --> AIR
97-
AIR --> CodeGen[代码生成 CodeGen]
98-
99-
subgraph Backend [后端处理]
100-
CodeGen --> SelectBackend{选择后端}
101-
SelectBackend -- LLVM --> LLVM_IR
102-
SelectBackend -- Self-Hosted --> MachineCode
103-
SelectBackend -- C --> C_Source[生成 C 源码]
104-
end
105-
106-
LLVM_IR --> Optimizer[LLVM 优化器]
107-
MachineCode --> Linker[Zig 内置链接器 zld]
108-
C_Source --> C_Compiler[外部 C 编译器]
109-
C_Compiler --> FinalArtifact[最终产物 Artifact]
110-
111-
Optimizer --> Linker
112-
Linker --> FinalArtifact[最终产物 Artifact]
113-
</pre>
114-
```
50+
[How Zig compiler works]($image.siteAsset('images/zig-compiler.svg'))
11551

11652
## **3\. 第一阶段:解析与 AST 构建 (Parsing)**
11753

0 commit comments

Comments
 (0)