From 1c2bc49838cb4d2bf45027b57e7e133d965263bf Mon Sep 17 00:00:00 2001 From: Bruce Weirdan Date: Thu, 16 Feb 2023 01:28:47 -0400 Subject: [PATCH] Forbid non-null defaults for callable parameters Fixes vimeo/psalm#3284 --- .../Internal/Analyzer/FunctionLikeAnalyzer.php | 15 +++++++++++++++ tests/FunctionCallTest.php | 6 ++++++ tests/MethodCallTest.php | 8 ++++++++ 3 files changed, 29 insertions(+) diff --git a/src/Psalm/Internal/Analyzer/FunctionLikeAnalyzer.php b/src/Psalm/Internal/Analyzer/FunctionLikeAnalyzer.php index 357bf57326b..152565c2862 100644 --- a/src/Psalm/Internal/Analyzer/FunctionLikeAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/FunctionLikeAnalyzer.php @@ -1256,6 +1256,21 @@ private function processParams( ), ); } + + if ($default_type + && !$default_type->isNull() + && $param_type->isSingleAndMaybeNullable() + && $param_type->getCallableTypes() + ) { + IssueBuffer::maybeAdd( + new InvalidParamDefault( + 'Default value type for ' . $param_type->getId() . ' argument ' . ($offset + 1) + . ' of method ' . $cased_method_id + . ' can only be null, ' . $default_type->getId() . ' specified', + $function_param->type_location, + ), + ); + } } if ($has_template_types) { diff --git a/tests/FunctionCallTest.php b/tests/FunctionCallTest.php index 6c0a4f8a643..751590c7b1c 100644 --- a/tests/FunctionCallTest.php +++ b/tests/FunctionCallTest.php @@ -2741,6 +2741,12 @@ function takesArrayShapeWithZeroOrPositiveInt(array $foo): void ', 'error_message' => 'RedundantFunctionCall', ], + 'incorrectCallableParamDefault' => [ + 'code' => ' 'InvalidParamDefault', + ], ]; } diff --git a/tests/MethodCallTest.php b/tests/MethodCallTest.php index e308dbd6f08..e2030863f24 100644 --- a/tests/MethodCallTest.php +++ b/tests/MethodCallTest.php @@ -1562,6 +1562,14 @@ public function foo(): string { }', 'error_message' => 'UndefinedMethod', ], + 'incorrectCallableParamDefault' => [ + 'code' => ' 'InvalidParamDefault', + ], ]; } }