Skip to content

Commit 39efdc6

Browse files
ondrejmirtesclaude
andcommitted
Match an intersection's finite types by value, not by description
IntersectionType::getFiniteTypes() keyed each member's finite types by describe(VerbosityLevel::typeOnly()), which is the same 'int', 'string' or 'float' for every value of a kind: (1|2)&(1|2|3) had the finite types [2] instead of [1, 2], and disjoint members could share one. The values are now keyed by FiniteTypeSet::key(), whose keys are equal exactly when the types are, and the values it does not key (floats, constant arrays) are matched with equals(). Ported to the native class the same way. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018Fdg8n3eEi4ZoXa4dA2k4A
1 parent f62737f commit 39efdc6

6 files changed

Lines changed: 259 additions & 58 deletions

File tree

‎phpstan-baseline.neon‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1392,12 +1392,6 @@ parameters:
13921392
count: 1
13931393
path: src/Type/IntersectionType.php
13941394

1395-
-
1396-
rawMessage: 'Doing instanceof PHPStan\Type\Enum\EnumCaseObjectType is error-prone and deprecated. Use Type::getEnumCaseObject() or Type::getEnumCases() instead.'
1397-
identifier: phpstanApi.instanceofType
1398-
count: 1
1399-
path: src/Type/IntersectionType.php
1400-
14011395
-
14021396
rawMessage: Doing instanceof PHPStan\Type\IntersectionType is error-prone and deprecated.
14031397
identifier: phpstanApi.instanceofType

‎src/Type/IntersectionType.php‎

Lines changed: 75 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
use PHPStan\Type\Traits\NonRemoveableTypeTrait;
5757
use function array_filter;
5858
use function array_intersect_key;
59+
use function array_key_exists;
5960
use function array_map;
6061
use function array_shift;
6162
use function array_unique;
@@ -64,6 +65,7 @@
6465
use function implode;
6566
use function in_array;
6667
use function is_int;
68+
use function is_string;
6769
use function ksort;
6870
use function sprintf;
6971
use function str_starts_with;
@@ -1785,20 +1787,32 @@ public function exponentiate(Type $exponent): Type
17851787

