Skip to content

Commit

Permalink
Fix #2914 - falsable functions who only expect true now produce errors
Browse files Browse the repository at this point in the history
  • Loading branch information
leightonthomas authored and muglug committed Mar 9, 2020
1 parent 2c8688d commit 60fb392
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Psalm/Internal/Analyzer/Statements/ReturnAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ public static function analyze(
if (!$stmt_type->ignore_falsable_issues
&& $inferred_type->isFalsable()
&& !$local_return_type->isFalsable()
&& !$local_return_type->hasBool()
&& (!$local_return_type->hasBool() || $local_return_type->isTrue())
&& !$local_return_type->hasScalar()
) {
if (IssueBuffer::accepts(
Expand Down
8 changes: 8 additions & 0 deletions src/Psalm/Type/Union.php
Original file line number Diff line number Diff line change
Expand Up @@ -998,6 +998,14 @@ public function isFalse()
return count($this->types) === 1 && isset($this->types['false']);
}

/**
* @return bool
*/
public function isTrue()
{
return count($this->types) === 1 && isset($this->types['true']);
}

/**
* @return bool
*/
Expand Down
34 changes: 34 additions & 0 deletions tests/AnnotationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,20 @@ function foo(): array {
return ["a" => 1, "b" => "two"];
}'
],
'falsableFunctionAllowedWhenBooleanExpected' => [
'<?php
/** @psalm-return bool */
function alwaysFalse1()
{
return false;
}
function alwaysFalse2(): bool
{
return false;
}'
],
];
}

Expand Down Expand Up @@ -1605,6 +1619,26 @@ function foo() {}',
function f($reference) {}',
'error_message' => 'MissingDocblockType',
],
'canNeverReturnDeclaredType' => [
'<?php
/** @psalm-return false */
function alwaysFalse() : bool
{
return true;
}',
'error_message' => 'InvalidReturnStatement - src' . DIRECTORY_SEPARATOR . 'somefile.php:6:32',
],
'falsableWithExpectedTypeTrue' => [
'<?php
/** @psalm-return true */
function alwaysFalse()
{
return false;
}',
'error_message' => 'FalsableReturnStatement - src' . DIRECTORY_SEPARATOR . 'somefile.php:6:32',
],
];
}
}

0 comments on commit 60fb392

Please sign in to comment.