Skip to content

Commit a2405f3

Browse files
ondrejmirtesclaude
andcommitted
Port ExpressionResultStorage to the turbo extension with copy-on-write duplication
The PHP implementation stores before-scopes in two spl_object_id-keyed arrays instead of an SplObjectStorage - exprsById pins each stored Expr so its id cannot be reused - which makes duplicate() two array assignments (copy-on-write) instead of an eager per-entry copy. The native class mirrors it in four declared property slots; pendingFibers/parkedFibers stay ordinary public properties driven from PHP. Measured on single-threaded src/ self-analysis (interleaved pairs, user CPU): -2.0s mean against the previous extension build, analysis output byte-identical. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RcA8GGUMoDM6y7QTCwLj2S
1 parent e2c3aa3 commit a2405f3

10 files changed

Lines changed: 215 additions & 11 deletions

File tree

‎src/Analyser/ExpressionResultStorage.php‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,40 +7,46 @@
77
use PhpParser\Node\Expr;
88
use PHPStan\Analyser\Fiber\BeforeScopeForExprRequest;
99
use PHPStan\Analyser\Fiber\ParkFiberRequest;
10-
use SplObjectStorage;
10+
use function spl_object_id;
1111

1212
final class ExpressionResultStorage
1313
{
1414

15-
/** @var SplObjectStorage<Expr, Scope> */
16-
private SplObjectStorage $scopes;
15+
/**
16+
* Keeps every stored Expr alive so its spl_object_id() cannot be reused
17+
* by another node while $scopesById still maps it.
18+
*
19+
* @var array<int, Expr>
20+
*/
21+
private array $exprsById = [];
22+
23+
/** @var array<int, Scope> */
24+
private array $scopesById = [];
1725

1826
/** @var array<array{fiber: Fiber<mixed, Scope|array{callable(Node $node, Scope $scope): void, Node, Scope}, null, BeforeScopeForExprRequest|ParkFiberRequest>, request: BeforeScopeForExprRequest}> */
1927
public array $pendingFibers = [];
2028

2129
/** @var list<Fiber<mixed, Scope|array{callable(Node $node, Scope $scope): void, Node, Scope}, null, BeforeScopeForExprRequest|ParkFiberRequest>> */
2230
public array $parkedFibers = [];
2331

24-
public function __construct()
25-
{
26-
$this->scopes = new SplObjectStorage();
27-
}
28-
2932
public function duplicate(): self
3033
{
3134
$new = new self();
32-
$new->scopes->addAll($this->scopes);
35+
$new->exprsById = $this->exprsById;
36+
$new->scopesById = $this->scopesById;
3337
return $new;
3438
}
3539

3640
public function storeBeforeScope(Expr $expr, Scope $scope): void
3741
{
38-
$this->scopes[$expr] = $scope;
42+
$id = spl_object_id($expr);
43+
$this->exprsById[$id] = $expr;
44+
$this->scopesById[$id] = $scope;
3945
}
4046

4147
public function findBeforeScope(Expr $expr): ?Scope
4248
{
43-
return $this->scopes[$expr] ?? null;
49+
return $this->scopesById[spl_object_id($expr)] ?? null;
4450
}
4551

4652
}

‎src/Turbo/TurboExtensionEnabler.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ public static function enableIfLoaded(): void
191191
require_once __DIR__ . '/../../turbo-ext/stubs/ParserRunner.php';
192192
require_once __DIR__ . '/../../turbo-ext/stubs/TypeCombinatorCache.php';
193193
require_once __DIR__ . '/../../turbo-ext/stubs/ArenaCache.php';
194+
require_once __DIR__ . '/../../turbo-ext/stubs/ExpressionResultStorage.php';
194195

195196
self::$typeCombinatorCacheEnabled = true;
196197
self::$enabled = true;

