From ad5e139dd364fe71ca4f0d16178c39662fc363d3 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 22:23:09 +0800 Subject: [PATCH] Add support for finite-float and bounded float ranges in type validation and evaluation --- .../Elimination/EliminationSafetyPolicy.php | 2 + .../Elimination/Evaluator/ScalarEvaluator.php | 73 +++- .../Ast/Elimination/StaticTypeEvaluator.php | 2 + src/Internal/Checker/InlineChecker.php | 3 + src/Internal/Diagnostic/TypeFormatter.php | 4 + src/Internal/Docblock/DocblockParser.php | 8 +- src/Internal/Generics/TemplateManager.php | 26 ++ src/Internal/Resolver/SpecialTypeResolver.php | 1 + src/Internal/Validator/GenericValidator.php | 102 +++++ .../Validator/IdentifierValidator.php | 1 + .../Validator/GenericValidatorTest.php | 62 ++++ .../Scalars/FloatRangeAndFiniteFloatTest.php | 347 ++++++++++++++++++ 12 files changed, 629 insertions(+), 2 deletions(-) create mode 100644 tests/TypeChecking/Scalars/FloatRangeAndFiniteFloatTest.php diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index 385c1a49..42a4117a 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -38,6 +38,8 @@ final class EliminationSafetyPolicy private const PERMISSIBLE_NON_OBJECT_GENERICS = [ 'int' => true, 'integer' => true, + 'float' => true, + 'double' => true, 'int-mask' => true, 'int-mask-of' => true, 'value-of' => true, diff --git a/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php index e1c3227e..bb65dbe3 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php @@ -177,6 +177,10 @@ private static function satisfiesInteger(int $value, TypeNode $typeNode): bool return self::satisfiesIntRange($value, $typeNode); } + if ($base === 'float' || $base === 'double') { + return self::satisfiesFloatRange($value, $typeNode); + } + if ($base === 'int-mask' || $base === 'int-mask-of') { return self::satisfiesIntMask($value, $typeNode); } @@ -185,7 +189,7 @@ private static function satisfiesInteger(int $value, TypeNode $typeNode): bool if ($typeNode instanceof IdentifierTypeNode) { return match (strtolower($typeNode->name)) { 'int', 'integer', 'scalar', 'numeric', 'number', 'mixed' => true, - 'float', 'double' => true, + 'float', 'double', 'finite-float' => true, 'positive-int', 'positive-float' => $value > 0, 'negative-int', 'negative-float' => $value < 0, 'non-positive-int', 'non-positive-float' => $value <= 0, @@ -279,9 +283,17 @@ private static function satisfiesFloat(float $value, TypeNode $typeNode): bool && abs($value - (float) $typeNode->constExpr->value) < ArithmeticEvaluator::FLOAT_EPSILON; } + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower((string) $typeNode->type); + if ($base === 'float' || $base === 'double') { + return self::satisfiesFloatRange($value, $typeNode); + } + } + if ($typeNode instanceof IdentifierTypeNode) { return match (strtolower($typeNode->name)) { 'float', 'double', 'scalar', 'numeric', 'number', 'mixed' => true, + 'finite-float' => is_finite($value), 'positive-float' => $value > 0.0, 'negative-float' => $value < 0.0, 'non-positive-float' => $value <= 0.0, @@ -296,6 +308,65 @@ private static function satisfiesFloat(float $value, TypeNode $typeNode): bool return false; } + /** + * Verifies if an int or float falls within static `float` bounds. + */ + private static function satisfiesFloatRange(int|float $value, GenericTypeNode $node): bool + { + $floatValue = (float) $value; + if (is_nan($floatValue)) { + return false; + } + + $min = self::resolveFloatRangeBound($node->genericTypes[0] ?? null); + $max = self::resolveFloatRangeBound($node->genericTypes[1] ?? null); + + if ($min !== null && $floatValue < (float) $min) { + return false; + } + + if ($max !== null && $floatValue > (float) $max) { + return false; + } + + return true; + } + + /** + * Resolves numeric bounds from float range AST nodes, ignoring 'min', 'max', and '*'. + */ + private static function resolveFloatRangeBound(?TypeNode $boundNode): int|float|null + { + if ($boundNode === null) { + return null; + } + + if ($boundNode instanceof ConstTypeNode) { + if ($boundNode->constExpr instanceof ConstExprIntegerNode) { + return (int) $boundNode->constExpr->value; + } + + if ($boundNode->constExpr instanceof ConstExprFloatNode) { + return (float) $boundNode->constExpr->value; + } + } + + if ($boundNode instanceof IdentifierTypeNode) { + $name = strtolower($boundNode->name); + if ($name === 'min' || $name === 'max' || $name === '*') { + return null; + } + + if (is_numeric($boundNode->name)) { + return str_contains($boundNode->name, '.') || stripos($boundNode->name, 'e') !== false + ? (float) $boundNode->name + : (int) $boundNode->name; + } + } + + return null; + } + /** * Evaluates a string against string literals and string refinements (e.g. non-empty, casing). */ diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index 781fcb50..5a6d96cd 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -39,6 +39,8 @@ final class StaticTypeEvaluator private const PERMISSIBLE_GENERIC_CONTAINERS = [ 'int' => true, 'integer' => true, + 'float' => true, + 'double' => true, 'int-mask' => true, 'int-mask-of' => true, 'value-of' => true, diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index f0b159f6..10669bfe 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -159,6 +159,7 @@ public static function reset(): void 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'non-empty-string' => true, 'numeric-string' => true, 'lowercase-string' => true, @@ -185,6 +186,8 @@ public static function reset(): void private const SCALAR_GENERIC_TYPES = [ 'int' => true, 'integer' => true, + 'float' => true, + 'double' => true, 'int-mask' => true, 'int-mask-of' => true, 'class-string' => true, diff --git a/src/Internal/Diagnostic/TypeFormatter.php b/src/Internal/Diagnostic/TypeFormatter.php index c111f8ba..a5b0311c 100644 --- a/src/Internal/Diagnostic/TypeFormatter.php +++ b/src/Internal/Diagnostic/TypeFormatter.php @@ -30,6 +30,10 @@ public static function formatGivenValue(mixed $value, bool $isSensitive = false) } if (\is_float($value)) { + if (is_nan($value)) { + return 'float (NAN)'; + } + return "float ($value)"; } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index 84c365e7..cc9b4688 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -142,6 +142,7 @@ final class DocblockParser 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'double' => true, ], 'double' => [ @@ -150,6 +151,7 @@ final class DocblockParser 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'double' => true, ], 'bool' => [ @@ -366,7 +368,7 @@ private static function computeContractFlags( if (! ($inner instanceof IdentifierTypeNode)) { if ($inner instanceof GenericTypeNode) { $base = strtolower((string) $inner->type); - if (! \in_array($base, ['class-string', 'int', 'integer', 'int-mask', 'int-mask-of', 'key-of', 'value-of'], true)) { + if (! \in_array($base, ['class-string', 'int', 'integer', 'float', 'double', 'int-mask', 'int-mask-of', 'key-of', 'value-of'], true)) { $paramsNeedPreInference = true; } } else { @@ -1854,6 +1856,10 @@ private static function isRefinementOfBuiltin(string $refinement, string $builti return true; } + if (($builtin === 'float' || $builtin === 'double') && (str_starts_with($refinement, 'float<') || str_starts_with($refinement, 'double<'))) { + return true; + } + if ($builtin === 'string' && str_starts_with($refinement, 'class-string<')) { return true; } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 64cf1c51..bf9cfbc9 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -249,6 +249,7 @@ final class TemplateManager 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, ], 'double' => [ 'float' => true, @@ -258,6 +259,7 @@ final class TemplateManager 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, ], 'bool' => [ 'bool' => true, @@ -315,6 +317,7 @@ final class TemplateManager 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'numeric-string' => true, ], 'number' => [ @@ -335,6 +338,7 @@ final class TemplateManager 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'numeric-string' => true, ], 'scalar' => [ @@ -357,6 +361,7 @@ final class TemplateManager 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'non-empty-string' => true, 'numeric-string' => true, 'lowercase-string' => true, @@ -419,6 +424,19 @@ final class TemplateManager 'scalar' => true, ]; + /** + * O(1) lookup set for valid supertypes of float ranges. + * + * @var array + */ + private const FLOAT_SUPERTYPES = [ + 'float' => true, + 'double' => true, + 'numeric' => true, + 'number' => true, + 'scalar' => true, + ]; + /** * O(1) lookup set for valid supertypes of string literals and class-string. * @@ -3690,6 +3708,10 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return true; } + if (($baseExisting === 'float' || $baseExisting === 'double') && isset(self::FLOAT_SUPERTYPES[$lowerExpected])) { + return true; + } + if ($baseExisting === 'class-string' && isset(self::STRING_SUPERTYPES[$lowerExpected])) { return true; } @@ -3876,6 +3898,10 @@ private static function isScalarSubtype(string $sub, string $super): bool return true; } + if ((str_starts_with($sub, 'float<') || str_starts_with($sub, 'double<')) && isset(self::FLOAT_SUPERTYPES[$super])) { + return true; + } + if ((str_starts_with($sub, 'class-string<') || ($sub !== '' && ($sub[0] === "'" || $sub[0] === '"'))) && isset(self::STRING_SUPERTYPES[$super])) { return true; } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 5ab905d8..254a5253 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -80,6 +80,7 @@ final class SpecialTypeResolver 'non-positive-float' => true, 'non-negative-float' => true, 'non-zero-float' => true, + 'finite-float' => true, 'class-string' => true, 'interface-string' => true, 'trait-string' => true, diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 971dd997..4f202854 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -4,6 +4,7 @@ namespace TypePHP\Internal\Validator; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; @@ -42,10 +43,13 @@ final class GenericValidator implements TypeValidatorInterface private const KIND_INT_MASK = 9; private const KIND_INT_MASK_OF = 10; private const KIND_OBJECT_GENERIC = 11; + private const KIND_FLOAT_RANGE = 12; private const BUILTIN_GENERICS = [ 'int' => true, 'integer' => true, + 'float' => true, + 'double' => true, 'class-string' => true, 'list' => true, 'non-empty-list' => true, @@ -209,6 +213,36 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return null; } + if ($kind === self::KIND_FLOAT_RANGE) { + if (! \is_float($value) && ! \is_int($value)) { + return ErrorFactory::createError($context . ' must be of type float, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + $floatValue = (float) $value; + if (is_nan($floatValue)) { + return ErrorFactory::createError($context . ' must be a non-NaN float matching ' . $genericNode . ', float (NAN) given'); + } + + /** @var array{0: int|float|null, 1: int|float|null} $bounds */ + $bounds = $compiled[1]; + [$minVal, $maxVal] = $bounds; + $redact = $isSensitive || Config::isRedactValuesEnabled(); + + if ($minVal !== null && $floatValue < (float) $minVal) { + $valDisplay = $redact ? 'float given' : "$value given"; + + return ErrorFactory::createError($context . " must be >= $minVal, $valDisplay"); + } + + if ($maxVal !== null && $floatValue > (float) $maxVal) { + $valDisplay = $redact ? 'float given' : "$value given"; + + return ErrorFactory::createError($context . " must be <= $maxVal, $valDisplay"); + } + + return null; + } + if ($kind === self::KIND_CLASS_STRING) { return $this->validateClassString($value, $genericNode, $context, $isSensitive); } @@ -271,6 +305,13 @@ private function compileGeneric(GenericTypeNode $node): array isset($node->genericTypes[1]) ? $this->resolveIntBound($node->genericTypes[1]) : null, ], ], + 'float', 'double' => [ + self::KIND_FLOAT_RANGE, + [ + isset($node->genericTypes[0]) ? $this->resolveFloatBound($node->genericTypes[0]) : null, + isset($node->genericTypes[1]) ? $this->resolveFloatBound($node->genericTypes[1]) : null, + ], + ], 'class-string' => [self::KIND_CLASS_STRING, $node->genericTypes[0] ?? null], 'key-of' => [self::KIND_KEY_OF, null], 'value-of' => [self::KIND_VALUE_OF, null], @@ -1140,6 +1181,67 @@ private function resolveIntBound(PhpDocNode $node): ?int return null; } + private function resolveFloatBound(PhpDocNode $node): int|float|null + { + if ($node instanceof ConstExprIntegerNode) { + return (int) $node->value; + } + + if ($node instanceof ConstExprFloatNode) { + return (float) $node->value; + } + + if ($node instanceof ConstTypeNode) { + $expr = $node->constExpr; + if ($expr instanceof ConstExprIntegerNode) { + return (int) $expr->value; + } + if ($expr instanceof ConstExprFloatNode) { + return (float) $expr->value; + } + if ($expr instanceof ConstFetchNode) { + $val = $this->resolveConstantValue($expr->className, $expr->name); + if (\is_int($val) || \is_float($val)) { + return $val; + } + } + } + + if ($node instanceof ConstFetchNode) { + $val = $this->resolveConstantValue($node->className, $node->name); + if (\is_int($val) || \is_float($val)) { + return $val; + } + } + + if ($node instanceof IdentifierTypeNode) { + $name = $node->name; + $lower = strtolower($name); + if ($lower === 'min' || $lower === 'max' || $lower === '*') { + return null; + } + + if (is_numeric($name)) { + return str_contains($name, '.') || stripos($name, 'e') !== false ? (float) $name : (int) $name; + } + + $target = $this->extractConstantTarget($node); + if ($target !== null) { + $val = $this->resolveConstantValue($target[0], $target[1]); + if (\is_int($val) || \is_float($val)) { + return $val; + } + } + } + + $str = (string) $node; + if (is_numeric($str)) { + return str_contains($str, '.') || stripos($str, 'e') !== false ? (float) $str : (int) $str; + } + + return null; + } + private function validateClassString(mixed $value, GenericTypeNode $node, string $context, bool $isSensitive = false): ?ErrorMessage { $targetClassNode = $node->genericTypes[0] ?? null; diff --git a/src/Internal/Validator/IdentifierValidator.php b/src/Internal/Validator/IdentifierValidator.php index 9d7bc0b6..822f132e 100644 --- a/src/Internal/Validator/IdentifierValidator.php +++ b/src/Internal/Validator/IdentifierValidator.php @@ -86,6 +86,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali 'non-positive-float' => (\is_float($value) || \is_int($value)) && $value <= 0, 'non-negative-float' => (\is_float($value) || \is_int($value)) && $value >= 0, 'non-zero-float' => (\is_float($value) || \is_int($value)) && $value !== 0 && $value !== 0.0, + 'finite-float' => (\is_float($value) || \is_int($value)) && is_finite((float) $value), 'class-string' => \is_string($value) && ClassNameValidator::isValidClassString($value), 'interface-string' => \is_string($value) && interface_exists($value), 'trait-string' => \is_string($value) && trait_exists($value), diff --git a/tests/Internal/Validator/GenericValidatorTest.php b/tests/Internal/Validator/GenericValidatorTest.php index e06a78c4..77bf2122 100644 --- a/tests/Internal/Validator/GenericValidatorTest.php +++ b/tests/Internal/Validator/GenericValidatorTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; @@ -38,6 +39,8 @@ class GenericConstFlagsFixture public const FLAG_B = 2; public const FLAGS_ARRAY = [1, 2, 4]; public const SCALAR_CONST = 'not_an_array'; + public const MIN_RATIO = 0.0; + public const MAX_RATIO = 1.5; } describe('GenericValidator Unit Tests', function () { @@ -275,6 +278,65 @@ class GenericConstFlagsFixture ; }); + test('validates float ranges with int/float/min/max/constant bounds and rejects NAN and non-numeric inputs', function () { + $range = new GenericTypeNode(new IdentifierTypeNode('float'), [ + new ConstExprIntegerNode('0'), + new ConstExprFloatNode('1.5'), + ]); + + expect($this->validator->validate(0, $range, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(0.0, $range, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(1, $range, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(1.5, $range, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(-0.001, $range, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(1.501, $range, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(INF, $range, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(-INF, $range, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(NAN, $range, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate('0.5', $range, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ; + + $minRange = new GenericTypeNode(new IdentifierTypeNode('float'), [ + new IdentifierTypeNode('min'), + new ConstExprFloatNode('10.5'), + ]); + expect($this->validator->validate(-INF, $minRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(-500.5, $minRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(10.5, $minRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(10.6, $minRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(NAN, $minRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ; + + $maxRange = new GenericTypeNode(new IdentifierTypeNode('float'), [ + new ConstExprFloatNode('0.5'), + new IdentifierTypeNode('max'), + ]); + expect($this->validator->validate(INF, $maxRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(0.5, $maxRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(0.49, $maxRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(-INF, $maxRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ->and($this->validator->validate(NAN, $maxRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ; + + $fullMinMaxRange = new GenericTypeNode(new IdentifierTypeNode('float'), [ + new IdentifierTypeNode('min'), + new IdentifierTypeNode('max'), + ]); + expect($this->validator->validate(INF, $fullMinMaxRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(-INF, $fullMinMaxRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(0.0, $fullMinMaxRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(NAN, $fullMinMaxRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ; + + $constRange = new GenericTypeNode(new IdentifierTypeNode('double'), [ + new ConstTypeNode(new ConstFetchNode(GenericConstFlagsFixture::class, 'MIN_RATIO')), + new ConstTypeNode(new ConstFetchNode(GenericConstFlagsFixture::class, 'MAX_RATIO')), + ]); + expect($this->validator->validate(0.75, $constRange, 'val', $this->registry))->toBeNull() + ->and($this->validator->validate(2.0, $constRange, 'val', $this->registry))->toBeInstanceOf(ErrorMessage::class) + ; + }); + test('validates class-string edge cases including non-string, object/mixed bounds, and intersection failures', function () { $bareClassString = new GenericTypeNode(new IdentifierTypeNode('class-string'), []); expect($this->validator->validate(stdClass::class, $bareClassString, 'cls', $this->registry))->toBeNull() diff --git a/tests/TypeChecking/Scalars/FloatRangeAndFiniteFloatTest.php b/tests/TypeChecking/Scalars/FloatRangeAndFiniteFloatTest.php new file mode 100644 index 00000000..9ce18e96 --- /dev/null +++ b/tests/TypeChecking/Scalars/FloatRangeAndFiniteFloatTest.php @@ -0,0 +1,347 @@ + $ratio + * + * @return float<0, 1.5> + */ +function testBoundedFloatRangeContract(mixed $ratio): float +{ + return $ratio; +} + +/** + * @param float $val + */ +function testMinToMaxFloatRangeParam(mixed $val): void +{ +} + +/** + * @param float<0.5, max> $val + */ +function testPositiveBoundToMaxFloatRangeParam(mixed $val): void +{ +} + +/** + * @param float $val + */ +function testFullMinMaxFloatRangeParam(mixed $val): void +{ +} + +/** + * @param float<-1.5, 1.5> $val + */ +function testNegativeFloatRangeParam(mixed $val): void +{ +} + +function testInlineVarFloatRange(mixed $val): mixed +{ + /** @var float<0, 1.5> $x */ + $x = $val; + + return $x; +} + +function testInlineVarFiniteFloat(mixed $val): mixed +{ + /** @var finite-float $x */ + $x = $val; + + return $x; +} + +/** + * @template T + */ +final class FloatRefinementBox +{ + /** + * @var T|null + */ + public mixed $value = null; + + /** + * @param T $value + */ + public function set(mixed $value): void + { + $this->value = $value; + } +} + +/** + * @template-covariant T + */ +final class FloatRefinementProducer +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } +} + +final class FloatRefinementPromotedHolder +{ + /** + * @param float<0, 1.5> $ratio + * @param finite-float $finite + */ + public function __construct( + public float $ratio, + public float $finite, + ) { + } +} + +/** + * @param FloatRefinementProducer $producer + */ +function testAcceptFloatProducer(FloatRefinementProducer $producer): void +{ +} + +/** + * @param FloatRefinementProducer $producer + */ +function testAcceptNumericProducer(FloatRefinementProducer $producer): void +{ +} + +/** + * @param FloatRefinementProducer $producer + */ +function testAcceptScalarProducer(FloatRefinementProducer $producer): void +{ +} + +function parseFloatTestType(string $typeString): TypeNode +{ + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + + return $typeParser->parse($tokens); +} + +describe('PHPStan 2.3.6 Float Range & finite-float Refinements', function () { + describe('finite-float validation', function () { + test('accepts finite floats and integers while rejecting INF, -INF, NAN, and non-numeric values', function () { + expect(testFiniteFloatContract(0.0))->toBe(0.0); + expect(testFiniteFloatContract(0))->toBe(0.0); + expect(testFiniteFloatContract(-42.5))->toBe(-42.5); + expect(testFiniteFloatContract(1.5e10))->toBe(1.5e10); + + expect(fn () => testFiniteFloatContract(INF)) + ->toThrow(TypeError::class, 'Argument $value must be of type finite-float') + ; + expect(fn () => testFiniteFloatContract(-INF)) + ->toThrow(TypeError::class, 'Argument $value must be of type finite-float') + ; + expect(fn () => testFiniteFloatContract(NAN)) + ->toThrow(TypeError::class, 'Argument $value must be of type finite-float') + ; + expect(fn () => testFiniteFloatContract('1.5')) + ->toThrow(TypeError::class, 'Argument $value must be of type finite-float') + ; + }); + }); + + describe('float validation', function () { + test('enforces inclusive int and float bounds and rejects out-of-range, INF, -INF, and NAN', function () { + expect(testBoundedFloatRangeContract(0))->toBe(0.0); + expect(testBoundedFloatRangeContract(0.0))->toBe(0.0); + expect(testBoundedFloatRangeContract(1))->toBe(1.0); + expect(testBoundedFloatRangeContract(1.5))->toBe(1.5); + + expect(fn () => testBoundedFloatRangeContract(-0.01)) + ->toThrow(TypeError::class, 'Argument $ratio must be >= 0') + ; + expect(fn () => testBoundedFloatRangeContract(1.51)) + ->toThrow(TypeError::class, 'Argument $ratio must be <= 1.5') + ; + expect(fn () => testBoundedFloatRangeContract(INF)) + ->toThrow(TypeError::class, 'Argument $ratio must be <= 1.5') + ; + expect(fn () => testBoundedFloatRangeContract(-INF)) + ->toThrow(TypeError::class, 'Argument $ratio must be >= 0') + ; + expect(fn () => testBoundedFloatRangeContract(NAN)) + ->toThrow(TypeError::class, 'NAN') + ; + }); + + test('handles one-sided min/max, negative bounds, and float excluding only NAN', function () { + testMinToMaxFloatRangeParam(-INF); + testMinToMaxFloatRangeParam(-999.9); + testMinToMaxFloatRangeParam(10.5); + expect(fn () => testMinToMaxFloatRangeParam(10.6))->toThrow(TypeError::class, 'must be <= 10.5'); + expect(fn () => testMinToMaxFloatRangeParam(NAN))->toThrow(TypeError::class, 'NAN'); + + testPositiveBoundToMaxFloatRangeParam(0.5); + testPositiveBoundToMaxFloatRangeParam(INF); + expect(fn () => testPositiveBoundToMaxFloatRangeParam(0.49))->toThrow(TypeError::class, 'must be >= 0.5'); + expect(fn () => testPositiveBoundToMaxFloatRangeParam(-INF))->toThrow(TypeError::class, 'must be >= 0.5'); + expect(fn () => testPositiveBoundToMaxFloatRangeParam(NAN))->toThrow(TypeError::class, 'NAN'); + + testFullMinMaxFloatRangeParam(-INF); + testFullMinMaxFloatRangeParam(INF); + testFullMinMaxFloatRangeParam(0.0); + expect(fn () => testFullMinMaxFloatRangeParam(NAN))->toThrow(TypeError::class, 'NAN'); + + testNegativeFloatRangeParam(-1.5); + testNegativeFloatRangeParam(0); + testNegativeFloatRangeParam(1.5); + expect(fn () => testNegativeFloatRangeParam(-1.51))->toThrow(TypeError::class, 'must be >= -1.5'); + }); + + test('validates promoted constructor properties with float<0, 1.5> and finite-float', function () { + $holder = new FloatRefinementPromotedHolder(1.5, 42.0); + expect($holder->ratio)->toBe(1.5) + ->and($holder->finite)->toBe(42.0) + ; + + expect(fn () => new FloatRefinementPromotedHolder(2.0, 1.0)) + ->toThrow(TypeError::class, 'must be <= 1.5') + ; + expect(fn () => new FloatRefinementPromotedHolder(1.0, INF)) + ->toThrow(TypeError::class, 'finite-float') + ; + }); + }); + + describe('Inline Config Routing & Built-in Keyword Recognition', function () { + $originalInlineVars = null; + + beforeEach(function () use (&$originalInlineVars) { + $originalInlineVars = TypePHP::getConfig()['inline_vars']; + }); + + afterEach(function () use (&$originalInlineVars) { + TypePHP::setConfig(['inline_vars' => $originalInlineVars]); + }); + + test('recognizes finite-float as built-in keyword', function () { + expect(SpecialTypeResolver::isBuiltInTypeKeyword('finite-float'))->toBeTrue(); + }); + + test('routes @var float<0, 1.5> and @var finite-float exclusively through inline_vars.scalars', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'objects' => false, + 'generics' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(testInlineVarFloatRange(0.5))->toBe(0.5); + expect(testInlineVarFiniteFloat(3.14))->toBe(3.14); + + expect(fn () => testInlineVarFloatRange(2.0)) + ->toThrow(TypeError::class, 'Variable $x must be <= 1.5') + ; + expect(fn () => testInlineVarFiniteFloat(INF)) + ->toThrow(TypeError::class, 'Variable $x must be of type finite-float') + ; + + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => false, + 'objects' => true, + 'generics' => true, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(testInlineVarFloatRange(2.0))->toBe(2.0); + expect(testInlineVarFiniteFloat(INF))->toBe(INF); + }); + }); + + describe('Compile-Time Elimination & Generic Variance', function () { + test('EliminationSafetyPolicy and StaticTypeEvaluator handle finite-float and float soundly', function () { + $fn = new Function_('dummy'); + $finiteFloat = parseFloatTestType('finite-float'); + $boundedFloat = parseFloatTestType('float<0, 1.5>'); + $minMaxFloat = parseFloatTestType('float'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, $finiteFloat))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, $boundedFloat))->toBeTrue(); + + expect(StaticTypeEvaluator::satisfies(new DNumber(0.5), $boundedFloat))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new LNumber(1), $boundedFloat))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new Plus(new DNumber(0.1), new DNumber(0.2)), $boundedFloat))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new DNumber(2.0), $boundedFloat))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies(new ConstFetch(new Name('NAN')), $boundedFloat))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies(new ConstFetch(new Name('NAN')), $minMaxFloat))->toBeFalse(); + + expect(StaticTypeEvaluator::satisfies(new DNumber(42.5), $finiteFloat))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new LNumber(10), $finiteFloat))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new ConstFetch(new Name('INF')), $finiteFloat))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies(new ConstFetch(new Name('NAN')), $finiteFloat))->toBeFalse(); + }); + + test('supports generic boxes and covariant variance for finite-float and float<0, 1.5>', function () { + /** @var FloatRefinementBox $finiteBox */ + $finiteBox = new FloatRefinementBox(); + $finiteBox->set(12.5); + expect($finiteBox->value)->toBe(12.5); + expect(fn () => $finiteBox->set(INF))->toThrow(TypeError::class, 'finite-float'); + + /** @var FloatRefinementBox> $rangeBox */ + $rangeBox = new FloatRefinementBox(); + $rangeBox->set(1.5); + expect($rangeBox->value)->toBe(1.5); + expect(fn () => $rangeBox->set(2.0))->toThrow(TypeError::class, 'must be <= 1.5'); + expect(fn () => $rangeBox->set(NAN))->toThrow(TypeError::class, 'NAN'); + + /** @var FloatRefinementProducer $finiteProducer */ + $finiteProducer = new FloatRefinementProducer(1.25); + testAcceptFloatProducer($finiteProducer); + testAcceptNumericProducer($finiteProducer); + testAcceptScalarProducer($finiteProducer); + + /** @var FloatRefinementProducer> $rangeProducer */ + $rangeProducer = new FloatRefinementProducer(1.25); + testAcceptFloatProducer($rangeProducer); + testAcceptNumericProducer($rangeProducer); + testAcceptScalarProducer($rangeProducer); + }); + }); +});