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

Handle BcMath\Number operators for simple cases #3787

Open
wants to merge 7 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
4 changes: 4 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,10 @@ services:
arguments:
reportMagicProperties: %reportMagicProperties%
checkDynamicProperties: %checkDynamicProperties%
-
class: PHPStan\Type\Php\BcMathNumberOperatorTypeSpecifyingExtension
tags:
- phpstan.broker.operatorTypeSpecifyingExtension

-
class: PHPStan\Rules\Properties\UninitializedPropertyRule
Expand Down
5 changes: 5 additions & 0 deletions src/Php/PhpVersion.php
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,9 @@ public function substrReturnFalseInsteadOfEmptyString(): bool
return $this->versionId < 80000;
}

public function supportsBcMathNumberOperatorOverloading(): bool
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I copied this from the original PR. But I'm not sure whether it's correct. I assume that the reason we even need this is because earlier PHP versions might use a polyfill (which wouldn't have the operators overloaded). But PHP 8.4 can also use a polyfill, because bcmath is an optional extension.

{
return $this->versionId >= 80400;
}

}
15 changes: 10 additions & 5 deletions src/Reflection/InitializerExprTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,11 @@ public function getModType(Expr $left, Expr $right, callable $getTypeCallback):
return $this->getNeverType($leftType, $rightType);
}

$extensionSpecified = $this->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mod($left, $right), $leftType, $rightType);
if ($extensionSpecified !== null) {
return $extensionSpecified;
}

if ($leftType->toNumber() instanceof ErrorType || $rightType->toNumber() instanceof ErrorType) {
return new ErrorType();
}
Expand Down Expand Up @@ -1234,16 +1239,16 @@ public function getPowType(Expr $left, Expr $right, callable $getTypeCallback):
$leftType = $getTypeCallback($left);
$rightType = $getTypeCallback($right);

$exponentiatedTyped = $leftType->exponentiate($rightType);
if (!$exponentiatedTyped instanceof ErrorType) {
return $exponentiatedTyped;
}

$extensionSpecified = $this->callOperatorTypeSpecifyingExtensions(new BinaryOp\Pow($left, $right), $leftType, $rightType);
if ($extensionSpecified !== null) {
return $extensionSpecified;
}

$exponentiatedTyped = $leftType->exponentiate($rightType);
if (!$exponentiatedTyped instanceof ErrorType) {
return $exponentiatedTyped;
}

return new ErrorType();
}

Expand Down
15 changes: 14 additions & 1 deletion src/Type/ObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
Expand Down Expand Up @@ -593,6 +595,14 @@ public function toFloat(): Type

