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

Add throw point for division #1280

Merged
merged 11 commits into from May 4, 2022
Merged

Conversation

rajyan
Copy link
Contributor

@rajyan rajyan commented May 3, 2022

fixes phpstan/phpstan#6349

Implemented throw point for zero value div/mod DivisionByZeroError.
I didn't implemented it for float, because currently there is no way to narrow float value as non-zero float.

I'm not satisfied enough with 01c2761
zero value ConstantScalarType would not be passed to calculateFromScalars because it's handled here

if (
$node instanceof Node\Expr\BinaryOp\Div
|| $node instanceof Node\Expr\AssignOp\Div
|| $node instanceof Node\Expr\BinaryOp\Mod
|| $node instanceof Node\Expr\AssignOp\Mod
) {
if ($node instanceof Node\Expr\AssignOp) {
$right = $node->expr;
} else {
$right = $node->right;
}
$rightType = $this->getType($right);
$integerType = $rightType->toInteger();
if (
$node instanceof Node\Expr\BinaryOp\Mod
|| $node instanceof Node\Expr\AssignOp\Mod
) {
if ($integerType instanceof ConstantIntegerType && $integerType->getValue() === 1) {
return new ConstantIntegerType(0);
}
}
$rightScalarTypes = TypeUtils::getConstantScalars($rightType->toNumber());
foreach ($rightScalarTypes as $scalarType) {
if (
$scalarType->getValue() === 0
|| $scalarType->getValue() === 0.0
) {
return new ErrorType();
}
}
}

Although, this commit might not be redundant, because using calculateFromScalars in other places may cause DivisionByZeroError.

@rajyan rajyan marked this pull request as draft May 3, 2022 16:33
@rajyan rajyan marked this pull request as ready for review May 3, 2022 17:56
@herndlm
Copy link
Contributor

herndlm commented May 3, 2022

I'm too much out of context but would checking against PHP_FLOAT_EPSILON help with the float 0 detection?

@rajyan
Copy link
Contributor Author

rajyan commented May 4, 2022

@herndlm
No. The problem for float is, division with 0.0 causes DivisionByZeroError but we can’t narrow down float.
https://phpstan.org/r/ff0c680f-2c75-46c3-b889-7e900e4609e1
so if I add a throw point for float, there is no way to make PHPStan not throw. (we need a type like float~ 0.0

@ondrejmirtes ondrejmirtes merged commit 58b6023 into phpstan:1.6.x May 4, 2022
@ondrejmirtes
Copy link
Member

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants