diff --git a/composer.json b/composer.json index 4c3f6e19..d9b472dd 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "typephp/typephp", - "description": "Transparent Runtime type checker for PHP. Enforces PHPDoc annotations including generics, typed arrays, array shapes, and advanced types at runtime in development and production.", + "description": "Transparent Runtime type checker for PHP. Enforces PHPDoc annotations including generics, typed arrays, array shapes, and advanced types at runtime.", "type": "library", "license": "MIT", "keywords": [ diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 39e21f51..c0e8d764 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -417,6 +417,20 @@ private static function validateAllParameters( } } + if (\count($allTemplates) > 1) { + return self::validateCrossReferencedTemplateBounds( + $contractTypes, + $baseTypes, + $vars, + $effectiveFunction, + $thisObj, + $allTemplates, + $registry, + $thisOrClass, + $sensitiveParams + ); + } + return null; } @@ -636,6 +650,87 @@ private static function extractCallableNodes(array $types): array return $callableNodes; } + /** + * Re-validates template upper bounds that reference other sibling templates once all parameters have been bound. + * + * @param array $contractTypes + * @param array $baseTypes + * @param array $vars + * @param array $allTemplates + * @param array $sensitiveParams + */ + private static function validateCrossReferencedTemplateBounds( + array $contractTypes, + array $baseTypes, + array $vars, + string $effectiveFunction, + ?object $thisObj, + array $allTemplates, + TypeValidatorRegistry $registry, + object|string|null $thisOrClass = null, + array $sensitiveParams = [] + ): ?ErrorMessage { + $finalBoundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates); + if (\count($finalBoundTemplates) === 0) { + return null; + } + + foreach ($allTemplates as $tName => $templateNode) { + if ($templateNode->bound === null || ! isset($finalBoundTemplates[$tName])) { + continue; + } + + $otherTemplates = $allTemplates; + unset($otherTemplates[$tName]); + + if (! DocblockParser::typeReferencesTemplate($templateNode->bound, $otherTemplates)) { + continue; + } + + $substitutedBound = TemplateSubstitutor::substitute($templateNode->bound, $finalBoundTemplates); + $resolvedBound = SpecialTypeResolver::resolve($substitutedBound, $effectiveFunction, $thisObj); + + $matchedParam = false; + foreach ($contractTypes as $paramName => $_) { + if (! isset($vars[$paramName]) && ! \array_key_exists($paramName, $vars)) { + continue; + } + + $baseType = $baseTypes[$paramName]; + $val = $vars[$paramName]; + $isSensitive = $sensitiveParams[$paramName] ?? false; + + if ($baseType instanceof GenericTypeNode && self::isClassStringTemplate($baseType, [$tName => $templateNode])) { + $matchedParam = true; + if (\is_string($val) && ! self::checkClassStringSatisfiesBound($val, $resolvedBound)) { + $redact = $isSensitive || Config::isRedactValuesEnabled(); + $boundDisplay = (string) $resolvedBound; + $displayVal = $redact ? 'string given' : "'" . $val . "' given"; + + return ErrorFactory::createError($effectiveFunction . '(): Argument $' . $paramName . ' (class-string<' . $tName . '>) must be a class-string of ' . $boundDisplay . ', ' . $displayVal); + } + } elseif (self::getTemplateName($baseType, [$tName => $templateNode]) === $tName) { + $matchedParam = true; + $sampleVal = ($baseType instanceof ArrayTypeNode && \is_array($val)) ? ($val[0] ?? null) : $val; + if ($sampleVal !== null) { + $err = $registry->validate($sampleVal, $resolvedBound, $effectiveFunction . '(): Argument $' . $paramName . ' (template ' . $tName . ')', $isSensitive); + if ($err !== null) { + return $err; + } + } + } + } + + if (! $matchedParam && ! TemplateManager::checkVariance($finalBoundTemplates[$tName], $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT)) { + return ErrorFactory::createError( + $effectiveFunction . "(): Generic type argument {$finalBoundTemplates[$tName]} does not satisfy upper bound {$resolvedBound} of template {$tName}" + ); + } + } + + return null; + } + /** * Extracts an inferred TypeNode from a closure parameter, ignoring `mixed`. */ @@ -1311,7 +1406,19 @@ private static function resolveClassStringTemplate( if ($templateNode->bound !== null) { $boundLower = $templateNode->bound instanceof IdentifierTypeNode ? strtolower($templateNode->bound->name) : ''; if ($boundLower !== 'object' && $boundLower !== 'mixed') { - $resolvedBound = SpecialTypeResolver::resolve($templateNode->bound, $function, $thisObj); + $boundNode = $templateNode->bound; + $classNode = TemplateManager::$classNodeCache[$val] ??= new IdentifierTypeNode($val); + $currentBindings = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $allBindings = [...$currentBindings, $templateName => $classNode]; + + if ( + TemplateManager::isFBounded($templateNode, $function) + || DocblockParser::typeReferencesTemplate($boundNode, $templates) + ) { + $boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings); + } + + $resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj); if (! self::checkClassStringSatisfiesBound($val, $resolvedBound)) { $boundDisplay = (string) $resolvedBound; $displayVal = $redact ? 'string given' : "'" . $val . "' given"; @@ -1455,7 +1562,8 @@ private static function resolveTemplateParam( $templateNode, $isVariadic, $isClassLevelTemplate, - $registry + $registry, + $templates ); } @@ -1473,6 +1581,9 @@ private static function resolveTemplateParam( ); } + /** + * @param array $templates + */ private static function bindInitialTemplate( mixed $val, string $paramName, @@ -1483,15 +1594,22 @@ private static function bindInitialTemplate( TemplateTagValueNode $templateNode, bool $isVariadic, bool $isClassLevelTemplate, - TypeValidatorRegistry $registry + TypeValidatorRegistry $registry, + array $templates = [] ): ?ErrorMessage { $sampleVal = ($isVariadic && \is_array($val)) ? ($val[0] ?? null) : $val; $inferredType = TemplateManager::inferTypeFromValue($sampleVal); if ($templateNode->bound !== null) { $boundNode = $templateNode->bound; - if (TemplateManager::isFBounded($templateNode, $function)) { - $boundNode = TemplateSubstitutor::substitute($boundNode, [$templateName => $inferredType]); + $currentBindings = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $allBindings = [...$currentBindings, $templateName => $inferredType]; + + if ( + TemplateManager::isFBounded($templateNode, $function) + || DocblockParser::typeReferencesTemplate($boundNode, $templates) + ) { + $boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings); } $resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj); diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 8115e527..f98ebf09 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -887,12 +887,33 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t $templateList = array_values($templates); $normalizedTypeArgs = self::normalizeGenericArguments($typeNode->genericTypes, $templateList); + $candidateBindings = self::$instanceTemplateBindings[$instance] ?? []; + foreach ($templateList as $index => $templateTag) { + if (isset($normalizedTypeArgs[$index])) { + $arg = $normalizedTypeArgs[$index]; + $isWildcardOrMixed = ($arg instanceof IdentifierTypeNode && ($arg->name === '*' || strtolower($arg->name) === 'mixed')); + if (! $isWildcardOrMixed) { + $candidateBindings[$templateTag->name] = $arg; + } + } + } + foreach ($templateList as $index => $templateTag) { if (! isset($normalizedTypeArgs[$index])) { continue; } - $err = self::bindSingleTemplateArgument($instance, $className, $normalizedTypeArgs[$index], $typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT, $templateTag, $classVariances, $context, $forceBind); + $err = self::bindSingleTemplateArgument( + $instance, + $className, + $normalizedTypeArgs[$index], + $typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT, + $templateTag, + $classVariances, + $context, + $forceBind, + $candidateBindings + ); if ($err !== null) { return $err; } @@ -959,6 +980,7 @@ private static function collectHierarchyTemplatesAndVariances(\ReflectionClass $ /** * @param array $classVariances + * @param array $candidateBindings */ private static function bindSingleTemplateArgument( object $instance, @@ -968,7 +990,8 @@ private static function bindSingleTemplateArgument( TemplateTagValueNode $templateTag, array $classVariances, string $context, - bool $forceBind + bool $forceBind, + array $candidateBindings = [] ): ?ErrorMessage { if ($expectedTypeNode instanceof IdentifierTypeNode) { if (str_contains($expectedTypeNode->name, '::')) { @@ -994,8 +1017,9 @@ private static function bindSingleTemplateArgument( if ($templateTag->bound !== null && ! $isWildcardOrMixed) { $boundNode = $templateTag->bound; - if (self::isFBounded($templateTag, $className)) { - $boundNode = TemplateSubstitutor::substitute($boundNode, [$templateTag->name => $expectedTypeNode]); + $allBindings = [...$candidateBindings, $templateTag->name => $expectedTypeNode]; + if (self::isFBounded($templateTag, $className) || DocblockParser::typeReferencesTemplate($boundNode, $allBindings)) { + $boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings); } $satisfiesBound = self::checkVariance($expectedTypeNode, $boundNode, GenericTypeNode::VARIANCE_COVARIANT); @@ -1234,7 +1258,7 @@ private static function collectInheritedGenericTagBindings( } } - $bindings[$templateName] = $resolved; + $bindings[$templateName] ??= $resolved; } } } catch (\Throwable $e) { @@ -1423,13 +1447,24 @@ private static function checkIdentifierAgainstGenericVariance( $actualArg = $classBindings[$tName]; $expectedArg = $expected->genericTypes[$idx]; + if ($expectedArg instanceof IdentifierTypeNode) { + $isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($expectedArg->name); + $isRealType = self::isRealTypeSymbol($expectedArg->name); + if (! $isBuiltIn && ! $isRealType) { + continue; + } + } + $useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; $declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; + $templateBound = $parentTemplates[$tName]->bound ?? null; + $isExpectedUpperBound = $templateBound !== null && (string) $expectedArg === (string) $templateBound; $innerVariance = match (true) { $useSiteVariance !== GenericTypeNode::VARIANCE_INVARIANT => $useSiteVariance, - $declaredVariance === GenericTypeNode::VARIANCE_CONTRAVARIANT => GenericTypeNode::VARIANCE_CONTRAVARIANT, - default => GenericTypeNode::VARIANCE_COVARIANT, + $declaredVariance !== GenericTypeNode::VARIANCE_INVARIANT => $declaredVariance, + $isExpectedUpperBound => GenericTypeNode::VARIANCE_COVARIANT, + default => GenericTypeNode::VARIANCE_INVARIANT, }; if (! self::checkVariance($actualArg, $expectedArg, $innerVariance)) { @@ -1588,6 +1623,14 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge } foreach ($expected->genericTypes as $idx => $expectedInner) { + if ($expectedInner instanceof IdentifierTypeNode) { + $isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($expectedInner->name); + $isRealType = self::isRealTypeSymbol($expectedInner->name); + if (! $isBuiltIn && ! $isRealType) { + continue; + } + } + $existingInner = $existing->genericTypes[$idx] ?? new IdentifierTypeNode('mixed'); $useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; $declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index 3b7d55e9..a80dd9f1 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -145,7 +145,7 @@ public static function isEnabled(): bool } } - if (\defined('TYPEPHP_DISABLE') && TYPEPHP_DISABLE) { + if (\defined('TYPEPHP_DISABLE') && (bool) TYPEPHP_DISABLE) { return false; } diff --git a/src/bootstrap.php b/src/bootstrap.php index 2fef4df4..e2f5cd1a 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -14,7 +14,7 @@ || (isset($_ENV['TYPEPHP_DISABLE']) && filter_var($_ENV['TYPEPHP_DISABLE'], FILTER_VALIDATE_BOOLEAN)) || (isset($_SERVER['TYPEPHP_DISABLE']) && filter_var($_SERVER['TYPEPHP_DISABLE'], FILTER_VALIDATE_BOOLEAN)) ); - $isDisabledConst = \defined('TYPEPHP_DISABLE') && TYPEPHP_DISABLE; + $isDisabledConst = \defined('TYPEPHP_DISABLE') && (bool) TYPEPHP_DISABLE; $isTooling = false; $binary = ''; diff --git a/tests/TypeChecking/Generics/MutuallyRecursiveBoundsTest.php b/tests/TypeChecking/Generics/MutuallyRecursiveBoundsTest.php new file mode 100644 index 00000000..de9e0726 --- /dev/null +++ b/tests/TypeChecking/Generics/MutuallyRecursiveBoundsTest.php @@ -0,0 +1,556 @@ + + */ +final class MutualUser implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * @implements MutualComparable + */ +final class MutualAdmin implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * Implements MutualComparable, NOT MutualComparable + * + * @implements MutualComparable + */ +final class MutualMalicious implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * Valid asymmetric pair: Lock is comparable to Key, and Key is comparable to Lock + * + * @implements MutualComparable + */ +final class MutualLock implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * @implements MutualComparable + */ +final class MutualKey implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +class MutualBaseRole +{ +} + +/** + * @implements MutualComparable + */ +class MutualMemberRole extends MutualBaseRole implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * Implements MutualComparable (where SuperAdminRole is a subtype of MemberRole) + * + * @implements MutualComparable + */ +class MutualAdminRole extends MutualMemberRole implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * @implements MutualComparable + */ +class MutualSuperAdminRole extends MutualAdminRole implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * Implements MutualComparable (where BaseRole is a supertype of MemberRole) + * + * @implements MutualComparable + */ +class MutualBadSuperRole extends MutualAdminRole implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +/** + * Implements invariant MutualComparable (supertype of MutualBroadRole) + * + * @implements MutualComparable + */ +class MutualBroadRole extends MutualBaseRole implements MutualComparable +{ + public function compareTo(mixed $other): int + { + return 0; + } +} + +class CovariantBaseRole +{ +} + +/** + * @implements CovariantMutualComparable + */ +class CovariantMemberRole extends CovariantBaseRole implements CovariantMutualComparable +{ + public function getPartner(): mixed + { + return null; + } +} + +/** + * @implements CovariantMutualComparable + */ +class CovariantAdminRole extends CovariantMemberRole implements CovariantMutualComparable +{ + public function getPartner(): mixed + { + return null; + } +} + +class CovariantSuperAdminRole extends CovariantAdminRole +{ +} + +/** + * @implements CovariantMutualComparable + */ +class CovariantBadSuperRole extends CovariantAdminRole implements CovariantMutualComparable +{ + public function getPartner(): mixed + { + return null; + } +} + +class ContraBaseRole +{ +} + +/** + * Implements ContravariantMutualComparable (supertype of ContraSubRole) + * + * @implements ContravariantMutualComparable + */ +class ContraSubRole extends ContraBaseRole implements ContravariantMutualComparable +{ + public function acceptPartner(mixed $other): void + { + } +} + +class ContraSubSubRole extends ContraSubRole +{ +} + +/** + * Implements ContravariantMutualComparable (narrower subtype of ContraSubRole) + * + * @implements ContravariantMutualComparable + */ +class ContraNarrowRole extends ContraBaseRole implements ContravariantMutualComparable +{ + public function acceptPartner(mixed $other): void + { + } +} + +// ========================================================================= +// Functions & Classes Under Test +// ========================================================================= + +/** + * Standalone function with invariant mutually recursive bounds: + * T must be MutualComparable + * U must be MutualComparable + * + * @template T of MutualComparable + * @template U of MutualComparable + * + * @param T $a + * @param U $b + */ +function mutuallyRecursiveCompare(mixed $a, mixed $b): bool +{ + return true; +} + +/** + * Standalone function with class-string mutually recursive bounds + * + * @template T of MutualComparable + * @template U of MutualComparable + * + * @param class-string $classA + * @param class-string $classB + */ +function mutuallyRecursiveClassStrings(string $classA, string $classB): bool +{ + return true; +} + +/** + * Generic class with invariant mutually recursive bounds + * + * @template T of MutualComparable + * @template U of MutualComparable + */ +final class MutualPairBox +{ + /** + * @param T $first + * @param U $second + */ + public function __construct( + public mixed $first, + public mixed $second, + ) { + } +} + +/** + * Standalone function with declaration-site covariant mutually recursive bounds + * + * @template T of CovariantMutualComparable + * @template U of CovariantMutualComparable + * + * @param T $a + * @param U $b + */ +function covariantMutuallyRecursiveCompare(mixed $a, mixed $b): bool +{ + return true; +} + +/** + * Generic class with declaration-site covariant mutually recursive bounds + * + * @template T of CovariantMutualComparable + * @template U of CovariantMutualComparable + */ +final class CovariantMutualPairBox +{ + /** + * @param T $first + * @param U $second + */ + public function __construct( + public mixed $first, + public mixed $second, + ) { + } +} + +/** + * Standalone function with declaration-site contravariant mutually recursive bounds + * + * @template T of ContravariantMutualComparable + * @template U of ContravariantMutualComparable + * + * @param T $a + * @param U $b + */ +function contravariantMutuallyRecursiveCompare(mixed $a, mixed $b): bool +{ + return true; +} + +/** + * Generic class with declaration-site contravariant mutually recursive bounds + * + * @template T of ContravariantMutualComparable + * @template U of ContravariantMutualComparable + */ +final class ContravariantMutualPairBox +{ + /** + * @param T $first + * @param U $second + */ + public function __construct( + public mixed $first, + public mixed $second, + ) { + } +} + +/** + * Standalone function with use-site covariant mutually recursive bounds on invariant interface + * + * @template T of MutualComparable + * @template U of MutualComparable + * + * @param T $a + * @param U $b + */ +function useSiteCovariantMutualCompare(mixed $a, mixed $b): bool +{ + return true; +} + +/** + * Standalone function with use-site contravariant mutually recursive bounds on invariant interface + * + * @template T of MutualComparable + * @template U of MutualComparable + * + * @param T $a + * @param U $b + */ +function useSiteContravariantMutualCompare(mixed $a, mixed $b): bool +{ + return true; +} + +describe('Mutually Recursive Generic Bounds (@template T of Comparable, @template U of Comparable)', function () { + describe('1. Standalone Function Mutual Bounds', function () { + test('accepts valid identical-type mutual bounds (User, User)', function () { + expect(mutuallyRecursiveCompare(new MutualUser(), new MutualUser()))->toBeTrue(); + }); + + test('accepts valid distinct asymmetric mutual bounds (Lock, Key)', function () { + expect(mutuallyRecursiveCompare(new MutualLock(), new MutualKey()))->toBeTrue(); + expect(mutuallyRecursiveCompare(new MutualKey(), new MutualLock()))->toBeTrue(); + }); + + test('rejects mismatched types (User, Admin) where User is Comparable and Admin is Comparable', function () { + expect(fn () => mutuallyRecursiveCompare(new MutualUser(), new MutualAdmin())) + ->toThrow(TypeError::class) + ; + }); + + test('rejects (Malicious, Malicious) where Malicious implements Comparable instead of Comparable', function () { + expect(fn () => mutuallyRecursiveCompare(new MutualMalicious(), new MutualMalicious())) + ->toThrow(TypeError::class) + ; + }); + + test('rejects forward-reference mismatch (User, Malicious) where U satisfies Comparable but T violates Comparable', function () { + expect(fn () => mutuallyRecursiveCompare(new MutualUser(), new MutualMalicious())) + ->toThrow(TypeError::class) + ; + }); + + test('rejects reverse mismatch (Malicious, User) where T satisfies Comparable but U violates Comparable', function () { + expect(fn () => mutuallyRecursiveCompare(new MutualMalicious(), new MutualUser())) + ->toThrow(TypeError::class) + ; + }); + }); + + describe('2. Class-Level Mutual Bounds (MutualPairBox)', function () { + test('accepts valid MutualPairBox and MutualPairBox', function () { + /** @var MutualPairBox $userBox */ + $userBox = new MutualPairBox(new MutualUser(), new MutualUser()); + expect($userBox->first)->toBeInstanceOf(MutualUser::class); + + /** @var MutualPairBox $lockKeyBox */ + $lockKeyBox = new MutualPairBox(new MutualLock(), new MutualKey()); + expect($lockKeyBox->first)->toBeInstanceOf(MutualLock::class); + }); + + test('rejects invalid @var pre-binding MutualPairBox', function () { + expect(function () { + /** @var MutualPairBox $box */ + $box = new MutualPairBox(new MutualUser(), new MutualAdmin()); + })->toThrow(TypeError::class); + }); + + test('rejects invalid @var pre-binding MutualPairBox', function () { + expect(function () { + /** @var MutualPairBox $box */ + $box = new MutualPairBox(new MutualMalicious(), new MutualMalicious()); + })->toThrow(TypeError::class); + }); + + test('rejects invalid @var pre-binding MutualPairBox', function () { + expect(function () { + /** @var MutualPairBox $box */ + $box = new MutualPairBox(new MutualUser(), new MutualMalicious()); + })->toThrow(TypeError::class); + }); + + test('rejects unannotated constructor call new MutualPairBox(new MutualUser(), new MutualAdmin())', function () { + expect(fn () => new MutualPairBox(new MutualUser(), new MutualAdmin())) + ->toThrow(TypeError::class) + ; + }); + + test('rejects unannotated constructor call new MutualPairBox(new MutualUser(), new MutualMalicious())', function () { + expect(fn () => new MutualPairBox(new MutualUser(), new MutualMalicious())) + ->toThrow(TypeError::class) + ; + }); + }); + + describe('3. class-string & class-string Mutual Bounds', function () { + test('accepts valid mutually recursive class-strings', function () { + expect(mutuallyRecursiveClassStrings(MutualUser::class, MutualUser::class))->toBeTrue(); + expect(mutuallyRecursiveClassStrings(MutualLock::class, MutualKey::class))->toBeTrue(); + }); + + test('rejects mismatched class-strings (MutualUser::class, MutualAdmin::class)', function () { + expect(fn () => mutuallyRecursiveClassStrings(MutualUser::class, MutualAdmin::class)) + ->toThrow(TypeError::class) + ; + }); + + test('rejects forward-reference mismatched class-strings (MutualUser::class, MutualMalicious::class)', function () { + expect(fn () => mutuallyRecursiveClassStrings(MutualUser::class, MutualMalicious::class)) + ->toThrow(TypeError::class) + ; + }); + }); + + describe('4. Variance in Mutually Recursive Bounds (Invariance, Covariance, Contravariance & Use-Site)', function () { + test('strictly enforces invariance when MutualComparable is invariant (@template T)', function () { + expect(fn () => mutuallyRecursiveCompare(new MutualMemberRole(), new MutualAdminRole())) + ->toThrow(TypeError::class) + ; + + expect(function () { + /** @var MutualPairBox $box */ + $box = new MutualPairBox(new MutualMemberRole(), new MutualAdminRole()); + })->toThrow(TypeError::class); + + expect(fn () => mutuallyRecursiveClassStrings(MutualMemberRole::class, MutualAdminRole::class)) + ->toThrow(TypeError::class) + ; + }); + + test('allows covariant subtypes when interface declares @template-covariant T and rejects supertypes', function () { + expect(covariantMutuallyRecursiveCompare(new CovariantMemberRole(), new CovariantAdminRole()))->toBeTrue(); + + /** @var CovariantMutualPairBox $box */ + $box = new CovariantMutualPairBox(new CovariantMemberRole(), new CovariantAdminRole()); + expect($box->first)->toBeInstanceOf(CovariantMemberRole::class); + + expect(fn () => covariantMutuallyRecursiveCompare(new CovariantMemberRole(), new CovariantBadSuperRole())) + ->toThrow(TypeError::class) + ; + + expect(function () { + /** @var CovariantMutualPairBox $badBox */ + $badBox = new CovariantMutualPairBox(new CovariantMemberRole(), new CovariantBadSuperRole()); + })->toThrow(TypeError::class); + }); + + test('allows contravariant supertypes when interface declares @template-contravariant T and rejects subtypes', function () { + expect(contravariantMutuallyRecursiveCompare(new ContraSubRole(), new ContraSubRole()))->toBeTrue(); + + /** @var ContravariantMutualPairBox $box */ + $box = new ContravariantMutualPairBox(new ContraSubRole(), new ContraSubRole()); + expect($box->first)->toBeInstanceOf(ContraSubRole::class); + + expect(fn () => contravariantMutuallyRecursiveCompare(new ContraSubRole(), new ContraNarrowRole())) + ->toThrow(TypeError::class) + ; + + expect(function () { + /** @var ContravariantMutualPairBox $badBox */ + $badBox = new ContravariantMutualPairBox(new ContraSubRole(), new ContraNarrowRole()); + })->toThrow(TypeError::class); + }); + + test('respects use-site covariance () and use-site contravariance () on invariant interface', function () { + expect(useSiteCovariantMutualCompare(new MutualMemberRole(), new MutualAdminRole()))->toBeTrue(); + + expect(fn () => useSiteCovariantMutualCompare(new MutualMemberRole(), new MutualBadSuperRole())) + ->toThrow(TypeError::class) + ; + + expect(useSiteContravariantMutualCompare(new MutualBroadRole(), new MutualBroadRole()))->toBeTrue(); + + expect(fn () => mutuallyRecursiveCompare(new MutualBroadRole(), new MutualBroadRole())) + ->toThrow(TypeError::class) + ; + }); + }); +});