public function toString(): Type
{
if ($this->isInstanceOf('BcMath\Number')->yes()) {
return new IntersectionType([
new StringType(),
new AccessoryNumericStringType(),
new AccessoryNonEmptyStringType(),
]);
}

$classReflection = $this->getClassReflection();
if ($classReflection === null) {
return new ErrorType();
Expand Down Expand Up @@ -673,7 +683,10 @@ public function toArrayKey(): Type

public function toBoolean(): BooleanType
{
if ($this->isInstanceOf('SimpleXMLElement')->yes()) {
if (
$this->isInstanceOf('SimpleXMLElement')->yes()
|| $this->isInstanceOf('BcMath\Number')->yes()
) {
return new BooleanType();
}

Expand Down
53 changes: 53 additions & 0 deletions src/Type/Php/BcMathNumberOperatorTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PHPStan\Php\PhpVersion;
use PHPStan\Type\ErrorType;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\OperatorTypeSpecifyingExtension;
use PHPStan\Type\Type;
use function in_array;

final class BcMathNumberOperatorTypeSpecifyingExtension implements OperatorTypeSpecifyingExtension
{

public function __construct(private PhpVersion $phpVersion)
{
}

public function isOperatorSupported(string $operatorSigil, Type $leftSide, Type $rightSide): bool
{
if (!$this->phpVersion->supportsBcMathNumberOperatorOverloading() || $leftSide instanceof NeverType || $rightSide instanceof NeverType) {
return false;
}

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

return in_array($operatorSigil, ['-', '+', '*', '/', '**', '%'], true)
&& (
$bcMathNumberType->isSuperTypeOf($leftSide)->yes()
|| $bcMathNumberType->isSuperTypeOf($rightSide)->yes()
);
}

public function specifyType(string $operatorSigil, Type $leftSide, Type $rightSide): Type
{
$bcMathNumberType = new ObjectType('BcMath\Number');
$otherSide = $bcMathNumberType->isSuperTypeOf($leftSide)->yes()
? $rightSide
: $leftSide;

if (
$otherSide->isInteger()->yes()
|| $otherSide->isNumericString()->yes()
|| $bcMathNumberType->isSuperTypeOf($otherSide)->yes()
) {
return $bcMathNumberType;
}

return new ErrorType();
}

}
16 changes: 16 additions & 0 deletions src/Type/TypeCombinator.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
use function md5;
use function sprintf;
use function usort;
use const PHP_INT_MAX;
use const PHP_INT_MIN;

/**
* @api
Expand Down Expand Up @@ -185,6 +187,7 @@ public static function union(Type ...$types): Type
$scalarTypes = [];
$hasGenericScalarTypes = [];
$enumCaseTypes = [];
$integerRangeTypes = [];
for ($i = 0; $i < $typesCount; $i++) {
if ($types[$i] instanceof ConstantScalarType) {
$type = $types[$i];
Expand Down Expand Up @@ -212,6 +215,13 @@ public static function union(Type ...$types): Type
continue;
}

if ($types[$i] instanceof IntegerRangeType) {
$integerRangeTypes[] = $types[$i];
unset($types[$i]);

continue;
}

if (!$types[$i]->isArray()->yes()) {
continue;
}
Expand All @@ -225,6 +235,12 @@ public static function union(Type ...$types): Type
}

$enumCaseTypes = array_values($enumCaseTypes);
usort(
$integerRangeTypes,
static fn (IntegerRangeType $a, IntegerRangeType $b): int => ($a->getMin() ?? PHP_INT_MIN) <=> ($b->getMin() ?? PHP_INT_MIN)
?: ($a->getMax() ?? PHP_INT_MAX) <=> ($b->getMax() ?? PHP_INT_MAX)
);
$types = array_merge($types, $integerRangeTypes);
$types = array_values($types);
$typesCount = count($types);

Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ private static function findTestFiles(): iterable
yield __DIR__ . '/../Rules/Comparison/data/bug-9499.php';
}

if (PHP_VERSION_ID >= 80400) {
yield __DIR__ . '/../Rules/Operators/data/bcmath-number.php';
}

yield __DIR__ . '/../Rules/PhpDoc/data/bug-8609-function.php';
yield __DIR__ . '/../Rules/Comparison/data/bug-5365.php';
yield __DIR__ . '/../Rules/Comparison/data/bug-6551.php';
Expand Down
8 changes: 4 additions & 4 deletions tests/PHPStan/Analyser/nsrt/pow.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ function (): void {
$x = 4;
}

assertType('int<4, 27>|int<16, 81>', pow($range, $x));
assertType('int<4, 27>|int<16, 81>', $range ** $x);
assertType('int<4, 81>', pow($range, $x));
assertType('int<4, 81>', $range ** $x);

assertType('int<4, 27>|int<16, 64>', pow($x, $range));
assertType('int<4, 27>|int<16, 64>', $x ** $range);
assertType('int<4, 64>', pow($x, $range));
assertType('int<4, 64>', $x ** $range);
Comment on lines -50 to +54
Copy link
Contributor Author

@schlndh schlndh Jan 19, 2025

Choose a reason for hiding this comment

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

This is a result of UnionType::getSortedTypes being called. I haven't looked into it, but I guess it's a bug in TypeCombinator::union, because the result of a union shouldn't depend on the order of parameters.

EDIT: I had to fix it, because it broke the test on PHP <8.4 due to the extension only running on 8.4 and above.


assertType('int<4, 27>', pow($range, $range));
assertType('int<4, 27>', $range ** $range);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -433,4 +433,10 @@ public function testBug5365(): void
$this->analyse([__DIR__ . '/data/bug-5365.php'], []);
}

public function testBug8555(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/data/bug-8555.php'], []);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ public function testBug8797(): void
$this->analyse([__DIR__ . '/data/bug-8797.php'], []);
}

public function testBug7937(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/data/bug-7937.php'], []);
}

public function dataReportAlwaysTrueInLastCondition(): iterable
{
yield [false, [
Expand Down
31 changes: 31 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-7937.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php declare(strict_types = 1);

namespace Bug7937;

class HelloWorld
{
public function f(int $a, int $b)
{
if (!$a && !$b) {
return "";
}

$output = " ";

if ($a) {
$output .= "$a";
}

\PHPStan\dumpType($a);

if ($b) {
\PHPStan\dumpType($a);

if (!$a) {
$output .= "_";
}
}

return $output;
}
}
14 changes: 14 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-8555.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Bug8555;

/**
* @return array<string, int|null>
*/
function test(int $first, int $second): array
{
return [
'test' => $first && $second ? $first : null,
'test2' => $first && $second ? $first : null,
];
}
Loading
Loading