Skip to content

Bleeding edge - improve comparison against BcMath\Number #3995

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

Open
wants to merge 2 commits into
base: 2.1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions conf/bleedingEdge.neon
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ parameters:
stricterFunctionMap: true
reportPreciseLineForUnusedFunctionParameter: true
internalTag: true
checkExtensionsForComparisonOperators: true
7 changes: 6 additions & 1 deletion conf/config.level2.neon
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ rules:
- PHPStan\Rules\Methods\CallPrivateMethodThroughStaticRule
- PHPStan\Rules\Methods\IncompatibleDefaultParameterTypeRule
- PHPStan\Rules\Operators\InvalidBinaryOperationRule
- PHPStan\Rules\Operators\InvalidComparisonOperationRule
- PHPStan\Rules\Operators\InvalidUnaryOperationRule
- PHPStan\Rules\PhpDoc\FunctionConditionalReturnTypeRule
- PHPStan\Rules\PhpDoc\MethodConditionalReturnTypeRule
Expand Down Expand Up @@ -122,3 +121,9 @@ services:

-
class: PHPStan\Rules\InternalTag\RestrictedInternalMethodUsageExtension
-
class: PHPStan\Rules\Operators\InvalidComparisonOperationRule
arguments:
checkExtensionsForComparisonOperators: %featureToggles.checkExtensionsForComparisonOperators%
tags:
- phpstan.rules.rule
1 change: 1 addition & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ parameters:
stricterFunctionMap: false
reportPreciseLineForUnusedFunctionParameter: false
internalTag: false
checkExtensionsForComparisonOperators: false
fileExtensions:
- php
checkAdvancedIsset: false
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ parametersSchema:
stricterFunctionMap: bool()
reportPreciseLineForUnusedFunctionParameter: bool()
internalTag: bool()
checkExtensionsForComparisonOperators: bool()
])
fileExtensions: listOf(string())
checkAdvancedIsset: bool()
Expand Down
28 changes: 6 additions & 22 deletions src/Reflection/InitializerExprTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,8 @@ public function getModType(Expr $left, Expr $right, callable $getTypeCallback):
return $this->getNeverType($leftType, $rightType);
}

$extensionSpecified = $this->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mod($left, $right), $leftType, $rightType);
$extensionSpecified = $this->operatorTypeSpecifyingExtensionRegistryProvider->getRegistry()
->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mod($left, $right), $leftType, $rightType);
if ($extensionSpecified !== null) {
return $extensionSpecified;
}
Expand Down Expand Up @@ -1239,7 +1240,8 @@ public function getPowType(Expr $left, Expr $right, callable $getTypeCallback):
$leftType = $getTypeCallback($left);
$rightType = $getTypeCallback($right);

$extensionSpecified = $this->callOperatorTypeSpecifyingExtensions(new BinaryOp\Pow($left, $right), $leftType, $rightType);
$extensionSpecified = $this->operatorTypeSpecifyingExtensionRegistryProvider->getRegistry()
->callOperatorTypeSpecifyingExtensions(new BinaryOp\Pow($left, $right), $leftType, $rightType);
if ($extensionSpecified !== null) {
return $extensionSpecified;
}
Expand Down Expand Up @@ -1492,25 +1494,6 @@ private function resolveConstantArrayTypeComparison(ConstantArrayType $leftType,
return new TypeResult($resultType->toBoolean(), []);
}

private function callOperatorTypeSpecifyingExtensions(Expr\BinaryOp $expr, Type $leftType, Type $rightType): ?Type
{
$operatorSigil = $expr->getOperatorSigil();
$operatorTypeSpecifyingExtensions = $this->operatorTypeSpecifyingExtensionRegistryProvider->getRegistry()->getOperatorTypeSpecifyingExtensions($operatorSigil, $leftType, $rightType);

/** @var Type[] $extensionTypes */
$extensionTypes = [];

foreach ($operatorTypeSpecifyingExtensions as $extension) {
$extensionTypes[] = $extension->specifyType($operatorSigil, $leftType, $rightType);
}

if (count($extensionTypes) > 0) {
return TypeCombinator::union(...$extensionTypes);
}

return null;
}

/**
* @param BinaryOp\Plus|BinaryOp\Minus|BinaryOp\Mul|BinaryOp\Div|BinaryOp\ShiftLeft|BinaryOp\ShiftRight $expr
*/
Expand Down Expand Up @@ -1555,7 +1538,8 @@ private function resolveCommonMath(Expr\BinaryOp $expr, Type $leftType, Type $ri
}
}

