Skip to content
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 @@ -24,6 +24,7 @@ parameters:
newOnNonObject: true
unnecessaryNullCoalesce: true
finiteTypesInHaystack: true
nonFiniteFloats: true
switchConditionAlwaysFalse: true
checkImportedClassNameCase: true
sortWithoutEffect: true
Expand Down
2 changes: 2 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ parameters:
newOnNonObject: false
unnecessaryNullCoalesce: false
finiteTypesInHaystack: false
nonFiniteFloats: false
switchConditionAlwaysFalse: false
checkImportedClassNameCase: false
sortWithoutEffect: false
Expand All @@ -75,6 +76,7 @@ parameters:
checkClassCaseSensitivity: false
checkExplicitMixed: false
checkImplicitMixed: false
checkNonFiniteFloats: false
checkFunctionArgumentTypes: false
checkFunctionNameCase: false
checkInternalClassCaseSensitivity: false
Expand Down
2 changes: 2 additions & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ parametersSchema:
newOnNonObject: bool()
unnecessaryNullCoalesce: bool()
finiteTypesInHaystack: bool()
nonFiniteFloats: bool()
switchConditionAlwaysFalse: bool()
checkImportedClassNameCase: bool()
sortWithoutEffect: bool()
Expand All @@ -72,6 +73,7 @@ parametersSchema:
checkClassCaseSensitivity: bool()
checkExplicitMixed: bool()
checkImplicitMixed: bool()
checkNonFiniteFloats: bool()
checkFunctionArgumentTypes: bool()
checkFunctionNameCase: bool()
checkInternalClassCaseSensitivity: bool()
Expand Down
5 changes: 5 additions & 0 deletions src/Php/PhpVersion.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions src/Php/PhpVersions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions src/Rules/Floats/AssignConcatNanRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Floats;

use PhpParser\Node;
use PhpParser\Node\Expr\AssignOp\Concat;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\Conditional;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\Rule;

/**
* @implements Rule<Concat>
*/
#[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');
}

}
45 changes: 45 additions & 0 deletions src/Rules/Floats/ConcatNanRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Floats;

use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\Conditional;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\Rule;

/**
* @implements Rule<Concat>
*/
#[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;
}

}
45 changes: 45 additions & 0 deletions src/Rules/Floats/EchoNanRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Floats;

use PhpParser\Node;
use PhpParser\Node\Stmt\Echo_;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\Conditional;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\Rule;

/**
* @implements Rule<Echo_>
*/
#[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;
}

}
160 changes: 160 additions & 0 deletions src/Rules/Floats/FormatNonFiniteFloatRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Floats;

use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\Conditional;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Php\PrintfFormatParser;
use PHPStan\Type\Type;
use PHPStan\Type\VerbosityLevel;
use function array_key_exists;
use function array_values;
use function count;
use function in_array;
use function sprintf;
use function strtolower;

/**
* Formatting a float that is not finite prints "NaN", "INF", "-INF" or
* "inf" with the float placeholders and number_format(), and an unspecified
* number with the int placeholders.
*
* @implements Rule<FuncCall>
*/
#[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()) {

Check warning on line 128 in src/Rules/Floats/FormatNonFiniteFloatRule.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ $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()) { + } elseif ($use['specifier'] === 's' && !$scope->getPhpVersion()->warnsOnNonFiniteFloatConversion()->no()) { $error = $this->check($this->helper->canBeNan($type), $type, $label, '"NAN" with a warning', 'it is NAN'); } else { continue;
$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();
}

}
41 changes: 41 additions & 0 deletions src/Rules/Floats/IntCastNonFiniteFloatRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Floats;

use PhpParser\Node;
use PhpParser\Node\Expr\Cast;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\Conditional;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\Rule;

/**
* (int) of NAN, INF or a float out of the int range gives an unspecified
* int, and PHP 8.5 warns that the float is not representable.
*
* @implements Rule<Cast\Int_>
*/
#[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');
}

}
Loading
Loading