# 编译流水线 TypePHP 的核心入口是 `bin/tpc.php`,它通过 `main()` 串起整条流水线:`prepare → convert → compile → build → run`。本章用一张图和一个阶段表把全链路讲清楚。 Sources: [bin/tpc.php](bin/tpc.php#L1-L9) · [src/compiler.php](src/compiler.php#L4-L46) ## 总体流程 ```mermaid flowchart TD A["main(argc, argv)"] --> B["prepare(argv)\n扫描 PHP 文件 + 预处理"] B --> C["convert(files)\nPHP AST → C++ 源文件"] C --> D{"--dry?"} D -- "是" --> Z["仅输出 C++,结束"] D -- "否" --> E["compile(sourceFiles)\nC++ → .o / .obj"] E --> F["build(objectFiles)\n链接为二进制 / 库 / 扩展"] F --> G{"--run?"} G -- "是" --> H["run(binary)\n立即执行"] G -- "否" --> Z ``` `.prof` 后缀会被切换为 `profileAnalyze` 模式,调用 `pprof --web` 做性能剖析。 Sources: [src/compiler.php](src/compiler.php#L14-L18) · [src/compiler.php](src/compiler.php#L26-L45) ## 各阶段职责 | 阶段 | 方法 | 关键工作 | |---|---|---| | 准备 | `Translator::prepare()` | 扫描所有 PHP 文件、解析命令行、构建符号表(类/函数/常量/属性) | | 转换 | `Translator::convert()` → `convertFile()` → `doConvert()` | 对每个 PHP 文件解析 AST,跑 Transform 访客,生成 `.cc` 与 `_arginfo.h` | | 编译 | `Translator::compile()` | 追加 phpx misc 源文件、准备 PCH、单进程或 `pcntl` 并行编译 | | 构建 | `Translator::build()` | 调用原生链接器把目标文件 + 资源文件链接成最终产物 | | 运行 | `Translator::run()` | 仅在 `bin` 模式且带 `--run` 时执行产物 | Sources: [src/Translator.php](src/Translator.php#L504-L527) · [src/Translator.php](src/Translator.php#L1419-L1447) · [src/Translator.php](src/Translator.php#L1649-L1680) ## 转换阶段的两趟扫描 `doConvert()` 内部做了两件事([src/Translator.php](src/Translator.php#L2455-L2537)): 1. **AST 遍历**:用 `NodeTraverser` 串联 `NameResolver`、`Transform\Visitor`、`ConstantExpressionValidationVisitor`、`RuntimeAttributeFactoryLowering` 四个访客,做名称解析、编译期属性 lowering、常量表达式校验。 2. **语句分发**:遍历顶层语句,按 `Stmt_Class` / `Stmt_Function` / `Stmt_Const` 等类型调用对应的 `parseXxx()`,最后为每个类、接口、函数生成 C++ 包装代码(`genClassWrapper` / `genFunctionWrapper`)。 > 前端的解析/符号表逻辑在 [preprocessor](preprocessor) 与 [transform](transform) 章节展开;C++ 生成细节在 [generator](generator)。 ## 关键文件 - `src/compiler.php` — 顶层 `main()` 与 `.prof` 剖析模式。 - `src/Translator.php` — 流水线编排 + 构建/链接/缓存。 - `src/Preprocessor.php` / `src/CompilerBase.php` — 解析、符号收集、C++ 代码发射(占 7000+ 行,是编译器主体)。