Skip to content

Commit 65be556

Browse files
committed
Do not record nested loop heads walked from an unreachable entry
A nested loop walked in a branch an enclosing loop's earlier pass ruled out (such as isset() of an offset of a still empty array) converged with its variables narrowed to never and the types read from them *ERROR*. Its head was kept and joined into the reachable entry of a later pass, where *ERROR* swallowed the real types. ConvergedLoopHeads now remembers the entry each loop was walked from and does not record a head when a defined variable of that entry is never. The native mirror does the same. Amp-Thread-ID: https://ampcode.com/threads/T-01a217b0-4f5c-74a6-90c4-a6c351fad7e3
1 parent 42fc068 commit 65be556

4 files changed

Lines changed: 152 additions & 4 deletions

File tree

‎src/Analyser/ConvergedLoopHeads.php‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PhpParser\Node;
66
use PHPStan\Turbo\ShadowedByTurboExtension;
7+
use PHPStan\Type\NeverType;
78
use function spl_object_id;
89

910
/**
@@ -15,6 +16,10 @@
1516
* converging from the head it reached the previous time instead of from
1617
* scratch - a nested loop whose head is already stable converges in a single
1718
* pass, which also stands in for its final walk.
19+
*
20+
* A walk from an unreachable entry records no head: its variables narrowed to
21+
* never make the types read from them *ERROR*, which would swallow the types
22+
* of the reachable entries the head is joined into later.
1823
*/
1924
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ConvergedLoopHeads.cpp')]
2025
final class ConvergedLoopHeads
@@ -23,6 +28,13 @@ final class ConvergedLoopHeads
2328
/** @var array<int, MutatingScope> */
2429
private array $heads = [];
2530

31+
/**
32+
* The entry each loop was last walked from.
33+
*
34+
* @var array<int, MutatingScope>
35+
*/
36+
private array $entries = [];
37+
2638
/**
2739
* The last entry each loop was warm-started from and the warm entry it gave
2840
* with the current head - an enclosing loop's later passes mostly bring the
@@ -35,6 +47,7 @@ final class ConvergedLoopHeads
3547
public function warmStart(Node $loop, MutatingScope $entryScope): MutatingScope
3648
{
3749
$id = spl_object_id($loop);
50+
$this->entries[$id] = $entryScope;
3851
$head = $this->heads[$id] ?? null;
3952
if ($head === null) {
4053
return $entryScope;
@@ -54,6 +67,11 @@ public function warmStart(Node $loop, MutatingScope $entryScope): MutatingScope
5467
public function record(Node $loop, MutatingScope $head): void
5568
{
5669
$id = spl_object_id($loop);
70+
// a walk the entry of which is unreachable does not widen the head
71+
if (self::isUnreachable($this->entries[$id])) {
72+
return;
73+
}
74+
5775
$previous = $this->heads[$id] ?? null;
5876
// an unchanged head keeps the warm entry derived from it
5977
if ($previous !== null && ($previous === $head || $previous->equals($head))) {
@@ -64,4 +82,19 @@ public function record(Node $loop, MutatingScope $head): void
6482
unset($this->warmEntries[$id]);
6583
}
6684

85+
/**
86+
* A variable that can hold no value - the walk is in a branch the
87+
* condition rules out, such as isset() of an offset of an empty array.
88+
*/
89+
private static function isUnreachable(MutatingScope $scope): bool
90+
{
91+
foreach ($scope->getDefinedVariables() as $variableName) {
92+
if ($scope->getVariableType($variableName) instanceof NeverType) {
93+
return true;
94+
}
95+
}
96+
97+
return false;
98+
}
99+
67100
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15841;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template TKey of string
9+
* @template TValue
10+
* @param array<TKey, TValue> $array
11+
* @return array<TKey, TValue>
12+
*/
13+
function identity(array $array) : array{
14+
return $array;
15+
}
16+
17+
/**
18+
* @param array<string, array<string, list<int>>> $a
19+
*/
20+
function build(array $a) : void{
21+
$mapping = [];
22+
$table = [];
23+
24+
foreach($a as $blockName => $remaps){
25+
foreach($remaps as $propertyName => $values){
26+
if(isset($table[$propertyName])){
27+
foreach($table[$propertyName] as $k => $existing){
28+
foreach($values as $v){
29+
if(!isset($existing[$v])){
30+
continue 2;
31+
}
32+
}
33+
34+
$mapping[$blockName][$propertyName] = $k;
35+
continue 2;
36+
}
37+
}
38+
39+
$table[$propertyName][] = $values;
40+
$mapping[$blockName][$propertyName] = array_key_last($table[$propertyName]);
41+
}
42+
}
43+
44+
assertType('array<string, non-empty-array<string, int<0, max>>>', $mapping);
45+
foreach(identity($mapping) as $properties){
46+
assertType('non-empty-array<string, int<0, max>>', $properties);
47+
}
48+
}
49+
50+
/**
51+
* @param list<array{string, array<string, int>, array<string, int>}> $table
52+
*/
53+
function process(array $table) : void{
54+
$unchanged = [];
55+
56+
foreach($table as [$newName, $oldStates, $newStates]){
57+
if(count($oldStates) === 0){
58+
$unchanged[$newName] = [];
59+
continue;
60+
}
61+
62+
if(!isset($unchanged[$newName])){
63+
$unchanged[$newName] = [];
64+
foreach($oldStates as $propertyName => $propertyValue){
65+
if(isset($newStates[$propertyName]) && $newStates[$propertyName] === $propertyValue){
66+
$unchanged[$newName][] = $propertyName;
67+
}
68+
}
69+
}else{
70+
foreach($unchanged[$newName] as $k => $propertyName){
71+
if(!isset($oldStates[$propertyName])){
72+
unset($unchanged[$newName][$k]);
73+
}
74+
}
75+
}
76+
}
77+
78+
assertType('array<string, array<int<0, max>, string>>', $unchanged);
79+
}

