Skip to content

Commit 82f0506

Browse files
committed
Make the fixes of MissingReturnTypeFixRule without parsing the files again
The collected data carries where the method node is and its declared native return type, so the rule creates the fix without finding the node in a parse of its file. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301
1 parent 7ad7364 commit 82f0506

7 files changed

Lines changed: 31 additions & 47 deletions

‎src/Rules/Functions/MissingFunctionReturnTypehintRule.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ private function createReturnTypeErrors(FunctionReturnStatementsNode $node, arra
102102
if ($this->fixer->isEnabled()) {
103103
$type = $this->fixer->combine([$this->fixer->getReturnInfo($node)]);
104104
if ($type !== null) {
105-
$fix = $this->fixer->createFix($function, $type, $type, null);
105+
$fix = $this->fixer->createFix($function->returnType !== null ? $node->getFunctionReflection()->getNativeReturnType() : null, $type, $type, null);
106106
}
107107
}
108108

‎src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co
129129
if (!$isInTrait && !$isOverridable) {
130130
$type = $this->fixer->combine([$returnInfo]);
131131
if ($type !== null) {
132-
$fix = $this->fixer->createFix($classMethod, $type, $type, $classReflection, $parentReturnType, $parentNativeReturnType);
132+
$fix = $this->fixer->createFix($classMethod->returnType !== null ? $methodReflection->getNativeReturnType() : null, $type, $type, $classReflection, $parentReturnType, $parentNativeReturnType);
133133
}
134134
}
135135

@@ -164,13 +164,14 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co
164164
'returnInfo' => $this->fixer->serializeReturnInfo($returnInfo),
165165
'parentReturnType' => $parentReturnType !== null ? $this->fixer->serialize($parentReturnType) ?? false : null,
166166
'parentNativeReturnType' => $parentNativeReturnType !== null ? $this->fixer->serialize($parentNativeReturnType) ?? false : null,
167-
'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null,
167+
'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) ?? false : null,
168168
'fixedNatively' => $fixedNatively,
169169
'errors' => $isDeferred ? $errors : [],
170170
'file' => $file,
171171
'fileDescription' => $scope->getFileDescription(),
172172
'line' => $node->getStartLine(),
173173
'startPos' => $classMethod->getStartFilePos(),
174+
'endPos' => $classMethod->getEndFilePos(),
174175
]);
175176
}
176177

‎src/Rules/Methods/MissingMethodReturnTypehintRule.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,14 @@ private function emitOverridingMethodWithoutBody(InClassMethodNode $node, Scope&
140140
'returnInfo' => null,
141141
'parentReturnType' => null,
142142
'parentNativeReturnType' => null,
143-
'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null,
143+
'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) ?? false : null,
144144
'fixedNatively' => false,
145145
'errors' => [],
146146
'file' => $scope->getFile(),
147147
'fileDescription' => $scope->getFileDescription(),
148148
'line' => $node->getStartLine(),
149149
'startPos' => $classMethod->getStartFilePos(),
150+
'endPos' => $classMethod->getEndFilePos(),
150151
]);
151152
}
152153