‎turbo-ext/shadowed-classes.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
"php": "src/Analyser/ConditionalExpressionHolder.php",
44
"cpp": "turbo-ext/src/ConditionalExpressionHolder.cpp"
55
},
6+
"PHPStan\\Analyser\\ExpressionResultStorage": {
7+
"php": "src/Analyser/ExpressionResultStorage.php",
8+
"cpp": "turbo-ext/src/ExpressionResultStorage.cpp"
9+
},
610
"PHPStan\\Analyser\\ExpressionTypeHolder": {
711
"php": "src/Analyser/ExpressionTypeHolder.php",
812
"cpp": "turbo-ext/src/ExpressionTypeHolder.cpp"
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
* PHPStanTurbo\ExpressionResultStorage — native implementation of
3+
* PHPStan\Analyser\ExpressionResultStorage.
4+
*
5+
* Not final: a PHP stub subclass extends this class. duplicate() creates
6+
* instances of the object's own class (the stub), so userland type hints
7+
* keep working without a configured Impl entry.
8+
*
9+
* The before-scope table is two id-keyed arrays in private property slots,
10+
* exactly like the PHP twin: exprsById pins each stored Expr so its object
11+
* handle cannot be reused while scopesById still maps it. duplicate() copies
12+
* the two array zvals by refcount (copy-on-write) — the eager per-entry copy
13+
* of the twin's former SplObjectStorage is what made this worth porting.
14+
* pendingFibers/parkedFibers are ordinary public properties read and written
15+
* by FiberNodeScopeResolver in PHP; the native code never touches them.
16+
*/
17+
18+
#include "support.h"
19+
#include "zv.h"
20+
21+
#define PT_ERS_PROP_EXPRS 0
22+
#define PT_ERS_PROP_SCOPES 1
23+
24+
namespace phpstanturbo {
25+
26+
/* Mirrors PHPStan\Analyser\ExpressionResultStorage. State lives in the PHP
27+
* object's exprsById/scopesById properties. */
28+
class ExpressionResultStorage
29+
{
30+
public:
31+
explicit ExpressionResultStorage(zval *self) : self(self) {}
32+
33+
zv::Val duplicate() const
34+
{
35+
zval newObj;
36+
if (UNEXPECTED(object_init_ex(&newObj, Z_OBJCE_P(self)) != SUCCESS)) {
37+
return zv::Val();
38+
}
39+
zv::ObjRef src(self);
40+
zv::ObjRef dst(&newObj);
41+
dst.propAtWrite(PT_ERS_PROP_EXPRS, zv::Val::copyOf(src.propAt(PT_ERS_PROP_EXPRS)));
42+
dst.propAtWrite(PT_ERS_PROP_SCOPES, zv::Val::copyOf(src.propAt(PT_ERS_PROP_SCOPES)));
43+
return zv::Val::adopt(newObj);
44+
}
45+
46+
void storeBeforeScope(zval *expr, zval *scope)
47+
{
48+
zend_ulong id = Z_OBJ_HANDLE_P(expr);
49+
zv::ObjRef obj(self);
50+
zv::ArrRef(obj.propAt(PT_ERS_PROP_EXPRS).raw()).setIndex(id, zv::Ref(expr));
51+
zv::ArrRef(obj.propAt(PT_ERS_PROP_SCOPES).raw()).setIndex(id, zv::Ref(scope));
52+
}
53+
54+
zv::Val findBeforeScope(zval *expr) const
55+
{
56+
zv::Ref found = zv::ArrRef(zv::ObjRef(self).propAt(PT_ERS_PROP_SCOPES).raw()).findIndex(Z_OBJ_HANDLE_P(expr));
57+
if (found.raw() == NULL) {
58+
return zv::Val::null();
59+
}
60+
return zv::Val::copyOf(found);
61+
}
62+
63+
private:
64+
zval *self;
65+
};
66+
67+
} // namespace phpstanturbo
68+
69+
using phpstanturbo::ExpressionResultStorage;
70+
71+
/* {{{ engine ABI glue: parameter parsing + registration */
72+
73+
#include "reg.h"
74+
75+
void pt_register_expression_result_storage()
76+
{
77+
reg::Class cls("PHPStanTurbo\\ExpressionResultStorage");
78+
/* not final: a PHP stub subclass extends this class; exprsById/scopesById
79+
* must stay in this order (OBJ_PROP_NUM slots) */
80+
cls.privateArrayProperty("exprsById");
81+
cls.privateArrayProperty("scopesById");
82+
cls.publicArrayProperty("pendingFibers");
83+
cls.publicArrayProperty("parkedFibers");
84+
85+
cls.method("duplicate", reg::Public, 0, {}, [](INTERNAL_FUNCTION_PARAMETERS) {
86+
ZEND_PARSE_PARAMETERS_NONE();
87+
zv::Val result = ExpressionResultStorage(ZEND_THIS).duplicate();
88+
if (UNEXPECTED(result.isUndef())) {
89+
RETURN_THROWS();
90+
}
91+
result.intoReturnValue(return_value);
92+
});
93+
94+
cls.method("storeBeforeScope", reg::Public, 2, { reg::any("expr"), reg::any("scope") }, [](INTERNAL_FUNCTION_PARAMETERS) {
95+
zval *expr, *scope;
96+
ZEND_PARSE_PARAMETERS_START(2, 2)
97+
Z_PARAM_OBJECT(expr)
98+
Z_PARAM_OBJECT(scope)
99+
ZEND_PARSE_PARAMETERS_END();
100+
ExpressionResultStorage(ZEND_THIS).storeBeforeScope(expr, scope);
101+
});
102+
103+
cls.method("findBeforeScope", reg::Public, 1, { reg::any("expr") }, [](INTERNAL_FUNCTION_PARAMETERS) {
104+
zval *expr;
105+
ZEND_PARSE_PARAMETERS_START(1, 1)
106+
Z_PARAM_OBJECT(expr)
107+
ZEND_PARSE_PARAMETERS_END();
108+
ExpressionResultStorage(ZEND_THIS).findBeforeScope(expr).intoReturnValue(return_value);
109+
});
110+
111+
cls.register_();
112+
}
113+
114+
/* }}} */

‎turbo-ext/src/main.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ static PHP_MINIT_FUNCTION(phpstan_turbo)
6969
pt_register_parser_runner();
7070
pt_register_type_combinator_cache();
7171
pt_register_arena_cache();
72+
pt_register_expression_result_storage();
7273

7374
return SUCCESS;
7475
}

