Skip to content

Commit a0d9720

Browse files
ondrejmirtesclaude
andcommitted
Avoid redundant work in hot type-system and scope paths
Profiling self-analysis (`analyse -l 8 src/Analyser src/Rules src/Type`) surfaced several spots that recompute results that are either cacheable or provably unnecessary. None of these change behaviour: - MutatingScope::shouldInvalidateExpression: getNodeKey() is the pretty-printed expression and the printer is compositional, so a sub-expression's key is always a substring of its container's key. When the invalidated key is not a substring of a stored expression's key, that expression cannot contain it and the NodeFinder AST traversal is skipped. Carve-outs for '$this' (matches self/static/parent), the non-compositional '__phpstan…' virtual nodes, and '/*…*/' key suffixes keep it exact. - IntersectionType::describe: cache the result per VerbosityLevel, mirroring UnionType and ObjectType. IntersectionType::describe is a hot cache-key producer (e.g. ObjectType::isSuperTypeOf) and was recomputed every call. - ArrayType / ConstantArrayType: only a BenevolentUnionType describes with the surrounding parens of '(int|string)' / '(int|non-decimal-int-string)' (a plain union has no outer parens), so gate the describe() comparison behind `instanceof BenevolentUnionType` instead of calling describe() for every key type. - TypeCombinator::intersect: the union-ordering comparator is a no-op unless there are at least two UnionTypes, so skip the usort() in the common case. - MemoizingReflectionProvider::hasClass: compute strtolower() once. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 3c0ed74 commit a0d9720

6 files changed

Lines changed: 72 additions & 8 deletions

File tree

‎src/Analyser/MutatingScope.php‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
use function ltrim;
128128
use function md5;
129129
use function sprintf;
130+
use function str_contains;
130131
use function str_starts_with;
131132
use function strlen;
132133
use function strtolower;
@@ -3072,6 +3073,26 @@ private function shouldInvalidateExpression(string $exprStringToInvalidate, Expr
30723073
return $exprStringToInvalidate === $exprString;
30733074
}
30743075