‎src/Rules/MissingReturnTypeCollector.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@
2020
* - returnInfo: what the function returns, see MissingReturnTypeFixer, null when it is not known or the method has no body
2121
* - parentReturnType, parentNativeReturnType: the return types of the methods it overrides, see MissingReturnTypeFixer::findParentReturnTypes(),
2222
* false when they cannot be passed in collected data
23-
* - nativeReturnType: the declared native return type
23+
* - nativeReturnType: the declared native return type, false when it cannot be passed in collected data
2424
* - fixedNatively: whether the error of the method declares its native return type with a fix of its own
2525
* - errors: the errors of a missing return type MissingReturnTypeFixRule reports with the fix
26-
* - file, startPos: where the function node is, to find it in the parsed file
26+
* - file, startPos, endPos: where the function node is, the fix finds it there
2727
* - fileDescription: the file the errors are reported in, with the class using the trait the method comes from
2828
*
2929
* Not registered as a collector, the data is emitted by the rules for missing return types.
3030
*
31-
* @implements Collector<never, array{key: string, traitMethod: string|null, class: string|null, overrides: list<string>, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|null, fixedNatively: bool, errors: list<array{string, string, string|null}>, file: string, fileDescription: string, line: int, startPos: int}>
31+
* @implements Collector<never, array{key: string, traitMethod: string|null, class: string|null, overrides: list<string>, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|false|null, fixedNatively: bool, errors: list<array{string, string, string|null}>, file: string, fileDescription: string, line: int, startPos: int, endPos: int}>
3232
*/
3333
final class MissingReturnTypeCollector implements Collector
3434
{

‎src/Rules/MissingReturnTypeFixRule.php‎

Lines changed: 17 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,10 @@
55
use PhpParser\Node;
66
use PhpParser\Node\Stmt\ClassMethod;
77
use PhpParser\Node\Stmt\Function_;
8-
use PhpParser\NodeFinder;
98
use PHPStan\Analyser\NameScope;
109
use PHPStan\Analyser\Scope;
11-
use PHPStan\DependencyInjection\AutowiredParameter;
1210
use PHPStan\DependencyInjection\RegisteredRule;
1311
use PHPStan\Node\CollectedDataNode;
14-
use PHPStan\Parser\Parser;
15-
use PHPStan\Parser\ParserErrorsException;
1612
use PHPStan\PhpDoc\TypeStringResolver;
1713
use PHPStan\Reflection\ReflectionProvider;
1814
use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper;
@@ -32,7 +28,7 @@
3228
* so that \$this is static. Its return type covers what it returns in all of them, they share one fix.
3329
*
3430
* @phpstan-import-type ReturnInfo from MissingReturnTypeFixer
35-
* @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list<string>, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|null, fixedNatively: bool, errors: list<array{string, string, string|null}>, file: string, fileDescription: string, line: int, startPos: int}
31+
* @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list<string>, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|false|null, fixedNatively: bool, errors: list<array{string, string, string|null}>, file: string, fileDescription: string, line: int, startPos: int, endPos: int}
3632
* @implements Rule<CollectedDataNode>
3733
*/
3834
#[RegisteredRule(level: 6)]
@@ -61,8 +57,6 @@ public function __construct(
6157
private OverridableMemberHelper $overridableMemberHelper,
6258
private TypeStringResolver $typeStringResolver,
6359
private ReflectionProvider $reflectionProvider,
64-
#[AutowiredParameter(ref: '@defaultAnalysisParser')]
65-
private Parser $parser,
6660
)
6761
{
6862
}
@@ -116,10 +110,7 @@ public function processNode(Node $node, Scope $scope): array
116110
$builder->tip($tip);
117111
}
118112
if ($fix !== null) {
119-
$functionNode = $this->findFunctionNode($record);
120-
if ($functionNode !== null) {
121-
$builder->fixNode($functionNode, $fix, $record['file']);
122-
}
113+
$builder->fixNode(self::createFunctionNode($record), $fix, $record['file']);
123114
}
124115

125116
$errors[] = $builder->build();
@@ -153,6 +144,10 @@ private function getFix(string $key): ?callable
153144
private function createFix(string $key): ?callable
154145
{
155146
$record = $this->records[$key];
147+
if ($record['nativeReturnType'] === false) {
148+
return null;
149+
}
150+
156151
$traitMethod = $record['traitMethod'];
157152
// the classes using a trait might not be analysed
158153
if ($traitMethod !== null && $this->isOnlyFilesAnalysis) {
@@ -170,7 +165,7 @@ private function createFix(string $key): ?callable
170165
}
171166

172167
// the fixed return type has to be within the return types of the methods it overrides in every class
173-
if ($contextRecord['parentReturnType'] === false || $contextRecord['parentNativeReturnType'] === false) {
168+
if ($contextRecord['parentReturnType'] === false || $contextRecord['parentNativeReturnType'] === false || $contextRecord['nativeReturnType'] === false) {
174169
return null;
175170
}
176171
$parentReturnType = $this->resolve($contextRecord['parentReturnType'], $contextRecord['class']);
@@ -210,6 +205,10 @@ private function createFix(string $key): ?callable
210205
return null;
211206
}
212207

208+
if ($overridingRecord['nativeReturnType'] === false) {
209+
return null;
210+
}
211+
213212
$overridingReturnInfo = $this->getReturnInfo($overridingKey);
214213
$overridingNativeType = $this->resolve($overridingRecord['nativeReturnType'], $overridingRecord['class']);
215214
$overridingNativeReturnInfo = $overridingNativeType !== null ? $this->createNativeReturnInfo($overridingNativeType) : null;
@@ -243,17 +242,12 @@ private function createFix(string $key): ?callable
243242
return null;
244243
}
245244

