Skip to content

Commit 60c17fd

Browse files
committed
Coordinate the fixes of too-wide return types across the class hierarchy
In a closed project, and in an open project with checkTooWideReturnTypesInProtectedAndPublicMethods, the return type of a method that can be overridden is fixed in TooWideTypeInOverridableMemberRule. The overriding methods emit the members of the overridden type they return and declare, the fix keeps them, so the overridden type stays as wide as the overriding ones need. Usages computed against another version of the overridden type do not take part in a fix. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301
1 parent 06d8cf7 commit 60c17fd

18 files changed

Lines changed: 1229 additions & 36 deletions

‎src/Rules/TooWideTypehints/OverridableMemberHelper.php‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
* the member uses itself with emitDeclaration(), and the members of the types of the overridden members
2121
* an overriding member uses with emitUsage(). TooWideTypeInOverridableMemberRule reports the members
2222
* of the type nobody uses.
23+
*
24+
* @phpstan-import-type Plan from TooWideReturnTypeFixer
2325
*/
2426
#[AutowiredService]
2527
final class OverridableMemberHelper
@@ -124,6 +126,8 @@ public function findOverriddenPropertyHooks(ClassReflection $classReflection, st
124126
* @param list<array{string, string, string|null}> $memberErrors message, identifier and tip for each member of the type
125127
* @param string|null $usedMembersTip tip for the errors with %s for the used members, or void
126128
* @param list<string> $memberDescriptions the members of the type in $usedMembersTip
129+
* @param bool $ownOnly whether only the members the member uses itself are not reported, in an open project
130+
* @param array{plan: Plan, startPos: int, endPos: int}|null $fix the plan of the fix of the return type, see TooWideReturnTypeFixer
127131
*/
128132
public function emitDeclaration(
129133
Scope&CollectedDataEmitter $scope,
@@ -136,6 +140,8 @@ public function emitDeclaration(
136140
array $memberErrors,
137141
?string $usedMembersTip = null,
138142
array $memberDescriptions = [],
143+
bool $ownOnly = false,
144+
?array $fix = null,
139145
): void
140146
{
141147
$file = null;
@@ -159,12 +165,36 @@ public function emitDeclaration(
159165
'errors' => $memberErrors,
160166
'usedMembersTip' => $usedMembersTip,
161167
'memberDescriptions' => $memberDescriptions,
168+
'ownOnly' => $ownOnly,
169+
'fix' => $fix,
162170
]);
163171
}
164172

173+
/**
174+
* emitDeclaration() of the return type of a method, with the plan of its fix.
175+
*
176+
* @param list<int> $usedMembers
177+
* @param list<array{string, string, string|null}> $memberErrors
178+
* @param array{plan: Plan, startPos: int, endPos: int}|null $fix
179+
*/
180+
public function emitReturnTypeDeclaration(
181+
Scope&CollectedDataEmitter $scope,
182+
string $className,
183+
string $memberKey,
184+
int $line,
185+
array $usedMembers,
186+
array $memberErrors,
187+
bool $ownOnly,
188+
?array $fix,
189+
): void
190+
{
191+
$this->emitDeclaration($scope, self::KIND_RETURN, $className, $memberKey, 0, $line, $usedMembers, $memberErrors, null, [], $ownOnly, $fix);
192+
}
193+
165194
/**
166195
* @param self::KIND_* $kind
167196
* @param list<int> $usedMembers the members of the type of the overridden member the overriding member uses
197+
* @param array{list<int>, list<int>, int}|null $declaredMembers the members its PHPDoc and native types overlap and the number of members, for the fix of the overridden member
168198
*/
169199
public function emitUsage(
170200
CollectedDataEmitter $scope,
@@ -173,6 +203,7 @@ public function emitUsage(
173203
string $overriddenMemberKey,
174204
int $slot,
175205
array $usedMembers,
206+
?array $declaredMembers = null,
176207
): void
177208
{
178209
$scope->emitCollectedData(TypeUsedInOverridingMemberCollector::class, [
@@ -181,6 +212,7 @@ public function emitUsage(
181212
'member' => $overriddenMemberKey,
182213
'slot' => $slot,
183214
'used' => $usedMembers,
215+
'declared' => $declaredMembers,
184216
]);
185217
}
186218

‎src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php‎

Lines changed: 67 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
use PHPStan\DependencyInjection\AutowiredParameter;
99
use PHPStan\DependencyInjection\RegisteredRule;
1010
use PHPStan\Node\MethodReturnStatementsNode;
11+
use PHPStan\Rules\IdentifierRuleError;
1112
use PHPStan\Rules\Rule;
13+
use function in_array;
1214
use function sprintf;
1315

1416
/**
@@ -37,20 +39,27 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra
3739
$method = $node->getMethodReflection();
3840
$classReflection = $node->getClassReflection();
3941
$isClosedProject = $this->overridableMemberHelper->isClosedProject();
40-
if ($isClosedProject) {
42+
$isFixEnabled = $this->check->isReturnTypeFixEnabled();
43+
// the fix of an overridden method keeps what the overriding methods return and declare
44+
if ($isClosedProject || ($isFixEnabled && $this->checkProtectedAndPublicMethods)) {
4145
foreach ($this->overridableMemberHelper->findOverriddenMethods($classReflection, $method->getName()) as $overriddenMethod) {
4246
$usedMembers = $this->check->getUsedOverriddenReturnTypeMembers($node, $overriddenMethod->getOnlyVariant(), $scope);
4347
if ($usedMembers === null) {
4448
continue;
4549
}
4650

51+
$declaredMembers = $isFixEnabled
52+
? $this->check->getDeclaredOverriddenReturnTypeMembers($overriddenMethod->getOnlyVariant(), $method, TooWideReturnTypeFixer::hasOwnReturnTag($node->getClassMethod()), $scope)
53+
: null;
54+
4755
$this->overridableMemberHelper->emitUsage(
4856
$scope,
4957
OverridableMemberHelper::KIND_RETURN,
5058
$overriddenMethod->getDeclaringClass()->getName(),
5159
OverridableMemberHelper::getMethodKey($overriddenMethod->getName()),
5260
0,
5361
$usedMembers,
62+
$declaredMembers,
5463
);
5564
}
5665
}
@@ -76,16 +85,7 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra
7685
$scope,
7786
);
7887
if ($result !== null) {
79-
$this->overridableMemberHelper->emitDeclaration(
80-
$scope,
81-
OverridableMemberHelper::KIND_RETURN,
82-
$classReflection->getName(),
83-
OverridableMemberHelper::getMethodKey($method->getName()),
84-
0,
85-
$node->getStartLine(),
86-
$result[0],
87-
$result[1],
88-
);
88+
$this->emitDeclaration($node, $scope, $result, false);
8989
}
9090

9191
return [];
@@ -98,6 +98,28 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra
9898
if ($isFirstDeclaration) {
9999
return [];
100100
}
101+
102+
$errors = $this->check->checkFunctionReturnType(
103+
$node,
104+
$method->getNativeReturnType(),
105+
$method->getPhpDocReturnType(),
106+
$functionDescription,
107+
$checkDescendantClass,
108+
$scope,
109+
);
110+
if (!$isFixEnabled || !self::hasRemovableMemberErrors($errors)) {
111+
return $errors;
112+
}
113+
114+
// the same errors, reported with a fix that keeps what the analysed overriding methods need
115+
$result = $this->check->createOverridableReturnTypeErrors($node, $method, $functionDescription, $checkDescendantClass, $scope, false);
116+
if ($result === null) {
117+
return $errors;
118+
}
119+
120+
$this->emitDeclaration($node, $scope, $result, true);
121+
122+
return [];
101123
}
102124
}
103125

@@ -111,4 +133,38 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra
111133
);
112134
}
113135

136+
/**
137+
* @param array{list<int>, list<array{string, string, string|null}>} $result
138+
*/
139+
private function emitDeclaration(MethodReturnStatementsNode $node, Scope&CollectedDataEmitter $scope, array $result, bool $ownOnly): void
140+
{
141+
$method = $node->getMethodReflection();
142+
$classMethod = $node->getClassMethod();
143+
$plan = $this->check->createReturnTypeFixPlan($node, $method->getNativeReturnType(), $method->getPhpDocReturnType(), true, $scope);
144+
$this->overridableMemberHelper->emitReturnTypeDeclaration(
145+
$scope,
146+
$node->getClassReflection()->getName(),
147+
OverridableMemberHelper::getMethodKey($method->getName()),
148+
$node->getStartLine(),
149+
$result[0],
150+
$result[1],
151+
$ownOnly,
152+
$plan !== null ? ['plan' => $plan, 'startPos' => $classMethod->getStartFilePos(), 'endPos' => $classMethod->getEndFilePos()] : null,
153+
);
154+
}
155+
156+
/**
157+
* @param list<IdentifierRuleError> $errors
158+
*/
159+
private static function hasRemovableMemberErrors(array $errors): bool
160+
{
161+
foreach ($errors as $error) {
162+
if (in_array($error->getIdentifier(), ['return.unusedType', 'return.tooWideBool'], true)) {
163+
return true;
164+
}
165+
}
166+
167+
return false;
168+
}
169+
114170
}

‎src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,16 +175,17 @@ public function createPlan(
175175

176176
/**
177177
* @param Plan $plan
178-
* @param list<int> $kept the members of the checked return type to keep
178+
* @param list<int> $phpDocKept the members of the checked return type the @return tags keep
179+
* @param list<int> $nativeKept the members of the checked return type the native type keeps, a superset of $phpDocKept
179180
* @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null null when nothing changes or the result would be invalid
180181
*/
181-
public function createFix(array $plan, array $kept): ?callable
182+
public function createFix(array $plan, array $phpDocKept, array $nativeKept): ?callable
182183
{
183184
$changes = false;
184185
$nativeDecisions = null;
185186
$nativeOverlaps = null;
186187
if ($plan['native'] !== null) {
187-
$nativeDecisions = $this->decide($plan['native'], $kept, $this->phpVersion->supportsTrueFalseNullStandaloneType());
188+
$nativeDecisions = $this->decide($plan['native'], $nativeKept, $this->phpVersion->supportsTrueFalseNullStandaloneType());
188189
if ($nativeDecisions === null) {
189190
return null;
190191
}
@@ -194,7 +195,7 @@ public function createFix(array $plan, array $kept): ?callable
194195

195196
$tagDecisions = [];
196197
foreach ($plan['tags'] as $tagMembers) {
197-
$decisions = $this->decide($tagMembers, $kept, true);
198+
$decisions = $this->decide($tagMembers, $phpDocKept, true);
198199
if ($decisions === null) {
199200
return null;
200201
}

‎src/Rules/TooWideTypehints/TooWideTypeCheck.php‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,8 @@ private function createReturnTypeFix(
342342
return null;
343343
}
344344

345-
$fix = $this->returnTypeFixer->createFix($plan, $this->getUsedMembers($declaredType, $members, $returnType, false));
345+
$usedMembers = $this->getUsedMembers($declaredType, $members, $returnType, false);
346+
$fix = $this->returnTypeFixer->createFix($plan, $usedMembers, $usedMembers);
346347
if ($fix === null) {
347348
return null;
348349
}
@@ -363,6 +364,7 @@ public function createOverridableReturnTypeErrors(
363364
string $functionDescription,
364365
bool $checkDescendantClass,
365366
Scope $scope,
367+
?bool $usedMembersCheckDescendantClass = null,
366368
): ?array
367369
{
368370
$returnType = $this->getReturnedType($node);
@@ -382,7 +384,7 @@ public function createOverridableReturnTypeErrors(
382384
[$unionMessagePattern, $boolMessagePattern] = $this->getReturnTypeMessagePatterns($functionDescription);
383385

384386
return [
385-
$this->getUsedMembers($declaredType, $members, $returnType, $checkDescendantClass),
387+
$this->getUsedMembers($declaredType, $members, $returnType, $usedMembersCheckDescendantClass ?? $checkDescendantClass),
386388
$this->createMemberErrors($declaredType, $members, $unionMessagePattern, $boolMessagePattern, 'return', null),
387389
];
388390
}
@@ -416,14 +418,17 @@ public function getUsedOverriddenReturnTypeMembers(
416418

417419
/**
418420
* The members of the return type of an overridden method, as createOverridableReturnTypeErrors() lists them,
419-
* that the declared return type of the overriding method overlaps. The fix of the overridden method keeps them,
420-
* so that the overriding method stays covariant. Null when no member of the return type can be reported.
421+
* that the declared return types of the overriding method overlap: the PHPDoc one and the native one.
422+
* The fix of the overridden method keeps them, so that the overriding method stays covariant.
423+
* Null when no member of the return type can be reported. The last item is the number of members,
424+
* the indexes are valid only for a declaration with the same number of them.
421425
*
422-
* @return list<int>|null
426+
* @return array{list<int>, list<int>, int}|null
423427
*/
424428
public function getDeclaredOverriddenReturnTypeMembers(
425429
ExtendedParametersAcceptor $overriddenMethodVariant,
426-
Type $declaredReturnType,
430+
ExtendedParametersAcceptor $overridingMethodVariant,
431+
bool $hasOwnReturnTag,
427432
Scope $scope,
428433
): ?array
429434
{
@@ -433,14 +438,31 @@ public function getDeclaredOverriddenReturnTypeMembers(
433438
return null;
434439
}
435440

436-
if ($declaredReturnType instanceof MixedType && !$declaredReturnType->isExplicitMixed()) {
441+
// without a @return tag of its own, the overriding method inherits the narrowed PHPDoc type
442+
[$overridingType] = $this->getCheckedReturnType($overridingMethodVariant);
443+
444+
return [
445+
$hasOwnReturnTag ? self::getOverlappingMembers($members, $overridingType) : [],
446+
self::getOverlappingMembers($members, $overridingMethodVariant->getNativeReturnType()),
447+
count($members),
448+
];
449+
}
450+
451+
/**
452+
* @param list<Type> $members
453+
* @return list<int>
454+
*/
455+
private static function getOverlappingMembers(array $members, Type $type): array
456+
{
457+
// a method without a return type does not declare anything, what it returns is in its usage
458+
if ($type instanceof MixedType && !$type->isExplicitMixed()) {
437459
return [];
438460
}
439461

440-
$declaredReturnType = TypeUtils::resolveLateResolvableTypes($declaredReturnType);
462+
$type = TypeUtils::resolveLateResolvableTypes($type);
441463
$overlapping = [];
442464
foreach ($members as $i => $member) {
443-
if ($member->isSuperTypeOf($declaredReturnType)->no()) {
465+
if ($member->isSuperTypeOf($type)->no()) {
444466
continue;
445467
}
446468

‎src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
use PHPStan\ShouldNotHappenException;
99

1010
/**
11+
* @phpstan-import-type Plan from TooWideReturnTypeFixer
12+
*
1113
* Not registered as a collector, the data is emitted with OverridableMemberHelper::emitDeclaration().
1214
*
13-
* @implements Collector<never, array{kind: string, class: string, member: string, slot: int, file: string|null, fileDescription: string|null, line: int, used: list<int>, errors: list<array{string, string, string|null}>, usedMembersTip: string|null, memberDescriptions: list<string>}>
15+
* @implements Collector<never, array{kind: string, class: string, member: string, slot: int, file: string|null, fileDescription: string|null, line: int, used: list<int>, errors: list<array{string, string, string|null}>, usedMembersTip: string|null, memberDescriptions: list<string>, ownOnly: bool, fix: array{plan: Plan, startPos: int, endPos: int}|null}>
1416
*/
1517
final class TooWideTypeInOverridableMemberCollector implements Collector
1618
{

0 commit comments

Comments
 (0)