Skip to content

Commit 9cebb2a

Browse files
phpstan-botclaude
authored andcommitted
Ask isCallable() of callable-like arrays and strings only where the answer is consumed
- ArrayHandler: check for a narrowed `is_callable()` expression in scope before asking the array literal type `isCallable()`, instead of asking it for every two-item array literal - ArgumentsHandler: ask the argument type `isCallable()` only when the result is used - when the callback is called immediately, or when invalidation applies and the argument can be an object (only closures carry expressions to invalidate) - DependencyResolver: skip the callable-array dependency for class-level initializers (class constants, property defaults, enum case values), which are never called where declared - GenericParametersAcceptorResolver: ask the argument type `isCallable()` only once a callable parameter with asserts is found (same eager reflection for generic function arguments) - Mirror the ArrayHandler and ArgumentsHandler changes in turbo-ext - Probed and left as is: UnusedPrivateMethodRule, SimpleImpurePoint, FuncCallHandler and other callers ask `isCallable()` only of values that are actually used as callables Answering `isCallable()` of `['SomeClass', 'someString']` or `'SomeClass::someString'` locates and reflects `SomeClass`, which for a huge generated class costs hundreds of MB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 01c272f commit 9cebb2a

12 files changed

Lines changed: 277 additions & 32 deletions

‎src/Analyser/ArgumentsHandler.php‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -654,13 +654,18 @@ public function processArgs(
654654
}
655655
$hasYield = $hasYield || $exprResult->hasYield();
656656

