Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

multiply by zero is always zero #974

Merged
merged 3 commits into from Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Analyser/MutatingScope.php
Expand Up @@ -1040,6 +1040,24 @@ private function resolveType(Expr $node): Type
return new StringType();
}

if (
$node instanceof Node\Expr\BinaryOp\Mul
|| $node instanceof Node\Expr\AssignOp\Mul
) {
if ($node instanceof Node\Expr\AssignOp) {
$leftType = null;
$rightType = $this->getType($node->expr);
} else {
$leftType = $this->getType($node->left);
$rightType = $this->getType($node->right);
}

if ($leftType instanceof ConstantIntegerType && $leftType->getValue() === 0 ||
$rightType instanceof ConstantIntegerType && $rightType->getValue() === 0) {
return new ConstantIntegerType(0);
}
}

if (
$node instanceof Node\Expr\BinaryOp\Div
|| $node instanceof Node\Expr\AssignOp\Div
Expand Down
22 changes: 22 additions & 0 deletions tests/PHPStan/Analyser/data/math.php
Expand Up @@ -109,4 +109,26 @@ public function doSit(int $i, int $j): void
assertType('int', $i - $j);
}

/**
* @param int<-5, 5> $range
*/
public function multiplyZero(int $i, float $f, $range): void
{
assertType('0', $i * 0);
assertType('0', $f * 0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Float multiplied by zero is a float: https://3v4l.org/u6dA6

It also works for strings: https://3v4l.org/Ksheh

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch. fixed

assertType('0', $range * 0);

assertType('0', 0 * $i);
assertType('0', 0 * $f);
assertType('0', 0 * $range);

$i *= 0;
$f *= 0;
$range *= 0;
assertType('0', $i);
assertType('0', $f);
assertType('0', $range);

}

}