‎turbo-ext/src/reg.h‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,18 @@ class Class
167167
return *this;
168168
}
169169

170+
Class &privateArrayProperty(const char *propertyName)
171+
{
172+
properties.push_back({ propertyName, PropertyKind::EmptyArray, ZEND_ACC_PRIVATE, 0 });
173+
return *this;
174+
}
175+
176+
Class &publicArrayProperty(const char *propertyName)
177+
{
178+
properties.push_back({ propertyName, PropertyKind::EmptyArray, ZEND_ACC_PUBLIC, 0 });
179+
return *this;
180+
}
181+
170182
/* a protected bool property (zend_declare_property_bool) */
171183
Class &protectedBoolProperty(const char *propertyName, bool defaultValue)
172184
{

‎turbo-ext/src/support.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ void pt_register_node_scanner();
141141
void pt_register_parser_runner();
142142
void pt_register_type_combinator_cache();
143143
void pt_register_arena_cache();
144+
void pt_register_expression_result_storage();
144145

145146
/* per-request hooks of individual classes */
146147
void pt_node_traverser_rinit();

‎turbo-ext/src/zv.h‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,22 @@ class ArrRef : public Ref
373373
Z_TRY_ADDREF_P(borrowed.raw());
374374
zend_hash_next_index_insert(table(), borrowed.raw());
375375
}
376+
377+
/* $a[$index] ?? null */
378+
Ref findIndex(zend_ulong index) const
379+
{
380+
zval *found = zend_hash_index_find(table(), index);
381+
return Ref(found); /* raw() == NULL when absent */
382+
}
383+
384+
/* $a[$index] = $value; separates a shared table first (writes through
385+
* the slot), releases a replaced value */
386+
void setIndex(zend_ulong index, Ref borrowed)
387+
{
388+
SEPARATE_ARRAY(z);
389+
Z_TRY_ADDREF_P(borrowed.raw());
390+
zend_hash_index_update(table(), index, borrowed.raw());
391+
}
376392
};
377393

