From 89999fd55441c19e5f8a9ceb24c9f8074589ee74 Mon Sep 17 00:00:00 2001 From: Matthew Brown Date: Sun, 27 Jan 2019 18:34:13 -0500 Subject: [PATCH] Add suppport for float enums Fixes #1099 --- src/Psalm/Type.php | 15 +++++++++++++++ tests/EnumTest.php | 15 +++++++++++++-- tests/TypeParseTest.php | 10 ++++++---- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/Psalm/Type.php b/src/Psalm/Type.php index 616089148..c3ba33744 100644 --- a/src/Psalm/Type.php +++ b/src/Psalm/Type.php @@ -500,6 +500,10 @@ abstract class Type return new Atomic\TScalarClassConstant($fq_classlike_name, $const_name); } + if (preg_match('/^\-?(0|[1-9][0-9]*)(\.[0-9]{1,})$/', $parse_tree->value)) { + return new TLiteralFloat((float) $parse_tree->value); + } + if (preg_match('/^\-?(0|[1-9][0-9]*)$/', $parse_tree->value)) { return new TLiteralInt((int) $parse_tree->value); } @@ -701,6 +705,17 @@ abstract class Type } if ($char === '.') { + if ($i + 1 < $c + && is_numeric($chars[$i + 1]) + && $i > 0 + && is_numeric($chars[$i - 1]) + ) { + $type_tokens[$rtc] .= $char; + $was_char = false; + + continue; + } + if ($i + 2 > $c || $chars[$i + 1] !== '.' || $chars[$i + 2] !== '.') { throw new TypeParseTreeException('Unexpected token ' . $char); } diff --git a/tests/EnumTest.php b/tests/EnumTest.php index a275edc64..187c8d3eb 100644 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -31,13 +31,15 @@ class EnumTest extends TestCase ' [ ' 'InvalidArgument', ], + 'enumWrongFloat' => [ + ' 'InvalidArgument', + ], 'classConstantIncorrect' => [ 'assertSame($resolved_type->getId(), $docblock_type->getId()); @@ -678,7 +679,7 @@ class TypeParseTest extends TestCase */ public function testEnumWithoutSpaces() { - $docblock_type = Type::parseString('\'foo\\\'with\'|"bar\"bar"|"baz"|"bat\\\\"|\'bang bang\'|1|2|3'); + $docblock_type = Type::parseString('\'foo\\\'with\'|"bar\"bar"|"baz"|"bat\\\\"|\'bang bang\'|1|2|3|4.5'); $resolved_type = new Type\Union([ new Type\Atomic\TLiteralString('foo\'with'), @@ -688,7 +689,8 @@ class TypeParseTest extends TestCase new Type\Atomic\TLiteralString('bang bang'), new Type\Atomic\TLiteralInt(1), new Type\Atomic\TLiteralInt(2), - new Type\Atomic\TLiteralInt(3) + new Type\Atomic\TLiteralInt(3), + new Type\Atomic\TLiteralFloat(4.5) ]); $this->assertSame($resolved_type->getId(), $docblock_type->getId());