$specifiedTypes = $this->callOperatorTypeSpecifyingExtensions($expr, $leftType, $rightType);
$specifiedTypes = $this->operatorTypeSpecifyingExtensionRegistryProvider->getRegistry()
->callOperatorTypeSpecifyingExtensions($expr, $leftType, $rightType);
if ($specifiedTypes !== null) {
return $specifiedTypes;
}
Expand Down
104 changes: 66 additions & 38 deletions src/Rules/Operators/InvalidComparisonOperationRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\Type\OperatorTypeSpecifyingExtensionRegistryProvider;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
Expand All @@ -26,7 +28,11 @@
final class InvalidComparisonOperationRule implements Rule
{

public function __construct(private RuleLevelHelper $ruleLevelHelper)
public function __construct(
private RuleLevelHelper $ruleLevelHelper,
private OperatorTypeSpecifyingExtensionRegistryProvider $operatorTypeSpecifyingExtensionRegistryProvider,
private bool $checkExtensionsForComparisonOperators,
)
{
}

Expand All @@ -53,6 +59,22 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$result = $this->operatorTypeSpecifyingExtensionRegistryProvider->getRegistry()->callOperatorTypeSpecifyingExtensions(
$node,
$scope->getType($node->left),
$scope->getType($node->right),
Comment on lines +64 to +65
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This might cause some issues below level 7, but I'm not sure how to improve it. The operator type specifying extensions don't support union well anyway.

);

if ($result !== null) {
if (! $result instanceof ErrorType) {
return [];
}

if ($this->checkExtensionsForComparisonOperators) {
return $this->createError($node, $scope);
}
}

if (
($this->isNumberType($scope, $node->left) && (
$this->isPossiblyNullableObjectType($scope, $node->right) || $this->isPossiblyNullableArrayType($scope, $node->right)
Expand All @@ -61,43 +83,7 @@ public function processNode(Node $node, Scope $scope): array
$this->isPossiblyNullableObjectType($scope, $node->left) || $this->isPossiblyNullableArrayType($scope, $node->left)
))
) {
switch (get_class($node)) {
case Node\Expr\BinaryOp\Equal::class:
$nodeType = 'equal';
break;
case Node\Expr\BinaryOp\NotEqual::class:
$nodeType = 'notEqual';
break;
case Node\Expr\BinaryOp\Greater::class:
$nodeType = 'greater';
break;
case Node\Expr\BinaryOp\GreaterOrEqual::class:
$nodeType = 'greaterOrEqual';
break;
case Node\Expr\BinaryOp\Smaller::class:
$nodeType = 'smaller';
break;
case Node\Expr\BinaryOp\SmallerOrEqual::class:
$nodeType = 'smallerOrEqual';
break;
case Node\Expr\BinaryOp\Spaceship::class:
$nodeType = 'spaceship';
break;
default:
throw new ShouldNotHappenException();
}

return [
RuleErrorBuilder::message(sprintf(
'Comparison operation "%s" between %s and %s results in an error.',
$node->getOperatorSigil(),
$scope->getType($node->left)->describe(VerbosityLevel::value()),
$scope->getType($node->right)->describe(VerbosityLevel::value()),
))
->line($node->left->getStartLine())
->identifier(sprintf('%s.invalid', $nodeType))
->build(),
];
return $this->createError($node, $scope);
}

return [];
Expand Down Expand Up @@ -164,4 +150,46 @@ private function isPossiblyNullableArrayType(Scope $scope, Node\Expr $expr): boo
return !($type instanceof ErrorType) && $type->isArray()->yes();
}

/** @return list<IdentifierRuleError> */
private function createError(Node\Expr\BinaryOp $node, Scope $scope): array
{
switch (get_class($node)) {
case Node\Expr\BinaryOp\Equal::class:
$nodeType = 'equal';
break;
case Node\Expr\BinaryOp\NotEqual::class:
$nodeType = 'notEqual';
break;
case Node\Expr\BinaryOp\Greater::class:
$nodeType = 'greater';
break;
case Node\Expr\BinaryOp\GreaterOrEqual::class:
$nodeType = 'greaterOrEqual';
break;
case Node\Expr\BinaryOp\Smaller::class:
$nodeType = 'smaller';
break;
case Node\Expr\BinaryOp\SmallerOrEqual::class:
$nodeType = 'smallerOrEqual';
break;
case Node\Expr\BinaryOp\Spaceship::class:
$nodeType = 'spaceship';
break;
default:
throw new ShouldNotHappenException();
}

return [
RuleErrorBuilder::message(sprintf(
'Comparison operation "%s" between %s and %s results in an error.',
$node->getOperatorSigil(),
$scope->getType($node->left)->describe(VerbosityLevel::value()),
$scope->getType($node->right)->describe(VerbosityLevel::value()),
))
->line($node->left->getStartLine())
->identifier(sprintf('%s.invalid', $nodeType))
->build(),
];
}

}
21 changes: 21 additions & 0 deletions src/Type/OperatorTypeSpecifyingExtensionRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace PHPStan\Type;

