Skip to content

Commit b234a39

Browse files
ondrejmirtesclaude
andcommitted
Remove a union of values from a set in one pass
Removing a UnionType peeled it one member at a time. Peeling is what keeps the result precise - removing one member can narrow the type so that removing the next achieves more - but it is quadratic whenever removing a member rebuilds the from-type, and subtracting a sealed hierarchy from its own type rebuilds the whole subtraction once per member. The whole union is now offered first where the subtraction is a set difference and no order of removals can sharpen it: a sealed hierarchy, or a union, whose members each weigh the same question again so that a member needing them one at a time still gets them that way. UnionType::tryRemove() takes a complete finite value set minus a union of values as one difference, and ObjectType::subtract() stops normalising a union that changeSubtractedType() only flattens and throws away - the describe() that keyed the matches goes with it, an allowed subtype being dropped as it matches so the matches cannot repeat. Removing a 250-case enum from its own type: 149ms -> 0.5ms. Removing 125 of 250 constant strings: 6.1ms -> 0.03ms. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LDqrN1pcN3qWc7xzKfkJaF
1 parent c2e16da commit b234a39

3 files changed

Lines changed: 157 additions & 41 deletions

File tree

‎src/Type/ObjectType.php‎

Lines changed: 70 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
use Traversable;
5858
use function array_key_exists;
5959
use function array_map;
60+
use function array_merge;
6061
use function array_values;
6162
use function count;
6263
use function get_class;
@@ -1751,11 +1752,24 @@ public function isInstanceOf(string $className): TrinaryLogic
17511752

