From 4f1b7c37aa773dcdd65a3c015a4a031ca4af20ce Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 11:42:42 +0800 Subject: [PATCH 01/37] Enhance type inference and validation in ParamChecker, TemplateManager, and RuntimeTypeChecker; add tests for iterable object handling and ignore tag support in callables Find in noctud collection report.. --- src/Internal/Checker/ParamChecker.php | 124 ++++++++++++- src/Internal/Generics/TemplateManager.php | 76 ++++++-- src/Internal/RuntimeTypeChecker.php | 11 +- src/Internal/Validator/GenericValidator.php | 4 +- src/Internal/Wrapper/CallableWrapper.php | 25 +++ src/Internal/Wrapper/IterableWrapper.php | 9 + tests/Internal/RuntimeTypeCheckerTest.php | 31 ++++ .../CallableAndIteratorIgnoreTagTest.php | 152 ++++++++++++++++ .../InheritedCompoundTemplateTest.php | 114 ++++++++++++ .../Generics/IterableObjectInferenceTest.php | 171 ++++++++++++++++++ 10 files changed, 695 insertions(+), 22 deletions(-) create mode 100644 tests/TypeChecking/CallablesAndIterators/CallableAndIteratorIgnoreTagTest.php create mode 100644 tests/TypeChecking/Generics/InheritedCompoundTemplateTest.php create mode 100644 tests/TypeChecking/Generics/IterableObjectInferenceTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 50b1cb7d..80b96afb 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -15,6 +15,7 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use TypePHP\Internal\Ast\Elimination\Evaluator\GeneratorEvaluator; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; @@ -46,6 +47,16 @@ final class ParamChecker 'traversable' => true, ]; + /** + * O(1) lookup table for iterable/generator object container types. + */ + private const TRAVERSABLE_OBJECT_TYPES = [ + 'iterable' => true, + 'traversable' => true, + 'generator' => true, + 'iterator' => true, + ]; + /** * O(1) lookup table for all collection and slice container types. */ @@ -1051,16 +1062,20 @@ private static function getSampleArraySlice(array $arrVal): array * ensuring it satisfies declared upper bounds. * * @param array $templates + * @param array $classTemplates */ private static function bindTemplateIfUnbound( string $templateName, TypeNode $inferredType, string $effectiveFunction, ?object $thisObj, - array $templates + array $templates, + array $classTemplates = [] ): void { - $contract = DocblockParser::parse($effectiveFunction); - $classTemplates = $contract['classTemplates'] ?? []; + if ($classTemplates === []) { + $contract = DocblockParser::parse($effectiveFunction); + $classTemplates = $contract['classTemplates'] ?? []; + } $isClassLevelTemplate = ! TemplateManager::isMethodTemplate($effectiveFunction, $templateName) && isset($classTemplates[$templateName]); $targetObj = $isClassLevelTemplate ? $thisObj : null; @@ -1131,6 +1146,13 @@ private static function inferGenericObjectNode( if ($typeNode instanceof GenericTypeNode && \is_object($value)) { $baseName = strtolower((string) $typeNode->type); + + if ($value instanceof \Traversable && isset(self::TRAVERSABLE_OBJECT_TYPES[$baseName])) { + self::inferTemplatesFromIterableObject($typeNode, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); + + return; + } + if (isset(self::COLLECTION_TYPES[$baseName])) { return; } @@ -1229,6 +1251,102 @@ private static function inferGenericObjectNode( } } + /** + * Infers key and value template parameters when an object (Generator or Traversable) + * is passed to an iterable or iterable parameter. + * + * @param array $templates + * @param array $classTemplates + */ + private static function inferTemplatesFromIterableObject( + GenericTypeNode $typeNode, + object $value, + string $effectiveFunction, + ?object $thisObj, + array $templates, + array $classTemplates = [] + ): void { + $inferredKey = null; + $inferredVal = null; + + if ($value instanceof \Generator) { + try { + $refGen = new \ReflectionGenerator($value); + $genFunc = $refGen->getFunction(); + $genDoc = $genFunc->getDocComment(); + if ($genDoc !== false) { + $phpDocNode = DocblockExtractor::parseDocString($genDoc); + $returnTag = DocblockExtractor::getReturnTag($phpDocNode); + if ($returnTag !== null) { + $genContract = GeneratorEvaluator::extractContract($returnTag->type); + if ($genContract !== null) { + $inferredKey = $genContract['key']; + $inferredVal = $genContract['value']; + + $genThis = $refGen->getThis(); + if ($genThis !== null) { + $boundOnGenThis = TemplateManager::getBoundTemplatesForInstance($genThis); + if ($boundOnGenThis !== []) { + if ($inferredKey !== null) { + $inferredKey = TemplateSubstitutor::substitute($inferredKey, $boundOnGenThis); + } + if ($inferredVal !== null) { + $inferredVal = TemplateSubstitutor::substitute($inferredVal, $boundOnGenThis); + } + } + } + } + } + } + } catch (\Throwable) { + } + } elseif ($value instanceof \Traversable) { + $boundOnInstance = TemplateManager::getBoundTemplatesForInstance($value); + if ($boundOnInstance !== []) { + $keyTName = null; + $valTName = null; + + foreach ($boundOnInstance as $tName => $tNode) { + $lower = strtolower($tName); + if ($lower === 'k' || $lower === 'key' || $lower === 'tkey') { + $keyTName = $tName; + } else { + $valTName = $tName; + } + } + + if ($keyTName !== null) { + $inferredKey = $boundOnInstance[$keyTName]; + } + if ($valTName !== null) { + $inferredVal = $boundOnInstance[$valTName]; + } elseif (\count($boundOnInstance) === 1) { + $inferredVal = reset($boundOnInstance); + } + } + } + + $genericCount = \count($typeNode->genericTypes); + + if ($genericCount === 1) { + $valTarget = $typeNode->genericTypes[0]; + if ($valTarget instanceof IdentifierTypeNode && isset($templates[$valTarget->name]) && $inferredVal !== null) { + self::bindTemplateIfUnbound($valTarget->name, $inferredVal, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + } elseif ($genericCount >= 2) { + $keyTarget = $typeNode->genericTypes[0]; + $valTarget = $typeNode->genericTypes[1]; + + if ($keyTarget instanceof IdentifierTypeNode && isset($templates[$keyTarget->name]) && $inferredKey !== null) { + self::bindTemplateIfUnbound($keyTarget->name, $inferredKey, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + + if ($valTarget instanceof IdentifierTypeNode && isset($templates[$valTarget->name]) && $inferredVal !== null) { + self::bindTemplateIfUnbound($valTarget->name, $inferredVal, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + } + } + /** * Unified single-parameter validation pipeline. * diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 80507ec4..29c7892f 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -408,6 +408,14 @@ final class TemplateManager */ private static array $declaredClassTemplateNamesCache = []; + /** + * Cache for raw (unsubstituted) inherited template mappings per class name: + * [$className] => array. + * + * @var array> + */ + private static array $classInheritedRawMappingsCache = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -417,6 +425,7 @@ public static function reset(): void self::$callStackBindings = []; self::$classHierarchyTemplatesCache = []; self::$classInheritedBindingsCache = []; + self::$classInheritedRawMappingsCache = []; self::$subclassCache = []; self::$realTypeSymbolCache = []; self::$pendingCloneSource = null; @@ -529,7 +538,11 @@ public static function getClassInheritedBindings(string $className): array return self::$classInheritedBindingsCache[$className] = []; } - return self::$classInheritedBindingsCache[$className] = self::computeClassInheritedBindings($className); + $rawBindings = []; + $resolved = self::computeClassInheritedBindings($className, $rawBindings); + self::$classInheritedRawMappingsCache[$className] = $rawBindings; + + return self::$classInheritedBindingsCache[$className] = $resolved; } /** @@ -903,6 +916,14 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ self::$instanceTemplateBindings ??= new WeakMap(); $bindings = self::$instanceTemplateBindings[$thisObj] ?? []; $bindings[$templateName] = $inferredType; + + $rawMappings = self::$classInheritedRawMappingsCache[$thisObj::class] ?? []; + foreach ($rawMappings as $tName => $rawNode) { + if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { + $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + } + } + self::$instanceTemplateBindings[$thisObj] = $bindings; } else { if (! self::hasCallFrame($function)) { @@ -1206,7 +1227,16 @@ private static function bindSingleTemplateArgument( if ($forceBind || ! isset($existingBindings[$templateName])) { $bindings = self::$instanceTemplateBindings[$instance] ?? []; - $bindings[$templateName] = $isWildcardOrMixed && $templateTag->bound !== null ? $templateTag->bound : $expectedTypeNode; + $boundNode = $isWildcardOrMixed && $templateTag->bound !== null ? $templateTag->bound : $expectedTypeNode; + $bindings[$templateName] = $boundNode; + + $rawMappings = self::$classInheritedRawMappingsCache[$instance::class] ?? []; + foreach ($rawMappings as $tName => $rawNode) { + if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { + $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + } + } + self::$instanceTemplateBindings[$instance] = $bindings; } @@ -1222,26 +1252,36 @@ public static function resolveInheritedTemplates(object $instance, string $targe $actualClassName = $instance::class; self::$instanceTemplateBindings ??= new WeakMap(); - if (isset(self::$classInheritedBindingsCache[$actualClassName])) { - /** @var array $cachedBindings */ - $cachedBindings = self::$classInheritedBindingsCache[$actualClassName]; - $existing = self::$instanceTemplateBindings[$instance] ?? []; - self::$instanceTemplateBindings[$instance] = [...$cachedBindings, ...$existing]; - - return; + if (! isset(self::$classInheritedBindingsCache[$actualClassName])) { + $rawBindings = []; + $resolvedClassBindings = self::computeClassInheritedBindings($actualClassName, $rawBindings); + self::$classInheritedBindingsCache[$actualClassName] = $resolvedClassBindings; + self::$classInheritedRawMappingsCache[$actualClassName] = $rawBindings; } - $resolvedClassBindings = self::computeClassInheritedBindings($actualClassName); - self::$classInheritedBindingsCache[$actualClassName] = $resolvedClassBindings; - + $cachedBindings = self::$classInheritedBindingsCache[$actualClassName]; + $rawMappings = self::$classInheritedRawMappingsCache[$actualClassName] ?? []; $existing = self::$instanceTemplateBindings[$instance] ?? []; - self::$instanceTemplateBindings[$instance] = [...$resolvedClassBindings, ...$existing]; + + $specializedBindings = []; + foreach ($cachedBindings as $tName => $fallbackTypeNode) { + $rawNode = $rawMappings[$tName] ?? $fallbackTypeNode; + if ($existing !== [] && DocblockParser::typeReferencesTemplate($rawNode, $existing)) { + $specializedBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $existing); + } else { + $specializedBindings[$tName] = $existing[$tName] ?? $fallbackTypeNode; + } + } + + self::$instanceTemplateBindings[$instance] = [...$existing, ...$specializedBindings]; } /** + * @param array $rawBindings + * * @return array */ - private static function computeClassInheritedBindings(string $actualClassName): array + private static function computeClassInheritedBindings(string $actualClassName, array &$rawBindings = []): array { /** @var array $bindings */ $bindings = []; @@ -1273,7 +1313,7 @@ private static function computeClassInheritedBindings(string $actualClassName): foreach ($inheritedTags as $inheritedTag) { $genericTypeNode = $inheritedTag->type; if ($genericTypeNode instanceof GenericTypeNode) { - self::collectInheritedGenericTagBindings($genericTypeNode, $hierClass, $declaredTemplateNames, $actualClassName, $bindings); + self::collectInheritedGenericTagBindings($genericTypeNode, $hierClass, $declaredTemplateNames, $actualClassName, $bindings, $rawBindings); } } } @@ -1288,6 +1328,7 @@ private static function computeClassInheritedBindings(string $actualClassName): /** * @param array $declaredTemplateNames * @param array $bindings + * @param array $rawBindings * @param \ReflectionClass $hierClass */ private static function collectInheritedGenericTagBindings( @@ -1295,7 +1336,8 @@ private static function collectInheritedGenericTagBindings( \ReflectionClass $hierClass, array $declaredTemplateNames, string $actualClassName, - array &$bindings + array &$bindings, + array &$rawBindings = [] ): void { $parentName = SpecialTypeResolver::resolveFqcn((string) $genericTypeNode->type, $hierClass); $isHierarchyMember = is_a($actualClassName, $parentName, true) || trait_exists($parentName); @@ -1377,6 +1419,8 @@ private static function collectInheritedGenericTagBindings( } } + $rawBindings[$templateName] ??= $resolved; + if (DocblockParser::typeReferencesTemplate($resolved, $declaredTemplateNames) && $hierFallbackBindings !== []) { $resolved = TemplateSubstitutor::substitute($resolved, $hierFallbackBindings); } diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 30c22550..ccef9db1 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -357,8 +357,17 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t return null; } + $kind = 'parameter'; + if (str_contains($context, 'Return value')) { + $kind = 'return'; + } elseif (str_contains($context, 'Property ')) { + $kind = 'property'; + } elseif (str_contains($context, 'Variable ')) { + $kind = 'variable'; + } + /** @var ErrorMessage|null $handled */ - $handled = ViolationCollector::handle($err, 'parameter', null, function: $context); + $handled = ViolationCollector::handle($err, $kind, null, function: $context); return $handled; } diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 82e714a0..b6c62f91 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -19,7 +19,7 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; -use TypePHP\Internal\RuntimeTypeChecker; +use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; @@ -817,7 +817,7 @@ private function validateObjectGeneric(mixed $value, GenericTypeNode $node, stri return ErrorFactory::createError($context . ' must be an instance of ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } - return RuntimeTypeChecker::bindInstanceFromNode($value, $node, $context); + return TemplateManager::bindInstanceFromNode($value, $node, $context); } /** diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index d461624f..90aab253 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -31,6 +31,7 @@ use TypePHP\Internal\Reporting\ViolationCollector; use TypePHP\Internal\Resolver\CallerBoundaryResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\IgnoreManager; use TypePHP\Internal\Validator\TypeValidatorRegistry; /** @@ -486,6 +487,10 @@ private static function inferLocalTemplateFromParam( return; } + if (IgnoreManager::isCallerIgnored()) { + return; + } + $handled = ViolationCollector::handle($boundErr, 'callback', null); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($boundErr->getMessage())); @@ -617,6 +622,10 @@ private static function validateCallbackReturn( $err = $registry->validate($result, $typeNode->returnType, "$prefix return value"); if ($err !== null) { if (! CallerBoundaryResolver::shouldBypassCallback($callable, $prefix)) { + if (IgnoreManager::isCallerIgnored()) { + return $result; + } + $handled = ViolationCollector::handle($err, 'callback', $result); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); @@ -642,6 +651,10 @@ private static function enforceClosureConstraints(string $identifierName, mixed return; } + if (IgnoreManager::isCallerIgnored()) { + return; + } + $err = new ErrorMessage($prefix . ' must be of type Closure, ' . TypeFormatter::formatGivenValue($callable) . ' given'); $handled = ViolationCollector::handle($err, 'callback', null); @@ -657,6 +670,10 @@ private static function enforceClosureConstraints(string $identifierName, mixed return; } + if (IgnoreManager::isCallerIgnored()) { + return; + } + $err = new ErrorMessage($prefix . ' must be a static Closure (not bound to $this)'); $handled = ViolationCollector::handle($err, 'callback', null); @@ -722,6 +739,10 @@ private static function validateCallbackArguments( continue; } + if (IgnoreManager::isCallerIgnored()) { + continue; + } + $handled = ViolationCollector::handle($err, 'callback', null); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); @@ -790,6 +811,10 @@ private static function validateCallbackByRefMutations( continue; } + if (IgnoreManager::isCallerIgnored()) { + continue; + } + $handled = ViolationCollector::handle($err, 'callback', null); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 5d0c7e5f..1a9e15a7 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -20,6 +20,7 @@ use TypePHP\Internal\Reporting\ViolationCollector; use TypePHP\Internal\Resolver\CallerBoundaryResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\IgnoreManager; use TypePHP\Internal\Validator\TypeValidatorRegistry; /** @@ -209,6 +210,10 @@ private static function createValidationCallback( return; } + if (IgnoreManager::isCallerIgnored()) { + return; + } + $handled = ViolationCollector::handle($err, 'yield', null, function: $function); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); @@ -227,6 +232,10 @@ private static function createValidationCallback( return; } + if (IgnoreManager::isCallerIgnored()) { + return; + } + $handled = ViolationCollector::handle($err, 'yield', null, function: $function); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index 7e6eef3f..9e2ad4c2 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -9,6 +9,7 @@ use TypePHP\Internal\Checker\SelfOutChecker; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Generics\TemplateManager; +use TypePHP\Internal\Reporting\ViolationCollector; use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Validator\TypeValidatorRegistry; @@ -860,4 +861,34 @@ function vendorAction(): void ); expect($ignored)->toBe('not_an_int'); }); + + test('bindInstanceFromNode infers violation kind from context string', function () { + Config::set(['on_violation' => 'report']); + ViolationCollector::clear(); + + $dog = new Container(new Dog()); + $badNode = new GenericTypeNode(new IdentifierTypeNode(Container::class), [new IdentifierTypeNode(Cat::class)]); + + RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, 'App\Service::process(): Argument $container'); + $violations = ViolationCollector::getViolations(); + expect($violations)->toHaveCount(1) + ->and($violations[0]->kind)->toBe('parameter') + ; + + ViolationCollector::clear(); + + RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, 'App\Service::process(): Return value'); + $violations = ViolationCollector::getViolations(); + expect($violations)->toHaveCount(1) + ->and($violations[0]->kind)->toBe('return') + ; + + ViolationCollector::clear(); + + RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, 'Property App\Service::$container'); + $violations = ViolationCollector::getViolations(); + expect($violations)->toHaveCount(1) + ->and($violations[0]->kind)->toBe('property') + ; + }); }); diff --git a/tests/TypeChecking/CallablesAndIterators/CallableAndIteratorIgnoreTagTest.php b/tests/TypeChecking/CallablesAndIterators/CallableAndIteratorIgnoreTagTest.php new file mode 100644 index 00000000..4c9776f4 --- /dev/null +++ b/tests/TypeChecking/CallablesAndIterators/CallableAndIteratorIgnoreTagTest.php @@ -0,0 +1,152 @@ + $items + * + * @return array + */ +function consumeIterableWithContract(iterable $items): array +{ + $result = []; + foreach ($items as $k => $v) { + $result[$k] = $v; + } + + return $result; +} + +class IgnoredCallableCaller +{ + /** + * Deliberately annotated with @typephp-ignore to test bypass. + * + * @typephp-ignore + */ + public function runIgnoredCallbackReturn(): mixed + { + return invokeCallbackWithReturnContract(function (int $n): int { + return 100; + }); + } + + /** + * Deliberately annotated with @typephp-ignore to test bypass. + * + * @typephp-ignore + */ + public function runIgnoredCallbackParam(): void + { + invokeCallbackWithParamContract(function ($s): void { + }, 555); + } + + /** + * Deliberately annotated with @typephp-ignore to test bypass. + * + * @typephp-ignore + */ + public function runIgnoredIterableParam(): array + { + return consumeIterableWithContract([1 => 999]); + } +} + +class UnignoredCallableCaller +{ + public function runUnignoredCallbackReturn(): mixed + { + return invokeCallbackWithReturnContract(function (int $n): int { + return 100; + }); + } + + public function runUnignoredCallbackParam(): void + { + invokeCallbackWithParamContract(function ($s): void { + }, 555); + } + + public function runUnignoredIterableParam(): array + { + return consumeIterableWithContract([1 => 999]); + } +} + +describe('Ignore Tag Support in Callables and Iterators (@typephp-ignore)', function () { + test('unignored caller throws TypeError when callback return type is violated', function () { + $caller = new UnignoredCallableCaller(); + + expect(fn () => $caller->runUnignoredCallbackReturn()) + ->toThrow(TypeError::class) + ; + }); + + test('unignored caller throws TypeError when callback parameter type is violated', function () { + $caller = new UnignoredCallableCaller(); + + expect(fn () => $caller->runUnignoredCallbackParam()) + ->toThrow(TypeError::class) + ; + }); + + test('unignored caller throws TypeError when iterable item type is violated', function () { + $caller = new UnignoredCallableCaller(); + + expect(fn () => $caller->runUnignoredIterableParam()) + ->toThrow(TypeError::class) + ; + }); + + test('caller with @typephp-ignore bypasses callback return type violation', function () { + $caller = new IgnoredCallableCaller(); + + expect($caller->runIgnoredCallbackReturn())->toBe(100); + }); + + test('caller with @typephp-ignore bypasses callback parameter type violation', function () { + $caller = new IgnoredCallableCaller(); + + $caller->runIgnoredCallbackParam(); + expect(true)->toBeTrue(); + }); + + test('caller with @typephp-ignore bypasses iterable wrapper item type violation', function () { + $caller = new IgnoredCallableCaller(); + + $items = $caller->runIgnoredIterableParam(); + expect($items)->toBe([1 => 999]); + }); +}); diff --git a/tests/TypeChecking/Generics/InheritedCompoundTemplateTest.php b/tests/TypeChecking/Generics/InheritedCompoundTemplateTest.php new file mode 100644 index 00000000..8d5c84f8 --- /dev/null +++ b/tests/TypeChecking/Generics/InheritedCompoundTemplateTest.php @@ -0,0 +1,114 @@ + or Collection). + * + * @template TElement + */ +interface InheritedContainer +{ + /** + * @return TElement + */ + public function first(): mixed; +} + +/** + * Two-template data class (like MapEntry). + * + * @template TKey of string|int + * @template TValue + */ +class InheritedPair +{ + /** + * @param TKey $key + * @param TValue $value + */ + public function __construct(public mixed $key, public mixed $value) + { + } +} + +/** + * Generic class implementing an interface parameterized by a compound type that + * forwards its own declared templates: @implements InheritedContainer>. + * + * (Mirrors MapEntrySet: @implements Set>) + * + * @template K of string|int + * @template V + * + * @implements InheritedContainer> + */ +class InheritedPairContainer implements InheritedContainer +{ + /** + * @param K $key + * @param V $value + */ + public function __construct(public mixed $key, public mixed $value) + { + } + + /** + * @return InheritedPair + */ + public function first(): InheritedPair + { + return new InheritedPair($this->key, $this->value); + } +} + +/** + * Service holding a specialized container property (like Map::$entries). + */ +class InheritedConsumer +{ + /** + * @var InheritedContainer> + */ + public InheritedContainer $container; + + /** + * @param InheritedContainer> $container + */ + public function setContainer(InheritedContainer $container): void + { + $this->container = $container; + } + + /** + * @return InheritedContainer> + */ + public function getContainer(): InheritedContainer + { + return $this->container; + } +} + +describe('Inherited Generic Template Forwarding (Compound Template Mapping)', function () { + test('parameter check preserves specialized child templates on inherited interface', function () { + $consumer = new InheritedConsumer(); + + $container = new InheritedPairContainer('age', 30); + + $consumer->setContainer($container); + + expect($consumer->container->first()->key)->toBe('age'); + expect($consumer->container->first()->value)->toBe(30); + }); + + test('return check preserves specialized child templates on inherited interface', function () { + $consumer = new InheritedConsumer(); + $consumer->container = new InheritedPairContainer('age', 30); + + $returned = $consumer->getContainer(); + + expect($returned)->toBeInstanceOf(InheritedContainer::class); + }); +}); diff --git a/tests/TypeChecking/Generics/IterableObjectInferenceTest.php b/tests/TypeChecking/Generics/IterableObjectInferenceTest.php new file mode 100644 index 00000000..0f07490f --- /dev/null +++ b/tests/TypeChecking/Generics/IterableObjectInferenceTest.php @@ -0,0 +1,171 @@ + + */ +class GenericKeyValueSource implements IteratorAggregate +{ + /** + * @param array $data + */ + public function __construct(private array $data) + { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->data); + } +} + +/** + * Generic container storing an iterable source. + * + * @template K of string|int + * @template V + */ +class GenericBoxedMap +{ + /** + * @param iterable $source + */ + public function __construct(public iterable $source) + { + } +} + +/** + * Factory function that accepts iterable and returns GenericBoxedMap. + * + * (Mirrors mapOf(iterable $data): ImmutableMap) + * + * @template K of string|int + * @template V + * + * @param iterable $source + * + * @return GenericBoxedMap + */ +function createBoxedMap(iterable $source): GenericBoxedMap +{ + return new GenericBoxedMap($source); +} + +/** + * Consumer function requiring GenericBoxedMap with exact concrete types. + * + * @param GenericBoxedMap $map + * + * @return bool + */ +function consumeBoxedMap(GenericBoxedMap $map): bool +{ + return true; +} + +/** + * Generator function producing string keys and int values. + * + * @return Generator + */ +function generateKeyValues(): Generator +{ + yield 'apples' => 10; + yield 'oranges' => 20; +} + +/** + * Generic single-template container. + * + * @template T + */ +class GenericBoxedList +{ + /** + * @param iterable $source + */ + public function __construct(public iterable $source) + { + } +} + +/** + * Factory function accepting iterable and returning GenericBoxedList. + * + * (Mirrors listOf(iterable $data): ImmutableList) + * + * @template T + * + * @param iterable $source + * + * @return GenericBoxedList + */ +function createBoxedList(iterable $source): GenericBoxedList +{ + return new GenericBoxedList($source); +} + +/** + * Consumer function requiring GenericBoxedList with concrete type string. + * + * @param GenericBoxedList $list + * + * @return bool + */ +function consumeBoxedList(GenericBoxedList $list): bool +{ + return true; +} + +/** + * Generator producing string values. + * + * @return Generator + */ +function generateStringList(): Generator +{ + yield 'hello'; + yield 'world'; +} + +describe('Generic Template Inference from Traversable & Generator Objects', function () { + test('infers key and value template arguments from a generic IteratorAggregate object passed to iterable', function () { + $source = new GenericKeyValueSource(['apples' => 10, 'oranges' => 20]); + $boxed = createBoxedMap($source); + + expect(consumeBoxedMap($boxed))->toBeTrue(); + }); + + test('infers key and value template arguments from a typed Generator passed to iterable', function () { + $gen = generateKeyValues(); + + $boxed = createBoxedMap($gen); + + expect(consumeBoxedMap($boxed))->toBeTrue(); + }); + + test('infers single template argument from a typed Generator passed to iterable', function () { + $gen = generateStringList(); + + $boxed = createBoxedList($gen); + + expect(consumeBoxedList($boxed))->toBeTrue(); + }); +}); From fbac1bb3d31e5b8fdb32322b779e1cd0ef02ebf4 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 15:57:07 +0800 Subject: [PATCH 02/37] Enhance ParamChecker and TemplateManager with improved type inference; add UnboundGeneratorTemplateTest for verifying template behavior in generators --- src/Internal/Checker/ParamChecker.php | 163 ++++++++++++++-- src/Internal/Generics/TemplateManager.php | 120 +++++++++++- .../UnboundGeneratorTemplateTest.php | 177 ++++++++++++++++++ 3 files changed, 443 insertions(+), 17 deletions(-) create mode 100644 tests/TypeChecking/CallablesAndIterators/UnboundGeneratorTemplateTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 80b96afb..c5fba1b4 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -582,7 +582,7 @@ private static function preInferGenericTemplates( } /** - * Infers generic template parameters from closure parameter typehints. + * Infers generic template parameters from closure parameter typehints and return types. * * @param array $types * @param array $vars @@ -634,12 +634,147 @@ private static function inferTemplatesFromClosures( } } } + + self::inferClosureReturnTemplate( + $cTypeNode->returnType, + $refClosure, + $effectiveFunction, + $thisObj, + $templates, + $classTemplates + ); } catch (\Throwable $e) { // Silently ignore reflection errors } } } + /** + * Infers a return-type template parameter from a closure's declared return type. + * + * Handles direct templates (: R), nullables (: ?R), and union pairs (: R|null) such as in mapNotNull. + * + * @param array $templates + * @param array $classTemplates + */ + private static function inferClosureReturnTemplate( + TypeNode $returnTypeNode, + \ReflectionFunction $refClosure, + string $effectiveFunction, + ?object $thisObj, + array $templates, + array $classTemplates + ): void { + if (! $refClosure->hasReturnType()) { + return; + } + + $templateName = null; + $unwrapNullable = false; + + if ($returnTypeNode instanceof IdentifierTypeNode && isset($templates[$returnTypeNode->name])) { + $templateName = $returnTypeNode->name; + } elseif ($returnTypeNode instanceof NullableTypeNode && $returnTypeNode->type instanceof IdentifierTypeNode && isset($templates[$returnTypeNode->type->name])) { + $templateName = $returnTypeNode->type->name; + $unwrapNullable = true; + } elseif ($returnTypeNode instanceof UnionTypeNode) { + $foundTemplate = null; + $hasNull = false; + foreach ($returnTypeNode->types as $member) { + if ($member instanceof IdentifierTypeNode) { + if (strtolower($member->name) === 'null') { + $hasNull = true; + } elseif (isset($templates[$member->name])) { + $foundTemplate = $member->name; + } + } + } + if ($foundTemplate !== null && $hasNull && \count($returnTypeNode->types) === 2) { + $templateName = $foundTemplate; + $unwrapNullable = true; + } + } + + if ($templateName === null) { + return; + } + + $isClassLevel = ! TemplateManager::isMethodTemplate($effectiveFunction, $templateName) && isset($classTemplates[$templateName]); + $targetObj = $isClassLevel ? $thisObj : null; + + if (TemplateManager::isBound($effectiveFunction, $targetObj, $templateName)) { + return; + } + + $inferred = self::extractTypeFromReflectionType($refClosure->getReturnType()); + if ($inferred === null) { + return; + } + + if ($unwrapNullable && $inferred instanceof NullableTypeNode) { + $inferred = $inferred->type; + } + + $templateTag = $templates[$templateName]; + $satisfiesBound = true; + + if ($templateTag->bound !== null) { + $resolvedBound = SpecialTypeResolver::resolve($templateTag->bound, $effectiveFunction, $thisObj); + $satisfiesBound = TemplateManager::checkVariance($inferred, $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT); + } + + if ($satisfiesBound) { + TemplateManager::bindTemplate($effectiveFunction, $targetObj, $templateName, $inferred); + } + } + + /** + * Extracts an inferred TypeNode from a ReflectionType object, ignoring unconstrained types. + */ + private static function extractTypeFromReflectionType(?\ReflectionType $type): ?TypeNode + { + if ($type === null) { + return null; + } + + if ($type instanceof \ReflectionNamedType) { + $name = $type->getName(); + if ($name === 'mixed' || $name === 'void' || $name === 'never') { + return null; + } + + if (class_exists($name) || interface_exists($name) || SpecialTypeResolver::isBuiltInTypeKeyword($name)) { + $node = new IdentifierTypeNode($name); + + return $type->allowsNull() && $name !== 'null' ? new NullableTypeNode($node) : $node; + } + } elseif ($type instanceof \ReflectionUnionType) { + $members = []; + foreach ($type->getTypes() as $subType) { + $extracted = self::extractTypeFromReflectionType($subType); + if ($extracted !== null) { + $members[] = $extracted; + } + } + if ($members !== []) { + return \count($members) === 1 ? $members[0] : new UnionTypeNode($members); + } + } elseif ($type instanceof \ReflectionIntersectionType) { + $members = []; + foreach ($type->getTypes() as $subType) { + $extracted = self::extractTypeFromReflectionType($subType); + if ($extracted !== null) { + $members[] = $extracted; + } + } + if ($members !== []) { + return \count($members) === 1 ? $members[0] : new IntersectionTypeNode($members); + } + } + + return null; + } + /** * @param array $types * @@ -1284,16 +1419,22 @@ private static function inferTemplatesFromIterableObject( $inferredVal = $genContract['value']; $genThis = $refGen->getThis(); - if ($genThis !== null) { - $boundOnGenThis = TemplateManager::getBoundTemplatesForInstance($genThis); - if ($boundOnGenThis !== []) { - if ($inferredKey !== null) { - $inferredKey = TemplateSubstitutor::substitute($inferredKey, $boundOnGenThis); - } - if ($inferredVal !== null) { - $inferredVal = TemplateSubstitutor::substitute($inferredVal, $boundOnGenThis); - } - } + $boundOnGenThis = ($genThis !== null) + ? TemplateManager::getBoundTemplatesForInstance($genThis) + : []; + + $genMethodTemplates = DocblockExtractor::extractTemplates($phpDocNode); + $genClassTemplates = []; + if ($genFunc instanceof \ReflectionMethod) { + $genClassTemplates = DocblockParser::parseClassTemplates($genFunc->getDeclaringClass()->getName()); + } + $allGenDeclaredTemplates = [...$genClassTemplates, ...$genMethodTemplates]; + + if ($inferredKey !== null) { + $inferredKey = TemplateSubstitutor::substitute($inferredKey, $boundOnGenThis, $allGenDeclaredTemplates); + } + if ($inferredVal !== null) { + $inferredVal = TemplateSubstitutor::substitute($inferredVal, $boundOnGenThis, $allGenDeclaredTemplates); } } } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 29c7892f..ca6ae92d 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -4,6 +4,7 @@ namespace TypePHP\Internal\Generics; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; @@ -1184,12 +1185,11 @@ private static function bindSingleTemplateArgument( return null; } - $isDefaultOrBound = ($existingTypeNode instanceof IdentifierTypeNode) && ( - strtolower($existingTypeNode->name) === 'mixed' - || strtolower($existingTypeNode->name) === 'array-key' - || ($templateTag->bound !== null && (string) $existingTypeNode === (string) $templateTag->bound) - || ($templateTag->default !== null && (string) $existingTypeNode === (string) $templateTag->default) - ); + $isDefaultOrBound = self::isUnspecializedType($existingTypeNode) + || ($existingTypeNode instanceof IdentifierTypeNode && ( + ($templateTag->bound !== null && (string) $existingTypeNode === (string) $templateTag->bound) + || ($templateTag->default !== null && (string) $existingTypeNode === (string) $templateTag->default) + )); if (self::checkVariance($expectedTypeNode, $existingTypeNode, GenericTypeNode::VARIANCE_COVARIANT)) { if ($isDefaultOrBound || ($isReturnContext && ! $strictInvariance)) { @@ -1243,6 +1243,106 @@ private static function bindSingleTemplateArgument( return null; } + /** + * Checks if a type node contains unspecialized type placeholders (mixed, array-key, or *). + */ + public static function isUnspecializedType(TypeNode $node): bool + { + if ($node instanceof IdentifierTypeNode) { + $lower = strtolower($node->name); + + return $lower === 'mixed' || $lower === 'array-key' || $lower === '*'; + } + + if ($node instanceof ArrayTypeNode) { + return self::isUnspecializedType($node->type); + } + + if ($node instanceof GenericTypeNode) { + foreach ($node->genericTypes as $gt) { + if (self::isUnspecializedType($gt)) { + return true; + } + } + } + + if ($node instanceof ArrayShapeNode) { + foreach ($node->items as $item) { + if (self::isUnspecializedType($item->valueType)) { + return true; + } + } + } + + return false; + } + + /** + * Recursively verifies variance across array shape elements. + */ + private static function checkNestedArrayShapeVariance( + ArrayShapeNode $existing, + ArrayShapeNode $expected, + string $variance + ): bool { + if (\count($existing->items) !== \count($expected->items)) { + return false; + } + + $existingItems = []; + $autoIdx = 0; + foreach ($existing->items as $item) { + $key = self::extractShapeKey($item, $autoIdx); + $existingItems[$key] = $item; + } + + $expAutoIdx = 0; + foreach ($expected->items as $expItem) { + $key = self::extractShapeKey($expItem, $expAutoIdx); + if (! isset($existingItems[$key])) { + return false; + } + + $exItem = $existingItems[$key]; + if ($exItem->optional !== $expItem->optional) { + return false; + } + + if (! self::checkVariance($exItem->valueType, $expItem->valueType, $variance)) { + return false; + } + } + + return true; + } + + private static function extractShapeKey(ArrayShapeItemNode $item, int &$autoIdx): string|int + { + if ($item->keyName instanceof ConstExprStringNode) { + return $item->keyName->value; + } + + if ($item->keyName instanceof ConstExprIntegerNode) { + $key = (int) $item->keyName->value; + $autoIdx = max($autoIdx, $key + 1); + + return $key; + } + + if ($item->keyName instanceof IdentifierTypeNode) { + return $item->keyName->name; + } + + if ($item->keyName !== null) { + return (string) $item->keyName; + } + + $key = $autoIdx; + $autoIdx++; + + return $key; + } + /** * Resolves and binds parent class (@extends), interface (@implements), and trait (@use) template mappings. * Respects Vendor Isolation by skipping docblocks from excluded vendor ancestor files unless stubbed. @@ -1552,6 +1652,14 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::checkExistingIntersectionVariance($existing, $expected, $variance); } + if ($existing instanceof ArrayTypeNode && $expected instanceof ArrayTypeNode) { + return self::checkVariance($existing->type, $expected->type, $variance); + } + + if ($existing instanceof ArrayShapeNode && $expected instanceof ArrayShapeNode) { + return self::checkNestedArrayShapeVariance($existing, $expected, $variance); + } + if ($existing instanceof GenericTypeNode && $expected instanceof GenericTypeNode) { return self::checkNestedGenericVariance($existing, $expected); } diff --git a/tests/TypeChecking/CallablesAndIterators/UnboundGeneratorTemplateTest.php b/tests/TypeChecking/CallablesAndIterators/UnboundGeneratorTemplateTest.php new file mode 100644 index 00000000..2def0989 --- /dev/null +++ b/tests/TypeChecking/CallablesAndIterators/UnboundGeneratorTemplateTest.php @@ -0,0 +1,177 @@ +. + */ +class TransformPipelineFixture +{ + /** + * @template R + * + * @param list $items + * @param Closure(int): R $transform + * + * @return Generator + */ + public function map(array $items, Closure $transform): Generator + { + foreach ($items as $k => $v) { + yield $k => $transform($v); + } + } + + /** + * @template U + * + * @param list $left + * @param iterable $right + * + * @return Generator + */ + public function zip(array $left, iterable $right): Generator + { + $i = 0; + foreach ($right as $val) { + if (! isset($left[$i])) { + break; + } + yield $i => [$left[$i], $val]; + $i++; + } + } +} + +/** + * Fixture: A generic container class accepting iterable in its constructor. + * + * @template E + */ +class GenericCollectionFixture +{ + /** + * @var list + */ + public array $items = []; + + /** + * @param iterable $source + */ + public function __construct(iterable $source) + { + foreach ($source as $item) { + $this->items[] = $item; + } + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->items; + } +} + +/** + * Standalone consumer function taking iterable and returning list. + * + * @template T + * + * @param iterable $source + * + * @return list + */ +function collectStream(iterable $source): array +{ + $result = []; + foreach ($source as $item) { + $result[] = $item; + } + + return $result; +} + +/** + * Standalone function with a concrete return contract expecting string elements. + * + * @return GenericCollectionFixture + */ +function produceStringCollection(): GenericCollectionFixture +{ + $pipeline = new TransformPipelineFixture(); + $gen = $pipeline->map([1, 2, 3], static fn (int $x): string => "val_{$x}"); + + return new GenericCollectionFixture($gen); +} + +/** + * Standalone function expecting a zipped collection of integer and string pairs. + * + * @return GenericCollectionFixture + */ +function produceZippedCollection(): GenericCollectionFixture +{ + $pipeline = new TransformPipelineFixture(); + $gen = $pipeline->zip([1, 2], ['a', 'b']); + + return new GenericCollectionFixture($gen); +} + +describe('Unbound Method Template Leaks into Generators (NV, R, U)', function () { + test('does not leak method template R into consumer function collectStream(iterable)', function () { + $pipeline = new TransformPipelineFixture(); + $gen = $pipeline->map([1, 2, 3], static fn (int $x): string => "item_{$x}"); + + $result = collectStream($gen); + + expect($result)->toBe(['item_1', 'item_2', 'item_3']); + }); + + test('does not leak method template R into GenericCollectionFixture via constructor', function () { + $pipeline = new TransformPipelineFixture(); + $gen = $pipeline->map([10, 20], static fn (int $x): string => "number_{$x}"); + + $collection = new GenericCollectionFixture($gen); + + expect($collection->toArray())->toBe(['number_10', 'number_20']); + }); + + test('satisfies concrete return contract GenericCollectionFixture without invariance mismatch', function () { + $collection = produceStringCollection(); + + expect($collection)->toBeInstanceOf(GenericCollectionFixture::class) + ->and($collection->toArray())->toBe(['val_1', 'val_2', 'val_3']) + ; + }); + + test('does not leak method template U from zip operation into tuples', function () { + $pipeline = new TransformPipelineFixture(); + $gen = $pipeline->zip([1, 2], ['first', 'second']); + + $collection = new GenericCollectionFixture($gen); + + expect($collection->toArray())->toBe([ + [1, 'first'], + [2, 'second'], + ]); + }); + + test('satisfies concrete return contract GenericCollectionFixture without U template leak', function () { + $collection = produceZippedCollection(); + + expect($collection)->toBeInstanceOf(GenericCollectionFixture::class) + ->and($collection->toArray())->toBe([ + [1, 'a'], + [2, 'b'], + ]) + ; + }); +}); From a93b2c8066926b24f7cea0a6ae7c9167908c9fae Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 16:20:29 +0800 Subject: [PATCH 03/37] Add ConditionalReturnGenericsTest for filterNotNull and flatten behaviors in generic collections --- src/Internal/Generics/TemplateManager.php | 60 ++++++-- .../ConditionalReturnGenericsTest.php | 145 ++++++++++++++++++ 2 files changed, 196 insertions(+), 9 deletions(-) create mode 100644 tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index ca6ae92d..34dfc35b 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1620,19 +1620,58 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return true; } - if ($variance === GenericTypeNode::VARIANCE_COVARIANT && isset(self::COLLECTION_SUBTYPES[$lowerExpected])) { - $allowedSubtypes = self::COLLECTION_SUBTYPES[$lowerExpected]; + $baseExpected = strtolower($expected instanceof GenericTypeNode ? (string) $expected->type : ($expected instanceof IdentifierTypeNode ? $expected->name : $expectedStr)); + $baseExisting = strtolower($existing instanceof GenericTypeNode ? (string) $existing->type : ($existing instanceof IdentifierTypeNode ? $existing->name : $existingStr)); - if (isset($allowedSubtypes[$lowerExisting])) { - return true; + if ($variance === GenericTypeNode::VARIANCE_COVARIANT && isset(self::COLLECTION_SUBTYPES[$baseExpected])) { + $allowedSubtypes = self::COLLECTION_SUBTYPES[$baseExpected]; + + if (isset($allowedSubtypes[$baseExisting])) { + if ($expected instanceof IdentifierTypeNode) { + return true; + } + + if ($expected instanceof GenericTypeNode) { + $allUnconstrained = true; + foreach ($expected->genericTypes as $gt) { + if (! self::isUnspecializedType($gt)) { + $allUnconstrained = false; + break; + } + } + + if ($allUnconstrained) { + return true; + } + } } if ($existing instanceof ArrayTypeNode || $existing instanceof ArrayShapeNode) { - return $lowerExpected === 'array' || $lowerExpected === 'iterable'; + if ($baseExpected === 'array' || $baseExpected === 'iterable') { + if ($expected instanceof IdentifierTypeNode) { + return true; + } + + if ($expected instanceof GenericTypeNode) { + $allUnconstrained = true; + foreach ($expected->genericTypes as $gt) { + if (! self::isUnspecializedType($gt)) { + $allUnconstrained = false; + break; + } + } + + if ($allUnconstrained) { + return true; + } + } + } } - if ($existing instanceof GenericTypeNode && isset($allowedSubtypes[strtolower((string) $existing->type)])) { - return true; + if ($existing instanceof GenericTypeNode && isset($allowedSubtypes[$baseExisting])) { + if ($expected instanceof IdentifierTypeNode) { + return true; + } } } @@ -1877,8 +1916,9 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge { $expectedClassName = (string) $expected->type; $lowerExpected = strtolower($expectedClassName); + $isCollection = isset(self::COLLECTION_SUBTYPES[$lowerExpected]); - if (isset(self::COLLECTION_SUBTYPES[$lowerExpected])) { + if ($isCollection) { $lowerExisting = strtolower((string) $existing->type); if (! isset(self::COLLECTION_SUBTYPES[$lowerExpected][$lowerExisting])) { return false; @@ -1910,9 +1950,11 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge $useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; $declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; + $defaultVariance = $isCollection ? GenericTypeNode::VARIANCE_COVARIANT : GenericTypeNode::VARIANCE_INVARIANT; + $innerVariance = ($useSiteVariance !== GenericTypeNode::VARIANCE_INVARIANT) ? $useSiteVariance - : $declaredVariance; + : ($declaredVariance !== GenericTypeNode::VARIANCE_INVARIANT ? $declaredVariance : $defaultVariance); if (! self::checkVariance($existingInner, $expectedInner, $innerVariance)) { return false; diff --git a/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php b/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php new file mode 100644 index 00000000..70bf9d90 --- /dev/null +++ b/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php @@ -0,0 +1,145 @@ + */ + public array $items; + + /** + * @param list $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } + + /** + * Filters out null elements and narrows T. When T is pure null, the conditional resolves to never. + * + * @return self<(T is null ? never : T)> + */ + public function filterNotNull(): self + { + $filtered = []; + foreach ($this->items as $item) { + if ($item !== null) { + $filtered[] = $item; + } + } + + return new self($filtered); + } +} + +/** + * Fixture mimicking noctud's Collection/Set/List flatten pattern with pseudo-types (list, array). + * + * @template T + */ +class ConditionalFlattenContainerFixture +{ + /** @var list */ + public array $items; + + /** + * @param list $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } + + /** + * Flattens elements one level if iterable. + * + * @return self<(T is iterable ? mixed : T)> + */ + public function flatten(): self + { + $flat = []; + foreach ($this->items as $item) { + if (is_iterable($item)) { + foreach ($item as $sub) { + $flat[] = $sub; + } + } else { + $flat[] = $item; + } + } + + return new self($flat); + } +} + +/** + * Factory mimicking noctud's setOf() / listOf() wrapping of a generator with conditional return. + * + * @template E + * + * @param iterable $source + * + * @return ConditionalFilterContainerFixture + */ +function createContainerFromIterable(iterable $source): ConditionalFilterContainerFixture +{ + $items = []; + foreach ($source as $item) { + $items[] = $item; + } + + return new ConditionalFilterContainerFixture($items); +} + +/** + * Generator returning a conditional type element. + * + * @template V + * + * @param list $items + * + * @return \Generator ? mixed : V)> + */ +function generateFlattenedStream(array $items): \Generator +{ + foreach ($items as $item) { + if (is_iterable($item)) { + foreach ($item as $sub) { + yield $sub; + } + } else { + yield $item; + } + } +} + +describe('Conditional Return Types on Generic Collections (filterNotNull & flatten)', function () { + test('filterNotNull() on all-null collection satisfies Container<(T is null ? never : T)> without invariance mismatch', function () { + $container = new ConditionalFilterContainerFixture([null, null]); + $nonNull = $container->filterNotNull(); + + expect($nonNull->items)->toBe([]); + }); + + test('flatten() on collection of lists resolves (T is iterable) when T is pseudo-type list', function () { + $container = new ConditionalFlattenContainerFixture([[1, 2], [3]]); + $flattened = $container->flatten(); + + expect($flattened->items)->toBe([1, 2, 3]); + }); + + test('factory does not leak raw unevaluated conditional type from generator into container template', function () { + $gen = generateFlattenedStream([[1, 2], [3, 4]]); + $container = createContainerFromIterable($gen); + + expect($container->items)->toBe([1, 2, 3, 4]); + }); +}); \ No newline at end of file From e8a9a1445e75c3f5dccf21007dcac1935f77b220 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 16:25:51 +0800 Subject: [PATCH 04/37] Add GenericMapFixture and tests for factory reconstruction variance in generics --- .../FactoryReconstructionVarianceTest.php | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php diff --git a/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php b/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php new file mode 100644 index 00000000..cced6a50 --- /dev/null +++ b/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php @@ -0,0 +1,73 @@ + */ + public array $elements = []; + + /** + * @param array $elements + */ + public function __construct(array $elements = []) + { + $this->elements = $elements; + } + + /** + * Factory recreating a new map instance from an un-reified generator or array. + * + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $data + * + * @return GenericMapFixture + */ + public static function create(iterable $data): GenericMapFixture + { + $items = []; + foreach ($data as $k => $v) { + $items[$k] = $v; + } + + return new self($items); + } + + /** + * Method preserving K and V, returning through factory reconstruction. + * + * @return GenericMapFixture + */ + public function filter(): GenericMapFixture + { + return self::create($this->elements); + } +} + +/** + * @return GenericMapFixture + */ +function getFilteredMap(): GenericMapFixture +{ + /** @var GenericMapFixture $map */ + $map = new GenericMapFixture(['a' => 1, 'b' => 2]); + + return $map->filter(); +} + +describe('Factory Re-construction Generic Return Variance', function () { + test('specializes instance template from declared upper bound to return type on return', function () { + $result = getFilteredMap(); + + expect($result)->toBeInstanceOf(GenericMapFixture::class) + ->and($result->elements)->toBe(['a' => 1, 'b' => 2]); + }); +}); \ No newline at end of file From 1adbee53d9925d51235f0c774aea05f46c936a99 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 22:31:06 +0800 Subject: [PATCH 05/37] Refactor TemplateManager to simplify type matching logic and add UnionBoundSpecializationTest for lazy closure template inference --- src/Internal/Generics/TemplateManager.php | 18 +++++-- .../Generics/UnionBoundSpecializationTest.php | 52 +++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 tests/TypeChecking/Generics/UnionBoundSpecializationTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 34dfc35b..a254196e 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1186,10 +1186,8 @@ private static function bindSingleTemplateArgument( } $isDefaultOrBound = self::isUnspecializedType($existingTypeNode) - || ($existingTypeNode instanceof IdentifierTypeNode && ( - ($templateTag->bound !== null && (string) $existingTypeNode === (string) $templateTag->bound) - || ($templateTag->default !== null && (string) $existingTypeNode === (string) $templateTag->default) - )); + || ($templateTag->bound !== null && self::matchesBoundOrDefault($existingTypeNode, $templateTag->bound)) + || ($templateTag->default !== null && self::matchesBoundOrDefault($existingTypeNode, $templateTag->default)); if (self::checkVariance($expectedTypeNode, $existingTypeNode, GenericTypeNode::VARIANCE_COVARIANT)) { if ($isDefaultOrBound || ($isReturnContext && ! $strictInvariance)) { @@ -1718,6 +1716,18 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return false; } + private static function matchesBoundOrDefault(TypeNode $existing, TypeNode $target): bool + { + if ($existing === $target) { + return true; + } + + $existingStr = trim((string) $existing, '() '); + $targetStr = trim((string) $target, '() '); + + return $existingStr === $targetStr; + } + /** * Verifies whether a concrete class identifier satisfies an expected generic type (e.g. F-bound Rogue <: Comparable). */ diff --git a/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php b/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php new file mode 100644 index 00000000..561192a6 --- /dev/null +++ b/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php @@ -0,0 +1,52 @@ +|Closure():iterable $data + * @return MapSim + */ +function mapOfSim(iterable|Closure $data): MapSim +{ + return new MapSim(); +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable|Closure():iterable $data + * @return MapSim + */ +function testHelperMapOf(iterable|Closure $data): MapSim +{ + if (! is_callable($data)) { + return mapOfSim(fn () => $data); + } + + return mapOfSim($data); +} + +describe('Lazy Closure Template Inference Failure', function () { + test('specializes union bound template when returning instance', function () { + $data = ['user' => 1]; + $result = testHelperMapOf($data); + + expect($result)->toBeInstanceOf(MapSim::class); + expect(TypePHP\TypePHP::getGenericTypes($result))->toBe([ + 'K' => 'string', + 'V' => 'int', + ]); + }); +}); \ No newline at end of file From 23d856135e1d75a57b66a2cb9ecfeea73d8e1600 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 22:31:37 +0800 Subject: [PATCH 06/37] Improve type annotations and formatting in various tests and TemplateManager for better clarity and consistency --- src/Internal/Generics/TemplateManager.php | 2 ++ .../Conditionals/ConditionalReturnGenericsTest.php | 10 +++++++--- .../Generics/FactoryReconstructionVarianceTest.php | 11 +++++++---- .../Generics/UnionBoundSpecializationTest.php | 6 ++++-- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index a254196e..c340fbae 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1634,6 +1634,7 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str foreach ($expected->genericTypes as $gt) { if (! self::isUnspecializedType($gt)) { $allUnconstrained = false; + break; } } @@ -1655,6 +1656,7 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str foreach ($expected->genericTypes as $gt) { if (! self::isUnspecializedType($gt)) { $allUnconstrained = false; + break; } } diff --git a/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php b/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php index 70bf9d90..e23f7a20 100644 --- a/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php +++ b/tests/TypeChecking/Conditionals/ConditionalReturnGenericsTest.php @@ -11,7 +11,9 @@ */ class ConditionalFilterContainerFixture { - /** @var list */ + /** + * @var list + */ public array $items; /** @@ -47,7 +49,9 @@ public function filterNotNull(): self */ class ConditionalFlattenContainerFixture { - /** @var list */ + /** + * @var list + */ public array $items; /** @@ -142,4 +146,4 @@ function generateFlattenedStream(array $items): \Generator expect($container->items)->toBe([1, 2, 3, 4]); }); -}); \ No newline at end of file +}); diff --git a/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php b/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php index cced6a50..67a4851b 100644 --- a/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php +++ b/tests/TypeChecking/Generics/FactoryReconstructionVarianceTest.php @@ -10,7 +10,9 @@ */ class GenericMapFixture { - /** @var array */ + /** + * @var array + */ public array $elements = []; /** @@ -59,7 +61,7 @@ function getFilteredMap(): GenericMapFixture { /** @var GenericMapFixture $map */ $map = new GenericMapFixture(['a' => 1, 'b' => 2]); - + return $map->filter(); } @@ -68,6 +70,7 @@ function getFilteredMap(): GenericMapFixture $result = getFilteredMap(); expect($result)->toBeInstanceOf(GenericMapFixture::class) - ->and($result->elements)->toBe(['a' => 1, 'b' => 2]); + ->and($result->elements)->toBe(['a' => 1, 'b' => 2]) + ; }); -}); \ No newline at end of file +}); diff --git a/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php b/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php index 561192a6..4b75493c 100644 --- a/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php +++ b/tests/TypeChecking/Generics/UnionBoundSpecializationTest.php @@ -15,6 +15,7 @@ class MapSim * @template V * * @param iterable|Closure():iterable $data + * * @return MapSim */ function mapOfSim(iterable|Closure $data): MapSim @@ -27,11 +28,12 @@ function mapOfSim(iterable|Closure $data): MapSim * @template V * * @param iterable|Closure():iterable $data + * * @return MapSim */ function testHelperMapOf(iterable|Closure $data): MapSim { - if (! is_callable($data)) { + if (! \is_callable($data)) { return mapOfSim(fn () => $data); } @@ -49,4 +51,4 @@ function testHelperMapOf(iterable|Closure $data): MapSim 'V' => 'int', ]); }); -}); \ No newline at end of file +}); From 49952aaab01cc22f45a45e721950a41ef0e57786 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 11 Nov 2026 23:12:19 +0800 Subject: [PATCH 07/37] Refactor ParamChecker to simplify traversable type resolution; add SpuriousTemplateBleedTest for verifying template behavior in generic collections --- src/Internal/Checker/ParamChecker.php | 101 +++++++++++++---- .../Generics/SpuriousTemplateBleedTest.php | 103 ++++++++++++++++++ 2 files changed, 181 insertions(+), 23 deletions(-) create mode 100644 tests/TypeChecking/Generics/SpuriousTemplateBleedTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index c5fba1b4..2daa3732 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1442,29 +1442,7 @@ private static function inferTemplatesFromIterableObject( } catch (\Throwable) { } } elseif ($value instanceof \Traversable) { - $boundOnInstance = TemplateManager::getBoundTemplatesForInstance($value); - if ($boundOnInstance !== []) { - $keyTName = null; - $valTName = null; - - foreach ($boundOnInstance as $tName => $tNode) { - $lower = strtolower($tName); - if ($lower === 'k' || $lower === 'key' || $lower === 'tkey') { - $keyTName = $tName; - } else { - $valTName = $tName; - } - } - - if ($keyTName !== null) { - $inferredKey = $boundOnInstance[$keyTName]; - } - if ($valTName !== null) { - $inferredVal = $boundOnInstance[$valTName]; - } elseif (\count($boundOnInstance) === 1) { - $inferredVal = reset($boundOnInstance); - } - } + [$inferredKey, $inferredVal] = self::resolveTraversableItemTypes($value); } $genericCount = \count($typeNode->genericTypes); @@ -1488,6 +1466,83 @@ private static function inferTemplatesFromIterableObject( } } + /** + * Resolves the yielded key and value TypeNodes of a Traversable object. + * + * @return array{0: ?TypeNode, 1: ?TypeNode} [keyType, valueType] + */ + private static function resolveTraversableItemTypes(object $value): array + { + $className = $value::class; + $boundOnInstance = TemplateManager::getBoundTemplatesForInstance($value); + + if ($value instanceof \IteratorAggregate) { + try { + $refClass = new \ReflectionClass($className); + $doc = $refClass->hasMethod('getIterator') + ? $refClass->getMethod('getIterator')->getDocComment() + : false; + + if ($doc !== false) { + $phpDocNode = DocblockExtractor::parseDocString($doc); + $returnTag = DocblockExtractor::getReturnTag($phpDocNode); + $contract = $returnTag !== null ? GeneratorEvaluator::extractContract($returnTag->type) : null; + + if ($contract !== null) { + $key = $contract['key'] !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($contract['key'], $boundOnInstance) : $contract['key']; + $val = $contract['value'] !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($contract['value'], $boundOnInstance) : $contract['value']; + + return [$key, $val]; + } + } + } catch (\Throwable) { + } + } + + try { + $refClass = new \ReflectionClass($className); + $hierarchy = HierarchyResolver::getClassHierarchy($refClass); + + foreach ($hierarchy as $hierClass) { + $classDoc = StubManager::getClassDoc($hierClass->getName()) ?? $hierClass->getDocComment(); + if ($classDoc === false || $classDoc === null) { + continue; + } + + $phpDocNode = DocblockExtractor::parseDocString($classDoc); + $inheritedTags = DocblockExtractor::getInheritedTags($phpDocNode); + + foreach ($inheritedTags as $inheritedTag) { + $genericNode = $inheritedTag->type; + if (! $genericNode instanceof GenericTypeNode) { + continue; + } + + $base = strtolower(ltrim((string) $genericNode->type, '\\')); + if ($base !== 'iteratoraggregate' && $base !== 'iterator' && $base !== 'traversable') { + continue; + } + + $count = \count($genericNode->genericTypes); + $key = $count >= 2 ? $genericNode->genericTypes[0] : null; + $val = $count >= 2 ? $genericNode->genericTypes[1] : ($genericNode->genericTypes[0] ?? null); + + $key = $key !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($key, $boundOnInstance) : $key; + $val = $val !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($val, $boundOnInstance) : $val; + + return [$key, $val]; + } + } + } catch (\Throwable) { + } + + if (\count($boundOnInstance) === 1) { + return [null, reset($boundOnInstance)]; + } + + return [null, null]; + } + /** * Unified single-parameter validation pipeline. * diff --git a/tests/TypeChecking/Generics/SpuriousTemplateBleedTest.php b/tests/TypeChecking/Generics/SpuriousTemplateBleedTest.php new file mode 100644 index 00000000..3bc3e585 --- /dev/null +++ b/tests/TypeChecking/Generics/SpuriousTemplateBleedTest.php @@ -0,0 +1,103 @@ + $items + */ + public function __construct( + public array $items = [] + ) { + } +} + +/** + * An entry object holding key and value. + * + * @template K + * @template V + */ +class EntrySim +{ + public function __construct( + public mixed $key, + public mixed $value + ) { + } +} + +/** + * An entry store that receives KeyValueStoreSim. + * Implements IteratorAggregate, but yields `int => EntrySim`, NOT `K => V`. + * + * @template K + * @template V + * + * @implements IteratorAggregate> + */ +class EntryStoreSim implements IteratorAggregate +{ + /** + * @param KeyValueStoreSim $store + */ + public function __construct( + public KeyValueStoreSim $store + ) { + } + + public function getIterator(): Traversable + { + foreach ($this->store->items as $k => $v) { + yield new EntrySim($k, $v); + } + } +} + +/** + * An operation whose template names happen to match the store: K and V. + * + * @template K + * @template V + */ +class OperationWithMatchingTemplateNames +{ + /** + * @param iterable $data + */ + public function __construct( + public iterable $data + ) { + } + + public function run(): array + { + $items = []; + foreach ($this->data as $k => $v) { + $items[$k] = $v; + } + + return $items; + } +} + +describe('Spurious Template Bleed into Traversable Wrapper', function () { + test('fails because TypePHP assumes Traversable templates K and V are its yielded types', function () { + $kvStore = new KeyValueStoreSim(['user' => 'Alice']); + + $entryStore = new EntryStoreSim($kvStore); + + $operation = new OperationWithMatchingTemplateNames($entryStore); + + $operation->run(); + + expect(true)->toBeTrue(); + }); +}); From dbfbc56121e84d3d4b62a179f11137a4a9db33d2 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 00:07:39 +0800 Subject: [PATCH 08/37] Enhance ParamChecker to utilize class templates in type substitution for improved generic handling --- src/Internal/Checker/ParamChecker.php | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 2daa3732..fc0bf026 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1489,8 +1489,10 @@ private static function resolveTraversableItemTypes(object $value): array $contract = $returnTag !== null ? GeneratorEvaluator::extractContract($returnTag->type) : null; if ($contract !== null) { - $key = $contract['key'] !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($contract['key'], $boundOnInstance) : $contract['key']; - $val = $contract['value'] !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($contract['value'], $boundOnInstance) : $contract['value']; + $classTemplates = DocblockParser::parseClassTemplates($refClass->getName()); + + $key = $contract['key'] !== null ? TemplateSubstitutor::substitute($contract['key'], $boundOnInstance, $classTemplates) : null; + $val = $contract['value'] !== null ? TemplateSubstitutor::substitute($contract['value'], $boundOnInstance, $classTemplates) : null; return [$key, $val]; } @@ -1527,8 +1529,10 @@ private static function resolveTraversableItemTypes(object $value): array $key = $count >= 2 ? $genericNode->genericTypes[0] : null; $val = $count >= 2 ? $genericNode->genericTypes[1] : ($genericNode->genericTypes[0] ?? null); - $key = $key !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($key, $boundOnInstance) : $key; - $val = $val !== null && $boundOnInstance !== [] ? TemplateSubstitutor::substitute($val, $boundOnInstance) : $val; + $classTemplates = DocblockParser::parseClassTemplates($hierClass->getName()); + + $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $classTemplates) : null; + $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $classTemplates) : null; return [$key, $val]; } @@ -1536,6 +1540,7 @@ private static function resolveTraversableItemTypes(object $value): array } catch (\Throwable) { } + // 3. Fallback: single generic argument container (e.g. Collection) if (\count($boundOnInstance) === 1) { return [null, reset($boundOnInstance)]; } From 1a324db4e9e143454056a34410ce62867d1c6d30 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 14:18:39 +0800 Subject: [PATCH 09/37] Enhance ParamChecker to support class alias substitution in traversable type resolution; add tests for aliased generics handling --- src/Internal/Checker/ParamChecker.php | 26 +++- .../TraversableResolutionFixtures.php | 119 ++++++++++++++++ .../TraversableTemplateFqcnResolutionTest.php | 127 ++++++++++++++++++ 3 files changed, 270 insertions(+), 2 deletions(-) create mode 100644 tests/Fixtures/Generics/TraversableResolutionFixtures.php create mode 100644 tests/TypeChecking/Generics/TraversableTemplateFqcnResolutionTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index fc0bf026..6af6a759 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1490,9 +1490,22 @@ private static function resolveTraversableItemTypes(object $value): array if ($contract !== null) { $classTemplates = DocblockParser::parseClassTemplates($refClass->getName()); + $aliases = DocblockParser::parseClassAliases($refClass->getName()); - $key = $contract['key'] !== null ? TemplateSubstitutor::substitute($contract['key'], $boundOnInstance, $classTemplates) : null; - $val = $contract['value'] !== null ? TemplateSubstitutor::substitute($contract['value'], $boundOnInstance, $classTemplates) : null; + $key = $contract['key']; + $val = $contract['value']; + + if ($aliases !== []) { + $key = $key !== null ? DocblockParser::substituteAliases($key, $aliases) : null; + $val = $val !== null ? DocblockParser::substituteAliases($val, $aliases) : null; + } + + $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $classTemplates) : null; + $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $classTemplates) : null; + + $refMethod = $refClass->getMethod('getIterator'); + $key = $key !== null ? SpecialTypeResolver::resolve($key, $refMethod) : null; + $val = $val !== null ? SpecialTypeResolver::resolve($val, $refMethod) : null; return [$key, $val]; } @@ -1530,10 +1543,19 @@ private static function resolveTraversableItemTypes(object $value): array $val = $count >= 2 ? $genericNode->genericTypes[1] : ($genericNode->genericTypes[0] ?? null); $classTemplates = DocblockParser::parseClassTemplates($hierClass->getName()); + $aliases = DocblockParser::parseClassAliases($hierClass->getName()); + + if ($aliases !== []) { + $key = $key !== null ? DocblockParser::substituteAliases($key, $aliases) : null; + $val = $val !== null ? DocblockParser::substituteAliases($val, $aliases) : null; + } $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $classTemplates) : null; $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $classTemplates) : null; + $key = $key !== null ? SpecialTypeResolver::resolve($key, $hierClass) : null; + $val = $val !== null ? SpecialTypeResolver::resolve($val, $hierClass) : null; + return [$key, $val]; } } diff --git a/tests/Fixtures/Generics/TraversableResolutionFixtures.php b/tests/Fixtures/Generics/TraversableResolutionFixtures.php new file mode 100644 index 00000000..cf4e10e6 --- /dev/null +++ b/tests/Fixtures/Generics/TraversableResolutionFixtures.php @@ -0,0 +1,119 @@ +id; + } +} + +/** + * @template T + */ +class GenericItemContainer +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } +} + +/** + * Case A: Traversable with an aliased import in @implements IteratorAggregate + * + * @implements IteratorAggregate + */ +class TraversableViaImplementsWithAlias implements IteratorAggregate +{ + public function __construct(private array $items) + { + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->items); + } +} + +/** + * Case B: Traversable with an aliased import in getIterator() return tag + */ +class TraversableViaGetIteratorWithAlias implements IteratorAggregate +{ + public function __construct(private array $items) + { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->items); + } +} + +/** + * Case C: Traversable with a nested GenericTypeNode item (mirrors MapEntry) + * + * @implements IteratorAggregate> + */ +class TraversableWithNestedGenericItem implements IteratorAggregate +{ + public function __construct(private array $items) + { + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->items); + } +} + +/** + * Case D: Intermediate interface in inheritance hierarchy + * + * @template E + * + * @extends IteratorAggregate + */ +interface BaseCollectionInterface extends IteratorAggregate +{ +} + +/** + * @implements BaseCollectionInterface + */ +class TraversableViaInheritedInterface implements BaseCollectionInterface +{ + public function __construct(private array $items) + { + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->items); + } +} diff --git a/tests/TypeChecking/Generics/TraversableTemplateFqcnResolutionTest.php b/tests/TypeChecking/Generics/TraversableTemplateFqcnResolutionTest.php new file mode 100644 index 00000000..a5de7bf1 --- /dev/null +++ b/tests/TypeChecking/Generics/TraversableTemplateFqcnResolutionTest.php @@ -0,0 +1,127 @@ + $collection + * + * @return list + */ +function testConsumeExternalTraversable(iterable $collection): array +{ + $results = []; + foreach ($collection as $item) { + $results[] = $item; + } + + return $results; +} + +describe('ParamChecker::resolveTraversableItemTypes FQCN Resolution', function () { + describe('A. Direct Inspection of Inferred TypeNode ASTs', function () { + test('resolves aliased item types in @implements IteratorAggregate to FQCN', function () { + $refMethod = new ReflectionMethod(ParamChecker::class, 'resolveTraversableItemTypes'); + $aggregate = new TraversableViaImplementsWithAlias([new ConcreteItem(1)]); + + $resolved = $refMethod->invoke(null, $aggregate); + + expect($resolved[1])->not->toBeNull(); + expect((string) $resolved[1])->toBe(ItemContract::class); + }); + + test('resolves aliased item types in getIterator() return tag to FQCN', function () { + $refMethod = new ReflectionMethod(ParamChecker::class, 'resolveTraversableItemTypes'); + $aggregate = new TraversableViaGetIteratorWithAlias([new ConcreteItem(1)]); + + $resolved = $refMethod->invoke(null, $aggregate); + + expect($resolved[1])->not->toBeNull(); + expect((string) $resolved[1])->toBe(ItemContract::class); + }); + + test('resolves nested GenericTypeNode item types to FQCN base types', function () { + $refMethod = new ReflectionMethod(ParamChecker::class, 'resolveTraversableItemTypes'); + $aggregate = new TraversableWithNestedGenericItem([new GenericItemContainer('payload')]); + + $resolved = $refMethod->invoke(null, $aggregate); + + expect($resolved[1])->not->toBeNull(); + expect((string) $resolved[1])->toBe(GenericItemContainer::class . ''); + }); + + test('resolves item types through intermediate inherited interfaces to FQCN', function () { + $refMethod = new ReflectionMethod(ParamChecker::class, 'resolveTraversableItemTypes'); + $aggregate = new TraversableViaInheritedInterface([new ConcreteItem(1)]); + + $resolved = $refMethod->invoke(null, $aggregate); + + expect($resolved[1])->not->toBeNull(); + expect((string) $resolved[1])->toBe(ItemContract::class); + }); + }); + + describe('B. End-to-End Runtime Contract Validation', function () { + test('successfully accepts items when traversable uses aliased @implements in another namespace', function () { + $item = new ConcreteItem(42); + $aggregate = new TraversableViaImplementsWithAlias([$item]); + + $consumed = testConsumeExternalTraversable($aggregate); + + expect($consumed)->toBe([$item]); + }); + + test('successfully accepts items when traversable uses aliased getIterator() DocBlock', function () { + $item = new ConcreteItem(100); + $aggregate = new TraversableViaGetIteratorWithAlias([$item]); + + $consumed = testConsumeExternalTraversable($aggregate); + + expect($consumed)->toBe([$item]); + }); + + test('successfully accepts items when traversable yields generic object items', function () { + $container = new GenericItemContainer('alpha'); + $aggregate = new TraversableWithNestedGenericItem([$container]); + + $consumed = testConsumeExternalTraversable($aggregate); + + expect($consumed)->toBe([$container]); + }); + + test('successfully accepts items from inherited generic interface traversable', function () { + $item = new ConcreteItem(7); + $aggregate = new TraversableViaInheritedInterface([$item]); + + $consumed = testConsumeExternalTraversable($aggregate); + + expect($consumed)->toBe([$item]); + }); + + test('still enforces type safety by rejecting genuinely incompatible items', function () { + $invalid = new stdClass(); + $aggregate = new TraversableViaImplementsWithAlias([$invalid]); + + expect(fn () => testConsumeExternalTraversable($aggregate)) + ->toThrow(TypeError::class, 'must be of type ' . ItemContract::class) + ; + }); + }); +}); From 6fe6b1061996c50f7df2c9f4d8719136f04c31e3 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 18:21:45 +0800 Subject: [PATCH 10/37] Enhance ParamChecker to support class templates in template inference; add tests for generic map construction and inference --- src/Internal/Checker/ParamChecker.php | 43 +++-- src/Internal/Generics/TemplateManager.php | 9 +- .../ReturnGenericReificationFixtures.php | 159 ++++++++++++++++++ .../Generics/ReturnGenericReificationTest.php | 28 +++ 4 files changed, 228 insertions(+), 11 deletions(-) create mode 100644 tests/Fixtures/Generics/ReturnGenericReificationFixtures.php create mode 100644 tests/TypeChecking/Generics/ReturnGenericReificationTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 6af6a759..4307c0b3 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -575,7 +575,7 @@ private static function preInferGenericTemplates( } if (\count($types) > 0) { - self::inferTemplatesFromArrays($types, $vars, $effectiveFunction, $thisObj, $templates); + self::inferTemplatesFromArrays($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); self::inferTemplatesFromShapes($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); self::inferTemplatesFromGenericObjects($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); } @@ -914,20 +914,22 @@ private static function extractTypeFromClosureParameter(\ReflectionParameter $cl * @param array $types * @param array $vars * @param array $templates + * @param array $classTemplates */ private static function inferTemplatesFromArrays( array $types, array $vars, string $effectiveFunction, ?object $thisObj, - array $templates + array $templates, + array $classTemplates = [] ): void { foreach ($types as $paramName => $typeNode) { if (! isset($vars[$paramName]) || ! \is_array($vars[$paramName]) || \count($vars[$paramName]) === 0) { continue; } - self::inferArrayTemplatesFromAllElements($typeNode, $vars[$paramName], $effectiveFunction, $thisObj, $templates); + self::inferArrayTemplatesFromAllElements($typeNode, $vars[$paramName], $effectiveFunction, $thisObj, $templates, $classTemplates); } } @@ -1082,13 +1084,15 @@ private static function inferTemplateFromTypeAndValue( * * @param array $arrVal * @param array $templates + * @param array $classTemplates */ private static function inferArrayTemplatesFromAllElements( TypeNode $typeNode, array $arrVal, string $effectiveFunction, ?object $thisObj, - array $templates + array $templates, + array $classTemplates = [] ): void { while ($typeNode instanceof NullableTypeNode) { $typeNode = $typeNode->type; @@ -1096,7 +1100,18 @@ private static function inferArrayTemplatesFromAllElements( if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { foreach ($typeNode->types as $subType) { - self::inferArrayTemplatesFromAllElements($subType, $arrVal, $effectiveFunction, $thisObj, $templates); + self::inferArrayTemplatesFromAllElements($subType, $arrVal, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + + return; + } + + if ($typeNode instanceof ArrayTypeNode && $typeNode->type instanceof ArrayShapeNode) { + $sampleItems = self::getSampleArraySlice($arrVal); + foreach ($sampleItems as $sample) { + if (\is_array($sample)) { + self::inferShapeNodeTemplates($typeNode->type, $sample, $effectiveFunction, $thisObj, $templates, $classTemplates); + } } return; @@ -1112,7 +1127,13 @@ private static function inferArrayTemplatesFromAllElements( $genericCount = \count($typeNode->genericTypes); if ($genericCount === 1 && $typeNode->genericTypes[0] instanceof IdentifierTypeNode) { - self::inferSingleTemplateFromArraySamples($typeNode->genericTypes[0]->name, $sampleItems, $effectiveFunction, $thisObj, $templates); + self::inferSingleTemplateFromArraySamples($typeNode->genericTypes[0]->name, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); + } elseif ($genericCount === 1 && $typeNode->genericTypes[0] instanceof ArrayShapeNode) { + foreach ($sampleItems as $sample) { + if (\is_array($sample)) { + self::inferShapeNodeTemplates($typeNode->genericTypes[0], $sample, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + } } elseif ($genericCount >= 2) { $keyTName = $typeNode->genericTypes[0] instanceof IdentifierTypeNode ? $typeNode->genericTypes[0]->name : null; $valTName = $typeNode->genericTypes[1] instanceof IdentifierTypeNode ? $typeNode->genericTypes[1]->name : null; @@ -1132,10 +1153,10 @@ private static function inferArrayTemplatesFromAllElements( } if ($keyTName !== null && $inferredKeyType !== null) { - self::bindTemplateIfUnbound($keyTName, $inferredKeyType, $effectiveFunction, $thisObj, $templates); + self::bindTemplateIfUnbound($keyTName, $inferredKeyType, $effectiveFunction, $thisObj, $templates, $classTemplates); } if ($valTName !== null && $inferredValType !== null) { - self::bindTemplateIfUnbound($valTName, $inferredValType, $effectiveFunction, $thisObj, $templates); + self::bindTemplateIfUnbound($valTName, $inferredValType, $effectiveFunction, $thisObj, $templates, $classTemplates); } } } @@ -1144,13 +1165,15 @@ private static function inferArrayTemplatesFromAllElements( /** * @param array $sampleItems * @param array $templates + * @param array $classTemplates */ private static function inferSingleTemplateFromArraySamples( string $templateName, array $sampleItems, string $effectiveFunction, ?object $thisObj, - array $templates + array $templates, + array $classTemplates = [] ): void { $inferredType = null; foreach ($sampleItems as $item) { @@ -1159,7 +1182,7 @@ private static function inferSingleTemplateFromArraySamples( } if ($inferredType !== null) { - self::bindTemplateIfUnbound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates); + self::bindTemplateIfUnbound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates, $classTemplates); } } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index c340fbae..72f9eb39 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1727,7 +1727,14 @@ private static function matchesBoundOrDefault(TypeNode $existing, TypeNode $targ $existingStr = trim((string) $existing, '() '); $targetStr = trim((string) $target, '() '); - return $existingStr === $targetStr; + if ($existingStr === $targetStr) { + return true; + } + + $normExisting = preg_replace('/\s*([|&()])\s*/', '$1', $existingStr); + $normTarget = preg_replace('/\s*([|&()])\s*/', '$1', $targetStr); + + return $normExisting === $normTarget; } /** diff --git a/tests/Fixtures/Generics/ReturnGenericReificationFixtures.php b/tests/Fixtures/Generics/ReturnGenericReificationFixtures.php new file mode 100644 index 00000000..bbb53f0f --- /dev/null +++ b/tests/Fixtures/Generics/ReturnGenericReificationFixtures.php @@ -0,0 +1,159 @@ + + */ +class TestMapKeySet implements TestSetInterface +{ + /** + * @template TV + * + * @param TestKeyValueStoreInterface $store + */ + public function __construct(public TestKeyValueStoreInterface $store) + { + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @extends IteratorAggregate + */ +interface TestKeyValueStoreInterface extends IteratorAggregate +{ +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements TestKeyValueStoreInterface + */ +class TestHashKeyValueStore implements TestKeyValueStoreInterface +{ + /** + * @var array + */ + public array $data = []; + + public function __construct() + { + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromPairs(iterable $source): self + { + $store = new self(); + foreach ($source as [$k, $v]) { + $store->data[$k] = $v; + } + + return $store; + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->data); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +interface TestMapInterface +{ +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +trait TestMapLogic +{ + /** + * @var TestKeyValueStoreInterface + */ + public TestKeyValueStoreInterface $store; + + /** + * @var TestSetInterface + */ + public TestSetInterface $keys { + get => new TestMapKeySet($this->store); + } + + /** + * @template R of mixed + * + * @param (Closure(K): R)|null $selector + * + * @return self + */ + public function sortedByKey(?Closure $selector = null): self + { + $map = new self(); + $map->store = clone $this->store; + + return $map; + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements TestMapInterface + */ +class TestMutableHashMap implements TestMapInterface +{ + /** @use TestMapLogic */ + use TestMapLogic; + + public function __construct() + { + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $data + * + * @return self + */ + public static function ofPairs(iterable $data = []): self + { + $map = new self(); + $map->store = TestHashKeyValueStore::fromPairs($data); + + return $map; + } +} diff --git a/tests/TypeChecking/Generics/ReturnGenericReificationTest.php b/tests/TypeChecking/Generics/ReturnGenericReificationTest.php new file mode 100644 index 00000000..2f5d4dc9 --- /dev/null +++ b/tests/TypeChecking/Generics/ReturnGenericReificationTest.php @@ -0,0 +1,28 @@ +toBe([ + 'K' => 'string', + 'V' => 'string', + ]); + + $sorted = $map->sortedByKey(fn (string $k): int => \strlen($k)); + + $keys = $sorted->keys; + expect($keys)->toBeInstanceOf(TestSetInterface::class); + expect(TypePHP::getGenericType($keys))->toBe('string'); + }); +}); From 9c136f64f9c950f7312b105c9ab51c65c8468044 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 20:11:22 +0800 Subject: [PATCH 11/37] Enhance FunctionContractInjector and RuntimeTypeChecker to support scope management; add ScopeCleaner for template binding; introduce GenericStreamPipeline with tests for generator interleaving and template isolation --- src/Internal/Ast/FunctionContractInjector.php | 41 ++++++++++++----- src/Internal/Ast/ScopeCleaner.php | 8 ++++ src/Internal/Checker/GeneratorChecker.php | 43 ++++++++++++------ src/Internal/RuntimeTypeChecker.php | 43 +++++++++++++----- .../Generics/GenericGeneratorPipelineTest.php | 45 +++++++++++++++++++ 5 files changed, 145 insertions(+), 35 deletions(-) create mode 100644 tests/TypeChecking/Generics/GenericGeneratorPipelineTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 22f06ce9..12c6799e 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -168,7 +168,8 @@ public static function inject( $hasMethodTemplates, $needsReturnVars, $hasParamOut ? $byRefParams : [], - $hasSelfOut + $hasSelfOut, + $hasParam ) : self::wrapNonGeneratorReturns( $node->stmts, @@ -406,7 +407,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class () extends NodeVisitorAbstract { + $visitor = new class() extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -850,6 +851,11 @@ public static function buildWrappedYieldNode( array $byRefParams = [], bool $needsReturnVars = false ): Node\Expr { + $scopeArg = new Node\Expr\BinaryOp\Coalesce( + new Node\Expr\Variable('__typephpScope'), + new Node\Expr\ConstFetch(new Node\Name('null')) + ); + if ($wrapYield) { $checkYieldCall = new Node\Expr\FuncCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkYield'), @@ -858,6 +864,7 @@ public static function buildWrappedYieldNode( new Node\Arg($n->key ?? new Node\Expr\ConstFetch(new Node\Name('null'))), new Node\Arg($n->value ?? new Node\Expr\ConstFetch(new Node\Name('null'))), new Node\Arg($thisArg), + new Node\Arg($scopeArg), ] ); @@ -886,6 +893,7 @@ public static function buildWrappedYieldNode( new Node\Arg(new Node\Scalar\MagicConst\Method()), new Node\Arg($n), new Node\Arg($thisArg), + new Node\Arg($scopeArg), ] ); @@ -916,7 +924,8 @@ private static function wrapGeneratorReturns( bool $hasMethodTemplates = false, bool $needsReturnVars = false, array $byRefParams = [], - bool $hasSelfOut = false + bool $hasSelfOut = false, + bool $hasScope = false ): array { $canEliminate = $functionNode !== null && ! $hasMethodTemplates @@ -932,13 +941,13 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $genContract, $currentFile, $needsReturnVars, $byRefParams, - $hasSelfOut + $hasSelfOut, ) extends NodeVisitorAbstract { /** * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract @@ -950,9 +959,8 @@ public function __construct( private string $currentFile, private bool $needsReturnVars, private array $byRefParams, - private bool $hasSelfOut - ) { - } + private bool $hasSelfOut, + ) {} public function enterNode(Node $n): int|Node|array|null { @@ -1089,12 +1097,18 @@ public function enterNode(Node $n): int|Node|array|null return $exitStmts !== [] ? [...$exitStmts, $n] : $n; } + $scopeArg = new Node\Expr\BinaryOp\Coalesce( + new Node\Expr\Variable('__typephpScope'), + new Node\Expr\ConstFetch(new Node\Name('null')) + ); + $checkCall = new Node\Expr\FuncCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkGeneratorReturn'), [ new Node\Arg(new Node\Scalar\MagicConst\Method()), new Node\Arg($exprToWrap), new Node\Arg($this->thisArg), + new Node\Arg($scopeArg), ] ); @@ -1133,12 +1147,18 @@ public function enterNode(Node $n): int|Node|array|null $genContract === null || ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile) ) { + $scopeArg = new Node\Expr\BinaryOp\Coalesce( + new Node\Expr\Variable('__typephpScope'), + new Node\Expr\ConstFetch(new Node\Name('null')) + ); + $checkCall = new Node\Expr\FuncCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkGeneratorReturn'), [ new Node\Arg(new Node\Scalar\MagicConst\Method()), new Node\Arg(new Node\Expr\ConstFetch(new Node\Name('null'))), new Node\Arg($thisArg), + new Node\Arg($scopeArg), ] ); @@ -1179,7 +1199,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1208,8 +1228,7 @@ public function __construct( private ?array $classContext, private ?TypeNode $returnTypeNode, private string $currentFile - ) { - } + ) {} public function enterNode(Node $n): int|array|null { diff --git a/src/Internal/Ast/ScopeCleaner.php b/src/Internal/Ast/ScopeCleaner.php index a85e4426..4fe36ef2 100644 --- a/src/Internal/Ast/ScopeCleaner.php +++ b/src/Internal/Ast/ScopeCleaner.php @@ -4,6 +4,7 @@ namespace TypePHP\Internal\Ast; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; use TypePHP\Internal\Generics\TemplateManager; /** @@ -11,6 +12,13 @@ */ final class ScopeCleaner { + /** + * Captured template bindings specific to this execution scope. + * + * @var array + */ + public array $boundTemplates = []; + public function __construct(private string $function) { } diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 9f7dc6f0..1ce0a272 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -8,6 +8,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use TypePHP\Internal\Ast\ScopeCleaner; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Docblock\DocblockParser; @@ -44,6 +45,13 @@ final class GeneratorChecker */ private static array $genericYieldTypeCache = []; + public static function reset(): void + { + self::$noContractCache = []; + self::$staticYieldTypeCache = []; + self::$genericYieldTypeCache = []; + } + /** * Validates a value sent into a generator via $gen->send() against TSend. */ @@ -51,13 +59,14 @@ public static function checkSend( string $function, mixed $sendValue, TypeValidatorRegistry $registry, - object|string|null $thisOrClass = null + object|string|null $thisOrClass = null, + ?ScopeCleaner $scopeCleaner = null ): mixed { if ($sendValue === null) { return null; } - $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $sendValue; } @@ -80,9 +89,10 @@ public static function checkYield( mixed $key, mixed $value, TypeValidatorRegistry $registry, - object|string|null $thisOrClass = null + object|string|null $thisOrClass = null, + ?ScopeCleaner $scopeCleaner = null ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $value; } @@ -113,9 +123,10 @@ public static function checkReturn( string $function, mixed $value, TypeValidatorRegistry $registry, - object|string|null $thisOrClass = null + object|string|null $thisOrClass = null, + ?ScopeCleaner $scopeCleaner = null ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $value; } @@ -146,13 +157,14 @@ public static function checkReturn( private static function resolveYieldAndSendTypes( string $function, object|string|null $thisOrClass, - ?TypeValidatorRegistry $registry = null + ?TypeValidatorRegistry $registry = null, + ?ScopeCleaner $scopeCleaner = null ): ?array { - if (isset(self::$noContractCache[$function])) { + if ($scopeCleaner === null && isset(self::$noContractCache[$function])) { return null; } - if (isset(self::$staticYieldTypeCache[$function])) { + if ($scopeCleaner === null && isset(self::$staticYieldTypeCache[$function])) { return self::$staticYieldTypeCache[$function]; } @@ -172,19 +184,22 @@ private static function resolveYieldAndSendTypes( $hasConditionals = ConditionalChecker::containsConditional($returnTypeNode); $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - // Static / non-generic generator: cache permanently for this function - if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && $thisObj === null) { + if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && $thisObj === null && $scopeCleaner === null) { $resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null); return self::$staticYieldTypeCache[$function] = self::extractYieldTypes($resolvedNode); } - // Generic generator: check signature-based 2D cache - $boundTemplates = $hasGenerics ? TemplateManager::getBoundTemplates($function, $thisObj, $allTemplates) : []; + $boundTemplates = []; + if ($scopeCleaner !== null && $scopeCleaner->boundTemplates !== []) { + $boundTemplates = $scopeCleaner->boundTemplates; + } elseif ($hasGenerics) { + $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $allTemplates); + } $sig = null; $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && ! $hasConditionals && $thisObj === null) { + if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && ! $hasConditionals && $thisObj === null && $scopeCleaner === null) { if ($boundCount === 1) { $first = reset($boundTemplates); $sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first; diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index ccef9db1..23ac460d 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -60,6 +60,7 @@ public static function reset(): void CallerBoundaryResolver::reset(); ParamOutChecker::reset(); SelfOutChecker::reset(); + GeneratorChecker::reset(); ViolationCollector::reset(); } @@ -515,7 +516,16 @@ public static function setupScope(string $function, array $vars, object|string|n self::$hasMethodTemplatesCache[$function] = $hasMethodTemplates; } - return $hasMethodTemplates ? new ScopeCleaner($effectiveFunction) : null; + if ($hasMethodTemplates) { + $cleaner = new ScopeCleaner($effectiveFunction); + $contract = DocblockParser::parse($effectiveFunction); + $allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + $cleaner->boundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates); + + return $cleaner; + } + + return null; } /** @@ -690,8 +700,12 @@ public static function checkReturn(string $function, mixed $value, object|string /** * Validates a value sent into a generator via $gen->send() against TSend. */ - public static function checkSend(string $function, mixed $sendValue, object|string|null $thisOrClass = null): mixed - { + public static function checkSend( + string $function, + mixed $sendValue, + object|string|null $thisOrClass = null, + ?ScopeCleaner $scopeCleaner = null + ): mixed { if (! Config::isEnabled()) { return $sendValue; } @@ -703,7 +717,7 @@ public static function checkSend(string $function, mixed $sendValue, object|stri return $sendValue; } - $res = GeneratorChecker::checkSend($function, $sendValue, self::getRegistry(), $thisOrClass); + $res = GeneratorChecker::checkSend($function, $sendValue, self::getRegistry(), $thisOrClass, $scopeCleaner); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { @@ -719,8 +733,12 @@ public static function checkSend(string $function, mixed $sendValue, object|stri /** * Validates a value returned from a generator against TReturn. */ - public static function checkGeneratorReturn(string $function, mixed $value, object|string|null $thisOrClass = null): mixed - { + public static function checkGeneratorReturn( + string $function, + mixed $value, + object|string|null $thisOrClass = null, + ?ScopeCleaner $scopeCleaner = null + ): mixed { if (! Config::isEnabled() || ! Config::isReturnsEnabled()) { return $value; } @@ -732,7 +750,7 @@ public static function checkGeneratorReturn(string $function, mixed $value, obje return $value; } - $res = GeneratorChecker::checkReturn($function, $value, self::getRegistry(), $thisOrClass); + $res = GeneratorChecker::checkReturn($function, $value, self::getRegistry(), $thisOrClass, $scopeCleaner); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { @@ -748,8 +766,13 @@ public static function checkGeneratorReturn(string $function, mixed $value, obje /** * Validates yielded keys and values from a generator function against TKey and TValue. */ - public static function checkYield(string $function, mixed $key, mixed $value, object|string|null $thisOrClass = null): mixed - { + public static function checkYield( + string $function, + mixed $key, + mixed $value, + object|string|null $thisOrClass = null, + ?ScopeCleaner $scopeCleaner = null + ): mixed { if (! Config::isEnabled()) { return $value; } @@ -761,7 +784,7 @@ public static function checkYield(string $function, mixed $key, mixed $value, ob return $value; } - $res = GeneratorChecker::checkYield($function, $key, $value, self::getRegistry(), $thisOrClass); + $res = GeneratorChecker::checkYield($function, $key, $value, self::getRegistry(), $thisOrClass, $scopeCleaner); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { diff --git a/tests/TypeChecking/Generics/GenericGeneratorPipelineTest.php b/tests/TypeChecking/Generics/GenericGeneratorPipelineTest.php new file mode 100644 index 00000000..9e5455d7 --- /dev/null +++ b/tests/TypeChecking/Generics/GenericGeneratorPipelineTest.php @@ -0,0 +1,45 @@ + $data + * @param callable(TIn): TOut $transform + * + * @return Generator + */ + public function transform(iterable $data, callable $transform): Generator + { + foreach ($data as $item) { + yield $transform($item); + } + } +} + +describe('Generic Generator Pipeline Interleaving and Template Isolation', function () { + test('does not leak method templates across interleaved pipeline generators of the same method', function () { + $p1 = new GenericStreamPipeline(); + $p2 = new GenericStreamPipeline(); + + $gen1 = $p1->transform([10, 20, 30], fn (int $i): stdClass => (object) ['val' => $i]); + + $gen2 = $p2->transform($gen1, fn (stdClass $obj): int => $obj->val); + + $results = []; + foreach ($gen2 as $item) { + $results[] = $item; + } + + expect($results)->toBe([10, 20, 30]); + }); +}); From 511eda91a2b522924a74100cf521e01044f7dbab Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 20:11:28 +0800 Subject: [PATCH 12/37] Fix formatting in FunctionContractInjector by adding spaces in anonymous class definitions for improved readability --- src/Internal/Ast/FunctionContractInjector.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 12c6799e..94c46b1f 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -407,7 +407,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class() extends NodeVisitorAbstract { + $visitor = new class () extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -941,7 +941,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $genContract, $currentFile, @@ -960,7 +960,8 @@ public function __construct( private bool $needsReturnVars, private array $byRefParams, private bool $hasSelfOut, - ) {} + ) { + } public function enterNode(Node $n): int|Node|array|null { @@ -1199,7 +1200,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1228,7 +1229,8 @@ public function __construct( private ?array $classContext, private ?TypeNode $returnTypeNode, private string $currentFile - ) {} + ) { + } public function enterNode(Node $n): int|array|null { From 4f8332422fa438af522067510f2ac28ab4b59d05 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 21:46:12 +0800 Subject: [PATCH 13/37] Enhance ParamChecker to support ObjectShapeNode in template inference; add TuplePairStore with tests for heterogeneous key unification and template upper bounds enforcement --- src/Internal/Checker/ParamChecker.php | 176 +++++++++++++++--- ...upleAndShapeArrayTemplateInferenceTest.php | 176 ++++++++++++++++++ 2 files changed, 330 insertions(+), 22 deletions(-) create mode 100644 tests/TypeChecking/Generics/TupleAndShapeArrayTemplateInferenceTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 4307c0b3..4f07f34c 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1106,13 +1106,9 @@ private static function inferArrayTemplatesFromAllElements( return; } - if ($typeNode instanceof ArrayTypeNode && $typeNode->type instanceof ArrayShapeNode) { + if ($typeNode instanceof ArrayTypeNode && ($typeNode->type instanceof ArrayShapeNode || $typeNode->type instanceof ObjectShapeNode)) { $sampleItems = self::getSampleArraySlice($arrVal); - foreach ($sampleItems as $sample) { - if (\is_array($sample)) { - self::inferShapeNodeTemplates($typeNode->type, $sample, $effectiveFunction, $thisObj, $templates, $classTemplates); - } - } + self::inferShapeTemplatesFromArraySamples($typeNode->type, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); return; } @@ -1128,15 +1124,12 @@ private static function inferArrayTemplatesFromAllElements( if ($genericCount === 1 && $typeNode->genericTypes[0] instanceof IdentifierTypeNode) { self::inferSingleTemplateFromArraySamples($typeNode->genericTypes[0]->name, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); - } elseif ($genericCount === 1 && $typeNode->genericTypes[0] instanceof ArrayShapeNode) { - foreach ($sampleItems as $sample) { - if (\is_array($sample)) { - self::inferShapeNodeTemplates($typeNode->genericTypes[0], $sample, $effectiveFunction, $thisObj, $templates, $classTemplates); - } - } + } elseif ($genericCount === 1 && ($typeNode->genericTypes[0] instanceof ArrayShapeNode || $typeNode->genericTypes[0] instanceof ObjectShapeNode)) { + self::inferShapeTemplatesFromArraySamples($typeNode->genericTypes[0], $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); } elseif ($genericCount >= 2) { $keyTName = $typeNode->genericTypes[0] instanceof IdentifierTypeNode ? $typeNode->genericTypes[0]->name : null; - $valTName = $typeNode->genericTypes[1] instanceof IdentifierTypeNode ? $typeNode->genericTypes[1]->name : null; + $valTypeNode = $typeNode->genericTypes[1]; + $valTName = $valTypeNode instanceof IdentifierTypeNode ? $valTypeNode->name : null; $inferredKeyType = null; $inferredValType = null; @@ -1158,10 +1151,157 @@ private static function inferArrayTemplatesFromAllElements( if ($valTName !== null && $inferredValType !== null) { self::bindTemplateIfUnbound($valTName, $inferredValType, $effectiveFunction, $thisObj, $templates, $classTemplates); } + if ($valTypeNode instanceof ArrayShapeNode || $valTypeNode instanceof ObjectShapeNode) { + self::inferShapeTemplatesFromArraySamples($valTypeNode, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); + } } } } + /** + * Collects and unifies shape template types across multiple elements of a collection/array. + * Within each individual shape element, the first occurrence of a template determines that element's type; + * across separate elements of the collection, those types are unified if they satisfy the template's bound. + * + * @param array $sampleItems + * @param array $templates + * @param array $classTemplates + */ + private static function inferShapeTemplatesFromArraySamples( + TypeNode $shapeTypeNode, + array $sampleItems, + string $effectiveFunction, + ?object $thisObj, + array $templates, + array $classTemplates = [] + ): void { + /** @var array $unifiedAcrossSamples */ + $unifiedAcrossSamples = []; + + foreach ($sampleItems as $sample) { + /** @var array $sampleBindings */ + $sampleBindings = []; + self::collectSingleShapeElementTemplates($shapeTypeNode, $sample, $templates, $sampleBindings); + + foreach ($sampleBindings as $tName => $inferredType) { + if (self::doesInferredTypeSatisfyBound($tName, $inferredType, $effectiveFunction, $thisObj, $templates)) { + $unifiedAcrossSamples[$tName] = isset($unifiedAcrossSamples[$tName]) + ? self::unifyTypes($unifiedAcrossSamples[$tName], $inferredType) + : $inferredType; + } + } + } + + foreach ($unifiedAcrossSamples as $tName => $unifiedType) { + self::bindTemplateIfUnbound($tName, $unifiedType, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + } + + /** + * Extracts template types from a single shape element into $sampleBindings (locking the first seen per template within that element). + * + * @param array $templates + * @param array $sampleBindings + */ + private static function collectSingleShapeElementTemplates( + TypeNode $typeNode, + mixed $value, + array $templates, + array &$sampleBindings + ): void { + if ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof IdentifierTypeNode) { + if (isset($templates[$typeNode->name]) && ! isset($sampleBindings[$typeNode->name])) { + $sampleBindings[$typeNode->name] = TemplateManager::inferTypeFromValue($value); + } + + return; + } + + if ($typeNode instanceof IntersectionTypeNode || $typeNode instanceof UnionTypeNode) { + foreach ($typeNode->types as $subType) { + self::collectSingleShapeElementTemplates($subType, $value, $templates, $sampleBindings); + } + + return; + } + + if ($typeNode instanceof ObjectShapeNode && \is_object($value)) { + foreach ($typeNode->items as $item) { + $prop = $item->keyName instanceof IdentifierTypeNode ? $item->keyName->name : (string) $item->keyName; + + // @phpstan-ignore property.dynamicName + if (isset($value->$prop) || property_exists($value, $prop)) { + // @phpstan-ignore property.dynamicName + $propVal = $value->$prop; + self::collectSingleShapeElementTemplates($item->valueType, $propVal, $templates, $sampleBindings); + } + } + + return; + } + + if ($typeNode instanceof ArrayShapeNode && \is_array($value)) { + $nextIdx = 0; + foreach ($typeNode->items as $item) { + $key = match (true) { + $item->keyName instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode => $item->keyName->value, + $item->keyName instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode => (int) $item->keyName->value, + $item->keyName instanceof IdentifierTypeNode => $item->keyName->name, + $item->keyName !== null => (string) $item->keyName, + default => $nextIdx, + }; + + if (\is_int($key)) { + $nextIdx = max($nextIdx, $key + 1); + } + + if (\array_key_exists($key, $value)) { + self::collectSingleShapeElementTemplates($item->valueType, $value[$key], $templates, $sampleBindings); + } + } + + if ($typeNode->unsealedType !== null) { + $unsealed = $typeNode->unsealedType; + foreach ($value as $k => $v) { + self::collectSingleShapeElementTemplates($unsealed->valueType, $v, $templates, $sampleBindings); + if ($unsealed->keyType !== null) { + self::collectSingleShapeElementTemplates($unsealed->keyType, $k, $templates, $sampleBindings); + } + } + } + } + } + + /** + * Checks whether a candidate inferred TypeNode satisfies the declared upper bound of a template. + * + * @param array $templates + */ + private static function doesInferredTypeSatisfyBound( + string $templateName, + TypeNode $inferredType, + string $effectiveFunction, + ?object $thisObj, + array $templates + ): bool { + if (! isset($templates[$templateName])) { + return false; + } + + $templateTag = $templates[$templateName]; + if ($templateTag->bound === null) { + return true; + } + + $resolvedBound = SpecialTypeResolver::resolve($templateTag->bound, $effectiveFunction, $thisObj); + + return TemplateManager::checkVariance($inferredType, $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT); + } + /** * @param array $sampleItems * @param array $templates @@ -1238,15 +1378,7 @@ private static function bindTemplateIfUnbound( $targetObj = $isClassLevelTemplate ? $thisObj : null; if (isset($templates[$templateName]) && ! TemplateManager::isBound($effectiveFunction, $targetObj, $templateName)) { - $templateTag = $templates[$templateName]; - $satisfiesBound = true; - - if ($templateTag->bound !== null) { - $resolvedBound = SpecialTypeResolver::resolve($templateTag->bound, $effectiveFunction, $thisObj); - $satisfiesBound = TemplateManager::checkVariance($inferredType, $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT); - } - - if ($satisfiesBound) { + if (self::doesInferredTypeSatisfyBound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates)) { TemplateManager::bindTemplate($effectiveFunction, $targetObj, $templateName, $inferredType); } } diff --git a/tests/TypeChecking/Generics/TupleAndShapeArrayTemplateInferenceTest.php b/tests/TypeChecking/Generics/TupleAndShapeArrayTemplateInferenceTest.php new file mode 100644 index 00000000..0aac3fdf --- /dev/null +++ b/tests/TypeChecking/Generics/TupleAndShapeArrayTemplateInferenceTest.php @@ -0,0 +1,176 @@ + $pairs + */ + public function __construct(public array $pairs = []) + { + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromPairs(iterable $source): self + { + $pairs = []; + foreach ($source as [$k, $v]) { + $pairs[] = [$k, $v]; + } + + return new self($pairs); + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable|Closure(): iterable $data + * + * @return self + */ + public static function ofPairs(iterable|Closure $data): self + { + if ($data instanceof Closure) { + return self::fromPairs($data()); + } + + return self::fromPairs($data); + } + + /** + * @template NK of string|int + * @template NV of TupleInferenceAnimal + * + * @param list $records + * + * @return list + */ + public static function extractPetsFromNamedShapes(array $records): array + { + $out = []; + foreach ($records as $r) { + $out[] = $r['pet']; + } + + return $out; + } +} + +describe('Tuple & Array Shape Multi-Element Template Inference', function () { + describe('1. Unifying Heterogeneous Key Types Across Tuples (array{0: NK, 1: NV})', function () { + test('unifies string, int, float, bool, and object keys across multiple tuple elements', function () { + $obj = new stdClass(); + + $store = TuplePairStore::fromPairs([ + ['1', 'a'], + [1, 'b'], + [$obj, 'c'], + [false, 'd'], + [2.5, 'e'], + ]); + + expect($store->pairs)->toHaveCount(5); + }); + + test('unifies tuple key and value types when parameter is a union with Closure (iterable|Closure)', function () { + $obj = new stdClass(); + + $store = TuplePairStore::ofPairs([ + [$obj, 'a'], + ['b', 2], + ]); + + expect($store->pairs)->toHaveCount(2); + }); + }); + + describe('2. Unifying Heterogeneous Object & Nullable Value Types Across Tuples', function () { + test('unifies sibling object classes (Dog and Cat) across tuple elements', function () { + $dog1 = new TupleInferenceDog('Rex'); + $cat = new TupleInferenceCat('Whiskers'); + $dog2 = new TupleInferenceDog('Buddy'); + + $store = TuplePairStore::ofPairs([ + ['a', $dog1], + ['b', $cat], + ['c', $dog2], + ]); + + expect($store->pairs)->toHaveCount(3); + }); + + test('unifies non-null and null values when null appears in a later tuple element', function () { + $store = TuplePairStore::ofPairs([ + ['01', 'a'], + ['1', 'b'], + ['2', null], + ]); + + expect($store->pairs)->toHaveCount(3); + }); + + test('unifies named array shape fields across list elements while respecting upper bounds', function () { + $dog = new TupleInferenceDog('Rex'); + $cat = new TupleInferenceCat('Whiskers'); + + $pets = TuplePairStore::extractPetsFromNamedShapes([ + ['id' => 'first', 'pet' => $dog], + ['id' => 2, 'pet' => $cat], + ]); + + expect($pets)->toHaveCount(2); + }); + }); + + describe('3. Enforcing Template Upper Bounds Across All Tuple Elements', function () { + test('rejects tuple when a later element violates the template upper bound (null key)', function () { + expect(fn () => TuplePairStore::fromPairs([ + ['valid_key', 'a'], + [null, 'b'], + ]))->toThrow(TypeError::class); + }); + + test('rejects named shape when a later element violates the template upper bound', function () { + $dog = new TupleInferenceDog('Rex'); + + expect(fn () => TuplePairStore::extractPetsFromNamedShapes([ + ['id' => 'first', 'pet' => $dog], + ['id' => 2, 'pet' => new stdClass()], + ]))->toThrow(TypeError::class); + }); + }); +}); From ffbab62dc0d54d1b4f11395edd02457342f2244e Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 21:55:25 +0800 Subject: [PATCH 14/37] Add tests for cloned store template widening in immutable collections and maps --- src/Internal/Generics/TemplateManager.php | 86 ++++++ .../ClonedStoreTemplateWideningTest.php | 268 ++++++++++++++++++ 2 files changed, 354 insertions(+) create mode 100644 tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 72f9eb39..094872fa 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -579,11 +579,14 @@ public static function normalizeGenericArguments(array $genericTypes, array $tem /** * Copies bound generic template types from a source object to a cloned target object. + * If cloned inside an active method that widens class templates via method templates in its @return type, + * the cloned target receives the widened template bindings while the source retains its original bindings. */ public static function copyInstanceBindings(object $source, object $target): void { if (self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$source])) { $bindings = self::$instanceTemplateBindings[$source]; + $bindings = self::widenClonedBindingsFromActiveCall($target, $bindings); self::$instanceTemplateBindings[$target] = $bindings; } } @@ -1101,6 +1104,89 @@ private static function collectHierarchyTemplatesAndVariances(\ReflectionClass $ return self::$classHierarchyTemplatesCache[$className] = [$templates, $classVariances]; } + /** + * Widens template bindings on a cloned instance when the enclosing method's @return contract + * widens class templates with method-level templates (e.g. @return self or ImmutableMap). + * + * @param array $bindings + * + * @return array + */ + private static function widenClonedBindingsFromActiveCall(object $target, array $bindings): array + { + if (self::$callStackBindings === []) { + return $bindings; + } + + $activeFunction = array_key_last(self::$callStackBindings); + $topFrame = self::getTopCallFrame($activeFunction); + if ($topFrame === null || $topFrame === []) { + return $bindings; + } + + $contract = DocblockParser::parse($activeFunction); + $returnTypeNode = $contract['return'] ?? null; + if (! ($returnTypeNode instanceof GenericTypeNode)) { + return $bindings; + } + + $targetClass = $target::class; + $targetTemplates = DocblockParser::parseClassTemplates($targetClass); + if ($targetTemplates === []) { + return $bindings; + } + + $returnBaseClass = (string) $returnTypeNode->type; + if (isset(self::CONTEXT_SELF_REFERENCES[strtolower($returnBaseClass)]) && str_contains($activeFunction, '::')) { + $returnBaseClass = explode('::', $activeFunction, 2)[0]; + } + + $returnTemplateNames = array_keys(DocblockParser::parseClassTemplates($returnBaseClass)); + $targetTemplateNames = array_keys($targetTemplates); + $combinedBindings = [...$bindings, ...$topFrame]; + $changed = false; + + foreach ($returnTypeNode->genericTypes as $idx => $gtNode) { + if (! DocblockParser::typeReferencesTemplate($gtNode, $topFrame)) { + continue; + } + + $tName = null; + if (isset($returnTemplateNames[$idx]) && isset($targetTemplates[$returnTemplateNames[$idx]])) { + $tName = $returnTemplateNames[$idx]; + } elseif (\count($targetTemplateNames) === \count($returnTypeNode->genericTypes) && isset($targetTemplateNames[$idx])) { + $tName = $targetTemplateNames[$idx]; + } + + if ($tName === null) { + continue; + } + + $widenedNode = TemplateSubstitutor::substitute($gtNode, $combinedBindings); + $templateTag = $targetTemplates[$tName]; + + if ($templateTag->bound !== null) { + if (! self::checkVariance($widenedNode, $templateTag->bound, GenericTypeNode::VARIANCE_COVARIANT)) { + continue; + } + } + + $bindings[$tName] = $widenedNode; + $changed = true; + } + + if ($changed) { + $rawMappings = self::$classInheritedRawMappingsCache[$targetClass] ?? []; + foreach ($rawMappings as $rawTName => $rawNode) { + if (DocblockParser::typeReferencesTemplate($rawNode, $bindings)) { + $bindings[$rawTName] = TemplateSubstitutor::substitute($rawNode, $bindings); + } + } + } + + return $bindings; + } + /** * @param array $classVariances * @param array $candidateBindings diff --git a/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php b/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php new file mode 100644 index 00000000..be42bd4b --- /dev/null +++ b/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php @@ -0,0 +1,268 @@ + + */ + public array $elements = []; + + /** + * @param iterable $source + */ + public function __construct(iterable $source = []) + { + foreach ($source as $item) { + $this->elements[] = $item; + } + } + + /** + * @param E $element + */ + public function add(mixed $element): void + { + $this->elements[] = $element; + } +} + +/** + * @template E + */ +final class WideningImmutableSet +{ + /** + * @var WideningElementStore + */ + private WideningElementStore $store; + + /** + * @param iterable|WideningElementStore $data + */ + public function __construct(iterable|WideningElementStore $data = []) + { + $this->store = $data instanceof WideningElementStore + ? clone $data + : new WideningElementStore($data); + } + + /** + * @template NE + * @param NE $element + * @return self + */ + public function add(mixed $element): self + { + $store = clone $this->store; + $store->add($element); + + return new self($store); + } + + /** + * @param E $element + */ + public function contains(mixed $element): bool + { + return \in_array($element, $this->store->elements, true); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->store->elements; + } +} + +/** + * @template K of string|int|object + * @template V + */ +final class WideningKeyValueStore +{ + /** + * @var array + */ + private array $keys = []; + + /** + * @var array + */ + private array $values = []; + + /** + * @param iterable $source + */ + public function __construct(iterable $source = []) + { + foreach ($source as $k => $v) { + $this->put($k, $v); + } + } + + /** + * @param K $key + * @param V $value + */ + public function put(string|int|object $key, mixed $value): void + { + $hash = \is_object($key) ? 'o:' . spl_object_id($key) : (\is_int($key) ? 'i:' . $key : 's:' . $key); + $this->keys[$hash] = $key; + $this->values[$hash] = $value; + } + + /** + * @template NK of string|int|object + * @template NV + * @param iterable $source + */ + public function putAllFromAssoc(iterable $source): void + { + foreach ($source as $k => $v) { + $hash = \is_object($key = $k) ? 'o:' . spl_object_id($key) : (\is_int($key) ? 'i:' . $key : 's:' . $key); + $this->keys[$hash] = $k; + $this->values[$hash] = $v; + } + } + + /** + * @param K $key + * @return V|null + */ + public function get(string|int|object $key): mixed + { + $hash = \is_object($key) ? 'o:' . spl_object_id($key) : (\is_int($key) ? 'i:' . $key : 's:' . $key); + + return $this->values[$hash] ?? null; + } +} + +/** + * @template K of string|int|object + * @template V + */ +final class WideningImmutableMap +{ + /** + * @var WideningKeyValueStore + */ + private WideningKeyValueStore $store; + + /** + * @param iterable|WideningKeyValueStore $data + */ + public function __construct(iterable|WideningKeyValueStore $data = []) + { + $this->store = $data instanceof WideningKeyValueStore + ? clone $data + : new WideningKeyValueStore($data); + } + + /** + * @template NK of string|int|object + * @template NV + * @param NK $key + * @param NV $value + * @return self + */ + public function put(string|int|object $key, mixed $value): self + { + $entries = clone $this->store; + $entries->put($key, $value); + + return new self($entries); + } + + /** + * @template NK of string|int|object + * @template NV + * @param iterable $data + * @return self + */ + public function putAll(iterable $data): self + { + $entries = clone $this->store; + $entries->putAllFromAssoc($data); + + return new self($entries); + } + + /** + * @param K $key + * @return V|null + */ + public function get(string|int|object $key): mixed + { + return $this->store->get($key); + } +} + +describe('Cloned Store Template Widening in Immutable Collections & Maps', function () { + describe('1. Immutable Set Element Type Widening via Cloned Store', function () { + test('widens element type E to E|NE when cloning internal store in add()', function () { + $set = new WideningImmutableSet([1, 2]); + $obj = new stdClass(); + + $widened = $set->add($obj); + + expect($widened->toArray())->toBe([1, 2, $obj]) + ->and($widened->contains(1))->toBeTrue() + ->and($widened->contains($obj))->toBeTrue() + ; + }); + + test('preserves narrow type E on the original immutable set after widening clone', function () { + $set = new WideningImmutableSet([1, 2]); + $widened = $set->add('widened_string'); + + expect($widened->contains('widened_string'))->toBeTrue(); + + expect(fn () => $set->contains('widened_string'))->toThrow(TypeError::class); + }); + }); + + describe('2. Immutable Map Key and Value Type Widening via Cloned Store', function () { + test('widens key type K from int to int|string and allows subsequent get() with string key', function () { + $map = new WideningImmutableMap([1 => 'a', 2 => 'b']); + + $widened = $map->put('foo', 'c'); + + expect($widened->get(1))->toBe('a') + ->and($widened->get(2))->toBe('b') + ->and($widened->get('foo'))->toBe('c') + ; + }); + + test('widens key and value types via putAll() on cloned store', function () { + $map = new WideningImmutableMap([1 => 'a']); + + $widened = $map->putAll(['foo' => 100, 'bar' => 200]); + + expect($widened->get(1))->toBe('a') + ->and($widened->get('foo'))->toBe(100) + ->and($widened->get('bar'))->toBe(200) + ; + }); + + test('preserves narrow key type K on original map after widening clone', function () { + $map = new WideningImmutableMap([1 => 'a', 2 => 'b']); + $widened = $map->put('foo', 'c'); + + expect($widened->get('foo'))->toBe('c'); + + expect(fn () => $map->get('foo'))->toThrow(TypeError::class); + }); + }); +}); \ No newline at end of file From a806e8054311b5c94d47aa3ae3e8324f1732b9bb Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 22:24:35 +0800 Subject: [PATCH 15/37] Refactor ParamChecker to improve return type handling and add NullableClosureAndTemplateDefaultInference tests for enhanced type inference --- src/Internal/Checker/ParamChecker.php | 26 ++- ...ClosureAndTemplateDefaultInferenceTest.php | 177 ++++++++++++++++++ 2 files changed, 196 insertions(+), 7 deletions(-) create mode 100644 tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 4f07f34c..e4da7d72 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -665,10 +665,6 @@ private static function inferClosureReturnTemplate( array $templates, array $classTemplates ): void { - if (! $refClosure->hasReturnType()) { - return; - } - $templateName = null; $unwrapNullable = false; @@ -706,8 +702,19 @@ private static function inferClosureReturnTemplate( return; } - $inferred = self::extractTypeFromReflectionType($refClosure->getReturnType()); + $templateTag = $templates[$templateName]; + $inferred = $refClosure->hasReturnType() + ? self::extractTypeFromReflectionType($refClosure->getReturnType()) + : null; + if ($inferred === null) { + if ($templateTag->default !== null) { + $fallback = $templateTag->bound !== null + ? SpecialTypeResolver::resolve($templateTag->bound, $effectiveFunction, $thisObj) + : new IdentifierTypeNode('mixed'); + TemplateManager::bindTemplate($effectiveFunction, $targetObj, $templateName, $fallback); + } + return; } @@ -715,7 +722,6 @@ private static function inferClosureReturnTemplate( $inferred = $inferred->type; } - $templateTag = $templates[$templateName]; $satisfiesBound = true; if ($templateTag->bound !== null) { @@ -784,6 +790,10 @@ private static function extractCallableNodes(array $types): array { $callableNodes = []; foreach ($types as $paramName => $tNode) { + while ($tNode instanceof NullableTypeNode) { + $tNode = $tNode->type; + } + if ($tNode instanceof CallableTypeNode) { $callableNodes[$paramName] = $tNode; } elseif ($tNode instanceof UnionTypeNode) { @@ -888,7 +898,9 @@ private static function extractTypeFromClosureParameter(\ReflectionParameter $cl if ($cType instanceof \ReflectionNamedType) { $cTypeName = $cType->getName(); if ($cTypeName !== 'mixed' && (class_exists($cTypeName) || interface_exists($cTypeName) || SpecialTypeResolver::isBuiltInTypeKeyword($cTypeName))) { - return new IdentifierTypeNode($cTypeName); + $node = new IdentifierTypeNode($cTypeName); + + return $cType->allowsNull() && $cTypeName !== 'null' ? new NullableTypeNode($node) : $node; } } elseif ($cType instanceof \ReflectionUnionType) { $unionSubTypes = []; diff --git a/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php b/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php new file mode 100644 index 00000000..f1b7dcf4 --- /dev/null +++ b/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php @@ -0,0 +1,177 @@ + $entries + */ + public function __construct(private array $entries = []) + { + } + + /** + * @param K $key + * @return V + */ + public function get(int|string $key): mixed + { + return $this->entries[$key]; + } + + /** + * @template NV + * @param Closure(V, K): (NV|null) $transform + * @return self + */ + public function mapValuesNotNull(Closure $transform): self + { + $out = []; + foreach ($this->entries as $k => $v) { + $mapped = $transform($v, $k); + if ($mapped !== null) { + $out[$k] = $mapped; + } + } + + return new self($out); + } +} + +/** + * @template E + */ +final class ClosureInferredList +{ + /** + * @param list $items + */ + public function __construct(private array $items = []) + { + } + + /** + * @template K of array-key + * @template V = E + * @param Closure(E, int): K $keySelector + * @param ?Closure(E, int): V $valueTransform + * @return ClosureInferredMap + */ + public function toMap(Closure $keySelector, ?Closure $valueTransform = null): ClosureInferredMap + { + $out = []; + foreach ($this->items as $i => $item) { + $k = $keySelector($item, $i); + $out[$k] = $valueTransform === null ? $item : $valueTransform($item, $i); + } + + return new ClosureInferredMap($out); + } + + /** + * @template V = E + * @param ?Closure(E, int): V $valueTransform + * @return ClosureInferredMap + */ + public function toIndexedMap(?Closure $valueTransform = null): ClosureInferredMap + { + if ($valueTransform === null) { + return new ClosureInferredMap($this->items); + } + + $out = []; + foreach ($this->items as $i => $item) { + $out[$i] = $valueTransform($item, $i); + } + + return new ClosureInferredMap($out); + } +} + +/** + * Creates a ClosureInferredMap lazily via a factory closure (simulating lazy proxy without pre-bound V). + * + * @template K of array-key + * @template V + * @param Closure(): array $producer + * @return ClosureInferredMap + */ +function lazyClosureInferredMapOf(Closure $producer): ClosureInferredMap +{ + return new ClosureInferredMap($producer()); +} + +describe('Nullable Closure Parameters & Template Default Inference', function () { + describe('1. Nullable Closure Parameter (?Closure(E, int): V) with Template Default (@template V = E)', function () { + test('uses template default V = E when optional ?Closure is omitted (null)', function () { + $list = new ClosureInferredList(['apple', 'banana']); + + $map = $list->toIndexedMap(); + + expect($map->get(0))->toBe('apple') + ->and($map->get(1))->toBe('banana') + ; + }); + + test('infers V = int from ?Closure with explicit return typehint overriding default V = E', function () { + $list = new ClosureInferredList(['apple', 'banana']); + + $map = $list->toIndexedMap(fn (string $v): int => \strlen($v)); + + expect($map->get(0))->toBe(5) + ->and($map->get(1))->toBe(6) + ; + }); + + test('does not falsely lock V to default E when untyped ?Closure is provided to toIndexedMap()', function () { + $list = new ClosureInferredList(['apple', 'banana']); + + $map = $list->toIndexedMap(fn ($v) => \strlen($v)); + + expect($map->get(0))->toBe(5) + ->and($map->get(1))->toBe(6) + ; + }); + + test('does not falsely lock V to default E when untyped ?Closure is provided to toMap()', function () { + $list = new ClosureInferredList(['apple', 'banana', 'cherry']); + + $map = $list->toMap(fn ($v) => $v[0], fn ($v) => \strlen($v)); + + expect($map->get('a'))->toBe(5) + ->and($map->get('b'))->toBe(6) + ->and($map->get('c'))->toBe(6) + ; + }); + }); + + describe('2. Closure Parameter Nullability Inference (fn (?int $v) => ...)', function () { + test('preserves nullable ?int parameter typehint when inferring template V from closure', function () { + $map = lazyClosureInferredMapOf(fn () => [1 => 10, 2 => null, 3 => 30]); + + $mapped = $map->mapValuesNotNull(fn (?int $v) => $v === null ? null : $v * 2); + + expect($mapped->get(1))->toBe(20) + ->and($mapped->get(3))->toBe(60) + ; + }); + + test('rejects invalid non-int value when closure parameter is typed ?int', function () { + $map = lazyClosureInferredMapOf(fn () => [1 => 10, 2 => 'invalid_string']); + + expect(fn () => $map->mapValuesNotNull(fn (?int $v) => $v === null ? null : $v * 2)) + ->toThrow(TypeError::class) + ; + }); + }); +}); \ No newline at end of file From 4acaa29072cf8572076280d0cf1fc25d55317f71 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 12 Nov 2026 23:59:57 +0800 Subject: [PATCH 16/37] Enhance template inference by adding generator support in ParamChecker and TemplateManager; improve test coverage for nullable closures and template defaults --- src/Internal/Checker/ParamChecker.php | 18 +- src/Internal/Generics/TemplateManager.php | 162 ++++++++- .../ClonedStoreTemplateWideningTest.php | 11 +- ...eratorTransformAndFlattenInferenceTest.php | 310 ++++++++++++++++++ ...ClosureAndTemplateDefaultInferenceTest.php | 11 +- 5 files changed, 499 insertions(+), 13 deletions(-) create mode 100644 tests/TypeChecking/Generics/GeneratorTransformAndFlattenInferenceTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index e4da7d72..6690b392 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1480,6 +1480,10 @@ private static function inferGenericObjectNode( return; } + if (TemplateManager::isGeneratorInferred($value)) { + TemplateManager::markGeneratorInferred($thisObj, $effectiveFunction); + } + $targetTemplateNames = self::$classDeclaredTemplateNamesCache[$targetClassFqcn] ?? null; if ($targetTemplateNames === null) { @@ -1572,6 +1576,8 @@ private static function inferTemplatesFromIterableObject( $inferredVal = null; if ($value instanceof \Generator) { + TemplateManager::markGeneratorInferred($thisObj, $effectiveFunction); + try { $refGen = new \ReflectionGenerator($value); $genFunc = $refGen->getFunction(); @@ -1599,9 +1605,15 @@ private static function inferTemplatesFromIterableObject( if ($inferredKey !== null) { $inferredKey = TemplateSubstitutor::substitute($inferredKey, $boundOnGenThis, $allGenDeclaredTemplates); + if (ConditionalChecker::containsConditional($inferredKey)) { + $inferredKey = ConditionalChecker::resolve($inferredKey, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $effectiveFunction); + } } if ($inferredVal !== null) { $inferredVal = TemplateSubstitutor::substitute($inferredVal, $boundOnGenThis, $allGenDeclaredTemplates); + if (ConditionalChecker::containsConditional($inferredVal)) { + $inferredVal = ConditionalChecker::resolve($inferredVal, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $effectiveFunction); + } } } } @@ -1656,7 +1668,9 @@ private static function resolveTraversableItemTypes(object $value): array $contract = $returnTag !== null ? GeneratorEvaluator::extractContract($returnTag->type) : null; if ($contract !== null) { - $classTemplates = DocblockParser::parseClassTemplates($refClass->getName()); + $refMethod = $refClass->getMethod('getIterator'); + $declaringClassTemplates = DocblockParser::parseClassTemplates($refMethod->getDeclaringClass()->getName()); + $classTemplates = [...$declaringClassTemplates, ...DocblockParser::parseClassTemplates($refClass->getName())]; $aliases = DocblockParser::parseClassAliases($refClass->getName()); $key = $contract['key']; @@ -1670,7 +1684,6 @@ private static function resolveTraversableItemTypes(object $value): array $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $classTemplates) : null; $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $classTemplates) : null; - $refMethod = $refClass->getMethod('getIterator'); $key = $key !== null ? SpecialTypeResolver::resolve($key, $refMethod) : null; $val = $val !== null ? SpecialTypeResolver::resolve($val, $refMethod) : null; @@ -1729,7 +1742,6 @@ private static function resolveTraversableItemTypes(object $value): array } catch (\Throwable) { } - // 3. Fallback: single generic argument container (e.g. Collection) if (\count($boundOnInstance) === 1) { return [null, reset($boundOnInstance)]; } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 094872fa..d696e8f4 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -417,6 +417,20 @@ final class TemplateManager */ private static array $classInheritedRawMappingsCache = []; + /** + * WeakMap tracking instances whose template bindings were inferred from an unconsumed Generator's static docblock. + * + * @var WeakMap|null + */ + private static ?WeakMap $generatorInferredInstances = null; + + /** + * Tracks active function call frames where template bindings were inferred from a Generator. + * + * @var array + */ + private static array $generatorInferredCallFrames = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -436,6 +450,8 @@ public static function reset(): void self::$pendingInstantiations = []; self::$varianceCycleStack = []; self::$declaredClassTemplateNamesCache = []; + self::$generatorInferredInstances = null; + self::$generatorInferredCallFrames = []; } /** @@ -577,6 +593,29 @@ public static function normalizeGenericArguments(array $genericTypes, array $tem return $genericTypes; } + /** + * Marks an instance or active call frame as having template bindings inferred from a Generator's static docblock. + */ + public static function markGeneratorInferred(?object $instance, string $function = ''): void + { + if ($instance !== null) { + self::$generatorInferredInstances ??= new WeakMap(); + self::$generatorInferredInstances[$instance] = true; + } + + if ($function !== '') { + self::$generatorInferredCallFrames[$function] = true; + } + } + + /** + * Checks whether an instance's template bindings were inferred from a Generator's static docblock. + */ + public static function isGeneratorInferred(object $instance): bool + { + return self::$generatorInferredInstances !== null && isset(self::$generatorInferredInstances[$instance]); + } + /** * Copies bound generic template types from a source object to a cloned target object. * If cloned inside an active method that widens class templates via method templates in its @return type, @@ -589,6 +628,10 @@ public static function copyInstanceBindings(object $source, object $target): voi $bindings = self::widenClonedBindingsFromActiveCall($target, $bindings); self::$instanceTemplateBindings[$target] = $bindings; } + + if (self::isGeneratorInferred($source)) { + self::markGeneratorInferred($target); + } } /** @@ -607,8 +650,10 @@ public static function popCallFrame(string $function): void if (isset(self::$callStackBindings[$function])) { array_pop(self::$callStackBindings[$function]); if (self::$callStackBindings[$function] === []) { - unset(self::$callStackBindings[$function]); + unset(self::$callStackBindings[$function], self::$generatorInferredCallFrames[$function]); } + } else { + unset(self::$generatorInferredCallFrames[$function]); } } @@ -1244,6 +1289,13 @@ private static function bindSingleTemplateArgument( self::$instanceTemplateBindings ??= new WeakMap(); + if (self::$generatorInferredCallFrames !== [] && self::$callStackBindings !== []) { + $activeFunc = array_key_last(self::$callStackBindings); + if ($activeFunc !== null && isset(self::$generatorInferredCallFrames[$activeFunc])) { + self::markGeneratorInferred($instance); + } + } + $declaredVariance = $classVariances[$templateTag->name] ?? GenericTypeNode::VARIANCE_INVARIANT; $isReturnContext = str_contains($context, 'Return value'); $strictInvariance = Config::isStrictReturnGenericInvarianceEnabled(); @@ -1263,11 +1315,23 @@ private static function bindSingleTemplateArgument( $valid = self::checkVariance($existingTypeNode, $expectedTypeNode, $variance); if (! $valid) { - if ($forceBind) { + if ($forceBind || ($isReturnContext && self::isGeneratorInferred($instance))) { $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; + + $rawMappings = self::$classInheritedRawMappingsCache[$instance::class] ?? []; + foreach ($rawMappings as $tName => $rawNode) { + if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { + $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + } + } + self::$instanceTemplateBindings[$instance] = $bindings; + if ($isReturnContext && self::isGeneratorInferred($instance)) { + self::propagateGeneratorRefinementToProperties($instance, $templateName, $expectedTypeNode); + } + return null; } @@ -1327,6 +1391,45 @@ private static function bindSingleTemplateArgument( return null; } + /** + * Propagates a refined return-type template binding to any internal store properties of $instance + * that were also initialized from the same Generator. + */ + private static function propagateGeneratorRefinementToProperties(object $instance, string $templateName, TypeNode $expectedTypeNode): void + { + if (self::$instanceTemplateBindings === null) { + return; + } + + try { + $ref = new \ReflectionObject($instance); + foreach ($ref->getProperties() as $prop) { + if ($prop->isStatic() || ! $prop->isInitialized($instance)) { + continue; + } + + $propVal = $prop->getValue($instance); + if (! \is_object($propVal) || ! self::isGeneratorInferred($propVal)) { + continue; + } + + self::$instanceTemplateBindings ??= new WeakMap(); + $propBindings = self::$instanceTemplateBindings[$propVal] ?? []; + if (isset($propBindings[$templateName])) { + $propBindings[$templateName] = $expectedTypeNode; + $rawMappings = self::$classInheritedRawMappingsCache[$propVal::class] ?? []; + foreach ($rawMappings as $tName => $rawNode) { + if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { + $propBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $propBindings); + } + } + self::$instanceTemplateBindings[$propVal] = $propBindings; + } + } + } catch (\Throwable) { + } + } + /** * Checks if a type node contains unspecialized type placeholders (mixed, array-key, or *). */ @@ -1457,7 +1560,16 @@ public static function resolveInheritedTemplates(object $instance, string $targe } } - self::$instanceTemplateBindings[$instance] = [...$existing, ...$specializedBindings]; + foreach ($rawMappings as $tName => $rawNode) { + if (! isset($specializedBindings[$tName]) && $existing !== [] && DocblockParser::typeReferencesTemplate($rawNode, $existing)) { + $specializedBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $existing); + } + } + + $merged = [...$existing, ...$specializedBindings]; + if ($merged !== []) { + self::$instanceTemplateBindings[$instance] = $merged; + } } /** @@ -1478,6 +1590,7 @@ private static function computeClassInheritedBindings(string $actualClassName, a /** @var class-string $actualClassName */ $ref = new \ReflectionClass($actualClassName); $classHierarchy = HierarchyResolver::getClassHierarchy($ref); + $rootDeclaredTemplates = array_fill_keys(self::getDeclaredClassTemplateNames($actualClassName), true); foreach ($classHierarchy as $hierClass) { $docsToInspect = self::collectDocsForClassHierarchyMember($hierClass); @@ -1497,7 +1610,15 @@ private static function computeClassInheritedBindings(string $actualClassName, a foreach ($inheritedTags as $inheritedTag) { $genericTypeNode = $inheritedTag->type; if ($genericTypeNode instanceof GenericTypeNode) { - self::collectInheritedGenericTagBindings($genericTypeNode, $hierClass, $declaredTemplateNames, $actualClassName, $bindings, $rawBindings); + self::collectInheritedGenericTagBindings( + $genericTypeNode, + $hierClass, + $declaredTemplateNames, + $actualClassName, + $bindings, + $rawBindings, + $rootDeclaredTemplates + ); } } } @@ -1513,6 +1634,7 @@ private static function computeClassInheritedBindings(string $actualClassName, a * @param array $declaredTemplateNames * @param array $bindings * @param array $rawBindings + * @param array $rootDeclaredTemplates * @param \ReflectionClass $hierClass */ private static function collectInheritedGenericTagBindings( @@ -1521,7 +1643,8 @@ private static function collectInheritedGenericTagBindings( array $declaredTemplateNames, string $actualClassName, array &$bindings, - array &$rawBindings = [] + array &$rawBindings = [], + array $rootDeclaredTemplates = [] ): void { $parentName = SpecialTypeResolver::resolveFqcn((string) $genericTypeNode->type, $hierClass); $isHierarchyMember = is_a($actualClassName, $parentName, true) || trait_exists($parentName); @@ -1574,7 +1697,9 @@ private static function collectInheritedGenericTagBindings( if ($hierAliases !== []) { $typeArg = DocblockParser::substituteAliases($typeArg, $hierAliases); } - if ($bindings !== []) { + if ($rawBindings !== []) { + $typeArg = TemplateSubstitutor::substitute($typeArg, $rawBindings); + } elseif ($bindings !== []) { $typeArg = TemplateSubstitutor::substitute($typeArg, $bindings); } $resolved = self::resolveTypeNodeAst($typeArg, $hierClass); @@ -1589,11 +1714,11 @@ private static function collectInheritedGenericTagBindings( $isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($resolved->name); $isRealType = self::isRealTypeSymbol($resolved->name); - if (! $isBuiltIn && ! $isRealType && ! isset($declaredTemplateNames[$resolved->name])) { + if (! $isBuiltIn && ! $isRealType && ! isset($declaredTemplateNames[$resolved->name]) && ! isset($rootDeclaredTemplates[$resolved->name])) { continue; } - if (isset($declaredTemplateNames[$resolved->name]) && $resolved->name === $templateName) { + if ((isset($declaredTemplateNames[$resolved->name]) || isset($rootDeclaredTemplates[$resolved->name])) && $resolved->name === $templateName) { continue; } } @@ -1603,8 +1728,29 @@ private static function collectInheritedGenericTagBindings( } } + if (isset($rootDeclaredTemplates[$templateName]) && DocblockParser::typeReferencesTemplate($resolved, $rootDeclaredTemplates)) { + continue; + } + $rawBindings[$templateName] ??= $resolved; + if (DocblockParser::typeReferencesTemplate($resolved, $rootDeclaredTemplates)) { + $boundOnlyFallbacks = []; + foreach ($rootDeclaredTemplates as $rootTName => $_) { + $rootTag = $hierTemplates[$rootTName] ?? null; + $boundOrDef = $rootTag !== null ? ($rootTag->default ?? $rootTag->bound) : null; + if ($boundOrDef !== null) { + $boundOnlyFallbacks[$rootTName] = SpecialTypeResolver::resolve($boundOrDef, $hierClass); + } + } + + if (\count($boundOnlyFallbacks) === \count($rootDeclaredTemplates)) { + $bindings[$templateName] ??= TemplateSubstitutor::substitute($resolved, $boundOnlyFallbacks); + } + + continue; + } + if (DocblockParser::typeReferencesTemplate($resolved, $declaredTemplateNames) && $hierFallbackBindings !== []) { $resolved = TemplateSubstitutor::substitute($resolved, $hierFallbackBindings); } diff --git a/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php b/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php index be42bd4b..6e11ee2b 100644 --- a/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php +++ b/tests/TypeChecking/Generics/ClonedStoreTemplateWideningTest.php @@ -58,7 +58,9 @@ public function __construct(iterable|WideningElementStore $data = []) /** * @template NE + * * @param NE $element + * * @return self */ public function add(mixed $element): self @@ -126,6 +128,7 @@ public function put(string|int|object $key, mixed $value): void /** * @template NK of string|int|object * @template NV + * * @param iterable $source */ public function putAllFromAssoc(iterable $source): void @@ -139,6 +142,7 @@ public function putAllFromAssoc(iterable $source): void /** * @param K $key + * * @return V|null */ public function get(string|int|object $key): mixed @@ -173,8 +177,10 @@ public function __construct(iterable|WideningKeyValueStore $data = []) /** * @template NK of string|int|object * @template NV + * * @param NK $key * @param NV $value + * * @return self */ public function put(string|int|object $key, mixed $value): self @@ -188,7 +194,9 @@ public function put(string|int|object $key, mixed $value): self /** * @template NK of string|int|object * @template NV + * * @param iterable $data + * * @return self */ public function putAll(iterable $data): self @@ -201,6 +209,7 @@ public function putAll(iterable $data): self /** * @param K $key + * * @return V|null */ public function get(string|int|object $key): mixed @@ -265,4 +274,4 @@ public function get(string|int|object $key): mixed expect(fn () => $map->get('foo'))->toThrow(TypeError::class); }); }); -}); \ No newline at end of file +}); diff --git a/tests/TypeChecking/Generics/GeneratorTransformAndFlattenInferenceTest.php b/tests/TypeChecking/Generics/GeneratorTransformAndFlattenInferenceTest.php new file mode 100644 index 00000000..fbcac7fa --- /dev/null +++ b/tests/TypeChecking/Generics/GeneratorTransformAndFlattenInferenceTest.php @@ -0,0 +1,310 @@ + <- ReadWriteElementStore <- AbstractElementStore <- ArrayIndexStore + * + * @template E + * + * @extends IteratorAggregate + */ +interface GenReadOnlyStore extends IteratorAggregate +{ +} + +/** + * @template V + * + * @implements GenReadOnlyStore + */ +abstract class GenAbstractStore implements GenReadOnlyStore +{ + /** + * @var list + */ + protected array $elements = []; + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return new \ArrayIterator($this->elements); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->elements; + } +} + +/** + * @template E + * + * @extends GenAbstractStore + */ +final class GenArrayIndexStore extends GenAbstractStore +{ + /** + * @param iterable $source + */ + public function __construct(iterable $source = []) + { + foreach ($source as $item) { + $this->elements[] = $item; + } + } +} + +/** + * @template K + * @template V + */ +abstract class GenAbstractOperation +{ + /** + * @param iterable $data + */ + public function __construct(protected iterable $data) + { + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @extends GenAbstractOperation + */ +final class GenFilterOperation extends GenAbstractOperation +{ + /** + * @param callable(V, K): bool $predicate + * + * @return Generator + */ + public function byPredicate(callable $predicate): Generator + { + foreach ($this->data as $k => $v) { + if ($predicate($v, $k)) { + yield $k => $v; + } + } + } + + /** + * @param callable(V): bool $predicate + * + * @return Generator + */ + public function byValue(callable $predicate): Generator + { + return $this->byPredicate(fn ($v, $k) => $predicate($v)); + } +} + +/** + * @template V + * + * @extends GenAbstractOperation + */ +final class GenFlattenOperation extends GenAbstractOperation +{ + /** + * @return Generator ? value-of : V)> + */ + public function items(): Generator + { + foreach ($this->data as $v) { + if (is_iterable($v)) { + foreach ($v as $x) { + yield $x; + } + } else { + yield $v; + } + } + } +} + +/** + * @template E + */ +final class GenImmutableCollection +{ + /** + * @var GenArrayIndexStore + */ + private GenArrayIndexStore $store; + + /** + * @param iterable $data + */ + public function __construct(iterable $data = []) + { + $this->store = $data instanceof GenArrayIndexStore + ? clone $data + : new GenArrayIndexStore($data); + } + + /** + * @template T + * + * @param class-string $type + * + * @return self + */ + public function filterInstanceOf(string $type): self + { + return self::of((new GenFilterOperation($this->store))->byValue(fn ($v) => $v instanceof $type)); + } + + /** + * @return self<(E is null ? never : E)> + */ + public function filterNotNull(): self + { + return self::of((new GenFilterOperation($this->store))->byValue(fn ($v) => $v !== null)); + } + + /** + * @return self<(E is iterable ? value-of : E)> + */ + public function flatten(): self + { + return self::of((new GenFlattenOperation($this->store))->items()); + } + + /** + * @param E $element + */ + public function contains(mixed $element): bool + { + return \in_array($element, $this->store->toArray(), true); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->store->toArray(); + } + + /** + * @template NE + * + * @param iterable $data + * + * @return self + */ + public static function of(iterable $data = []): self + { + return new self($data); + } +} + +describe('Generator-Backed Transformations (filterInstanceOf, filterNotNull, flatten)', function () { + describe('1. filterInstanceOf() Narrowing via FilterOperation Generator', function () { + test('narrows union element type Dog|Cat to Dog', function () { + $dog1 = new GenFilterDog('Rex'); + $cat = new GenFilterCat('Whiskers'); + $dog2 = new GenFilterDog('Buddy'); + + $collection = GenImmutableCollection::of([$dog1, $cat, $dog2]); + $filtered = $collection->filterInstanceOf(GenFilterDog::class); + + expect($filtered->toArray())->toBe([$dog1, $dog2]) + ->and($filtered->contains($dog1))->toBeTrue() + ; + + // Filtered collection is now strictly GenImmutableCollection + expect(fn () => $filtered->contains($cat))->toThrow(TypeError::class); + }); + + test('narrows union element type Dog|Cat to Walkable interface', function () { + $dog = new GenFilterDog('Rex'); + $cat = new GenFilterCat('Whiskers'); + + $collection = GenImmutableCollection::of([$dog, $cat]); + $filtered = $collection->filterInstanceOf(GenFilterWalkable::class); + + expect($filtered->toArray())->toBe([$dog]); + }); + + test('returns empty collection typed to target class when no elements match', function () { + $cat = new GenFilterCat('Whiskers'); + + $collection = GenImmutableCollection::of([$cat]); + $filtered = $collection->filterInstanceOf(GenFilterDog::class); + + expect($filtered->toArray())->toBe([]); + }); + }); + + describe('2. filterNotNull() Narrowing via FilterOperation Generator', function () { + test('narrows all-null collection to empty collection of never without return violation', function () { + $collection = GenImmutableCollection::of([null, null, null]); + $filtered = $collection->filterNotNull(); + + expect($filtered->toArray())->toBe([]); + }); + }); + + describe('3. flatten() with Conditional value-of Return Type and Multi-Hop Store Hierarchy', function () { + test('flattens nested arrays of ints', function () { + $collection = GenImmutableCollection::of([[1, 2], [3, 4], [5]]); + $flattened = $collection->flatten(); + + expect($flattened->toArray())->toBe([1, 2, 3, 4, 5]); + }); + + test('flattens mixed array and scalar elements', function () { + $collection = GenImmutableCollection::of([[1, 2], 3, [4]]); + $flattened = $collection->flatten(); + + expect($flattened->toArray())->toBe([1, 2, 3, 4]); + }); + + test('preserves non-iterable object element type when flattening flat object collection', function () { + $dog1 = new GenFilterDog('Rex'); + $dog2 = new GenFilterDog('Buddy'); + + $collection = GenImmutableCollection::of([$dog1, $dog2]); + $flattened = $collection->flatten(); + + expect($flattened->toArray())->toBe([$dog1, $dog2]); + }); + }); +}); diff --git a/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php b/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php index f1b7dcf4..2fd12a83 100644 --- a/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php +++ b/tests/TypeChecking/Generics/NullableClosureAndTemplateDefaultInferenceTest.php @@ -22,6 +22,7 @@ public function __construct(private array $entries = []) /** * @param K $key + * * @return V */ public function get(int|string $key): mixed @@ -31,7 +32,9 @@ public function get(int|string $key): mixed /** * @template NV + * * @param Closure(V, K): (NV|null) $transform + * * @return self */ public function mapValuesNotNull(Closure $transform): self @@ -63,8 +66,10 @@ public function __construct(private array $items = []) /** * @template K of array-key * @template V = E + * * @param Closure(E, int): K $keySelector * @param ?Closure(E, int): V $valueTransform + * * @return ClosureInferredMap */ public function toMap(Closure $keySelector, ?Closure $valueTransform = null): ClosureInferredMap @@ -80,7 +85,9 @@ public function toMap(Closure $keySelector, ?Closure $valueTransform = null): Cl /** * @template V = E + * * @param ?Closure(E, int): V $valueTransform + * * @return ClosureInferredMap */ public function toIndexedMap(?Closure $valueTransform = null): ClosureInferredMap @@ -103,7 +110,9 @@ public function toIndexedMap(?Closure $valueTransform = null): ClosureInferredMa * * @template K of array-key * @template V + * * @param Closure(): array $producer + * * @return ClosureInferredMap */ function lazyClosureInferredMapOf(Closure $producer): ClosureInferredMap @@ -174,4 +183,4 @@ function lazyClosureInferredMapOf(Closure $producer): ClosureInferredMap ; }); }); -}); \ No newline at end of file +}); From 42286d4aee340eada6ef0e61ce3ec081e4ae01e5 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 13 Nov 2026 01:50:52 +0800 Subject: [PATCH 17/37] Refactor TemplateManager to utilize WeakMap for instance template bindings; add SelfPreserving subtype variance tests for enhanced type safety in generics --- src/Internal/Generics/TemplateManager.php | 22 +- .../SelfPreservingSubtypeVarianceTest.php | 214 ++++++++++++++++++ 2 files changed, 230 insertions(+), 6 deletions(-) create mode 100644 tests/TypeChecking/Generics/SelfPreservingSubtypeVarianceTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index d696e8f4..97f77007 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1374,7 +1374,9 @@ private static function bindSingleTemplateArgument( } if ($forceBind || ! isset($existingBindings[$templateName])) { - $bindings = self::$instanceTemplateBindings[$instance] ?? []; + $map = self::$instanceTemplateBindings ??= new WeakMap(); + + $bindings = $map[$instance] ?? []; $boundNode = $isWildcardOrMixed && $templateTag->bound !== null ? $templateTag->bound : $expectedTypeNode; $bindings[$templateName] = $boundNode; @@ -1385,7 +1387,7 @@ private static function bindSingleTemplateArgument( } } - self::$instanceTemplateBindings[$instance] = $bindings; + $map[$instance] = $bindings; } return null; @@ -1401,6 +1403,8 @@ private static function propagateGeneratorRefinementToProperties(object $instanc return; } + $map = self::$instanceTemplateBindings; + try { $ref = new \ReflectionObject($instance); foreach ($ref->getProperties() as $prop) { @@ -1413,8 +1417,7 @@ private static function propagateGeneratorRefinementToProperties(object $instanc continue; } - self::$instanceTemplateBindings ??= new WeakMap(); - $propBindings = self::$instanceTemplateBindings[$propVal] ?? []; + $propBindings = $map[$propVal] ?? []; if (isset($propBindings[$templateName])) { $propBindings[$templateName] = $expectedTypeNode; $rawMappings = self::$classInheritedRawMappingsCache[$propVal::class] ?? []; @@ -1423,7 +1426,7 @@ private static function propagateGeneratorRefinementToProperties(object $instanc $propBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $propBindings); } } - self::$instanceTemplateBindings[$propVal] = $propBindings; + $map[$propVal] = $propBindings; } } } catch (\Throwable) { @@ -1981,7 +1984,7 @@ private static function checkIdentifierAgainstGenericVariance( return false; } - if ($variance !== GenericTypeNode::VARIANCE_COVARIANT) { + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { return false; } @@ -1993,6 +1996,13 @@ private static function checkIdentifierAgainstGenericVariance( try { $classBindings = self::getClassInheritedBindings($existing->name); + + if ($variance === GenericTypeNode::VARIANCE_INVARIANT) { + if ($classBindings === [] || self::getDeclaredClassTemplateNames($existing->name) !== []) { + return false; + } + } + if ($classBindings !== []) { $parentTemplates = DocblockParser::parseClassTemplates((string) $expected->type); $parentTemplateNames = array_keys($parentTemplates); diff --git a/tests/TypeChecking/Generics/SelfPreservingSubtypeVarianceTest.php b/tests/TypeChecking/Generics/SelfPreservingSubtypeVarianceTest.php new file mode 100644 index 00000000..4c2e04ab --- /dev/null +++ b/tests/TypeChecking/Generics/SelfPreservingSubtypeVarianceTest.php @@ -0,0 +1,214 @@ + + */ + public function toArray(): array; +} + +/** + * @template K of array-key + * @template V + */ +interface SelfPreservingMapInterface +{ + /** + * @param K $key + * + * @return V + */ + public function get(int|string $key): mixed; +} + +/** + * @template K of array-key + * @template V + * + * @implements SelfPreservingMapInterface + */ +final class SelfPreservingHashMap implements SelfPreservingMapInterface +{ + /** + * @param array $entries + */ + public function __construct(private array $entries = []) + { + } + + /** + * @param K $key + * + * @return V + */ + public function get(int|string $key): mixed + { + return $this->entries[$key]; + } +} + +/** + * @template E + * + * @implements SelfPreservingSetInterface + */ +class SelfPreservingBaseSet implements SelfPreservingSetInterface +{ + /** + * @var list + */ + protected array $items = []; + + /** + * @param iterable $data + */ + public function __construct(iterable $data = []) + { + foreach ($data as $item) { + $this->items[] = $item; + } + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->items; + } + + /** + * @template GK of array-key + * @template GV + * + * @param Closure(E): GK $keySelector + * @param (Closure(E): GV)|null $valueTransform + * + * @return ($valueTransform is null ? SelfPreservingMapInterface> : SelfPreservingMapInterface>) + */ + public function groupBy(Closure $keySelector, ?Closure $valueTransform = null): SelfPreservingMapInterface + { + $buckets = []; + foreach ($this->items as $item) { + $k = $keySelector($item); + $buckets[$k][] = $valueTransform !== null ? $valueTransform($item) : $item; + } + + $wrapped = []; + foreach ($buckets as $k => $bucket) { + $wrapped[$k] = $valueTransform !== null + ? new self($bucket) + : $this->newCollectionOf($bucket); + } + + return new SelfPreservingHashMap($wrapped); + } + + /** + * @template NE + * + * @param iterable $data + * + * @return SelfPreservingSetInterface + */ + protected function newCollectionOf(iterable $data): SelfPreservingSetInterface + { + return new self($data); + } +} + +/** + * Non-generic domain subtype that fixes E = SelfPreservingItem via @implements + * and overrides newCollectionOf() to return `new static($data)` (matching Noctud's TraitItemCollection & LineItems). + * + * @implements SelfPreservingSetInterface + */ +final class SelfPreservingDomainSet extends SelfPreservingBaseSet implements SelfPreservingSetInterface +{ + /** + * @param iterable $data + */ + public function __construct(iterable $data = []) + { + parent::__construct($data); + } + + /** + * @param iterable $data + * + * @return static + */ + protected function newCollectionOf(iterable $data): SelfPreservingSetInterface + { + return new self($data); + } +} + +/** + * Non-generic subtype fixing E = string (mismatched element type for negative test). + * + * @implements SelfPreservingSetInterface + */ +final class SelfPreservingStringSet extends SelfPreservingBaseSet implements SelfPreservingSetInterface +{ +} + +/** + * Helper to test negative case where a concrete subtype with the WRONG fixed template argument is returned. + */ +final class SelfPreservingMismatchProbe +{ + /** + * @return SelfPreservingMapInterface> + */ + public static function getMismatchedMap(): SelfPreservingMapInterface + { + return new SelfPreservingHashMap(['bad' => new SelfPreservingStringSet(['a', 'b'])]); + } +} + +describe('Self-Preserving Concrete Subtype Variance in Nested Generic Containers', function () { + test('accepts concrete subtype fixing E = SelfPreservingItem when return type expects Map>', function () { + $item1 = new SelfPreservingItem(1, true); + $item2 = new SelfPreservingItem(2, false); + + $collection = new SelfPreservingDomainSet([$item1, $item2]); + + $groups = $collection->groupBy(static fn (SelfPreservingItem $i): string => $i->swapped ? 'y' : 'n'); + $ids = $collection->groupBy( + static fn (SelfPreservingItem $i): string => $i->swapped ? 'y' : 'n', + static fn (SelfPreservingItem $i): int => $i->id + ); + + expect($groups->get('y'))->toBeInstanceOf(SelfPreservingDomainSet::class) + ->and($groups->get('y')->toArray())->toBe([$item1]) + ->and($ids->get('y')->toArray())->toBe([1]) + ; + }); + + test('rejects concrete subtype when its fixed template argument does not match expected nested generic type', function () { + expect(fn () => SelfPreservingMismatchProbe::getMismatchedMap()) + ->toThrow(TypeError::class) + ; + }); +}); From 245c90ee9676b3dc4cbe21bc01891a7b12ace31e Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 13 Nov 2026 14:11:20 +0800 Subject: [PATCH 18/37] Enhance ParamChecker and TemplateManager with improved call binding handling; add propagation logic for instance properties and introduce LazyProxy and ClonedStore tests for type inference validation --- src/Internal/Checker/ParamChecker.php | 2 +- src/Internal/Generics/TemplateManager.php | 109 +++- .../Generics/LazyProxyAndClonedStoreTest.php | 482 ++++++++++++++++++ 3 files changed, 586 insertions(+), 7 deletions(-) create mode 100644 tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 6690b392..31ab0fe0 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -312,7 +312,7 @@ private static function prepareGenericBindings( $hasTemplatesToClear = \count($methodTemplates) > 0 || ($thisObj === null && \count($classTemplates) > 0); if ($hasTemplatesToClear) { - TemplateManager::clearCallBindings($effectiveFunction, [...$classTemplates, ...$methodTemplates]); + TemplateManager::clearCallBindings($effectiveFunction, [...$classTemplates, ...$methodTemplates], $thisObj); } if (\count($classTemplates) > 0 && str_contains($effectiveFunction, '::')) { diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 97f77007..26ca0452 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -431,6 +431,20 @@ final class TemplateManager */ private static array $generatorInferredCallFrames = []; + /** + * Call stack frames storing $this objects per function or method call. + * + * @var array> + */ + private static array $callStackThis = []; + + /** + * Cycle-guarded tracker for property binding propagation. + * + * @var array + */ + private static array $propagationStack = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -452,6 +466,8 @@ public static function reset(): void self::$declaredClassTemplateNamesCache = []; self::$generatorInferredInstances = null; self::$generatorInferredCallFrames = []; + self::$callStackThis = []; + self::$propagationStack = []; } /** @@ -637,9 +653,10 @@ public static function copyInstanceBindings(object $source, object $target): voi /** * Pushes a new empty call frame onto the stack for a function execution. */ - public static function pushCallFrame(string $function): void + public static function pushCallFrame(string $function, ?object $thisObj = null): void { self::$callStackBindings[$function][] = []; + self::$callStackThis[$function][] = $thisObj; } /** @@ -649,8 +666,11 @@ public static function popCallFrame(string $function): void { if (isset(self::$callStackBindings[$function])) { array_pop(self::$callStackBindings[$function]); + if (isset(self::$callStackThis[$function])) { + array_pop(self::$callStackThis[$function]); + } if (self::$callStackBindings[$function] === []) { - unset(self::$callStackBindings[$function], self::$generatorInferredCallFrames[$function]); + unset(self::$callStackBindings[$function], self::$callStackThis[$function], self::$generatorInferredCallFrames[$function]); } } else { unset(self::$generatorInferredCallFrames[$function]); @@ -662,9 +682,23 @@ public static function popCallFrame(string $function): void * * @param array $templates */ - public static function clearCallBindings(string $function, array $templates): void + public static function clearCallBindings(string $function, array $templates, ?object $thisObj = null): void { - self::pushCallFrame($function); + self::pushCallFrame($function, $thisObj); + } + + /** + * @return object|null + */ + private static function getTopCallThis(string $function): ?object + { + if (! isset(self::$callStackThis[$function]) || self::$callStackThis[$function] === []) { + return null; + } + + $top = end(self::$callStackThis[$function]); + + return $top !== false ? $top : null; } /** @@ -1043,6 +1077,8 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t // Silently ignore reflection or parsing errors } + self::propagateBindingsToInstanceProperties($instance); + return null; } @@ -1096,6 +1132,59 @@ public static function applyClassTemplateDefaults(object $instance, array $class } } + /** + * Propagates resolved class template bindings on an instance to any of its object properties + * whose declared types reference those class templates (e.g. $this->store with @var KeyValueStore). + */ + private static function propagateBindingsToInstanceProperties(object $instance): void + { + if (self::$instanceTemplateBindings === null || ! isset(self::$instanceTemplateBindings[$instance])) { + return; + } + + $instanceBindings = self::$instanceTemplateBindings[$instance]; + if ($instanceBindings === []) { + return; + } + + $oid = spl_object_id($instance); + if (isset(self::$propagationStack[$oid])) { + return; + } + self::$propagationStack[$oid] = true; + + try { + $ref = new \ReflectionObject($instance); + foreach ($ref->getProperties() as $prop) { + if ($prop->isStatic() || ! $prop->isInitialized($instance)) { + continue; + } + + $propVal = $prop->getValue($instance); + if (! \is_object($propVal)) { + continue; + } + + $propType = DocblockParser::parseProperty($instance::class, $prop->getName()); + if (! ($propType instanceof GenericTypeNode)) { + continue; + } + + if (! DocblockParser::typeReferencesTemplate($propType, $instanceBindings)) { + continue; + } + + $resolvedPropType = TemplateSubstitutor::substitute($propType, $instanceBindings); + if ($resolvedPropType instanceof GenericTypeNode) { + self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true); + } + } + } catch (\Throwable) { + } finally { + unset(self::$propagationStack[$oid]); + } + } + /** * @param \ReflectionClass $ref * @@ -1188,8 +1277,11 @@ private static function widenClonedBindingsFromActiveCall(object $target, array $returnTemplateNames = array_keys(DocblockParser::parseClassTemplates($returnBaseClass)); $targetTemplateNames = array_keys($targetTemplates); - $combinedBindings = [...$bindings, ...$topFrame]; + $activeThis = self::getTopCallThis($activeFunction); + $thisBindings = $activeThis !== null ? self::getBoundTemplatesForInstance($activeThis) : []; + $combinedBindings = [...$thisBindings, ...$bindings, ...$topFrame]; $changed = false; + $isReturnBaseInstance = is_a($target, $returnBaseClass); foreach ($returnTypeNode->genericTypes as $idx => $gtNode) { if (! DocblockParser::typeReferencesTemplate($gtNode, $topFrame)) { @@ -1199,7 +1291,7 @@ private static function widenClonedBindingsFromActiveCall(object $target, array $tName = null; if (isset($returnTemplateNames[$idx]) && isset($targetTemplates[$returnTemplateNames[$idx]])) { $tName = $returnTemplateNames[$idx]; - } elseif (\count($targetTemplateNames) === \count($returnTypeNode->genericTypes) && isset($targetTemplateNames[$idx])) { + } elseif ($isReturnBaseInstance && \count($targetTemplateNames) === \count($returnTypeNode->genericTypes) && isset($targetTemplateNames[$idx])) { $tName = $targetTemplateNames[$idx]; } @@ -1208,6 +1300,11 @@ private static function widenClonedBindingsFromActiveCall(object $target, array } $widenedNode = TemplateSubstitutor::substitute($gtNode, $combinedBindings); + + if (DocblockParser::typeReferencesTemplate($widenedNode, array_fill_keys($returnTemplateNames, true))) { + continue; + } + $templateTag = $targetTemplates[$tName]; if ($templateTag->bound !== null) { diff --git a/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php b/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php new file mode 100644 index 00000000..2d3ce7f3 --- /dev/null +++ b/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php @@ -0,0 +1,482 @@ + + */ +interface ReproKeyValueStore extends IteratorAggregate +{ + public function count(): int; +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements ReproKeyValueStore + */ +final class ReproHashStore implements ReproKeyValueStore +{ + /** + * @var array + */ + private array $data = []; + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromAssoc(iterable $source): self + { + $store = new self(); + foreach ($source as $k => $v) { + $store->data[$k] = $v; + } + + return $store; + } + + public function count(): int + { + return \count($this->data); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + yield from $this->data; + } +} + +/** + * Note: intentionally has no upper bound on E (just like Noctud\Collection\Set\Set). + * + * @template E + * + * @extends IteratorAggregate + */ +interface ReproSet extends IteratorAggregate +{ +} + +/** + * Note: adds upper bound on E (just like Noctud\Collection\Map\View\MapKeySet). + * + * @template E of string|int|bool|float|object + * + * @implements ReproSet + */ +final class ReproMapKeySet implements ReproSet +{ + /** + * @template TV + * + * @param ReproKeyValueStore $store + */ + public function __construct(private ReproKeyValueStore $store) + { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->store as $k => $v) { + yield $k; + } + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +final class ReproLazyMap +{ + /** + * @var ReproKeyValueStore + */ + private ReproKeyValueStore $store; + + /** + * @var ReproSet + */ + public ReproSet $keys { + get => $this->keys ??= new ReproMapKeySet($this->store); + } + + /** + * @param iterable|Closure(): iterable $data + */ + public function __construct(iterable|Closure $data = []) + { + if ($data instanceof Closure) { + $reflector = new ReflectionClass(ReproHashStore::class); + $this->store = $reflector->newLazyProxy( + fn (ReproHashStore $object): ReproHashStore => $object::fromAssoc($data()) + ); + } else { + $this->store = ReproHashStore::fromAssoc($data); + } + } + + public function count(): int + { + return $this->store->count(); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return ReproLazyMap + */ +function reproMakeLazyMap(iterable $data): ReproLazyMap +{ + return new ReproLazyMap(fn () => $data); +} + +// ========================================================================= +// Pattern 2: Cloned Internal Store in Widening Methods (Noctud ImmutableListLogic) +// ========================================================================= + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface ReproReadOnlyElementStore extends IteratorAggregate +{ +} + +/** + * Note: uses template V while subclass ArrayIndexStore uses E (just like Noctud). + * + * @template V + * + * @extends ReproReadOnlyElementStore + */ +interface ReproReadWriteIndexedStore extends ReproReadOnlyElementStore +{ + /** + * @param V $element + */ + public function add(mixed $element): void; + + /** + * @param iterable $source + */ + public function addAll(iterable $source): void; +} + +/** + * @template E + * + * @implements ReproReadWriteIndexedStore + */ +final class ReproArrayIndexStore implements ReproReadWriteIndexedStore +{ + /** + * @var list + */ + private array $elements = []; + + /** + * @param iterable $source + */ + public function __construct(iterable $source = []) + { + foreach ($source as $el) { + $this->elements[] = $el; + } + } + + /** + * @param E $element + */ + public function add(mixed $element): void + { + $this->elements[] = $element; + } + + /** + * @param iterable $source + */ + public function addAll(iterable $source): void + { + foreach ($source as $el) { + $this->elements[] = $el; + } + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->elements); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->elements; + } +} + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface ReproImmutableList extends IteratorAggregate +{ + /** + * @template NE + * + * @param NE $element + * + * @return ReproImmutableList + */ + public function add(mixed $element): ReproImmutableList; + + /** + * @template NE + * + * @param iterable $elements + * + * @return ReproImmutableList + */ + public function addAll(iterable $elements): ReproImmutableList; + + /** + * @return list + */ + public function toArray(): array; +} + +/** + * @template E + * + * @implements ReproImmutableList + */ +final class ReproImmutableArrayList implements ReproImmutableList +{ + /** + * @var ReproReadWriteIndexedStore + */ + private ReproReadWriteIndexedStore $store; + + /** + * @param iterable|Closure(): iterable $data + */ + public function __construct(iterable|Closure $data = []) + { + if ($data instanceof Closure) { + $reflector = new ReflectionClass(ReproArrayIndexStore::class); + $this->store = $reflector->newLazyProxy( + fn (): ReproArrayIndexStore => new ReproArrayIndexStore($data()) + ); + } elseif ($data instanceof ReproArrayIndexStore) { + $this->store = clone $data; + } else { + $this->store = new ReproArrayIndexStore($data); + } + } + + /** + * {@inheritDoc} + */ + public function add(mixed $element): ReproImmutableList + { + $store = clone $this->store; + $store->add($element); + + return $this->newCollectionOf($store); + } + + /** + * {@inheritDoc} + */ + public function addAll(iterable $elements): ReproImmutableList + { + $store = clone $this->store; + $store->addAll($elements); + + return $this->newCollectionOf($store); + } + + /** + * @return list + */ + public function toArray(): array + { + return iterator_to_array($this->store, false); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return $this->store->getIterator(); + } + + /** + * @template NE + * + * @param iterable $data + * + * @return ReproImmutableList + */ + private function newCollectionOf(iterable $data): ReproImmutableList + { + return reproListOf($data); + } +} + +/** + * @template E + * + * @param iterable|Closure(): iterable $data + * + * @return ReproImmutableList + */ +function reproListOf(iterable|Closure $data = []): ReproImmutableList +{ + return new ReproImmutableArrayList($data); +} + +/** + * @template E + * + * @param iterable $data + * + * @return ReproImmutableList + */ +function reproMakeLazyList(iterable $data): ReproImmutableList +{ + return reproListOf(fn () => $data); +} + +/** + * @template T + */ +final class ReproTokenBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } +} + +/** + * @template E + */ +final class ReproWrapper +{ + /** + * @param ReproTokenBox $helper + */ + public function __construct(private ReproTokenBox $helper) + { + } + + /** + * @template NE + * + * @param NE $element + * + * @return ReproWrapper + */ + public function widenWithClonedHelper(mixed $element): self + { + $clonedHelper = clone $this->helper; + + return new self($clonedHelper); + } + + /** + * @return ReproTokenBox + */ + public function getHelper(): ReproTokenBox + { + return $this->helper; + } +} + +/** + * @template E + * + * @param E $seed + * + * @return ReproWrapper + */ +function reproMakeWrapper(mixed $seed): ReproWrapper +{ + return new ReproWrapper(new ReproTokenBox('ok')); +} + +describe('Lazy Proxy Generic Property Inference', function () { + test('accessing $keys view on lazy map does not fail with stale upper-bound binding', function () { + $map = reproMakeLazyMap(['a' => 1, 'b' => 2]); + + expect(iterator_to_array($map->keys))->toBe(['a', 'b']); + }); + + test('accessing $keys view after materializing lazy map proxy preserves K = string', function () { + $map = reproMakeLazyMap(['a' => 1, 'b' => 2]); + + expect($map->count())->toBe(2); + expect(iterator_to_array($map->keys))->toBe(['a', 'b']); + }); +}); + +describe('Cloned Internal Store in Widening Methods', function () { + test('add() on lazily initialized immutable list does not leak unsubstituted template E', function () { + $list = reproMakeLazyList([1, 2]); + $result = $list->add(3); + + expect($result->toArray())->toBe([1, 2, 3]); + }); + + test('addAll() on lazily initialized immutable list does not leak unsubstituted template E', function () { + $list = reproMakeLazyList([1]); + $result = $list->addAll([2, 3]); + + expect($result->toArray())->toBe([1, 2, 3]); + }); + + test('add() with type widening on eager immutable list succeeds without mutating source bindings', function () { + $list = reproListOf([1, 2]); + $widened = $list->add('x'); + + expect($widened->toArray())->toBe([1, 2, 'x']); + expect($list->toArray())->toBe([1, 2]); + }); + + test('cloning an unrelated generic object inside a widening method does not corrupt its template bindings', function () { + $wrapper = reproMakeWrapper(10); + $widened = $wrapper->widenWithClonedHelper(20); + + expect($widened->getHelper()->value)->toBe('ok'); + }); +}); From a5fdcd80c5ad83f4db588add32d6855d69cce4c2 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 13 Nov 2026 14:34:15 +0800 Subject: [PATCH 19/37] Enhance propagateBindingsToInstanceProperties method to prevent premature initialization of uninitialized lazy objects; improve property inspection logic for better handling of lazy properties. --- src/Internal/Generics/TemplateManager.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 26ca0452..92fe60c8 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1132,7 +1132,7 @@ public static function applyClassTemplateDefaults(object $instance, array $class } } - /** + /** * Propagates resolved class template bindings on an instance to any of its object properties * whose declared types reference those class templates (e.g. $this->store with @var KeyValueStore). */ @@ -1147,6 +1147,12 @@ private static function propagateBindingsToInstanceProperties(object $instance): return; } + $ref = new \ReflectionObject($instance); + + if (\PHP_VERSION_ID >= 80400 && $ref->isUninitializedLazyObject($instance)) { + return; + } + $oid = spl_object_id($instance); if (isset(self::$propagationStack[$oid])) { return; @@ -1154,9 +1160,16 @@ private static function propagateBindingsToInstanceProperties(object $instance): self::$propagationStack[$oid] = true; try { - $ref = new \ReflectionObject($instance); foreach ($ref->getProperties() as $prop) { - if ($prop->isStatic() || ! $prop->isInitialized($instance)) { + if ($prop->isStatic()) { + continue; + } + + if (\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) { + continue; + } + + if (! $prop->isInitialized($instance)) { continue; } From f346a48e03b4f832882e4cc0e91d1b4b2b907295 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 13 Nov 2026 23:00:31 +0800 Subject: [PATCH 20/37] Implement generics for map and set structures, including immutable and mutable hash maps, with comprehensive type checking and tests for entries and keys views. Add Noctud-style entries view tests to ensure type consistency after accessing values. --- src/Internal/Generics/TemplateManager.php | 46 +- .../Generics/NoctudEntriesViewFixture.php | 570 ++++++++++++++ .../Fixtures/Generics/NoctudReproFixture.php | 694 ++++++++++++++++++ .../Generics/LazyProxyAndClonedStoreTest.php | 480 ++---------- .../NoctudEntriesViewFalsePositiveTest.php | 59 ++ 5 files changed, 1422 insertions(+), 427 deletions(-) create mode 100644 tests/Fixtures/Generics/NoctudEntriesViewFixture.php create mode 100644 tests/Fixtures/Generics/NoctudReproFixture.php create mode 100644 tests/TypeChecking/Generics/NoctudEntriesViewFalsePositiveTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 92fe60c8..2709482c 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1019,8 +1019,9 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ /** * Binds generic template types to an object instance or validates variance against an existing binding. + * With $refineOnly, an existing binding is never replaced by a less specific one (downward propagation). */ - public static function bindInstanceFromNode(object $instance, GenericTypeNode $typeNode, string $context = '', bool $forceBind = false): ?ErrorMessage + public static function bindInstanceFromNode(object $instance, GenericTypeNode $typeNode, string $context = '', bool $forceBind = false, bool $refineOnly = false): ?ErrorMessage { $className = (string) $typeNode->type; if (isset(self::CONTEXT_SELF_REFERENCES[strtolower($className)])) { @@ -1067,7 +1068,8 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t $classVariances, $context, $forceBind, - $candidateBindings + $candidateBindings, + $refineOnly ); if ($err !== null) { return $err; @@ -1132,7 +1134,7 @@ public static function applyClassTemplateDefaults(object $instance, array $class } } - /** + /** * Propagates resolved class template bindings on an instance to any of its object properties * whose declared types reference those class templates (e.g. $this->store with @var KeyValueStore). */ @@ -1189,7 +1191,7 @@ private static function propagateBindingsToInstanceProperties(object $instance): $resolvedPropType = TemplateSubstitutor::substitute($propType, $instanceBindings); if ($resolvedPropType instanceof GenericTypeNode) { - self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true); + self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true, refineOnly: true); } } } catch (\Throwable) { @@ -1355,7 +1357,8 @@ private static function bindSingleTemplateArgument( array $classVariances, string $context, bool $forceBind, - array $candidateBindings = [] + array $candidateBindings = [], + bool $refineOnly = false ): ?ErrorMessage { if ($expectedTypeNode instanceof IdentifierTypeNode) { if (str_contains($expectedTypeNode->name, '::')) { @@ -1488,6 +1491,18 @@ private static function bindSingleTemplateArgument( $bindings = $map[$instance] ?? []; $boundNode = $isWildcardOrMixed && $templateTag->bound !== null ? $templateTag->bound : $expectedTypeNode; + + if ($refineOnly && isset($existingBindings[$templateName])) { + $existingTypeNode = $existingBindings[$templateName]; + + $isPlaceholder = self::isUnspecializedArgument($boundNode, $templateTag); + $isRefinement = self::checkVariance($boundNode, $existingTypeNode, GenericTypeNode::VARIANCE_COVARIANT); + + if ($isPlaceholder && ! $isRefinement) { + return null; + } + } + $bindings[$templateName] = $boundNode; $rawMappings = self::$classInheritedRawMappingsCache[$instance::class] ?? []; @@ -1577,6 +1592,27 @@ public static function isUnspecializedType(TypeNode $node): bool return false; } + /** + * Checks if a generic type argument carries no information: an unspecialized placeholder, + * or nothing beyond the template's own declared bound or default. + */ + private static function isUnspecializedArgument(TypeNode $node, TemplateTagValueNode $templateTag): bool + { + if (self::isUnspecializedType($node)) { + return true; + } + + if ($templateTag->bound !== null && self::matchesBoundOrDefault($node, $templateTag->bound)) { + return true; + } + + if ($templateTag->default !== null && self::matchesBoundOrDefault($node, $templateTag->default)) { + return true; + } + + return false; + } + /** * Recursively verifies variance across array shape elements. */ diff --git a/tests/Fixtures/Generics/NoctudEntriesViewFixture.php b/tests/Fixtures/Generics/NoctudEntriesViewFixture.php new file mode 100644 index 00000000..61667406 --- /dev/null +++ b/tests/Fixtures/Generics/NoctudEntriesViewFixture.php @@ -0,0 +1,570 @@ + + */ +interface EntriesViewKeyValueStore extends IteratorAggregate +{ + public function count(): int; + + /** + * @return list + */ + public function keys(): array; + + /** + * @return list + */ + public function values(): array; +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements EntriesViewKeyValueStore + */ +final class EntriesViewHashStore implements EntriesViewKeyValueStore +{ + /** + * @var array + */ + private array $keys = []; + + /** + * @var array + */ + private array $values = []; + + /** + * @param array $keys + * @param array $values + */ + private function __construct(array $keys = [], array $values = []) + { + $this->keys = $keys; + $this->values = $values; + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromAssoc(iterable $source): self + { + $keys = []; + $values = []; + foreach ($source as $k => $v) { + $hash = 'k:' . (string) $k; + $keys[$hash] = $k; + $values[$hash] = $v; + } + + return new self($keys, $values); + } + + public function count(): int + { + return \count($this->values); + } + + /** + * @return list + */ + public function keys(): array + { + return array_values($this->keys); + } + + /** + * @return list + */ + public function values(): array + { + return array_values($this->values); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->keys as $hash => $k) { + yield $k => $this->values[$hash]; + } + } +} + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface EntriesViewReadOnlyElementStore extends IteratorAggregate +{ + /** + * @return list + */ + public function toArray(): array; +} + +/** + * @template E of string|int|bool|float|object + * + * @implements EntriesViewReadOnlyElementStore + */ +final class EntriesViewMapKeyStore implements EntriesViewReadOnlyElementStore +{ + public function __construct( + /** + * @var EntriesViewKeyValueStore + */ + private readonly EntriesViewKeyValueStore $store, + ) { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->store as $k => $v) { + yield $k; + } + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->store->keys(); + } +} + +/** + * POISON SOURCE B: the key type is hardcoded to the upper bound union here, + * exactly as in Noctud's MapValueStore. Reading $map->values pushes + * KeyValueStore onto the shared store. + * + * @template E + * + * @implements EntriesViewReadOnlyElementStore + */ +final class EntriesViewMapValueStore implements EntriesViewReadOnlyElementStore +{ + public function __construct( + /** + * @var EntriesViewKeyValueStore + */ + private readonly EntriesViewKeyValueStore $store, + ) { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->store as $v) { + yield $v; + } + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->store->values(); + } +} + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface EntriesViewCollection extends IteratorAggregate +{ +} + +/** + * @template E + * + * @implements EntriesViewCollection + */ +final class EntriesViewMapValueCollection implements EntriesViewCollection +{ + /** + * @var EntriesViewReadOnlyElementStore + */ + protected EntriesViewReadOnlyElementStore $store; + + /** + * @template TK of string|int|bool|float|object + * + * @param EntriesViewKeyValueStore|EntriesViewReadOnlyElementStore $store + */ + public function __construct(EntriesViewKeyValueStore|EntriesViewReadOnlyElementStore $store) + { + $this->store = $store instanceof EntriesViewReadOnlyElementStore + ? $store + : new EntriesViewMapValueStore($store); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return $this->store->getIterator(); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->store->toArray(); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +interface EntriesViewMapEntry +{ + /** + * @var K + */ + public string|int|bool|float|object $key { get; } + + /** + * @var V + */ + public mixed $value { get; } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements EntriesViewMapEntry + */ +final class EntriesViewSimpleMapEntry implements EntriesViewMapEntry +{ + /** + * @param K $key + * @param V $value + */ + public function __construct( + /** + * @var K + */ + public readonly string|int|bool|float|object $key, + /** + * @var V + */ + public readonly mixed $value, + ) { + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements EntriesViewReadOnlyElementStore> + */ +final class EntriesViewMapEntryStore implements EntriesViewReadOnlyElementStore +{ + public function __construct( + /** + * @var EntriesViewKeyValueStore + */ + private readonly EntriesViewKeyValueStore $store, + ) { + } + + /** + * @return Traversable> + */ + public function getIterator(): Traversable + { + foreach ($this->store as $k => $v) { + yield new EntriesViewSimpleMapEntry($k, $v); + } + } + + /** + * @return list> + */ + public function toArray(): array + { + return iterator_to_array($this, false); + } +} + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface EntriesViewSet extends IteratorAggregate +{ +} + +/** + * @template E + * + * @property EntriesViewReadOnlyElementStore $store + */ +trait EntriesViewSetLogic +{ + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return $this->store->getIterator(); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->store->toArray(); + } +} + +/** + * @template E of string|int|bool|float|object + * + * @implements EntriesViewSet + */ +final class EntriesViewMapKeySet implements EntriesViewSet +{ + /** @use EntriesViewSetLogic */ + use EntriesViewSetLogic; + + /** + * @var EntriesViewReadOnlyElementStore + */ + protected EntriesViewReadOnlyElementStore $store; + + /** + * @template TV + * + * @param EntriesViewKeyValueStore|EntriesViewReadOnlyElementStore $store + */ + public function __construct(EntriesViewKeyValueStore|EntriesViewReadOnlyElementStore $store) + { + $this->store = $store instanceof EntriesViewReadOnlyElementStore + ? $store + : new EntriesViewMapKeyStore($store); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements EntriesViewSet> + */ +final class EntriesViewMapEntrySet implements EntriesViewSet +{ + /** @use EntriesViewSetLogic> */ + use EntriesViewSetLogic; + + /** + * @var EntriesViewReadOnlyElementStore> + */ + protected EntriesViewReadOnlyElementStore $store; + + /** + * @param EntriesViewKeyValueStore|EntriesViewReadOnlyElementStore> $store + */ + public function __construct(EntriesViewKeyValueStore|EntriesViewReadOnlyElementStore $store) + { + $this->store = $store instanceof EntriesViewReadOnlyElementStore + ? $store + : new EntriesViewMapEntryStore($store); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +interface EntriesViewMap +{ + /** + * @var EntriesViewSet + */ + public EntriesViewSet $keys { get; } + + /** + * @var EntriesViewCollection + */ + public EntriesViewCollection $values { get; } + + /** + * @var EntriesViewSet> + */ + public EntriesViewSet $entries { get; } +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +trait EntriesViewMapLogic +{ + /** + * @var EntriesViewKeyValueStore + */ + protected EntriesViewKeyValueStore $store; + + /** + * @var EntriesViewSet + */ + public EntriesViewSet $keys { + get => $this->keys ??= new EntriesViewMapKeySet($this->store); + } + + /** + * @var EntriesViewCollection + */ + public EntriesViewCollection $values { + get => $this->values ??= new EntriesViewMapValueCollection($this->store); + } + + /** + * @var EntriesViewSet> + */ + public EntriesViewSet $entries { + get => $this->entries ??= new EntriesViewMapEntrySet($this->store); + } + + /** + * Diagnostic accessor. Deliberately carries no return-type annotation: a generic + * one would run a return check that refines the poisoned store back to K=string + * and hides the bug. + */ + public function internalStore(): EntriesViewKeyValueStore + { + return $this->store; + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements EntriesViewMap + */ +final class EntriesViewImmutableHashMap implements EntriesViewMap +{ + /** @use EntriesViewMapLogic */ + use EntriesViewMapLogic; + + /** + * @param iterable $data + */ + public function __construct(iterable $data = []) + { + $this->store = EntriesViewHashStore::fromAssoc($data); + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $data + * + * @return EntriesViewMap + */ + public static function of(iterable $data = []): EntriesViewMap + { + return new self($data); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements EntriesViewMap + */ +final class EntriesViewMutableHashMap implements EntriesViewMap +{ + /** @use EntriesViewMapLogic */ + use EntriesViewMapLogic; + + /** + * @param iterable $data + */ + public function __construct(iterable $data = []) + { + $this->store = EntriesViewHashStore::fromAssoc($data); + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $data + * + * @return EntriesViewMap + */ + public static function of(iterable $data = []): EntriesViewMap + { + return new self($data); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return EntriesViewMap + */ +function entriesViewImmutableMap(iterable $data): EntriesViewMap +{ + return EntriesViewImmutableHashMap::of($data); +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return EntriesViewMap + */ +function entriesViewMutableMap(iterable $data): EntriesViewMap +{ + return EntriesViewMutableHashMap::of($data); +} + +/** + * @param positive-int $n + */ +function entriesViewCanary(int $n): int +{ + return $n; +} diff --git a/tests/Fixtures/Generics/NoctudReproFixture.php b/tests/Fixtures/Generics/NoctudReproFixture.php new file mode 100644 index 00000000..ed47fcdb --- /dev/null +++ b/tests/Fixtures/Generics/NoctudReproFixture.php @@ -0,0 +1,694 @@ + + */ +final class ReproSimpleMapEntry implements ReproMapEntry +{ + public function __construct( + public readonly string|int|bool|float|object $key, + public readonly mixed $value + ) { + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @extends IteratorAggregate + */ +interface ReproKeyValueStore extends IteratorAggregate +{ + public function count(): int; +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements ReproKeyValueStore + */ +final class ReproHashStore implements ReproKeyValueStore +{ + /** + * @var array + */ + private array $keys = []; + + /** + * @var array + */ + private array $values = []; + + /** + * @param array $keys + * @param array $values + */ + private function __construct(array $keys = [], array $values = []) + { + $this->keys = $keys; + $this->values = $values; + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromAssoc(iterable $source): self + { + $keys = []; + $values = []; + foreach ($source as $k => $v) { + $hash = 'k:' . (string) $k; + $keys[$hash] = $k; + $values[$hash] = $v; + } + + return new self($keys, $values); + } + + public function count(): int + { + return \count($this->values); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->keys as $hash => $k) { + yield $k => $this->values[$hash]; + } + } +} + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface ReproSet extends IteratorAggregate +{ +} + +/** + * @template E + */ +interface ReproReadOnlyElementStore extends IteratorAggregate +{ +} + +/** + * @template E of string|int|bool|float|object + * + * @implements ReproReadOnlyElementStore + */ +final class ReproMapKeyStore implements ReproReadOnlyElementStore +{ + /** + * @param ReproKeyValueStore $store + */ + public function __construct(private ReproKeyValueStore $store) + { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + foreach ($this->store as $k => $v) { + yield $k; + } + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @implements ReproReadOnlyElementStore> + */ +final class ReproMapEntryStore implements ReproReadOnlyElementStore +{ + /** + * @param ReproKeyValueStore $store + */ + public function __construct(private ReproKeyValueStore $store) + { + } + + /** + * @return Traversable> + */ + public function getIterator(): Traversable + { + foreach ($this->store as $k => $v) { + yield new ReproSimpleMapEntry($k, $v); + } + } +} + +/** + * @template E + */ +trait ReproSetLogic +{ + /** + * @var ReproReadOnlyElementStore + */ + protected ReproReadOnlyElementStore $store; + + public function getIterator(): Traversable + { + return $this->store->getIterator(); + } +} + +/** + * @template E of string|int|bool|float|object + * + * @implements ReproSet + */ +final class ReproMapKeySet implements ReproSet +{ + /** @use ReproSetLogic */ + use ReproSetLogic; + + /** + * @var ReproReadOnlyElementStore + */ + protected ReproReadOnlyElementStore $store; + + /** + * @template TV + * + * @param ReproKeyValueStore|ReproReadOnlyElementStore $store + */ + public function __construct(ReproKeyValueStore|ReproReadOnlyElementStore $store) + { + $this->store = $store instanceof ReproReadOnlyElementStore + ? $store + : new ReproMapKeyStore($store); + } +} + +/** + * Simulates Noctud\Collection\Map\View\MapEntrySet. + * + * @template K of string|int|bool|float|object + * @template V + * + * @implements ReproSet> + */ +final class ReproMapEntrySet implements ReproSet +{ + /** @use ReproSetLogic> */ + use ReproSetLogic; + + /** + * @var ReproReadOnlyElementStore> + */ + protected ReproReadOnlyElementStore $store; + + /** + * Union parameter exactly as in Noctud: + * + * @param ReproKeyValueStore|ReproReadOnlyElementStore> $store + */ + public function __construct(ReproKeyValueStore|ReproReadOnlyElementStore $store) + { + $this->store = $store instanceof ReproReadOnlyElementStore + ? $store + : new ReproMapEntryStore($store); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + */ +interface ReproMapInterface +{ + /** + * @var ReproSet + */ + public ReproSet $keys { get; } + + /** + * @var ReproSet> + */ + public ReproSet $entries { get; } +} + +/** + * Simulates Noctud\Collection\Map\MapLogic. + * + * @template K of string|int|bool|float|object + * @template V + */ +trait ReproMapLogic +{ + /** + * @var ReproKeyValueStore + */ + protected ReproKeyValueStore $store; + + /** + * @var ReproSet + */ + public ReproSet $keys { + get => $this->keys ??= new ReproMapKeySet($this->store); + } + + /** + * @var ReproSet> + */ + public ReproSet $entries { + get => $this->entries ??= new ReproMapEntrySet($this->store); + } +} + +/** + * Simulates Noctud\Collection\Map\HashMap\ImmutableHashMap. + * + * @template K of string|int|bool|float|object + * @template V + * + * @implements ReproMapInterface + */ +final class ReproImmutableHashMap implements ReproMapInterface +{ + /** @use ReproMapLogic */ + use ReproMapLogic; + + /** + * @param iterable|Closure(): iterable $data + */ + public function __construct(iterable|Closure $data = []) + { + if ($data instanceof Closure) { + $reflector = new ReflectionClass(ReproHashStore::class); + $this->store = $reflector->newLazyProxy( + fn (ReproHashStore $object): ReproHashStore => $object::fromAssoc($data()) + ); + } else { + $this->store = ReproHashStore::fromAssoc($data); + } + } + + public function count(): int + { + return $this->store->count(); + } +} + +/** + * Simulates Noctud\Collection\Map\HashMap\MutableHashMap. + * + * @template K of string|int|bool|float|object + * @template V + * + * @implements ReproMapInterface + */ +final class ReproMutableHashMap implements ReproMapInterface +{ + /** @use ReproMapLogic */ + use ReproMapLogic; + + /** + * @param iterable|Closure(): iterable $data + */ + public function __construct(iterable|Closure $data = []) + { + if ($data instanceof Closure) { + $reflector = new ReflectionClass(ReproHashStore::class); + $this->store = $reflector->newLazyProxy( + fn (ReproHashStore $object): ReproHashStore => $object::fromAssoc($data()) + ); + } else { + $this->store = ReproHashStore::fromAssoc($data); + } + } + + public function count(): int + { + return $this->store->count(); + } +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return ReproImmutableHashMap + */ +function reproMakeEagerImmutableMap(iterable $data): ReproImmutableHashMap +{ + return new ReproImmutableHashMap($data); +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return ReproImmutableHashMap + */ +function reproMakeLazyImmutableMap(iterable $data): ReproImmutableHashMap +{ + return new ReproImmutableHashMap(fn () => $data); +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return ReproMutableHashMap + */ +function reproMakeEagerMutableMap(iterable $data): ReproMutableHashMap +{ + return new ReproMutableHashMap($data); +} + +/** + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable $data + * + * @return ReproMutableHashMap + */ +function reproMakeLazyMutableMap(iterable $data): ReproMutableHashMap +{ + return new ReproMutableHashMap(fn () => $data); +} + +// ========================================================================= +// Pattern 2: Cloned Internal Store in Widening Methods (Noctud ImmutableListLogic) +// ========================================================================= + +/** + * Note: uses template V while subclass uses E (matches Noctud). + * + * @template V + * + * @extends ReproReadOnlyElementStore + */ +interface ReproReadWriteIndexedStore extends ReproReadOnlyElementStore +{ + /** + * @param V $element + */ + public function add(mixed $element): void; + + /** + * @param iterable $source + */ + public function addAll(iterable $source): void; +} + +/** + * @template E + * + * @implements ReproReadWriteIndexedStore + */ +final class ReproArrayIndexStore implements ReproReadWriteIndexedStore +{ + /** + * @var list + */ + private array $elements = []; + + /** + * @param iterable $source + */ + public function __construct(iterable $source = []) + { + foreach ($source as $el) { + $this->elements[] = $el; + } + } + + /** + * @param E $element + */ + public function add(mixed $element): void + { + $this->elements[] = $element; + } + + /** + * @param iterable $source + */ + public function addAll(iterable $source): void + { + foreach ($source as $el) { + $this->elements[] = $el; + } + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->elements); + } + + /** + * @return list + */ + public function toArray(): array + { + return $this->elements; + } +} + +/** + * @template E + * + * @extends IteratorAggregate + */ +interface ReproImmutableList extends IteratorAggregate +{ + /** + * @template NE + * + * @param NE $element + * + * @return ReproImmutableList + */ + public function add(mixed $element): ReproImmutableList; + + /** + * @template NE + * + * @param iterable $elements + * + * @return ReproImmutableList + */ + public function addAll(iterable $elements): ReproImmutableList; + + /** + * @return list + */ + public function toArray(): array; +} + +/** + * @template E + * + * @implements ReproImmutableList + */ +final class ReproImmutableArrayList implements ReproImmutableList +{ + /** + * @var ReproReadWriteIndexedStore + */ + private ReproReadWriteIndexedStore $store; + + /** + * @param iterable|Closure(): iterable $data + */ + public function __construct(iterable|Closure $data = []) + { + if ($data instanceof Closure) { + $reflector = new ReflectionClass(ReproArrayIndexStore::class); + $this->store = $reflector->newLazyProxy( + fn (): ReproArrayIndexStore => new ReproArrayIndexStore($data()) + ); + } elseif ($data instanceof ReproArrayIndexStore) { + $this->store = clone $data; + } else { + $this->store = new ReproArrayIndexStore($data); + } + } + + /** + * {@inheritDoc} + */ + public function add(mixed $element): ReproImmutableList + { + $store = clone $this->store; + $store->add($element); + + return $this->newCollectionOf($store); + } + + /** + * {@inheritDoc} + */ + public function addAll(iterable $elements): ReproImmutableList + { + $store = clone $this->store; + $store->addAll($elements); + + return $this->newCollectionOf($store); + } + + /** + * @return list + */ + public function toArray(): array + { + return iterator_to_array($this->store, false); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return $this->store->getIterator(); + } + + /** + * @template NE + * + * @param iterable $data + * + * @return ReproImmutableList + */ + private function newCollectionOf(iterable $data): ReproImmutableList + { + return reproListOf($data); + } +} + +/** + * @template E + * + * @param iterable|Closure(): iterable $data + * + * @return ReproImmutableList + */ +function reproListOf(iterable|Closure $data = []): ReproImmutableList +{ + return new ReproImmutableArrayList($data); +} + +/** + * @template E + * + * @param iterable $data + * + * @return ReproImmutableList + */ +function reproMakeLazyList(iterable $data): ReproImmutableList +{ + return reproListOf(fn () => $data); +} + +/** + * @template T + */ +final class ReproTokenBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } +} + +/** + * @template E + */ +final class ReproWrapper +{ + /** + * @param ReproTokenBox $helper + */ + public function __construct(private ReproTokenBox $helper) + { + } + + /** + * @template NE + * + * @param NE $element + * + * @return ReproWrapper + */ + public function widenWithClonedHelper(mixed $element): self + { + $clonedHelper = clone $this->helper; + + return new self($clonedHelper); + } + + /** + * @return ReproTokenBox + */ + public function getHelper(): ReproTokenBox + { + return $this->helper; + } +} + +/** + * @template E + * + * @param E $seed + * + * @return ReproWrapper + */ +function reproMakeWrapper(mixed $seed): ReproWrapper +{ + return new ReproWrapper(new ReproTokenBox('ok')); +} diff --git a/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php b/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php index 2d3ce7f3..da780b44 100644 --- a/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php +++ b/tests/TypeChecking/Generics/LazyProxyAndClonedStoreTest.php @@ -2,455 +2,91 @@ declare(strict_types=1); -/** - * @template K of string|int|bool|float|object - * @template V - * - * @extends IteratorAggregate - */ -interface ReproKeyValueStore extends IteratorAggregate -{ - public function count(): int; +if (PHP_VERSION_ID < 80400) { + return; } -/** - * @template K of string|int|bool|float|object - * @template V - * - * @implements ReproKeyValueStore - */ -final class ReproHashStore implements ReproKeyValueStore -{ - /** - * @var array - */ - private array $data = []; - - /** - * @template NK of string|int|bool|float|object - * @template NV - * - * @param iterable $source - * - * @return self - */ - public static function fromAssoc(iterable $source): self - { - $store = new self(); - foreach ($source as $k => $v) { - $store->data[$k] = $v; - } - - return $store; - } - - public function count(): int - { - return \count($this->data); - } - - /** - * @return Traversable - */ - public function getIterator(): Traversable - { - yield from $this->data; - } -} +require_once __DIR__ . '/../../Fixtures/Generics/NoctudReproFixture.php'; -/** - * Note: intentionally has no upper bound on E (just like Noctud\Collection\Set\Set). - * - * @template E - * - * @extends IteratorAggregate - */ -interface ReproSet extends IteratorAggregate -{ -} +describe('Map $entries and $keys Views (Noctud MapLogic)', function () { + test('accessing $entries view on eager ImmutableMap matches Set>', function () { + $map = reproMakeEagerImmutableMap(['a' => 1, 'b' => 2]); -/** - * Note: adds upper bound on E (just like Noctud\Collection\Map\View\MapKeySet). - * - * @template E of string|int|bool|float|object - * - * @implements ReproSet - */ -final class ReproMapKeySet implements ReproSet -{ - /** - * @template TV - * - * @param ReproKeyValueStore $store - */ - public function __construct(private ReproKeyValueStore $store) - { - } - - /** - * @return Traversable - */ - public function getIterator(): Traversable - { - foreach ($this->store as $k => $v) { - yield $k; - } - } -} + $entries = $map->entries; + $items = iterator_to_array($entries); -/** - * @template K of string|int|bool|float|object - * @template V - */ -final class ReproLazyMap -{ - /** - * @var ReproKeyValueStore - */ - private ReproKeyValueStore $store; - - /** - * @var ReproSet - */ - public ReproSet $keys { - get => $this->keys ??= new ReproMapKeySet($this->store); - } - - /** - * @param iterable|Closure(): iterable $data - */ - public function __construct(iterable|Closure $data = []) - { - if ($data instanceof Closure) { - $reflector = new ReflectionClass(ReproHashStore::class); - $this->store = $reflector->newLazyProxy( - fn (ReproHashStore $object): ReproHashStore => $object::fromAssoc($data()) - ); - } else { - $this->store = ReproHashStore::fromAssoc($data); - } - } - - public function count(): int - { - return $this->store->count(); - } -} + expect(\count($items))->toBe(2); + expect($items[0]->key)->toBe('a'); + expect($items[0]->value)->toBe(1); + }); -/** - * @template K of string|int|bool|float|object - * @template V - * - * @param iterable $data - * - * @return ReproLazyMap - */ -function reproMakeLazyMap(iterable $data): ReproLazyMap -{ - return new ReproLazyMap(fn () => $data); -} + test('accessing $entries view on eager MutableMap matches Set>', function () { + $map = reproMakeEagerMutableMap(['a' => 1, 'b' => 2]); -// ========================================================================= -// Pattern 2: Cloned Internal Store in Widening Methods (Noctud ImmutableListLogic) -// ========================================================================= - -/** - * @template E - * - * @extends IteratorAggregate - */ -interface ReproReadOnlyElementStore extends IteratorAggregate -{ -} + $entries = $map->entries; + $items = iterator_to_array($entries); -/** - * Note: uses template V while subclass ArrayIndexStore uses E (just like Noctud). - * - * @template V - * - * @extends ReproReadOnlyElementStore - */ -interface ReproReadWriteIndexedStore extends ReproReadOnlyElementStore -{ - /** - * @param V $element - */ - public function add(mixed $element): void; - - /** - * @param iterable $source - */ - public function addAll(iterable $source): void; -} + expect(\count($items))->toBe(2); + expect($items[0]->key)->toBe('a'); + expect($items[0]->value)->toBe(1); + }); -/** - * @template E - * - * @implements ReproReadWriteIndexedStore - */ -final class ReproArrayIndexStore implements ReproReadWriteIndexedStore -{ - /** - * @var list - */ - private array $elements = []; - - /** - * @param iterable $source - */ - public function __construct(iterable $source = []) - { - foreach ($source as $el) { - $this->elements[] = $el; - } - } - - /** - * @param E $element - */ - public function add(mixed $element): void - { - $this->elements[] = $element; - } - - /** - * @param iterable $source - */ - public function addAll(iterable $source): void - { - foreach ($source as $el) { - $this->elements[] = $el; - } - } - - /** - * @return Traversable - */ - public function getIterator(): Traversable - { - return new ArrayIterator($this->elements); - } - - /** - * @return list - */ - public function toArray(): array - { - return $this->elements; - } -} + test('accessing $entries view on lazy ImmutableMap preserves K = string and V = int without upper-bound fallback', function () { + $map = reproMakeLazyImmutableMap(['a' => 1, 'b' => 2]); -/** - * @template E - * - * @extends IteratorAggregate - */ -interface ReproImmutableList extends IteratorAggregate -{ - /** - * @template NE - * - * @param NE $element - * - * @return ReproImmutableList - */ - public function add(mixed $element): ReproImmutableList; - - /** - * @template NE - * - * @param iterable $elements - * - * @return ReproImmutableList - */ - public function addAll(iterable $elements): ReproImmutableList; - - /** - * @return list - */ - public function toArray(): array; -} + $entries = $map->entries; + $items = iterator_to_array($entries); -/** - * @template E - * - * @implements ReproImmutableList - */ -final class ReproImmutableArrayList implements ReproImmutableList -{ - /** - * @var ReproReadWriteIndexedStore - */ - private ReproReadWriteIndexedStore $store; - - /** - * @param iterable|Closure(): iterable $data - */ - public function __construct(iterable|Closure $data = []) - { - if ($data instanceof Closure) { - $reflector = new ReflectionClass(ReproArrayIndexStore::class); - $this->store = $reflector->newLazyProxy( - fn (): ReproArrayIndexStore => new ReproArrayIndexStore($data()) - ); - } elseif ($data instanceof ReproArrayIndexStore) { - $this->store = clone $data; - } else { - $this->store = new ReproArrayIndexStore($data); - } - } - - /** - * {@inheritDoc} - */ - public function add(mixed $element): ReproImmutableList - { - $store = clone $this->store; - $store->add($element); - - return $this->newCollectionOf($store); - } - - /** - * {@inheritDoc} - */ - public function addAll(iterable $elements): ReproImmutableList - { - $store = clone $this->store; - $store->addAll($elements); - - return $this->newCollectionOf($store); - } - - /** - * @return list - */ - public function toArray(): array - { - return iterator_to_array($this->store, false); - } - - /** - * @return Traversable - */ - public function getIterator(): Traversable - { - return $this->store->getIterator(); - } - - /** - * @template NE - * - * @param iterable $data - * - * @return ReproImmutableList - */ - private function newCollectionOf(iterable $data): ReproImmutableList - { - return reproListOf($data); - } -} + expect(\count($items))->toBe(2); + expect($items[0]->key)->toBe('a'); + expect($items[0]->value)->toBe(1); + }); -/** - * @template E - * - * @param iterable|Closure(): iterable $data - * - * @return ReproImmutableList - */ -function reproListOf(iterable|Closure $data = []): ReproImmutableList -{ - return new ReproImmutableArrayList($data); -} + test('accessing $entries view on lazy MutableMap preserves K = string and V = int without upper-bound fallback', function () { + $map = reproMakeLazyMutableMap(['a' => 1, 'b' => 2]); -/** - * @template E - * - * @param iterable $data - * - * @return ReproImmutableList - */ -function reproMakeLazyList(iterable $data): ReproImmutableList -{ - return reproListOf(fn () => $data); -} + $entries = $map->entries; + $items = iterator_to_array($entries); -/** - * @template T - */ -final class ReproTokenBox -{ - /** - * @param T $value - */ - public function __construct(public mixed $value) - { - } -} + expect(\count($items))->toBe(2); + expect($items[0]->key)->toBe('a'); + expect($items[0]->value)->toBe(1); + }); -/** - * @template E - */ -final class ReproWrapper -{ - /** - * @param ReproTokenBox $helper - */ - public function __construct(private ReproTokenBox $helper) - { - } - - /** - * @template NE - * - * @param NE $element - * - * @return ReproWrapper - */ - public function widenWithClonedHelper(mixed $element): self - { - $clonedHelper = clone $this->helper; - - return new self($clonedHelper); - } - - /** - * @return ReproTokenBox - */ - public function getHelper(): ReproTokenBox - { - return $this->helper; - } -} + test('accessing $entries view after materializing lazy map preserves K = string and V = int', function () { + $map = reproMakeLazyImmutableMap(['a' => 1, 'b' => 2]); -/** - * @template E - * - * @param E $seed - * - * @return ReproWrapper - */ -function reproMakeWrapper(mixed $seed): ReproWrapper -{ - return new ReproWrapper(new ReproTokenBox('ok')); -} + expect($map->count())->toBe(2); + + $entries = $map->entries; + $items = iterator_to_array($entries); + + expect(\count($items))->toBe(2); + expect($items[0]->key)->toBe('a'); + expect($items[0]->value)->toBe(1); + }); + + test('accessing $keys view on eager map returns correct keys', function () { + $map = reproMakeEagerImmutableMap(['a' => 1, 'b' => 2]); + + expect(iterator_to_array($map->keys))->toBe(['a', 'b']); + }); -describe('Lazy Proxy Generic Property Inference', function () { - test('accessing $keys view on lazy map does not fail with stale upper-bound binding', function () { - $map = reproMakeLazyMap(['a' => 1, 'b' => 2]); + test('accessing $keys view on lazy map preserves K = string', function () { + $map = reproMakeLazyImmutableMap(['a' => 1, 'b' => 2]); expect(iterator_to_array($map->keys))->toBe(['a', 'b']); }); - test('accessing $keys view after materializing lazy map proxy preserves K = string', function () { - $map = reproMakeLazyMap(['a' => 1, 'b' => 2]); + test('accessing $keys view after materializing lazy map preserves K = string', function () { + $map = reproMakeLazyImmutableMap(['a' => 1, 'b' => 2]); expect($map->count())->toBe(2); expect(iterator_to_array($map->keys))->toBe(['a', 'b']); }); }); -describe('Cloned Internal Store in Widening Methods', function () { +describe('Cloned Internal Store in Widening Methods (Noctud ImmutableListLogic)', function () { test('add() on lazily initialized immutable list does not leak unsubstituted template E', function () { $list = reproMakeLazyList([1, 2]); $result = $list->add(3); diff --git a/tests/TypeChecking/Generics/NoctudEntriesViewFalsePositiveTest.php b/tests/TypeChecking/Generics/NoctudEntriesViewFalsePositiveTest.php new file mode 100644 index 00000000..5790d33f --- /dev/null +++ b/tests/TypeChecking/Generics/NoctudEntriesViewFalsePositiveTest.php @@ -0,0 +1,59 @@ + after reading $values (immutable)', function () { + $map = entriesViewImmutableMap(['a' => 1, 'b' => 2, 'c' => 3]); + + $map->values->toArray(); + + expect($map->entries->toArray())->toHaveCount(3); +}); + +it('keeps $entries bound to MapEntry after reading $values (mutable)', function () { + $map = entriesViewMutableMap(['a' => 1, 'b' => 2, 'c' => 3]); + + $map->values->toArray(); + + expect($map->entries->toArray())->toHaveCount(3); +}); + +it('keeps $entries valid when read before $values', function () { + $map = entriesViewImmutableMap(['a' => 1, 'b' => 2, 'c' => 3]); + + expect($map->entries->toArray())->toHaveCount(3); + + $map->values->toArray(); + + expect($map->entries->toArray())->toHaveCount(3); +}); + +it('keeps the shared store bound to K=string after reading $values', function () { + $map = entriesViewImmutableMap(['a' => 1, 'b' => 2, 'c' => 3]); + + $map->values->toArray(); + + expect(TypePHP::getGenericTypes($map->internalStore())) + ->toMatchArray(['K' => 'string', 'V' => 'int']) + ; +}); + +it('keeps V=int when $keys is read before $entries', function () { + $map = entriesViewImmutableMap(['a' => 1, 'b' => 2, 'c' => 3]); + + iterator_to_array($map->keys); + iterator_to_array($map->values); + + expect($map->entries->toArray())->toHaveCount(3); + expect(TypePHP::getGenericTypes($map->internalStore())) + ->toMatchArray(['K' => 'string', 'V' => 'int']) + ; +}); From 1b877ddfa94cd8d6acd7b45ddaf6de5428a15a3f Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 13 Nov 2026 23:45:37 +0800 Subject: [PATCH 21/37] Add caching for generic object contexts and template variances in ParamChecker and TemplateManager --- src/Internal/Checker/ParamChecker.php | 305 +++++++++++++++------- src/Internal/Generics/TemplateManager.php | 231 +++++++++++----- 2 files changed, 376 insertions(+), 160 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 31ab0fe0..efefcfa8 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -97,6 +97,43 @@ final class ParamChecker */ private static array $classDeclaredTemplateNamesCache = []; + /** + * Memoized reflection context for generic-object FQCN resolution. Null means "no reflectable context". + * + * @var array|\ReflectionFunction|null> + */ + private static array $genericObjectContextCache = []; + + /** + * 2D cache for resolved generic-object target FQCNs: [$contextKey][$typeName] => FQCN. + * + * @var array> + */ + private static array $genericObjectTargetCache = []; + + /** + * Per-class traversable contract plan: alias-substituted key/value nodes, the class templates + * they are expressed in, and the reflection context they resolve against. All class-derived; + * only the instance bindings are applied per call. + * + * @var array, context: \ReflectionClass|\ReflectionMethod}|null> + */ + private static array $traversablePlanCache = []; + + /** + * In-memory cache for callable parameter nodes per function. + * + * @var array> + */ + private static array $callableNodesCache = []; + + /** + * 2D cache for whether a parameter's declared type is instance-dependent (static/$this). + * + * @var array> + */ + private static array $paramDynamicCache = []; + /** * Resets internal caches. Useful for test isolation. */ @@ -107,6 +144,11 @@ public static function reset(): void self::$classDeclaredTemplateNamesCache = []; ClassNameValidator::reset(); self::$baseTypeCache = []; + self::$genericObjectContextCache = []; + self::$genericObjectTargetCache = []; + self::$traversablePlanCache = []; + self::$callableNodesCache = []; + self::$paramDynamicCache = []; } /** @@ -347,7 +389,13 @@ private static function resolveBaseTypes( ): array { $baseTypes = []; foreach ($types as $paramName => $typeNode) { - $isParamDynamic = $paramsAreDynamic && (str_contains((string) $typeNode, 'static') || str_contains((string) $typeNode, '$this')); + if ($paramsAreDynamic && ! isset(self::$paramDynamicCache[$effectiveFunction][$paramName])) { + $typeString = (string) $typeNode; + self::$paramDynamicCache[$effectiveFunction][$paramName] = + str_contains($typeString, 'static') || str_contains($typeString, '$this'); + } + + $isParamDynamic = $paramsAreDynamic && (self::$paramDynamicCache[$effectiveFunction][$paramName] ?? false); if (! $isParamDynamic && isset(self::$baseTypeCache[$effectiveFunction][$paramName])) { $baseTypes[$paramName] = self::$baseTypeCache[$effectiveFunction][$paramName]; @@ -468,7 +516,9 @@ public static function resolveEffectiveFunction(string $function, object|string| return self::$effectiveFunctionCache[$function][$actualClassName]; } - if (str_starts_with($function, $actualClassName . '::') && HierarchyResolver::getTraitAliases($actualClassName) === []) { + $traitAliases = HierarchyResolver::getTraitAliases($actualClassName); + + if (str_starts_with($function, $actualClassName . '::') && $traitAliases === []) { return self::$effectiveFunctionCache[$function][$actualClassName] = $function; } @@ -478,27 +528,23 @@ public static function resolveEffectiveFunction(string $function, object|string| ? $actualClassName . '::' . $methodName : $function; - if ($thisObj !== null) { - $traitAliases = HierarchyResolver::getTraitAliases($actualClassName); - - if (\count($traitAliases) > 0) { - $isTargetOfAlias = false; - foreach ($traitAliases as $originalTarget) { - if (str_ends_with($originalTarget, '::' . $methodName)) { - $isTargetOfAlias = true; + if ($thisObj !== null && $traitAliases !== []) { + $isTargetOfAlias = false; + foreach ($traitAliases as $originalTarget) { + if (str_ends_with($originalTarget, '::' . $methodName)) { + $isTargetOfAlias = true; - break; - } + break; } + } - if ($isTargetOfAlias) { - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6); - foreach ($trace as $frame) { - $frameFunc = $frame['function']; - $frameClass = $frame['class'] ?? ''; - if (($frameClass === $actualClassName || $frameClass === $classOrTrait) && isset($traitAliases[$frameFunc])) { - return self::$effectiveFunctionCache[$function][$actualClassName] = $actualClassName . '::' . $frameFunc; - } + if ($isTargetOfAlias) { + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6); + foreach ($trace as $frame) { + $frameFunc = $frame['function']; + $frameClass = $frame['class'] ?? ''; + if (($frameClass === $actualClassName || $frameClass === $classOrTrait) && isset($traitAliases[$frameFunc])) { + return self::$effectiveFunctionCache[$function][$actualClassName] = $actualClassName . '::' . $frameFunc; } } } @@ -561,19 +607,16 @@ private static function preInferGenericTemplates( array $templates, array $classTemplates = [] ): void { - $hasClosure = false; - foreach ($vars as $v) { - if ($v instanceof \Closure) { - $hasClosure = true; + if (self::callableNodesFor($effectiveFunction, $types) !== []) { + foreach ($vars as $v) { + if ($v instanceof \Closure) { + self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); - break; + break; + } } } - if ($hasClosure) { - self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); - } - if (\count($types) > 0) { self::inferTemplatesFromArrays($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); self::inferTemplatesFromShapes($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); @@ -597,7 +640,7 @@ private static function inferTemplatesFromClosures( array $templates, array $classTemplates = [] ): void { - $callableNodes = self::extractCallableNodes($types); + $callableNodes = self::callableNodesFor($effectiveFunction, $types); if (\count($callableNodes) === 0) { return; } @@ -749,7 +792,7 @@ private static function extractTypeFromReflectionType(?\ReflectionType $type): ? return null; } - if (class_exists($name) || interface_exists($name) || SpecialTypeResolver::isBuiltInTypeKeyword($name)) { + if (SpecialTypeResolver::isBuiltInTypeKeyword($name) || class_exists($name) || interface_exists($name)) { $node = new IdentifierTypeNode($name); return $type->allowsNull() && $name !== 'null' ? new NullableTypeNode($node) : $node; @@ -781,6 +824,18 @@ private static function extractTypeFromReflectionType(?\ReflectionType $type): ? return null; } + /** + * Returns the callable parameter nodes of a contract, memoized per function. + * + * @param array $types + * + * @return array + */ + private static function callableNodesFor(string $effectiveFunction, array $types): array + { + return self::$callableNodesCache[$effectiveFunction] ??= self::extractCallableNodes($types); + } + /** * @param array $types * @@ -897,7 +952,7 @@ private static function extractTypeFromClosureParameter(\ReflectionParameter $cl $cType = $closureParam->getType(); if ($cType instanceof \ReflectionNamedType) { $cTypeName = $cType->getName(); - if ($cTypeName !== 'mixed' && (class_exists($cTypeName) || interface_exists($cTypeName) || SpecialTypeResolver::isBuiltInTypeKeyword($cTypeName))) { + if ($cTypeName !== 'mixed' && (SpecialTypeResolver::isBuiltInTypeKeyword($cTypeName) || class_exists($cTypeName) || interface_exists($cTypeName))) { $node = new IdentifierTypeNode($cTypeName); return $cType->allowsNull() && $cTypeName !== 'null' ? new NullableTypeNode($node) : $node; @@ -907,7 +962,7 @@ private static function extractTypeFromClosureParameter(\ReflectionParameter $cl foreach ($cType->getTypes() as $subNamedType) { if ($subNamedType instanceof \ReflectionNamedType) { $subName = $subNamedType->getName(); - if ($subName !== 'mixed' && (class_exists($subName) || interface_exists($subName) || SpecialTypeResolver::isBuiltInTypeKeyword($subName))) { + if ($subName !== 'mixed' && (SpecialTypeResolver::isBuiltInTypeKeyword($subName) || class_exists($subName) || interface_exists($subName))) { $unionSubTypes[] = new IdentifierTypeNode($subName); } } @@ -1422,6 +1477,31 @@ private static function inferTemplatesFromGenericObjects( } } + /** + * Resolves the reflection context of a function or method once, memoizing hits and misses alike. + * + * @return \ReflectionClass|\ReflectionFunction|null + */ + private static function genericObjectContext(string $effectiveFunction): \ReflectionClass|\ReflectionFunction|null + { + if (\array_key_exists($effectiveFunction, self::$genericObjectContextCache)) { + return self::$genericObjectContextCache[$effectiveFunction]; + } + + $context = null; + + if (str_contains($effectiveFunction, '::')) { + $declaringClass = explode('::', $effectiveFunction, 2)[0]; + if (class_exists($declaringClass, false) || class_exists($declaringClass) || interface_exists($declaringClass) || trait_exists($declaringClass)) { + $context = new \ReflectionClass($declaringClass); + } + } elseif (\function_exists($effectiveFunction)) { + $context = new \ReflectionFunction($effectiveFunction); + } + + return self::$genericObjectContextCache[$effectiveFunction] = $context; + } + /** * @param array $templates * @param array $classTemplates @@ -1459,17 +1539,15 @@ private static function inferGenericObjectNode( return; } - $contextRef = null; - if (str_contains($effectiveFunction, '::')) { - $declaringClass = explode('::', $effectiveFunction, 2)[0]; - if (class_exists($declaringClass, false) || class_exists($declaringClass) || interface_exists($declaringClass) || trait_exists($declaringClass)) { - $contextRef = new \ReflectionClass($declaringClass); - } - } elseif (\function_exists($effectiveFunction)) { - $contextRef = new \ReflectionFunction($effectiveFunction); - } + $typeName = (string) $typeNode->type; + $contextRef = self::genericObjectContext($effectiveFunction); + $contextKey = $contextRef !== null ? $effectiveFunction : '@' . $value::class; - $targetClassFqcn = SpecialTypeResolver::resolveFqcn((string) $typeNode->type, $contextRef ?? new \ReflectionClass($value)); + $targetClassFqcn = self::$genericObjectTargetCache[$contextKey][$typeName] ?? null; + if ($targetClassFqcn === null) { + $targetClassFqcn = SpecialTypeResolver::resolveFqcn($typeName, $contextRef ?? new \ReflectionClass($value)); + self::$genericObjectTargetCache[$contextKey][$typeName] = $targetClassFqcn; + } if (! is_a($value, $targetClassFqcn)) { return; @@ -1652,27 +1730,58 @@ private static function inferTemplatesFromIterableObject( */ private static function resolveTraversableItemTypes(object $value): array { - $className = $value::class; + $plan = self::traversablePlan($value); $boundOnInstance = TemplateManager::getBoundTemplatesForInstance($value); + if ($plan !== null) { + $key = $plan['key']; + $val = $plan['value']; + + $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $plan['templates']) : null; + $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $plan['templates']) : null; + + $key = $key !== null ? SpecialTypeResolver::resolve($key, $plan['context']) : null; + $val = $val !== null ? SpecialTypeResolver::resolve($val, $plan['context']) : null; + + return [$key, $val]; + } + + if (\count($boundOnInstance) === 1) { + return [null, reset($boundOnInstance)]; + } + + return [null, null]; + } + + /** + * Builds and memoizes everything about a Traversable's iteration contract that does not + * depend on the instance's bound templates. + * + * @return array{key: ?TypeNode, value: ?TypeNode, templates: array, context: \ReflectionClass|\ReflectionMethod}|null + */ + private static function traversablePlan(object $value): ?array + { + $className = $value::class; + + if (\array_key_exists($className, self::$traversablePlanCache)) { + return self::$traversablePlanCache[$className]; + } + + $plan = null; + if ($value instanceof \IteratorAggregate) { try { $refClass = new \ReflectionClass($className); - $doc = $refClass->hasMethod('getIterator') - ? $refClass->getMethod('getIterator')->getDocComment() - : false; + $refMethod = $refClass->hasMethod('getIterator') ? $refClass->getMethod('getIterator') : null; + $doc = $refMethod?->getDocComment() ?? false; - if ($doc !== false) { + if ($doc !== false && $refMethod !== null) { $phpDocNode = DocblockExtractor::parseDocString($doc); $returnTag = DocblockExtractor::getReturnTag($phpDocNode); $contract = $returnTag !== null ? GeneratorEvaluator::extractContract($returnTag->type) : null; if ($contract !== null) { - $refMethod = $refClass->getMethod('getIterator'); - $declaringClassTemplates = DocblockParser::parseClassTemplates($refMethod->getDeclaringClass()->getName()); - $classTemplates = [...$declaringClassTemplates, ...DocblockParser::parseClassTemplates($refClass->getName())]; $aliases = DocblockParser::parseClassAliases($refClass->getName()); - $key = $contract['key']; $val = $contract['value']; @@ -1681,72 +1790,69 @@ private static function resolveTraversableItemTypes(object $value): array $val = $val !== null ? DocblockParser::substituteAliases($val, $aliases) : null; } - $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $classTemplates) : null; - $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $classTemplates) : null; - - $key = $key !== null ? SpecialTypeResolver::resolve($key, $refMethod) : null; - $val = $val !== null ? SpecialTypeResolver::resolve($val, $refMethod) : null; - - return [$key, $val]; + $plan = [ + 'key' => $key, + 'value' => $val, + 'templates' => [ + ...DocblockParser::parseClassTemplates($refMethod->getDeclaringClass()->getName()), + ...DocblockParser::parseClassTemplates($refClass->getName()), + ], + 'context' => $refMethod, + ]; } } } catch (\Throwable) { } } - try { - $refClass = new \ReflectionClass($className); - $hierarchy = HierarchyResolver::getClassHierarchy($refClass); - - foreach ($hierarchy as $hierClass) { - $classDoc = StubManager::getClassDoc($hierClass->getName()) ?? $hierClass->getDocComment(); - if ($classDoc === false || $classDoc === null) { - continue; - } - - $phpDocNode = DocblockExtractor::parseDocString($classDoc); - $inheritedTags = DocblockExtractor::getInheritedTags($phpDocNode); + if ($plan === null) { + try { + $refClass = new \ReflectionClass($className); - foreach ($inheritedTags as $inheritedTag) { - $genericNode = $inheritedTag->type; - if (! $genericNode instanceof GenericTypeNode) { + foreach (HierarchyResolver::getClassHierarchy($refClass) as $hierClass) { + $classDoc = StubManager::getClassDoc($hierClass->getName()) ?? $hierClass->getDocComment(); + if ($classDoc === false || $classDoc === null) { continue; } - $base = strtolower(ltrim((string) $genericNode->type, '\\')); - if ($base !== 'iteratoraggregate' && $base !== 'iterator' && $base !== 'traversable') { - continue; - } + $phpDocNode = DocblockExtractor::parseDocString($classDoc); - $count = \count($genericNode->genericTypes); - $key = $count >= 2 ? $genericNode->genericTypes[0] : null; - $val = $count >= 2 ? $genericNode->genericTypes[1] : ($genericNode->genericTypes[0] ?? null); + foreach (DocblockExtractor::getInheritedTags($phpDocNode) as $inheritedTag) { + $genericNode = $inheritedTag->type; + if (! $genericNode instanceof GenericTypeNode) { + continue; + } - $classTemplates = DocblockParser::parseClassTemplates($hierClass->getName()); - $aliases = DocblockParser::parseClassAliases($hierClass->getName()); + $base = strtolower(ltrim((string) $genericNode->type, '\\')); + if ($base !== 'iteratoraggregate' && $base !== 'iterator' && $base !== 'traversable') { + continue; + } - if ($aliases !== []) { - $key = $key !== null ? DocblockParser::substituteAliases($key, $aliases) : null; - $val = $val !== null ? DocblockParser::substituteAliases($val, $aliases) : null; - } + $count = \count($genericNode->genericTypes); + $key = $count >= 2 ? $genericNode->genericTypes[0] : null; + $val = $count >= 2 ? $genericNode->genericTypes[1] : ($genericNode->genericTypes[0] ?? null); - $key = $key !== null ? TemplateSubstitutor::substitute($key, $boundOnInstance, $classTemplates) : null; - $val = $val !== null ? TemplateSubstitutor::substitute($val, $boundOnInstance, $classTemplates) : null; + $aliases = DocblockParser::parseClassAliases($hierClass->getName()); + if ($aliases !== []) { + $key = $key !== null ? DocblockParser::substituteAliases($key, $aliases) : null; + $val = $val !== null ? DocblockParser::substituteAliases($val, $aliases) : null; + } - $key = $key !== null ? SpecialTypeResolver::resolve($key, $hierClass) : null; - $val = $val !== null ? SpecialTypeResolver::resolve($val, $hierClass) : null; + $plan = [ + 'key' => $key, + 'value' => $val, + 'templates' => DocblockParser::parseClassTemplates($hierClass->getName()), + 'context' => $hierClass, + ]; - return [$key, $val]; + break 2; + } } + } catch (\Throwable) { } - } catch (\Throwable) { - } - - if (\count($boundOnInstance) === 1) { - return [null, reset($boundOnInstance)]; } - return [null, null]; + return self::$traversablePlanCache[$className] = $plan; } /** @@ -1756,7 +1862,6 @@ private static function resolveTraversableItemTypes(object $value): array * @param array $aliases * @param array $boundTemplates * @param array $declaredTemplates - * @param TypeValidatorRegistry $registry * @param array $classTemplates * @param array $vars */ @@ -2384,4 +2489,4 @@ private static function typeContainsNull(TypeNode $node): bool return false; } -} +} \ No newline at end of file diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 2709482c..3b4f8855 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -65,6 +65,27 @@ final class TemplateManager */ private static array $classHierarchyTemplatesCache = []; + /** + * Cache for declared template variance lists per class name (positional, as consumed by variance checks). + * + * @var array> + */ + private static array $declaredVarianceListCache = []; + + /** + * Cache for usable declared template defaults per class name. + * + * @var array> + */ + private static array $classTemplateDefaultsCache = []; + + /** + * Cache for declared template variances per class name. + * + * @var array> + */ + private static array $templateVariancesCache = []; + /** * Cache for inherited template bindings per class name. * @@ -445,6 +466,14 @@ final class TemplateManager */ private static array $propagationStack = []; + /** + * Per-class propagation plan: non-static properties whose declared type is generic. + * Holds reusable ReflectionProperty descriptors so propagation allocates nothing per instance. + * + * @var array> + */ + private static array $propagationPlanCache = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -453,6 +482,9 @@ public static function reset(): void self::$instanceTemplateBindings = null; self::$callStackBindings = []; self::$classHierarchyTemplatesCache = []; + self::$declaredVarianceListCache = []; + self::$classTemplateDefaultsCache = []; + self::$templateVariancesCache = []; self::$classInheritedBindingsCache = []; self::$classInheritedRawMappingsCache = []; self::$subclassCache = []; @@ -468,6 +500,7 @@ public static function reset(): void self::$generatorInferredCallFrames = []; self::$callStackThis = []; self::$propagationStack = []; + self::$propagationPlanCache = []; } /** @@ -734,17 +767,10 @@ public static function getClassStaticBindings(string $className): array { $bindings = self::getClassInheritedBindings($className); - try { - $ref = new \ReflectionClass($className); - [$hierarchyTemplates] = self::collectHierarchyTemplatesAndVariances($ref); - - foreach ($hierarchyTemplates as $tName => $templateTag) { - if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { - $bindings[$tName] = $templateTag->default; - } + foreach (self::classTemplateDefaults($className) as $tName => $default) { + if (! isset($bindings[$tName])) { + $bindings[$tName] = $default; } - } catch (\Throwable $e) { - // Silently ignore reflection errors } return $bindings; @@ -824,17 +850,10 @@ public static function getBoundTemplatesForInstance(object $instance): array ? self::$instanceTemplateBindings[$instance] : []; - try { - $ref = new \ReflectionClass($instance); - [$hierarchyTemplates] = self::collectHierarchyTemplatesAndVariances($ref); - - foreach ($hierarchyTemplates as $tName => $templateTag) { - if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { - $bindings[$tName] = $templateTag->default; - } + foreach (self::classTemplateDefaults($instance::class) as $tName => $default) { + if (! isset($bindings[$tName])) { + $bindings[$tName] = $default; } - } catch (\Throwable $e) { - // Silently ignore reflection errors } return $bindings; @@ -849,6 +868,10 @@ public static function getTemplateVariances(object $instance): array { $className = $instance::class; + if (isset(self::$templateVariancesCache[$className])) { + return self::$templateVariancesCache[$className]; + } + try { $stubDoc = StubManager::getClassDoc($className); $ref = new \ReflectionClass($instance); @@ -857,13 +880,13 @@ public static function getTemplateVariances(object $instance): array if ($classDoc !== false) { $classPhpDocNode = DocblockExtractor::parseDocString($classDoc); - return DocblockExtractor::extractTemplateVariances($classPhpDocNode); + return self::$templateVariancesCache[$className] = DocblockExtractor::extractTemplateVariances($classPhpDocNode); } } catch (\Throwable $e) { // Silently ignore reflection errors } - return []; + return self::$templateVariancesCache[$className] = []; } /** @@ -1035,9 +1058,7 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t self::resolveInheritedTemplates($instance, $className); try { - /** @var class-string $className */ - $ref = new \ReflectionClass($className); - [$templates, $classVariances] = self::collectHierarchyTemplatesAndVariances($ref); + [$templates, $classVariances] = self::hierarchyTemplatesForClass($className); self::$instanceTemplateBindings ??= new WeakMap(); $templateList = array_values($templates); @@ -1134,6 +1155,38 @@ public static function applyClassTemplateDefaults(object $instance, array $class } } + /** + * Builds the per-class propagation plan: non-static properties whose declared type is generic. + * ReflectionProperty descriptors are reusable across instances, so propagation allocates nothing per instance. + * + * @return list + */ + private static function propagationPlan(string $className): array + { + if (isset(self::$propagationPlanCache[$className])) { + return self::$propagationPlanCache[$className]; + } + + $plan = []; + try { + /** @var class-string $className */ + $ref = new \ReflectionClass($className); + foreach ($ref->getProperties() as $prop) { + if ($prop->isStatic()) { + continue; + } + + $propType = DocblockParser::parseProperty($className, $prop->getName()); + if ($propType instanceof GenericTypeNode) { + $plan[] = ['prop' => $prop, 'type' => $propType]; + } + } + } catch (\Throwable) { + } + + return self::$propagationPlanCache[$className] = $plan; + } + /** * Propagates resolved class template bindings on an instance to any of its object properties * whose declared types reference those class templates (e.g. $this->store with @var KeyValueStore). @@ -1149,9 +1202,8 @@ private static function propagateBindingsToInstanceProperties(object $instance): return; } - $ref = new \ReflectionObject($instance); - - if (\PHP_VERSION_ID >= 80400 && $ref->isUninitializedLazyObject($instance)) { + $plan = self::propagationPlan($instance::class); + if ($plan === []) { return; } @@ -1162,10 +1214,12 @@ private static function propagateBindingsToInstanceProperties(object $instance): self::$propagationStack[$oid] = true; try { - foreach ($ref->getProperties() as $prop) { - if ($prop->isStatic()) { - continue; - } + if (\PHP_VERSION_ID >= 80400 && (new \ReflectionObject($instance))->isUninitializedLazyObject($instance)) { + return; + } + + foreach ($plan as $entry) { + $prop = $entry['prop']; if (\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) { continue; @@ -1180,16 +1234,11 @@ private static function propagateBindingsToInstanceProperties(object $instance): continue; } - $propType = DocblockParser::parseProperty($instance::class, $prop->getName()); - if (! ($propType instanceof GenericTypeNode)) { - continue; - } - - if (! DocblockParser::typeReferencesTemplate($propType, $instanceBindings)) { + if (! DocblockParser::typeReferencesTemplate($entry['type'], $instanceBindings)) { continue; } - $resolvedPropType = TemplateSubstitutor::substitute($propType, $instanceBindings); + $resolvedPropType = TemplateSubstitutor::substitute($entry['type'], $instanceBindings); if ($resolvedPropType instanceof GenericTypeNode) { self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true, refineOnly: true); } @@ -1200,6 +1249,21 @@ private static function propagateBindingsToInstanceProperties(object $instance): } } + /** + * Resolves hierarchy templates and variances by class name, skipping reflection entirely on a cache hit. + * + * @return array{0: array, 1: array} + */ + private static function hierarchyTemplatesForClass(string $className): array + { + if (isset(self::$classHierarchyTemplatesCache[$className])) { + return self::$classHierarchyTemplatesCache[$className]; + } + + /** @var class-string $className */ + return self::collectHierarchyTemplatesAndVariances(new \ReflectionClass($className)); + } + /** * @param \ReflectionClass $ref * @@ -1253,6 +1317,57 @@ private static function collectHierarchyTemplatesAndVariances(\ReflectionClass $ return self::$classHierarchyTemplatesCache[$className] = [$templates, $classVariances]; } + /** + * Returns the positional declared variances of a class, memoized so recursive variance + * checks never construct reflection for a class already resolved. + * + * @return list + */ + private static function declaredVarianceList(string $className): array + { + if (isset(self::$declaredVarianceListCache[$className])) { + return self::$declaredVarianceListCache[$className]; + } + + $variances = []; + if (class_exists($className, false) || class_exists($className) || interface_exists($className)) { + try { + [, $classVariances] = self::hierarchyTemplatesForClass($className); + $variances = array_values($classVariances); + } catch (\Throwable $e) { + } + } + + return self::$declaredVarianceListCache[$className] = $variances; + } + + /** + * Returns the usable declared template defaults of a class, memoized so the common + * "no defaults" case costs neither reflection nor a hierarchy walk. + * + * @return array + */ + private static function classTemplateDefaults(string $className): array + { + if (isset(self::$classTemplateDefaultsCache[$className])) { + return self::$classTemplateDefaultsCache[$className]; + } + + $defaults = []; + try { + [$hierarchyTemplates] = self::hierarchyTemplatesForClass($className); + foreach ($hierarchyTemplates as $tName => $templateTag) { + if ($templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $defaults[$tName] = $templateTag->default; + } + } + } catch (\Throwable $e) { + // Silently ignore reflection errors + } + + return self::$classTemplateDefaultsCache[$className] = $defaults; + } + /** * Widens template bindings on a cloned instance when the enclosing method's @return contract * widens class templates with method-level templates (e.g. @return self or ImmutableMap). @@ -1699,10 +1814,22 @@ public static function resolveInheritedTemplates(object $instance, string $targe $rawMappings = self::$classInheritedRawMappingsCache[$actualClassName] ?? []; $existing = self::$instanceTemplateBindings[$instance] ?? []; + if ($cachedBindings === [] && $rawMappings === []) { + return; + } + + if ($existing === []) { + if ($cachedBindings !== []) { + self::$instanceTemplateBindings[$instance] = $cachedBindings; + } + + return; + } + $specializedBindings = []; foreach ($cachedBindings as $tName => $fallbackTypeNode) { $rawNode = $rawMappings[$tName] ?? $fallbackTypeNode; - if ($existing !== [] && DocblockParser::typeReferencesTemplate($rawNode, $existing)) { + if (DocblockParser::typeReferencesTemplate($rawNode, $existing)) { $specializedBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $existing); } else { $specializedBindings[$tName] = $existing[$tName] ?? $fallbackTypeNode; @@ -1710,13 +1837,13 @@ public static function resolveInheritedTemplates(object $instance, string $targe } foreach ($rawMappings as $tName => $rawNode) { - if (! isset($specializedBindings[$tName]) && $existing !== [] && DocblockParser::typeReferencesTemplate($rawNode, $existing)) { + if (! isset($specializedBindings[$tName]) && DocblockParser::typeReferencesTemplate($rawNode, $existing)) { $specializedBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $existing); } } $merged = [...$existing, ...$specializedBindings]; - if ($merged !== []) { + if ($merged !== [] && $merged !== $existing) { self::$instanceTemplateBindings[$instance] = $merged; } } @@ -2153,15 +2280,7 @@ private static function checkIdentifierAgainstGenericVariance( $parentTemplates = DocblockParser::parseClassTemplates((string) $expected->type); $parentTemplateNames = array_keys($parentTemplates); - $declaredVariances = []; - if (class_exists((string) $expected->type, false) || class_exists((string) $expected->type) || interface_exists((string) $expected->type)) { - try { - $ref = new \ReflectionClass((string) $expected->type); - [, $classVariances] = self::collectHierarchyTemplatesAndVariances($ref); - $declaredVariances = array_values($classVariances); - } catch (\Throwable $e) { - } - } + $declaredVariances = self::declaredVarianceList((string) $expected->type); foreach ($parentTemplateNames as $idx => $tName) { if (isset($classBindings[$tName], $expected->genericTypes[$idx])) { @@ -2334,15 +2453,7 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge return false; } - $declaredVariances = []; - if (class_exists($expectedClassName, false) || class_exists($expectedClassName) || interface_exists($expectedClassName)) { - try { - $ref = new \ReflectionClass($expectedClassName); - [, $classVariances] = self::collectHierarchyTemplatesAndVariances($ref); - $declaredVariances = array_values($classVariances); - } catch (\Throwable $e) { - } - } + $declaredVariances = self::declaredVarianceList($expectedClassName); foreach ($expected->genericTypes as $idx => $expectedInner) { if ($expectedInner instanceof IdentifierTypeNode) { From fe86ceb56a20e95da5bcbd39c24b98f4f9f02c2d Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 13 Nov 2026 23:46:05 +0800 Subject: [PATCH 22/37] Fix formatting by adding missing newlines in ParamChecker and TemplateManager --- src/Internal/Checker/ParamChecker.php | 2 +- src/Internal/Generics/TemplateManager.php | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index efefcfa8..219e5258 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -2489,4 +2489,4 @@ private static function typeContainsNull(TypeNode $node): bool return false; } -} \ No newline at end of file +} diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 3b4f8855..c2fb57e3 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1168,6 +1168,7 @@ private static function propagationPlan(string $className): array } $plan = []; + try { /** @var class-string $className */ $ref = new \ReflectionClass($className); @@ -1354,6 +1355,7 @@ private static function classTemplateDefaults(string $className): array } $defaults = []; + try { [$hierarchyTemplates] = self::hierarchyTemplatesForClass($className); foreach ($hierarchyTemplates as $tName => $templateTag) { @@ -1817,7 +1819,7 @@ public static function resolveInheritedTemplates(object $instance, string $targe if ($cachedBindings === [] && $rawMappings === []) { return; } - + if ($existing === []) { if ($cachedBindings !== []) { self::$instanceTemplateBindings[$instance] = $cachedBindings; From fc1cd2a59248212ca4d78f9feae076c9d6bc7a99 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 14 Nov 2026 00:38:23 +0800 Subject: [PATCH 23/37] Fix PHP version check placement in ReturnGenericReificationTest --- tests/TypeChecking/Generics/ReturnGenericReificationTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/TypeChecking/Generics/ReturnGenericReificationTest.php b/tests/TypeChecking/Generics/ReturnGenericReificationTest.php index 2f5d4dc9..c0b90f21 100644 --- a/tests/TypeChecking/Generics/ReturnGenericReificationTest.php +++ b/tests/TypeChecking/Generics/ReturnGenericReificationTest.php @@ -8,6 +8,10 @@ use TypePHP\Tests\Fixtures\Generics\TestSetInterface; use TypePHP\TypePHP; +if (PHP_VERSION_ID < 80400) { + return; +} + require_once __DIR__ . '/../../Fixtures/Generics/ReturnGenericReificationFixtures.php'; describe('Generic Template Inference from Iterables of Array Shapes', function () { From 81e624c784af16d2631dca48eb2ea0a0fc770c2c Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 14 Nov 2026 21:09:37 +0800 Subject: [PATCH 24/37] Add generic iterable and animal producer classes with tests for type inference across namespaces --- src/Internal/Checker/ParamChecker.php | 40 +++++++++++++- .../Fixtures/Consumer/GenericIterableBox.php | 44 +++++++++++++++ .../Fixtures/Domain/AnimalGeneratorTrait.php | 35 ++++++++++++ .../Domain/Sub/GenericIterableBox.php | 44 +++++++++++++++ .../Domain/Sub/ImportedAnimalProducer.php | 20 +++++++ .../Domain/Sub/TraitAnimalProducer.php | 32 +++++++++++ .../Generics/GeneratorCrossNamespaceTest.php | 55 +++++++++++++++++++ 7 files changed, 267 insertions(+), 3 deletions(-) create mode 100644 tests/Fixtures/Consumer/GenericIterableBox.php create mode 100644 tests/Fixtures/Domain/AnimalGeneratorTrait.php create mode 100644 tests/Fixtures/Domain/Sub/GenericIterableBox.php create mode 100644 tests/Fixtures/Domain/Sub/ImportedAnimalProducer.php create mode 100644 tests/Fixtures/Domain/Sub/TraitAnimalProducer.php create mode 100644 tests/TypeChecking/Generics/GeneratorCrossNamespaceTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 219e5258..edc073c2 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1676,21 +1676,55 @@ private static function inferTemplatesFromIterableObject( $genMethodTemplates = DocblockExtractor::extractTemplates($phpDocNode); $genClassTemplates = []; + $genAliases = []; + $genContext = null; + if ($genFunc instanceof \ReflectionMethod) { - $genClassTemplates = DocblockParser::parseClassTemplates($genFunc->getDeclaringClass()->getName()); + $genContext = $genFunc; + $declaringClassName = $genFunc->getDeclaringClass()->getName(); + $genClassTemplates = DocblockParser::parseClassTemplates($declaringClassName); + $genAliases = DocblockParser::parseClassAliases($declaringClassName); + DocblockExtractor::extractAliases($phpDocNode, $genAliases, $genFunc); + $genFunctionName = $declaringClassName . '::' . $genFunc->getName(); + } elseif ($genFunc instanceof \ReflectionFunction) { + $genContext = $genFunc; + DocblockExtractor::extractAliases($phpDocNode, $genAliases, $genFunc); + $genFunctionName = $genFunc->getName(); + } else { + $genFunctionName = $genFunc->getName(); } + $allGenDeclaredTemplates = [...$genClassTemplates, ...$genMethodTemplates]; if ($inferredKey !== null) { + if ($genAliases !== []) { + $inferredKey = DocblockParser::substituteAliases($inferredKey, $genAliases); + } $inferredKey = TemplateSubstitutor::substitute($inferredKey, $boundOnGenThis, $allGenDeclaredTemplates); + if ($genContext !== null) { + $inferredKey = SpecialTypeResolver::resolve($inferredKey, $genContext, $genThis); + } if (ConditionalChecker::containsConditional($inferredKey)) { - $inferredKey = ConditionalChecker::resolve($inferredKey, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $effectiveFunction); + $inferredKey = ConditionalChecker::resolve($inferredKey, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $genFunctionName); + if ($genContext !== null) { + $inferredKey = SpecialTypeResolver::resolve($inferredKey, $genContext, $genThis); + } } } + if ($inferredVal !== null) { + if ($genAliases !== []) { + $inferredVal = DocblockParser::substituteAliases($inferredVal, $genAliases); + } $inferredVal = TemplateSubstitutor::substitute($inferredVal, $boundOnGenThis, $allGenDeclaredTemplates); + if ($genContext !== null) { + $inferredVal = SpecialTypeResolver::resolve($inferredVal, $genContext, $genThis); + } if (ConditionalChecker::containsConditional($inferredVal)) { - $inferredVal = ConditionalChecker::resolve($inferredVal, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $effectiveFunction); + $inferredVal = ConditionalChecker::resolve($inferredVal, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $genFunctionName); + if ($genContext !== null) { + $inferredVal = SpecialTypeResolver::resolve($inferredVal, $genContext, $genThis); + } } } } diff --git a/tests/Fixtures/Consumer/GenericIterableBox.php b/tests/Fixtures/Consumer/GenericIterableBox.php new file mode 100644 index 00000000..f0aa575d --- /dev/null +++ b/tests/Fixtures/Consumer/GenericIterableBox.php @@ -0,0 +1,44 @@ + + */ + private array $values = []; + + /** + * @template NK + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromIterable(iterable $source): self + { + /** @var self $box */ + $box = new self(); + foreach ($source as $k => $v) { + $box->values[$k] = $v; + } + + return $box; + } + + /** + * @return array + */ + public function values(): array + { + return $this->values; + } +} diff --git a/tests/Fixtures/Domain/AnimalGeneratorTrait.php b/tests/Fixtures/Domain/AnimalGeneratorTrait.php new file mode 100644 index 00000000..3dbb86c1 --- /dev/null +++ b/tests/Fixtures/Domain/AnimalGeneratorTrait.php @@ -0,0 +1,35 @@ + + */ + public function yieldSameNamespaceAnimals(): Generator + { + yield 'first' => new Dog(); + } + + /** + * @return Generator + */ + public function yieldConditionalAnimal(): Generator + { + if ($this->item === null) { + yield 'car' => new Car(); + + return; + } + + yield 'dog' => new Dog(); + } +} diff --git a/tests/Fixtures/Domain/Sub/GenericIterableBox.php b/tests/Fixtures/Domain/Sub/GenericIterableBox.php new file mode 100644 index 00000000..f0aa575d --- /dev/null +++ b/tests/Fixtures/Domain/Sub/GenericIterableBox.php @@ -0,0 +1,44 @@ + + */ + private array $values = []; + + /** + * @template NK + * @template NV + * + * @param iterable $source + * + * @return self + */ + public static function fromIterable(iterable $source): self + { + /** @var self $box */ + $box = new self(); + foreach ($source as $k => $v) { + $box->values[$k] = $v; + } + + return $box; + } + + /** + * @return array + */ + public function values(): array + { + return $this->values; + } +} diff --git a/tests/Fixtures/Domain/Sub/ImportedAnimalProducer.php b/tests/Fixtures/Domain/Sub/ImportedAnimalProducer.php new file mode 100644 index 00000000..e9440559 --- /dev/null +++ b/tests/Fixtures/Domain/Sub/ImportedAnimalProducer.php @@ -0,0 +1,20 @@ + + */ + public function yieldImportedAnimals(): Generator + { + yield 'first' => new Dog(); + } +} diff --git a/tests/Fixtures/Domain/Sub/TraitAnimalProducer.php b/tests/Fixtures/Domain/Sub/TraitAnimalProducer.php new file mode 100644 index 00000000..ad300f28 --- /dev/null +++ b/tests/Fixtures/Domain/Sub/TraitAnimalProducer.php @@ -0,0 +1,32 @@ + + */ +final class TraitAnimalProducer implements \IteratorAggregate +{ + /** @use AnimalGeneratorTrait */ + use AnimalGeneratorTrait; + + /** + * @param T $item + */ + public function __construct( + private readonly ?Animal $item = null, + ) { + } + + public function getIterator(): \Traversable + { + yield $this->item; + } +} diff --git a/tests/TypeChecking/Generics/GeneratorCrossNamespaceTest.php b/tests/TypeChecking/Generics/GeneratorCrossNamespaceTest.php new file mode 100644 index 00000000..19a07216 --- /dev/null +++ b/tests/TypeChecking/Generics/GeneratorCrossNamespaceTest.php @@ -0,0 +1,55 @@ +yieldSameNamespaceAnimals()); + + expect($box->values()['first'])->toBeInstanceOf(Animal::class); + }); + + test('resolves imported class in generator @return when consumed in another namespace', function () { + $producer = new ImportedAnimalProducer(); + $box = GenericIterableBox::fromIterable($producer->yieldImportedAnimals()); + + expect($box->values()['first'])->toBeInstanceOf(Animal::class); + }); + + test('resolves conditional generator @return in the generator own context across namespaces', function () { + $dogProducer = new TraitAnimalProducer(new Dog()); + $dogBox = GenericIterableBox::fromIterable($dogProducer->yieldConditionalAnimal()); + expect($dogBox->values()['dog'])->toBeInstanceOf(Animal::class); + + $nullProducer = new TraitAnimalProducer(null); + $carBox = GenericIterableBox::fromIterable($nullProducer->yieldConditionalAnimal()); + expect($carBox->values()['car'])->toBeInstanceOf(Car::class); + }); + + test('still throws TypeError with resolved FQCN when generator yields wrong type to consumer', function () { + $producer = new class () { + /** + * @return \Generator + */ + public function yieldInvalid(): \Generator + { + yield 'bad' => new Car(); + } + }; + + expect(fn () => GenericIterableBox::fromIterable($producer->yieldInvalid())) + ->toThrow(TypeError::class, Animal::class) + ; + }); +}); From 8c613abab5f4b6559792afd20783658f94eba170 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 00:11:52 +0800 Subject: [PATCH 25/37] Refactor contract cache handling in checkers and enhance method hierarchy resolution with dynamic class name support --- src/Internal/Ast/FunctionContractInjector.php | 27 +- src/Internal/Checker/ParamChecker.php | 1 - src/Internal/Checker/ParamOutChecker.php | 3 - src/Internal/Checker/ReturnChecker.php | 6 +- src/Internal/Checker/SelfOutChecker.php | 3 - src/Internal/Docblock/DocblockParser.php | 7 +- src/Internal/Resolver/HierarchyResolver.php | 42 ++- src/Internal/RuntimeTypeChecker.php | 16 +- tests/Internal/RuntimeTypeCheckerTest.php | 2 +- .../SiblingInheritanceCachePoisoningTest.php | 248 ++++++++++++++++++ 10 files changed, 312 insertions(+), 43 deletions(-) create mode 100644 tests/TypeChecking/InheritanceAndAttributes/SiblingInheritanceCachePoisoningTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 94c46b1f..83b5c7f2 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -137,9 +137,11 @@ public static function inject( $hasInheritance || str_contains($docText, ' is ') || ($hasReturnDoc && str_contains($docText, '$')) )) || ($isClassMethod && $paramCount > 0 && ($isMagicGet || $isMagicCall)); + $useDynamicMethodKey = $isClassMethod && ! $isPrivate && ! $isFinalClass; + $injectedStmts = []; if ($hasParam) { - $injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars); + $injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars, $useDynamicMethodKey); } $returnTypeNode = null; @@ -445,9 +447,10 @@ private static function buildParamInjections( string $docText, Node\Expr $thisArg, bool $isReadonlyClass = false, - bool $needsReturnVars = false + bool $needsReturnVars = false, + bool $useDynamicMethodKey = false ): array { - $setupScopeStmts = self::buildSetupScopeStmt($params, $thisArg, $needsReturnVars); + $setupScopeStmts = self::buildSetupScopeStmt($params, $thisArg, $needsReturnVars, $useDynamicMethodKey); $callableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isCallableCandidate'], 'wrapCallable', $isReadonlyClass); $iterableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isIterableCandidate'], 'wrapIterable', $isReadonlyClass); @@ -459,8 +462,12 @@ private static function buildParamInjections( * * @return array */ - private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, bool $needsReturnVars = false): array - { + private static function buildSetupScopeStmt( + array $params, + Node\Expr $thisArg, + bool $needsReturnVars = false, + bool $useDynamicMethodKey = false + ): array { $arrayItems = []; foreach ($params as $param) { if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name)) { @@ -490,7 +497,15 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b ); $throwStmt = self::buildTypeErrorThrowStmt(new Node\Expr\Variable('__typephpScope')); - $cacheKeyExpr = new Node\Scalar\MagicConst\Method(); + $cacheKeyExpr = $useDynamicMethodKey + ? new Node\Expr\BinaryOp\Concat( + new Node\Expr\BinaryOp\Concat( + new Node\Expr\ClassConstFetch(new Node\Name('static'), 'class'), + new Node\Scalar\String_('::') + ), + new Node\Scalar\MagicConst\Function_() + ) + : new Node\Scalar\MagicConst\Method(); $noParamFetch = new Node\Expr\StaticPropertyFetch( new Node\Name\FullyQualified('TypePHP\Internal\Checker\ParamChecker'), diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index edc073c2..d28acd5f 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -224,7 +224,6 @@ public static function checkParams( if (! $contract['hasParamContract']) { self::$noParamContractCache[$effectiveFunction] = true; - self::$noParamContractCache[$function] = true; return null; } diff --git a/src/Internal/Checker/ParamOutChecker.php b/src/Internal/Checker/ParamOutChecker.php index 45db2f4d..ff23c28d 100644 --- a/src/Internal/Checker/ParamOutChecker.php +++ b/src/Internal/Checker/ParamOutChecker.php @@ -56,8 +56,6 @@ public static function checkParamOut( } if (isset(self::$noParamOutContractCache[$effectiveFunction])) { - self::$noParamOutContractCache[$function] = true; - return null; } @@ -65,7 +63,6 @@ public static function checkParamOut( if (! ($contract['hasParamOutContract'] ?? false)) { self::$noParamOutContractCache[$effectiveFunction] = true; - self::$noParamOutContractCache[$function] = true; return null; } diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index e20b6266..b5a19658 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -118,9 +118,7 @@ public static function checkReturn( $isMagicGet = str_ends_with($effectiveFunction, '::__get'); if (! $isMagicCall && ! $isMagicGet) { - if (isset(self::$noReturnContractCache[$function]) || isset(self::$noReturnContractCache[$effectiveFunction])) { - self::$noReturnContractCache[$function] = true; - + if (isset(self::$noReturnContractCache[$effectiveFunction])) { return $value; } } @@ -155,7 +153,6 @@ public static function checkReturn( if (! ($contract['hasReturnContract'] ?? ($contract['return'] !== null))) { self::$noReturnContractCache[$effectiveFunction] = true; - self::$noReturnContractCache[$function] = true; return $value; } @@ -163,7 +160,6 @@ public static function checkReturn( $returnTypeNode = $contract['return']; if ($returnTypeNode === null) { self::$noReturnContractCache[$effectiveFunction] = true; - self::$noReturnContractCache[$function] = true; return $value; } diff --git a/src/Internal/Checker/SelfOutChecker.php b/src/Internal/Checker/SelfOutChecker.php index c695e71e..508e8309 100644 --- a/src/Internal/Checker/SelfOutChecker.php +++ b/src/Internal/Checker/SelfOutChecker.php @@ -52,8 +52,6 @@ public static function checkSelfOut( } if (isset(self::$noSelfOutContractCache[$effectiveFunction])) { - self::$noSelfOutContractCache[$function] = true; - return; } @@ -61,7 +59,6 @@ public static function checkSelfOut( if (! ($contract['hasSelfOutContract'] ?? false) || $contract['selfOut'] === null) { self::$noSelfOutContractCache[$effectiveFunction] = true; - self::$noSelfOutContractCache[$function] = true; return; } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index e42800b9..1d3bed18 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -968,7 +968,7 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t self::parseClassLevelDocs($ref->getDeclaringClass(), $classTemplates, $aliases); } - self::parseMethodHierarchyDocs($ref, $types, $methodTemplates, $returnType, $aliases, $paramOuts, $selfOut, $classTemplates, $sensitiveParams); + self::parseMethodHierarchyDocs($ref, $types, $methodTemplates, $returnType, $aliases, $paramOuts, $selfOut, $classTemplates, $sensitiveParams, $targetClass->getName()); if ($ref->getName() === '__construct') { self::applyConstructorPromotionFallback($ref, $types, $classTemplates, $aliases); @@ -1358,9 +1358,10 @@ private static function parseMethodHierarchyDocs( array &$paramOuts = [], ?TypeNode &$selfOut = null, array &$classTemplates = [], - array &$sensitiveParams = [] + array &$sensitiveParams = [], + ?string $targetClassName = null ): void { - $hierarchy = HierarchyResolver::getMethodHierarchy($ref); + $hierarchy = HierarchyResolver::getMethodHierarchy($ref, $targetClassName); $baseParams = $ref->getParameters(); $baseParamNames = []; $baseParamSet = []; diff --git a/src/Internal/Resolver/HierarchyResolver.php b/src/Internal/Resolver/HierarchyResolver.php index 8f16766d..5ce2cf9f 100644 --- a/src/Internal/Resolver/HierarchyResolver.php +++ b/src/Internal/Resolver/HierarchyResolver.php @@ -129,9 +129,10 @@ public static function getTraitAliases(string $className): array * * @return list */ - public static function getMethodHierarchy(ReflectionMethod $ref): array + public static function getMethodHierarchy(ReflectionMethod $ref, ?string $targetClassName = null): array { - $targetClassName = $ref->class; + $declaringClassName = $ref->class; + $targetClassName ??= $declaringClassName; $methodName = $ref->getName(); if (isset(self::$methodHierarchyCache[$targetClassName][$methodName])) { @@ -139,15 +140,25 @@ public static function getMethodHierarchy(ReflectionMethod $ref): array } $hierarchy = [$ref]; - $targetClass = new ReflectionClass($targetClassName); + $seen = [$declaringClassName . '::' . $methodName => true]; - $traitAliases = self::getTraitAliases($targetClassName); + /** @var class-string $targetClassName */ + $targetClass = self::typeExists($targetClassName) + ? new ReflectionClass($targetClassName) + : new ReflectionClass($declaringClassName); + + $traitAliases = self::getTraitAliases($targetClass->getName()); if (isset($traitAliases[$methodName])) { [$traitName, $originalMethodName] = explode('::', $traitAliases[$methodName], 2); if (trait_exists($traitName)) { $traitRef = new ReflectionClass($traitName); if ($traitRef->hasMethod($originalMethodName)) { - $hierarchy[] = $traitRef->getMethod($originalMethodName); + $m = $traitRef->getMethod($originalMethodName); + $key = $m->class . '::' . $m->getName(); + if (! isset($seen[$key])) { + $seen[$key] = true; + $hierarchy[] = $m; + } } } } @@ -155,20 +166,35 @@ public static function getMethodHierarchy(ReflectionMethod $ref): array $parent = $targetClass->getParentClass(); while ($parent !== false) { if ($parent->hasMethod($methodName)) { - $hierarchy[] = $parent->getMethod($methodName); + $m = $parent->getMethod($methodName); + $key = $m->class . '::' . $m->getName(); + if (! isset($seen[$key])) { + $seen[$key] = true; + $hierarchy[] = $m; + } } $parent = $parent->getParentClass(); } foreach ($targetClass->getInterfaces() as $interface) { if ($interface->hasMethod($methodName)) { - $hierarchy[] = $interface->getMethod($methodName); + $m = $interface->getMethod($methodName); + $key = $m->class . '::' . $m->getName(); + if (! isset($seen[$key])) { + $seen[$key] = true; + $hierarchy[] = $m; + } } } foreach ($targetClass->getTraits() as $trait) { if ($trait->hasMethod($methodName)) { - $hierarchy[] = $trait->getMethod($methodName); + $m = $trait->getMethod($methodName); + $key = $m->class . '::' . $m->getName(); + if (! isset($seen[$key])) { + $seen[$key] = true; + $hierarchy[] = $m; + } } } diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 23ac460d..7d15cb33 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -469,8 +469,8 @@ public static function setupScope(string $function, array $vars, object|string|n } if ( - isset(ParamChecker::$noParamContractCache[$function]) - && ! (self::$hasMethodTemplatesCache[$function] ?? false) + isset(ParamChecker::$noParamContractCache[$effectiveFunction]) + && ! (self::$hasMethodTemplatesCache[$effectiveFunction] ?? false) ) { return null; } @@ -478,7 +478,6 @@ public static function setupScope(string $function, array $vars, object|string|n $contract = DocblockParser::parse($effectiveFunction); if (! $isMagicCall && ($contract['allParamsUnconstrained'] ?? false)) { ParamChecker::$noParamContractCache[$effectiveFunction] = true; - ParamChecker::$noParamContractCache[$function] = true; return null; } @@ -513,7 +512,6 @@ public static function setupScope(string $function, array $vars, object|string|n || ($contract['returnUsesMethodTemplates'] ?? false) || ($isStaticCall && ($contract['classTemplates'] ?? []) !== []) ); - self::$hasMethodTemplatesCache[$function] = $hasMethodTemplates; } if ($hasMethodTemplates) { @@ -614,15 +612,9 @@ public static function checkSelfOut(string $function, object $thisObj, ?array $v return; } - if (isset(SelfOutChecker::$noSelfOutContractCache[$function])) { - return; - } - $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisObj, $thisObj); if (isset(SelfOutChecker::$noSelfOutContractCache[$effectiveFunction])) { - SelfOutChecker::$noSelfOutContractCache[$function] = true; - return; } @@ -661,9 +653,7 @@ public static function checkReturn(string $function, mixed $value, object|string && (str_contains($effectiveFunction, '__call') || str_ends_with($effectiveFunction, '::__get')); if (! $isDynamicDispatch) { - if (isset(ReturnChecker::$noReturnContractCache[$function]) || isset(ReturnChecker::$noReturnContractCache[$effectiveFunction])) { - ReturnChecker::$noReturnContractCache[$function] = true; - + if (isset(ReturnChecker::$noReturnContractCache[$effectiveFunction])) { return $value; } } diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index 9e2ad4c2..8a3b016f 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -445,7 +445,7 @@ function runtimeUnconstrainedReturn(): mixed RuntimeTypeChecker::checkSelfOut('FakeParent::runMethod', new stdClass()); - expect(SelfOutChecker::$noSelfOutContractCache['FakeParent::runMethod'])->toBeTrue(); + expect(SelfOutChecker::$noSelfOutContractCache)->not()->toHaveKey('FakeParent::runMethod'); }); test('handles vendor boundary bypasses across methods', function () { diff --git a/tests/TypeChecking/InheritanceAndAttributes/SiblingInheritanceCachePoisoningTest.php b/tests/TypeChecking/InheritanceAndAttributes/SiblingInheritanceCachePoisoningTest.php new file mode 100644 index 00000000..b99d26de --- /dev/null +++ b/tests/TypeChecking/InheritanceAndAttributes/SiblingInheritanceCachePoisoningTest.php @@ -0,0 +1,248 @@ + + */ + public function transition(): static; +} + +/** + * @extends SiblingCachePoisoningSelfOutBase<'idle'|'ready'> + */ +class SiblingCachePoisoningSelfOutStrictChild extends SiblingCachePoisoningSelfOutBase implements SiblingCachePoisoningStrictSelfOutInterface +{ +} + +class SiblingCachePoisoningStaticBase implements SiblingCachePoisoningMarkerInterface +{ + public static function make(mixed $val): mixed + { + return $val; + } +} + +class SiblingCachePoisoningStaticUnannotatedChild extends SiblingCachePoisoningStaticBase +{ +} + +interface SiblingCachePoisoningStrictStaticInterface +{ + /** + * @param positive-int $val + * + * @return positive-int + */ + public static function make(mixed $val): mixed; +} + +class SiblingCachePoisoningStaticStrictChild extends SiblingCachePoisoningStaticBase implements SiblingCachePoisoningStrictStaticInterface +{ +} + +class SiblingCachePoisoningTemplateBase implements SiblingCachePoisoningMarkerInterface +{ + /** + * @param int|string $val + */ + public static function echoValue(int|string $val): int|string + { + return $val; + } +} + +/** + * @template T + */ +class SiblingCachePoisoningTemplatedChild extends SiblingCachePoisoningTemplateBase +{ +} + +class SiblingCachePoisoningNonTemplatedChild extends SiblingCachePoisoningTemplateBase +{ +} + +describe('Sibling Inheritance Cache Poisoning Prevention', function () { + test('does not poison ParamChecker::$noParamContractCache on base method when unannotated sibling runs first', function () { + $unannotated = new SiblingCachePoisoningParamUnannotatedChild(); + expect($unannotated->process(-5))->toBe(-5); + + expect(ParamChecker::$noParamContractCache)->not()->toHaveKey(SiblingCachePoisoningParamBase::class . '::process'); + + $strict = new SiblingCachePoisoningParamStrictChild(); + + expect(fn () => $strict->process(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('does not poison ReturnChecker::$noReturnContractCache on base method when unannotated sibling runs first', function () { + $unannotated = new SiblingCachePoisoningReturnUnannotatedChild(); + expect($unannotated->fetch())->toBe(-99); + + expect(ReturnChecker::$noReturnContractCache)->not()->toHaveKey(SiblingCachePoisoningReturnBase::class . '::fetch'); + + $strict = new SiblingCachePoisoningReturnStrictChild(); + + expect(fn () => $strict->fetch()) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('does not poison ParamOutChecker::$noParamOutContractCache on base method when unannotated sibling runs first', function () { + $val1 = -10; + $unannotated = new SiblingCachePoisoningParamOutUnannotatedChild(); + $unannotated->mutate($val1); + expect($val1)->toBe(-10); + + expect(ParamOutChecker::$noParamOutContractCache)->not()->toHaveKey(SiblingCachePoisoningParamOutBase::class . '::mutate'); + + $val2 = -10; + $strict = new SiblingCachePoisoningParamOutStrictChild(); + + expect(function () use ($strict, &$val2) { + $strict->mutate($val2); + })->toThrow(TypeError::class, 'positive-int'); + }); + + test('does not poison SelfOutChecker::$noSelfOutContractCache on base method when unannotated sibling runs first', function () { + $unannotated = new SiblingCachePoisoningSelfOutUnannotatedChild(); + $unannotated->transition(); + + expect(SelfOutChecker::$noSelfOutContractCache)->not()->toHaveKey(SiblingCachePoisoningSelfOutBase::class . '::transition'); + + /** @var SiblingCachePoisoningSelfOutStrictChild<'idle'> $strict */ + $strict = new SiblingCachePoisoningSelfOutStrictChild(); + $strict->transition(); + + expect(TypePHP::getGenericType($strict, 'TState'))->toBe("'ready'"); + }); + + test('does not poison static inherited method caches across sibling subclasses', function () { + expect(SiblingCachePoisoningStaticUnannotatedChild::make(-5))->toBe(-5); + + expect(ParamChecker::$noParamContractCache)->not()->toHaveKey(SiblingCachePoisoningStaticBase::class . '::make') + ->and(ReturnChecker::$noReturnContractCache)->not()->toHaveKey(SiblingCachePoisoningStaticBase::class . '::make') + ; + + expect(fn () => SiblingCachePoisoningStaticStrictChild::make(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('does not poison RuntimeTypeChecker::$hasMethodTemplatesCache across sibling subclasses', function () { + expect(SiblingCachePoisoningTemplatedChild::echoValue('hello'))->toBe('hello'); + + expect(RuntimeTypeChecker::$hasMethodTemplatesCache)->not()->toHaveKey(SiblingCachePoisoningTemplateBase::class . '::echoValue'); + + expect(SiblingCachePoisoningNonTemplatedChild::echoValue(42))->toBe(42); + }); +}); From 4fc37a1e21ecc88423add8cb88528cf90531b2be Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 00:29:47 +0800 Subject: [PATCH 26/37] Enhance ConstantAndEnumEvaluator with enum support and add comprehensive soundness tests --- .../Evaluator/ConstantAndEnumEvaluator.php | 132 ++++++++- .../ConstantAndEnumEvaluatorTest.php | 13 +- .../ConstantAndEnumSoundnessTest.php | 278 ++++++++++++++++++ .../Elimination/StaticTypeEvaluatorTest.php | 16 +- 4 files changed, 415 insertions(+), 24 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php index 76079cf7..aec70c52 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -4,6 +4,7 @@ namespace TypePHP\Internal\Ast\Elimination\Evaluator; +use BackedEnum; use PhpParser\Node\Expr; use PhpParser\Node\Expr\BinaryOp\BitwiseOr; use PhpParser\Node\Expr\ClassConstFetch; @@ -16,6 +17,7 @@ use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use UnitEnum; /** * Statically evaluates whether constant fetches, enum cases, bitmasks, @@ -25,13 +27,25 @@ */ final class ConstantAndEnumEvaluator { + /** + * O(1) hash map of relative class keywords. + * + * @var array + */ + private const RELATIVE_CLASS_KEYWORDS = [ + 'self' => true, + 'static' => true, + 'parent' => true, + '$this' => true, + ]; + /** * Determines whether an expression satisfies constant or enum contracts. * * Flow of logic: - * 1. Evaluates ClassConstFetch nodes against exact constants, wildcards, and base enum types. + * 1. Evaluates ClassConstFetch nodes against exact constants, wildcards, and loaded enum cases. * 2. Evaluates bitwise OR expressions (A | B) against `int-mask-of` wildcards. - * 3. Evaluates enum backing property reads (Enum::Case->value) against `value-of`. + * 3. Evaluates backed enum property reads (Enum::Case->value) against `value-of`. */ public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool { @@ -60,9 +74,17 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty } $constName = $fetch->name->toString(); + if (strtolower($constName) === 'class') { + return false; + } + $targetClassName = $fetch->class->toString(); if ($typeNode instanceof ConstTypeNode && $typeNode->constExpr instanceof ConstFetchNode) { + if (! self::classesMatch($targetClassName, $typeNode->constExpr->className, $currentFile)) { + return false; + } + $docConstName = $typeNode->constExpr->name; if (str_contains($docConstName, '*')) { @@ -73,20 +95,31 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty } if ($typeNode instanceof IdentifierTypeNode) { - if ($currentFile !== '') { - $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($targetClassName, $currentFile, false); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false); + if (! self::classesMatch($targetClassName, $typeNode->name, $currentFile)) { + return false; + } - return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass; + $resolvedEnum = self::resolveClassForReflection($targetClassName, $currentFile); + if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false)) { + return false; } - return $targetClassName === $typeNode->name; + return self::isEnumCase($resolvedEnum, $constName); } if ($typeNode instanceof GenericTypeNode && strtolower((string) $typeNode->type) === 'int-mask-of') { $inner = $typeNode->genericTypes[0] ?? null; if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) { - return self::matchesWildcard($constName, $inner->constExpr->name); + if (! self::classesMatch($targetClassName, $inner->constExpr->className, $currentFile)) { + return false; + } + + $pattern = $inner->constExpr->name; + if (str_contains($pattern, '*')) { + return self::matchesWildcard($constName, $pattern); + } + + return $constName === $pattern; } } @@ -107,7 +140,7 @@ private static function satisfiesBitwiseOr(BitwiseOr $expr, TypeNode $typeNode, } /** - * Verifies whether an Enum::Case->value property access satisfies `value-of`. + * Verifies whether a BackedEnum::Case->value property access satisfies `value-of`. */ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode $typeNode, string $currentFile): bool { @@ -115,7 +148,7 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode return false; } - if (! ($fetch->var instanceof ClassConstFetch) || ! ($fetch->var->class instanceof Name)) { + if (! ($fetch->var instanceof ClassConstFetch) || ! ($fetch->var->class instanceof Name) || ! ($fetch->var->name instanceof Identifier)) { return false; } @@ -129,15 +162,86 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode } $enumClassName = $fetch->var->class->toString(); + $caseName = $fetch->var->name->toString(); + + if (strtolower($caseName) === 'class') { + return false; + } + + if (! self::classesMatch($enumClassName, $enumTarget->name, $currentFile)) { + return false; + } + + $resolvedEnum = self::resolveClassForReflection($enumClassName, $currentFile); + if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false) || ! is_subclass_of($resolvedEnum, BackedEnum::class)) { + return false; + } + + return self::isEnumCase($resolvedEnum, $caseName); + } + + /** + * Verifies whether two class references deterministically denote the same class/enum. + */ + private static function classesMatch(string $fetchClass, string $docClass, string $currentFile): bool + { + if ($docClass === '') { + return false; + } + + $lowerFetch = strtolower($fetchClass); + $lowerDoc = strtolower($docClass); + + if ($lowerFetch === 'self' && $lowerDoc === 'self') { + return true; + } + + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerFetch]) || isset(self::RELATIVE_CLASS_KEYWORDS[$lowerDoc])) { + return false; + } + + if ($fetchClass === $docClass) { + return true; + } if ($currentFile !== '') { - $resolvedEnumClass = SpecialTypeResolver::resolveFqcnForFile($enumClassName, $currentFile, false); - $resolvedTargetClass = SpecialTypeResolver::resolveFqcnForFile($enumTarget->name, $currentFile, false); + $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($fetchClass, $currentFile, false); + $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($docClass, $currentFile, false); - return $resolvedEnumClass !== '' && $resolvedEnumClass === $resolvedTargetClass; + return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass; } - return $enumClassName === $enumTarget->name; + return false; + } + + /** + * Resolves a class name without invoking autoloading. + */ + private static function resolveClassForReflection(string $rawClass, string $currentFile): string + { + if ($currentFile !== '') { + return SpecialTypeResolver::resolveFqcnForFile($rawClass, $currentFile, false); + } + + return ltrim($rawClass, '\\'); + } + + /** + * Verifies that a symbol is a declared enum case (excluding regular class constants on enums). + */ + private static function isEnumCase(string $enumClass, string $caseName): bool + { + if (! enum_exists($enumClass, false) || ! is_subclass_of($enumClass, UnitEnum::class)) { + return false; + } + + foreach ($enumClass::cases() as $case) { + if ($case->name === $caseName) { + return true; + } + } + + return false; } /** diff --git a/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php b/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php index 9891c308..3a56c6b7 100644 --- a/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php +++ b/tests/Internal/Ast/Elimination/ConstantAndEnumEvaluatorTest.php @@ -14,6 +14,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; +use TypePHP\Tests\Fixtures\Types\StatusEnum; describe('ConstantAndEnumEvaluator Unit Tests', function () { describe('Class Constants & Wildcards', function () { @@ -55,8 +56,10 @@ describe('Enums and Backing Values', function () { test('evaluates enum case fetch against enum base type', function () { - $fetch = new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')); - $type = new IdentifierTypeNode('StatusEnum'); + enum_exists(StatusEnum::class); + + $fetch = new ClassConstFetch(new Name(StatusEnum::class), new Identifier('Active')); + $type = new IdentifierTypeNode(StatusEnum::class); expect(StaticTypeEvaluator::satisfies($fetch, $type))->toBeTrue(); }); @@ -76,13 +79,15 @@ }); test('evaluates enum backing property access against value-of', function () { + enum_exists(StatusEnum::class); + $propFetch = new PropertyFetch( - new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')), + new ClassConstFetch(new Name(StatusEnum::class), new Identifier('Active')), new Identifier('value') ); $valueOf = new GenericTypeNode(new IdentifierTypeNode('value-of'), [ - new IdentifierTypeNode('StatusEnum'), + new IdentifierTypeNode(StatusEnum::class), ]); expect(StaticTypeEvaluator::satisfies($propFetch, $valueOf))->toBeTrue(); diff --git a/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php b/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php new file mode 100644 index 00000000..969e22cf --- /dev/null +++ b/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php @@ -0,0 +1,278 @@ +toBeFalse() + ->and(StaticTypeEvaluator::satisfies($fetch, $wildcard))->toBeFalse() + ; + }); + + test('does not eliminate ClassConstFetch against global constant without class name', function () { + $fetch = new ClassConstFetch(new Name('Order'), new Identifier('PHP_VERSION_ID')); + $globalConst = new ConstTypeNode(new ConstFetchNode('', 'PHP_VERSION_ID')); + + expect(StaticTypeEvaluator::satisfies($fetch, $globalConst))->toBeFalse(); + }); + + test('retains checkReturn at AST transform time and throws TypeError at runtime on cross-class constant return', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + + $tempDir = sys_get_temp_dir() . '/typephp_const_soundness_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/cross_class_const.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, 'must be a valid constant matching') + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('2. int-mask-of Class Isolation & Non-Wildcard Matching', function () { + test('does not eliminate int-mask-of when bitwise OR mixes a constant from a different class', function () { + $flagA = new ClassConstFetch(new Name('FlagsA'), new Identifier('FLAG_READ')); + $flagB = new ClassConstFetch(new Name('FlagsB'), new Identifier('FLAG_WRITE')); + $orExpr = new BitwiseOr($flagA, $flagB); + + $maskOfA = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode('FlagsA', 'FLAG_*')), + ]); + + expect(StaticTypeEvaluator::satisfies($flagB, $maskOfA))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($orExpr, $maskOfA))->toBeFalse() + ; + }); + + test('does not match prefix substring when int-mask-of pattern has no asterisk wildcard', function () { + $fetch = new ClassConstFetch(new Name('self'), new Identifier('FLAG_READ_EXTRA')); + $nonWildcardMask = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode('self', 'FLAG_READ')), + ]); + + expect(StaticTypeEvaluator::satisfies($fetch, $nonWildcardMask))->toBeFalse(); + }); + }); + + describe('3. ::class Pseudo-Constant vs Class::* Wildcards & Object Types', function () { + test('does not satisfy Class::* wildcard when fetching ::class pseudo-constant', function () { + $classFetch = new ClassConstFetch(new Name(StatusEnum::class), new Identifier('class')); + $wildcard = new ConstTypeNode(new ConstFetchNode(StatusEnum::class, '*')); + + expect(StaticTypeEvaluator::satisfies($classFetch, $wildcard, __FILE__))->toBeFalse(); + }); + + test('retains checkReturn and throws TypeError when returning Enum::class for @return Enum::*', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + + $tempDir = sys_get_temp_dir() . '/typephp_enum_class_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/enum_class_wildcard.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, 'must be a valid constant matching') + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('4. ClassConstFetch vs IdentifierTypeNode (Non-Enum Constants, ::class, Enum Scalar Consts)', function () { + test('does not eliminate Class::CONST or Class::class against @return Class', function () { + $constFetch = new ClassConstFetch(new Name(SoundnessOrderConst::class), new Identifier('STATUS_PAID')); + $classFetch = new ClassConstFetch(new Name(SoundnessOrderConst::class), new Identifier('class')); + $targetType = new IdentifierTypeNode(SoundnessOrderConst::class); + + expect(StaticTypeEvaluator::satisfies($constFetch, $targetType, __FILE__))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($classFetch, $targetType, __FILE__))->toBeFalse() + ; + }); + + test('does not eliminate regular scalar const declared inside a BackedEnum against @return Enum', function () { + $scalarConstOnEnum = new ClassConstFetch(new Name(SoundnessEnumWithConst::class), new Identifier('NON_CASE_LABEL')); + $targetType = new IdentifierTypeNode(SoundnessEnumWithConst::class); + + expect(StaticTypeEvaluator::satisfies($scalarConstOnEnum, $targetType, __FILE__))->toBeFalse(); + }); + + test('still eliminates genuine loaded Enum case against @return Enum', function () { + $enumCaseFetch = new ClassConstFetch(new Name(StatusEnum::class), new Identifier('Active')); + $targetType = new IdentifierTypeNode(StatusEnum::class); + + expect(StaticTypeEvaluator::satisfies($enumCaseFetch, $targetType, __FILE__))->toBeTrue(); + }); + + test('throws TypeError at runtime when returning regular class constant for @return ClassName', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + + $tempDir = sys_get_temp_dir() . '/typephp_const_as_obj_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/const_as_obj.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, SoundnessOrderConst::class) + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('5. value-of Backing Property Soundness', function () { + test('does not eliminate UnitEnum::Case->value or non-enum Class::CONST->value against value-of', function () { + $unitEnumValue = new PropertyFetch( + new ClassConstFetch(new Name(Suit::class), new Identifier('Hearts')), + new Identifier('value') + ); + $unitTarget = new GenericTypeNode(new IdentifierTypeNode('value-of'), [new IdentifierTypeNode(Suit::class)]); + + $classConstValue = new PropertyFetch( + new ClassConstFetch(new Name(SoundnessOrderConst::class), new Identifier('STATUS_PAID')), + new Identifier('value') + ); + $classTarget = new GenericTypeNode(new IdentifierTypeNode('value-of'), [new IdentifierTypeNode(SoundnessOrderConst::class)]); + + expect(StaticTypeEvaluator::satisfies($unitEnumValue, $unitTarget, __FILE__))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($classConstValue, $classTarget, __FILE__))->toBeFalse() + ; + }); + + test('still eliminates genuine BackedEnum::Case->value against value-of', function () { + $backedEnumValue = new PropertyFetch( + new ClassConstFetch(new Name(StatusEnum::class), new Identifier('Active')), + new Identifier('value') + ); + $target = new GenericTypeNode(new IdentifierTypeNode('value-of'), [new IdentifierTypeNode(StatusEnum::class)]); + + expect(StaticTypeEvaluator::satisfies($backedEnumValue, $target, __FILE__))->toBeTrue(); + }); + }); +}); diff --git a/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php b/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php index d148e32f..198646d8 100644 --- a/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php +++ b/tests/Internal/Ast/Elimination/StaticTypeEvaluatorTest.php @@ -36,6 +36,7 @@ use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; +use TypePHP\Tests\Fixtures\Types\StatusEnum; describe('StaticTypeEvaluator Comprehensive Unit Tests', function () { describe('Safety Invariants', function () { @@ -230,11 +231,13 @@ }); test('evaluates enum case fetches against enum base type and case wildcards', function () { - $enumFetch = new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')); + enum_exists(StatusEnum::class); - expect(StaticTypeEvaluator::satisfies($enumFetch, new IdentifierTypeNode('StatusEnum')))->toBeTrue() - ->and(StaticTypeEvaluator::satisfies($enumFetch, new ConstTypeNode(new ConstFetchNode('StatusEnum', '*'))))->toBeTrue() - ->and(StaticTypeEvaluator::satisfies($enumFetch, new ConstTypeNode(new ConstFetchNode('StatusEnum', 'ACT*'))))->toBeTrue() + $enumFetch = new ClassConstFetch(new Name(StatusEnum::class), new Identifier('Active')); + + expect(StaticTypeEvaluator::satisfies($enumFetch, new IdentifierTypeNode(StatusEnum::class)))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($enumFetch, new ConstTypeNode(new ConstFetchNode(StatusEnum::class, '*'))))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($enumFetch, new ConstTypeNode(new ConstFetchNode(StatusEnum::class, 'ACT*'))))->toBeTrue() ; }); @@ -254,11 +257,12 @@ }); test('evaluates enum backing property access against value-of', function () { + enum_exists(StatusEnum::class); $propFetch = new PropertyFetch( - new ClassConstFetch(new Name('StatusEnum'), new Identifier('Active')), + new ClassConstFetch(new Name(StatusEnum::class), new Identifier('Active')), new Identifier('value') ); - $valueOf = new GenericTypeNode(new IdentifierTypeNode('value-of'), [new IdentifierTypeNode('StatusEnum')]); + $valueOf = new GenericTypeNode(new IdentifierTypeNode('value-of'), [new IdentifierTypeNode(StatusEnum::class)]); expect(StaticTypeEvaluator::satisfies($propFetch, $valueOf))->toBeTrue(); }); From 8f33cbac4be9285c128c2564dbfa9c8d6a208182 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 00:35:21 +0800 Subject: [PATCH 27/37] Refactor ArrayLiteralEvaluator to improve non-empty array and list checks, and add hasConcreteItem method for better item validation. Introduce ArrayLiteralSpreadSoundnessTest for comprehensive spread expression testing. --- .../Evaluator/ArrayLiteralEvaluator.php | 26 +- .../ArrayLiteralSpreadSoundnessTest.php | 311 ++++++++++++++++++ 2 files changed, 331 insertions(+), 6 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index 0062d0ce..d41c07ee 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -128,8 +128,8 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy return match ($name) { 'array', 'iterable', 'mixed' => true, 'list' => self::isSequentialList($arrayExpr), - 'non-empty-array' => \count($arrayExpr->items) > 0, - 'non-empty-list' => \count($arrayExpr->items) > 0 && self::isSequentialList($arrayExpr), + 'non-empty-array' => self::hasConcreteItem($arrayExpr), + 'non-empty-list' => self::hasConcreteItem($arrayExpr) && self::isSequentialList($arrayExpr), default => false, }; } @@ -184,7 +184,7 @@ private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, boo $expectedIdx = 0; foreach ($arrayExpr->items as $item) { - if ($item === null) { + if ($item === null || $item->unpack) { return false; } @@ -216,7 +216,7 @@ private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyT $currentIdx = 0; foreach ($arrayExpr->items as $item) { - if ($item === null) { + if ($item === null || $item->unpack) { return false; } @@ -276,7 +276,7 @@ private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $s $actualItems = []; $currentIdx = 0; foreach ($arrayExpr->items as $item) { - if ($item === null) { + if ($item === null || $item->unpack) { return false; } @@ -342,7 +342,7 @@ private static function isSequentialList(Array_ $arrayExpr): bool { $expectedIdx = 0; foreach ($arrayExpr->items as $item) { - if ($item === null) { + if ($item === null || $item->unpack) { return false; } @@ -356,4 +356,18 @@ private static function isSequentialList(Array_ $arrayExpr): bool return true; } + + /** + * Checks whether an array expression contains at least one non-unpacked concrete item. + */ + private static function hasConcreteItem(Array_ $arrayExpr): bool + { + foreach ($arrayExpr->items as $item) { + if ($item !== null && ! $item->unpack) { + return true; + } + } + + return false; + } } diff --git a/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php b/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php new file mode 100644 index 00000000..0fccfdcf --- /dev/null +++ b/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php @@ -0,0 +1,311 @@ +toBeFalse() + ->and(StaticTypeEvaluator::satisfies($spreadExpr, new IdentifierTypeNode('non-empty-array')))->toBeFalse() + ->and(StaticTypeEvaluator::satisfies($spreadExpr, new IdentifierTypeNode('non-empty-list')))->toBeFalse() + ; + }); + + test('does not eliminate non-empty-list when spreading an empty array [...[]]', function () { + $spreadEmpty = new Array_([ + new ArrayItem(new Array_([]), null, false, [], true), + ]); + + $type = new GenericTypeNode(new IdentifierTypeNode('non-empty-list'), [ + new IdentifierTypeNode('array'), + ]); + + expect(StaticTypeEvaluator::satisfies($spreadEmpty, $type))->toBeFalse(); + }); + + test('retains checkReturn and throws TypeError at runtime when spreading empty or associative array into non-empty-array / list', function () { + $source = <<<'PHP' + spreadIntoNonEmptyArray([]), +]; +PHP; + + $transformed = StreamWrapper::transformSource($source, __FILE__); + expect(substr_count($transformed, 'RuntimeTypeChecker::checkReturn'))->toBe(2); + + $tempDir = sys_get_temp_dir() . '/typephp_spread_ident_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/spread_ident.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, 'non-empty-array') + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + + test('throws TypeError at runtime when spreading associative array into bare list return', function () { + $source = <<<'PHP' + 1]); +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_spread_list_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/spread_list.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, 'must be of type list') + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('2. Generic Lists & Typed Arrays (list, T[], array)', function () { + test('does not eliminate list when spreading associative array literal [...[\'a\' => 1]]', function () { + $spreadAssoc = new Array_([ + new ArrayItem( + new Array_([new ArrayItem(new LNumber(1), new String_('a'))]), + null, + false, + [], + true + ), + ]); + + $listType = new GenericTypeNode(new IdentifierTypeNode('list'), [ + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('array')]), + ]); + + expect(StaticTypeEvaluator::satisfies($spreadAssoc, $listType))->toBeFalse(); + }); + + test('does not eliminate array when spreading associative array literal with string keys', function () { + $spreadAssoc = new Array_([ + new ArrayItem( + new Array_([new ArrayItem(new LNumber(1), new String_('a'))]), + null, + false, + [], + true + ), + ]); + + $mapType = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('int'), + new UnionTypeNode([new IdentifierTypeNode('int'), new IdentifierTypeNode('array')]), + ]); + + expect(StaticTypeEvaluator::satisfies($spreadAssoc, $mapType))->toBeFalse(); + }); + + test('does not eliminate ArrayTypeNode (array[]) when spreading non-matching elements', function () { + $spreadBad = new Array_([ + new ArrayItem( + new Array_([new ArrayItem(new String_('not_an_int'), new String_('k'))]), + null, + false, + [], + true + ), + ]); + + $arrayType = new ArrayTypeNode(new IdentifierTypeNode('array')); + + expect(StaticTypeEvaluator::satisfies($spreadBad, $arrayType))->toBeFalse(); + }); + + test('retains checkReturn and throws TypeError at runtime on spread into list and array', function () { + $source = <<<'PHP' + + */ +function spreadAssocIntoTypedList(): array +{ + return [...['a' => 1]]; +} + +return spreadAssocIntoTypedList(); +PHP; + + $transformed = StreamWrapper::transformSource($source, __FILE__); + expect($transformed)->toContain('RuntimeTypeChecker::checkReturn'); + + $tempDir = sys_get_temp_dir() . '/typephp_spread_typed_list_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/spread_typed_list.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, 'must be a list') + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('3. Array Shapes (ArrayShapeNode)', function () { + test('does not eliminate array{0: array} when spreading [...[\'bad_key\' => [\'a\' => 1]]]', function () { + $spreadShape = new Array_([ + new ArrayItem( + new Array_([ + new ArrayItem( + new Array_([new ArrayItem(new LNumber(1), new String_('a'))]), + new String_('bad_key') + ), + ]), + null, + false, + [], + true + ), + ]); + + $shapeType = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode( + new ConstExprIntegerNode('0'), + false, + new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('int'), + ]) + ), + ]); + + expect(StaticTypeEvaluator::satisfies($spreadShape, $shapeType))->toBeFalse(); + }); + + test('retains checkReturn and throws TypeError at runtime when spread violates array shape', function () { + $source = <<<'PHP' + 'not_an_int']]; +} + +return spreadIntoShape(); +PHP; + + $transformed = StreamWrapper::transformSource($source, __FILE__); + expect($transformed)->toContain('RuntimeTypeChecker::checkReturn'); + + $tempDir = sys_get_temp_dir() . '/typephp_spread_shape_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/spread_shape.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, "['id'] must be of type int") + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('4. Safe Positive Control: Mixed Concrete + Spread on non-empty-array', function () { + test('still allows non-empty-array when at least one non-unpacked concrete item is present', function () { + $mixed = new Array_([ + new ArrayItem(new LNumber(1)), + new ArrayItem(new Variable('dynamic'), null, false, [], true), + ]); + + expect(StaticTypeEvaluator::satisfies($mixed, new IdentifierTypeNode('non-empty-array')))->toBeTrue() + ->and(StaticTypeEvaluator::satisfies($mixed, new IdentifierTypeNode('non-empty-list')))->toBeFalse() + ; + }); + }); +}); From fcd31f083574940722c6b09c8454f763298dd01c Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 00:42:16 +0800 Subject: [PATCH 28/37] Refactor DocblockNormalizer to quote unquoted class constant keys in array/object shapes for phpdoc-parser compatibility. Add tests for conditional class constants and enums in various scenarios. --- src/Internal/Docblock/DocblockNormalizer.php | 22 ++- .../ConditionalWithClassConstantTest.php | 152 ++++++++++++++++++ 2 files changed, 170 insertions(+), 4 deletions(-) create mode 100644 tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php diff --git a/src/Internal/Docblock/DocblockNormalizer.php b/src/Internal/Docblock/DocblockNormalizer.php index 76a30f3e..6d34c126 100644 --- a/src/Internal/Docblock/DocblockNormalizer.php +++ b/src/Internal/Docblock/DocblockNormalizer.php @@ -82,10 +82,6 @@ static function (array $matches): string { } } - if (str_contains($doc, '::') && str_contains($doc, ':')) { - $doc = preg_replace('/(\\\\?[a-zA-Z_\x80-\xff][\\\\a-zA-Z0-9_\x80-\xff]*::[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)\s*(\??:)/', '"$1"$2', $doc) ?? $doc; - } - if (str_contains($doc, 'int-mask-of') && str_contains($doc, '*')) { $doc = preg_replace('/int-mask-of<\s*([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*\*)\s*>/', 'int-mask-of<"$1">', $doc) ?? $doc; } @@ -220,6 +216,7 @@ private static function normalizeShapes(string $doc): string function (array $matches): string { $className = $matches[1]; $shapeBody = self::normalizeShapes($matches[2]); + $shapeBody = self::quoteShapeConstantKeys($shapeBody); $lower = strtolower(ltrim($className, '\\')); if (\in_array($lower, self::BUILTIN_SHAPE_KEYWORDS, strict: true)) { @@ -231,4 +228,21 @@ function (array $matches): string { $doc ) ?? $doc; } + + /** + * Quotes unquoted Class::CONST keys inside array/object shape bodies for phpdoc-parser compatibility, + * leaving class constants inside conditional type expressions untouched. + */ + private static function quoteShapeConstantKeys(string $shapeBody): string + { + if (! str_contains($shapeBody, '::') || ! str_contains($shapeBody, ':')) { + return $shapeBody; + } + + return preg_replace( + '/(^|,)((?:\s|\*(?!\/))*)(\\\\?[a-zA-Z_\x80-\xff][\\\\a-zA-Z0-9_\x80-\xff]*::[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)\s*(\??:)/', + '$1$2"$3"$4', + $shapeBody + ) ?? $shapeBody; + } } diff --git a/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php b/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php new file mode 100644 index 00000000..d0faf669 --- /dev/null +++ b/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php @@ -0,0 +1,152 @@ + $roleVal, + ConditionalConstRole::KEY_LABEL => $label, + ]; +} + +describe('DocblockNormalizer Class Constants in Conditional Types (Red Phase)', function () { + describe('1. DocblockNormalizer Unit Assertions', function () { + test('does not quote class constant in conditional true branch', function () { + $doc = '/** @return ($isAdmin is true ? Role::ADMIN : Role::USER) */'; + + expect(DocblockNormalizer::normalize($doc))->toBe($doc); + }); + + test('does not quote self:: constant in template conditional true branch', function () { + $doc = '/** @return (T is int ? self::INT_CODE : self::STR_CODE) */'; + + expect(DocblockNormalizer::normalize($doc))->toBe($doc); + }); + + test('does not quote class constant in conditional nested inside an array shape value', function () { + $doc = '/** @return array{role: ($isAdmin is true ? Role::ADMIN : Role::USER)} */'; + + expect(DocblockNormalizer::normalize($doc))->toBe($doc); + }); + + test('does not quote conditional class constant when another tag in the same docblock contains braces', function () { + $doc = "/**\n * @param array{id: int} \$cfg\n * @return (\$isAdmin is true ? Role::ADMIN : Role::USER)\n */"; + + expect(DocblockNormalizer::normalize($doc))->toBe($doc); + }); + + test('still quotes genuine class constant keys inside single-line and multi-line array shapes', function () { + $single = '/** @param array{self::KEY_ID: int, App\Constants::ROLE?: string} $payload */'; + expect(DocblockNormalizer::normalize($single)) + ->toBe('/** @param array{"self::KEY_ID": int, "App\Constants::ROLE"?: string} $payload */') + ; + + $multi = "/**\n * @param array{\n * self::KEY_ID: int,\n * App\\Constants::ROLE: string\n * } \$payload\n */"; + $expectedMulti = "/**\n * @param array{\n * \"self::KEY_ID\": int,\n * \"App\\Constants::ROLE\": string\n * } \$payload\n */"; + expect(DocblockNormalizer::normalize($multi))->toBe($expectedMulti); + }); + }); + + describe('2. End-to-End Runtime Conditional Evaluation with Class Constants & Enums', function () { + test('accepts actual constant value and rejects stringified constant name in parameter conditional true branch', function () { + expect(resolveConditionalRoleConstant(true, ConditionalConstRole::ADMIN))->toBe(1); + expect(resolveConditionalRoleConstant(false, ConditionalConstRole::USER))->toBe(2); + + expect(fn () => resolveConditionalRoleConstant(true, 'ConditionalConstRole::ADMIN')) + ->toThrow(TypeError::class) + ; + expect(fn () => resolveConditionalRoleConstant(true, ConditionalConstRole::USER)) + ->toThrow(TypeError::class) + ; + }); + + test('resolves self::CONST in class method conditional true branch', function () { + $service = new ConditionalSelfConstService(); + + expect($service->getStatusCode(true, 200))->toBe(200); + expect($service->getStatusCode(false, 500))->toBe(500); + + expect(fn () => $service->getStatusCode(true, 500)) + ->toThrow(TypeError::class) + ; + }); + + test('accepts Enum::Case in conditional true branch', function () { + expect(resolveConditionalEnumCase(true, StatusEnum::Active))->toBe(StatusEnum::Active); + expect(resolveConditionalEnumCase(false, StatusEnum::Inactive))->toBe(StatusEnum::Inactive); + + expect(fn () => resolveConditionalEnumCase(true, StatusEnum::Inactive)) + ->toThrow(TypeError::class) + ; + }); + + test('quotes shape constant key while leaving conditional constant value intact inside the same shape', function () { + $valid = resolveShapeWithKeyAndConditionalConst(true, ConditionalConstRole::ADMIN, 'Admin User'); + expect($valid)->toBe([ + 'role' => 1, + 'label' => 'Admin User', + ]); + + expect(fn () => resolveShapeWithKeyAndConditionalConst(true, ConditionalConstRole::USER, 'Admin User')) + ->toThrow(TypeError::class, "['role']") + ; + }); + }); +}); From be2cf99f2467afa70fd817b049402d7a997ce969 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 11:39:06 +0800 Subject: [PATCH 29/37] Enhance ContractVisitor with side-effect detection and hoisting for impure targets. Add tests for foreach and by-reference array item write contexts, ensuring proper handling of static properties and contract violations. --- src/Internal/Ast/ContractVisitor.php | 190 ++++++++- tests/Internal/Ast/ContractVisitorTest.php | 3 +- ...tVisitorWriteContextAndDuplicationTest.php | 382 ++++++++++++++++++ 3 files changed, 565 insertions(+), 10 deletions(-) create mode 100644 tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 2a75f216..72bf6b56 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -5,6 +5,7 @@ namespace TypePHP\Internal\Ast; use PhpParser\Node; +use PhpParser\NodeFinder; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; @@ -89,6 +90,8 @@ final class ContractVisitor extends NodeVisitorAbstract */ private array $localClassTemplates = []; + private int $hoistTempCounter = 0; + public function __construct(private string $currentFile = '') { $this->scopeManager = new ScopeManager(); @@ -97,9 +100,9 @@ public function __construct(private string $currentFile = '') /** * Traverses and transforms AST nodes during entry. * - * @return array|null + * @return Node|array|null */ - public function enterNode(Node $node): ?array + public function enterNode(Node $node): Node|array|null { $this->trackDeclarationEntry($node); @@ -141,6 +144,8 @@ public function enterNode(Node $node): ?array $this->scopeManager->unregisterVarType($v->name); } } + } elseif ($node instanceof Node\ArrayItem && $node->byRef) { + $this->markWriteContext($node->value); } elseif ($node instanceof Node\Expr\Isset_) { foreach ($node->vars as $v) { $this->markWriteContext($v); @@ -192,13 +197,22 @@ public function enterNode(Node $node): ?array $this->scopeManager->extractVarDocblock($doc->getText(), $node->valueVar); } + if ($node->keyVar !== null) { + $this->markWriteContext($node->keyVar); + } + $this->markWriteContext($node->valueVar); + $this->handleForeachTypePropagation($node); return null; } if ($node instanceof Node\Expr\Assign) { - $this->handleAssign($node); + if ($node->getAttribute('typephp_wrapped') === true) { + return null; + } + + return $this->handleAssign($node); } elseif ($node instanceof Node\Expr\AssignRef) { $this->handleAssignRef($node); } @@ -1171,7 +1185,7 @@ private function propagateShapeTypesToDestructuring(Node\Expr\List_|Node\Expr\Ar } } - private function handleAssign(Node\Expr\Assign $node): void + private function handleAssign(Node\Expr\Assign $node): ?Node { if ($node->var instanceof Node\Expr\Variable && \is_string($node->var->name)) { $varName = $node->var->name; @@ -1220,7 +1234,7 @@ private function handleAssign(Node\Expr\Assign $node): void $node->expr = $this->wrapVariableCheck($expr, $typeString, $varName, $node->var->getStartLine()); - return; + return null; } try { @@ -1229,21 +1243,39 @@ private function handleAssign(Node\Expr\Assign $node): void $parsedType = $typeParser->parse($tokens); if (StaticTypeEvaluator::satisfies($expr, $parsedType, $this->currentFile)) { - return; + return null; } } catch (\Throwable) { } $node->expr = $this->wrapVariableCheck($expr, $typeString, $varName, $node->var->getStartLine()); - return; + return null; + } + } + + if ($this->targetHasSideEffects($node->var)) { + $preAssignments = []; + $cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments); + $wrapped = $this->wrapTargetMutation($cleanTarget, $node->expr, $node->var->getStartLine()); + + if ($wrapped !== null) { + $this->markWriteContext($cleanTarget); + $newAssign = new Node\Expr\Assign($cleanTarget, $wrapped); + $newAssign->setAttribute('typephp_wrapped', true); + + return $this->wrapWithPreEvaluations($preAssignments, $newAssign); } + + return null; } $wrapped = $this->wrapTargetMutation($node->var, $node->expr, $node->var->getStartLine()); if ($wrapped !== null) { $node->expr = $wrapped; } + + return null; } private function handleAssignRef(Node\Expr\AssignRef $node): void @@ -1338,23 +1370,54 @@ private function handleForeachTypePropagation(Node\Stmt\Foreach_ $node): void } } - private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr\Assign + private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr { $binaryOpClass = self::ASSIGN_OP_MAP[$node::class] ?? null; if ($binaryOpClass === null) { return null; } + if ($this->targetHasSideEffects($node->var)) { + $preAssignments = []; + $cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments); + $binaryExpr = new $binaryOpClass(clone $cleanTarget, $node->expr); + $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine()); + + if ($wrapped === null) { + return null; + } + + $this->markWriteContext($cleanTarget); + + return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped)); + } + $binaryExpr = new $binaryOpClass($node->var, $node->expr); $wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine()); return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null; } - private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr\Assign + private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr { $isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc; $binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class; + + if ($this->targetHasSideEffects($node->var)) { + $preAssignments = []; + $cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments); + $binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1)); + $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine()); + + if ($wrapped === null) { + return null; + } + + $this->markWriteContext($cleanTarget); + + return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped)); + } + $binaryExpr = new $binaryClass($node->var, new Node\Scalar\LNumber(1)); $wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine()); @@ -1362,6 +1425,115 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null; } + private function targetHasSideEffects(Node $node): bool + { + return (new NodeFinder())->findFirst($node, static function (Node $n): bool { + return $n instanceof Node\Expr\CallLike + || $n instanceof Node\Expr\PreInc + || $n instanceof Node\Expr\PostInc + || $n instanceof Node\Expr\PreDec + || $n instanceof Node\Expr\PostDec + || $n instanceof Node\Expr\Assign + || $n instanceof Node\Expr\AssignOp + || $n instanceof Node\Expr\AssignRef + || $n instanceof Node\Expr\Yield_ + || $n instanceof Node\Expr\YieldFrom + || $n instanceof Node\Expr\Throw_ + || $n instanceof Node\Expr\Eval_ + || $n instanceof Node\Expr\Include_ + || $n instanceof Node\Expr\ShellExec + || $n instanceof Node\Expr\Exit_; + }) !== null; + } + + /** + * @param list $preAssignments + */ + private function hoistImpureTarget(Node\Expr $target, array &$preAssignments): Node\Expr + { + if ($target instanceof Node\Expr\PropertyFetch) { + $newVar = $this->targetHasSideEffects($target->var) + ? $this->hoistImpureTarget($target->var, $preAssignments) + : $target->var; + + $newName = $target->name; + if ($newName instanceof Node\Expr && $this->targetHasSideEffects($newName)) { + $newName = $this->createHoistedTemp($newName, $preAssignments); + } + + return new Node\Expr\PropertyFetch($newVar, $newName); + } + + if ($target instanceof Node\Expr\StaticPropertyFetch) { + $newClass = $target->class; + if ($newClass instanceof Node\Expr && $this->targetHasSideEffects($newClass)) { + $newClass = $this->hoistImpureTarget($newClass, $preAssignments); + } + + $newName = $target->name; + if ($newName instanceof Node\Expr && $this->targetHasSideEffects($newName)) { + $newName = $this->createHoistedTemp($newName, $preAssignments); + } + + return new Node\Expr\StaticPropertyFetch($newClass, $newName); + } + + if ($target instanceof Node\Expr\ArrayDimFetch) { + $newVar = $this->targetHasSideEffects($target->var) + ? $this->hoistImpureTarget($target->var, $preAssignments) + : $target->var; + + $newDim = $target->dim; + if ($newDim !== null && $this->targetHasSideEffects($newDim)) { + $newDim = $this->createHoistedTemp($newDim, $preAssignments); + } + + return new Node\Expr\ArrayDimFetch($newVar, $newDim); + } + + if ($this->targetHasSideEffects($target)) { + return $this->createHoistedTemp($target, $preAssignments); + } + + return $target; + } + + /** + * @param list $preAssignments + */ + private function createHoistedTemp(Node\Expr $expr, array &$preAssignments): Node\Expr\Variable + { + $tempVar = new Node\Expr\Variable('__typephpTgt' . $this->hoistTempCounter++); + $preAssignments[] = new Node\Expr\Assign($tempVar, $expr); + + return new Node\Expr\Variable($tempVar->name); + } + + /** + * @param list $preAssignments + */ + private function wrapWithPreEvaluations(array $preAssignments, Node\Expr $expr): Node\Expr + { + if ($preAssignments === []) { + return $expr; + } + + $falseNode = static fn (): Node\Expr\ConstFetch => new Node\Expr\ConstFetch(new Node\Name('false')); + + $cond = new Node\Expr\Ternary($preAssignments[0], $falseNode(), $falseNode()); + $count = \count($preAssignments); + for ($i = 1; $i < $count; $i++) { + $step = new Node\Expr\Ternary($preAssignments[$i], $falseNode(), $falseNode()); + $cond = new Node\Expr\BinaryOp\BooleanOr($cond, $step); + } + + return new Node\Expr\Ternary( + $cond, + new Node\Expr\ConstFetch(new Node\Name('null')), + $expr + ); + } + /** * Unifies wrapping of mutations across assignments, compound assignments, and increments/decrements. */ diff --git a/tests/Internal/Ast/ContractVisitorTest.php b/tests/Internal/Ast/ContractVisitorTest.php index 13ad5d61..b0927ed9 100644 --- a/tests/Internal/Ast/ContractVisitorTest.php +++ b/tests/Internal/Ast/ContractVisitorTest.php @@ -397,7 +397,8 @@ public function enumMethod() { $transformed = $this->printer->prettyPrint($newStmts); expect($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$className::\$staticCount + 5, \$className, 'staticCount'") - ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$getObj()::\$staticCount + 1, \$getObj(), 'staticCount'") + ->and($transformed)->toContain('$__typephpTgt0 = $getObj()') + ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$__typephpTgt0::\$staticCount + 1, \$__typephpTgt0, 'staticCount'") ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$className::\$staticCount2 - 1, \$className, 'staticCount2'") ; }); diff --git a/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php b/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php new file mode 100644 index 00000000..ce9b05d0 --- /dev/null +++ b/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php @@ -0,0 +1,382 @@ + + */ + public static array $map = []; + + public static int $pairSecond = 0; + + public static function run(): void + { + foreach ([10, 20] as self::$current) { + } + + foreach (['a' => 1, 'b' => 2] as self::$lastKey => self::$lastVal) { + } + + foreach ([[1, 30], [2, 40]] as [$first, self::$pairSecond]) { + } + + foreach ([50, 60] as self::$map['latest']) { + } + } +} + +ForeachStaticTargetFixture::run(); + +return [ + 'current' => ForeachStaticTargetFixture::$current, + 'lastKey' => ForeachStaticTargetFixture::$lastKey, + 'lastVal' => ForeachStaticTargetFixture::$lastVal, + 'pairSecond' => ForeachStaticTargetFixture::$pairSecond, + 'latest' => ForeachStaticTargetFixture::$map['latest'], +]; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'foreach_static_target.php'); + + expect($transformed)->not()->toContain("checkStaticProperty(self::class, 'current'") + ->and($transformed)->not()->toContain("checkStaticProperty(self::class, 'lastKey'") + ->and($transformed)->not()->toContain("checkStaticProperty(self::class, 'lastVal'") + ->and($transformed)->not()->toContain("checkStaticProperty(self::class, 'pairSecond'") + ->and($transformed)->not()->toContain("checkStaticProperty(self::class, 'map'") + ; + + $tempDir = sys_get_temp_dir() . '/typephp_foreach_static_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/run_foreach_static.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + $result = require $scriptPath; + + expect($result)->toBe([ + 'current' => 20, + 'lastKey' => 'b', + 'lastVal' => 2, + 'pairSecond' => 40, + 'latest' => 60, + ]); + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + + test('does not wrap by-reference ArrayItem static property (&Class::$prop) in checkStaticProperty', function () { + $source = <<<'PHP' +toContain('[&self::$counter]') + ->and($transformed)->not()->toContain('&\TypePHP\Internal\RuntimeTypeChecker::checkStaticProperty') + ; + + $tempDir = sys_get_temp_dir() . '/typephp_byref_static_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/run_byref_static.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + $result = require $scriptPath; + + expect($result)->toBe(99); + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); + + describe('2. Side-Effecting Target Single-Evaluation (Assign, AssignOp, IncDec)', function () { + test('evaluates impure property receiver once on direct assignment, compound assignment, and increment', function () { + $source = <<<'PHP' + + */ + public array $items = [1, 2, 3]; +} + +class TargetBoxFactory +{ + public int $calls = 0; + + public TargetBox $box; + + public function __construct() + { + $this->box = new TargetBox(); + } + + public function next(): TargetBox + { + $this->calls++; + + return $this->box; + } +} + +$factory = new TargetBoxFactory(); + +$factory->next()->score = 20; +$callsAfterAssign = $factory->calls; + +$factory->next()->score += 10; +$callsAfterAssignOp = $factory->calls; + +$factory->next()->score++; +$callsAfterInc = $factory->calls; + +return [ + 'score' => $factory->box->score, + 'callsAfterAssign' => $callsAfterAssign, + 'callsAfterAssignOp' => $callsAfterAssignOp, + 'callsAfterInc' => $callsAfterInc, +]; +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_target_once_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/run_target_once.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + $result = require $scriptPath; + + expect($result)->toBe([ + 'score' => 31, + 'callsAfterAssign' => 1, + 'callsAfterAssignOp' => 2, + 'callsAfterInc' => 3, + ]); + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + + test('evaluates impure array index expression once on compound assignment and property dimension assignment', function () { + $source = <<<'PHP' + + */ + public array $items = [10, 20, 30]; +} + +/** @var list $list */ +$list = [10, 20, 30]; +$idx = 0; +$list[$idx++] += 5; +$idxAfterListCompound = $idx; + +$box = new DimTargetBox(); +$boxIdx = 0; +$box->items[$boxIdx++] = 99; +$idxAfterPropDim = $boxIdx; + +return [ + 'list' => $list, + 'idxAfterListCompound' => $idxAfterListCompound, + 'boxItems' => $box->items, + 'idxAfterPropDim' => $idxAfterPropDim, +]; +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_dim_once_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/run_dim_once.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + $result = require $scriptPath; + + expect($result)->toBe([ + 'list' => [15, 20, 30], + 'idxAfterListCompound' => 1, + 'boxItems' => [99, 20, 30], + 'idxAfterPropDim' => 1, + ]); + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + + test('evaluates dynamic static property receiver once and still enforces contract violations', function () { + $source = <<<'PHP' + DynamicStaticCounter::$count, + 'callsAfterValid' => $callsAfterValid, + 'callsAfterInvalid' => $getCalls, + 'threw' => $threw, +]; +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_dyn_static_once_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/run_dyn_static_once.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + $result = require $scriptPath; + + expect($result)->toBe([ + 'count' => 15, + 'callsAfterValid' => 1, + 'callsAfterInvalid' => 2, + 'threw' => true, + ]); + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when hoisted impure property assignment violates @var contract', function () { + $source = <<<'PHP' +score = -5; +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_hoist_err_' . uniqid(); + mkdir($tempDir, 0777, true); + $scriptPath = $tempDir . '/run_hoist_err.php'; + file_put_contents($scriptPath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $scriptPath) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($scriptPath); + @rmdir($tempDir); + } + }); + }); +}); From 8c5f832e38175d9c71b670c7aa68def497e001a8 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 12:24:27 +0800 Subject: [PATCH 30/37] Enhance ContractVisitor and TemplateManager with improved generic type handling and add Nullable and Union Generic Pre-binding tests --- src/Internal/Ast/ContractVisitor.php | 130 +++++++--- src/Internal/Generics/TemplateManager.php | 102 +++++++- .../NullableAndUnionGenericPrebindingTest.php | 229 ++++++++++++++++++ 3 files changed, 429 insertions(+), 32 deletions(-) create mode 100644 tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 72bf6b56..b49c3b53 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -12,14 +12,19 @@ use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; +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\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; @@ -1211,41 +1216,47 @@ private function handleAssign(Node\Expr\Assign $node): ?Node if ($typeString !== null) { $expr = $node->expr; - if ($expr instanceof Node\Expr\New_ && str_contains($typeString, '<')) { - $constructorArgs = $expr->args; - $factoryArrow = new Node\Expr\ArrowFunction([ - 'params' => [new Node\Param(new Node\Expr\Variable('_typephpCtorArgs'), null, null, false, true)], - 'expr' => new Node\Expr\New_( - $expr->class, - [new Node\Arg(new Node\Expr\Variable('_typephpCtorArgs'), false, true)] - ), - ]); - - $expr = new Node\Expr\StaticCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker'), - 'withPendingGeneric', - [ - new Node\Arg(new Node\Scalar\String_($typeString)), - new Node\Arg($factoryArrow), - new Node\Arg(new Node\Scalar\MagicConst\File()), - ...$constructorArgs, - ] - ); - - $node->expr = $this->wrapVariableCheck($expr, $typeString, $varName, $node->var->getStartLine()); - - return null; - } + $parsedType = null; try { [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); $parsedType = $typeParser->parse($tokens); + } catch (\Throwable) { + } + + if ($expr instanceof Node\Expr\New_ && $parsedType !== null) { + $pendingGenericTypeString = $this->extractPendingGenericTypeString($parsedType, $expr); + + if ($pendingGenericTypeString !== null) { + $constructorArgs = $expr->args; + $factoryArrow = new Node\Expr\ArrowFunction([ + 'params' => [new Node\Param(new Node\Expr\Variable('_typephpCtorArgs'), null, null, false, true)], + 'expr' => new Node\Expr\New_( + $expr->class, + [new Node\Arg(new Node\Expr\Variable('_typephpCtorArgs'), false, true)] + ), + ]); + + $wrappedNew = new Node\Expr\StaticCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker'), + 'withPendingGeneric', + [ + new Node\Arg(new Node\Scalar\String_($pendingGenericTypeString)), + new Node\Arg($factoryArrow), + new Node\Arg(new Node\Scalar\MagicConst\File()), + ...$constructorArgs, + ] + ); + + $node->expr = $this->wrapVariableCheck($wrappedNew, $typeString, $varName, $node->var->getStartLine()); - if (StaticTypeEvaluator::satisfies($expr, $parsedType, $this->currentFile)) { return null; } - } catch (\Throwable) { + } + + if ($parsedType !== null && StaticTypeEvaluator::satisfies($expr, $parsedType, $this->currentFile)) { + return null; } $node->expr = $this->wrapVariableCheck($expr, $typeString, $varName, $node->var->getStartLine()); @@ -1278,6 +1289,71 @@ private function handleAssign(Node\Expr\Assign $node): ?Node return null; } + private function extractPendingGenericTypeString(TypeNode $typeNode, Node\Expr\New_ $newExpr): ?string + { + $candidates = $this->collectObjectGenericNodes($typeNode); + if ($candidates === []) { + return null; + } + + if (\count($candidates) === 1) { + return (string) $candidates[0]; + } + + if ($newExpr->class instanceof Node\Name) { + $instantiatedFqcn = $this->resolveClassNameFromNode($newExpr->class); + if ($instantiatedFqcn !== null) { + $instantiatedFqcn = ltrim($instantiatedFqcn, '\\'); + $matching = []; + + foreach ($candidates as $candidate) { + $candFqcn = $this->resolveClassNameFromNode(new Node\Name((string) $candidate->type)); + if ($candFqcn !== null && ltrim($candFqcn, '\\') === $instantiatedFqcn) { + $matching[] = $candidate; + } + } + + if (\count($matching) === 1) { + return (string) $matching[0]; + } + } + } + + return null; + } + + /** + * @return list + */ + private function collectObjectGenericNodes(TypeNode $node): array + { + while ($node instanceof NullableTypeNode) { + $node = $node->type; + } + + if ($node instanceof GenericTypeNode) { + $baseName = (string) $node->type; + if (! SpecialTypeResolver::isBuiltInTypeKeyword($baseName) && ClassNameValidator::isValid($baseName)) { + return [$node]; + } + + return []; + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + $collected = []; + foreach ($node->types as $member) { + foreach ($this->collectObjectGenericNodes($member) as $found) { + $collected[] = $found; + } + } + + return $collected; + } + + return []; + } + private function handleAssignRef(Node\Expr\AssignRef $node): void { if (! ($node->var instanceof Node\Expr\Variable) || ! \is_string($node->var->name)) { diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index c2fb57e3..f74712fa 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -524,12 +524,25 @@ public static function restoreInstanceBindings(object $instance, array $bindings */ public static function pushPendingInstantiation(string $typeString, string $file): void { - $pos = strpos($typeString, '<'); - $rawClass = $pos !== false ? trim(substr($typeString, 0, $pos)) : $typeString; - $targetClass = SpecialTypeResolver::resolveFqcnForFile($rawClass, $file); + $resolvedTypeString = $typeString; + $targetClass = ''; + + if (str_starts_with($typeString, '?') || str_contains($typeString, '|') || str_contains($typeString, '&')) { + $extracted = self::extractSingleGenericTypeString($typeString); + if ($extracted !== null) { + $resolvedTypeString = $extracted[0]; + $targetClass = SpecialTypeResolver::resolveFqcnForFile($extracted[1], $file); + } + } else { + $pos = strpos($typeString, '<'); + $rawClass = $pos !== false ? trim(substr($typeString, 0, $pos)) : $typeString; + if (! SpecialTypeResolver::isBuiltInTypeKeyword($rawClass) && ClassNameValidator::isValid($rawClass)) { + $targetClass = SpecialTypeResolver::resolveFqcnForFile($rawClass, $file); + } + } self::$pendingInstantiations[] = [ - 'typeString' => $typeString, + 'typeString' => $resolvedTypeString, 'file' => $file, 'targetClass' => $targetClass, ]; @@ -553,7 +566,7 @@ public static function applyPendingInstantiation(object $instance): void } $pending = end(self::$pendingInstantiations); - if ($pending !== false && is_a($instance, $pending['targetClass'])) { + if ($pending !== false && $pending['targetClass'] !== '' && is_a($instance, $pending['targetClass'])) { self::bindInstance($instance, $pending['typeString'], $pending['file']); } } @@ -2525,8 +2538,17 @@ public static function bindInstance(object $instance, string $typeString, string $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); } + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + if ($typeNode instanceof GenericTypeNode) { self::bindInstanceFromNode($instance, $typeNode, '', true); + } elseif ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { + $matching = self::collectMatchingObjectGenericNodes($instance, $typeNode); + if (\count($matching) === 1) { + self::bindInstanceFromNode($instance, $matching[0], '', true); + } } } catch (\Throwable $e) { // Silently ignore malformed docblock strings @@ -2587,6 +2609,76 @@ public static function inferTypeFromValue(mixed $value): TypeNode return self::$mixedNode ??= new IdentifierTypeNode('mixed'); } + /** + * @return array{0: string, 1: string}|null + */ + private static function extractSingleGenericTypeString(string $typeString): ?array + { + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($typeString)); + $typeNode = $typeParser->parse($tokens); + + $candidates = self::collectObjectGenericNodesFromType($typeNode); + if (\count($candidates) === 1) { + $node = $candidates[0]; + + return [(string) $node, (string) $node->type]; + } + } catch (\Throwable) { + } + + return null; + } + + /** + * @return list + */ + private static function collectObjectGenericNodesFromType(TypeNode $node): array + { + while ($node instanceof NullableTypeNode) { + $node = $node->type; + } + + if ($node instanceof GenericTypeNode) { + $baseName = (string) $node->type; + if (! SpecialTypeResolver::isBuiltInTypeKeyword($baseName) && ClassNameValidator::isValid($baseName)) { + return [$node]; + } + + return []; + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + $collected = []; + foreach ($node->types as $member) { + foreach (self::collectObjectGenericNodesFromType($member) as $found) { + $collected[] = $found; + } + } + + return $collected; + } + + return []; + } + + /** + * @return list + */ + private static function collectMatchingObjectGenericNodes(object $instance, TypeNode $node): array + { + $matching = []; + foreach (self::collectObjectGenericNodesFromType($node) as $candidate) { + $baseName = (string) $candidate->type; + if (is_a($instance, $baseName)) { + $matching[] = $candidate; + } + } + + return $matching; + } + /** * Checks whether a function has at least one active call frame on the stack. */ diff --git a/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php b/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php new file mode 100644 index 00000000..e31165ab --- /dev/null +++ b/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php @@ -0,0 +1,229 @@ +typeDuringConstruct = TypePHP::getGenericType($this); + $this->bodyExecuted = true; + } + + /** + * @param T $item + */ + public function add(mixed $item): void + { + $this->content[] = $item; + } + + /** + * @return T[] + */ + public function getContent(): array + { + return $this->content; + } +} + +describe('Nullable & Union Generic Constructor Pre-binding (Red Phase)', function () { + describe('0. Control: Direct GenericTypeNode Pre-binding', function () { + test('prebinds T inside constructor and validates elements on entry', function () { + /** @var PrebindNullableBox $box */ + $box = new PrebindNullableBox([new PrebindNullableDog()]); + + expect($box->typeDuringConstruct)->toBe(PrebindNullableDog::class) + ->and($box->bodyExecuted)->toBeTrue() + ; + + expect(function () { + /** @var PrebindNullableBox $bad */ + $bad = new PrebindNullableBox([new PrebindNullableCat()]); + })->toThrow( + TypeError::class, + 'Argument $content[0] (template T = ' . PrebindNullableDog::class . ') must be of type ' . PrebindNullableDog::class + ); + }); + }); + + describe('1. Nullable Generic (?Box)', function () { + test('prebinds template T during __construct() for ?Box', function () { + /** @var ?PrebindNullableBox $box */ + $box = new PrebindNullableBox([new PrebindNullableDog()]); + + expect($box->typeDuringConstruct)->toBe(PrebindNullableDog::class) + ->and(TypePHP::getGenericType($box))->toBe(PrebindNullableDog::class) + ; + }); + + test('prebinds ?Box before constructor so [new Dog()] does not lock T=Dog and cause invariance mismatch', function () { + /** @var ?PrebindNullableBox $box */ + $box = new PrebindNullableBox([new PrebindNullableDog()]); + + expect($box->typeDuringConstruct)->toBe(PrebindNullableAnimal::class) + ->and(TypePHP::getGenericType($box))->toBe(PrebindNullableAnimal::class) + ; + + $box->add(new PrebindNullableCat()); + expect($box->getContent())->toHaveCount(2); + }); + + test('rejects invalid constructor items at parameter boundary before constructor body runs on ?Box', function () { + $bodyRan = false; + + $probe = new class () extends PrebindNullableBox { + public static bool $ran = false; + + /** + * @param T[] $content + */ + public function __construct(array $content = []) + { + self::$ran = true; + parent::__construct($content); + } + }; + $probeClass = $probe::class; + $probeClass::$ran = false; + + expect(function () use ($probeClass) { + /** @var ?PrebindNullableBox $box */ + $box = new $probeClass([new PrebindNullableCat()]); + })->toThrow( + TypeError::class, + 'Argument $content[0] (template T = ' . PrebindNullableDog::class . ')' + ); + + expect($probeClass::$ran)->toBeFalse(); + }); + + test('allows null assignment to ?Box', function () { + /** @var ?PrebindNullableBox $box */ + $box = null; + + expect($box)->toBeNull(); + }); + }); + + describe('2. Union Generics (Box|null, null|Box, Box|Other)', function () { + test('prebinds template T during __construct() for Box|null', function () { + /** @var PrebindNullableBox|null $box */ + $box = new PrebindNullableBox([new PrebindNullableDog()]); + + expect($box->typeDuringConstruct)->toBe(PrebindNullableDog::class); + }); + + test('prebinds template T during __construct() for null|Box', function () { + /** @var null|PrebindNullableBox $box */ + $box = new PrebindNullableBox([new PrebindNullableDog()]); + + expect($box->typeDuringConstruct)->toBe(PrebindNullableDog::class); + }); + + test('prebinds Box|null and null|Box without false-positive invariance mismatch on [new Dog()]', function () { + /** @var PrebindNullableBox|null $boxA */ + $boxA = new PrebindNullableBox([new PrebindNullableDog()]); + expect($boxA->typeDuringConstruct)->toBe(PrebindNullableAnimal::class); + + /** @var null|PrebindNullableBox $boxB */ + $boxB = new PrebindNullableBox([new PrebindNullableDog()]); + expect($boxB->typeDuringConstruct)->toBe(PrebindNullableAnimal::class); + }); + + test('rejects invalid constructor item at constructor parameter boundary for Box|null', function () { + expect(function () { + /** @var PrebindNullableBox|null $box */ + $box = new PrebindNullableBox([new PrebindNullableCat()]); + })->toThrow( + TypeError::class, + 'Argument $content[0] (template T = ' . PrebindNullableDog::class . ')' + ); + }); + + test('prebinds Box when unioned with unrelated non-generic class (Box|Car)', function () { + /** @var PrebindNullableBox|PrebindNullableCar $box */ + $box = new PrebindNullableBox([new PrebindNullableDog()]); + + expect($box->typeDuringConstruct)->toBe(PrebindNullableDog::class); + }); + + test('prebinds template T during 0-arg __construct() for ?Box and Box|null', function () { + /** @var ?PrebindNullableBox $nullable */ + $nullable = new PrebindNullableBox(); + + /** @var PrebindNullableBox|null $unionRight */ + $unionRight = new PrebindNullableBox(); + + /** @var null|PrebindNullableBox $unionLeft */ + $unionLeft = new PrebindNullableBox(); + + expect($nullable->typeDuringConstruct)->toBe(PrebindNullableDog::class) + ->and($unionRight->typeDuringConstruct)->toBe(PrebindNullableDog::class) + ->and($unionLeft->typeDuringConstruct)->toBe(PrebindNullableDog::class) + ; + }); + }); + + describe('3. Ambiguous Multi-Generic Unions (Box|Box)', function () { + test('does not wrongly prebind first branch Box when Box is instantiated', function () { + /** @var PrebindNullableBox|PrebindNullableBox $box */ + $box = new PrebindNullableBox([new PrebindNullableCat()]); + + expect($box)->toBeInstanceOf(PrebindNullableBox::class) + ->and(TypePHP::getGenericType($box))->toBe(PrebindNullableCat::class) + ; + }); + }); + + describe('4. Non-Class Scalar Generics AST Transformation (int<1, 10>)', function () { + test('does not wrap new expression in withPendingGeneric() when @var is a scalar range int<1, 10>', function () { + $source = <<<'PHP' + $count */ +$count = new \stdClass(); +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_scalar_range_new.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::withPendingGeneric') + ->and($transformed)->toContain('RuntimeTypeChecker::checkVariable') + ; + }); + }); +}); From ad2363c6cda8e11fd73f04ec8668071588f69bba Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 12:47:40 +0800 Subject: [PATCH 31/37] Enhance InlineChecker and SpecialTypeResolver with namespace extraction and improved file metadata handling; add MultiNamespaceAndEnumTraitMetadataTest for comprehensive coverage of multi-namespace and trait use cases. --- src/Internal/Checker/InlineChecker.php | 22 +- src/Internal/Io/StreamWrapper.php | 133 +++++-- src/Internal/Resolver/SpecialTypeResolver.php | 247 ++++++++---- ...MultiNamespaceAndEnumTraitMetadataTest.php | 352 ++++++++++++++++++ 4 files changed, 654 insertions(+), 100 deletions(-) create mode 100644 tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index ae67929d..92c27043 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -167,7 +167,8 @@ public static function checkVariable( [$typeNode, $needsContext] = self::parseTypeString($normalized); if ($file !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + $callerNamespace = self::extractNamespaceFromCaller($caller); + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); } if ($needsContext && $caller !== null) { @@ -251,7 +252,8 @@ public static function validateCollectionElementMutation( [$typeNode, $needsContext] = self::parseTypeString($normalized); if ($file !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + $callerNamespace = self::extractNamespaceFromCaller($caller); + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); } if ($needsContext && $caller !== null) { @@ -308,6 +310,22 @@ public static function validateCollectionElementMutation( return null; } + private static function extractNamespaceFromCaller(?string $caller): ?string + { + if ($caller === null || $caller === '') { + return null; + } + + $symbol = str_contains($caller, '::') ? explode('::', $caller, 2)[0] : $caller; + if (str_contains($symbol, '@anonymous')) { + return null; + } + + $pos = strrpos($symbol, '\\'); + + return $pos !== false ? substr($symbol, 0, $pos) : ''; + } + /** * Recursively wraps callable items nested inside array shapes. * diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index 54a24f38..9ca725f2 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -975,22 +975,96 @@ private static function extractAndSeedFileMetadata(array $stmts, string $filePat return; } - $namespace = ''; - $imports = []; + $lastNamespace = ''; + $mergedImports = []; + $namespaceImports = []; + $namespaceRanges = []; $classTraitUseDocs = []; $anonymousTraitUseDocs = []; - $nodesToScan = $stmts; + $hasNamespaceStmt = false; + $topLevelOtherStmts = []; + foreach ($stmts as $stmt) { if ($stmt instanceof \PhpParser\Node\Stmt\Namespace_) { - $namespace = $stmt->name !== null ? $stmt->name->toString() : ''; - $nodesToScan = $stmt->stmts; + $hasNamespaceStmt = true; + $ns = $stmt->name !== null ? $stmt->name->toString() : ''; + $lastNamespace = $ns; + $namespaceRanges[] = [ + 'start' => $stmt->getStartLine(), + 'end' => $stmt->getEndLine(), + 'ns' => $ns, + ]; + + self::scanNamespaceStatements( + $stmt->stmts, + $ns, + $mergedImports, + $namespaceImports, + $classTraitUseDocs + ); + } else { + $topLevelOtherStmts[] = $stmt; + } + } + + if (! $hasNamespaceStmt && $topLevelOtherStmts !== []) { + self::scanNamespaceStatements( + $topLevelOtherStmts, + '', + $mergedImports, + $namespaceImports, + $classTraitUseDocs + ); + } + + $nodeFinder = new \PhpParser\NodeFinder(); + /** @var list<\PhpParser\Node\Stmt\Class_> $anonClasses */ + $anonClasses = $nodeFinder->find($stmts, function (\PhpParser\Node $node): bool { + return $node instanceof \PhpParser\Node\Stmt\Class_ && $node->name === null; + }); - break; + foreach ($anonClasses as $anonClass) { + $startLine = $anonClass->getStartLine(); + foreach ($anonClass->stmts as $classStmt) { + if ($classStmt instanceof \PhpParser\Node\Stmt\TraitUse) { + $doc = $classStmt->getDocComment(); + if ($doc !== null) { + $anonymousTraitUseDocs[$startLine][] = $doc->getText(); + } + } } } - foreach ($nodesToScan as $stmt) { + SpecialTypeResolver::seedFileMetadata( + $filePath, + $lastNamespace, + $mergedImports, + $classTraitUseDocs, + $anonymousTraitUseDocs, + $namespaceImports, + $namespaceRanges + ); + } + + /** + * Extracts use imports and TraitUse docblocks for a single namespace block or un-namespaced statement list. + * + * @param array<\PhpParser\Node\Stmt> $statements + * @param array $mergedImports + * @param array> $namespaceImports + * @param array> $classTraitUseDocs + */ + private static function scanNamespaceStatements( + array $statements, + string $ns, + array &$mergedImports, + array &$namespaceImports, + array &$classTraitUseDocs + ): void { + $nsImports = $namespaceImports[$ns] ?? []; + + foreach ($statements as $stmt) { if ($stmt instanceof \PhpParser\Node\Stmt\Use_) { if ($stmt->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL) { continue; @@ -999,51 +1073,46 @@ private static function extractAndSeedFileMetadata(array $stmts, string $filePat foreach ($stmt->uses as $use) { $fqcn = $use->name->toString(); $alias = $use->getAlias()->toString(); - $imports[$alias] = $fqcn; + $nsImports[$alias] = $fqcn; + $mergedImports[$alias] = $fqcn; } } elseif ($stmt instanceof \PhpParser\Node\Stmt\GroupUse) { $prefix = $stmt->prefix->toString(); foreach ($stmt->uses as $use) { - if ($use->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL && $use->type !== \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN && $stmt->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL) { + if ( + $use->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL + && $use->type !== \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN + && $stmt->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL + ) { continue; } $fqcn = $prefix . '\\' . $use->name->toString(); $alias = $use->getAlias()->toString(); - $imports[$alias] = $fqcn; + $nsImports[$alias] = $fqcn; + $mergedImports[$alias] = $fqcn; } - } elseif ($stmt instanceof \PhpParser\Node\Stmt\Class_ && $stmt->name !== null) { - $className = $namespace !== '' ? $namespace . '\\' . $stmt->name->toString() : $stmt->name->toString(); + } elseif ( + ( + $stmt instanceof \PhpParser\Node\Stmt\Class_ + || $stmt instanceof \PhpParser\Node\Stmt\Enum_ + || $stmt instanceof \PhpParser\Node\Stmt\Trait_ + ) + && $stmt->name !== null + ) { + $typeName = $ns !== '' ? $ns . '\\' . $stmt->name->toString() : $stmt->name->toString(); foreach ($stmt->stmts as $classStmt) { if ($classStmt instanceof \PhpParser\Node\Stmt\TraitUse) { $doc = $classStmt->getDocComment(); if ($doc !== null) { - $classTraitUseDocs[$className][] = $doc->getText(); + $classTraitUseDocs[$typeName][] = $doc->getText(); } } } } } - $nodeFinder = new \PhpParser\NodeFinder(); - /** @var list<\PhpParser\Node\Stmt\Class_> $anonClasses */ - $anonClasses = $nodeFinder->find($stmts, function (\PhpParser\Node $node): bool { - return $node instanceof \PhpParser\Node\Stmt\Class_ && $node->name === null; - }); - - foreach ($anonClasses as $anonClass) { - $startLine = $anonClass->getStartLine(); - foreach ($anonClass->stmts as $classStmt) { - if ($classStmt instanceof \PhpParser\Node\Stmt\TraitUse) { - $doc = $classStmt->getDocComment(); - if ($doc !== null) { - $anonymousTraitUseDocs[$startLine][] = $doc->getText(); - } - } - } - } - - SpecialTypeResolver::seedFileMetadata($filePath, $namespace, $imports, $classTraitUseDocs, $anonymousTraitUseDocs); + $namespaceImports[$ns] = $nsImports; } } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 80172316..bd8c4074 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -175,6 +175,20 @@ final class SpecialTypeResolver */ private static array $anonymousTraitUseDocs = []; + /** + * In-memory cache of per-namespace use import maps keyed by filename and namespace name. + * + * @var array>> + */ + private static array $fileNamespaceUseImports = []; + + /** + * In-memory cache of namespace line ranges keyed by filename. + * + * @var array> + */ + private static array $fileNamespaceRanges = []; + /** * Resets reflection context and dynamic caches. Preserves static file imports. */ @@ -327,7 +341,7 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct /** * Recursively resolves type identifiers in a TypeNode AST using file context (use imports and namespace). */ - public static function resolveForFile(TypeNode $node, string $file): TypeNode + public static function resolveForFile(TypeNode $node, string $file, ?string $namespace = null): TypeNode { $file = str_replace('\\', '/', $file); @@ -348,25 +362,25 @@ public static function resolveForFile(TypeNode $node, string $file): TypeNode return clone $node; } - $resolvedClass = self::resolveFqcnForFile($className, $file); + $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); return $resolvedClass !== $className ? new IdentifierTypeNode($resolvedClass . '::' . $member) : clone $node; } - $fqcn = self::resolveFqcnForFile($node->name, $file); + $fqcn = self::resolveFqcnForFile($node->name, $file, true, $namespace); return $fqcn !== $node->name ? new IdentifierTypeNode($fqcn) : clone $node; } if ($node instanceof ConstTypeNode) { - return self::resolveConstTypeForFile($node, $file); + return self::resolveConstTypeForFile($node, $file, $namespace); } if ($node instanceof GenericTypeNode) { - $genericType = self::resolveForFile($node->type, $file); + $genericType = self::resolveForFile($node->type, $file, $namespace); $innerTypes = []; foreach ($node->genericTypes as $gt) { - $innerTypes[] = self::resolveForFile($gt, $file); + $innerTypes[] = self::resolveForFile($gt, $file, $namespace); } return new GenericTypeNode( @@ -377,27 +391,27 @@ public static function resolveForFile(TypeNode $node, string $file): TypeNode } if ($node instanceof OffsetAccessTypeNode) { - return self::resolveOffsetAccessForFile($node, $file); + return self::resolveOffsetAccessForFile($node, $file, $namespace); } if ($node instanceof ArrayShapeNode) { - return self::resolveArrayShapeForFile($node, $file); + return self::resolveArrayShapeForFile($node, $file, $namespace); } if ($node instanceof ObjectShapeNode) { - return self::resolveObjectShapeForFile($node, $file); + return self::resolveObjectShapeForFile($node, $file, $namespace); } if ($node instanceof CallableTypeNode) { - return self::resolveCallableForFile($node, $file); + return self::resolveCallableForFile($node, $file, $namespace); } if ($node instanceof ConditionalTypeNode) { return new ConditionalTypeNode( - self::resolveForFile($node->subjectType, $file), - self::resolveForFile($node->targetType, $file), - self::resolveForFile($node->if, $file), - self::resolveForFile($node->else, $file), + self::resolveForFile($node->subjectType, $file, $namespace), + self::resolveForFile($node->targetType, $file, $namespace), + self::resolveForFile($node->if, $file, $namespace), + self::resolveForFile($node->else, $file, $namespace), $node->negated ); } @@ -405,25 +419,25 @@ public static function resolveForFile(TypeNode $node, string $file): TypeNode if ($node instanceof ConditionalTypeForParameterNode) { return new ConditionalTypeForParameterNode( $node->parameterName, - self::resolveForFile($node->targetType, $file), - self::resolveForFile($node->if, $file), - self::resolveForFile($node->else, $file), + self::resolveForFile($node->targetType, $file, $namespace), + self::resolveForFile($node->if, $file, $namespace), + self::resolveForFile($node->else, $file, $namespace), $node->negated ); } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::resolveForFile($node->type, $file)); + return new NullableTypeNode(self::resolveForFile($node->type, $file, $namespace)); } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::resolveForFile($node->type, $file)); + return new ArrayTypeNode(self::resolveForFile($node->type, $file, $namespace)); } if ($node instanceof UnionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::resolveForFile($t, $file); + $types[] = self::resolveForFile($t, $file, $namespace); } return new UnionTypeNode($types); @@ -432,7 +446,7 @@ public static function resolveForFile(TypeNode $node, string $file): TypeNode if ($node instanceof IntersectionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::resolveForFile($t, $file); + $types[] = self::resolveForFile($t, $file, $namespace); } return new IntersectionTypeNode($types); @@ -759,7 +773,7 @@ private static function resolveCallable(CallableTypeNode $node, \ReflectionClass return new CallableTypeNode($node->identifier, $resolvedParameters, $resolvedReturnType, $resolvedTemplateTypes); } - private static function resolveConstTypeForFile(ConstTypeNode $node, string $file): ConstTypeNode + private static function resolveConstTypeForFile(ConstTypeNode $node, string $file, ?string $namespace = null): ConstTypeNode { if ($node->constExpr instanceof ConstFetchNode && $node->constExpr->className !== '') { $className = $node->constExpr->className; @@ -768,7 +782,7 @@ private static function resolveConstTypeForFile(ConstTypeNode $node, string $fil if ($lowerClassName === 'self' || $lowerClassName === 'parent') { $resolvedClass = $className; } else { - $resolvedClass = self::resolveFqcnForFile($className, $file); + $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); } return new ConstTypeNode(new ConstFetchNode($resolvedClass, $node->constExpr->name)); @@ -777,10 +791,10 @@ private static function resolveConstTypeForFile(ConstTypeNode $node, string $fil return clone $node; } - private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, string $file): TypeNode + private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, string $file, ?string $namespace = null): TypeNode { - $baseType = self::resolveForFile($node->type, $file); - $offsetType = self::resolveForFile($node->offset, $file); + $baseType = self::resolveForFile($node->type, $file, $namespace); + $offsetType = self::resolveForFile($node->offset, $file, $namespace); $offsetKey = self::extractOffsetKey($offsetType); @@ -805,7 +819,7 @@ private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, s return new OffsetAccessTypeNode($baseType, $offsetType); } - private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $file): ArrayShapeNode + private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $file, ?string $namespace = null): ArrayShapeNode { $items = []; foreach ($node->items as $item) { @@ -828,7 +842,7 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $lowerClassName = strtolower($className); if ($lowerClassName !== 'self' && $lowerClassName !== 'parent') { - $resolvedClass = self::resolveFqcnForFile($className, $file); + $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); $resolvedKeyNode = self::resolveConstantKeyValue($resolvedClass, $constName); if ($resolvedKeyNode !== null) { $keyName = $resolvedKeyNode; @@ -839,7 +853,7 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $items[] = new ArrayShapeItemNode( $keyName, $item->optional, - self::resolveForFile($item->valueType, $file) + self::resolveForFile($item->valueType, $file, $namespace) ); } @@ -849,39 +863,39 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $unsealedType = null; if ($node->unsealedType !== null) { - $unsealedKey = $node->unsealedType->keyType !== null ? self::resolveForFile($node->unsealedType->keyType, $file) : null; - $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file); + $unsealedKey = $node->unsealedType->keyType !== null ? self::resolveForFile($node->unsealedType->keyType, $file, $namespace) : null; + $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace); $unsealedType = new ArrayShapeUnsealedTypeNode($unsealedValue, $unsealedKey); } return ArrayShapeNode::createUnsealed($items, $unsealedType, $node->kind); } - private static function resolveObjectShapeForFile(ObjectShapeNode $node, string $file): ObjectShapeNode + private static function resolveObjectShapeForFile(ObjectShapeNode $node, string $file, ?string $namespace = null): ObjectShapeNode { $items = []; foreach ($node->items as $item) { $items[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::resolveForFile($item->valueType, $file) + self::resolveForFile($item->valueType, $file, $namespace) ); } return new ObjectShapeNode($items); } - private static function resolveCallableForFile(CallableTypeNode $node, string $file): CallableTypeNode + private static function resolveCallableForFile(CallableTypeNode $node, string $file, ?string $namespace = null): CallableTypeNode { $localTemplates = []; $resolvedTemplateTypes = []; foreach ($node->templateTypes as $tTag) { $localTemplates[$tTag->name] = true; $resolvedBound = $tTag->bound !== null - ? self::resolveForFile($tTag->bound, $file) + ? self::resolveForFile($tTag->bound, $file, $namespace) : null; $resolvedDefault = $tTag->default !== null - ? self::resolveForFile($tTag->default, $file) + ? self::resolveForFile($tTag->default, $file, $namespace) : null; $resolvedTemplateTypes[] = new \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode( $tTag->name, @@ -895,7 +909,7 @@ private static function resolveCallableForFile(CallableTypeNode $node, string $f foreach ($node->parameters as $param) { $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[(string) $param->type])) ? clone $param->type - : self::resolveForFile($param->type, $file); + : self::resolveForFile($param->type, $file, $namespace); $resolvedParameters[] = new CallableTypeParameterNode( $paramType, @@ -908,7 +922,7 @@ private static function resolveCallableForFile(CallableTypeNode $node, string $f $resolvedReturnType = ($node->returnType instanceof IdentifierTypeNode && isset($localTemplates[$node->returnType->name])) ? clone $node->returnType - : self::resolveForFile($node->returnType, $file); + : self::resolveForFile($node->returnType, $file, $namespace); return new CallableTypeNode($node->identifier, $resolvedParameters, $resolvedReturnType, $resolvedTemplateTypes); } @@ -1004,21 +1018,36 @@ public static function resolveConstantKeyValue(string $fqcn, string $constName): * @param array $imports * @param array> $classTraitUseDocs * @param array> $anonymousTraitUseDocs + * @param array> $namespaceImports + * @param list $namespaceRanges */ public static function seedFileMetadata( string $fileName, string $namespace, array $imports, array $classTraitUseDocs = [], - array $anonymousTraitUseDocs = [] + array $anonymousTraitUseDocs = [], + array $namespaceImports = [], + array $namespaceRanges = [] ): void { if ($fileName !== '') { $fileName = str_replace('\\', '/', $fileName); self::$fileNamespaces[$fileName] = $namespace; self::$fileUseImports[$fileName] = $imports; + self::$fileNamespaceUseImports[$fileName] = $namespaceImports !== [] + ? $namespaceImports + : [$namespace => $imports]; + + if ($namespaceRanges !== []) { + self::$fileNamespaceRanges[$fileName] = $namespaceRanges; + } else { + unset(self::$fileNamespaceRanges[$fileName]); + } + foreach ($classTraitUseDocs as $className => $docs) { self::$classTraitUseDocs[$className] = $docs; } + if ($anonymousTraitUseDocs !== []) { self::$anonymousTraitUseDocs[$fileName] = $anonymousTraitUseDocs; } @@ -1123,11 +1152,11 @@ public static function getUseImports(\ReflectionClass|\ReflectionFunction|\Refle } /** - * Extracts and caches use imports directly from a file path. + * Extracts and caches use imports directly from a file path, optionally scoped to a namespace. * * @return array */ - public static function getUseImportsFromFile(string $fileName): array + public static function getUseImportsFromFile(string $fileName, ?string $namespace = null): array { if ($fileName === '') { return []; @@ -1135,20 +1164,22 @@ public static function getUseImportsFromFile(string $fileName): array $fileName = str_replace('\\', '/', $fileName); - if (isset(self::$fileUseImports[$fileName])) { - return self::$fileUseImports[$fileName]; - } + if (! isset(self::$fileUseImports[$fileName])) { + if (! file_exists($fileName)) { + return []; + } - if (! file_exists($fileName)) { - return []; - } + $source = file_get_contents($fileName); + if ($source === false) { + return self::$fileUseImports[$fileName] = []; + } - $source = file_get_contents($fileName); - if ($source === false) { - return self::$fileUseImports[$fileName] = []; + self::parseFileMetadata($fileName, $source); } - self::parseFileMetadata($fileName, $source); + if ($namespace !== null && isset(self::$fileNamespaceUseImports[$fileName])) { + return self::$fileNamespaceUseImports[$fileName][$namespace] ?? []; + } return self::$fileUseImports[$fileName] ?? []; } @@ -1207,7 +1238,9 @@ public static function resolveFqcn(string $name, \ReflectionClass|\ReflectionFun $fileName = $ref->getFileName(); if ($fileName !== false && $fileName !== '') { - return self::resolveFqcnForFile($name, $fileName); + $namespace = self::resolveNamespaceFromReflection($ref, $fileName); + + return self::resolveFqcnForFile($name, $fileName, true, $namespace); } $contextKey = $ref instanceof \ReflectionMethod @@ -1236,7 +1269,7 @@ public static function resolveFqcn(string $name, \ReflectionClass|\ReflectionFun /** * Resolves a short class name to its FQCN purely based on file context with 2D caching. */ - public static function resolveFqcnForFile(string $name, string $file, bool $autoload = true): string + public static function resolveFqcnForFile(string $name, string $file, bool $autoload = true, ?string $namespace = null): string { $file = str_replace('\\', '/', $file); $lower = strtolower($name); @@ -1255,15 +1288,15 @@ public static function resolveFqcnForFile(string $name, string $file, bool $auto return $name; } - $cacheKey = $autoload ? $name : ($name . ':no_auto'); + $cacheKey = ($namespace !== null ? $namespace . '|' : '') . ($autoload ? $name : ($name . ':no_auto')); if (isset(self::$fileFqcnCache[$file][$cacheKey])) { return self::$fileFqcnCache[$file][$cacheKey]; } - $imports = self::getUseImportsFromFile($file); - $namespace = self::getNamespaceFromFile($file); + $imports = self::getUseImportsFromFile($file, $namespace); + $resolvedNamespace = $namespace ?? self::getNamespaceFromFile($file); - $resolved = self::resolveNameFromImportsAndNamespace($name, $imports, $namespace, $autoload); + $resolved = self::resolveNameFromImportsAndNamespace($name, $imports, $resolvedNamespace, $autoload); if (isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) && $resolved === $name && ! self::symbolExists($name, $autoload)) { return self::$fileFqcnCache[$file][$cacheKey] = $name; @@ -1272,6 +1305,47 @@ public static function resolveFqcnForFile(string $name, string $file, bool $auto return self::$fileFqcnCache[$file][$cacheKey] = $resolved; } + /** + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref + */ + private static function resolveNamespaceFromReflection(\ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref, string $fileName): string + { + $normalizedFile = str_replace('\\', '/', $fileName); + + if (! isset(self::$fileUseImports[$normalizedFile]) && file_exists($fileName)) { + $source = file_get_contents($fileName); + if ($source !== false) { + self::parseFileMetadata($fileName, $source); + } + } + + if (isset(self::$fileNamespaceRanges[$normalizedFile])) { + $ranges = self::$fileNamespaceRanges[$normalizedFile]; + if (\count($ranges) === 1) { + return $ranges[0]['ns']; + } + + $startLine = $ref->getStartLine(); + if ($startLine !== false) { + foreach ($ranges as $range) { + if ($startLine >= $range['start'] && $startLine <= $range['end']) { + return $range['ns']; + } + } + } + } + + if (isset(self::$fileNamespaces[$normalizedFile])) { + return self::$fileNamespaces[$normalizedFile]; + } + + return match (true) { + $ref instanceof \ReflectionClass => $ref->getNamespaceName(), + $ref instanceof \ReflectionMethod => $ref->getDeclaringClass()->getNamespaceName(), + $ref instanceof \ReflectionFunction => $ref->getNamespaceName(), + }; + } + /** * Common name resolution algorithm adhering to PHP standard name resolution rules. * @@ -1365,17 +1439,24 @@ public static function parseFileMetadata(string $fileName, string $source): void $normalizedFile = str_replace('\\', '/', $fileName); self::$fileNamespaces[$normalizedFile] = ''; self::$fileUseImports[$normalizedFile] = []; + self::$fileNamespaceUseImports[$normalizedFile] = []; self::$anonymousTraitUseDocs[$normalizedFile] = []; + unset(self::$fileNamespaceRanges[$normalizedFile]); try { $tokens = \PhpToken::tokenize($source); $count = \count($tokens); $namespace = ''; $imports = []; + $allImports = []; + $namespaceImports = []; + $namespaceRanges = []; + $hasSeenNamespace = false; + $currentNsStartLine = 1; - /** @var list $classStack */ + /** @var list $classStack */ $classStack = []; - /** @var array{type: 'named'|'anon', name?: string, line?: int}|null $pendingClass */ + /** @var array{type: 'named'|'anon', name?: ?string, line?: ?int}|null $pendingClass */ $pendingClass = null; $braceDepth = 0; @@ -1383,6 +1464,21 @@ public static function parseFileMetadata(string $fileName, string $source): void $token = $tokens[$i]; if ($token->id === T_NAMESPACE) { + if ($hasSeenNamespace) { + $namespaceImports[$namespace] = $imports; + $namespaceRanges[] = [ + 'start' => $currentNsStartLine, + 'end' => max($currentNsStartLine, $token->line - 1), + 'ns' => $namespace, + ]; + } elseif ($imports !== []) { + $namespaceImports[$namespace] = $imports; + } + + $hasSeenNamespace = true; + $currentNsStartLine = $token->line; + $imports = []; + $nsParts = []; for ($j = $i + 1; $j < $count; $j++) { if ($tokens[$j]->text === ';' || $tokens[$j]->text === '{') { @@ -1530,9 +1626,10 @@ public static function parseFileMetadata(string $fileName, string $source): void continue; } if (preg_match('/^([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $part, $m) === 1) { - $fqcn = rtrim($prefix, '\\') . '\\' . trim($m[1]); + $fqcn = ltrim(rtrim($prefix, '\\') . '\\' . trim($m[1]), '\\'); $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); - $imports[$alias] = ltrim($fqcn, '\\'); + $imports[$alias] = $fqcn; + $allImports[$alias] = $fqcn; } } @@ -1548,22 +1645,40 @@ public static function parseFileMetadata(string $fileName, string $source): void continue; } if (preg_match('/^(?:function\s+|const\s+)?([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $part, $m) === 1) { - $fqcn = trim($m[1]); + $fqcn = ltrim(trim($m[1]), '\\'); $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); - $imports[$alias] = ltrim($fqcn, '\\'); + $imports[$alias] = $fqcn; + $allImports[$alias] = $fqcn; } } } elseif (preg_match('/^(?:function\s+|const\s+)?([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', trim($useStatement), $m) === 1) { - $fqcn = trim($m[1]); + $fqcn = ltrim(trim($m[1]), '\\'); $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); - $imports[$alias] = ltrim($fqcn, '\\'); + $imports[$alias] = $fqcn; + $allImports[$alias] = $fqcn; } } } - self::$fileUseImports[$normalizedFile] = $imports; + $namespaceImports[$namespace] = $imports; + if ($hasSeenNamespace) { + $lastTokenLine = $count > 0 ? $tokens[$count - 1]->line : $currentNsStartLine; + $namespaceRanges[] = [ + 'start' => $currentNsStartLine, + 'end' => max($currentNsStartLine, $lastTokenLine), + 'ns' => $namespace, + ]; + } + + self::$fileNamespaceUseImports[$normalizedFile] = $namespaceImports; + if ($namespaceRanges !== []) { + self::$fileNamespaceRanges[$normalizedFile] = $namespaceRanges; + } + self::$fileUseImports[$normalizedFile] = $allImports; } catch (\Throwable $e) { self::$fileUseImports[$normalizedFile] = []; + self::$fileNamespaceUseImports[$normalizedFile] = []; + unset(self::$fileNamespaceRanges[$normalizedFile]); } } } diff --git a/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php b/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php new file mode 100644 index 00000000..e53d28f6 --- /dev/null +++ b/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php @@ -0,0 +1,352 @@ + */ + use GenericTrait; + } +} + +namespace VirtualMultiNs\Second { + use TypePHP\Tests\Fixtures\Domain\Cat; + + class SecondConsumer + { + /** @use GenericTrait */ + use GenericTrait; + } +} +PHP; + + StreamWrapper::transformSource($source, 'VirtualMultiNsClasses.php'); + + $firstDocs = SpecialTypeResolver::getClassTraitUseDocs('VirtualMultiNs\First\FirstConsumer'); + $secondDocs = SpecialTypeResolver::getClassTraitUseDocs('VirtualMultiNs\Second\SecondConsumer'); + + expect($firstDocs)->toHaveCount(1) + ->and($firstDocs[0])->toContain('GenericTrait') + ->and($secondDocs)->toHaveCount(1) + ->and($secondDocs[0])->toContain('GenericTrait') + ; + }); + + test('seeds TraitUse docblocks for Enum_ and Trait_ declarations', function () { + $source = <<<'PHP' + */ + use InnerGenericTrait; +} + +enum StatusEnumWithTrait: string +{ + /** @use OuterUsingTrait */ + use OuterUsingTrait; + + case Active = 'active'; +} +PHP; + + StreamWrapper::transformSource($source, 'VirtualEnumAndTraitSeed.php'); + + $traitDocs = SpecialTypeResolver::getClassTraitUseDocs('VirtualEnumTraitNs\OuterUsingTrait'); + $enumDocs = SpecialTypeResolver::getClassTraitUseDocs('VirtualEnumTraitNs\StatusEnumWithTrait'); + + expect($traitDocs)->toHaveCount(1) + ->and($traitDocs[0])->toContain('InnerGenericTrait') + ->and($enumDocs)->toHaveCount(1) + ->and($enumDocs[0])->toContain('OuterUsingTrait') + ; + }); + + test('seeds TraitUse docblocks for Enum_ and Trait_ inside a second namespace block', function () { + $source = <<<'PHP' + */ + use BetaTrait; + + case One = 'one'; +} + +trait BetaTraitHolder +{ + /** @use BetaTrait */ + use BetaTrait; +} +PHP; + + StreamWrapper::transformSource($source, 'VirtualMultiNsEnumTrait.php'); + + $enumDocs = SpecialTypeResolver::getClassTraitUseDocs('VirtualMultiNsEnum\Beta\BetaEnum'); + $traitDocs = SpecialTypeResolver::getClassTraitUseDocs('VirtualMultiNsEnum\Beta\BetaTraitHolder'); + + expect($enumDocs)->toHaveCount(1) + ->and($enumDocs[0])->toContain('BetaTrait') + ->and($traitDocs)->toHaveCount(1) + ->and($traitDocs[0])->toContain('BetaTrait') + ; + }); + }); + + describe('2. End-to-End Runtime Resolution in Multi-Namespace Files', function () { + test('resolves use imports and same-namespace classes in the second namespace block at runtime', function () { + $baseTemp = sys_get_temp_dir() . '/typephp_multins_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $filePath = $tempDir . '/multi_ns_runtime.php'; + + $source = <<<'PHP' + [$normDir . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + $first = new \MultiNsRuntime\First\FirstBox(); + $first->pet = new Dog(); + expect($first->pet)->toBeInstanceOf(Dog::class); + + $second = new \MultiNsRuntime\Second\SecondBox(); + $second->pet = new Cat(); + $second->helper = new \MultiNsRuntime\Second\SecondHelper(); + + expect($second->pet)->toBeInstanceOf(Cat::class) + ->and($second->helper)->toBeInstanceOf(\MultiNsRuntime\Second\SecondHelper::class) + ; + + expect(fn () => $second->pet = new Car()) + ->toThrow(TypeError::class, Cat::class) + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('isolates conflicting use aliases across multiple namespaces in the same file', function () { + $baseTemp = sys_get_temp_dir() . '/typephp_multins_alias_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $filePath = $tempDir . '/multi_ns_conflict.php'; + + $source = <<<'PHP' + [$normDir . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + $first = new \MultiNsConflict\First\FirstHolder(); + $first->pet = new Dog(); + expect($first->pet)->toBeInstanceOf(Dog::class); + + expect(fn () => $first->pet = new Cat()) + ->toThrow(TypeError::class, Dog::class) + ; + + $second = new \MultiNsConflict\Second\SecondHolder(); + $second->pet = new Cat(); + expect($second->pet)->toBeInstanceOf(Cat::class); + + expect(fn () => $second->pet = new Dog()) + ->toThrow(TypeError::class, Cat::class) + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('enforces @use generic trait contract on an Enum and nested Trait at runtime', function () { + $baseTemp = sys_get_temp_dir() . '/typephp_enum_trait_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $filePath = $tempDir . '/enum_nested_trait.php'; + + $source = <<<'PHP' + */ + use LeafGenericTrait; +} + +enum ColorCode: string +{ + /** @use MiddleNestedTrait */ + use MiddleNestedTrait; + + case Red = 'red'; +} +PHP; + file_put_contents($filePath, $source); + + try { + $normDir = str_replace('\\', '/', $tempDir); + Config::set([ + 'include' => [$normDir . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + expect(\RuntimeEnumTraitNs\ColorCode::Red->accept(42))->toBe(42); + + expect(fn () => \RuntimeEnumTraitNs\ColorCode::Red->accept(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); +}); From 6a2475104db8cfa467a317ae822dbfd5f4a9790a Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 12:58:10 +0800 Subject: [PATCH 32/37] Refactor FunctionContractInjector to simplify return statement checks; add UnannotatedNativeReturnInjectionTest for verifying native return type injection behavior in standalone classes. --- src/Internal/Ast/FunctionContractInjector.php | 33 +-- .../UnannotatedNativeReturnInjectionTest.php | 237 ++++++++++++++++++ 2 files changed, 238 insertions(+), 32 deletions(-) create mode 100644 tests/Unit/UnannotatedNativeReturnInjectionTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 83b5c7f2..a970d0f9 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -82,8 +82,6 @@ public static function inject( || str_contains($docText, '@phpstan-return') || str_contains($docText, '@psalm-return'); - $hasMethodReturnStatements = self::hasReturnStatements($node); - $hasReturn = ! $isMagicLifecycle && ! $isNativeNever && ! ($isNativeVoid && ! $hasReturnDoc) @@ -92,9 +90,6 @@ public static function inject( $isClassMethod, $hasInheritance, $isPrivate, - $isFinalClass, - $node->returnType !== null, - $hasMethodReturnStatements, $classContext === null, )); @@ -327,9 +322,6 @@ private static function hasReturnContracts( bool $isClassMethod, bool $hasInheritance, bool $isPrivate, - bool $isFinalClass = false, - bool $hasNativeReturnType = false, - bool $hasReturnStatements = false, bool $isDirectUnitTest = false, ): bool { if ($isDirectUnitTest && $isClassMethod) { @@ -365,36 +357,13 @@ private static function hasReturnContracts( return false; } - if ($hasInheritance && ! $isPrivate) { - return true; - } - - if ($isFinalClass) { - return false; - } - - if (! $hasNativeReturnType) { + if (! $hasInheritance) { return false; } return ! $isPrivate; } - private static function hasReturnStatements(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool - { - if ($node->stmts === null || $node->stmts === []) { - return false; - } - - foreach ($node->stmts as $stmt) { - if ($stmt instanceof Node\Stmt\Return_ && $stmt->expr !== null) { - return true; - } - } - - return false; - } - private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_|Node\Stmt\ClassMethod $node): Node\Expr { if (! $isClassMethod) { diff --git a/tests/Unit/UnannotatedNativeReturnInjectionTest.php b/tests/Unit/UnannotatedNativeReturnInjectionTest.php new file mode 100644 index 00000000..603471d4 --- /dev/null +++ b/tests/Unit/UnannotatedNativeReturnInjectionTest.php @@ -0,0 +1,237 @@ +count; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'StandaloneCounter.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('$__typephpRet') + ->and($transformed)->toContain('return $this->count;') + ; + }); + + test('does not inject checkReturn into unannotated methods with nullable or union native return types', function () { + $source = <<<'PHP' +name; + } + + public function getId(): int|string + { + return $this->id; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'StandaloneModels.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->not()->toContain('$__typephpRet') + ; + }); + + test('does not inject checkReturn when standalone method only has @param or summary docblock and native return type', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->not()->toContain('$__typephpRet') + ; + }); + }); + + describe('2. Controls: Explicit @return, Inheritance, and Stubs (Must STILL Inject checkReturn)', function () { + test('injects checkReturn when standalone non-final method has explicit @return docblock', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('injects checkReturn on unannotated method with native return type when class extends, implements, or uses a trait', function () { + $extendsSource = <<<'PHP' +count; + } +} +PHP; + expect(StreamWrapper::transformSource($extendsSource, 'ChildCounter.php')) + ->toContain('RuntimeTypeChecker::checkReturn') + ; + + $implementsSource = <<<'PHP' +count; + } +} +PHP; + expect(StreamWrapper::transformSource($implementsSource, 'ImplCounter.php')) + ->toContain('RuntimeTypeChecker::checkReturn') + ; + + $traitSource = <<<'PHP' +count; + } +} +PHP; + expect(StreamWrapper::transformSource($traitSource, 'TraitCounter.php')) + ->toContain('RuntimeTypeChecker::checkReturn') + ; + }); + + test('injects checkReturn on standalone non-final class when a stub file defines @return for the method', function () { + $tempDir = sys_get_temp_dir() . '/typephp_issue3_stub_' . uniqid(); + mkdir($tempDir, 0777, true); + $stubFile = $tempDir . '/StubbedStandalone.stub'; + + file_put_contents($stubFile, <<<'PHP' + [str_replace('\\', '/', $tempDir) . '/**'], + ]); + + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + } finally { + @unlink($stubFile); + @rmdir($tempDir); + } + }); + }); +}); From 482289001a55deda71b1bb75e804ff10993f77f2 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 13:08:37 +0800 Subject: [PATCH 33/37] Add active call order tracking to TemplateManager and implement tests for re-entrant call stack behavior --- src/Internal/Generics/TemplateManager.php | 44 +++++- .../ReentrantCallStackWideningTest.php | 149 ++++++++++++++++++ 2 files changed, 188 insertions(+), 5 deletions(-) create mode 100644 tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index f74712fa..877a8023 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -58,6 +58,13 @@ final class TemplateManager */ private static array $callStackBindings = []; + /** + * Sequential execution order of active function call frames on the stack. + * + * @var list + */ + private static array $activeCallOrder = []; + /** * Cache for resolved hierarchy templates and variances per class name. * @@ -481,6 +488,7 @@ public static function reset(): void { self::$instanceTemplateBindings = null; self::$callStackBindings = []; + self::$activeCallOrder = []; self::$classHierarchyTemplatesCache = []; self::$declaredVarianceListCache = []; self::$classTemplateDefaultsCache = []; @@ -703,6 +711,7 @@ public static function pushCallFrame(string $function, ?object $thisObj = null): { self::$callStackBindings[$function][] = []; self::$callStackThis[$function][] = $thisObj; + self::$activeCallOrder[] = $function; } /** @@ -718,6 +727,8 @@ public static function popCallFrame(string $function): void if (self::$callStackBindings[$function] === []) { unset(self::$callStackBindings[$function], self::$callStackThis[$function], self::$generatorInferredCallFrames[$function]); } + + self::popActiveCallOrder($function); } else { unset(self::$generatorInferredCallFrames[$function]); } @@ -733,6 +744,24 @@ public static function clearCallBindings(string $function, array $templates, ?ob self::pushCallFrame($function, $thisObj); } + private static function popActiveCallOrder(string $function): void + { + $count = \count(self::$activeCallOrder); + if ($count > 0 && self::$activeCallOrder[$count - 1] === $function) { + array_pop(self::$activeCallOrder); + + return; + } + + for ($i = $count - 2; $i >= 0; $i--) { + if (self::$activeCallOrder[$i] === $function) { + array_splice(self::$activeCallOrder, $i, 1); + + break; + } + } + } + /** * @return object|null */ @@ -1047,6 +1076,7 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ } else { if (! self::hasCallFrame($function)) { self::$callStackBindings[$function][] = []; + self::$activeCallOrder[] = $function; } $lastIndex = \count(self::$callStackBindings[$function]) - 1; self::$callStackBindings[$function][$lastIndex][$templateName] = $inferredType; @@ -1393,11 +1423,15 @@ private static function classTemplateDefaults(string $className): array */ private static function widenClonedBindingsFromActiveCall(object $target, array $bindings): array { - if (self::$callStackBindings === []) { + if (self::$activeCallOrder === []) { + return $bindings; + } + + $activeFunction = end(self::$activeCallOrder); + if ($activeFunction === false) { return $bindings; } - $activeFunction = array_key_last(self::$callStackBindings); $topFrame = self::getTopCallFrame($activeFunction); if ($topFrame === null || $topFrame === []) { return $bindings; @@ -1532,9 +1566,9 @@ private static function bindSingleTemplateArgument( self::$instanceTemplateBindings ??= new WeakMap(); - if (self::$generatorInferredCallFrames !== [] && self::$callStackBindings !== []) { - $activeFunc = array_key_last(self::$callStackBindings); - if ($activeFunc !== null && isset(self::$generatorInferredCallFrames[$activeFunc])) { + if (self::$generatorInferredCallFrames !== [] && self::$activeCallOrder !== []) { + $activeFunc = end(self::$activeCallOrder); + if ($activeFunc !== false && isset(self::$generatorInferredCallFrames[$activeFunc])) { self::markGeneratorInferred($instance); } } diff --git a/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php b/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php new file mode 100644 index 00000000..ac468947 --- /dev/null +++ b/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php @@ -0,0 +1,149 @@ + + */ + public array $elements = []; + + /** + * @param iterable $items + */ + public function __construct(iterable $items = []) + { + foreach ($items as $item) { + $this->elements[] = $item; + } + } + + /** + * @param E $element + */ + public function add(mixed $element): void + { + $this->elements[] = $element; + } +} + +/** + * An immutable collection with a type-widening method: addWidened(). + * + * @template E + */ +class ReentrantCollection +{ + /** + * @param ReentrantStore $store + */ + public function __construct(public ReentrantStore $store) + { + } + + /** + * Widens E to E|NE on the cloned internal store. + * + * @template NE + * + * @param NE $element + * @param (callable(): void)|null $interveningAction + * + * @return self + */ + public function addWidened(mixed $element, ?callable $interveningAction = null): self + { + if ($interveningAction !== null) { + $interveningAction(); + } + + $clonedStore = clone $this->store; + $clonedStore->add($element); + + return new self($clonedStore); + } +} + +class InterveningService +{ + /** + * An intermediate call that pushes its own frame onto the call stack. + * + * @template TUnrelated of string + * + * @param TUnrelated $tag + * @param callable(): void $callback + */ + public static function intermediateDispatch(string $tag, callable $callback): void + { + $callback(); + } +} + +describe('Re-entrant Call Stack Order in TemplateManager (Issue 4 Red Phase)', function () { + beforeEach(function () { + Config::reset(); + TemplateManager::reset(); + }); + + afterEach(function () { + Config::reset(); + TemplateManager::reset(); + }); + + test('reproduces array_key_last key ordering bug when a widening method is invoked re-entrantly (A -> B -> A)', function () { + $outerCol = new ReentrantCollection(new ReentrantStore([1, 2])); + $innerCol = new ReentrantCollection(new ReentrantStore([10, 20])); + + $innerResult = null; + + $outerResult = $outerCol->addWidened('outer_string', function () use ($innerCol, &$innerResult) { + InterveningService::intermediateDispatch('test_tag', function () use ($innerCol, &$innerResult) { + $innerResult = $innerCol->addWidened('inner_string'); + }); + }); + + expect($innerResult)->toBeInstanceOf(ReentrantCollection::class) + ->and($innerResult->store->elements)->toBe([10, 20, 'inner_string']) + ->and(TypePHP::getGenericType($innerResult->store))->toBe('(int | string)') + ; + + expect($outerResult)->toBeInstanceOf(ReentrantCollection::class) + ->and($outerResult->store->elements)->toBe([1, 2, 'outer_string']) + ->and(TypePHP::getGenericType($outerResult->store))->toBe('(int | string)') + ; + }); + + test('verifies call stack order reflects true chronological top during re-entrancy', function () { + $ref = new ReflectionClass(TemplateManager::class); + $activeCallProp = $ref->getProperty('activeCallOrder'); + + TemplateManager::pushCallFrame('FuncA'); + TemplateManager::pushCallFrame('FuncB'); + TemplateManager::pushCallFrame('FuncA'); + + expect($activeCallProp->getValue())->toBe(['FuncA', 'FuncB', 'FuncA']); + + TemplateManager::popCallFrame('FuncA'); + expect($activeCallProp->getValue())->toBe(['FuncA', 'FuncB']); + + TemplateManager::popCallFrame('FuncB'); + expect($activeCallProp->getValue())->toBe(['FuncA']); + + TemplateManager::popCallFrame('FuncA'); + expect($activeCallProp->getValue())->toBe([]); + }); +}); From 78e0c2a01aa0c13cb79c829123e080d4ae754009 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 13:17:26 +0800 Subject: [PATCH 34/37] Enhance DocblockNormalizer to support nested angle brackets and callable generics; add comprehensive tests for preservation and normalization of complex types. --- src/Internal/Docblock/DocblockNormalizer.php | 14 ++- .../DocblockNormalizerNestedGenericsTest.php | 87 +++++++++++++++++++ 2 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php diff --git a/src/Internal/Docblock/DocblockNormalizer.php b/src/Internal/Docblock/DocblockNormalizer.php index 6d34c126..328afa0b 100644 --- a/src/Internal/Docblock/DocblockNormalizer.php +++ b/src/Internal/Docblock/DocblockNormalizer.php @@ -75,7 +75,11 @@ static function (array $matches): 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)(<(?>(?:[^<>]+|(?2)))*>)?\s*(\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))(?!\s*:)/i', + '$1$2$3: mixed', + $doc + ) ?? $doc; if (str_contains($doc, ':')) { $doc = self::normalizeNestedCallables($doc); @@ -88,7 +92,11 @@ static function (array $matches): string { if (str_contains($doc, '...')) { $doc = preg_replace('/(\.\.\.\s*)([a-zA-Z0-9_\x80-\xff\\\\]+)\[\]/', '$1<$2>', $doc) ?? $doc; - $doc = preg_replace('/(\.\.\.\s*)(?:list|array)<([^>]+)>/', '$1<$2>', $doc) ?? $doc; + $doc = preg_replace( + '/(\.\.\.\s*)(?:non-empty-list|non-empty-array|list|array)<((?:[^<>]|(?<(?:[^<>]|(?&angles))*>))*)>/', + '$1<$2>', + $doc + ) ?? $doc; } if (str_contains($doc, '$')) { @@ -127,7 +135,7 @@ private static function normalizeNestedCallables(string $doc): string } $remaining = substr($doc, $j); - if (preg_match('/^(callable|Closure|static-closure)\s*\(/i', $remaining) === 1) { + if (preg_match('/^(callable|Closure|static-closure)(?<(?:[^<>]|(?&angles))*>)?\s*\(/i', $remaining) === 1) { $result .= ': ('; $k = $j; diff --git a/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php b/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php new file mode 100644 index 00000000..67b43f3c --- /dev/null +++ b/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php @@ -0,0 +1,87 @@ +)', function () { + test('preserves generic template when auto-completing omitted return type to : mixed', function () { + $doc = '/** @param callable(T) $fn */'; + $normalized = DocblockNormalizer::normalize($doc); + + expect($normalized)->toBe('/** @param callable(T): mixed $fn */'); + + $parsed = DocblockExtractor::parseDocString($normalized); + $tag = DocblockExtractor::getParamTags($parsed)['fn'] ?? null; + expect($tag)->not()->toBeNull() + ->and((string) $tag->type)->toBe('callable(T): mixed') + ; + }); + + test('preserves generic template on Closure with omitted return type', function () { + $doc = '/** @param Closure(T) $fn */'; + $normalized = DocblockNormalizer::normalize($doc); + + expect($normalized)->toBe('/** @param Closure(T): mixed $fn */'); + }); + + test('handles nested angle brackets inside callable template bounds without truncation', function () { + $doc = '/** @param callable>(T) $fn */'; + $normalized = DocblockNormalizer::normalize($doc); + + expect($normalized)->toBe('/** @param callable>(T): mixed $fn */'); + + $parsed = DocblockExtractor::parseDocString($normalized); + $tag = DocblockExtractor::getParamTags($parsed)['fn'] ?? null; + expect($tag)->not()->toBeNull() + ->and((string) $tag->type)->toBe('callable>(T): mixed') + ; + }); + + test('preserves callable(T): R when explicit return type is already present', function () { + $doc = '/** @param callable(T): T $fn */'; + expect(DocblockNormalizer::normalize($doc))->toBe($doc); + }); + + test('normalizes nested curried callable that declares generic templates', function () { + $doc = '/** @param callable(int): callable(T): T $fn */'; + $expected = '/** @param callable(int): (callable(T): T) $fn */'; + + expect(DocblockNormalizer::normalize($doc))->toBe($expected); + }); + }); + + describe('2. Tuple and Shape Spread Normalization with Nested Generics', function () { + test('normalizes ...list> without truncating at inner angle bracket', function () { + $doc = '/** @param array{string, ...list>} $tuple */'; + $normalized = DocblockNormalizer::normalize($doc); + + expect($normalized)->toBe('/** @param array{string, ...>} $tuple */'); + + $parsed = DocblockExtractor::parseDocString($normalized); + $tag = DocblockExtractor::getParamTags($parsed)['tuple'] ?? null; + expect($tag)->not()->toBeNull() + ->and((string) $tag->type)->toBe('array{string, ...>}') + ; + }); + + test('normalizes ...array> without truncating', function () { + $doc = '/** @param array{id: int, ...array>} $payload */'; + $normalized = DocblockNormalizer::normalize($doc); + + expect($normalized)->toBe('/** @param array{id: int, ...>} $payload */'); + }); + + test('normalizes ...non-empty-list and ...non-empty-array spreads', function () { + $docList = '/** @param array{string, ...non-empty-list} $tuple */'; + expect(DocblockNormalizer::normalize($docList))->toBe('/** @param array{string, ...} $tuple */'); + + $docArray = '/** @param array{id: int, ...non-empty-array} $payload */'; + expect(DocblockNormalizer::normalize($docArray))->toBe('/** @param array{id: int, ...} $payload */'); + }); + }); +}); \ No newline at end of file From f4cec529e597bfb9ba187890c3b2ccc1703d7e2a Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 14:47:08 +0800 Subject: [PATCH 35/37] fix code styling --- .../Internal/Docblock/DocblockNormalizerNestedGenericsTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php b/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php index 67b43f3c..e6138d57 100644 --- a/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php +++ b/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php @@ -84,4 +84,4 @@ expect(DocblockNormalizer::normalize($docArray))->toBe('/** @param array{id: int, ...} $payload */'); }); }); -}); \ No newline at end of file +}); From 87fd29f6dad22ae209cb0f7d1bfd09d4746b9d73 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 15:08:13 +0800 Subject: [PATCH 36/37] Enhance ReportCommand output to include detailed report file information and summary statistics for violations and affected files. --- src/Internal/Cli/ReportCommand.php | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/Internal/Cli/ReportCommand.php b/src/Internal/Cli/ReportCommand.php index f8f2cf41..4dbeebc1 100644 --- a/src/Internal/Cli/ReportCommand.php +++ b/src/Internal/Cli/ReportCommand.php @@ -71,6 +71,7 @@ public function execute(array $args, $outputStream = STDOUT, $errorStream = STDE if ($projectRoot !== null) { fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Project Root: ' . $c($projectRoot, 'gray') . "\n"); } + fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Report File: ' . $c($relativeReportPath, 'gray') . "\n"); fwrite($outputStream, "\n " . $c('✗', 'red') . " 0 violations over 0 instrumented files. Check your 'include'/'exclude' paths in typephp.php.\n\n"); return 1; @@ -82,6 +83,7 @@ public function execute(array $args, $outputStream = STDOUT, $errorStream = STDE if ($configSource !== null) { fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Config Source: ' . $c($configSource, 'gray') . "\n"); } + fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Report File: ' . $c($relativeReportPath, 'gray') . "\n"); fwrite($outputStream, "\n " . $c('✓', 'green') . " Clean run: No type violations found across {$filesInstrumented} instrumented file(s).\n\n"); return 0; @@ -108,15 +110,7 @@ public function execute(array $args, $outputStream = STDOUT, $errorStream = STDE ? $data['summary']['files_affected'] : \count($filesAffectedMap); - fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Total Violations: ' . $c((string) $totalCount, 'bold') . "\n"); - fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Files Affected: ' . $c((string) $filesAffected, 'bold') . "\n"); - if ($filesInstrumented !== null) { - fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Files Instrumented: ' . $c((string) $filesInstrumented, 'bold') . "\n"); - } - if ($configSource !== null) { - fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Config Source: ' . $c($configSource, 'gray') . "\n"); - } - fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Report File: ' . $c($relativeReportPath, 'gray') . "\n\n"); + fwrite($outputStream, ' ' . $c('Report Source:', 'gray') . ' ' . $c($relativeReportPath, 'gray') . "\n\n"); foreach ($grouped as $file => $items) { fwrite($outputStream, ' ' . $c($file, 'bold') . "\n"); @@ -150,6 +144,16 @@ public function execute(array $args, $outputStream = STDOUT, $errorStream = STDE fwrite($outputStream, "\n"); } + fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Total Violations: ' . $c((string) $totalCount, 'bold') . "\n"); + fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Files Affected: ' . $c((string) $filesAffected, 'bold') . "\n"); + if ($filesInstrumented !== null) { + fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Files Instrumented: ' . $c((string) $filesInstrumented, 'bold') . "\n"); + } + if ($configSource !== null) { + fwrite($outputStream, ' ' . $c('•', 'cyan') . ' Config Source: ' . $c($configSource, 'gray') . "\n"); + } + fwrite($outputStream, "\n"); + return 1; } -} +} \ No newline at end of file From 6f18aa8f07a4de553b1d055e00e557f76cee7c83 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 16 Nov 2026 15:08:25 +0800 Subject: [PATCH 37/37] Fix missing newline at end of file in ReportCommand.php --- src/Internal/Cli/ReportCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Internal/Cli/ReportCommand.php b/src/Internal/Cli/ReportCommand.php index 4dbeebc1..97191205 100644 --- a/src/Internal/Cli/ReportCommand.php +++ b/src/Internal/Cli/ReportCommand.php @@ -156,4 +156,4 @@ public function execute(array $args, $outputStream = STDOUT, $errorStream = STDE return 1; } -} \ No newline at end of file +}