‎turbo-ext/src/ConvergedLoopHeads.cpp‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
*
55
* The entry scopes the loops nested in a top-level loop converged to, keyed
66
* by the loop node's object id (spl_object_id() is the object handle). The
7-
* state lives in the twin's $heads slot (generated declarations); the loop
8-
* handlers use the pt_converged_loop_heads_* direct entries (support.h).
7+
* state lives in the twin's $heads, $entries and $warmEntries slots
8+
* (generated declarations); the loop handlers use the
9+
* pt_converged_loop_heads_* direct entries (support.h).
910
*/
1011

1112
#include "support.h"
@@ -38,6 +39,10 @@ class ConvergedLoopHeads
3839
zv::Val warmStart(zval *loop, zval *entryScope) const
3940
{
4041
zend_ulong id = Z_OBJ_HANDLE_P(loop);
42+
zval *entries = OBJ_PROP_NUM(self, slots::entries);
43+
SEPARATE_ARRAY(entries);
44+
Z_ADDREF_P(entryScope);
45+
zend_hash_index_update(Z_ARRVAL_P(entries), id, entryScope);
4146
zval *head = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::heads)), id);
4247
if (head == nullptr) return zv::Val::copyOf(zv::Ref(entryScope));
4348

@@ -71,6 +76,12 @@ class ConvergedLoopHeads
7176
[[nodiscard]] bool record(zval *loop, zval *head) const
7277
{
7378
zend_ulong id = Z_OBJ_HANDLE_P(loop);
79+
// a walk the entry of which is unreachable does not widen the head
80+
zval *entry = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::entries)), id);
81+
bool unreachable;
82+
if (UNEXPECTED(!isUnreachable(Z_OBJ_P(entry), unreachable))) return false;
83+
if (unreachable) return true;
84+
7485
zval *previous = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::heads)), id);
7586
// an unchanged head keeps the warm entry derived from it
7687
if (previous != nullptr) {
@@ -91,6 +102,24 @@ class ConvergedLoopHeads
91102

92103
private:
93104
zend_object *self;
105+
106+
/* Mirrors isUnreachable(); false = pending exception */
107+
[[nodiscard]] static bool isUnreachable(zend_object *scope, bool &out)
108+
{
109+
out = false;
110+
zv::Val definedVariables = pt_mutating_scope_get_defined_variables(scope);
111+
if (UNEXPECTED(definedVariables.isUndef())) return false;
112+
for (zv::ArrayEntry variable : zv::TableRef(Z_ARRVAL_P(definedVariables.raw()))) {
113+
zv::Val variableType = pt_mutating_scope_get_variable_type(scope, Z_STR_P(variable.value().raw()));
114+
if (UNEXPECTED(variableType.isUndef())) return false;
115+
if (Z_TYPE_P(variableType.raw()) == IS_OBJECT && instanceof_function(Z_OBJCE_P(variableType.raw()), pt_ce_never_type)) {
116+
out = true;
117+
return true;
118+
}
119+
}
120+
121+
return true;
122+
}
94123
};
95124