246-
$functionNode = $this->findFunctionNode($record);
247-
if ($functionNode === null) {
248-
return null;
249-
}
250-
251245
$classReflection = $record['class'] !== null && $this->reflectionProvider->hasClass($record['class'])
252246
? $this->reflectionProvider->getClass($record['class'])
253247
: null;
254248

255249
return $this->fixer->createFix(
256-
$functionNode,
250+
$this->resolve($record['nativeReturnType'], $record['class']),
257251
$phpDocType,
258252
$nativeSourceType,
259253
$classReflection,
@@ -320,23 +314,14 @@ private function resolve(?string $type, ?string $className): ?Type
320314
}
321315

322316
/**
317+
* The node the fix is made on, found in the parsed file by its position, see ReplacingNodeVisitor.
318+
* The records are made from the analysed nodes, so the file is not parsed again here.
319+
*
323320
* @param Record $record
324321
*/
325-
private function findFunctionNode(array $record): ClassMethod|Function_|null
322+
private static function createFunctionNode(array $record): ClassMethod
326323
{
327-
try {
328-
$stmts = $this->parser->parseFile($record['file']);
329-
} catch (ParserErrorsException) {
330-
return null;
331-
}
332-
333-
$startPos = $record['startPos'];
334-
$functionNode = (new NodeFinder())->findFirst($stmts, static fn (Node $node): bool => ($node instanceof ClassMethod || $node instanceof Function_) && $node->getStartFilePos() === $startPos);
335-
if (!$functionNode instanceof ClassMethod && !$functionNode instanceof Function_) {
336-
return null;
337-
}
338-
339-
return $functionNode;
324+
return new ClassMethod('fixed', attributes: ['startFilePos' => $record['startPos'], 'endFilePos' => $record['endPos']]);
340325
}
341326

342327
}

‎src/Rules/MissingReturnTypeFixer.php‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -300,12 +300,11 @@ public function findParentReturnTypes(ClassReflection $classReflection, string $
300300
* The return type of a method has to be within the return types of the methods it overrides,
301301
* see findParentReturnTypes(), when it is not, the method breaks their contract and is not fixed.
302302
*
303-
* @template TNode of ClassMethod|Function_
304-
* @param TNode $node
305-
* @return (callable(TNode): TNode)|null
303+
* @param Type|null $declaredNativeType the native return type the function declares
304+
* @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null
306305
*/
307306
public function createFix(
308-
ClassMethod|Function_ $node,
307+
?Type $declaredNativeType,
309308
Type $phpDocType,
310309
Type $nativeSourceType,
311310
?ClassReflection $classReflection,
@@ -325,14 +324,13 @@ public function createFix(
325324
}
326325

327326
$nativeTypeNode = null;
328-
if ($node->returnType === null) {
327+
$nativeType = $declaredNativeType;
328+
if ($nativeType === null) {
329329
$nativeTypeNode = $this->createNativeTypeNode($nativeSourceType);
330330
if ($nativeTypeNode === null) {
331331
return null;
332332
}
333333
$nativeType = ParserNodeTypeToPHPStanType::resolve($nativeTypeNode, $classReflection);
334-
} else {
335-
$nativeType = ParserNodeTypeToPHPStanType::resolve($node->returnType, $classReflection);
336334
}
337335

338336
if ($nativeType->isSuperTypeOf($phpDocType)->no()) {

‎tests/PHPStan/Rules/MissingReturnTypeFixTestCase.php‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ protected function getRule(): Rule
4444
$overridableMemberHelper,
4545
self::getContainer()->getByType(TypeStringResolver::class),
4646
self::createReflectionProvider(),
47-
self::getContainer()->getService('defaultAnalysisParser'),
4847
),
4948
];
5049
if ($this->reportMissingParameterTypes) {

0 commit comments

Comments
 (0)