diff --git a/conf/bleedingEdge.neon b/conf/bleedingEdge.neon index e8e63a9814a..793f807cd14 100644 --- a/conf/bleedingEdge.neon +++ b/conf/bleedingEdge.neon @@ -24,6 +24,7 @@ parameters: newOnNonObject: true unnecessaryNullCoalesce: true finiteTypesInHaystack: true + nonFiniteFloats: true switchConditionAlwaysFalse: true checkImportedClassNameCase: true sortWithoutEffect: true diff --git a/conf/config.neon b/conf/config.neon index 32ea19804ba..72fad05d8d8 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -56,6 +56,7 @@ parameters: newOnNonObject: false unnecessaryNullCoalesce: false finiteTypesInHaystack: false + nonFiniteFloats: false switchConditionAlwaysFalse: false checkImportedClassNameCase: false sortWithoutEffect: false @@ -75,6 +76,7 @@ parameters: checkClassCaseSensitivity: false checkExplicitMixed: false checkImplicitMixed: false + checkNonFiniteFloats: false checkFunctionArgumentTypes: false checkFunctionNameCase: false checkInternalClassCaseSensitivity: false diff --git a/conf/parametersSchema.neon b/conf/parametersSchema.neon index 70db3760586..0f44e21f44d 100644 --- a/conf/parametersSchema.neon +++ b/conf/parametersSchema.neon @@ -53,6 +53,7 @@ parametersSchema: newOnNonObject: bool() unnecessaryNullCoalesce: bool() finiteTypesInHaystack: bool() + nonFiniteFloats: bool() switchConditionAlwaysFalse: bool() checkImportedClassNameCase: bool() sortWithoutEffect: bool() @@ -72,6 +73,7 @@ parametersSchema: checkClassCaseSensitivity: bool() checkExplicitMixed: bool() checkImplicitMixed: bool() + checkNonFiniteFloats: bool() checkFunctionArgumentTypes: bool() checkFunctionNameCase: bool() checkInternalClassCaseSensitivity: bool() diff --git a/src/Php/PhpVersion.php b/src/Php/PhpVersion.php index 19931c097e6..3477353ac51 100644 --- a/src/Php/PhpVersion.php +++ b/src/Php/PhpVersion.php @@ -514,6 +514,11 @@ public function supportsNoDiscardAttribute(): bool return $this->versionId >= 80500; } + public function warnsOnNonFiniteFloatConversion(): bool + { + return $this->versionId >= 80500; + } + public function deprecatesNonStandardCasts(): bool { return $this->versionId >= 80500; diff --git a/src/Php/PhpVersions.php b/src/Php/PhpVersions.php index 18a699c704f..fcd4729c7d1 100644 --- a/src/Php/PhpVersions.php +++ b/src/Php/PhpVersions.php @@ -249,6 +249,12 @@ public function supportsVoidCast(): TrinaryLogic return IntegerRangeType::fromInterval(80500, null)->isSuperTypeOf($this->phpVersions)->result; } + /** Converting NAN to string, or NAN, INF or a float out of the int range to int, emits a warning. */ + public function warnsOnNonFiniteFloatConversion(): TrinaryLogic + { + return IntegerRangeType::fromInterval(80500, null)->isSuperTypeOf($this->phpVersions)->result; + } + public function deprecatesNonStandardCasts(): TrinaryLogic { return IntegerRangeType::fromInterval(80500, null)->isSuperTypeOf($this->phpVersions)->result; diff --git a/src/Rules/Floats/AssignConcatNanRule.php b/src/Rules/Floats/AssignConcatNanRule.php new file mode 100644 index 00000000000..9bb517e7bd9 --- /dev/null +++ b/src/Rules/Floats/AssignConcatNanRule.php @@ -0,0 +1,38 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class AssignConcatNanRule implements Rule +{ + + use NanToStringHelperTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return Concat::class; + } + + public function processNode(Node $node, Scope $scope): array + { + return $this->checkNanToString($this->helper, $scope, $node->expr, 'Concatenation'); + } + +} diff --git a/src/Rules/Floats/ConcatNanRule.php b/src/Rules/Floats/ConcatNanRule.php new file mode 100644 index 00000000000..14553fba10b --- /dev/null +++ b/src/Rules/Floats/ConcatNanRule.php @@ -0,0 +1,45 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class ConcatNanRule implements Rule +{ + + use NanToStringHelperTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return Concat::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $errors = []; + foreach ([$node->left, $node->right] as $expr) { + foreach ($this->checkNanToString($this->helper, $scope, $expr, 'Concatenation') as $error) { + $errors[] = $error; + } + } + + return $errors; + } + +} diff --git a/src/Rules/Floats/EchoNanRule.php b/src/Rules/Floats/EchoNanRule.php new file mode 100644 index 00000000000..2db4b2e5e50 --- /dev/null +++ b/src/Rules/Floats/EchoNanRule.php @@ -0,0 +1,45 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class EchoNanRule implements Rule +{ + + use NanToStringHelperTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return Echo_::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $errors = []; + foreach ($node->exprs as $expr) { + foreach ($this->checkNanToString($this->helper, $scope, $expr, 'Echo') as $error) { + $errors[] = $error; + } + } + + return $errors; + } + +} diff --git a/src/Rules/Floats/FormatNonFiniteFloatRule.php b/src/Rules/Floats/FormatNonFiniteFloatRule.php new file mode 100644 index 00000000000..d9fd4b2076f --- /dev/null +++ b/src/Rules/Floats/FormatNonFiniteFloatRule.php @@ -0,0 +1,160 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class FormatNonFiniteFloatRule implements Rule +{ + + private const FORMAT_ARGUMENT_POSITIONS = [ + 'printf' => 0, + 'sprintf' => 0, + 'fprintf' => 1, + ]; + + public function __construct( + private ReflectionProvider $reflectionProvider, + private PrintfFormatParser $printfFormatParser, + private NonFiniteFloatHelper $helper, + ) + { + } + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->name instanceof Node\Name) { + return []; + } + + $name = $this->reflectionProvider->resolveFunctionName($node->name, $scope); + if ($name === null) { + return []; + } + $name = strtolower($name); + + $args = $node->getArgs(); + foreach ($args as $arg) { + if ($arg->unpack) { + return []; + } + } + + if ($name === 'number_format') { + if (count($args) === 0) { + return []; + } + + $error = $this->check( + $this->helper->canBeNonFinite($scope->getType($args[0]->value)), + $scope->getType($args[0]->value), + 'Parameter #1 $num of function number_format()', + '"nan" or "inf"', + 'it is not a finite float', + ); + + return $error === null ? [] : [$error]; + } + + if (!array_key_exists($name, self::FORMAT_ARGUMENT_POSITIONS)) { + return []; + } + + $formatPosition = self::FORMAT_ARGUMENT_POSITIONS[$name]; + if (!isset($args[$formatPosition])) { + return []; + } + + $formats = $scope->getType($args[$formatPosition]->value)->getConstantStrings(); + if (count($formats) !== 1) { + return []; + } + + $uses = $this->printfFormatParser->parse($formats[0]->getValue(), $scope->getPhpVersion()); + if ($uses === null) { + return []; + } + + $errors = []; + foreach ($uses as $use) { + if ($use['kind'] !== 'value') { + continue; + } + $argIndex = $formatPosition + 1 + $use['index']; + if (!isset($args[$argIndex])) { + continue; + } + + $type = $scope->getType($args[$argIndex]->value); + $label = sprintf('Placeholder "%s" of function %s()', $use['placeholder'], $name); + if (in_array($use['specifier'], ['e', 'E', 'f', 'F', 'g', 'G', 'h', 'H'], true)) { + $error = $this->check($this->helper->canBeNonFinite($type), $type, $label, '"NaN", "INF" or "-INF"', 'it is not a finite float'); + } elseif (in_array($use['specifier'], ['d', 'u', 'c', 'o', 'x', 'X', 'b'], true)) { + $error = $this->check($this->helper->canBeOutOfIntRange($type), $type, $label, 'an unspecified number', 'it is NAN, INF or out of the int range'); + } elseif ($use['specifier'] === 's' && $scope->getPhpVersion()->warnsOnNonFiniteFloatConversion()->yes()) { + $error = $this->check($this->helper->canBeNan($type), $type, $label, '"NAN" with a warning', 'it is NAN'); + } else { + continue; + } + + // a placeholder used twice, like `%1$f %1$f`, is reported once + if ($error === null) { + continue; + } + + $errors[$error->getMessage()] = $error; + } + + return array_values($errors); + } + + private function check(TrinaryLogic $canBe, Type $type, string $label, string $output, string $condition): ?IdentifierRuleError + { + if (!$this->helper->shouldReport($canBe)) { + return null; + } + + return RuleErrorBuilder::message(sprintf( + '%s formats %s, which prints %s%s.', + $label, + $type->describe(VerbosityLevel::value()), + $output, + $canBe->yes() ? '' : ' when ' . $condition, + ))->identifier('nonFiniteFloat.format')->build(); + } + +} diff --git a/src/Rules/Floats/IntCastNonFiniteFloatRule.php b/src/Rules/Floats/IntCastNonFiniteFloatRule.php new file mode 100644 index 00000000000..ff4524de5e3 --- /dev/null +++ b/src/Rules/Floats/IntCastNonFiniteFloatRule.php @@ -0,0 +1,41 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class IntCastNonFiniteFloatRule implements Rule +{ + + use NonFiniteFloatToIntTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return Cast\Int_::class; + } + + public function processNode(Node $node, Scope $scope): array + { + return $this->checkToInt($this->helper, $scope, $node->expr, 'Casting to int'); + } + +} diff --git a/src/Rules/Floats/InterpolatedStringNanRule.php b/src/Rules/Floats/InterpolatedStringNanRule.php new file mode 100644 index 00000000000..cb7a08afd1f --- /dev/null +++ b/src/Rules/Floats/InterpolatedStringNanRule.php @@ -0,0 +1,48 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class InterpolatedStringNanRule implements Rule +{ + + use NanToStringHelperTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return InterpolatedString::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $errors = []; + foreach ($node->parts as $part) { + if (!$part instanceof Node\Expr) { + continue; + } + foreach ($this->checkNanToString($this->helper, $scope, $part, 'String interpolation') as $error) { + $errors[] = $error; + } + } + + return $errors; + } + +} diff --git a/src/Rules/Floats/IntvalNonFiniteFloatRule.php b/src/Rules/Floats/IntvalNonFiniteFloatRule.php new file mode 100644 index 00000000000..3a9ffeae274 --- /dev/null +++ b/src/Rules/Floats/IntvalNonFiniteFloatRule.php @@ -0,0 +1,61 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class IntvalNonFiniteFloatRule implements Rule +{ + + use NonFiniteFloatToIntTrait; + + public function __construct( + private ReflectionProvider $reflectionProvider, + private NonFiniteFloatHelper $helper, + ) + { + } + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->name instanceof Node\Name) { + return []; + } + + $name = $this->reflectionProvider->resolveFunctionName($node->name, $scope); + if ($name === null || strtolower($name) !== 'intval') { + return []; + } + + $args = $node->getArgs(); + if (count($args) === 0 || $args[0]->unpack) { + return []; + } + + return $this->checkToInt($this->helper, $scope, $args[0]->value, 'Function intval()'); + } + +} diff --git a/src/Rules/Floats/JsonEncodeNonFiniteFloatRule.php b/src/Rules/Floats/JsonEncodeNonFiniteFloatRule.php new file mode 100644 index 00000000000..2084ccffbfc --- /dev/null +++ b/src/Rules/Floats/JsonEncodeNonFiniteFloatRule.php @@ -0,0 +1,116 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class JsonEncodeNonFiniteFloatRule implements Rule +{ + + private const ARRAY_DEPTH_LIMIT = 8; + + public function __construct( + private ReflectionProvider $reflectionProvider, + private NonFiniteFloatHelper $helper, + ) + { + } + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->name instanceof Node\Name) { + return []; + } + + $name = $this->reflectionProvider->resolveFunctionName($node->name, $scope); + if ($name === null || strtolower($name) !== 'json_encode') { + return []; + } + + $args = $node->getArgs(); + if (count($args) === 0 || $args[0]->unpack) { + return []; + } + + $valueType = $scope->getType($args[0]->value); + $canBe = $this->canContainNonFinite($valueType, 0); + if (!$this->helper->shouldReport($canBe)) { + return []; + } + + return [ + RuleErrorBuilder::message(sprintf( + 'Parameter #1 $value of function json_encode() %s, which cannot be JSON encoded: %s given.', + $canBe->yes() ? ($this->helper->canBeNonFinite($valueType)->yes() ? 'is INF or NAN' : 'contains INF or NAN') : 'can contain INF or NAN', + $valueType->describe(VerbosityLevel::value()), + ))->identifier('nonFiniteFloat.jsonEncode')->build(), + ]; + } + + /** + * Yes when the value certainly holds INF or NAN somewhere: itself, or in a + * key of an array shape that is not optional, or in every value of an array + * that is not empty. + */ + private function canContainNonFinite(Type $type, int $depth): TrinaryLogic + { + $canBe = $this->helper->canBeNonFinite($type); + if ($canBe->yes() || $depth >= self::ARRAY_DEPTH_LIMIT || !$type->isArray()->yes()) { + return $canBe; + } + + $constantArrays = $type->getConstantArrays(); + if (count($constantArrays) > 0) { + $results = []; + foreach ($constantArrays as $constantArray) { + $result = TrinaryLogic::createNo(); + foreach ($constantArray->getValueTypes() as $i => $valueType) { + $inValue = $this->canContainNonFinite($valueType, $depth + 1); + if ($constantArray->isOptionalKey($i)) { + $inValue = $inValue->and(TrinaryLogic::createMaybe()); + } + $result = $result->or($inValue); + } + $results[] = $result; + } + + return $canBe->or(TrinaryLogic::extremeIdentity(...$results)); + } + + $inValues = $this->canContainNonFinite($type->getIterableValueType(), $depth + 1); + if (!$type->isIterableAtLeastOnce()->yes()) { + $inValues = $inValues->and(TrinaryLogic::createMaybe()); + } + + return $canBe->or($inValues); + } + +} diff --git a/src/Rules/Floats/NanToStringHelperTrait.php b/src/Rules/Floats/NanToStringHelperTrait.php new file mode 100644 index 00000000000..fd15fa84fa0 --- /dev/null +++ b/src/Rules/Floats/NanToStringHelperTrait.php @@ -0,0 +1,40 @@ + + */ + private function checkNanToString(NonFiniteFloatHelper $helper, Scope $scope, Expr $expr, string $where): array + { + if (!$scope->getPhpVersion()->warnsOnNonFiniteFloatConversion()->yes()) { + return []; + } + + $type = $scope->getType($expr); + $canBe = $helper->canBeNan($type); + if (!$helper->shouldReport($canBe)) { + return []; + } + + return [ + RuleErrorBuilder::message(sprintf( + '%s converts %s to string, which emits a warning%s.', + $where, + $type->describe(VerbosityLevel::value()), + $canBe->yes() ? '' : ' when it is NAN', + ))->identifier('nonFiniteFloat.toString')->build(), + ]; + } + +} diff --git a/src/Rules/Floats/NonFiniteFloatHelper.php b/src/Rules/Floats/NonFiniteFloatHelper.php new file mode 100644 index 00000000000..bd7168ab45e --- /dev/null +++ b/src/Rules/Floats/NonFiniteFloatHelper.php @@ -0,0 +1,102 @@ +canBe($type, new ConstantFloatType(NAN)); + } + + public function canBeNonFinite(Type $type): TrinaryLogic + { + return $this->canBe($type, TypeCombinator::union( + new ConstantFloatType(NAN), + new ConstantFloatType(INF), + new ConstantFloatType(-INF), + )); + } + + public function canBeOutOfIntRange(Type $type): TrinaryLogic + { + // (float) PHP_INT_MIN is -2**63 and still an int, 2**63 is not + $intMin = (float) PHP_INT_MIN; + + return $this->canBe($type, TypeCombinator::union( + new ConstantFloatType(NAN), + FloatRangeType::createAllSmallerThan($intMin), + FloatRangeType::createAllGreaterThanOrEqualTo(-$intMin), + )); + } + + public function shouldReport(TrinaryLogic $canBe): bool + { + if ($canBe->yes()) { + return true; + } + + return $canBe->maybe() && $this->checkNonFiniteFloats; + } + + /** + * Yes when every value of $type is one of $offending, Maybe when the float + * part of $type holds one of them. A mixed value is left to the mixed + * checks. + */ + private function canBe(Type $type, Type $offending): TrinaryLogic + { + if ($type instanceof MixedType) { + return TrinaryLogic::createNo(); + } + + $floatPart = TypeCombinator::intersect($type, new FloatType()); + if ($floatPart instanceof NeverType) { + return TrinaryLogic::createNo(); + } + + if (TypeCombinator::intersect($floatPart, $offending) instanceof NeverType) { + return TrinaryLogic::createNo(); + } + + if ($offending->isSuperTypeOf($type)->yes()) { + return TrinaryLogic::createYes(); + } + + return TrinaryLogic::createMaybe(); + } + +} diff --git a/src/Rules/Floats/NonFiniteFloatToIntTrait.php b/src/Rules/Floats/NonFiniteFloatToIntTrait.php new file mode 100644 index 00000000000..f14a8cca517 --- /dev/null +++ b/src/Rules/Floats/NonFiniteFloatToIntTrait.php @@ -0,0 +1,40 @@ + + */ + private function checkToInt(NonFiniteFloatHelper $helper, Scope $scope, Expr $expr, string $where): array + { + if (!$scope->getPhpVersion()->warnsOnNonFiniteFloatConversion()->yes()) { + return []; + } + + $type = $scope->getType($expr); + $canBe = $helper->canBeOutOfIntRange($type); + if (!$helper->shouldReport($canBe)) { + return []; + } + + return [ + RuleErrorBuilder::message(sprintf( + '%s converts %s to int, which emits a warning%s.', + $where, + $type->describe(VerbosityLevel::value()), + $canBe->yes() ? '' : ' when it is NAN, INF or out of the int range', + ))->identifier('nonFiniteFloat.toInt')->build(), + ]; + } + +} diff --git a/src/Rules/Floats/PrintNanRule.php b/src/Rules/Floats/PrintNanRule.php new file mode 100644 index 00000000000..71847321d38 --- /dev/null +++ b/src/Rules/Floats/PrintNanRule.php @@ -0,0 +1,38 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class PrintNanRule implements Rule +{ + + use NanToStringHelperTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return Print_::class; + } + + public function processNode(Node $node, Scope $scope): array + { + return $this->checkNanToString($this->helper, $scope, $node->expr, 'Print'); + } + +} diff --git a/src/Rules/Floats/StringCastNanRule.php b/src/Rules/Floats/StringCastNanRule.php new file mode 100644 index 00000000000..84ecfb53692 --- /dev/null +++ b/src/Rules/Floats/StringCastNanRule.php @@ -0,0 +1,38 @@ + + */ +#[Conditional( + attribute: new RegisteredRule(level: 5), + if: '%featureToggles.nonFiniteFloats%', +)] +final class StringCastNanRule implements Rule +{ + + use NanToStringHelperTrait; + + public function __construct(private NonFiniteFloatHelper $helper) + { + } + + public function getNodeType(): string + { + return Cast\String_::class; + } + + public function processNode(Node $node, Scope $scope): array + { + return $this->checkNanToString($this->helper, $scope, $node->expr, 'Casting to string'); + } + +} diff --git a/tests/PHPStan/Rules/Floats/NonFiniteFloatRulesPhp84Test.php b/tests/PHPStan/Rules/Floats/NonFiniteFloatRulesPhp84Test.php new file mode 100644 index 00000000000..45d6549d25a --- /dev/null +++ b/tests/PHPStan/Rules/Floats/NonFiniteFloatRulesPhp84Test.php @@ -0,0 +1,120 @@ + + */ +class NonFiniteFloatRulesPhp84Test extends RuleTestCase +{ + + private bool $checkNonFiniteFloats = false; + + protected function getRule(): Rule + { + $helper = new NonFiniteFloatHelper($this->checkNonFiniteFloats); + $reflectionProvider = $this->createReflectionProvider(); + + // @phpstan-ignore argument.type + return new CompositeRule([ + new JsonEncodeNonFiniteFloatRule($reflectionProvider, $helper), + new EchoNanRule($helper), + new PrintNanRule($helper), + new ConcatNanRule($helper), + new AssignConcatNanRule($helper), + new InterpolatedStringNanRule($helper), + new StringCastNanRule($helper), + new IntCastNonFiniteFloatRule($helper), + new IntvalNonFiniteFloatRule($reflectionProvider, $helper), + new FormatNonFiniteFloatRule($reflectionProvider, self::getContainer()->getByType(PrintfFormatParser::class), $helper), + ]); + } + + public function testDefinite(): void + { + $this->analyse([__DIR__ . '/data/non-finite-float.php'], self::errors([ + ['Parameter #1 $value of function json_encode() is INF or NAN, which cannot be JSON encoded: NAN given.', 11, false], + ['Echo converts NAN to string, which emits a warning.', 12, true], + ['Casting to int converts INF to int, which emits a warning.', 13, true], + ['Placeholder "%f" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 14, false], + ['Echo converts NAN to string, which emits a warning.', 18, true], + ['Parameter #1 $value of function json_encode() contains INF or NAN, which cannot be JSON encoded: array{a: NAN} given.', 38, false], + ['Print converts NAN to string, which emits a warning.', 50, true], + ['Concatenation converts NAN to string, which emits a warning.', 51, true], + ['String interpolation converts NAN to string, which emits a warning.', 53, true], + ['Casting to string converts NAN to string, which emits a warning.', 54, true], + ['Casting to int converts NAN to int, which emits a warning.', 68, true], + ['Function intval() converts NAN to int, which emits a warning.', 69, true], + ['Parameter #1 $num of function number_format() formats NAN, which prints "nan" or "inf".', 83, false], + ['Placeholder "%.2f" of function sprintf() formats INF, which prints "NaN", "INF" or "-INF".', 85, false], + ['Placeholder "%d" of function sprintf() formats INF, which prints an unspecified number.', 85, false], + ['Placeholder "%e" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 86, false], + ['Placeholder "%s" of function sprintf() formats NAN, which prints "NAN" with a warning.', 86, true], + ])); + } + + public function testCheckNonFiniteFloats(): void + { + $this->checkNonFiniteFloats = true; + $this->analyse([__DIR__ . '/data/non-finite-float.php'], self::errors([ + ['Parameter #1 $value of function json_encode() is INF or NAN, which cannot be JSON encoded: NAN given.', 11, false], + ['Echo converts NAN to string, which emits a warning.', 12, true], + ['Casting to int converts INF to int, which emits a warning.', 13, true], + ['Placeholder "%f" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 14, false], + ['Echo converts float to string, which emits a warning when it is NAN.', 16, true], + ['Echo converts NAN to string, which emits a warning.', 18, true], + ['Parameter #1 $value of function json_encode() can contain INF or NAN, which cannot be JSON encoded: float<0.0, max> given.', 34, false], + ['Parameter #1 $value of function json_encode() can contain INF or NAN, which cannot be JSON encoded: NAN|float<0.0, 1.0> given.', 35, false], + ['Parameter #1 $value of function json_encode() can contain INF or NAN, which cannot be JSON encoded: list given.', 36, false], + ['Parameter #1 $value of function json_encode() contains INF or NAN, which cannot be JSON encoded: array{a: NAN} given.', 38, false], + ['Print converts NAN to string, which emits a warning.', 50, true], + ['Concatenation converts NAN to string, which emits a warning.', 51, true], + ['Concatenation converts float to string, which emits a warning when it is NAN.', 52, true], + ['String interpolation converts NAN to string, which emits a warning.', 53, true], + ['Casting to string converts NAN to string, which emits a warning.', 54, true], + ['Casting to int converts NAN to int, which emits a warning.', 68, true], + ['Function intval() converts NAN to int, which emits a warning.', 69, true], + ['Casting to int converts float<-1.7976931348623157E+308, 1.7976931348623157E+308> to int, which emits a warning when it is NAN, INF or out of the int range.', 71, true], + ['Casting to int converts float to int, which emits a warning when it is NAN, INF or out of the int range.', 72, true], + ['Parameter #1 $num of function number_format() formats NAN, which prints "nan" or "inf".', 83, false], + ['Placeholder "%.2f" of function sprintf() formats INF, which prints "NaN", "INF" or "-INF".', 85, false], + ['Placeholder "%d" of function sprintf() formats INF, which prints an unspecified number.', 85, false], + ['Placeholder "%e" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 86, false], + ['Placeholder "%s" of function sprintf() formats NAN, which prints "NAN" with a warning.', 86, true], + ['Placeholder "%1$f" of function sprintf() formats float, which prints "NaN", "INF" or "-INF" when it is not a finite float.', 87, false], + ['Placeholder "%d" of function printf() formats float<-1.7976931348623157E+308, 1.7976931348623157E+308>, which prints an unspecified number when it is NAN, INF or out of the int range.', 88, false], + ['Placeholder "%F" of function fprintf() formats float, which prints "NaN", "INF" or "-INF" when it is not a finite float.', 89, false], + ])); + } + + public static function getAdditionalConfigFiles(): array + { + return [__DIR__ . '/php84.neon']; + } + + /** + * Conversions to string and to int warn only on PHP 8.5+, so none of + * them is reported for PHP 8.4. + * + * @param list $errors message, line, PHP 8.5+ only + * @return list + */ + private static function errors(array $errors): array + { + $result = []; + foreach ($errors as [$message, $line, $php85Only]) { + if ($php85Only) { + continue; + } + $result[] = [$message, $line]; + } + + return $result; + } + +} diff --git a/tests/PHPStan/Rules/Floats/NonFiniteFloatRulesTest.php b/tests/PHPStan/Rules/Floats/NonFiniteFloatRulesTest.php new file mode 100644 index 00000000000..6705c158860 --- /dev/null +++ b/tests/PHPStan/Rules/Floats/NonFiniteFloatRulesTest.php @@ -0,0 +1,115 @@ + + */ +class NonFiniteFloatRulesTest extends RuleTestCase +{ + + private bool $checkNonFiniteFloats = false; + + protected function getRule(): Rule + { + $helper = new NonFiniteFloatHelper($this->checkNonFiniteFloats); + $reflectionProvider = $this->createReflectionProvider(); + + // @phpstan-ignore argument.type + return new CompositeRule([ + new JsonEncodeNonFiniteFloatRule($reflectionProvider, $helper), + new EchoNanRule($helper), + new PrintNanRule($helper), + new ConcatNanRule($helper), + new AssignConcatNanRule($helper), + new InterpolatedStringNanRule($helper), + new StringCastNanRule($helper), + new IntCastNonFiniteFloatRule($helper), + new IntvalNonFiniteFloatRule($reflectionProvider, $helper), + new FormatNonFiniteFloatRule($reflectionProvider, self::getContainer()->getByType(PrintfFormatParser::class), $helper), + ]); + } + + public function testDefinite(): void + { + $this->analyse([__DIR__ . '/data/non-finite-float.php'], self::errors([ + ['Parameter #1 $value of function json_encode() is INF or NAN, which cannot be JSON encoded: NAN given.', 11, false], + ['Echo converts NAN to string, which emits a warning.', 12, true], + ['Casting to int converts INF to int, which emits a warning.', 13, true], + ['Placeholder "%f" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 14, false], + ['Echo converts NAN to string, which emits a warning.', 18, true], + ['Parameter #1 $value of function json_encode() contains INF or NAN, which cannot be JSON encoded: array{a: NAN} given.', 38, false], + ['Print converts NAN to string, which emits a warning.', 50, true], + ['Concatenation converts NAN to string, which emits a warning.', 51, true], + ['String interpolation converts NAN to string, which emits a warning.', 53, true], + ['Casting to string converts NAN to string, which emits a warning.', 54, true], + ['Casting to int converts NAN to int, which emits a warning.', 68, true], + ['Function intval() converts NAN to int, which emits a warning.', 69, true], + ['Parameter #1 $num of function number_format() formats NAN, which prints "nan" or "inf".', 83, false], + ['Placeholder "%.2f" of function sprintf() formats INF, which prints "NaN", "INF" or "-INF".', 85, false], + ['Placeholder "%d" of function sprintf() formats INF, which prints an unspecified number.', 85, false], + ['Placeholder "%e" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 86, false], + ['Placeholder "%s" of function sprintf() formats NAN, which prints "NAN" with a warning.', 86, true], + ])); + } + + public function testCheckNonFiniteFloats(): void + { + $this->checkNonFiniteFloats = true; + $this->analyse([__DIR__ . '/data/non-finite-float.php'], self::errors([ + ['Parameter #1 $value of function json_encode() is INF or NAN, which cannot be JSON encoded: NAN given.', 11, false], + ['Echo converts NAN to string, which emits a warning.', 12, true], + ['Casting to int converts INF to int, which emits a warning.', 13, true], + ['Placeholder "%f" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 14, false], + ['Echo converts float to string, which emits a warning when it is NAN.', 16, true], + ['Echo converts NAN to string, which emits a warning.', 18, true], + ['Parameter #1 $value of function json_encode() can contain INF or NAN, which cannot be JSON encoded: float<0.0, max> given.', 34, false], + ['Parameter #1 $value of function json_encode() can contain INF or NAN, which cannot be JSON encoded: NAN|float<0.0, 1.0> given.', 35, false], + ['Parameter #1 $value of function json_encode() can contain INF or NAN, which cannot be JSON encoded: list given.', 36, false], + ['Parameter #1 $value of function json_encode() contains INF or NAN, which cannot be JSON encoded: array{a: NAN} given.', 38, false], + ['Print converts NAN to string, which emits a warning.', 50, true], + ['Concatenation converts NAN to string, which emits a warning.', 51, true], + ['Concatenation converts float to string, which emits a warning when it is NAN.', 52, true], + ['String interpolation converts NAN to string, which emits a warning.', 53, true], + ['Casting to string converts NAN to string, which emits a warning.', 54, true], + ['Casting to int converts NAN to int, which emits a warning.', 68, true], + ['Function intval() converts NAN to int, which emits a warning.', 69, true], + ['Casting to int converts float<-1.7976931348623157E+308, 1.7976931348623157E+308> to int, which emits a warning when it is NAN, INF or out of the int range.', 71, true], + ['Casting to int converts float to int, which emits a warning when it is NAN, INF or out of the int range.', 72, true], + ['Parameter #1 $num of function number_format() formats NAN, which prints "nan" or "inf".', 83, false], + ['Placeholder "%.2f" of function sprintf() formats INF, which prints "NaN", "INF" or "-INF".', 85, false], + ['Placeholder "%d" of function sprintf() formats INF, which prints an unspecified number.', 85, false], + ['Placeholder "%e" of function sprintf() formats NAN, which prints "NaN", "INF" or "-INF".', 86, false], + ['Placeholder "%s" of function sprintf() formats NAN, which prints "NAN" with a warning.', 86, true], + ['Placeholder "%1$f" of function sprintf() formats float, which prints "NaN", "INF" or "-INF" when it is not a finite float.', 87, false], + ['Placeholder "%d" of function printf() formats float<-1.7976931348623157E+308, 1.7976931348623157E+308>, which prints an unspecified number when it is NAN, INF or out of the int range.', 88, false], + ['Placeholder "%F" of function fprintf() formats float, which prints "NaN", "INF" or "-INF" when it is not a finite float.', 89, false], + ])); + } + + /** + * Conversions to string and to int warn only on PHP 8.5+. + * + * @param list $errors message, line, PHP 8.5+ only + * @return list + */ + private static function errors(array $errors): array + { + $result = []; + foreach ($errors as [$message, $line, $php85Only]) { + if ($php85Only && PHP_VERSION_ID < 80500) { + continue; + } + $result[] = [$message, $line]; + } + + return $result; + } + +} diff --git a/tests/PHPStan/Rules/Floats/data/non-finite-float.php b/tests/PHPStan/Rules/Floats/data/non-finite-float.php new file mode 100644 index 00000000000..c8289ed8b41 --- /dev/null +++ b/tests/PHPStan/Rules/Floats/data/non-finite-float.php @@ -0,0 +1,90 @@ + $nonNegative + * @param NAN|float<0, 1> $nanOrUnit + * @param list $floats + * @param list $finiteFloats + * @param array{a: NAN} $nanShape + * @param int|string $noFloat + */ +function jsonEncode(float $finite, float $nonNegative, float $nanOrUnit, array $floats, array $finiteFloats, array $nanShape, $noFloat, $mixed): void +{ + json_encode($finite); + json_encode($nonNegative); + json_encode($nanOrUnit); + json_encode($floats); + json_encode($finiteFloats); + json_encode($nanShape); + json_encode($noFloat); + json_encode($mixed); +} + +/** + * @param NAN $nan + * @param INF $inf + * @param finite-float $finite + */ +function toString(float $nan, float $inf, float $finite, float $plain): void +{ + print $nan; + $s = 'x' . $nan; + $s .= $plain; + $s = "value: {$nan}"; + $s = (string) $nan; + echo $inf, $finite; + if (is_finite($plain)) { + echo $plain; + } +} + +/** + * @param NAN $nan + * @param finite-float $finite + * @param float<-1000.0, 1000.0> $small + */ +function toInt(float $nan, float $finite, float $small, float $plain): void +{ + $i = (int) $nan; + $i = intval($nan); + $i = (int) $small; + $i = (int) $finite; + $i = (int) $plain; + $i = intval('12', 8); +} + +/** + * @param NAN $nan + * @param INF $inf + * @param finite-float $finite + */ +function format(float $nan, float $inf, float $finite, float $plain): void +{ + echo number_format($nan); + echo number_format($finite); + echo sprintf('%.2f %d %s', $inf, $inf, $inf); + echo sprintf('%e %s', $nan, $nan); + echo sprintf('%1$f %1$f', $plain); + printf('%d', $finite); + fprintf(STDOUT, '%F', $plain); +} diff --git a/tests/PHPStan/Rules/Floats/php84.neon b/tests/PHPStan/Rules/Floats/php84.neon new file mode 100644 index 00000000000..39467bfece6 --- /dev/null +++ b/tests/PHPStan/Rules/Floats/php84.neon @@ -0,0 +1,2 @@ +parameters: + phpVersion: 80400