17861788
public function getFiniteTypes(): array
17871789
{
1788-
$compare = [];
1790+
$first = null;
1791+
$others = [];
17891792
foreach ($this->types as $type) {
1790-
$oneType = [];
1791-
foreach ($type->getFiniteTypes() as $finiteType) {
1792-
if ($finiteType instanceof EnumCaseObjectType) {
1793-
$oneType[$finiteType->getClassName() . '::' . $finiteType->getEnumCaseName()] = $finiteType;
1794-
continue;
1795-
}
1796-
$oneType[$finiteType->describe(VerbosityLevel::typeOnly())] = $finiteType;
1793+
$indexed = self::indexFiniteTypes($type->getFiniteTypes());
1794+
if ($first === null) {
1795+
$first = $indexed;
1796+
continue;
17971797
}
1798-
$compare[] = $oneType;
1798+
1799+
$others[] = $indexed;
1800+
}
1801+
1802+
if ($first === null) {
1803+
return [];
17991804
}
18001805

1801-
$result = array_values(array_intersect_key(...$compare));
1806+
$result = [];
1807+
foreach ($first as $key => $finiteType) {
1808+
foreach ($others as $other) {
1809+
if (!self::hasFiniteType($other, is_string($key) ? $key : null, $finiteType)) {
1810+
continue 2;
1811+
}
1812+
}
1813+
1814+
$result[] = $finiteType;
1815+
}
18021816

18031817
if (count($result) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
18041818
return [];
@@ -1807,6 +1821,57 @@ public function getFiniteTypes(): array
18071821
return $result;
18081822
}
18091823

1824+
/**
1825+
* The finite types of one member, one per value, in their order: keyed by
1826+
* FiniteTypeSet::key(), which never keys by a number, and the values it
1827+
* does not key (floats, constant arrays) by a list position, deduplicated
1828+
* by equals().
1829+
*
1830+
* @param list<Type> $finiteTypes
1831+
* @return array<int|string, Type>
1832+
*/
1833+
private static function indexFiniteTypes(array $finiteTypes): array
1834+
{
1835+
$indexed = [];
1836+
foreach ($finiteTypes as $finiteType) {
1837+
$key = FiniteTypeSet::key($finiteType);
1838+
if ($key !== null) {
1839+
$indexed[$key] = $finiteType;
1840+
continue;
1841+
}
1842+
1843+
foreach ($indexed as $existingKey => $existing) {
1844+
if (is_int($existingKey) && $existing->equals($finiteType)) {
1845+
$indexed[$existingKey] = $finiteType;
1846+
continue 2;
1847+
}
1848+
}
1849+
1850+
$indexed[] = $finiteType;
1851+
}
1852+
1853+
return $indexed;
1854+
}
1855+
1856+
/**
1857+
* @param array<int|string, Type> $indexed
1858+
* @param string|null $key the FiniteTypeSet::key() of $finiteType
1859+
*/
1860+
private static function hasFiniteType(array $indexed, ?string $key, Type $finiteType): bool
1861+
{
1862+
if ($key !== null) {
1863+
return array_key_exists($key, $indexed);
1864+
}
1865+
1866+
foreach ($indexed as $otherKey => $other) {
1867+
if (is_int($otherKey) && $other->equals($finiteType)) {
1868+
return true;
1869+
}
1870+
}
1871+
1872+
return false;
1873+
}
1874+
18101875
/**
18111876
* @param callable(Type $type): TrinaryLogic $getResult
18121877
* @param (callable(Type $type): bool)|null $filter

‎tests/PHPStan/Type/IntersectionTypeTest.php‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
use PHPStan\Type\Accessory\NonEmptyArrayType;
2121
use PHPStan\Type\Accessory\OversizedArrayType;
2222
use PHPStan\Type\Constant\ConstantArrayType;
23+
use PHPStan\Type\Constant\ConstantBooleanType;
24+
use PHPStan\Type\Constant\ConstantFloatType;
2325
use PHPStan\Type\Constant\ConstantIntegerType;
2426
use PHPStan\Type\Constant\ConstantStringType;
2527
use PHPStan\Type\Enum\EnumCaseObjectType;
@@ -30,6 +32,7 @@
3032
use stdClass;
3133
use Test\ClassWithToString;
3234
use Traversable;
35+
use function array_map;
3336
use function count;
3437
use function sprintf;
3538
use const PHP_INT_MAX;
@@ -1017,6 +1020,57 @@ public function testConstantOfIntersectionWithTemplateMixed(IntersectionType $ty
10171020
$this->assertSame(DateTimeInterface::class, $constant->getDeclaringClass()->getName());
10181021
}
10191022

1023+
/**
1024+
* @return Iterator<string, array{IntersectionType, list<string>}>
1025+
*/
1026+
public static function dataGetFiniteTypes(): Iterator
1027+
{
1028+
yield 'integers' => [
1029+
new IntersectionType([
1030+
new UnionType([new ConstantIntegerType(1), new ConstantIntegerType(2)]),
1031+
new UnionType([new ConstantIntegerType(1), new ConstantIntegerType(2), new ConstantIntegerType(3)]),
1032+
]),
1033+
['1', '2'],
1034+
];
1035+
yield 'strings' => [
1036+
new IntersectionType([
1037+
new UnionType([new ConstantStringType('a'), new ConstantStringType('b'), new ConstantStringType('c')]),
1038+
new UnionType([new ConstantStringType('c'), new ConstantStringType('a')]),
1039+
]),
1040+
["'a'", "'c'"],
1041+
];
1042+
yield 'floats' => [
1043+
new IntersectionType([
1044+
new UnionType([new ConstantFloatType(1.5), new ConstantFloatType(2.5)]),
1045+
new UnionType([new ConstantFloatType(2.5), new ConstantFloatType(3.5)]),
1046+
]),
1047+
['2.5'],
1048+
];
1049+
yield 'mixed kinds' => [
1050+
new IntersectionType([
1051+
new UnionType([new ConstantIntegerType(1), new ConstantStringType('1'), new ConstantBooleanType(true), new NullType()]),
1052+
new UnionType([new ConstantStringType('1'), new NullType(), new ConstantIntegerType(2)]),
1053+
]),
1054+
["'1'", 'null'],
1055+
];
1056+
yield 'disjoint' => [
1057+
new IntersectionType([
1058+
new UnionType([new ConstantIntegerType(1), new ConstantIntegerType(2)]),
1059+
new UnionType([new ConstantIntegerType(3), new ConstantIntegerType(4)]),
1060+
]),
1061+
[],
1062+
];
1063+
}
1064+
1065+
/**
1066+
* @param list<string> $expected
1067+
*/
1068+
#[DataProvider('dataGetFiniteTypes')]
1069+
public function testGetFiniteTypes(IntersectionType $type, array $expected): void
1070+
{
1071+
$this->assertSame($expected, array_map(static fn (Type $finiteType): string => $finiteType->describe(VerbosityLevel::precise()), $type->getFiniteTypes()));
1072+
}
1073+
10201074
public function testSetOffsetValueTypeOnListWithOffsetAtIntMax(): void
10211075
{
10221076
$type = new IntersectionType([

‎turbo-ext/src/IntersectionType.cpp‎

Lines changed: 79 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2148,35 +2148,91 @@ class IntersectionType
21482148
zval *types = this->types();
21492149
if (UNEXPECTED(types == NULL)) return zv::Val();
21502150
zv::Val typesCopy = zv::Val::copyOf(zv::Ref(types));
2151-
zv::Val typeOnly;
2152-
std::vector<zv::Val> compare;
2151+
zv::Val first;
2152+
std::vector<zv::Val> others;
21532153
for (zv::ArrayEntry entry : zv::ArrRef(typesCopy.raw())) {
21542154
zv::Val finiteTypes = pt_type_call_array(entry.value().deref().asObject(), PT_LC("getfinitetypes"), 0, NULL);
21552155
if (UNEXPECTED(finiteTypes.isUndef())) return zv::Val();
2156-
zv::Arr oneType = zv::Arr::create(zv::ArrRef(finiteTypes.raw()).size());
2157-
for (zv::ArrayEntry finiteEntry : zv::ArrRef(finiteTypes.raw())) {
2158-
zval *finiteType = finiteEntry.value().deref().raw();
2159-
bool isEnumCase;
2160-
if (UNEXPECTED(!pt_type_instanceof_ce(finiteType, pt_ce_enum_case_object_type, isEnumCase))) return zv::Val();
2161-
zv::Val key;
2162-
if (isEnumCase) {
2163-
key = enumCaseKey(finiteType);
2164-
} else {
2165-
if (typeOnly.isUndef()) {
2166-
typeOnly = verbosityLevel(PT_VERBOSITY_LEVEL_TYPE_ONLY);
2167-
if (UNEXPECTED(typeOnly.isUndef())) return zv::Val();
2168-
}
2169-
key = describeOf(finiteType, typeOnly.raw());
2170-
}
2171-
if (UNEXPECTED(key.isUndef())) return zv::Val();
2172-
oneType.set(zv::Ref(key.raw()).asString(), zv::Val::copyOf(zv::Ref(finiteType)));
2156+
zv::Val indexed = indexFiniteTypes(finiteTypes.raw());
2157+
if (UNEXPECTED(indexed.isUndef())) return zv::Val();
2158+
if (first.isUndef()) {
2159+
first = std::move(indexed);
2160+
continue;
2161+
}
2162+
others.push_back(std::move(indexed));
2163+
}
2164+
2165+
if (first.isUndef()) return zv::Val(zv::Arr::empty());
2166+
2167+
zv::Arr result = zv::Arr::create(0);
2168+
for (zv::ArrayEntry entry : zv::ArrRef(first.raw())) {
2169+
bool inAll = true;
2170+
for (zv::Val &other : others) {
2171+
if (UNEXPECTED(!hasFiniteType(other.raw(), entry.stringKeyOrNull(), entry.value().raw(), inAll))) return zv::Val();
2172+
if (!inAll) break;
2173+
}
2174+
if (inAll) {
2175+
result.push(entry.value());
21732176
}
2174-
compare.push_back(zv::Val(std::move(oneType)));
21752177
}
2176-
zv::Val result = intersectKeysOf(compare);
2177-
if (UNEXPECTED(result.isUndef())) return zv::Val();
21782178
if ((zend_long) zv::ArrRef(result.raw()).size() > PT_INITIALIZER_EXPR_TYPE_RESOLVER_CALCULATE_SCALARS_LIMIT) return zv::Val(zv::Arr::empty());
2179-
return result;
2179+
return zv::Val(std::move(result));
2180+
}
2181+
2182+
/* the twin's indexFiniteTypes(): the finite types of one member, one per
2183+
* value, in their order — keyed by FiniteTypeSet::key() (never numeric),
2184+
* the values it does not key by a list position, deduplicated by
2185+
* equals(); UNDEF = pending exception */
2186+
static zv::Val indexFiniteTypes(zval *finiteTypes)
2187+
{
2188+
zv::Arr indexed = zv::Arr::create(zv::ArrRef(finiteTypes).size());
2189+
for (zv::ArrayEntry entry : zv::ArrRef(finiteTypes)) {
2190+
zval *finiteType = entry.value().deref().raw();
2191+
zv::Val key = pt_type_finite_type_set_key(finiteType);
2192+
if (UNEXPECTED(key.isUndef())) return zv::Val();
2193+
if (!key.isNull()) {
2194+
indexed.set(zv::Ref(key.raw()).asString(), zv::Val::copyOf(zv::Ref(finiteType)));
2195+
continue;
2196+
}
2197+
bool replaced = false;
2198+
for (zv::ArrayEntry existing : zv::ArrRef(indexed.raw())) {
2199+
if (existing.stringKeyOrNull() != NULL) continue;
2200+
bool equal;
2201+
if (UNEXPECTED(!pt_type_op_bool(existing.value().deref().asObject(), PT_OP_EQUALS, 1, finiteType, equal))) return zv::Val();
2202+
if (!equal) continue;
2203+
zval copy;
2204+
ZVAL_COPY(&copy, finiteType);
2205+
zend_hash_index_update(indexed.table(), existing.indexKey(), &copy);
2206+
replaced = true;
2207+
break;
2208+
}
2209+
if (!replaced) {
2210+
indexed.push(zv::Val::copyOf(zv::Ref(finiteType)));
2211+
}
2212+
}
2213+
return zv::Val(std::move(indexed));
2214+
}
2215+
2216+
/* the twin's hasFiniteType(): $key (NULL for a value FiniteTypeSet::key()
2217+
* does not key) among $indexed's keys, or an equal unkeyed value; false =
2218+
* pending exception */
2219+
[[nodiscard]] static bool hasFiniteType(zval *indexed, zend_string *key, zval *finiteType, bool &out)
2220+
{
2221+
if (key != NULL) {
2222+
out = zend_symtable_find(Z_ARRVAL_P(indexed), key) != NULL;
2223+
return true;
2224+
}
2225+
for (zv::ArrayEntry other : zv::ArrRef(indexed)) {
2226+
if (other.stringKeyOrNull() != NULL) continue;
2227+
bool equal;
2228+
if (UNEXPECTED(!pt_type_op_bool(other.value().deref().asObject(), PT_OP_EQUALS, 1, finiteType, equal))) return false;
2229+
if (equal) {
2230+
out = true;
2231+
return true;
2232+
}
2233+
}
2234+
out = false;
2235+
return true;
21802236
}
21812237

21822238
/* whether any member has one; -1 = pending exception */

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

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -266,15 +266,21 @@ inline constexpr char strings[] =
266266
"exponent\0" /* 3435 */
267267
"exponentiate\0" /* 3444 */
268268
"getFiniteTypes\0" /* 3457 */
269-
"getResult\0" /* 3472 */
270-
"filter\0" /* 3482 */
271-
"intersectResults\0" /* 3489 */
272-
"getType\0" /* 3506 */
273-
"intersectTypes\0" /* 3514 */
274-
"intersectTypesPreserveTemplateType\0" /* 3529 */
275-
"PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 3564 */
276-
"toPhpDocNode\0" /* 3603 */
277-
"hasTemplateOrLateResolvableType"; /* 3616 */
269+
"finiteTypes\0" /* 3472 */
270+
"indexFiniteTypes\0" /* 3484 */
271+
"indexed\0" /* 3501 */
272+
"key\0" /* 3509 */
273+
"finiteType\0" /* 3513 */
274+
"hasFiniteType\0" /* 3524 */
275+
"getResult\0" /* 3538 */
276+
"filter\0" /* 3548 */
277+
"intersectResults\0" /* 3555 */
278+
"getType\0" /* 3572 */
279+
"intersectTypes\0" /* 3580 */
280+
"intersectTypesPreserveTemplateType\0" /* 3595 */
281+
"PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 3630 */
282+
"toPhpDocNode\0" /* 3669 */
283+
"hasTemplateOrLateResolvableType"; /* 3682 */
278284
inline constexpr reg::PackedArg args[] = {
279285
reg::packed(0, MAY_BE_ARRAY), /* __construct $types */
280286
reg::packed(18, MAY_BE_ARRAY), /* getTypes return */
@@ -511,14 +517,20 @@ inline constexpr reg::PackedArg args[] = {
511517
reg::packed(3435, 0, 56), /* exponentiate $exponent */
512518
reg::packed(18, 0, 56), /* exponentiate return */
513519
reg::packed(18, MAY_BE_ARRAY), /* getFiniteTypes return */
514-
reg::packed(3472, MAY_BE_CALLABLE), /* intersectResults $getResult */
515-
reg::packed(3482, MAY_BE_NULL | MAY_BE_CALLABLE, reg::NoString, false, false, 2271), /* intersectResults $filter */
520+
reg::packed(3472, MAY_BE_ARRAY), /* indexFiniteTypes $finiteTypes */
521+
reg::packed(18, MAY_BE_ARRAY), /* indexFiniteTypes return */
522+
reg::packed(3501, MAY_BE_ARRAY), /* hasFiniteType $indexed */
523+
reg::packed(3509, MAY_BE_NULL | MAY_BE_STRING), /* hasFiniteType $key */
524+
reg::packed(3513, 0, 56), /* hasFiniteType $finiteType */
525+
reg::packed(18, MAY_BE_BOOL), /* hasFiniteType return */
526+
reg::packed(3538, MAY_BE_CALLABLE), /* intersectResults $getResult */
527+
reg::packed(3548, MAY_BE_NULL | MAY_BE_CALLABLE, reg::NoString, false, false, 2271), /* intersectResults $filter */
516528
reg::packed(18, 0, 542), /* intersectResults return */
517-
reg::packed(3506, MAY_BE_CALLABLE), /* intersectTypes $getType */
529+
reg::packed(3572, MAY_BE_CALLABLE), /* intersectTypes $getType */
518530
reg::packed(18, 0, 56), /* intersectTypes return */
519-
reg::packed(3506, MAY_BE_CALLABLE), /* intersectTypesPreserveTemplateType $getType */
531+
reg::packed(3572, MAY_BE_CALLABLE), /* intersectTypesPreserveTemplateType $getType */
520532
reg::packed(18, 0, 56), /* intersectTypesPreserveTemplateType return */
521-
reg::packed(18, 0, 3564), /* toPhpDocNode return */
533+
reg::packed(18, 0, 3630), /* toPhpDocNode return */
522534
reg::packed(18, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */
523535
};
524536
using Sig = reg::Sig<strings, args>;
@@ -667,11 +679,13 @@ inline constexpr sigtab::Sig traverseSimultaneously = { { 3389 /* traverseSimult
667679
inline constexpr sigtab::Sig tryRemove = { { 3425 /* tryRemove */, 1, 230, 1, 231, ZEND_ACC_PUBLIC } };
668680
inline constexpr sigtab::Sig exponentiate = { { 3444 /* exponentiate */, 1, 232, 1, 233, ZEND_ACC_PUBLIC } };
669681
inline constexpr sigtab::Sig getFiniteTypes = { { 3457 /* getFiniteTypes */, 0, 234, 0, 234, ZEND_ACC_PUBLIC } };
670-
inline constexpr sigtab::Sig intersectResults = { { 3489 /* intersectResults */, 1, 235, 2, 237, ZEND_ACC_PRIVATE } };
671-
inline constexpr sigtab::Sig intersectTypes = { { 3514 /* intersectTypes */, 1, 238, 1, 239, ZEND_ACC_PRIVATE } };
672-
inline constexpr sigtab::Sig intersectTypesPreserveTemplateType = { { 3529 /* intersectTypesPreserveTemplateType */, 1, 240, 1, 241, ZEND_ACC_PRIVATE } };
673-
inline constexpr sigtab::Sig toPhpDocNode = { { 3603 /* toPhpDocNode */, 0, 242, 0, 242, ZEND_ACC_PUBLIC } };
674-
inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 3616 /* hasTemplateOrLateResolvableType */, 0, 243, 0, 243, ZEND_ACC_PUBLIC } };
682+
inline constexpr sigtab::Sig indexFiniteTypes = { { 3484 /* indexFiniteTypes */, 1, 235, 1, 236, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
683+
inline constexpr sigtab::Sig hasFiniteType = { { 3524 /* hasFiniteType */, 3, 237, 3, 240, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
684+
inline constexpr sigtab::Sig intersectResults = { { 3555 /* intersectResults */, 1, 241, 2, 243, ZEND_ACC_PRIVATE } };
685+
inline constexpr sigtab::Sig intersectTypes = { { 3580 /* intersectTypes */, 1, 244, 1, 245, ZEND_ACC_PRIVATE } };
686+
inline constexpr sigtab::Sig intersectTypesPreserveTemplateType = { { 3595 /* intersectTypesPreserveTemplateType */, 1, 246, 1, 247, ZEND_ACC_PRIVATE } };
687+
inline constexpr sigtab::Sig toPhpDocNode = { { 3669 /* toPhpDocNode */, 0, 248, 0, 248, ZEND_ACC_PUBLIC } };
688+
inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 3682 /* hasTemplateOrLateResolvableType */, 0, 249, 0, 249, ZEND_ACC_PUBLIC } };
675689
} // namespace sig
676690

677691
} // namespace ptdecl::IntersectionType

0 commit comments

Comments
 (0)