use PhpParser\Node\Expr;
use function array_filter;
use function array_values;
use function count;

final class OperatorTypeSpecifyingExtensionRegistry
{
Expand All @@ -25,4 +27,23 @@ public function getOperatorTypeSpecifyingExtensions(string $operator, Type $left
return array_values(array_filter($this->extensions, static fn (OperatorTypeSpecifyingExtension $extension): bool => $extension->isOperatorSupported($operator, $leftType, $rightType)));
}

public function callOperatorTypeSpecifyingExtensions(Expr\BinaryOp $expr, Type $leftType, Type $rightType): ?Type
{
$operatorSigil = $expr->getOperatorSigil();
$operatorTypeSpecifyingExtensions = $this->getOperatorTypeSpecifyingExtensions($operatorSigil, $leftType, $rightType);

/** @var Type[] $extensionTypes */
$extensionTypes = [];

foreach ($operatorTypeSpecifyingExtensions as $extension) {
$extensionTypes[] = $extension->specifyType($operatorSigil, $leftType, $rightType);
}

if (count($extensionTypes) > 0) {
return TypeCombinator::union(...$extensionTypes);
}

return null;
}

}
16 changes: 15 additions & 1 deletion src/Type/Php/BcMathNumberOperatorTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
namespace PHPStan\Type\Php;

use PHPStan\Php\PhpVersion;
use PHPStan\Type\BooleanType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\OperatorTypeSpecifyingExtension;
Expand All @@ -25,7 +27,7 @@ public function isOperatorSupported(string $operatorSigil, Type $leftSide, Type

$bcMathNumberType = new ObjectType('BcMath\Number');

return in_array($operatorSigil, ['-', '+', '*', '/', '**', '%'], true)
return in_array($operatorSigil, ['-', '+', '*', '/', '**', '%', '<', '<=', '>', '>=', '==', '!=', '<=>'], true)
&& (
$bcMathNumberType->isSuperTypeOf($leftSide)->yes()
|| $bcMathNumberType->isSuperTypeOf($rightSide)->yes()
Expand All @@ -39,6 +41,18 @@ public function specifyType(string $operatorSigil, Type $leftSide, Type $rightSi
? $rightSide
: $leftSide;

if ($otherSide->isFloat()->yes()) {
return new ErrorType();
}

if (in_array($operatorSigil, ['<', '<=', '>', '>=', '==', '!='], true)) {
return new BooleanType();
}

if ($operatorSigil === '<=>') {
return IntegerRangeType::fromInterval(-1, 1);
}

if (
$otherSide->isInteger()->yes()
|| $otherSide->isNumericString()->yes()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PHPStan\Rules\Operators;

use PHPStan\DependencyInjection\Type\OperatorTypeSpecifyingExtensionRegistryProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Testing\RuleTestCase;
Expand All @@ -17,6 +18,8 @@ protected function getRule(): Rule
{
return new InvalidComparisonOperationRule(
new RuleLevelHelper($this->createReflectionProvider(), true, false, true, false, false, false, true),
$this->getContainer()->getByType(OperatorTypeSpecifyingExtensionRegistryProvider::class),
true,
);
}

Expand Down Expand Up @@ -173,4 +176,22 @@ public function testBug11119(): void
$this->analyse([__DIR__ . '/data/bug-11119.php'], []);
}

public function testBug13001(): void
{
if (PHP_VERSION_ID < 80400) {
$this->markTestSkipped('Test requires PHP 8.4.');
}

$this->analyse([__DIR__ . '/data/bug-13001.php'], [
[
'Comparison operation ">" between BcMath\\Number and 0.2 results in an error.',
10,
],
[
'Comparison operation "<=>" between 0.2 and BcMath\\Number results in an error.',
11,
],
]);
}

}
Loading
Loading