378394
/* Owned PHP array under construction.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
/** Turbo stub: shadows the PHP implementation with the native one. */
6+
final class ExpressionResultStorage extends \PHPStanTurbo\ExpressionResultStorage
7+
{
8+
9+
}

‎turbo-ext/tests/smoke.php‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,5 +278,45 @@ function check(bool $cond, string $msg): void
278278
check($describe($afterClear) === $describe($first), 'TCC clearCache keeps results correct');
279279
check($afterClear !== $first, 'TCC clearCache actually drops entries');
280280

281+
// ---- ExpressionResultStorage ----
282+
$makeScope = static function () {
283+
static $reflection = null;
284+
$reflection ??= new ReflectionClass(\PHPStan\Analyser\MutatingScope::class);
285+
return $reflection->newInstanceWithoutConstructor();
286+
};
287+
288+
foreach (['php' => \PHPStan\Analyser\ExpressionResultStorage::class, 'native' => \PHPStanTurbo\ExpressionResultStorage::class] as $label => $storageClass) {
289+
$storage = new $storageClass();
290+
$exprA = new \PhpParser\Node\Expr\Variable('a');
291+
$exprB = new \PhpParser\Node\Expr\Variable('b');
292+
$scopeA = $makeScope();
293+
$scopeB = $makeScope();
294+
295+
check($storage->findBeforeScope($exprA) === null, "ERS $label: find on empty storage is null");
296+
$storage->storeBeforeScope($exprA, $scopeA);
297+
check($storage->findBeforeScope($exprA) === $scopeA, "ERS $label: find returns the stored scope");
298+
check($storage->findBeforeScope($exprB) === null, "ERS $label: unknown expr is null");
299+
$storage->storeBeforeScope($exprA, $scopeB);
300+
check($storage->findBeforeScope($exprA) === $scopeB, "ERS $label: overwrite for the same expr");
301+
302+
$duplicate = $storage->duplicate();
303+
check(get_class($duplicate) === $storageClass, "ERS $label: duplicate creates the same class");
304+
check($duplicate->findBeforeScope($exprA) === $scopeB, "ERS $label: duplicate carries stored entries");
305+
$duplicate->storeBeforeScope($exprB, $scopeA);
306+
check($duplicate->findBeforeScope($exprB) === $scopeA, "ERS $label: store on the duplicate");
307+
check($storage->findBeforeScope($exprB) === null, "ERS $label: duplicate stores do not leak back");
308+
$storage->storeBeforeScope($exprB, $scopeB);
309+
check($duplicate->findBeforeScope($exprB) === $scopeA, "ERS $label: original stores do not leak into the duplicate");
310+
311+
check($duplicate->pendingFibers === [] && $duplicate->parkedFibers === [], "ERS $label: duplicate starts with empty fiber arrays");
312+
$storage->pendingFibers[] = ['marker' => 1];
313+
$storage->parkedFibers[] = 'parked';
314+
check(count($storage->pendingFibers) === 1 && $storage->parkedFibers === ['parked'], "ERS $label: fiber arrays are appendable");
315+
$secondDuplicate = $storage->duplicate();
316+
check($secondDuplicate->pendingFibers === [] && $secondDuplicate->parkedFibers === [], "ERS $label: duplicate does not carry fiber arrays");
317+
unset($storage->pendingFibers[0]);
318+
check($storage->pendingFibers === [], "ERS $label: fiber array entries can be unset");
319+
}
320+
281321
echo $failures === 0 ? "ALL OK\n" : "$failures FAILURES\n";
282322
exit($failures === 0 ? 0 : 1);

0 commit comments

Comments
 (0)