96125
} // namespace phpstanturbo

‎turbo-ext/src/generated/ConvergedLoopHeads.h‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ namespace ptdecl::ConvergedLoopHeads {
1111
/* the OBJ_PROP_NUM slots of the instance properties the class declares (the inherited ones come first) */
1212
namespace slot {
1313
inline constexpr uint32_t heads = 0;
14-
inline constexpr uint32_t warmEntries = 1;
14+
inline constexpr uint32_t entries = 1;
15+
inline constexpr uint32_t warmEntries = 2;
1516
} // namespace slot
1617

1718
inline void declareClass(reg::Class &cls)
@@ -23,6 +24,7 @@ inline void declareClass(reg::Class &cls)
2324
inline void declareProperties(reg::Class &cls)
2425
{
2526
cls.property("heads", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY);
27+
cls.property("entries", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY);
2628
cls.property("warmEntries", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY);
2729
}
2830

@@ -36,14 +38,18 @@ inline constexpr char strings[] =
3638
"\0" /* 62 */
3739
"warmStart\0" /* 63 */
3840
"head\0" /* 73 */
39-
"record"; /* 78 */
41+
"record\0" /* 78 */
42+
"scope\0" /* 85 */
43+
"isUnreachable"; /* 91 */
4044
inline constexpr reg::PackedArg args[] = {
4145
reg::packed(0, 0, 5), /* warmStart $loop */
4246
reg::packed(20, 0, 31), /* warmStart $entryScope */
4347
reg::packed(62, 0, 31), /* warmStart return */
4448
reg::packed(0, 0, 5), /* record $loop */
4549
reg::packed(73, 0, 31), /* record $head */
4650
reg::packed(62, MAY_BE_VOID), /* record return */
51+
reg::packed(85, 0, 31), /* isUnreachable $scope */
52+
reg::packed(62, MAY_BE_BOOL), /* isUnreachable return */
4753
};
4854
using Sig = reg::Sig<strings, args>;
4955
} // namespace sigtab
@@ -52,6 +58,7 @@ using Sig = reg::Sig<strings, args>;
5258
namespace sig {
5359
inline constexpr sigtab::Sig warmStart = { { 63 /* warmStart */, 2, 0, 2, 2, ZEND_ACC_PUBLIC } };
5460
inline constexpr sigtab::Sig record = { { 78 /* record */, 2, 3, 2, 5, ZEND_ACC_PUBLIC } };
61+
inline constexpr sigtab::Sig isUnreachable = { { 91 /* isUnreachable */, 1, 6, 1, 7, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
5562
} // namespace sig
5663

5764
} // namespace ptdecl::ConvergedLoopHeads

0 commit comments

Comments
 (0)