2.1 KiB
编译期属性
除了 PHP 8 的运行时 attribute,TypePHP 引入一组编译期函数与属性,用于在翻译阶段向编译器传递类型/语义提示。它们被 Transform 层的 Lowering 算子在遍历 AST 时识别与校验。
Sources: src/Transform/CompileTimeAttribute.php · src/Transform/CompileTimeAttributeRegistry.php · docs/COMPILE_TIME_FUNCTIONS.md
核心编译期函数
| 函数 | 用途 |
|---|---|
any($v) |
显式标记变量为「任意 PHP 值」(通用 php::Var),绕过原生类型推断 |
refval($v, Type) |
以指定类型解释变量(类型恢复/断言) |
objval($v, 'ClassName') |
从数组/返回值恢复对象的类信息(见 native-types) |
expected() / unexpected() |
编译期断言/分支提示 |
Sources: docs/COMPILE_TIME_FUNCTIONS.md
编译期属性
CompileTimeAttribute::validateNode() 在 Visitor::enterNode 中对每个节点校验编译期属性;CompileTimeAttributeRegistry 维护已知属性注册表。典型如 MustUse(要求函数/方法有返回值且调用方使用)、Any(类型放宽)等——Preprocessor 在 parseFunctionDecl() 中也会对 MustUse 强行校验返回类型。
Sources: src/Transform/Visitor.php · src/Preprocessor.php
与 Lowering 的配合
FunctionAttributeLowering / ConstructorLowering / GetterLowering / PropertyMethodLowering 把带编译期属性的节点降级为可翻译结构;RuntimeAttributeFactoryLowering 作为独立访客挂在遍历链上,处理运行时工厂属性。
Sources: src/Transform/Visitor.php · src/Translator.php