3076+
// getNodeKey() is the pretty-printed expression, and the standard printer is
3077+
// compositional: the key of any sub-expression appears verbatim as a substring of
3078+
// the key of the expression containing it. So if the invalidated expression's key
3079+
// does not appear anywhere in this expression's key, this expression cannot contain
3080+
// it and we can skip the expensive AST traversal below.
3081+
// Carve-outs where that invariant does not hold:
3082+
// - '$this' is special-cased in the visitor to also match self/static/parent,
3083+
// - PHPStan's virtual nodes (printed as '__phpstan…') use non-compositional printers
3084+
// (e.g. a wrapped variable is printed by name, not as '$name'),
3085+
// - keys carrying a getNodeKey() suffix ('/*…*/') are not plain substrings.
3086+
if (
3087+
$exprStringToInvalidate !== '$this'
3088+
&& !str_contains($exprStringToInvalidate, '__phpstan')
3089+
&& !str_contains($exprStringToInvalidate, '/*')
3090+
&& !str_contains($exprString, '__phpstan')
3091+
&& !str_contains($exprString, $exprStringToInvalidate)
3092+
) {
3093+
return false;
3094+
}
3095+
30753096
$nodeFinder = new NodeFinder();
30763097
$expressionToInvalidateClass = get_class($exprToInvalidate);
30773098
$found = $nodeFinder->findFirst([$expr], function (Node $node) use ($expressionToInvalidateClass, $exprStringToInvalidate): bool {

‎src/Reflection/ReflectionProvider/MemoizingReflectionProvider.php‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ public function __construct(private ReflectionProvider $provider)
3232

3333
public function hasClass(string $className): bool
3434
{
35-
if (isset($this->knownClasses[strtolower($className)])) {
35+
$lowerClassName = strtolower($className);
36+
if (isset($this->knownClasses[$lowerClassName])) {
3637
return true;
3738
}
3839

@@ -43,7 +44,7 @@ public function hasClass(string $className): bool
4344
$result = $this->provider->hasClass($className);
4445

4546
if ($result) {
46-
$this->knownClasses[strtolower($className)] = true;
47+
$this->knownClasses[$lowerClassName] = true;
4748
} else {
4849
$this->unknownClasses[$className] = true;
4950
}

‎src/Type/ArrayType.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,10 @@ class ArrayType implements Type
6969
/** @api */
7070
public function __construct(Type $keyType, private Type $itemType)
7171
{
72-
if (in_array($keyType->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
72+
// Only a BenevolentUnionType describes with the surrounding parentheses of
73+
// '(int|string)' / '(int|non-decimal-int-string)' (a plain union has no outer
74+
// parens), so skip the expensive describe() call for every other key type.
75+
if ($keyType instanceof BenevolentUnionType && in_array($keyType->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
7376
$keyType = new MixedType();
7477
}
7578
if ($keyType instanceof StrictMixedType && !$keyType instanceof TemplateStrictMixedType) {

‎src/Type/Constant/ConstantArrayType.php‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,10 @@ public function __construct(
171171
$this->isList = $isList;
172172

173173
if ($unsealed !== null) {
174-
if (in_array($unsealed[0]->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
174+
// Only a BenevolentUnionType describes with the surrounding parentheses of
175+
// '(int|string)' / '(int|non-decimal-int-string)', so skip the describe() call
176+
// for every other key type.
177+
if ($unsealed[0] instanceof BenevolentUnionType && in_array($unsealed[0]->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
175178
$unsealed[0] = new MixedType();
176179
}
177180
if ($unsealed[0] instanceof StrictMixedType && !$unsealed[0] instanceof TemplateStrictMixedType) {
@@ -2504,7 +2507,10 @@ function () use ($arrayName, $level): string {
25042507
return $arrayName;
25052508
}
25062509
$keyType = $this->getIterableKeyType();
2507-
if (in_array($keyType->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
2510+
// Only a BenevolentUnionType describes with the surrounding parentheses of
2511+
// '(int|string)' / '(int|non-decimal-int-string)', so skip the describe()
2512+
// call for every other key type.
2513+
if ($keyType instanceof BenevolentUnionType && in_array($keyType->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
25082514
return sprintf('%s<%s>', $arrayName, $this->getIterableValueType()->describe($level));
25092515
}
25102516
return sprintf('%s<%s, %s>', $arrayName, $keyType->describe($level), $this->getIterableValueType()->describe($level));

‎src/Type/IntersectionType.php‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ class IntersectionType implements CompoundType
107107
/** @var array<string, TrinaryLogic> */
108108
private array $cachedHasOffsetValueType = [];
109109

110+
/** @var array<int, string> */
111+
private array $cachedDescriptions = [];
112+
110113
/**
111114
* @api
112115
* @param list<Type> $types
@@ -380,7 +383,11 @@ public function equals(Type $type): bool
380383

381384
public function describe(VerbosityLevel $level): string
382385
{
383-
return $level->handle(
386+
if (isset($this->cachedDescriptions[$level->getLevelValue()])) {
387+
return $this->cachedDescriptions[$level->getLevelValue()];
388+
}
389+
390+
return $this->cachedDescriptions[$level->getLevelValue()] = $level->handle(
384391
fn (): string => $this->describeType($level),
385392
fn (): string => $this->describeItself($level, true),
386393
fn (): string => $this->describeItself($level, false),

‎src/Type/TypeCombinator.php‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1507,7 +1507,21 @@ public static function intersect(Type ...$types): Type
15071507

15081508
return 0;
15091509
};
1510-
usort($types, $sortTypes);
1510+
// The comparator only orders UnionTypes relative to each other, so sorting is
1511+
// a no-op unless there are at least two of them. Skip it in the common case.
1512+
$unionTypesCount = 0;
1513+
foreach ($types as $type) {
1514+
if (!$type instanceof UnionType) {
1515+
continue;
1516+
}
1517+
$unionTypesCount++;
1518+
if ($unionTypesCount >= 2) {
1519+
break;
1520+
}
1521+
}
1522+
if ($unionTypesCount >= 2) {
1523+
usort($types, $sortTypes);
1524+
}
15111525
// transform A & (B | C) to (A & B) | (A & C)
15121526
foreach ($types as $i => $type) {
15131527
if (!$type instanceof UnionType) {
@@ -1516,7 +1530,19 @@ public static function intersect(Type ...$types): Type
15161530

15171531
$topLevelUnionSubTypes = [];
15181532
$innerTypes = $type->getTypes();
1519-
usort($innerTypes, $sortTypes);
1533+
$innerUnionTypesCount = 0;
1534+
foreach ($innerTypes as $innerType) {
1535+
if (!$innerType instanceof UnionType) {
1536+
continue;
1537+
}
1538+
$innerUnionTypesCount++;
1539+
if ($innerUnionTypesCount >= 2) {
1540+
break;
1541+
}
1542+
}
1543+
if ($innerUnionTypesCount >= 2) {
1544+
usort($innerTypes, $sortTypes);
1545+
}
15201546
$slice1 = array_slice($types, 0, $i);
15211547
$slice2 = array_slice($types, $i + 1);
15221548
foreach ($innerTypes as $innerUnionSubType) {

0 commit comments

Comments
 (0)