diff --git a/src/Internal/Checker/ConditionalChecker.php b/src/Internal/Checker/ConditionalChecker.php index fdeda3aa..1a028144 100644 --- a/src/Internal/Checker/ConditionalChecker.php +++ b/src/Internal/Checker/ConditionalChecker.php @@ -4,11 +4,23 @@ namespace TypePHP\Internal\Checker; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeUnsealedTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; +use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode; use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode; use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; +use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionClass; use Throwable; use TypePHP\Internal\Generics\TemplateManager; @@ -21,7 +33,84 @@ final class ConditionalChecker { /** - * Recursively resolves multi-branch nested conditional types ($param is Target ? A : B or T is Target ? A : B). + * Checks whether a TypeNode AST contains any conditional types. + */ + public static function containsConditional(TypeNode $node): bool + { + if ($node instanceof ConditionalTypeNode || $node instanceof ConditionalTypeForParameterNode) { + return true; + } + + if ($node instanceof NullableTypeNode || $node instanceof ArrayTypeNode) { + return self::containsConditional($node->type); + } + + if ($node instanceof GenericTypeNode) { + if (self::containsConditional($node->type)) { + return true; + } + foreach ($node->genericTypes as $gt) { + if (self::containsConditional($gt)) { + return true; + } + } + + return false; + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + foreach ($node->types as $t) { + if (self::containsConditional($t)) { + return true; + } + } + + return false; + } + + if ($node instanceof ArrayShapeNode) { + foreach ($node->items as $item) { + if (self::containsConditional($item->valueType)) { + return true; + } + } + if ($node->unsealedType !== null) { + return self::containsConditional($node->unsealedType->valueType) + || ($node->unsealedType->keyType !== null && self::containsConditional($node->unsealedType->keyType)); + } + + return false; + } + + if ($node instanceof ObjectShapeNode) { + foreach ($node->items as $item) { + if (self::containsConditional($item->valueType)) { + return true; + } + } + + return false; + } + + if ($node instanceof CallableTypeNode) { + foreach ($node->parameters as $p) { + if (self::containsConditional($p->type)) { + return true; + } + } + + return self::containsConditional($node->returnType); + } + + if ($node instanceof OffsetAccessTypeNode) { + return self::containsConditional($node->type) || self::containsConditional($node->offset); + } + + return false; + } + + /** + * Recursively resolves multi-branch and nested conditional types anywhere in a TypeNode AST. * * @param array $vars * @param array $boundTemplates @@ -41,6 +130,114 @@ public static function resolve( return self::resolveTemplateConditional($typeNode, $vars, $boundTemplates, $registry, $function); } + if (! self::containsConditional($typeNode)) { + return $typeNode; + } + + if ($typeNode instanceof NullableTypeNode) { + return new NullableTypeNode(self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function)); + } + + if ($typeNode instanceof ArrayTypeNode) { + return new ArrayTypeNode(self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function)); + } + + if ($typeNode instanceof GenericTypeNode) { + $genericType = self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function); + $genericTypes = array_map( + fn ($t) => self::resolve($t, $vars, $boundTemplates, $registry, $function), + $typeNode->genericTypes + ); + + return new GenericTypeNode( + $genericType instanceof IdentifierTypeNode ? $genericType : $typeNode->type, + $genericTypes, + $typeNode->variances + ); + } + + if ($typeNode instanceof UnionTypeNode) { + return new UnionTypeNode(array_map( + fn ($t) => self::resolve($t, $vars, $boundTemplates, $registry, $function), + $typeNode->types + )); + } + + if ($typeNode instanceof IntersectionTypeNode) { + return new IntersectionTypeNode(array_map( + fn ($t) => self::resolve($t, $vars, $boundTemplates, $registry, $function), + $typeNode->types + )); + } + + if ($typeNode instanceof ArrayShapeNode) { + $newItems = []; + foreach ($typeNode->items as $item) { + $newItems[] = new ArrayShapeItemNode( + $item->keyName, + $item->optional, + self::resolve($item->valueType, $vars, $boundTemplates, $registry, $function) + ); + } + + $newUnsealed = null; + if ($typeNode->unsealedType !== null) { + $unsealedKey = $typeNode->unsealedType->keyType !== null + ? self::resolve($typeNode->unsealedType->keyType, $vars, $boundTemplates, $registry, $function) + : null; + $unsealedVal = self::resolve($typeNode->unsealedType->valueType, $vars, $boundTemplates, $registry, $function); + $newUnsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey); + } + + if ($typeNode->sealed) { + return ArrayShapeNode::createSealed($newItems, $typeNode->kind); + } + + return ArrayShapeNode::createUnsealed($newItems, $newUnsealed, $typeNode->kind); + } + + if ($typeNode instanceof ObjectShapeNode) { + $newItems = []; + foreach ($typeNode->items as $item) { + $newItems[] = new ObjectShapeItemNode( + $item->keyName, + $item->optional, + self::resolve($item->valueType, $vars, $boundTemplates, $registry, $function) + ); + } + + return new ObjectShapeNode($newItems); + } + + if ($typeNode instanceof CallableTypeNode) { + $parameters = array_map( + fn (CallableTypeParameterNode $param) => new CallableTypeParameterNode( + self::resolve($param->type, $vars, $boundTemplates, $registry, $function), + $param->isReference, + $param->isVariadic, + $param->parameterName, + $param->isOptional + ), + $typeNode->parameters + ); + + $returnType = self::resolve($typeNode->returnType, $vars, $boundTemplates, $registry, $function); + + return new CallableTypeNode( + $typeNode->identifier, + $parameters, + $returnType, + $typeNode->templateTypes + ); + } + + if ($typeNode instanceof OffsetAccessTypeNode) { + return new OffsetAccessTypeNode( + self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function), + self::resolve($typeNode->offset, $vars, $boundTemplates, $registry, $function) + ); + } + return $typeNode; } diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 9241ed94..b484ad43 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -8,8 +8,6 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; -use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode; -use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; @@ -238,10 +236,7 @@ private static function validateSimpleParams( ): ?ErrorMessage { foreach ($types as $paramName => $typeNode) { if (isset($vars[$paramName]) || \array_key_exists($paramName, $vars)) { - if ( - $typeNode instanceof ConditionalTypeForParameterNode || - $typeNode instanceof ConditionalTypeNode - ) { + if (ConditionalChecker::containsConditional($typeNode)) { $typeNode = ConditionalChecker::resolve($typeNode, $vars, [], $registry, $effectiveFunction); } @@ -1095,10 +1090,7 @@ private static function validateSingleParam( object|string|null $thisOrClass = null, bool $isSensitive = false ): ?ErrorMessage { - if ( - $typeNode instanceof ConditionalTypeForParameterNode || - $typeNode instanceof ConditionalTypeNode - ) { + if (ConditionalChecker::containsConditional($typeNode)) { $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); } @@ -1115,10 +1107,7 @@ private static function validateSingleParam( $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); } - if ( - $typeNode instanceof ConditionalTypeForParameterNode || - $typeNode instanceof ConditionalTypeNode - ) { + if (ConditionalChecker::containsConditional($typeNode)) { $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); } diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index b52a83ad..a58b28f2 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -6,7 +6,6 @@ use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; -use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; @@ -343,9 +342,9 @@ private static function evaluateReturn( $hasGenerics = (\count($templates) > 0); $hasAliases = (\count($aliases) > 0); - $isParamConditional = ($returnTypeNode instanceof ConditionalTypeForParameterNode); + $hasConditionals = ConditionalChecker::containsConditional($returnTypeNode); - if (! $hasGenerics && ! $hasAliases && ! $isParamConditional && ! ($returnTypeNode instanceof CallableTypeNode)) { + if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && ! ($returnTypeNode instanceof CallableTypeNode)) { $isDynamic = $contract['returnIsDynamic'] ?? (str_contains((string) $returnTypeNode, 'static') || str_contains((string) $returnTypeNode, '$this')); if (! $isDynamic) { @@ -386,7 +385,7 @@ private static function evaluateReturn( $sig = null; $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $isParamConditional && \count($aliases) === 0 && $thisObj === null) { + if ($boundCount > 0 && $boundCount <= 2 && ! $hasConditionals && \count($aliases) === 0 && $thisObj === null) { if ($boundCount === 1) { $first = reset($boundTemplates); $sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first; @@ -409,7 +408,7 @@ private static function evaluateReturn( $resolvedType = $aliases[$resolvedType->name]; } - if (\count($boundTemplates) === 0 && \count($templates) > 0 && ! $isParamConditional && $thisObj === null) { + if (\count($boundTemplates) === 0 && \count($templates) > 0 && ! $hasConditionals && $thisObj === null) { $resolvedType = self::$unboundReturnCache[$function] ??= SpecialTypeResolver::resolve( TemplateSubstitutor::substitute($returnTypeNode, [], $templates), $function, diff --git a/src/Internal/Checker/SelfOutChecker.php b/src/Internal/Checker/SelfOutChecker.php index 4a9d3a2f..f4b23394 100644 --- a/src/Internal/Checker/SelfOutChecker.php +++ b/src/Internal/Checker/SelfOutChecker.php @@ -4,8 +4,6 @@ namespace TypePHP\Internal\Checker; -use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode; -use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Generics\TemplateManager; @@ -79,10 +77,7 @@ public static function checkSelfOut( $selfOutNode = SpecialTypeResolver::resolve($selfOutNode, $effectiveFunction, $thisObj); } - if ( - $selfOutNode instanceof ConditionalTypeForParameterNode || - $selfOutNode instanceof ConditionalTypeNode - ) { + if (ConditionalChecker::containsConditional($selfOutNode)) { $selfOutNode = ConditionalChecker::resolve($selfOutNode, $vars, $boundTemplates, $registry, $effectiveFunction); } diff --git a/src/Internal/Docblock/DocblockNormalizer.php b/src/Internal/Docblock/DocblockNormalizer.php index 5a2b4016..a28e1a82 100644 --- a/src/Internal/Docblock/DocblockNormalizer.php +++ b/src/Internal/Docblock/DocblockNormalizer.php @@ -51,7 +51,7 @@ public static function normalize(string $doc): string } if (stripos($doc, 'callable') !== false || stripos($doc, 'closure') !== false) { - $doc = preg_replace('/(callable|Closure|static-closure)\s*\(([^)]*)\)(?!\s*:)/i', '$1($2): mixed', $doc) ?? $doc; + $doc = preg_replace('/(callable|Closure|static-closure)\s*(\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))(?!\s*:)/i', '$1$2: mixed', $doc) ?? $doc; } if (str_contains($doc, '::') && str_contains($doc, ':')) { diff --git a/src/Internal/Generics/TemplateSubstitutor.php b/src/Internal/Generics/TemplateSubstitutor.php index ef7654a1..be32184e 100644 --- a/src/Internal/Generics/TemplateSubstitutor.php +++ b/src/Internal/Generics/TemplateSubstitutor.php @@ -42,6 +42,91 @@ public static function substitute(TypeNode $node, array $boundTemplates, array $ return self::substituteNode($node, $boundTemplates, $declaredTemplates, []); } + /** + * Flattens, deduplicates, and normalizes union types recursively. + * + * @param array $types + */ + public static function normalizeUnion(array $types): TypeNode + { + $unique = []; + /** @var list $deduped */ + $deduped = []; + + foreach (self::flatten($types, UnionTypeNode::class) as $t) { + if ($t instanceof IdentifierTypeNode && strtolower($t->name) === 'mixed') { + return new IdentifierTypeNode('mixed'); + } + + $str = (string) $t; + if (! isset($unique[$str])) { + $unique[$str] = true; + $deduped[] = $t; + } + } + + if (\count($deduped) === 0) { + return new IdentifierTypeNode('mixed'); + } + + return \count($deduped) === 1 ? $deduped[0] : new UnionTypeNode($deduped); + } + + /** + * Flattens, deduplicates, and normalizes intersection types recursively. + * + * @param array $types + */ + public static function normalizeIntersection(array $types): TypeNode + { + $unique = []; + /** @var list $deduped */ + $deduped = []; + + foreach (self::flatten($types, IntersectionTypeNode::class) as $t) { + if ($t instanceof IdentifierTypeNode && strtolower($t->name) === 'mixed') { + continue; + } + + $str = (string) $t; + if (! isset($unique[$str])) { + $unique[$str] = true; + $deduped[] = $t; + } + } + + if (\count($deduped) === 0) { + return new IdentifierTypeNode('mixed'); + } + + return \count($deduped) === 1 ? $deduped[0] : new IntersectionTypeNode($deduped); + } + + /** + * Recursively inlines nested nodes of the given container class. + * + * @param array $types + * @param class-string|class-string $containerClass + * + * @return list + */ + private static function flatten(array $types, string $containerClass): array + { + $result = []; + + foreach ($types as $t) { + if ($t instanceof $containerClass) { + foreach (self::flatten($t->types, $containerClass) as $inner) { + $result[] = $inner; + } + } else { + $result[] = $t; + } + } + + return $result; + } + /** * @param array $boundTemplates * @param array $declaredTemplates @@ -82,17 +167,21 @@ private static function substituteNode( } if ($node instanceof UnionTypeNode) { - return new UnionTypeNode(array_map( + $types = array_map( fn ($t) => self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited), $node->types - )); + ); + + return self::normalizeUnion($types); } if ($node instanceof IntersectionTypeNode) { - return new IntersectionTypeNode(array_map( + $types = array_map( fn ($t) => self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited), $node->types - )); + ); + + return self::normalizeIntersection($types); } if ($node instanceof ArrayShapeNode) { diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index 5af4dd0f..9ce46fa7 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -15,7 +15,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.1_'; + public const VERSION_PREFIX = 'v0.10.22_'; /** * Cached absolute cache directory path. diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index d9a655f3..721573dd 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -13,6 +13,7 @@ use ReflectionFunction; use TypeError; use TypePHP\Exception\TypeError as TypePHPTypeError; +use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Docblock\DocblockParser; @@ -88,6 +89,10 @@ public static function wrap(string $function, string $paramName, mixed $callable $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); } + if ($typeNode !== null && ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + } + $prefix = ($paramName === 'return') ? "$function(): Return value" : "$function(): Callback \$$paramName"; if (self::isCallable($callable)) { diff --git a/tests/Internal/Docblock/DocblockNormalizerTest.php b/tests/Internal/Docblock/DocblockNormalizerTest.php index c5a5f3f3..bdc0552c 100644 --- a/tests/Internal/Docblock/DocblockNormalizerTest.php +++ b/tests/Internal/Docblock/DocblockNormalizerTest.php @@ -102,6 +102,37 @@ $expected3 = '/** @param callable(): mixed $emptyCallable */'; expect(DocblockNormalizer::normalize($doc3))->toBe($expected3); }); + + test('preserves callable signatures containing inner parenthesized conditional types without inserting premature : mixed', function () { + $doc1 = '/** @param callable((T is int ? positive-int : T)): bool $callback */'; + expect(DocblockNormalizer::normalize($doc1))->toBe($doc1); + + $doc2 = '/** @param Closure((T is string ? non-empty-string : int)): string $closure */'; + expect(DocblockNormalizer::normalize($doc2))->toBe($doc2); + }); + + test('preserves callable signatures containing inner parenthesized unions and intersections', function () { + $doc1 = '/** @param callable((int|string)): bool $cb */'; + expect(DocblockNormalizer::normalize($doc1))->toBe($doc1); + + $doc2 = '/** @param callable((Countable&ArrayAccess)): void $cb */'; + expect(DocblockNormalizer::normalize($doc2))->toBe($doc2); + }); + + test('preserves nested higher-order callable signatures', function () { + $doc = '/** @param callable(callable(int): string): bool $cb */'; + expect(DocblockNormalizer::normalize($doc))->toBe($doc); + }); + + test('auto-completes omitted return types for callables with inner parenthesized parameter types', function () { + $doc1 = '/** @param callable((T is int ? positive-int : T) $x) $cb */'; + $expected1 = '/** @param callable((T is int ? positive-int : T) $x): mixed $cb */'; + expect(DocblockNormalizer::normalize($doc1))->toBe($expected1); + + $doc2 = '/** @param callable((int|string) $x) $cb */'; + $expected2 = '/** @param callable((int|string) $x): mixed $cb */'; + expect(DocblockNormalizer::normalize($doc2))->toBe($expected2); + }); }); describe('Type Alias Normalization (@phpstan-type and @psalm-type)', function () { diff --git a/tests/TypeChecking/Conditionals/NestedCompoundConditionalTypesTest.php b/tests/TypeChecking/Conditionals/NestedCompoundConditionalTypesTest.php new file mode 100644 index 00000000..bf022b83 --- /dev/null +++ b/tests/TypeChecking/Conditionals/NestedCompoundConditionalTypesTest.php @@ -0,0 +1,355 @@ + $out]; +} + +/** + * Conditional inside Array Shape Parameter + * + * @template T + * + * @param T $v + * @param array{data: (T is int ? positive-int : T)} $payload + */ +function testConditionalInArrayShapeParam(mixed $v, array $payload): bool +{ + return true; +} + +/** + * 2. Conditional inside Generic List Return + * + * @template T + * + * @param T $v + * @param array $items + * + * @return list<(T is int ? positive-int : T)> + */ +function testConditionalInGenericListReturn(mixed $v, array $items): array +{ + return $items; +} + +/** + * Conditional inside Generic List Parameter + * + * @template T + * + * @param T $v + * @param list<(T is int ? positive-int : T)> $items + */ +function testConditionalInGenericListParam(mixed $v, array $items): bool +{ + return true; +} + +/** + * 3. Conditional inside Union Return + * + * @template T + * + * @param T $v + * @param mixed $result + * + * @return (T is int ? positive-int : T)|null + */ +function testConditionalInUnionReturn(mixed $v, mixed $result): mixed +{ + return $result; +} + +/** + * 4. Conditional inside Nullable Return + * + * @template T + * + * @param T $v + * @param mixed $result + * + * @return ?(T is int ? positive-int : T) + */ +function testConditionalInNullableReturn(mixed $v, mixed $result): mixed +{ + return $result; +} + +/** + * 5. Conditional inside Callable Return Type + * + * @template T + * + * @param T $v + * @param mixed $closureReturn + * + * @return callable(): (T is int ? positive-int : T) + */ +function testConditionalInCallableReturn(mixed $v, mixed $closureReturn): callable +{ + return fn () => $closureReturn; +} + +/** + * Conditional inside Callable Parameter Type + * + * @template T + * + * @param T $v + * @param callable((T is int ? positive-int : T)): bool $callback + * @param mixed $arg + */ +function testConditionalInCallableParam(mixed $v, callable $callback, mixed $arg): bool +{ + return $callback($arg); +} + +/** + * 6. Conditional inside Object Shape (stdClass{...}) + * + * @template T + * + * @param T $v + * @param mixed $out + * + * @return stdClass{out: (T is int ? positive-int : T)} + */ +function testConditionalInObjectShapeReturn(mixed $v, mixed $out): stdClass +{ + $obj = new stdClass(); + $obj->out = $out; + + return $obj; +} + +/** + * Parameter-based conditional inside an Array Shape return + * + * @param bool $asInt + * @param mixed $out + * + * @return array{result: ($asInt is true ? positive-int : non-empty-string)} + */ +function testParamConditionalInShapeReturn(bool $asInt, mixed $out): array +{ + return ['result' => $out]; +} + +/** + * Parameter-based conditional inside a Generic List parameter + * + * @param string $format + * @param list<($format is 'int' ? positive-int : non-empty-string)> $items + */ +function testParamConditionalInListParam(string $format, array $items): bool +{ + return true; +} + +class NestedConditionalServiceFixture +{ + /** + * @template T + * + * @param T $v + * @param mixed $out + * + * @return array{out: (T is int ? positive-int : T)} + */ + public function transformShape(mixed $v, mixed $out): array + { + return ['out' => $out]; + } + + /** + * @template T + * + * @param T $v + * @param array $items + * + * @return list<(T is string ? non-empty-string : positive-int)> + */ + public function transformList(mixed $v, array $items): array + { + return $items; + } +} + +describe('Nested Conditional Types Inside Compound Structures', function () { + describe('1. Conditionals Inside Array Shapes (array{key: (T is Target ? A : B)})', function () { + test('evaluates conditional inside array shape return when T is int (positive-int)', function () { + $valid = testConditionalInArrayShapeReturn(5, 42); + expect($valid)->toBe(['out' => 42]); + + expect(fn () => testConditionalInArrayShapeReturn(5, -5)) + ->toThrow(TypeError::class, "['out'] must be of type positive-int") + ; + }); + + test('evaluates fallback branch inside array shape return when T is string (T)', function () { + $valid = testConditionalInArrayShapeReturn('hello', 'world'); + expect($valid)->toBe(['out' => 'world']); + + expect(fn () => testConditionalInArrayShapeReturn('hello', 12345)) + ->toThrow(TypeError::class, "['out'] must be of type string") + ; + }); + + test('evaluates conditional inside array shape parameter', function () { + expect(testConditionalInArrayShapeParam(10, ['data' => 100]))->toBeTrue(); + + expect(fn () => testConditionalInArrayShapeParam(10, ['data' => -50])) + ->toThrow(TypeError::class, "['data'] must be of type positive-int") + ; + }); + }); + + describe('2. Conditionals Inside Generic Lists (list<(T is Target ? A : B)>)', function () { + test('evaluates conditional inside generic list return when T is int', function () { + $valid = testConditionalInGenericListReturn(5, [1, 2, 3]); + expect($valid)->toBe([1, 2, 3]); + + expect(fn () => testConditionalInGenericListReturn(5, [1, -5, 3])) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates fallback branch inside generic list return when T is string', function () { + $valid = testConditionalInGenericListReturn('tag', ['alpha', 'beta']); + expect($valid)->toBe(['alpha', 'beta']); + + expect(fn () => testConditionalInGenericListReturn('tag', ['alpha', 123])) + ->toThrow(TypeError::class, 'string') + ; + }); + + test('evaluates conditional inside generic list parameter', function () { + expect(testConditionalInGenericListParam(10, [10, 20, 30]))->toBeTrue(); + + expect(fn () => testConditionalInGenericListParam(10, [10, -5, 30])) + ->toThrow(TypeError::class, '[1] must be of type positive-int') + ; + }); + }); + + describe('3. Conditionals Inside Unions and Nullables ((Cond)|null & ?Cond)', function () { + test('evaluates conditional inside union return and allows null', function () { + expect(testConditionalInUnionReturn(5, null))->toBeNull(); + expect(testConditionalInUnionReturn(5, 42))->toBe(42); + + expect(fn () => testConditionalInUnionReturn(5, -5)) + ->toThrow(TypeError::class, 'must be of type (positive-int | null)') + ; + }); + + test('evaluates conditional inside nullable return and allows null', function () { + expect(testConditionalInNullableReturn(5, null))->toBeNull(); + expect(testConditionalInNullableReturn(5, 100))->toBe(100); + + expect(fn () => testConditionalInNullableReturn(5, -5)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + }); + + describe('4. Conditionals Inside Callables (callable(): Cond & callable(Cond): bool)', function () { + test('evaluates conditional in callable return and validates callback invocation', function () { + $validCb = testConditionalInCallableReturn(5, 42); + expect($validCb())->toBe(42); + + $invalidCb = testConditionalInCallableReturn(5, -5); + expect(fn () => $invalidCb()) + ->toThrow(TypeError::class, 'return value must be of type positive-int') + ; + }); + + test('evaluates conditional in callable parameter and validates callback argument', function () { + $cb = fn (int $x): bool => $x > 0; + + expect(testConditionalInCallableParam(5, $cb, 10))->toBeTrue(); + + expect(fn () => testConditionalInCallableParam(5, $cb, -50)) + ->toThrow(TypeError::class, 'must be of type positive-int') + ; + }); + }); + + describe('5. Conditionals Inside Object Shapes (stdClass{out: Cond})', function () { + test('evaluates conditional inside object shape return', function () { + $valid = testConditionalInObjectShapeReturn(5, 42); + expect($valid->out)->toBe(42); + + expect(fn () => testConditionalInObjectShapeReturn(5, -5)) + ->toThrow(TypeError::class, '->out must be of type positive-int') + ; + }); + }); + + describe('6. Parameter-Based Conditionals in Compounds ($param is Target ? A : B)', function () { + test('evaluates parameter conditional inside array shape return ($asInt is true)', function () { + $resInt = testParamConditionalInShapeReturn(true, 100); + expect($resInt)->toBe(['result' => 100]); + + expect(fn () => testParamConditionalInShapeReturn(true, -50)) + ->toThrow(TypeError::class, "['result'] must be of type positive-int") + ; + + $resStr = testParamConditionalInShapeReturn(false, 'active_status'); + expect($resStr)->toBe(['result' => 'active_status']); + + expect(fn () => testParamConditionalInShapeReturn(false, '')) + ->toThrow(TypeError::class, "['result'] must be of type non-empty-string") + ; + }); + + test('evaluates parameter conditional inside generic list parameter', function () { + expect(testParamConditionalInListParam('int', [10, 20]))->toBeTrue(); + + expect(fn () => testParamConditionalInListParam('int', [10, -5])) + ->toThrow(TypeError::class, '[1] must be of type positive-int') + ; + + expect(testParamConditionalInListParam('str', ['a', 'b']))->toBeTrue(); + + expect(fn () => testParamConditionalInListParam('str', ['a', ''])) + ->toThrow(TypeError::class, '[1] must be of type non-empty-string') + ; + }); + }); + + describe('7. Class Methods with Nested Conditionals', function () { + test('evaluates nested conditional shape in class methods', function () { + $service = new NestedConditionalServiceFixture(); + + expect($service->transformShape(10, 42))->toBe(['out' => 42]); + + expect(fn () => $service->transformShape(10, -5)) + ->toThrow(TypeError::class, "['out'] must be of type positive-int") + ; + }); + + test('evaluates nested conditional list in class methods', function () { + $service = new NestedConditionalServiceFixture(); + + expect($service->transformList('sample', ['valid_a', 'valid_b']))->toBe(['valid_a', 'valid_b']); + + expect(fn () => $service->transformList('sample', ['valid_a', ''])) + ->toThrow(TypeError::class, '[1] must be of type non-empty-string'); + }); + }); +}); diff --git a/tests/TypeChecking/Generics/UnionAccumulationAndNormalizationTest.php b/tests/TypeChecking/Generics/UnionAccumulationAndNormalizationTest.php new file mode 100644 index 00000000..37fafc11 --- /dev/null +++ b/tests/TypeChecking/Generics/UnionAccumulationAndNormalizationTest.php @@ -0,0 +1,274 @@ + + * + * @template T + */ +class MutableAccumulationCollection +{ + /** + * @var array + */ + public array $items = []; + + /** + * @template TNew + * + * @param TNew $item + * + * @self-out self + */ + public function push(mixed $item): void + { + $this->items[] = $item; + } + + /** + * @param T $item + */ + public function addStrict(mixed $item): void + { + $this->items[] = $item; + } +} + +/** + * Class with redundant union in return type + */ +class DuplicateUnionMethodFixture +{ + /** + * @template T + * + * @param T $a + * @param T $b + * + * @return T|T + */ + public function duplicateUnion(mixed $a, mixed $b): mixed + { + return $a; + } +} + +describe('Union & Intersection Accumulation, Flattening and Deduplication', function () { + + describe('1. Dynamic @self-out Union Accumulation (self)', function () { + test('initial state initializes cleanly with single type', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + expect(TypePHP::getGenericType($col))->toBe(Dog::class); + }); + + test('deduplicates identical type on push without creating redundant (Dog | Dog) union', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + $col->push(new Dog('Rex')); + + expect(TypePHP::getGenericType($col))->toBe(Dog::class); + }); + + test('accumulates distinct second type into 2-member union (Dog | Cat)', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + $col->push(new Dog('Rex')); + $col->push(new Cat('Whiskers')); + + expect(TypePHP::getGenericType($col))->toBe('(' . Dog::class . ' | ' . Cat::class . ')'); + }); + + test('flattens 3-member nested union into single-level (Dog | Cat | Bird) without ((A|B)|C) nesting', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + $col->push(new Dog('Rex')); + $col->push(new Cat('Whiskers')); + $col->push(new AccumulationBird('Tweety')); + + $expected = '(' . Dog::class . ' | ' . Cat::class . ' | ' . AccumulationBird::class . ')'; + expect(TypePHP::getGenericType($col))->toBe($expected); + }); + + test('flattens 4-member nested union through sequential pushes', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + $col->push(new Dog('Rex')); + $col->push(new Cat('Whiskers')); + $col->push(new AccumulationBird('Tweety')); + $col->push(new AccumulationFish('Nemo')); + + $expected = '(' . Dog::class . ' | ' . Cat::class . ' | ' . AccumulationBird::class . ' | ' . AccumulationFish::class . ')'; + expect(TypePHP::getGenericType($col))->toBe($expected); + }); + + test('deduplicates already accumulated types when pushed again later in the sequence', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + $col->push(new Cat('Whiskers')); + $col->push(new AccumulationBird('Tweety')); + $col->push(new Dog('Rex')); + $col->push(new Cat('Shadow')); + + $expected = '(' . Dog::class . ' | ' . Cat::class . ' | ' . AccumulationBird::class . ')'; + expect(TypePHP::getGenericType($col))->toBe($expected); + }); + + test('strictly enforces the accumulated union against invalid additions', function () { + /** @var MutableAccumulationCollection $col */ + $col = new MutableAccumulationCollection(); + + $col->push(new Cat('Whiskers')); + $col->push(new AccumulationBird('Tweety')); + + $col->addStrict(new Dog()); + $col->addStrict(new Cat()); + $col->addStrict(new AccumulationBird()); + + expect(\count($col->items))->toBe(5); + + expect(fn () => $col->addStrict(new Car())) + ->toThrow(TypeError::class) + ; + }); + }); + + describe('2. AST Level Normalization Helpers (TemplateSubstitutor)', function () { + test('normalizeUnion flattens deeply nested UnionTypeNode trees', function () { + $dog = new IdentifierTypeNode('Dog'); + $cat = new IdentifierTypeNode('Cat'); + $bird = new IdentifierTypeNode('Bird'); + + $nested = new UnionTypeNode([ + new UnionTypeNode([$dog, $cat]), + $bird, + ]); + + $normalized = TemplateSubstitutor::normalizeUnion([$nested]); + + expect($normalized)->toBeInstanceOf(UnionTypeNode::class) + ->and((string) $normalized)->toBe('(Dog | Cat | Bird)') + ->and(\count($normalized->types))->toBe(3) + ; + }); + + test('normalizeUnion deduplicates identical types', function () { + $types = [ + new IdentifierTypeNode('Dog'), + new IdentifierTypeNode('Cat'), + new IdentifierTypeNode('Dog'), + new IdentifierTypeNode('Cat'), + new IdentifierTypeNode('Bird'), + ]; + + $normalized = TemplateSubstitutor::normalizeUnion($types); + + expect($normalized)->toBeInstanceOf(UnionTypeNode::class) + ->and((string) $normalized)->toBe('(Dog | Cat | Bird)') + ->and(\count($normalized->types))->toBe(3) + ; + }); + + test('normalizeUnion unwraps single-element union back to base TypeNode', function () { + $types = [ + new IdentifierTypeNode('Dog'), + new IdentifierTypeNode('Dog'), + ]; + + $normalized = TemplateSubstitutor::normalizeUnion($types); + + expect($normalized)->toBeInstanceOf(IdentifierTypeNode::class) + ->and($normalized->name)->toBe('Dog') + ; + }); + + test('normalizeUnion simplifies union containing mixed to mixed directly', function () { + $types = [ + new IdentifierTypeNode('int'), + new IdentifierTypeNode('string'), + new IdentifierTypeNode('mixed'), + ]; + + $normalized = TemplateSubstitutor::normalizeUnion($types); + + expect($normalized)->toBeInstanceOf(IdentifierTypeNode::class) + ->and($normalized->name)->toBe('mixed') + ; + }); + + test('normalizeIntersection flattens, deduplicates, and eliminates mixed', function () { + $countable = new IdentifierTypeNode('Countable'); + $arrayAccess = new IdentifierTypeNode('ArrayAccess'); + $mixed = new IdentifierTypeNode('mixed'); + + $nested = new IntersectionTypeNode([ + $countable, + new IntersectionTypeNode([$arrayAccess, $countable]), + $mixed, + ]); + + $normalized = TemplateSubstitutor::normalizeIntersection([$nested]); + + expect($normalized)->toBeInstanceOf(IntersectionTypeNode::class) + ->and((string) $normalized)->toBe('(Countable & ArrayAccess)') + ->and(\count($normalized->types))->toBe(2) + ; + }); + + test('normalizeIntersection unwraps single-element intersection to base TypeNode', function () { + $types = [ + new IdentifierTypeNode('Countable'), + new IdentifierTypeNode('Countable'), + ]; + + $normalized = TemplateSubstitutor::normalizeIntersection($types); + + expect($normalized)->toBeInstanceOf(IdentifierTypeNode::class) + ->and($normalized->name)->toBe('Countable') + ; + }); + }); + + describe('3. Return Type Simplification with Duplicate Union Branches (@return T|T)', function () { + test('simplifies redundant union return types after template substitution', function () { + $service = new DuplicateUnionMethodFixture(); + + $result = $service->duplicateUnion(100, 200); + + expect($result)->toBe(100); + }); + }); +});