Skip to content

Commit 19482b7

Browse files
committed
Arrow function return type inference
1 parent 5a032f6 commit 19482b7

3 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/Analyser/MutatingScope.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1183,9 +1183,15 @@ private function resolveType(Expr $node): Type
11831183
);
11841184
}
11851185

1186+
if ($node->returnType === null && $node instanceof Expr\ArrowFunction) {
1187+
$returnType = $this->getType($node->expr);
1188+
} else {
1189+
$returnType = $this->getFunctionType($node->returnType, $node->returnType === null, false);
1190+
}
1191+
11861192
return new ClosureType(
11871193
$parameters,
1188-
$this->getFunctionType($node->returnType, $node->returnType === null, false),
1194+
$returnType,
11891195
$isVariadic
11901196
);
11911197
} elseif ($node instanceof New_) {

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9806,6 +9806,15 @@ public function dataExtDs(): array
98069806
return $this->gatherAssertTypes(__DIR__ . '/data/ext-ds.php');
98079807
}
98089808

9809+
public function dataArrowFunctionReturnTypeInference(): array
9810+
{
9811+
if (PHP_VERSION_ID < 70400) {
9812+
return [];
9813+
}
9814+
9815+
return $this->gatherAssertTypes(__DIR__ . '/data/arrow-function-return-type.php');
9816+
}
9817+
98099818
/**
98109819
* @dataProvider dataBug2574
98119820
* @dataProvider dataBug2577
@@ -9839,6 +9848,7 @@ public function dataExtDs(): array
98399848
* @dataProvider dataTypeChangeAfterArrayAccessAssignment
98409849
* @dataProvider dataIteratorToArray
98419850
* @dataProvider dataExtDs
9851+
* @dataProvider dataArrowFunctionReturnTypeInference
98429852
* @param ConstantStringType $expectedType
98439853
* @param Type $actualType
98449854
*/
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
namespace ArrowFunctionReturnTypeInference;
4+
5+
use function PHPStan\Analyser\assertType;
6+
7+
function (int $i): void {
8+
$fn = fn () => $i;
9+
assertType('int', $fn());
10+
};
11+
12+
function (int $i): void {
13+
$fn = fn (): string => $i;
14+
assertType('string', $fn());
15+
};

0 commit comments

Comments
 (0)