657-
if ($exprType->isCallable()->yes()) {
657+
// only callable objects (closures) carry expressions to invalidate - asking
658+
// isCallable() of other arguments reflects the classes named by callable-like
659+
// strings and arrays, so it is skipped when nothing would come of it
660+
$invalidateCallbackExpressions = $this->shouldInvalidateCallbackExpressions($parameter) && !$exprType->isObject()->no();
661+
$callCallbackImmediately = $this->callCallbackImmediately($parameter, $parameterType, $calleeReflection);
662+
if (($invalidateCallbackExpressions || $callCallbackImmediately) && $exprType->isCallable()->yes()) {
658663
$acceptors = $exprType->getCallableParametersAcceptors($scope);
659664
if (count($acceptors) === 1) {
660-
if ($this->shouldInvalidateCallbackExpressions($parameter)) {
665+
if ($invalidateCallbackExpressions) {
661666
$deferredInvalidateExpressions[] = [$acceptors[0]->getInvalidateExpressions(), $acceptors[0]->getUsedVariables()];
662667
}
663-
if ($this->callCallbackImmediately($parameter, $parameterType, $calleeReflection)) {
668+
if ($callCallbackImmediately) {
664669
$callableThrowPoints = array_map(static fn (SimpleThrowPoint $throwPoint) => $throwPoint->isExplicit() ? InternalThrowPoint::createExplicit($scope, $throwPoint->getType(), $arg->value, $throwPoint->canContainAnyThrowable(), $throwPoint->isFromThrowExpr()) : InternalThrowPoint::createImplicit($scope, $arg->value), $acceptors[0]->getThrowPoints());
665670
if (!$this->implicitThrows) {
666671
$callableThrowPoints = array_values(array_filter($callableThrowPoints, static fn (InternalThrowPoint $throwPoint) => $throwPoint->isExplicit()));

‎src/Analyser/ExprHandler/ArrayHandler.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,18 +174,21 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
174174
if (
175175
count($expr->items) === 2
176176
&& isset($expr->items[0], $expr->items[1])
177-
&& $type->isCallable()->maybe()
178177
) {
179178
$isCallableCall = new FuncCall(
180179
new FullyQualified('is_callable'),
181180
[new Arg($expr)],
182181
);
182+
// isCallable() is asked last - it reflects the class named by the
183+
// first item, which is expensive and unnecessary for arrays never
184+
// narrowed by is_callable()
183185
if (
184186
$beforeScope->hasExpressionType($isCallableCall)->yes()
185187
// read the narrowed type from expressionTypes directly (the
186188
// synthetic is_callable() call was never processed as a child),
187189
// mirroring ConstFetchHandler's narrowed-constant lookup
188190
&& $beforeScope->expressionTypes[$beforeScope->getNodeKey($isCallableCall)]->getType()->isTrue()->yes()
191+
&& $type->isCallable()->maybe()
189192
) {
190193
$type = TypeCombinator::intersect($type, new CallableType());
191194
}

‎src/Dependency/DependencyResolver.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,17 @@ private function considerArrayForCallableTest(Scope $scope, Array_ $arrayNode):
670670
return false;
671671
}
672672

673+
// a class constant, property default or enum case value is not called where it is
674+
// declared - testing it would reflect whatever class its first item happens to name
675+
if (
676+
$scope->isInClass()
677+
&& $scope->getFunction() === null
678+
&& !$scope->isInAnonymousFunction()
679+
&& $scope->getFunctionCallStack() === []
680+
) {
681+
return false;
682+
}
683+
673684
$itemType = $scope->getType($items[0]->value);
674685
return $itemType->isClassString()->yes();
675686
}

‎src/Reflection/GenericParametersAcceptorResolver.php‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,6 @@ public static function resolve(array $argTypes, ParametersAcceptor $parametersAc
171171
private static function inferPredicateTemplateTypes(Type $paramType, Type $argType): TemplateTypeMap
172172
{
173173
$typeMap = TemplateTypeMap::createEmpty();
174-
if (!$argType->isCallable()->yes()) {
175-
return $typeMap;
176-
}
177-
178174
foreach ($paramType instanceof UnionType ? $paramType->getTypes() : [$paramType] as $innerType) {
179175
if (!$innerType instanceof CallableParametersAcceptor) {
180176
continue;
@@ -183,6 +179,12 @@ private static function inferPredicateTemplateTypes(Type $paramType, Type $argTy
183179
continue;
184180
}
185181

182+
// asked only for parameters with asserts - it reflects the class named by
183+
// a callable-like argument
184+
if (!$argType->isCallable()->yes()) {
185+
return $typeMap;
186+
}
187+
186188
foreach ($argType->getCallableParametersAcceptors(new OutOfClassScope()) as $receivedAcceptor) {
187189
$typeMap = $typeMap->union(CallableAssertionsHelper::inferTemplateTypesOnAsserts($innerType, $receivedAcceptor));
188190
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PHPStan\Reflection\ClassReflection;
6+
use PHPStan\Reflection\MethodReflection;
7+
use PHPStan\Reflection\MethodsClassReflectionExtension;
8+
use PHPStan\ShouldNotHappenException;
9+
10+
/**
11+
* Records the methods asked about, so a test can assert that a class is not reflected
12+
* for a callable-looking value that is never used as a callable.
13+
*/
14+
final class Bug15292MethodsClassReflectionExtension implements MethodsClassReflectionExtension
15+
{
16+
17+
/** @var list<string> */
18+
public static array $askedMethods = [];
19+
20+
public function hasMethod(ClassReflection $classReflection, string $methodName): bool
21+
{
22+
self::$askedMethods[] = $classReflection->getName() . '::' . $methodName;
23+
24+
return false;
25+
}
26+
27+
public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection
28+
{
29+
throw new ShouldNotHappenException();
30+
}
31+
32+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Rules\Rule;
7+
use PHPStan\Testing\RuleTestCase;
8+
use PHPUnit\Framework\Attributes\RequiresPhp;
9+
use function array_filter;
10+
use function array_values;
11+
use function str_starts_with;
12+
13+
/**
14+
* @extends RuleTestCase<Rule<Node>>
15+
*/
16+
class Bug15292Test extends RuleTestCase
17+
{
18+
19+
protected function getRule(): Rule
20+
{
21+
return new class implements Rule {
22+
23+
public function getNodeType(): string
24+
{
25+
return Node::class;
26+
}
27+
28+
public function processNode(Node $node, Scope $scope): array
29+
{
30+
return [];
31+
}
32+
33+
};
34+
}
35+
36+
#[RequiresPhp('>= 8.1')]
37+
public function testCallableLikeValuesAreNotReflected(): void
38+
{
39+
Bug15292MethodsClassReflectionExtension::$askedMethods = [];
40+
$this->analyse([__DIR__ . '/data/bug-15292.php'], []);
41+
$this->assertSame([], $this->getAskedMethods('Bug15292\\'));
42+
}
43+
44+
public function testCallableLikeGenericArgumentsAreNotReflected(): void
45+
{
46+
Bug15292MethodsClassReflectionExtension::$askedMethods = [];
47+
$this->analyse([__DIR__ . '/data/bug-15292-generic.php'], []);
48+
$this->assertSame([], $this->getAskedMethods('Bug15292Generic\\'));
49+
}
50+
51+
public function testCallableIsReflected(): void
52+
{
53+
Bug15292MethodsClassReflectionExtension::$askedMethods = [];
54+
$this->analyse([__DIR__ . '/data/bug-15292-callable.php'], []);
55+
$this->assertContains('Bug15292Callable\BigContainer::callable_ident', $this->getAskedMethods('Bug15292Callable\\'));
56+
}
57+
58+
/**
59+
* @return list<string>
60+
*/
61+
private function getAskedMethods(string $prefix): array
62+
{
63+
return array_values(array_filter(
64+
Bug15292MethodsClassReflectionExtension::$askedMethods,
65+
static fn (string $method): bool => str_starts_with($method, $prefix),
66+
));
67+
}
68+
69+
public static function getAdditionalConfigFiles(): array
70+
{
71+
return [
72+
__DIR__ . '/bug-15292.neon',
73+
];
74+
}
75+
76+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
services:
2+
-
3+
class: PHPStan\Analyser\Bug15292MethodsClassReflectionExtension
4+
tags:
5+
- phpstan.broker.methodsClassReflectionExtension
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace Bug15292Callable;
6+
7+
class BigContainer
8+
{
9+
10+
}
11+
12+
function doFoo(): void
13+
{
14+
usort($list, ['Bug15292Callable\BigContainer', 'callable_ident']);
15+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15292Generic;
4+
5+
class BigContainer
6+
{
7+
8+
}
9+
10+
/**
11+
* @template T
12+
* @param T $v
13+
* @return T
14+
*/
15+
function identity($v)
16+
{
17+
return $v;
18+
}
19+
20+
final class Foo
21+
{
22+
23+
private const ALLOWED = [
24+
'Bug15292Generic\BigContainer',
25+
'generic_ident',
26+
];
27+
28+
public function doFoo(): void
29+
{
30+
identity(self::ALLOWED);
31+
identity('Bug15292Generic\BigContainer::generic_string_ident');
32+
}
33+
34+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php // lint >= 8.1
2+
3+
declare(strict_types = 1);
4+
5+
namespace Bug15292;
6+
7+
class BigContainer
8+
{
9+
10+
}
11+
12+
enum Modality: string
13+
{
14+
15+
case First = 'first';
16+
17+
public const ALLOWED = [
18+
'Bug15292\BigContainer',
19+
'enum_constant_ident',
20+
];
21+
22+
}
23+
24+
final class FooLeaking
25+
{
26+
27+
private const ALLOWED_MODALITIES = [
28+
'Bug15292\BigContainer',
29+
'arbitrary_ident',
30+
];
31+
32+
/** @var list<string> */
33+
private array $allowedProperty = [
34+
'Bug15292\BigContainer',
35+
'property_ident',
36+
];
37+
38+
public function isAllowed(string $item): bool
39+
{
40+
return in_array($item, self::ALLOWED_MODALITIES, true)
41+
|| in_array($item, $this->allowedProperty, true)
42+
|| in_array($item, Modality::ALLOWED, true)
43+
|| in_array('Bug15292\BigContainer::string_ident', [$item], true);
44+
}
45+
46+
}

0 commit comments

Comments
 (0)