TypePHP 编译器
https://swoole.com/aot/
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
2.1 KiB
38 lines
2.1 KiB
<blog>
|
|
|
|
# 编译期属性
|
|
|
|
除了 PHP 8 的运行时 attribute,TypePHP 引入一组**编译期函数与属性**,用于在翻译阶段向编译器传递类型/语义提示。它们被 `Transform` 层的 Lowering 算子在遍历 AST 时识别与校验。
|
|
|
|
Sources: [src/Transform/CompileTimeAttribute.php](src/Transform/CompileTimeAttribute.php) · [src/Transform/CompileTimeAttributeRegistry.php](src/Transform/CompileTimeAttributeRegistry.php) · [docs/COMPILE_TIME_FUNCTIONS.md](docs/COMPILE_TIME_FUNCTIONS.md)
|
|
|
|
## 核心编译期函数
|
|
|
|
| 函数 | 用途 |
|
|
|---|---|
|
|
| `any($v)` | 显式标记变量为「任意 PHP 值」(通用 `php::Var`),绕过原生类型推断 |
|
|
| `refval($v, Type)` | 以指定类型解释变量(类型恢复/断言) |
|
|
| `objval($v, 'ClassName')` | 从数组/返回值恢复对象的类信息(见 [native-types](native-types)) |
|
|
| `expected()` / `unexpected()` | 编译期断言/分支提示 |
|
|
|
|
Sources: [docs/COMPILE_TIME_FUNCTIONS.md](docs/COMPILE_TIME_FUNCTIONS.md)
|
|
|
|
## 编译期属性
|
|
|
|
`CompileTimeAttribute::validateNode()` 在 `Visitor::enterNode` 中对每个节点校验编译期属性;`CompileTimeAttributeRegistry` 维护已知属性注册表。典型如 `MustUse`(要求函数/方法有返回值且调用方使用)、`Any`(类型放宽)等——`Preprocessor` 在 `parseFunctionDecl()` 中也会对 `MustUse` 强行校验返回类型。
|
|
|
|
Sources: [src/Transform/Visitor.php](src/Transform/Visitor.php#L30) · [src/Preprocessor.php](src/Preprocessor.php#L537)
|
|
|
|
## 与 Lowering 的配合
|
|
|
|
`FunctionAttributeLowering` / `ConstructorLowering` / `GetterLowering` / `PropertyMethodLowering` 把带编译期属性的节点降级为可翻译结构;`RuntimeAttributeFactoryLowering` 作为独立访客挂在遍历链上,处理运行时工厂属性。
|
|
|
|
Sources: [src/Transform/Visitor.php](src/Transform/Visitor.php#L30-L35) · [src/Translator.php](src/Translator.php#L2467)
|
|
|
|
## 相关阅读
|
|
|
|
- 遍历中如何调用这些算子 → [AST 转换](transform)
|
|
- 类型如何因此被放宽/恢复 → [类型检查与兼容](type-check)
|
|
- SSA 优化如何消费类型信息 → [优化器](optimizer)
|
|
|
|
</blog>
|
|
|