Skip to content

Commit

Permalink
add error for void/never return functions that require-usage + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kkmuffme committed Feb 29, 2024
1 parent 1b70fae commit 5b4276c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Psalm/Internal/Analyzer/FunctionLike/ReturnTypeAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Psalm\Internal\Type\TemplateStandinTypeReplacer;
use Psalm\Internal\Type\TypeExpander;
use Psalm\Issue\ImplicitToStringCast;
use Psalm\Issue\InvalidDocblock;
use Psalm\Issue\InvalidFalsableReturnType;
use Psalm\Issue\InvalidNullableReturnType;
use Psalm\Issue\InvalidParent;
Expand Down Expand Up @@ -839,6 +840,28 @@ public static function checkReturnType(
$parent_class = $classlike_storage->parent_class;
}

if ($storage->return_type->isVoid() || $storage->return_type->isNever()) {
$incompatible_annotation_text = false;
if ($storage->require_usage) {
$incompatible_annotation_text = '@psalm-require-usage';
} elseif ($storage->pure) {
$incompatible_annotation_text = '@psalm-pure';
} elseif ($storage->removed_taints || $storage->conditionally_removed_taints) {
$incompatible_annotation_text = '@psalm-taint-escape';
}

if ($incompatible_annotation_text !== false) {
$return_type_text = $storage->return_type->isVoid() ? 'void' : 'never';
IssueBuffer::maybeAdd(
new InvalidDocblock(
'Return type "' . $return_type_text . '" is incompatible with '
. $incompatible_annotation_text,
$storage->return_type_location,
),
);
}
}

if (!$storage->signature_return_type || $storage->signature_return_type === $storage->return_type) {
foreach ($storage->return_type->getAtomicTypes() as $type) {
if ($type instanceof TNamedObject
Expand Down
41 changes: 41 additions & 0 deletions tests/AnnotationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,47 @@ public function barBar() {
function foo($arg) {}',
'error_message' => 'InvalidDocblock',
],
'invalidVoidPure' => [
'code' => '<?php
/**
* @psalm-pure
* @param array<float, string> $arg
* @return void
*/
function foo($arg) {}',
'error_message' => 'InvalidDocblock',
],
'invalidVoidRequireUsage' => [
'code' => '<?php
/**
* @psalm-require-usage
* @param array<float, string> $arg
* @return void
*/
function foo($arg) {}',
'error_message' => 'InvalidDocblock',
],
'invalidNeverRequireUsage' => [
'code' => '<?php
/**
* @psalm-require-usage
* @return never
*/
function foo() {
exit;
}',
'error_message' => 'InvalidDocblock',
],
'invalidVoidTaintEscape' => [
'code' => '<?php
/**
* @psalm-taint-escape html
* @param array<float, string> $arg
* @return void
*/
function foo($arg) {}',
'error_message' => 'InvalidDocblock',
],
'invalidClassMethodReturnBrackets' => [
'code' => '<?php
class C {
Expand Down

0 comments on commit 5b4276c

Please sign in to comment.