17521753
public function subtract(Type $type): Type
17531754
{
1754-
if ($this->subtractedType !== null) {
1755-
$type = TypeCombinator::union($this->subtractedType, $type);
1755+
if ($this->subtractedType === null) {
1756+
return $this->changeSubtractedType($type);
17561757
}
17571758

1758-
return $this->changeSubtractedType($type);
1759+
// A sealed hierarchy rebuilds its subtraction from the flattened parts
1760+
// below, so normalising the union of the old and the new subtracted type
1761+
// first is wasted work - and quadratic when a removal peels the subtypes
1762+
// off one at a time, as removing a whole enum from its own type does.
1763+
// Only the path that keeps the subtracted type as it is needs the union.
1764+
$matched = $this->matchAllowedSubTypes(array_merge(
1765+
TypeUtils::flattenTypes($this->subtractedType),
1766+
TypeUtils::flattenTypes($type),
1767+
));
1768+
if ($matched !== null) {
1769+
return $matched;
1770+
}
1771+
1772+
return $this->changeSubtractedType(TypeCombinator::union($this->subtractedType, $type));
17591773
}
17601774

17611775
public function getTypeWithoutSubtractedType(): Type
@@ -1783,55 +1797,70 @@ public function withoutFinalByKeywordOverride(): Type
17831797
public function changeSubtractedType(?Type $subtractedType): Type
17841798
{
17851799
if ($subtractedType !== null) {
1786-
$classReflection = $this->getClassReflection();
1787-
$allowedSubTypes = $classReflection !== null ? $classReflection->getAllowedSubTypes() : null;
1788-
if ($allowedSubTypes !== null) {
1789-
$preciseVerbosity = VerbosityLevel::precise();
1790-
1791-
$originalAllowedSubTypes = $allowedSubTypes;
1792-
$subtractedSubTypes = [];
1793-
1794-
$subtractedTypes = TypeUtils::flattenTypes($subtractedType);
1795-
foreach ($subtractedTypes as $subType) {
1796-
foreach ($allowedSubTypes as $key => $allowedSubType) {
1797-
if ($subType->equals($allowedSubType)) {
1798-
$description = $allowedSubType->describe($preciseVerbosity);
1799-
$subtractedSubTypes[$description] = $subType;
1800-
unset($allowedSubTypes[$key]);
1801-
continue 2;
1802-
}
1803-
}
1800+
$matched = $this->matchAllowedSubTypes(TypeUtils::flattenTypes($subtractedType));
1801+
if ($matched !== null) {
1802+
return $matched;
1803+
}
1804+
}
18041805

1805-
return new self($this->className, $subtractedType);
1806-
}
1806+
if ($this->subtractedType === null && $subtractedType === null) {
1807+
return $this;
1808+
}
18071809

1808-
if (count($allowedSubTypes) === 1) {
1809-
return array_values($allowedSubTypes)[0];
1810-
}
1810+
return new self($this->className, $subtractedType);
1811+
}
18111812

1812-
$subtractedSubTypes = array_values($subtractedSubTypes);
1813-
$subtractedSubTypesCount = count($subtractedSubTypes);
1814-
if ($subtractedSubTypesCount === count($originalAllowedSubTypes)) {
1815-
return new NeverType();
1816-
}
1813+
/**
1814+
* Rebuilds the type from the subtracted members of its sealed hierarchy.
1815+
*
1816+
* Returns null when the class has no allowed subtypes, or when a subtracted
1817+
* type is not one of them - the caller then keeps the subtracted type whole.
1818+
*
1819+
* @param array<Type> $subtractedTypes flattened, may repeat
1820+
*/
1821+
private function matchAllowedSubTypes(array $subtractedTypes): ?Type
1822+
{
1823+
$classReflection = $this->getClassReflection();
1824+
$allowedSubTypes = $classReflection !== null ? $classReflection->getAllowedSubTypes() : null;
1825+
if ($allowedSubTypes === null) {
1826+
return null;
1827+
}
18171828

1818-
if ($subtractedSubTypesCount === 0) {
1819-
return new self($this->className);
1820-
}
1829+
$allowedSubTypesCount = count($allowedSubTypes);
1830+
$subtractedSubTypes = [];
18211831

1822-
if ($subtractedSubTypesCount === 1) {
1823-
return new self($this->className, $subtractedSubTypes[0]);
1832+
foreach ($subtractedTypes as $subType) {
1833+
foreach ($allowedSubTypes as $key => $allowedSubType) {
1834+
if ($subType->equals($allowedSubType)) {
1835+
// An allowed subtype is dropped as it matches, so no two matches
1836+
// can be the same one and the matches need no keying.
1837+
$subtractedSubTypes[] = $subType;
1838+
unset($allowedSubTypes[$key]);
1839+
continue 2;
18241840
}
1825-
1826-
return new self($this->className, new UnionType($subtractedSubTypes));
18271841
}
1842+
1843+
return null;
18281844
}
18291845

1830-
if ($this->subtractedType === null && $subtractedType === null) {
1831-
return $this;
1846+
if (count($allowedSubTypes) === 1) {
1847+
return array_values($allowedSubTypes)[0];
18321848
}
18331849

1834-
return new self($this->className, $subtractedType);
1850+
$subtractedSubTypesCount = count($subtractedSubTypes);
1851+
if ($subtractedSubTypesCount === $allowedSubTypesCount) {
1852+
return new NeverType();
1853+
}
1854+
1855+
if ($subtractedSubTypesCount === 0) {
1856+
return new self($this->className);
1857+
}
1858+
1859+
if ($subtractedSubTypesCount === 1) {
1860+
return new self($this->className, $subtractedSubTypes[0]);
1861+
}
1862+
1863+
return new self($this->className, new UnionType($subtractedSubTypes));
18351864
}
18361865

18371866
public function getSubtractedType(): ?Type

‎src/Type/TypeCombinator.php‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,54 @@ public static function remove(Type $fromType, Type $typeToRemove): Type
9898
return self::doRemove($fromType, $typeToRemove);
9999
}
100100

101+
/**
102+
* Whether removing the union's members all at once gives what removing them
103+
* one at a time would: true when the subtraction is a set difference, so no
104+
* order of removals can sharpen the result.
105+
*
106+
* Everywhere else the members have to come off one at a time - removing one
107+
* can narrow the type so that removing the next achieves more.
108+
*/
109+
private static function canRemoveUnionAtOnce(Type $fromType, UnionType $typeToRemove): bool
110+
{
111+
// A sealed hierarchy - an enum, or a hierarchy an
112+
// AllowedSubTypesClassReflectionExtension seals - subtracts by dropping
113+
// allowed subtypes, and which ones are dropped does not depend on order.
114+
$classReflections = $fromType->getObjectClassReflections();
115+
if (count($classReflections) === 1 && $classReflections[0]->getAllowedSubTypes() !== null) {
116+
return true;
117+
}
118+
119+
// A union removes the whole thing from each of its members, and each of
120+
// those removals weighs this same question again - so a member that needs
121+
// the removals one at a time still gets them that way.
122+
return $fromType instanceof UnionType;
123+
}
124+
101125
/** @internal Delegated to from TypeCombinatorCache, which the native extension shadows to memoize it. */
102126
public static function doRemove(Type $fromType, Type $typeToRemove): Type
103127
{
104128
if ($typeToRemove instanceof UnionType) {
129+
// Removing the members one at a time is what keeps the result precise:
130+
// removing one can narrow the type so that removing the next achieves
131+
// more. A sealed hierarchy is the exception - there the subtraction is
132+
// a set difference over the allowed subtypes, so the order the members
133+
// come off cannot matter, and peeling them would rebuild the whole
134+
// subtraction once per member (removing an enum from its own type then
135+
// costs O(cases^2)).
136+
if (self::canRemoveUnionAtOnce($fromType, $typeToRemove)) {
137+
$removed = $fromType->tryRemove($typeToRemove);
138+
if ($removed !== null) {
139+
return $removed;
140+
}
141+
}
142+
105143
foreach ($typeToRemove->getTypes() as $unionTypeToRemove) {
106144
$fromType = self::remove($fromType, $unionTypeToRemove);
145+
if ($fromType instanceof NeverType) {
146+
// there is nothing left to remove from
147+
break;
148+
}
107149
}
108150
return $fromType;
109151
}

‎src/Type/UnionType.php‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
use function array_diff_assoc;
4040
use function array_fill_keys;
4141
use function array_intersect;
42+
use function array_key_exists;
4243
use function array_keys;
4344
use function array_map;
4445
use function array_merge;
@@ -1567,6 +1568,50 @@ public function tryRemove(Type $typeToRemove): ?Type
15671568

15681569
return new UnionType($remainingTypes);
15691570
}
1571+
1572+
// Every member of this union is a distinct value, and so is every member
1573+
// of the removed one: the result is their set difference, which no order
1574+
// of removals can sharpen. Taking it in one pass keeps removing a union
1575+
// of values linear instead of re-deriving this union once per value.
1576+
if ($typeToRemove instanceof self) {
1577+
$keysToRemove = [];
1578+
foreach ($typeToRemove->getTypes() as $innerTypeToRemove) {
1579+
$innerKey = FiniteTypeSet::key($innerTypeToRemove);
1580+
if ($innerKey === null) {
1581+
$keysToRemove = null;
1582+
break;
1583+
}
1584+
1585+
$keysToRemove[$innerKey] = true;
1586+
}
1587+
1588+
if ($keysToRemove !== null) {
1589+
$remainingTypes = [];
1590+
$removedAny = false;
1591+
foreach ($finiteTypeSet->getMembers() as $memberKey => $member) {
1592+
if (array_key_exists($memberKey, $keysToRemove)) {
1593+
$removedAny = true;
1594+
continue;
1595+
}
1596+
1597+
$remainingTypes[] = $member;
1598+
}
1599+
1600+
if (!$removedAny) {
1601+
return null;
1602+
}
1603+
1604+
if (count($remainingTypes) === 0) {
1605+
return new NeverType();
1606+
}
1607+
1608+
if (count($remainingTypes) === 1) {
1609+
return $remainingTypes[0];
1610+
}
1611+
1612+
return new UnionType($remainingTypes);
1613+
}
1614+
}
15701615
}
15711616

15721617
$innerTypes = [];

0 commit comments

Comments
 (0)