Skip to content

Commit

Permalink
Bleeding edge - report unused results of "and" and "or"
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Dec 8, 2023
1 parent 99afffd commit 1d8fff6
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
32 changes: 24 additions & 8 deletions src/Rules/DeadCode/NoopRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,30 @@ public function processNode(Node $node, Scope $scope): array
) {
$expr = $expr->expr;
}
if ($this->logicalXor && $expr instanceof Node\Expr\BinaryOp\LogicalXor) {
return [
RuleErrorBuilder::message(
'Unused result of "xor" operator.',
)->line($expr->getLine())
->tip('This operator has unexpected precedence, try disambiguating the logic with parentheses ().')
->build(),
];
if ($this->logicalXor) {
if ($expr instanceof Node\Expr\BinaryOp\LogicalXor) {
return [
RuleErrorBuilder::message(
'Unused result of "xor" operator.',
)->line($expr->getLine())
->tip('This operator has unexpected precedence, try disambiguating the logic with parentheses ().')
->build(),
];
}
if ($expr instanceof Node\Expr\BinaryOp\LogicalAnd || $expr instanceof Node\Expr\BinaryOp\LogicalOr) {
if (!$this->isNoopExpr($expr->right)) {
return [];
}

return [
RuleErrorBuilder::message(sprintf(
'Unused result of "%s" operator.',
$expr->getOperatorSigil(),
))->line($expr->getLine())
->tip('This operator has unexpected precedence, try disambiguating the logic with parentheses ().')
->build(),
];
}
}
if (!$this->isNoopExpr($expr)) {
return [];
Expand Down
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/DeadCode/NoopRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ public function testRule(): void
32,
'This operator has unexpected precedence, try disambiguating the logic with parentheses ().',
],
[
'Unused result of "and" operator.',
35,
'This operator has unexpected precedence, try disambiguating the logic with parentheses ().',
],
[
'Unused result of "or" operator.',
38,
'This operator has unexpected precedence, try disambiguating the logic with parentheses ().',
],
]);
}

Expand Down
6 changes: 6 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/noop.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,10 @@ function (stdClass $foo, bool $a, bool $b) {
(string) 1;

$r = $a xor $b;

$s = $a and doFoo();
$t = $a and $b;

$s = $a or doFoo();
$t = $a or $b;
};

0 comments on commit 1d8fff6

Please sign in to comment.