Skip to content

Commit 0829b8e

Browse files
ondrejmirtesclaude
andcommitted
Stop interning TypeCombinator results in the turbo extension
Interning (873ede9) kept one canonical instance per type value, so equal types reached by unrelated routes became the same object. Every place in the analyser that compares Type objects by identity - a proxy for "the same reference" that only holds while equal values stay distinct objects - then narrowed or resolved types it never meant to: with the extension `(T is array ? T : null)` came out as `array<array>|null` because the `mixed` value type of the `array` branch was the very object the subject had resolved to (phpstan/phpstan#15151). The native cache goes back to the memo as it was before interning; it only hands a result to structurally equal argument tuples of the same operation. TypeCombinator::doUnion() returning the operand for equal array operands (5d39326) stays, the memo relies on it just the same. The regression tests of the fix are added as they stand: the reporter's files as an E2E test in the turbo job, and the nsrt fixtures covering the identity narrowing, the parameter conditionals and the variance lookup. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FuKACbcMfZeRgpvHJrHvqw
1 parent ae70e9f commit 0829b8e

11 files changed

Lines changed: 537 additions & 322 deletions

File tree

‎.github/workflows/e2e-tests.yml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,23 @@ jobs:
11821182
echo "$OUTPUT"
11831183
e2e/bashunit -a contains 'Turbo extension: enabled' "$OUTPUT"
11841184
1185+
- name: "Verify conditional types leave interned types equal to a resolved subject alone"
1186+
# With the extension active TypeCombinator's results are interned, so equal
1187+
# types share one instance. ConditionalType used to narrow the types in its
1188+
# branches identical to the subject even once the subject had resolved to a
1189+
# concrete type, and interning made that hit unrelated types - the `mixed`
1190+
# value type of an `array` branch for a `mixed` subject -
1191+
# https://github.com/phpstan/phpstan/issues/15151
1192+
run: |
1193+
cd e2e/bug-15151
1194+
OUTPUT=$(php ../../bin/phpstan analyse --no-progress --error-format=raw 2>&1 || true)
1195+
echo "$OUTPUT"
1196+
../bashunit -a contains 'reception_formulaire.php:20:Dumped type: mixed' "$OUTPUT"
1197+
../bashunit -a contains 'webservice.php:25:Dumped type: mixed' "$OUTPUT"
1198+
../bashunit -a not_contains 'Dumped type: array' "$OUTPUT"
1199+
# the two dumps are the only errors: count the file:line:message lines
1200+
../bashunit -a equals '2' "$(echo "$OUTPUT" | grep -Ec '^/.+:[0-9]+:')"
1201+
11851202
- name: "Test"
11861203
# The arena is a per-run POSIX shared-memory object: shm_open() plus an
11871204
# ftruncate() to 256 MB that tmpfs honours sparsely, committing pages on

‎e2e/bug-15151/functions.php‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
namespace MyApp;
4+
5+
6+
/**
7+
* Note. The bug disappears if I remove this function or if I edit it in certain ways.
8+
*
9+
* @param ?int $quote_style
10+
* @param array{string, string}|bool|null ...$substitutions_list
11+
* @return ($string is null ? null : ($string is '' ? '' : ($string is non-empty-string ? non-empty-string : string)))
12+
*/
13+
function htmlentities2(string|int|float|\BackedEnum|null $string, ?int $quote_style = \ENT_QUOTES, array|bool|null ...$substitutions_list): string|null {
14+
if ($string instanceof \BackedEnum)
15+
$string = validate_string($string->value);
16+
if ($string === null)
17+
return null;
18+
$string = validate_string($string) ?? throw new \ValueError('Incompatible value');
19+
$sortie = \htmlspecialchars($string, ($quote_style ?? \ENT_QUOTES) | \ENT_HTML401 | \ENT_SUBSTITUTE, 'utf-8');
20+
foreach ($substitutions_list as $substitutions) {
21+
if ($substitutions) {
22+
if ($substitutions === true)
23+
$substitutions = [ [ "\n", "\r" ], [ '<br/>', '' ] ];
24+
$sortie = \str_replace($substitutions[0], $substitutions[1], $sortie);
25+
}
26+
}
27+
return $sortie;
28+
}
29+
30+
31+
32+
/**
33+
* @template T
34+
* @param T $val
35+
* @return (T is array ? T : null)
36+
*/
37+
function validate_array(mixed $val): ?array {
38+
return \is_array($val) ? $val : null;
39+
}
40+
41+
42+
/**
43+
* @template T of mixed
44+
* @param T $val
45+
* @return ($val is string ? T&string : ($val is int ? decimal-int-string : ($val is float ? ?numeric-string : null)))
46+
*/
47+
function validate_string(mixed $val): ?string {
48+
if (\is_string($val)) {
49+
return $val;
50+
}
51+
elseif (\is_int($val)) {
52+
return (string) $val;
53+
}
54+
elseif (\is_float($val)) {
55+
return (string) $val;
56+
}
57+
return null;
58+
}

‎e2e/bug-15151/phpstan.neon‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
parameters:
2+
level: 8
3+
paths:
4+
- .
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
namespace MyApp;
4+
5+
class reception_formulaire {
6+
7+
/** @var list<array{valeur: string, affichage: string}> */
8+
public array $liste_genre_pers = [ ];
9+
10+
11+
// @phpstan-ignore missingType.iterableValue (a phpstan error seems useful in order to trigger the bug)
12+
final function __construct(
13+
protected readonly array $params
14+
) { }
15+
16+
17+
public function foo(): void {
18+
$liste_genre = [ ];
19+
foreach (validate_array($this->params['Genre_Admis'] ?? null) ?? [ ] as $_) {
20+
\PHPStan\dumpType($_); // ### should be: mixed, sometimes incorrectly: array
21+
if (in_array($_, [ 'Cli', 'Emp', 'Fou', 'Pct', 'Pre', 'Self' ], true))
22+
$liste_genre[] = $_;
23+
}
24+
$liste_genre_pers = [ ];
25+
foreach ($liste_genre as $ce_genre) {
26+
$liste_genre_pers[] = [ 'valeur' => $ce_genre, 'affichage' => '['.$ce_genre.']' ];
27+
}
28+
$this->liste_genre_pers = $liste_genre_pers;
29+
30+
}
31+
32+
33+
}

‎e2e/bug-15151/webservice.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
namespace MyApp;
4+
5+
class webservice {
6+
7+
/**
8+
* @param array{limit_defaut: positive-int, limit_max: positive-int} $opt
9+
* @return array{positive-int, non-negative-int, list<non-empty-string>}
10+
* @phpstan-ignore missingType.iterableValue (a phpstan error seems useful in order to trigger the bug)
11+
*/
12+
public static function get_limit_offset_sort(array $par, array $opt): array {
13+
$limit = isset($par['limit']) ? (int) $par['limit'] : $opt['limit_defaut'];
14+
if ($limit < 1)
15+
$limit = 1;
16+
if ($limit > $opt['limit_max'])
17+
$limit = $opt['limit_max'];
18+
19+
$offset = isset($par['offset']) ? (int) $par['offset'] : 0;
20+
if ($offset < 0)
21+
$offset = 0;
22+
23+
$sort = [ ];
24+
foreach (validate_array($par['sort'] ?? null) ?? [ ] as $_) {
25+
\PHPStan\dumpType($_); // ### should be: mixed, sometimes incorrectly: array
26+
$_ = validate_string($_);
27+
if ($_ !== null && $_ !== '')
28+
$sort[] = $_;
29+
}
30+
31+
return [ $limit, $offset, $sort ];
32+
33+
}
34+
35+
36+
}

‎src/Type/TypeCombinatorCache.php‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
* This PHP implementation performs no caching at all — it delegates straight to
1111
* TypeCombinator. The native implementation memoizes each operation on a
1212
* structural key of its arguments; roughly 91% of the calls in a
13-
* self-analysis run repeat an argument tuple that was already computed. It also
14-
* interns the results, keeping one canonical instance per distinct type value,
15-
* so operations reaching the same value by different routes return the same
16-
* object and identity checks can stand in for structural comparison.
13+
* self-analysis run repeat an argument tuple that was already computed. It does
14+
* not intern the results: equal types reached by different routes stay distinct
15+
* objects, as they do here, because code comparing Type objects by identity
16+
* relies on that.
1717
*
1818
* The cache is scoped to a single container: it hands back shared Type
1919
* instances, and Type objects carry a lazily resolved ClassReflection tied to the
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php // lint >= 8.1
2+
3+
namespace Bug15151;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template T
9+
* @param T $val
10+
* @return (T is array ? T : null)
11+
*/
12+
function validate_array(mixed $val): ?array {
13+
return \is_array($val) ? $val : null;
14+
}
15+
16+
class reception_formulaire {
17+
18+
// @phpstan-ignore missingType.iterableValue
19+
final function __construct(
20+
protected readonly array $params
21+
) { }
22+
23+
public function foo(): void {
24+
foreach (validate_array($this->params['Genre_Admis'] ?? null) ?? [ ] as $_) {
25+
assertType('mixed', $_);
26+
}
27+
}
28+
29+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace ConditionalTypeForParameterTemplateBound;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template TData
9+
*/
10+
interface FormTypeInterface
11+
{
12+
13+
}
14+
15+
/**
16+
* @template TData
17+
*/
18+
interface FormInterface
19+
{
20+
21+
/**
22+
* @return TData
23+
*/
24+
public function getData();
25+
26+
}
27+
28+
class DataClass
29+
{
30+
31+
}
32+
33+
/**
34+
* @implements FormTypeInterface<DataClass>
35+
*/
36+
class DataClassType implements FormTypeInterface
37+
{
38+
39+
}
40+
41+
class Controller
42+
{
43+
44+
/**
45+
* @template TFormType of FormTypeInterface<TData>
46+
* @template TData
47+
*
48+
* @param class-string<TFormType> $type
49+
* @param TData $data
50+
* @param array<string, mixed> $options
51+
*
52+
* @phpstan-return ($data is null ? FormInterface<null|TData> : FormInterface<TData>)
53+
*/
54+
protected function createForm(string $type, $data = null, array $options = []): FormInterface
55+
{
56+
throw new \Exception();
57+
}
58+
59+
public function doSomethingNullable(): void
60+
{
61+
$form = $this->createForm(DataClassType::class);
62+
assertType('ConditionalTypeForParameterTemplateBound\DataClass|null', $form->getData());
63+
}
64+
65+
public function doSomething(): void
66+
{
67+
$form = $this->createForm(DataClassType::class, new DataClass());
68+
assertType('ConditionalTypeForParameterTemplateBound\DataClass', $form->getData());
69+
}
70+
71+
public function doSomethingNull(): void
72+
{
73+
$form = $this->createForm(DataClassType::class, null);
74+
assertType('ConditionalTypeForParameterTemplateBound\DataClass|null', $form->getData());
75+
}
76+
77+
}
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
<?php // lint >= 8.0
2+
3+
namespace ConditionalTypeForParameterTemplate;
4+
5+
use stdClass;
6+
use function PHPStan\Testing\assertType;
7+
8+
class A
9+
{
10+
11+
/**
12+
* @template T
13+
* @param T $result
14+
* @return ($result is false ? never : T)
15+
*/
16+
public function throwOnFailure($result)
17+
{
18+
if ($result === false) {
19+
throw new \Exception();
20+
}
21+
22+
return $result;
23+
}
24+
25+
/**
26+
* @template T
27+
* @param T $result
28+
* @return ($result is not false ? T : never)
29+
*/
30+
public function negated($result)
31+
{
32+
if ($result === false) {
33+
throw new \Exception();
34+
}
35+
36+
return $result;
37+
}
38+
39+
/**
40+
* @template T
41+
* @param T $a
42+
* @param T $b
43+
* @return ($a is false ? never : T)
44+
*/
45+
public function boundByTwoParameters($a, $b)
46+
{
47+
throw new \Exception();
48+
}
49+
50+
/**
51+
* @template T
52+
* @param T $a
53+
* @param list<T> $others
54+
* @return ($a is false ? never : T)
55+
*/
56+
public function boundByAnotherParameter($a, array $others)
57+
{
58+
throw new \Exception();
59+
}
60+
61+
/**
62+
* @template T
63+
* @param T|null $value
64+
* @return ($value is null ? never : T)
65+
*/
66+
public function nullable($value)
67+
{
68+
throw new \Exception();
69+
}
70+
71+
/**
72+
* @template T
73+
* @param T $val
74+
* @return ($val is array ? T : null)
75+
*/
76+
public function validateArray(mixed $val): ?array
77+
{
78+
return \is_array($val) ? $val : null;
79+
}
80+
81+
}
82+
83+
/**
84+
* @template T
85+
* @param T $result
86+
* @return ($result is false ? never : T)
87+
*/
88+
function throwOnFailure($result)
89+
{
90+
if ($result === false) {
91+
throw new \Exception();
92+
}
93+
94+
return $result;
95+
}
96+
97+
/**
98+
* @param stdClass|false $v
99+
* @param array{a: int}|string $as
100+
*/
101+
function test(A $a, $v, $as, mixed $m, ?stdClass $n): void
102+
{
103+
assertType('stdClass', $a->throwOnFailure($v));
104+
assertType('stdClass', throwOnFailure($v));
105+
assertType('stdClass', $a->negated($v));
106+
assertType("'str'|stdClass|false", $a->boundByTwoParameters($v, 'str'));
107+
assertType('stdClass|false', $a->boundByAnotherParameter($v, []));
108+
assertType('stdClass', $a->nullable($n));
109+
assertType('array|null', $a->validateArray($as));
110+
111+
foreach ($a->validateArray($m) ?? [] as $x) {
112+
assertType('mixed', $x);
113+
assertType('array|null', $a->validateArray($x));
114+
}
115+
}

0 commit comments

Comments
 (0)