Skip to content

fix(compiler): emit compilable C++ for readonly scalar reads and string ternaries - #186

Merged
matyhtf merged 3 commits into
swoole:masterfrom
yuan-dian:fix/aot-typed-property-storage
Nov 11, 2026
Merged

matyhtf merged 3 commits into
swoole:masterfrom
yuan-dian:fix/aot-typed-property-storage

Conversation

@yuan-dian

Copy link
Copy Markdown
Contributor

背景

AOT 编译在两种常见的类型退化场景下生成非法 C++,直接阻断整个工程构建(g++ / MSVC 均失败):

  1. readonly 标量属性读取(C2440):switch ($this->status) 中判别式被声明为 php::Int,却用返回 php::Variant 的 generic 读取初始化。
  2. 字符串三元(C2678):两个分支声明类型相同,但一个降级为 php::Variant、另一个是 const php::String&,裸 C++ 条件表达式没有公共类型。

复现

final class StaticMachine
{
    private static bool $enabled = false;
    private static string $mode = 'idle';

    public function label(): string
    {
        return self::$enabled ? self::$mode : '';   // C2678
    }
}

final class ReadonlyMachine
{
    public function __construct(private readonly int $status = 0) {}

    public function run(): string
    {
        switch ($this->status) {                    // C2440
            case 0: return 'pending';
            case 1: return 'done';
            default: return 'unknown';
        }
    }
}

final class InstanceMachine
{
    private bool $enabled = false;
    private string $mode = 'idle';

    public function modeOrEmpty(): string
    {
        return $this->enabled ? $this->mode : '';   // C2678
    }
}
machines.cc:43:62: error: operands to '?:' have different types 'php::Variant' and 'const php::String'
machines.cc:61:36: error: cannot convert 'php::Variant' to 'php::Int' {aka 'long int'} in initialization
machines.cc:91:134: error: operands to '?:' have different types 'php::Variant' and 'const php::String'
Fatal error: compile failed: build/src/machines.cc

根因

  • SsaPropOptimizer::canHoistObjectPropBySafety() 对 readonly 属性返回 false,这是有意的:promoted 属性的初始化顺序会让函数级引用不安全(NativePropertyTest::testReadonlyPropertiesDoNotUseNativeScalarReferences 已有断言保护)。emitNativeInstancePropertyTypedFetch() 因此直接 return null,调用方退回 generic 读取(php::Variant),而下游仍按声明类型(php::Int / php::Float)使用该值。
  • parseTernary 只比较 detectTypeOfExpr 得到的声明类型,不比较 getLoweredExpressionType 的存储类型。声明类型一致时不设置 ATTR_LOWERED_TYPE、也不包裹分支,于是 php::Variant 与 php::String 直接进入同一个条件表达式。注意 Variant 与 php::Int 有公共类型(Variant),int/float/bool 三元本来可编译,因此修复只需覆盖字符串。

改动

  • src/Parser/PropertyAccessTrait.php(emitNativeInstancePropertyTypedFetch):readonly 属性无法 hoist 时,对 generic 动态读取结果调用 convertExprFromType($def->type, $getter),恢复声明的标量存储类型,并标记 value source 为 DYNAMIC。不放宽 hoist 排除,readonly 语义不变。
  • src/Parser/SelectionExpressionTrait.php(parseTernary):新增一个收窄分支——当 $ifType === $elseType === Type::STR 且两侧 lowered storage 不同时,把两个分支都经 convertExprFromType(Type::STR, ...) 统一,并设置 ATTR_LOWERED_TYPE = Type::STR。其余类型路径输出保持字节级不变。
  • 该入口仅在做 usesNativeScalarStorage() 判断(INT/FLOAT/BOOL)时到达,string/array/object 属性的既有生成路径不受影响。

测试

新增 6 个回归用例(实现 + codegen 断言 + 运行时 PHPT 成对提交):

  • phpunit/src/ReadonlyTypedPropertyReadTest.php + phpunit/code/readonly-typed-property-read.php
    • 断言生成 php::toInt(this_.attr(、php::toFloat(this_.attr(、switch (tmp_var_0)
    • 断言不出现 _object_prop_this___status / ___ratio / AttrMode::Update(readonly 仍不 hoist)
  • phpunit/src/TernaryStorageTypeTest.php + phpunit/code/ternary-storage-unification.php
    • 断言生成 php::toString(this_.attr(、php::toString(php::empty_string)
    • 断言不再出现 ? (this_.attr( / ? (_typephp_static_property_
  • tests/compiler/switch/readonly-typed-property.phpt
  • tests/compiler/control_flow/ternary-typed-property-storage.phpt

验证

  • phpunit:新增用例 OK (2 tests, 12 assertions)。
  • 端到端:9 个源文件的探针工程用本分支编译器构建 build-rc=0、Successfully compiled 9 files;产物运行输出与 PHP 8.4 解释执行逐字节一致(含 readonly int/bool、static/实例字符串三元、null/?-> 三元)。
  • PHPT:tests/compiler/{switch,control_flow,object_property} 共 102/102 PASS(-j1 串行)。
  • 全量 phpunit 与干净 master 基线一致,仅存在既有的 swoole/php-nano 缺失与本地 phpx/clang 头不匹配失败,无新增失败。

风险与兼容性

  • 仅改变原本无法编译的两类输出;int/float/bool 三元、readonly 不 hoist 的既有 codegen 断言均未变化。
  • 无新增依赖、无 API 变更。

yuan-dian and others added 3 commits November 11, 2026 15:14
… storage

Readonly properties are intentionally excluded from scalar reference
hoisting, so their generic read yields php::Variant. Using that value to
initialize a php::Int/php::Float local produces invalid C++ when a
readonly typed property feeds a switch discriminant or a typed return.
Convert the dynamic read back to the declared scalar storage instead.
A Zend-backed string property read lowers to php::Variant while a
string literal lowers to php::String, so the branches have no common
C++ type when their declared types match but their storage differs.
Convert both string branches through the declared string storage;
other scalar storage already has a common type and needs no change.
Handle readonly scalar storage before either receiver-specific hoisting
path, including typed parameters and local objects. Recover readable
readonly declarations for expression receivers without changing dynamic
lookup for other properties.

Use the existing scoped property reader before conversion so uninitialized
slots throw instead of becoming zero or false, while lexical visibility
and the prohibition on hoisted readonly references remain enforced.

Add codegen and runtime coverage for parameter, local and expression
receivers, float/bool reads, and uninitialized int/float/bool properties.

Validated PHP 8.4/8.5 related PHPUnit suites (51 tests, 171 assertions each)
and all 103 switch/control_flow/object_property PHPTs on Linux PHP 8.4.
@matyhtf
matyhtf merged commit bff4648 into swoole:master Nov 11, 2026
9 checks passed
@yuan-dian
yuan-dian deleted the fix/aot-typed-property-storage branch November 13, 2026 09:13
yuan-dian added a commit to yuan-dian/typephp that referenced this pull request Nov 13, 2026
A readonly scalar read keeps the dynamic value source, so its result is
materialized as a Variant. swoole#186 correctly converts the read back to the
declared scalar, but it also stamped the expression with the declared
type. The surrounding expression then trusted that type and dropped its
own conversion: `$rect->width / 2.0` compiled to a raw Variant division
assigned to php::Float, which is C2440.

Keep the conversion in the read and leave the lowered type alone, so the
arithmetic keeps its toFloat/toInt. The switch discriminant consequently
falls back to PHP's loose equality over the Variant, which matches the
value the read actually returns.

Cover the readonly float division that the Drift2 layout code hits.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants