From fe033f1b6c591eb93721f4643cf1b000af2cf98a Mon Sep 17 00:00:00 2001 From: Matt Brown Date: Tue, 10 Apr 2018 13:05:31 -0400 Subject: [PATCH] Fix #663 - infer array return types for closures --- src/Psalm/Checker/FunctionLikeChecker.php | 40 +++++++++++++---------- tests/CallableTest.php | 36 ++++++++++++++++++++ 2 files changed, 58 insertions(+), 18 deletions(-) diff --git a/src/Psalm/Checker/FunctionLikeChecker.php b/src/Psalm/Checker/FunctionLikeChecker.php index e7fe56451..3bbb31cc8 100644 --- a/src/Psalm/Checker/FunctionLikeChecker.php +++ b/src/Psalm/Checker/FunctionLikeChecker.php @@ -481,31 +481,35 @@ abstract class FunctionLikeChecker extends SourceChecker implements StatementsSo $storage->return_type_location ); - if ($this->function->inferredType - && (!$storage->return_type + $closure_yield_types = []; + + $closure_return_types = EffectsAnalyser::getReturnTypes( + $this->function->stmts, + $closure_yield_types, + $ignore_nullable_issues, + $ignore_falsable_issues, + true + ); + + if ($closure_return_types) { + $closure_return_type = new Type\Union($closure_return_types); + + if (!$storage->return_type || $storage->return_type->isMixed() || TypeChecker::isContainedBy( $project_checker->codebase, - $this->function->inferredType, + $closure_return_type, $storage->return_type ) - ) - ) { - $closure_yield_types = []; - $closure_return_types = EffectsAnalyser::getReturnTypes( - $this->function->stmts, - $closure_yield_types, - $ignore_nullable_issues, - $ignore_falsable_issues, - true - ); - - if ($closure_return_types && $this->function->inferredType) { - /** @var Type\Atomic\Fn */ - $closure_atomic = $this->function->inferredType->getTypes()['Closure']; - $closure_atomic->return_type = new Type\Union($closure_return_types); + ) { + if ($this->function->inferredType) { + /** @var Type\Atomic\Fn */ + $closure_atomic = $this->function->inferredType->getTypes()['Closure']; + $closure_atomic->return_type = $closure_return_type; + } } } + } if ($context->collect_references diff --git a/tests/CallableTest.php b/tests/CallableTest.php index 36f081588..8a9675906 100644 --- a/tests/CallableTest.php +++ b/tests/CallableTest.php @@ -431,6 +431,42 @@ class CallableTest extends TestCase ], 'error_levels' => ['MissingClosureReturnType'], ], + 'inferArrayMapReturnTypeWithoutTypehints' => [ + ' [], + 'error_levels' => ['MissingClosureReturnType'], + ], + 'inferArrayMapReturnTypeWithTypehints' => [ + '