Skip to content

Commit

Permalink
Arrow function return type inference
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Mar 17, 2020
1 parent 5a032f6 commit 19482b7
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -1183,9 +1183,15 @@ private function resolveType(Expr $node): Type
);
}

if ($node->returnType === null && $node instanceof Expr\ArrowFunction) {
$returnType = $this->getType($node->expr);
} else {
$returnType = $this->getFunctionType($node->returnType, $node->returnType === null, false);
}

return new ClosureType(
$parameters,
$this->getFunctionType($node->returnType, $node->returnType === null, false),
$returnType,
$isVariadic
);
} elseif ($node instanceof New_) {
Expand Down
10 changes: 10 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9806,6 +9806,15 @@ public function dataExtDs(): array
return $this->gatherAssertTypes(__DIR__ . '/data/ext-ds.php');
}

public function dataArrowFunctionReturnTypeInference(): array
{
if (PHP_VERSION_ID < 70400) {
return [];
}

return $this->gatherAssertTypes(__DIR__ . '/data/arrow-function-return-type.php');
}

/**
* @dataProvider dataBug2574
* @dataProvider dataBug2577
Expand Down Expand Up @@ -9839,6 +9848,7 @@ public function dataExtDs(): array
* @dataProvider dataTypeChangeAfterArrayAccessAssignment
* @dataProvider dataIteratorToArray
* @dataProvider dataExtDs
* @dataProvider dataArrowFunctionReturnTypeInference
* @param ConstantStringType $expectedType
* @param Type $actualType
*/
Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Analyser/data/arrow-function-return-type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace ArrowFunctionReturnTypeInference;

use function PHPStan\Analyser\assertType;

function (int $i): void {
$fn = fn () => $i;
assertType('int', $fn());
};

function (int $i): void {
$fn = fn (): string => $i;
assertType('string', $fn());
};

0 comments on commit 19482b7

Please sign in to comment.