From c7c30c771312b5022096cd6a89f94236e80579ea Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 6 Dec 2026 00:52:47 +0800 Subject: [PATCH 1/3] Add support for generic type alias --- composer.json | 2 +- src/Internal/Ast/ContractVisitor.php | 133 +++- src/Internal/Ast/FunctionContractInjector.php | 36 +- src/Internal/Checker/GeneratorChecker.php | 8 +- src/Internal/Checker/InlineChecker.php | 105 ++- src/Internal/Checker/MemberAssignChecker.php | 10 +- src/Internal/Checker/ParamChecker.php | 14 +- src/Internal/Checker/ReturnChecker.php | 8 +- src/Internal/Docblock/DocblockExtractor.php | 169 ++++- src/Internal/Docblock/DocblockParser.php | 366 +++++++-- src/Internal/Docblock/GenericTypeAlias.php | 35 + src/Internal/Generics/TemplateSubstitutor.php | 128 +++- src/Internal/Resolver/SpecialTypeResolver.php | 265 ++++--- src/Internal/Wrapper/CallableWrapper.php | 6 +- src/Internal/Wrapper/IterableWrapper.php | 21 +- .../Internal/Docblock/DocblockParserTest.php | 58 ++ .../Generics/GenericTypeAliasTest.php | 716 ++++++++++++++++++ 17 files changed, 1752 insertions(+), 328 deletions(-) create mode 100644 src/Internal/Docblock/GenericTypeAlias.php create mode 100644 tests/TypeChecking/Generics/GenericTypeAliasTest.php diff --git a/composer.json b/composer.json index 9d446650..dbb3534f 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,7 @@ ], "require": { "php": "^8.1", - "phpstan/phpdoc-parser": "^2.3", + "phpstan/phpdoc-parser": "^2.6", "nikic/php-parser": "^5.3" }, "require-dev": { diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 474fea39..59e292d2 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -20,6 +20,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; +use PHPStan\PhpDocParser\Ast\Type\InvalidTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -29,6 +30,7 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\ClassNameValidator; @@ -100,7 +102,7 @@ final class ContractVisitor extends NodeVisitorAbstract /** * In-memory cache of class-level aliases resolved from AST without invoking PHP autoloading. * - * @var array> + * @var array> */ private static array $astClassAliasesCache = []; @@ -115,7 +117,7 @@ public static function reset(): void private array $localClassPropertyTypes = []; /** - * @var array> + * @var array> */ private array $localClassAliases = []; @@ -124,7 +126,7 @@ public static function reset(): void private string $currentNamespace = ''; /** - * @var list, templates?: array, unannotatedProps?: array}> + * @var list, templates?: array, unannotatedProps?: array}> */ private array $classStack = []; @@ -1307,14 +1309,14 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ * Extracts class-level and inherited @phpstan-type / @psalm-type / @phpstan-import-type aliases at AST transform time * without invoking PHP's autoloader/compiler. * - * @return array + * @return array */ private function extractClassLikeAliases( Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\Trait_|Node\Stmt\Enum_ $node, ?\PhpParser\Comment\Doc $doc, ?string $typeName ): array { - /** @var array $aliases */ + /** @var array $aliases */ $aliases = []; $visited = $typeName !== null ? [$typeName => true] : []; @@ -1367,9 +1369,7 @@ private function extractClassLikeAliases( } } - foreach ($aliases as $aName => $aType) { - $aliases[$aName] = DocblockParser::substituteAliases($aType, $aliases, [$aName => true]); - } + $aliases = self::finalizeAstAliases($aliases); if ($typeName !== null && $aliases !== []) { $this->localClassAliases[$typeName] = $aliases; @@ -1379,7 +1379,7 @@ private function extractClassLikeAliases( } /** - * @param array $aliases + * @param array $aliases * @param array $visited */ private function collectAliasesFromPhpDocInFile( @@ -1390,14 +1390,14 @@ private function collectAliasesFromPhpDocInFile( array $visited ): void { foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $aliases[$tag->value->alias] = DocblockExtractor::buildAliasEntry($tag->value); } } foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $aliases[$tag->value->alias] = DocblockExtractor::buildAliasEntry($tag->value); } } @@ -1428,10 +1428,10 @@ private function collectAliasesFromPhpDocInFile( /** * Resolves class-level aliases for an FQCN without invoking PHP autoloading/compilation. * - * @param array> $localClassAliases + * @param array> $localClassAliases * @param array $visited * - * @return array + * @return array */ public static function resolveClassAliasesNoAutoload( string $fqcn, @@ -1540,10 +1540,10 @@ public static function findClassFileWithoutAutoload(string $fqcn): ?string /** * @param array $stmts - * @param array> $localClassAliases + * @param array> $localClassAliases * @param array $visited * - * @return array + * @return array */ private static function extractTargetClassAliasesFromStmts( array $stmts, @@ -1571,10 +1571,10 @@ private static function extractTargetClassAliasesFromStmts( /** * @param array $stmts * @param array $imports - * @param array> $localClassAliases + * @param array> $localClassAliases * @param array $visited * - * @return array|null + * @return array|null */ private static function scanClassLikesForAliases( array $stmts, @@ -1653,23 +1653,16 @@ private static function scanClassLikesForAliases( } } - foreach ($aliases as $aName => $aType) { - $substituted = DocblockParser::substituteAliases($aType, $aliases, [$aName => true]); - $aliases[$aName] = $filePath !== '' - ? SpecialTypeResolver::resolveForFile($substituted, $filePath, $namespace, false) - : $substituted; - } - - return $aliases; + return self::finalizeAstAliases($aliases, $filePath, $namespace); } return null; } /** - * @param array $aliases + * @param array $aliases * @param array $imports - * @param array> $localClassAliases + * @param array> $localClassAliases * @param array $visited */ private static function collectRawAliasesFromAstDoc( @@ -1682,14 +1675,14 @@ private static function collectRawAliasesFromAstDoc( array $visited ): void { foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $aliases[$tag->value->alias] = DocblockExtractor::buildAliasEntry($tag->value); } } foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $aliases[$tag->value->alias] = DocblockExtractor::buildAliasEntry($tag->value); } } @@ -1719,10 +1712,82 @@ private static function collectRawAliasesFromAstDoc( } if ($filePath !== '') { + /** @var array $allAliasNames */ + $allAliasNames = []; + foreach (array_keys($aliases) as $k) { + $allAliasNames[$k] = true; + } + foreach ($aliases as $aName => $aType) { - $aliases[$aName] = SpecialTypeResolver::resolveForFile($aType, $filePath, $namespace, false); + if ($aType instanceof GenericTypeAlias) { + $localTemplateNames = []; + foreach ($aType->templateTypes as $tTag) { + $localTemplateNames[$tTag->name] = true; + } + $ignoredForBody = [...$allAliasNames, ...$localTemplateNames]; + $resolvedTemplates = []; + $declaredSoFar = []; + foreach ($aType->templateTypes as $tTag) { + $ignoredForParam = [...$allAliasNames, ...$declaredSoFar, $tTag->name => true]; + $bound = $tTag->bound !== null ? SpecialTypeResolver::resolveForFile($tTag->bound, $filePath, $namespace, false, $ignoredForParam) : null; + $default = $tTag->default !== null ? SpecialTypeResolver::resolveForFile($tTag->default, $filePath, $namespace, false, $ignoredForParam) : null; + $lowerBound = $tTag->lowerBound !== null ? SpecialTypeResolver::resolveForFile($tTag->lowerBound, $filePath, $namespace, false, $ignoredForParam) : null; + $declaredSoFar[$tTag->name] = true; + $resolvedTemplates[] = new TemplateTagValueNode($tTag->name, $bound, $tTag->description, $default, $lowerBound); + } + $resolvedBody = SpecialTypeResolver::resolveForFile($aType->type, $filePath, $namespace, false, $ignoredForBody); + $aliases[$aName] = new GenericTypeAlias($resolvedBody, $resolvedTemplates, $aType->originalName ?? $aName); + } else { + $aliases[$aName] = SpecialTypeResolver::resolveForFile($aType, $filePath, $namespace, false); + } + } + } + } + + /** + * Wires generic alias scopes, expands plain aliases, and pre-expands plain references + * inside generic alias bodies while preserving local template parameters. + * + * @param array $aliases + * + * @return array + */ + private static function finalizeAstAliases(array $aliases, string $filePath = '', string $namespace = ''): array + { + DocblockExtractor::wireGenericAliasScopes($aliases); + + /** @var array $plainScopeAliases */ + $plainScopeAliases = []; + foreach ($aliases as $aName => $aType) { + if ($aType instanceof TypeNode) { + $plainScopeAliases[$aName] = $aType; } } + + foreach ($aliases as $aName => $aType) { + if ($aType instanceof GenericTypeAlias) { + $localTemplateNames = []; + foreach ($aType->templateTypes as $tTag) { + $localTemplateNames[$tTag->name] = true; + } + $scopedPlain = array_diff_key($plainScopeAliases, $localTemplateNames); + if ($scopedPlain !== []) { + $expandedBody = DocblockParser::substituteAliases($aType->type, $scopedPlain, [$aName => true]); + $aliases[$aName] = new GenericTypeAlias($expandedBody, $aType->templateTypes, $aType->originalName ?? $aName); + } + + continue; + } + + $substituted = DocblockParser::substituteAliases($aType, $aliases, [$aName => true]); + $aliases[$aName] = $filePath !== '' + ? SpecialTypeResolver::resolveForFile($substituted, $filePath, $namespace, false) + : $substituted; + } + + DocblockExtractor::wireGenericAliasScopes($aliases); + + return $aliases; } /** diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 6ce8c51a..b6189e84 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -19,6 +19,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; +use PHPStan\PhpDocParser\Ast\Type\InvalidTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -31,6 +32,7 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\Config; @@ -55,7 +57,7 @@ final class FunctionContractInjector ]; /** - * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool, aliases?: array, templates?: array}|null $classContext + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool, aliases?: array, templates?: array}|null $classContext */ public static function inject( Node\Stmt\Function_|Node\Stmt\ClassMethod $node, @@ -1503,9 +1505,9 @@ private static function typeNodeContainsIterable(TypeNode $node, array $template } /** - * @param array $baseAliases + * @param array $baseAliases * - * @return array + * @return array */ private static function mergeDocblockAliases( PhpDocNode $phpDocNode, @@ -1516,14 +1518,14 @@ private static function mergeDocblockAliases( $aliases = $baseAliases; foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $aliases[$tag->value->alias] = DocblockExtractor::buildAliasEntry($tag->value); } } foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $aliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $aliases[$tag->value->alias] = DocblockExtractor::buildAliasEntry($tag->value); } } @@ -1566,7 +1568,13 @@ private static function mergeDocblockAliases( } } + DocblockExtractor::wireGenericAliasScopes($aliases); + foreach ($aliases as $name => $type) { + if (! ($type instanceof TypeNode)) { + continue; + } + $substituted = DocblockParser::substituteAliases($type, $aliases, [$name => true]); if ( $substituted instanceof IdentifierTypeNode @@ -1578,7 +1586,9 @@ private static function mergeDocblockAliases( } foreach ($aliases as $name => $type) { - $aliases[$name] = DocblockParser::bindRecursiveAliases($type, $aliases); + if ($type instanceof TypeNode) { + $aliases[$name] = DocblockParser::bindRecursiveAliases($type, $aliases); + } } return $aliases; @@ -1820,7 +1830,7 @@ public static function buildWrappedYieldNode( * Determines whether a Return_ node already wrapped by ContractVisitor::handleReturn() * safely subsumes the enclosing function/generator return contract. * - * @param array $effectiveAliases + * @param array $effectiveAliases */ public static function inlineVarSubsumesReturn( Node\Stmt\Return_ $returnNode, @@ -1891,7 +1901,7 @@ public static function inlineVarSubsumesReturn( * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * @param array $byRefParams * @param array $trustedParamTypes - * @param array $effectiveAliases + * @param array $effectiveAliases * * @return array */ @@ -1948,7 +1958,7 @@ private static function wrapGeneratorReturns( * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $explicitGenContract * @param array $byRefParams * @param array $trustedParamTypes - * @param array $effectiveAliases + * @param array $effectiveAliases */ public function __construct( private Node\Expr $thisArg, @@ -2208,7 +2218,7 @@ public function enterNode(Node $n): int|Node|array|null * @param array $byRefParams * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * @param array $trustedParamTypes - * @param array $effectiveAliases + * @param array $effectiveAliases * * @return array */ @@ -2258,7 +2268,7 @@ private static function wrapNonGeneratorReturns( * @param array $byRefParams * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * @param array $trustedParamTypes - * @param array $effectiveAliases + * @param array $effectiveAliases */ public function __construct( private Node\Expr $thisArg, diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 9f08b15f..6a247d1d 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -14,6 +14,7 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Resolver\SpecialTypeResolver; @@ -97,7 +98,7 @@ final class GeneratorChecker * @var array, - * aliases: array, + * aliases: array, * hasGenerics: bool, * hasMethodTemplates: bool, * hasAliases: bool, @@ -426,7 +427,10 @@ private static function resolveYieldAndSendTypes( } if ($returnTypeNode instanceof IdentifierTypeNode && isset($aliases[$returnTypeNode->name])) { - $returnTypeNode = $aliases[$returnTypeNode->name]; + $aliasEntry = $aliases[$returnTypeNode->name]; + $returnTypeNode = $aliasEntry instanceof GenericTypeAlias + ? DocblockParser::substituteAliases($returnTypeNode, $aliases) + : $aliasEntry; } if ($plan['hasConditionals'] && $registry !== null) { diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 10669bfe..4241bf27 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -310,6 +310,10 @@ public static function checkVariable( /** * Directly validates a mutated collection element in O(1) for hybrid validation mode. * + * Returns ErrorMessage on violation, true when directly validated OK, + * or false when the resolved type (e.g. ArrayShapeNode, UnionTypeNode) must fall back + * to prospective whole-structure validation. + * * @param list $path */ public static function validateCollectionElementMutation( @@ -321,9 +325,9 @@ public static function validateCollectionElementMutation( TypeValidatorRegistry $registry, ?string $caller = null, mixed $thisOrClass = null - ): ?ErrorMessage { + ): ErrorMessage|bool { if (\count($path) !== 1 || $path[0][0] !== 'dim') { - return null; + return false; } try { @@ -363,8 +367,10 @@ public static function validateCollectionElementMutation( if ($aaContract['valueType'] !== null) { $context = "Variable \${$varName}" . ($key !== null ? "['{$keyStr}']" : '[]'); - return $registry->validate($value, $aaContract['valueType'], $context); + return $registry->validate($value, $aaContract['valueType'], $context) ?? true; } + + return true; } if ($typeNode instanceof GenericTypeNode) { @@ -379,9 +385,13 @@ public static function validateCollectionElementMutation( if ($valueType !== null) { $context = "Variable \${$varName}" . ($key !== null ? "[{$key}]" : '[]'); - return $registry->validate($value, $valueType, $context); + return $registry->validate($value, $valueType, $context) ?? true; } - } else { + + return true; + } + + if (isset(self::ARRAY_TYPES[$base])) { $genericCount = \count($typeNode->genericTypes); if ($genericCount >= 2 && $key !== null) { @@ -399,20 +409,26 @@ public static function validateCollectionElementMutation( if ($valueType !== null) { $context = "Variable \${$varName}" . ($key !== null ? "['{$keyStr}']" : '[]'); - return $registry->validate($value, $valueType, $context); + return $registry->validate($value, $valueType, $context) ?? true; } + + return true; } - } elseif ($typeNode instanceof ArrayTypeNode) { + + return false; + } + + if ($typeNode instanceof ArrayTypeNode) { $context = "Variable \${$varName}" . ($key !== null ? "[{$keyStr}]" : '[]'); - return $registry->validate($value, $typeNode->type, $context); + return $registry->validate($value, $typeNode->type, $context) ?? true; } } catch (\Throwable $e) { DebugLog::swallowed($e); // @codeCoverageIgnore // Silently fall back to prospective whole-structure validation } - return null; + return false; } private static function extractNamespaceFromCaller(?string $caller): ?string @@ -807,18 +823,21 @@ private static function resolveFunctionContextWithFallback(TypeNode $typeNode, s try { $refFunc = new \ReflectionFunction($functionName); - $typeNode = SpecialTypeResolver::resolve($typeNode, $refFunc); $contract = DocblockParser::parse($functionName); $declaredTemplates = $contract['templates'] ?? []; $aliases = $contract['aliases'] ?? []; - $boundTemplates = TemplateManager::getBoundTemplates($functionName, null, $declaredTemplates); - $activeBindings = [...$aliases, ...$boundTemplates]; + if ($aliases !== []) { + $typeNode = DocblockParser::substituteAliases($typeNode, $aliases, [], $refFunc); + } - if (\count($activeBindings) > 0 || \count($declaredTemplates) > 0) { - $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $activeBindings, $declaredTemplates); - $typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $declaredTemplates); + $typeNode = SpecialTypeResolver::resolve($typeNode, $refFunc); + $boundTemplates = TemplateManager::getBoundTemplates($functionName, null, $declaredTemplates); + + if (\count($boundTemplates) > 0 || \count($declaredTemplates) > 0) { + $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $boundTemplates, $declaredTemplates); + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); $typeNode = SpecialTypeResolver::resolve($typeNode, $refFunc); } } catch (\ReflectionException $e) { @@ -874,13 +893,17 @@ private static function resolveClassContextWithFallback( try { /** @var class-string $className */ $refClass = new \ReflectionClass($className); - $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); - $classAliases = DocblockParser::parseClassAliases($className); $allTemplates = $contract['allTemplates'] ?? [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; $declaredTemplates = $allTemplates; - if ($classAliases === [] && $declaredTemplates === []) { + if ($classAliases !== []) { + $typeNode = DocblockParser::substituteAliases($typeNode, $classAliases, [], $refClass); + } + + $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); + + if ($declaredTemplates === []) { $result = [$typeNode, [0, []]]; if ($canCache && $typeString !== null) { return self::$resolvedClassContextCache[$className][$methodKey][$typeString] = $result; @@ -890,17 +913,13 @@ private static function resolveClassContextWithFallback( } $boundTemplates = TemplateManager::getBoundTemplates($targetFunc, $thisObj, $declaredTemplates); - $activeBindings = [...$classAliases, ...$boundTemplates]; - - if ($activeBindings !== [] || $declaredTemplates !== []) { - $thisFallbackKeys = $thisObj !== null ? TemplateManager::getFallbackBoundTemplates($thisObj) : []; - $concreteBindings = $thisFallbackKeys !== [] - ? array_diff_key($activeBindings, $thisFallbackKeys) - : $activeBindings; - $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $concreteBindings, $declaredTemplates); - $typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $declaredTemplates); - $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); - } + $thisFallbackKeys = $thisObj !== null ? TemplateManager::getFallbackBoundTemplates($thisObj) : []; + $concreteBindings = $thisFallbackKeys !== [] + ? array_diff_key($boundTemplates, $thisFallbackKeys) + : $boundTemplates; + $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $concreteBindings, $declaredTemplates); + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); + $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); } catch (\ReflectionException $e) { DebugLog::swallowed($e); // @codeCoverageIgnore // Silently continue if reflection fails @@ -1007,21 +1026,23 @@ private static function substituteStaticPropertyGenerics(TypeNode $typeNode, str $classBindings = TemplateManager::getClassInheritedBindings($className); $classAliases = DocblockParser::parseClassAliases($className); - $activeBindings = [...$classAliases, ...$classBindings]; - if (\count($activeBindings) > 0 || \count($allTemplates) > 0) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $allTemplates); + $refClass = null; + if (class_exists($className, false) || class_exists($className) || interface_exists($className) || trait_exists($className)) { + /** @var class-string $className */ + $refClass = new \ReflectionClass($className); + } - if (class_exists($className, false) || class_exists($className) || interface_exists($className) || trait_exists($className)) { - try { - /** @var class-string $className */ - $refClass = new \ReflectionClass($className); - $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); - } catch (\ReflectionException $e) { - DebugLog::swallowed($e); // @codeCoverageIgnore - // Silently continue if reflection fails - } - } + if ($classAliases !== []) { + $typeNode = DocblockParser::substituteAliases($typeNode, $classAliases, [], $refClass); + } + + if (\count($classBindings) > 0 || \count($allTemplates) > 0) { + $typeNode = TemplateSubstitutor::substitute($typeNode, $classBindings, $allTemplates); + } + + if ($refClass !== null) { + $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); } return self::$resolvedStaticPropertyTypeCache[$className][$propName] = $typeNode; diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 9b4259c3..0cdfd40d 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -213,7 +213,7 @@ public static function check( && \count($chain) === 1 && $chain[0][0] === 'dim' ) { - $directErr = InlineChecker::validateCollectionElementMutation( + $directRes = InlineChecker::validateCollectionElementMutation( $value, $chain, $typeString, @@ -224,11 +224,13 @@ public static function check( $thisOrClass ); - if ($directErr instanceof ErrorMessage) { - return $directErr; + if ($directRes instanceof ErrorMessage) { + return $directRes; } - return $value; + if ($directRes === true) { + return $value; + } } if ($isObjectDimAccess) { diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 96b3a692..022d501a 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -22,6 +22,7 @@ use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Resolver\HierarchyResolver; @@ -550,7 +551,7 @@ private static function prepareGenericBindings( * Pre‑resolves and caches base types for each parameter using zero-allocation 2D lookup. * * @param array $types - * @param array $aliases + * @param array $aliases * * @return array */ @@ -582,7 +583,10 @@ private static function resolveBaseTypes( } if ($typeNode instanceof IdentifierTypeNode && isset($aliases[$typeNode->name])) { - $typeNode = $aliases[$typeNode->name]; + $aliasEntry = $aliases[$typeNode->name]; + $typeNode = $aliasEntry instanceof GenericTypeAlias + ? DocblockParser::substituteAliases($typeNode, $aliases) + : $aliasEntry; } $resolved = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); @@ -604,7 +608,7 @@ private static function resolveBaseTypes( * @param array $baseTypes * @param array $vars * @param array $allTemplates - * @param array $aliases + * @param array $aliases * @param array $boundTemplates * @param array $declaredTemplates * @param array $classTemplates @@ -2512,7 +2516,7 @@ private static function traversablePlan(object $value): ?array * Unified single-parameter validation pipeline. * * @param array $templates - * @param array $aliases + * @param array $aliases * @param array $boundTemplates * @param array $declaredTemplates * @param array $classTemplates @@ -2632,7 +2636,7 @@ private static function validateSingleParam( } /** - * @param array{return: ?TypeNode, parameters: array, aliases: array, templates: array} $magicContract + * @param array{return: ?TypeNode, parameters: array, aliases: array, templates: array} $magicContract * @param array $args */ private static function validateMagicArguments( diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index b9c8c3f4..42a0cb67 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -13,6 +13,7 @@ use Traversable; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Resolver\SpecialTypeResolver; @@ -352,7 +353,7 @@ private static function handleMagicReturn( * Unified return value validation pipeline. * * @param array $vars - * @param array $aliases + * @param array $aliases * @param array $templates * @param FunctionContract|array{} $contract */ @@ -478,7 +479,10 @@ private static function evaluateReturn( : $returnTypeNode; if ($resolvedType instanceof IdentifierTypeNode && isset($aliases[$resolvedType->name])) { - $resolvedType = $aliases[$resolvedType->name]; + $aliasEntry = $aliases[$resolvedType->name]; + $resolvedType = $aliasEntry instanceof GenericTypeAlias + ? DocblockParser::substituteAliases($resolvedType, $aliases) + : $aliasEntry; } if ($hasConditionals || (! ($resolvedType instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($resolvedType))) { diff --git a/src/Internal/Docblock/DocblockExtractor.php b/src/Internal/Docblock/DocblockExtractor.php index 523b7494..dae587ca 100644 --- a/src/Internal/Docblock/DocblockExtractor.php +++ b/src/Internal/Docblock/DocblockExtractor.php @@ -15,6 +15,7 @@ use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode; use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode; +use PHPStan\PhpDocParser\Ast\Type\InvalidTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Lexer\Lexer; use PHPStan\PhpDocParser\Parser\ConstExprParser; @@ -553,9 +554,10 @@ public static function extractVarTagFromDoc(string $doc): ?array /** * Extracts local and imported type aliases (@phpstan-type/@psalm-type and @phpstan-import-type/@psalm-import-type) from a PHPDoc node. + * Supports both plain aliases (TypeNode) and generic aliases (GenericTypeAlias). * Prioritizes @phpstan-* > @psalm-* within the same docblock, and child class overrides over parent classes across inheritance. * - * @param array $aliases + * @param array $aliases * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref */ public static function extractAliases( @@ -563,22 +565,22 @@ public static function extractAliases( array &$aliases, \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref ): void { - /** @var array $currentDocAliases */ + /** @var array $currentDocAliases */ $currentDocAliases = []; foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $currentDocAliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $currentDocAliases[$tag->value->alias] = self::buildAliasEntry($tag->value); } } foreach ($phpDocNode->getTagsByName('@phpstan-type') as $tag) { - if ($tag->value instanceof TypeAliasTagValueNode) { - $currentDocAliases[$tag->value->alias] = $tag->value->type; + if ($tag->value instanceof TypeAliasTagValueNode && ! ($tag->value->type instanceof InvalidTypeNode)) { + $currentDocAliases[$tag->value->alias] = self::buildAliasEntry($tag->value); } } - /** @var array $currentDocImports */ + /** @var array $currentDocImports */ $currentDocImports = []; $importTags = [ ...$phpDocNode->getTagsByName('@psalm-import-type'), @@ -600,23 +602,112 @@ public static function extractAliases( } } - $docScopeAliases = [...$currentDocImports, ...$currentDocAliases]; - foreach ($currentDocAliases as $name => $type) { - $currentDocAliases[$name] = DocblockParser::substituteAliases($type, $docScopeAliases, [$name => true]); + /** @var array $allAliasNames */ + $allAliasNames = []; + foreach (array_keys($aliases) as $k) { + $allAliasNames[$k] = true; + } + foreach (array_keys($currentDocImports) as $k) { + $allAliasNames[$k] = true; + } + foreach (array_keys($currentDocAliases) as $k) { + $allAliasNames[$k] = true; + } + + /** @var array $plainScopeAliases */ + $plainScopeAliases = []; + foreach ([...$aliases, ...$currentDocImports, ...$currentDocAliases] as $k => $v) { + if ($v instanceof TypeNode) { + $plainScopeAliases[$k] = $v; + } + } + + // Pass 1: Resolve generic alias definitions (expanding plain aliases in bounds/defaults/body while preserving generic references) + foreach ($currentDocAliases as $name => $entry) { + if (! ($entry instanceof GenericTypeAlias)) { + continue; + } + + /** @var array $localTemplateNames */ + $localTemplateNames = []; + foreach ($entry->templateTypes as $tTag) { + $localTemplateNames[$tTag->name] = true; + } + + $ignoredForBody = [...$allAliasNames, ...$localTemplateNames]; + $scopedPlain = array_diff_key($plainScopeAliases, $localTemplateNames); + + $resolvedTemplateTypes = []; + /** @var array $declaredSoFar */ + $declaredSoFar = []; + foreach ($entry->templateTypes as $tTag) { + $ignoredForParam = [...$allAliasNames, ...$declaredSoFar, $tTag->name => true]; + $paramPlainScope = array_diff_key($plainScopeAliases, $declaredSoFar, [$tTag->name => true]); + + $bound = $tTag->bound; + if ($bound !== null) { + if ($paramPlainScope !== []) { + $bound = DocblockParser::substituteAliases($bound, $paramPlainScope, [], $ref); + } + $bound = SpecialTypeResolver::resolve($bound, $ref, null, $ignoredForParam); + } + + $default = $tTag->default; + if ($default !== null) { + if ($paramPlainScope !== []) { + $default = DocblockParser::substituteAliases($default, $paramPlainScope, [], $ref); + } + $default = SpecialTypeResolver::resolve($default, $ref, null, $ignoredForParam); + } + + $lowerBound = $tTag->lowerBound; + if ($lowerBound !== null) { + if ($paramPlainScope !== []) { + $lowerBound = DocblockParser::substituteAliases($lowerBound, $paramPlainScope, [], $ref); + } + $lowerBound = SpecialTypeResolver::resolve($lowerBound, $ref, null, $ignoredForParam); + } + + $declaredSoFar[$tTag->name] = true; + $resolvedTemplateTypes[] = new TemplateTagValueNode($tTag->name, $bound, $tTag->description, $default, $lowerBound); + } + + $body = $scopedPlain !== [] + ? DocblockParser::substituteAliases($entry->type, $scopedPlain, [$name => true], $ref) + : $entry->type; + $body = SpecialTypeResolver::resolve($body, $ref, null, $ignoredForBody); + + $currentDocAliases[$name] = new GenericTypeAlias($body, $resolvedTemplateTypes, $entry->originalName ?? $name); } - foreach ($currentDocAliases as $name => $type) { - $currentDocAliases[$name] = SpecialTypeResolver::resolve($type, $ref); + // Wire sibling generic alias scopes so imported/mutually recursive generic aliases can resolve each other + $docScopeAliases = [...$aliases, ...$currentDocImports, ...$currentDocAliases]; + self::wireGenericAliasScopes($docScopeAliases); + + // Pass 2: Expand and resolve plain aliases (which may instantiate generic aliases like `IntPair = Pair`) + foreach ($currentDocAliases as $name => $entry) { + if (! ($entry instanceof TypeNode)) { + continue; + } + + $expanded = DocblockParser::substituteAliases($entry, $docScopeAliases, [$name => true], $ref); + $currentDocAliases[$name] = SpecialTypeResolver::resolve($expanded, $ref); } - foreach ([...$currentDocImports, ...$currentDocAliases] as $name => $type) { + foreach ([...$currentDocImports, ...$currentDocAliases] as $name => $entry) { if (! isset($aliases[$name])) { - $aliases[$name] = $type; + $aliases[$name] = $entry; } } - foreach ($aliases as $name => $type) { - $substituted = DocblockParser::substituteAliases($type, $aliases, [$name => true]); + self::wireGenericAliasScopes($aliases); + + foreach ($aliases as $name => $entry) { + if (! ($entry instanceof TypeNode)) { + continue; + } + + $substituted = DocblockParser::substituteAliases($entry, $aliases, [$name => true], $ref); if ( $substituted instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode && $substituted->getAttribute('typephp_recursive_alias_name') !== null @@ -626,15 +717,55 @@ public static function extractAliases( $aliases[$name] = $substituted; } - foreach ($aliases as $name => $type) { - $aliases[$name] = DocblockParser::bindRecursiveAliases($type, $aliases); + foreach ($aliases as $name => $entry) { + if ($entry instanceof TypeNode) { + $aliases[$name] = DocblockParser::bindRecursiveAliases($entry, $aliases); + } + } + } + + public static function buildAliasEntry(TypeAliasTagValueNode $tag): TypeNode|GenericTypeAlias + { + if ($tag->templateTypes === []) { + return $tag->type; + } + + return new GenericTypeAlias($tag->type, array_values($tag->templateTypes), $tag->alias); + } + + /** + * Links sibling GenericTypeAlias instances within the same declaration scope + * so imported or mutually recursive generic aliases stay self-contained. + * + * @param array $aliases + */ + public static function wireGenericAliasScopes(array $aliases): void + { + /** @var array $generics */ + $generics = []; + foreach ($aliases as $name => $entry) { + if ($entry instanceof GenericTypeAlias) { + $generics[$name] = $entry; + } + } + + if (\count($generics) <= 1) { + return; + } + + foreach ($generics as $name => $entry) { + $siblings = $generics; + unset($siblings[$name]); + $entry->scopeAliases = $entry->scopeAliases !== [] + ? [...$entry->scopeAliases, ...$siblings] + : $siblings; } } /** * Resolves an imported type alias (@phpstan-import-type / @psalm-import-type) from a target class, interface, trait, or enum iteratively. */ - public static function resolveImportedTypeAlias(string $fqcn, string $importedAlias): ?TypeNode + public static function resolveImportedTypeAlias(string $fqcn, string $importedAlias): TypeNode|GenericTypeAlias|null { $visited = []; diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index cc9b4688..8e1301e1 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -26,8 +26,11 @@ use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Checker\InlineChecker; use TypePHP\Internal\Diagnostic\DebugLog; +use TypePHP\Internal\Generics\TemplateManager; +use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Resolver\HierarchyResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\FileFilter; use TypePHP\Internal\Util\StubManager; @@ -44,7 +47,7 @@ * classTemplates: array, * allTemplates?: array, * return: ?TypeNode, - * aliases: array, + * aliases: array, * sensitiveParams: array, * hasParamContract: bool, * hasParamOutContract: bool, @@ -87,17 +90,19 @@ final class DocblockParser /** * 2D Cache for resolved magic method contracts: [$className][$methodName] => ?array{...}. * - * @var array, aliases: array, templates: array}>> + * @var array, aliases: array, templates: array}>> */ private static array $magicMethodCache = []; /** * In-memory cache for class-level templates and aliases per class name. * - * @var array, aliases: array}> + * @var array, aliases: array}> */ private static array $classLevelDocCache = []; + private const MAX_GENERIC_ALIAS_EXPANSION_DEPTH = 12; + /** * Fast O(1) lookup matrix for scalar refinements compatible with PHP native built-in types. * @@ -317,7 +322,7 @@ private static function isUnconstrainedType(TypeNode $typeNode, bool $isNatively /** * @param array $types - * @param array $aliases + * @param array $aliases * @param array $methodTemplates * @param array $allTemplates * @param array $nativeArrayParams @@ -647,7 +652,7 @@ public static function parseProperty(string $className, string $propertyName): ? DocblockExtractor::extractAliases($phpDocNode, $aliases, $declaringClass); } - $typeNode = self::substituteAliases($typeNode, $aliases); + $typeNode = self::substituteAliases($typeNode, $aliases, [], $declaringClass); $resolvedNode = SpecialTypeResolver::resolve($typeNode, $declaringClass); return self::$propertyCache[$className][$propertyName] = $resolvedNode; @@ -697,14 +702,14 @@ public static function parseMagicPropertyContract(string $className, string $pro if ($contract['readType'] !== null) { $contract['readType'] = SpecialTypeResolver::resolve( - self::substituteAliases($contract['readType'], $aliases), + self::substituteAliases($contract['readType'], $aliases, [], $hierClass), $hierClass ); } if ($contract['writeType'] !== null) { $contract['writeType'] = SpecialTypeResolver::resolve( - self::substituteAliases($contract['writeType'], $aliases), + self::substituteAliases($contract['writeType'], $aliases, [], $hierClass), $hierClass ); } @@ -839,7 +844,7 @@ private static function findMagicPropertyDoc(\ReflectionClass $refClass, string /** * Parses and resolves a class-level @method docblock for __call / __callStatic with zero-allocation 2D caching. * - * @return array{return: ?TypeNode, parameters: array, aliases: array, templates: array}|null + * @return array{return: ?TypeNode, parameters: array, aliases: array, templates: array}|null */ public static function parseMagicMethod(string $className, string $methodName): ?array { @@ -877,7 +882,7 @@ public static function parseMagicMethod(string $className, string $methodName): $resolvedReturn = null; if ($methodTag->returnType !== null) { - $subReturn = self::substituteAliases($methodTag->returnType, $aliases); + $subReturn = self::substituteAliases($methodTag->returnType, $aliases, [], $declaringClass); $resolvedReturn = SpecialTypeResolver::resolve($subReturn, $declaringClass); } @@ -932,7 +937,7 @@ private static function findMagicMethodDoc(\ReflectionClass $refClass, string $m /** * @param \ReflectionClass $declaringClass - * @param array $aliases + * @param array $aliases * * @return array */ @@ -946,7 +951,7 @@ private static function resolveMagicParameters( foreach ($methodTag->parameters as $p) { $pType = $p->type ?? null; if ($pType !== null) { - $subType = self::substituteAliases($pType, $aliases); + $subType = self::substituteAliases($pType, $aliases, [], $declaringClass); $pType = SpecialTypeResolver::resolve($subType, $declaringClass); } @@ -1011,7 +1016,7 @@ private static function hasSensitiveAttribute(\ReflectionParameter $param): bool /** * Extracts and returns all class-level type aliases for a given class. * - * @return array + * @return array */ public static function parseClassAliases(string $className): array { @@ -1057,7 +1062,7 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t $classTemplates = []; $returnType = null; $selfOut = null; - /** @var array $aliases */ + /** @var array $aliases */ $aliases = []; /** @var array $sensitiveParams */ $sensitiveParams = []; @@ -1276,8 +1281,8 @@ private static function parseFunction(\ReflectionFunction $ref): array foreach (DocblockExtractor::extractTemplates($phpDocNode) as $name => $tag) { if ($tag->bound !== null || $tag->default !== null) { - $bound = $tag->bound !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->bound, $aliases), $ref) : null; - $default = $tag->default !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->default, $aliases), $ref) : null; + $bound = $tag->bound !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->bound, $aliases, [], $ref), $ref) : null; + $default = $tag->default !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->default, $aliases, [], $ref), $ref) : null; $tag = new TemplateTagValueNode($tag->name, $bound, $tag->description, $default); } $templates[$name] = $tag; @@ -1304,7 +1309,7 @@ private static function parseFunction(\ReflectionFunction $ref): array $type = new NullableTypeNode($type); } - $substitutedType = self::substituteAliases($type, $aliases); + $substitutedType = self::substituteAliases($type, $aliases, [], $ref); $resolvedType = SpecialTypeResolver::resolve($substitutedType, $ref); if ($resolvedType instanceof IdentifierTypeNode && strtolower($resolvedType->name) === 'mixed') { @@ -1316,14 +1321,14 @@ private static function parseFunction(\ReflectionFunction $ref): array foreach (DocblockExtractor::getParamOutTags($phpDocNode) as $paramName => $paramOutTag) { $type = $paramOutTag->type; - $substitutedType = self::substituteAliases($type, $aliases); + $substitutedType = self::substituteAliases($type, $aliases, [], $ref); $resolvedType = SpecialTypeResolver::resolve($substitutedType, $ref); $paramOuts[$paramName] = $resolvedType; } $returnTag = DocblockExtractor::getReturnTag($phpDocNode); if ($returnTag !== null) { - $substitutedReturn = self::substituteAliases($returnTag->type, $aliases); + $substitutedReturn = self::substituteAliases($returnTag->type, $aliases, [], $ref); $returnType = SpecialTypeResolver::resolve($substitutedReturn, $ref); if ( @@ -1421,7 +1426,7 @@ private static function parseFunction(\ReflectionFunction $ref): array * * @param \ReflectionClass $declaringClass * @param array $templates - * @param array $aliases + * @param array $aliases */ private static function parseClassLevelDocs(\ReflectionClass $declaringClass, array &$templates, array &$aliases): void { @@ -1445,7 +1450,7 @@ private static function parseClassLevelDocs(\ReflectionClass $declaringClass, ar $classHierarchy = HierarchyResolver::getClassHierarchy($declaringClass); /** @var array $localTemplates */ $localTemplates = []; - /** @var array $localAliases */ + /** @var array $localAliases */ $localAliases = []; foreach ($classHierarchy as $hierClass) { @@ -1497,7 +1502,7 @@ private static function parseClassLevelDocs(\ReflectionClass $declaringClass, ar * @param array $types * @param array $templates * @param TypeNode|null $returnType - * @param array $aliases + * @param array $aliases * @param array $paramOuts * @param TypeNode|null $selfOut * @param array $classTemplates @@ -1575,8 +1580,8 @@ private static function parseMethodHierarchyDocs( foreach (DocblockExtractor::extractTemplates($phpDocNode) as $name => $tag) { if (! isset($templates[$name])) { if ($tag->bound !== null || $tag->default !== null) { - $bound = $tag->bound !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->bound, $aliases), $hierRef) : null; - $default = $tag->default !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->default, $aliases), $hierRef) : null; + $bound = $tag->bound !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->bound, $aliases, [], $hierRef), $hierRef) : null; + $default = $tag->default !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->default, $aliases, [], $hierRef), $hierRef) : null; $tag = new TemplateTagValueNode($tag->name, $bound, $tag->description, $default); } $templates[$name] = $tag; @@ -1615,7 +1620,7 @@ private static function parseMethodHierarchyDocs( $type = new NullableTypeNode($type); } - $substitutedType = self::substituteAliases($type, $aliases); + $substitutedType = self::substituteAliases($type, $aliases, [], $hierRef); $resolvedType = SpecialTypeResolver::resolve($substitutedType, $hierRef); if ($resolvedType instanceof IdentifierTypeNode && strtolower($resolvedType->name) === 'mixed') { @@ -1644,7 +1649,7 @@ private static function parseMethodHierarchyDocs( if ($targetParamName !== null && ! isset($paramOuts[$targetParamName])) { $type = $paramOutTag->type; - $substitutedType = self::substituteAliases($type, $aliases); + $substitutedType = self::substituteAliases($type, $aliases, [], $hierRef); $resolvedType = SpecialTypeResolver::resolve($substitutedType, $hierRef); $paramOuts[$targetParamName] = $resolvedType; } @@ -1652,14 +1657,14 @@ private static function parseMethodHierarchyDocs( $selfOutType = DocblockExtractor::getSelfOutTag($phpDocNode); if ($selfOutType !== null && $selfOut === null) { - $substituted = self::substituteAliases($selfOutType, $aliases); + $substituted = self::substituteAliases($selfOutType, $aliases, [], $hierRef); $selfOut = SpecialTypeResolver::resolve($substituted, $hierRef); } if ($returnType === null) { $returnTag = DocblockExtractor::getReturnTag($phpDocNode); if ($returnTag !== null) { - $substitutedReturn = self::substituteAliases($returnTag->type, $aliases); + $substitutedReturn = self::substituteAliases($returnTag->type, $aliases, [], $hierRef); $returnType = SpecialTypeResolver::resolve($substitutedReturn, $hierRef); if ( @@ -1713,7 +1718,7 @@ private static function resolveTargetParamName( * @param \ReflectionMethod $ref * @param array $types * @param array $classTemplates - * @param array $aliases + * @param array $aliases */ private static function applyConstructorPromotionFallback( \ReflectionMethod $ref, @@ -1740,7 +1745,7 @@ private static function applyConstructorPromotionFallback( if ($propDoc !== false) { $propType = DocblockExtractor::extractTypeFromPropertyDoc($propDoc, $paramName); if ($propType !== null) { - $substitutedProp = self::substituteAliases($propType, $aliases); + $substitutedProp = self::substituteAliases($propType, $aliases, [], $ref); $resolvedProp = SpecialTypeResolver::resolve($substitutedProp, $ref); if ($p->hasType()) { @@ -1944,20 +1949,26 @@ private static function typeContainsNull(TypeNode $node): bool } /** - * Recursively substitutes all type aliases inside a TypeNode AST and simplifies unions/intersections containing `mixed`. + * Recursively substitutes all type aliases (plain and generic) inside a TypeNode AST + * and simplifies unions/intersections containing `mixed`. * Threads $visited across recursive calls to break self-referential and mutually recursive cycles. * - * @param array $aliases + * @param array $aliases * @param array $visited + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext */ - public static function substituteAliases(TypeNode $node, array $aliases, array $visited = []): TypeNode - { + public static function substituteAliases( + TypeNode $node, + array $aliases, + array $visited = [], + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext = null + ): TypeNode { if ($aliases === []) { return $node; } $hasRecursivePlaceholder = false; - $result = self::substituteAliasesInternal($node, $aliases, $visited, $hasRecursivePlaceholder); + $result = self::substituteAliasesInternal($node, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext); if ($hasRecursivePlaceholder && $visited === []) { return self::bindRecursiveAliases($result, $aliases); @@ -1970,7 +1981,7 @@ public static function substituteAliases(TypeNode $node, array $aliases, array $ * Links any recursive alias placeholders (`typephp_recursive_alias_name`) inside an AST * to their resolved target TypeNodes from `$aliases`. * - * @param array $aliases + * @param array $aliases */ public static function bindRecursiveAliases(TypeNode $node, array $aliases): TypeNode { @@ -1982,7 +1993,7 @@ public static function bindRecursiveAliases(TypeNode $node, array $aliases): Typ $aliasName = $node->getAttribute('typephp_recursive_alias_name'); if (\is_string($aliasName) && isset($aliases[$aliasName])) { $target = $aliases[$aliasName]; - if ($target !== $node) { + if ($target instanceof TypeNode && $target !== $node) { $node->setAttribute('typephp_recursive_alias', $target); } } @@ -2072,20 +2083,38 @@ public static function bindRecursiveAliases(TypeNode $node, array $aliases): Typ } /** - * @param array $aliases + * @param array $aliases * @param array $visited + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext + * @param array $genericDepth */ private static function substituteAliasesInternal( TypeNode $node, array $aliases, array $visited, - bool &$hasRecursivePlaceholder + bool &$hasRecursivePlaceholder, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext = null, + array $genericDepth = [] ): TypeNode { if ($node instanceof IdentifierTypeNode) { if (! isset($aliases[$node->name])) { return $node; } + $firstTarget = $aliases[$node->name]; + if ($firstTarget instanceof GenericTypeAlias) { + return self::expandGenericAlias( + $node->name, + $firstTarget, + [], + $aliases, + $visited, + $hasRecursivePlaceholder, + $resolverContext, + $genericDepth + ); + } + if (isset($visited[$node->name])) { if ($node->getAttribute('typephp_recursive_alias') instanceof TypeNode) { return $node; @@ -2110,13 +2139,26 @@ private static function substituteAliasesInternal( return self::createRecursiveAliasPlaceholder($current->name); } - $currentVisited[$current->name] = true; $target = $aliases[$current->name]; + if ($target instanceof GenericTypeAlias) { + return self::expandGenericAlias( + $current->name, + $target, + [], + $aliases, + $currentVisited, + $hasRecursivePlaceholder, + $resolverContext, + $genericDepth + ); + } + + $currentVisited[$current->name] = true; if ($target instanceof IdentifierTypeNode) { $current = $target; } else { - return self::substituteAliasesInternal($target, $aliases, $currentVisited, $hasRecursivePlaceholder); + return self::substituteAliasesInternal($target, $aliases, $currentVisited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); } } @@ -2127,7 +2169,7 @@ private static function substituteAliasesInternal( $parameters = []; foreach ($node->parameters as $param) { $parameters[] = new CallableTypeParameterNode( - self::substituteAliasesInternal($param->type, $aliases, $visited, $hasRecursivePlaceholder), + self::substituteAliasesInternal($param->type, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), $param->isReference, $param->isVariadic, $param->parameterName, @@ -2135,7 +2177,7 @@ private static function substituteAliasesInternal( ); } - $returnType = self::substituteAliasesInternal($node->returnType, $aliases, $visited, $hasRecursivePlaceholder); + $returnType = self::substituteAliasesInternal($node->returnType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); return new CallableTypeNode( $node->identifier, @@ -2147,22 +2189,39 @@ private static function substituteAliasesInternal( if ($node instanceof OffsetAccessTypeNode) { return new OffsetAccessTypeNode( - self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder), - self::substituteAliasesInternal($node->offset, $aliases, $visited, $hasRecursivePlaceholder) + self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), + self::substituteAliasesInternal($node->offset, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth) ); } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder)); + return new ArrayTypeNode(self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth)); } if ($node instanceof GenericTypeNode) { - $genericType = self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder); $genericTypes = []; foreach ($node->genericTypes as $gt) { - $genericTypes[] = self::substituteAliasesInternal($gt, $aliases, $visited, $hasRecursivePlaceholder); + $genericTypes[] = self::substituteAliasesInternal($gt, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + } + + if ($node->type instanceof IdentifierTypeNode && isset($aliases[$node->type->name])) { + $entry = $aliases[$node->type->name]; + if ($entry instanceof GenericTypeAlias) { + return self::expandGenericAlias( + $node->type->name, + $entry, + $genericTypes, + $aliases, + $visited, + $hasRecursivePlaceholder, + $resolverContext, + $genericDepth + ); + } } + $genericType = self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + return new GenericTypeNode( $genericType instanceof IdentifierTypeNode ? $genericType : $node->type, $genericTypes, @@ -2171,13 +2230,13 @@ private static function substituteAliasesInternal( } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder)); + return new NullableTypeNode(self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth)); } if ($node instanceof UnionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::substituteAliasesInternal($t, $aliases, $visited, $hasRecursivePlaceholder); + $types[] = self::substituteAliasesInternal($t, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); } foreach ($types as $t) { @@ -2192,7 +2251,7 @@ private static function substituteAliasesInternal( if ($node instanceof IntersectionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::substituteAliasesInternal($t, $aliases, $visited, $hasRecursivePlaceholder); + $types[] = self::substituteAliasesInternal($t, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); } $filtered = array_values(array_filter($types, function ($t) { @@ -2216,16 +2275,16 @@ private static function substituteAliasesInternal( $newItems[] = new ArrayShapeItemNode( $item->keyName, $item->optional, - self::substituteAliasesInternal($item->valueType, $aliases, $visited, $hasRecursivePlaceholder) + self::substituteAliasesInternal($item->valueType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth) ); } $newUnsealed = null; if ($node->unsealedType !== null) { $unsealedKey = $node->unsealedType->keyType !== null - ? self::substituteAliasesInternal($node->unsealedType->keyType, $aliases, $visited, $hasRecursivePlaceholder) + ? self::substituteAliasesInternal($node->unsealedType->keyType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth) : null; - $unsealedVal = self::substituteAliasesInternal($node->unsealedType->valueType, $aliases, $visited, $hasRecursivePlaceholder); + $unsealedVal = self::substituteAliasesInternal($node->unsealedType->valueType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); $newUnsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey); } @@ -2242,7 +2301,7 @@ private static function substituteAliasesInternal( $newItems[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::substituteAliasesInternal($item->valueType, $aliases, $visited, $hasRecursivePlaceholder) + self::substituteAliasesInternal($item->valueType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth) ); } @@ -2251,10 +2310,10 @@ private static function substituteAliasesInternal( if ($node instanceof ConditionalTypeNode) { return new ConditionalTypeNode( - self::substituteAliasesInternal($node->subjectType, $aliases, $visited, $hasRecursivePlaceholder), - self::substituteAliasesInternal($node->targetType, $aliases, $visited, $hasRecursivePlaceholder), - self::substituteAliasesInternal($node->if, $aliases, $visited, $hasRecursivePlaceholder), - self::substituteAliasesInternal($node->else, $aliases, $visited, $hasRecursivePlaceholder), + self::substituteAliasesInternal($node->subjectType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), + self::substituteAliasesInternal($node->targetType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), + self::substituteAliasesInternal($node->if, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), + self::substituteAliasesInternal($node->else, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), $node->negated ); } @@ -2262,9 +2321,9 @@ private static function substituteAliasesInternal( if ($node instanceof ConditionalTypeForParameterNode) { return new ConditionalTypeForParameterNode( $node->parameterName, - self::substituteAliasesInternal($node->targetType, $aliases, $visited, $hasRecursivePlaceholder), - self::substituteAliasesInternal($node->if, $aliases, $visited, $hasRecursivePlaceholder), - self::substituteAliasesInternal($node->else, $aliases, $visited, $hasRecursivePlaceholder), + self::substituteAliasesInternal($node->targetType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), + self::substituteAliasesInternal($node->if, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), + self::substituteAliasesInternal($node->else, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth), $node->negated ); } @@ -2272,6 +2331,191 @@ private static function substituteAliasesInternal( return $node; } + /** + * @param list $args + * @param array $aliases + * @param array $visited + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext + * @param array $genericDepth + */ + private static function expandGenericAlias( + string $aliasName, + GenericTypeAlias $alias, + array $args, + array $aliases, + array $visited, + bool &$hasRecursivePlaceholder, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext, + array $genericDepth + ): TypeNode { + $canonicalName = $alias->originalName ?? $aliasName; + + /** @var array $bindings */ + $bindings = []; + foreach ($alias->templateTypes as $idx => $templateTag) { + $tName = $templateTag->name; + if (isset($args[$idx])) { + $argNode = $args[$idx]; + if ($templateTag->bound !== null) { + $argNode = self::applyGenericAliasBound($argNode, $templateTag->bound, $bindings, $resolverContext); + } + $bindings[$tName] = $argNode; + } else { + $fallback = $templateTag->default ?? $templateTag->bound ?? new IdentifierTypeNode('mixed'); + $bindings[$tName] = $bindings !== [] + ? TemplateSubstitutor::substitute($fallback, $bindings) + : $fallback; + } + } + + $argKeyParts = []; + foreach ($alias->templateTypes as $templateTag) { + $argKeyParts[] = (string) $bindings[$templateTag->name]; + } + $instantiationKey = $canonicalName . '<' . implode(', ', $argKeyParts) . '>'; + + if (isset($visited[$instantiationKey])) { + $hasRecursivePlaceholder = true; + + return self::createRecursiveAliasPlaceholder($instantiationKey); + } + + $currentDepth = $genericDepth[$canonicalName] ?? 0; + if ($currentDepth >= self::MAX_GENERIC_ALIAS_EXPANSION_DEPTH) { + return new IdentifierTypeNode('mixed'); + } + + $nextVisited = $visited; + $nextVisited[$instantiationKey] = true; + + $nextDepth = $genericDepth; + $nextDepth[$canonicalName] = $currentDepth + 1; + + $instantiatedBody = TemplateSubstitutor::substitute($alias->type, $bindings); + + $expansionAliases = $aliases; + if ($alias->scopeAliases !== []) { + $expansionAliases = [...$alias->scopeAliases, ...$expansionAliases]; + } + if (! isset($expansionAliases[$canonicalName])) { + $expansionAliases[$canonicalName] = $alias; + } + + $localRecursivePlaceholder = false; + $expanded = self::substituteAliasesInternal( + $instantiatedBody, + $expansionAliases, + $nextVisited, + $localRecursivePlaceholder, + $resolverContext, + $nextDepth + ); + + if ($localRecursivePlaceholder) { + if ( + $expanded instanceof IdentifierTypeNode + && $expanded->getAttribute('typephp_recursive_alias_name') === $instantiationKey + ) { + return new IdentifierTypeNode('mixed'); + } + + self::bindRecursiveAliases($expanded, [$instantiationKey => $expanded]); + $hasRecursivePlaceholder = true; + } + + return $expanded; + } + + /** + * Enforces upper bounds (`of`) on concrete generic alias arguments while preserving + * unresolved outer @template parameters for runtime inference. + * + * @param array $bindings + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext + */ + private static function applyGenericAliasBound( + TypeNode $argNode, + TypeNode $rawBound, + array $bindings, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|null $resolverContext + ): TypeNode { + $bound = $bindings !== [] + ? TemplateSubstitutor::substitute($rawBound, $bindings) + : $rawBound; + + if ($bound instanceof IdentifierTypeNode && strtolower($bound->name) === 'mixed') { + return $argNode; + } + + if ($resolverContext !== null) { + $bound = SpecialTypeResolver::resolve($bound, $resolverContext); + $checkArg = SpecialTypeResolver::resolve($argNode, $resolverContext); + } else { + $checkArg = $argNode; + } + + if (! self::isConcreteTypeForBoundCheck($checkArg) || ! self::isConcreteTypeForBoundCheck($bound)) { + return $argNode; + } + + if (TemplateManager::checkVariance($checkArg, $bound, GenericTypeNode::VARIANCE_COVARIANT)) { + return $argNode; + } + + return new IntersectionTypeNode([$bound, $checkArg]); + } + + private static function isConcreteTypeForBoundCheck(TypeNode $node): bool + { + if ($node instanceof IdentifierTypeNode) { + if (SpecialTypeResolver::isBuiltInTypeKeyword($node->name)) { + return true; + } + + if (! ClassNameValidator::isValid($node->name)) { + return false; + } + + return class_exists($node->name, false) + || interface_exists($node->name, false) + || enum_exists($node->name, false) + || ($node->getAttribute('typephp_resolved') === true && (class_exists($node->name) || interface_exists($node->name) || enum_exists($node->name))); + } + + if ($node instanceof \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode || $node instanceof ArrayShapeNode || $node instanceof ObjectShapeNode || $node instanceof CallableTypeNode) { + return true; + } + + if ($node instanceof ArrayTypeNode || $node instanceof NullableTypeNode) { + return self::isConcreteTypeForBoundCheck($node->type); + } + + if ($node instanceof GenericTypeNode) { + if (! self::isConcreteTypeForBoundCheck($node->type)) { + return false; + } + foreach ($node->genericTypes as $gt) { + if (! self::isConcreteTypeForBoundCheck($gt)) { + return false; + } + } + + return true; + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + foreach ($node->types as $member) { + if (! self::isConcreteTypeForBoundCheck($member)) { + return false; + } + } + + return true; + } + + return false; + } + private static function createRecursiveAliasPlaceholder(string $name): IdentifierTypeNode { $placeholder = new IdentifierTypeNode($name); diff --git a/src/Internal/Docblock/GenericTypeAlias.php b/src/Internal/Docblock/GenericTypeAlias.php new file mode 100644 index 00000000..8d797a30 --- /dev/null +++ b/src/Internal/Docblock/GenericTypeAlias.php @@ -0,0 +1,35 @@ + array{TFirst, TSecond}). + * + * @internal + */ +final class GenericTypeAlias +{ + /** + * Sibling generic aliases from the declaring scope so imported / renamed + * generic aliases can still expand mutually recursive or helper generic aliases. + * + * @var array + */ + public array $scopeAliases = []; + + /** + * @param non-empty-list $templateTypes + */ + public function __construct( + public readonly TypeNode $type, + public readonly array $templateTypes, + public readonly ?string $originalName = null, + ) { + } +} diff --git a/src/Internal/Generics/TemplateSubstitutor.php b/src/Internal/Generics/TemplateSubstitutor.php index 217dfbad..7f6559e9 100644 --- a/src/Internal/Generics/TemplateSubstitutor.php +++ b/src/Internal/Generics/TemplateSubstitutor.php @@ -25,6 +25,7 @@ use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use TypePHP\Internal\Docblock\DocblockParser; /** * @internal Recursively substitutes template placeholders (like T) with their bound concrete types (like int). @@ -43,7 +44,10 @@ public static function substitute(TypeNode $node, array $boundTemplates, array $ return $node; } - return self::substituteNode($node, $boundTemplates, $declaredTemplates, []); + /** @var array $recursiveMemo */ + $recursiveMemo = []; + + return self::substituteNode($node, $boundTemplates, $declaredTemplates, [], $recursiveMemo); } /** @@ -143,41 +147,43 @@ private static function flatten(array $types, string $containerClass): array * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteNode( TypeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): TypeNode { if ($node instanceof IdentifierTypeNode) { - return self::substituteIdentifier($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteIdentifier($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof CallableTypeNode) { - return self::substituteCallable($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteCallable($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof ConditionalTypeNode) { - return self::substituteConditional($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteConditional($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof ConditionalTypeForParameterNode) { - return self::substituteParameterConditional($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteParameterConditional($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof ArrayTypeNode) { - $inner = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + $inner = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); return $inner === $node->type ? $node : new ArrayTypeNode($inner); } if ($node instanceof GenericTypeNode) { - return self::substituteGeneric($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteGeneric($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof NullableTypeNode) { - $inner = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + $inner = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); return $inner === $node->type ? $node : new NullableTypeNode($inner); } @@ -186,7 +192,7 @@ private static function substituteNode( $types = []; $changed = false; foreach ($node->types as $t) { - $sub = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited); + $sub = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); if ($sub !== $t) { $changed = true; } @@ -200,7 +206,7 @@ private static function substituteNode( $types = []; $changed = false; foreach ($node->types as $t) { - $sub = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited); + $sub = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); if ($sub !== $t) { $changed = true; } @@ -211,15 +217,15 @@ private static function substituteNode( } if ($node instanceof ArrayShapeNode) { - return self::substituteArrayShape($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteArrayShape($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof ObjectShapeNode) { - return self::substituteObjectShape($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteObjectShape($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } if ($node instanceof OffsetAccessTypeNode) { - return self::substituteOffsetAccess($node, $boundTemplates, $declaredTemplates, $visited); + return self::substituteOffsetAccess($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } return $node; @@ -229,17 +235,45 @@ private static function substituteNode( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteIdentifier( IdentifierTypeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): TypeNode { if (isset($boundTemplates[$node->name])) { return $boundTemplates[$node->name]; } + $recursiveTarget = $node->getAttribute('typephp_recursive_alias'); + if ($recursiveTarget instanceof TypeNode) { + $allTemplateKeys = $declaredTemplates === [] + ? $boundTemplates + : ($boundTemplates === [] ? $declaredTemplates : [...$declaredTemplates, ...$boundTemplates]); + + if (! DocblockParser::typeReferencesTemplate($recursiveTarget, $allTemplateKeys)) { + return $node; + } + + $targetId = spl_object_id($recursiveTarget); + if (isset($recursiveMemo[$targetId])) { + return $recursiveMemo[$targetId]; + } + + $placeholder = new IdentifierTypeNode($node->name); + $placeholder->setAttribute('typephp_recursive_alias_name', $node->getAttribute('typephp_recursive_alias_name') ?? $node->name); + $placeholder->setAttribute('typephp_resolved', true); + $recursiveMemo[$targetId] = $placeholder; + + $substitutedTarget = self::substituteNode($recursiveTarget, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); + $placeholder->setAttribute('typephp_recursive_alias', $substitutedTarget); + + return $placeholder; + } + if (isset($declaredTemplates[$node->name])) { if (isset($visited[$node->name])) { return new IdentifierTypeNode('mixed'); @@ -249,7 +283,7 @@ private static function substituteIdentifier( $templateTag = $declaredTemplates[$node->name]; $fallback = $templateTag->default ?? $templateTag->bound ?? new IdentifierTypeNode('mixed'); - return self::substituteNode($fallback, $boundTemplates, $declaredTemplates, $visited); + return self::substituteNode($fallback, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } return $node; @@ -259,12 +293,14 @@ private static function substituteIdentifier( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteCallable( CallableTypeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): CallableTypeNode { $localTemplateNames = []; foreach ($node->templateTypes as $tTag) { @@ -279,7 +315,7 @@ private static function substituteCallable( $parameters = []; foreach ($node->parameters as $param) { $parameters[] = new CallableTypeParameterNode( - self::substituteNode($param->type, $boundTemplates, $effectiveDeclared, $visited), + self::substituteNode($param->type, $boundTemplates, $effectiveDeclared, $visited, $recursiveMemo), $param->isReference, $param->isVariadic, $param->parameterName, @@ -287,7 +323,7 @@ private static function substituteCallable( ); } - $returnType = self::substituteNode($node->returnType, $boundTemplates, $effectiveDeclared, $visited); + $returnType = self::substituteNode($node->returnType, $boundTemplates, $effectiveDeclared, $visited, $recursiveMemo); return new CallableTypeNode( $node->identifier, @@ -301,18 +337,20 @@ private static function substituteCallable( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteConditional( ConditionalTypeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): ConditionalTypeNode { return new ConditionalTypeNode( - self::substituteNode($node->subjectType, $boundTemplates, $declaredTemplates, $visited), - self::substituteNode($node->targetType, $boundTemplates, $declaredTemplates, $visited), - self::substituteNode($node->if, $boundTemplates, $declaredTemplates, $visited), - self::substituteNode($node->else, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->subjectType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), + self::substituteNode($node->targetType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), + self::substituteNode($node->if, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), + self::substituteNode($node->else, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), $node->negated ); } @@ -321,18 +359,20 @@ private static function substituteConditional( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteParameterConditional( ConditionalTypeForParameterNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): ConditionalTypeForParameterNode { return new ConditionalTypeForParameterNode( $node->parameterName, - self::substituteNode($node->targetType, $boundTemplates, $declaredTemplates, $visited), - self::substituteNode($node->if, $boundTemplates, $declaredTemplates, $visited), - self::substituteNode($node->else, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->targetType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), + self::substituteNode($node->if, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), + self::substituteNode($node->else, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo), $node->negated ); } @@ -341,18 +381,20 @@ private static function substituteParameterConditional( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteGeneric( GenericTypeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): GenericTypeNode { - $type = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + $type = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); $changed = ($type !== $node->type); $genericTypes = []; foreach ($node->genericTypes as $gt) { - $sub = self::substituteNode($gt, $boundTemplates, $declaredTemplates, $visited); + $sub = self::substituteNode($gt, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); if ($sub !== $gt) { $changed = true; } @@ -374,28 +416,30 @@ private static function substituteGeneric( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteArrayShape( ArrayShapeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): ArrayShapeNode { $newItems = []; foreach ($node->items as $item) { $newItems[] = new ArrayShapeItemNode( $item->keyName, $item->optional, - self::substituteNode($item->valueType, $boundTemplates, $declaredTemplates, $visited) + self::substituteNode($item->valueType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo) ); } $newUnsealed = null; if ($node->unsealedType !== null) { $unsealedKey = $node->unsealedType->keyType !== null - ? self::substituteNode($node->unsealedType->keyType, $boundTemplates, $declaredTemplates, $visited) + ? self::substituteNode($node->unsealedType->keyType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo) : null; - $unsealedVal = self::substituteNode($node->unsealedType->valueType, $boundTemplates, $declaredTemplates, $visited); + $unsealedVal = self::substituteNode($node->unsealedType->valueType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); $newUnsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey); } @@ -410,19 +454,21 @@ private static function substituteArrayShape( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteObjectShape( ObjectShapeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): ObjectShapeNode { $newItems = []; foreach ($node->items as $item) { $newItems[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::substituteNode($item->valueType, $boundTemplates, $declaredTemplates, $visited) + self::substituteNode($item->valueType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo) ); } @@ -433,15 +479,17 @@ private static function substituteObjectShape( * @param array $boundTemplates * @param array $declaredTemplates * @param array $visited + * @param array $recursiveMemo */ private static function substituteOffsetAccess( OffsetAccessTypeNode $node, array $boundTemplates, array $declaredTemplates, - array $visited + array $visited, + array &$recursiveMemo ): TypeNode { - $baseType = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); - $offsetType = self::substituteNode($node->offset, $boundTemplates, $declaredTemplates, $visited); + $baseType = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); + $offsetType = self::substituteNode($node->offset, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); if ($baseType instanceof ArrayShapeNode) { $offsetKey = null; diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 254a5253..83e3018d 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -232,11 +232,16 @@ public static function checkThisIdentity(TypeNode $returnTypeNode, mixed $value, * Recursively resolves special type identifiers in a TypeNode AST using Reflection context. * * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + * @param array $ignoredTemplates */ - public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj = null): TypeNode - { + public static function resolve( + TypeNode $node, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, + ?object $thisObj = null, + array $ignoredTemplates = [] + ): TypeNode { if ($node instanceof IdentifierTypeNode) { - if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true || isset($ignoredTemplates[$node->name])) { return $node; } @@ -253,22 +258,24 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct ? $ref->getDeclaringClass()->getName() : ($ref instanceof \ReflectionClass ? $ref->getName() : null); - return self::resolveWithContext($node, $ref, $declaringClass, $context, $thisObj); + return self::resolveWithContext($node, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); } /** * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + * @param array $ignoredTemplates */ private static function resolveWithContext( TypeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref, ?string $declaringClass, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, - ?object $thisObj = null + ?object $thisObj = null, + array $ignoredTemplates = [] ): TypeNode { if ($node instanceof IdentifierTypeNode) { - if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true || isset($ignoredTemplates[$node->name])) { return $node; } @@ -302,11 +309,11 @@ private static function resolveWithContext( } if ($node instanceof GenericTypeNode) { - $genericType = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj); + $genericType = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); $changed = ($genericType !== $node->type); $innerTypes = []; foreach ($node->genericTypes as $gt) { - $resGt = self::resolveWithContext($gt, $ref, $declaringClass, $context, $thisObj); + $resGt = self::resolveWithContext($gt, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); if ($resGt !== $gt) { $changed = true; } @@ -325,27 +332,27 @@ private static function resolveWithContext( } if ($node instanceof OffsetAccessTypeNode) { - return self::resolveOffsetAccess($node, $context, $thisObj); + return self::resolveOffsetAccess($node, $context, $thisObj, $ignoredTemplates); } if ($node instanceof ArrayShapeNode) { - return self::resolveArrayShape($node, $context, $thisObj); + return self::resolveArrayShape($node, $context, $thisObj, $ignoredTemplates); } if ($node instanceof ObjectShapeNode) { - return self::resolveObjectShape($node, $context, $thisObj); + return self::resolveObjectShape($node, $context, $thisObj, $ignoredTemplates); } if ($node instanceof CallableTypeNode) { - return self::resolveCallable($node, $context, $thisObj); + return self::resolveCallable($node, $context, $thisObj, $ignoredTemplates); } if ($node instanceof ConditionalTypeNode) { return new ConditionalTypeNode( - self::resolveWithContext($node->subjectType, $ref, $declaringClass, $context, $thisObj), - self::resolveWithContext($node->targetType, $ref, $declaringClass, $context, $thisObj), - self::resolveWithContext($node->if, $ref, $declaringClass, $context, $thisObj), - self::resolveWithContext($node->else, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->subjectType, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), + self::resolveWithContext($node->targetType, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), + self::resolveWithContext($node->if, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), + self::resolveWithContext($node->else, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), $node->negated ); } @@ -353,21 +360,21 @@ private static function resolveWithContext( if ($node instanceof ConditionalTypeForParameterNode) { return new ConditionalTypeForParameterNode( $node->parameterName, - self::resolveWithContext($node->targetType, $ref, $declaringClass, $context, $thisObj), - self::resolveWithContext($node->if, $ref, $declaringClass, $context, $thisObj), - self::resolveWithContext($node->else, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->targetType, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), + self::resolveWithContext($node->if, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), + self::resolveWithContext($node->else, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates), $node->negated ); } if ($node instanceof NullableTypeNode) { - $resInner = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj); + $resInner = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); return $resInner === $node->type ? $node : new NullableTypeNode($resInner); } if ($node instanceof ArrayTypeNode) { - $resInner = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj); + $resInner = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); return $resInner === $node->type ? $node : new ArrayTypeNode($resInner); } @@ -376,7 +383,7 @@ private static function resolveWithContext( $types = []; $changed = false; foreach ($node->types as $t) { - $resT = self::resolveWithContext($t, $ref, $declaringClass, $context, $thisObj); + $resT = self::resolveWithContext($t, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); if ($resT !== $t) { $changed = true; } @@ -390,7 +397,7 @@ private static function resolveWithContext( $types = []; $changed = false; foreach ($node->types as $t) { - $resT = self::resolveWithContext($t, $ref, $declaringClass, $context, $thisObj); + $resT = self::resolveWithContext($t, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); if ($resT !== $t) { $changed = true; } @@ -405,9 +412,16 @@ private static function resolveWithContext( /** * Recursively resolves type identifiers in a TypeNode AST using file context (use imports and namespace). + * + * @param array $ignoredTemplates */ - public static function resolveForFile(TypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): TypeNode - { + public static function resolveForFile( + TypeNode $node, + string $file, + ?string $namespace = null, + bool $autoload = true, + array $ignoredTemplates = [] + ): TypeNode { $file = str_replace('\\', '/', $file); if ($node instanceof ThisTypeNode) { @@ -415,7 +429,7 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam } if ($node instanceof IdentifierTypeNode) { - if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true || isset($ignoredTemplates[$node->name])) { return clone $node; } @@ -462,10 +476,10 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam } if ($node instanceof GenericTypeNode) { - $genericType = self::resolveForFile($node->type, $file, $namespace, $autoload); + $genericType = self::resolveForFile($node->type, $file, $namespace, $autoload, $ignoredTemplates); $innerTypes = []; foreach ($node->genericTypes as $gt) { - $innerTypes[] = self::resolveForFile($gt, $file, $namespace, $autoload); + $innerTypes[] = self::resolveForFile($gt, $file, $namespace, $autoload, $ignoredTemplates); } return new GenericTypeNode( @@ -476,27 +490,27 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam } if ($node instanceof OffsetAccessTypeNode) { - return self::resolveOffsetAccessForFile($node, $file, $namespace, $autoload); + return self::resolveOffsetAccessForFile($node, $file, $namespace, $autoload, $ignoredTemplates); } if ($node instanceof ArrayShapeNode) { - return self::resolveArrayShapeForFile($node, $file, $namespace, $autoload); + return self::resolveArrayShapeForFile($node, $file, $namespace, $autoload, $ignoredTemplates); } if ($node instanceof ObjectShapeNode) { - return self::resolveObjectShapeForFile($node, $file, $namespace, $autoload); + return self::resolveObjectShapeForFile($node, $file, $namespace, $autoload, $ignoredTemplates); } if ($node instanceof CallableTypeNode) { - return self::resolveCallableForFile($node, $file, $namespace, $autoload); + return self::resolveCallableForFile($node, $file, $namespace, $autoload, $ignoredTemplates); } if ($node instanceof ConditionalTypeNode) { return new ConditionalTypeNode( - self::resolveForFile($node->subjectType, $file, $namespace, $autoload), - self::resolveForFile($node->targetType, $file, $namespace, $autoload), - self::resolveForFile($node->if, $file, $namespace, $autoload), - self::resolveForFile($node->else, $file, $namespace, $autoload), + self::resolveForFile($node->subjectType, $file, $namespace, $autoload, $ignoredTemplates), + self::resolveForFile($node->targetType, $file, $namespace, $autoload, $ignoredTemplates), + self::resolveForFile($node->if, $file, $namespace, $autoload, $ignoredTemplates), + self::resolveForFile($node->else, $file, $namespace, $autoload, $ignoredTemplates), $node->negated ); } @@ -504,25 +518,25 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam if ($node instanceof ConditionalTypeForParameterNode) { return new ConditionalTypeForParameterNode( $node->parameterName, - self::resolveForFile($node->targetType, $file, $namespace, $autoload), - self::resolveForFile($node->if, $file, $namespace, $autoload), - self::resolveForFile($node->else, $file, $namespace, $autoload), + self::resolveForFile($node->targetType, $file, $namespace, $autoload, $ignoredTemplates), + self::resolveForFile($node->if, $file, $namespace, $autoload, $ignoredTemplates), + self::resolveForFile($node->else, $file, $namespace, $autoload, $ignoredTemplates), $node->negated ); } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::resolveForFile($node->type, $file, $namespace, $autoload)); + return new NullableTypeNode(self::resolveForFile($node->type, $file, $namespace, $autoload, $ignoredTemplates)); } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::resolveForFile($node->type, $file, $namespace, $autoload)); + return new ArrayTypeNode(self::resolveForFile($node->type, $file, $namespace, $autoload, $ignoredTemplates)); } if ($node instanceof UnionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::resolveForFile($t, $file, $namespace, $autoload); + $types[] = self::resolveForFile($t, $file, $namespace, $autoload, $ignoredTemplates); } return new UnionTypeNode($types); @@ -531,7 +545,7 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam if ($node instanceof IntersectionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::resolveForFile($t, $file, $namespace, $autoload); + $types[] = self::resolveForFile($t, $file, $namespace, $autoload, $ignoredTemplates); } return new IntersectionTypeNode($types); @@ -748,10 +762,18 @@ private static function resolveConstType(ConstTypeNode $node, ?string $declaring /** * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context */ - private static function resolveOffsetAccess(OffsetAccessTypeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj): TypeNode - { - $baseType = self::resolve($node->type, $context, $thisObj); - $offsetType = self::resolve($node->offset, $context, $thisObj); + /** + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + * @param array $ignoredTemplates + */ + private static function resolveOffsetAccess( + OffsetAccessTypeNode $node, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, + ?object $thisObj, + array $ignoredTemplates = [] + ): TypeNode { + $baseType = self::resolve($node->type, $context, $thisObj, $ignoredTemplates); + $offsetType = self::resolve($node->offset, $context, $thisObj, $ignoredTemplates); $offsetKey = self::extractOffsetKey($offsetType); @@ -778,9 +800,14 @@ private static function resolveOffsetAccess(OffsetAccessTypeNode $node, \Reflect /** * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + * @param array $ignoredTemplates */ - private static function resolveArrayShape(ArrayShapeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj): ArrayShapeNode - { + private static function resolveArrayShape( + ArrayShapeNode $node, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, + ?object $thisObj, + array $ignoredTemplates = [] + ): ArrayShapeNode { $ref = self::getReflectionContext($context); $items = []; @@ -822,7 +849,7 @@ private static function resolveArrayShape(ArrayShapeNode $node, \ReflectionClass $items[] = new ArrayShapeItemNode( $keyName, $item->optional, - self::resolve($item->valueType, $context, $thisObj) + self::resolve($item->valueType, $context, $thisObj, $ignoredTemplates) ); } @@ -832,8 +859,8 @@ private static function resolveArrayShape(ArrayShapeNode $node, \ReflectionClass $unsealedType = null; if ($node->unsealedType !== null) { - $unsealedKey = $node->unsealedType->keyType !== null ? self::resolve($node->unsealedType->keyType, $context, $thisObj) : null; - $unsealedValue = self::resolve($node->unsealedType->valueType, $context, $thisObj); + $unsealedKey = $node->unsealedType->keyType !== null ? self::resolve($node->unsealedType->keyType, $context, $thisObj, $ignoredTemplates) : null; + $unsealedValue = self::resolve($node->unsealedType->valueType, $context, $thisObj, $ignoredTemplates); $unsealedType = new ArrayShapeUnsealedTypeNode($unsealedValue, $unsealedKey); } @@ -842,15 +869,20 @@ private static function resolveArrayShape(ArrayShapeNode $node, \ReflectionClass /** * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + * @param array $ignoredTemplates */ - private static function resolveObjectShape(ObjectShapeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj): ObjectShapeNode - { + private static function resolveObjectShape( + ObjectShapeNode $node, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, + ?object $thisObj, + array $ignoredTemplates = [] + ): ObjectShapeNode { $items = []; foreach ($node->items as $item) { $items[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::resolve($item->valueType, $context, $thisObj) + self::resolve($item->valueType, $context, $thisObj, $ignoredTemplates) ); } @@ -859,35 +891,43 @@ private static function resolveObjectShape(ObjectShapeNode $node, \ReflectionCla /** * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + * @param array $ignoredTemplates */ - private static function resolveCallable(CallableTypeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj): CallableTypeNode - { - $localTemplates = []; + private static function resolveCallable( + CallableTypeNode $node, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, + ?object $thisObj, + array $ignoredTemplates = [] + ): CallableTypeNode { + $innerIgnored = $ignoredTemplates; + foreach ($node->templateTypes as $tTag) { + $innerIgnored[$tTag->name] = true; + } + $resolvedTemplateTypes = []; foreach ($node->templateTypes as $tTag) { - $localTemplates[$tTag->name] = true; $resolvedBound = $tTag->bound !== null - ? self::resolve($tTag->bound, $context, $thisObj) + ? self::resolve($tTag->bound, $context, $thisObj, $innerIgnored) : null; $resolvedDefault = $tTag->default !== null - ? self::resolve($tTag->default, $context, $thisObj) + ? self::resolve($tTag->default, $context, $thisObj, $innerIgnored) + : null; + $resolvedLowerBound = $tTag->lowerBound !== null + ? self::resolve($tTag->lowerBound, $context, $thisObj, $innerIgnored) : null; $resolvedTemplateTypes[] = new \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode( $tTag->name, $resolvedBound, $tTag->description, - $resolvedDefault + $resolvedDefault, + $resolvedLowerBound ); } $resolvedParameters = []; foreach ($node->parameters as $param) { - $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[(string) $param->type])) - ? $param->type - : self::resolve($param->type, $context, $thisObj); - $resolvedParameters[] = new CallableTypeParameterNode( - $paramType, + self::resolve($param->type, $context, $thisObj, $innerIgnored), $param->isReference, $param->isVariadic, $param->parameterName, @@ -895,9 +935,7 @@ private static function resolveCallable(CallableTypeNode $node, \ReflectionClass ); } - $resolvedReturnType = ($node->returnType instanceof IdentifierTypeNode && isset($localTemplates[$node->returnType->name])) - ? $node->returnType - : self::resolve($node->returnType, $context, $thisObj); + $resolvedReturnType = self::resolve($node->returnType, $context, $thisObj, $innerIgnored); return new CallableTypeNode($node->identifier, $resolvedParameters, $resolvedReturnType, $resolvedTemplateTypes); } @@ -933,10 +971,18 @@ private static function resolveConstTypeForFile(ConstTypeNode $node, string $fil return clone $node; } - private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): TypeNode - { - $baseType = self::resolveForFile($node->type, $file, $namespace, $autoload); - $offsetType = self::resolveForFile($node->offset, $file, $namespace, $autoload); + /** + * @param array $ignoredTemplates + */ + private static function resolveOffsetAccessForFile( + OffsetAccessTypeNode $node, + string $file, + ?string $namespace = null, + bool $autoload = true, + array $ignoredTemplates = [] + ): TypeNode { + $baseType = self::resolveForFile($node->type, $file, $namespace, $autoload, $ignoredTemplates); + $offsetType = self::resolveForFile($node->offset, $file, $namespace, $autoload, $ignoredTemplates); $offsetKey = self::extractOffsetKey($offsetType); @@ -961,8 +1007,16 @@ private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, s return new OffsetAccessTypeNode($baseType, $offsetType); } - private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $file, ?string $namespace = null, bool $autoload = true): ArrayShapeNode - { + /** + * @param array $ignoredTemplates + */ + private static function resolveArrayShapeForFile( + ArrayShapeNode $node, + string $file, + ?string $namespace = null, + bool $autoload = true, + array $ignoredTemplates = [] + ): ArrayShapeNode { $items = []; foreach ($node->items as $item) { /** @var ConstExprIntegerNode|ConstExprStringNode|ConstFetchNode|IdentifierTypeNode|null $keyName */ @@ -995,7 +1049,7 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $items[] = new ArrayShapeItemNode( $keyName, $item->optional, - self::resolveForFile($item->valueType, $file, $namespace, $autoload) + self::resolveForFile($item->valueType, $file, $namespace, $autoload, $ignoredTemplates) ); } @@ -1005,56 +1059,75 @@ 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, $namespace, $autoload) : null; - $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace, $autoload); + $unsealedKey = $node->unsealedType->keyType !== null ? self::resolveForFile($node->unsealedType->keyType, $file, $namespace, $autoload, $ignoredTemplates) : null; + $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace, $autoload, $ignoredTemplates); $unsealedType = new ArrayShapeUnsealedTypeNode($unsealedValue, $unsealedKey); } return ArrayShapeNode::createUnsealed($items, $unsealedType, $node->kind); } - private static function resolveObjectShapeForFile(ObjectShapeNode $node, string $file, ?string $namespace = null, bool $autoload = true): ObjectShapeNode - { + /** + * @param array $ignoredTemplates + */ + private static function resolveObjectShapeForFile( + ObjectShapeNode $node, + string $file, + ?string $namespace = null, + bool $autoload = true, + array $ignoredTemplates = [] + ): ObjectShapeNode { $items = []; foreach ($node->items as $item) { $items[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::resolveForFile($item->valueType, $file, $namespace, $autoload) + self::resolveForFile($item->valueType, $file, $namespace, $autoload, $ignoredTemplates) ); } return new ObjectShapeNode($items); } - private static function resolveCallableForFile(CallableTypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): CallableTypeNode - { - $localTemplates = []; + /** + * @param array $ignoredTemplates + */ + private static function resolveCallableForFile( + CallableTypeNode $node, + string $file, + ?string $namespace = null, + bool $autoload = true, + array $ignoredTemplates = [] + ): CallableTypeNode { + $innerIgnored = $ignoredTemplates; + foreach ($node->templateTypes as $tTag) { + $innerIgnored[$tTag->name] = true; + } + $resolvedTemplateTypes = []; foreach ($node->templateTypes as $tTag) { - $localTemplates[$tTag->name] = true; $resolvedBound = $tTag->bound !== null - ? self::resolveForFile($tTag->bound, $file, $namespace, $autoload) + ? self::resolveForFile($tTag->bound, $file, $namespace, $autoload, $innerIgnored) : null; $resolvedDefault = $tTag->default !== null - ? self::resolveForFile($tTag->default, $file, $namespace, $autoload) + ? self::resolveForFile($tTag->default, $file, $namespace, $autoload, $innerIgnored) + : null; + $resolvedLowerBound = $tTag->lowerBound !== null + ? self::resolveForFile($tTag->lowerBound, $file, $namespace, $autoload, $innerIgnored) : null; $resolvedTemplateTypes[] = new \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode( $tTag->name, $resolvedBound, $tTag->description, - $resolvedDefault + $resolvedDefault, + $resolvedLowerBound ); } $resolvedParameters = []; foreach ($node->parameters as $param) { - $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[(string) $param->type])) - ? clone $param->type - : self::resolveForFile($param->type, $file, $namespace, $autoload); - $resolvedParameters[] = new CallableTypeParameterNode( - $paramType, + self::resolveForFile($param->type, $file, $namespace, $autoload, $innerIgnored), $param->isReference, $param->isVariadic, $param->parameterName, @@ -1062,9 +1135,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, $namespace, $autoload); + $resolvedReturnType = self::resolveForFile($node->returnType, $file, $namespace, $autoload, $innerIgnored); return new CallableTypeNode($node->identifier, $resolvedParameters, $resolvedReturnType, $resolvedTemplateTypes); } diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index 5cbc2cf6..7ae00acb 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -26,6 +26,7 @@ use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Reporting\ViolationCollector; @@ -204,7 +205,10 @@ private static function resolveCallableParamTypeNode( $aliases = $contract['aliases'] ?? []; if ($rawTypeNode instanceof IdentifierTypeNode && isset($aliases[$rawTypeNode->name])) { - $rawTypeNode = $aliases[$rawTypeNode->name]; + $aliasEntry = $aliases[$rawTypeNode->name]; + $rawTypeNode = $aliasEntry instanceof GenericTypeAlias + ? DocblockParser::substituteAliases($rawTypeNode, $aliases) + : $aliasEntry; } $templates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 290d1a96..5e7b039a 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -20,6 +20,7 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Docblock\GenericTypeAlias; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Reporting\ViolationCollector; @@ -45,7 +46,7 @@ final class IterableWrapper /** * @var array, + * aliases: array, * templates: array, * hasMethodTemplates: bool, * hasConditionals: bool, @@ -98,7 +99,7 @@ public static function containsTraversableIterable(TypeNode $typeNode): bool * Wraps a Traversable or Generator using an already-resolved TypeNode AST * (preserving resolved class/method generics, conditionals, aliases, and magic @method contracts). * - * @param array $aliases + * @param array $aliases */ public static function wrapTypeNode( TypeNode $typeNode, @@ -351,14 +352,17 @@ private static function isUnconstrained(?TypeNode $node): bool /** * Extracts key and value TypeNodes from an iterable type node AST or type alias. * - * @param array $aliases + * @param array $aliases * * @return array{?TypeNode, ?TypeNode} */ private static function extractKeyAndItemTypeNodes(?TypeNode $typeNode, array $aliases): array { if ($typeNode instanceof IdentifierTypeNode && isset($aliases[$typeNode->name])) { - $typeNode = $aliases[$typeNode->name]; + $aliasEntry = $aliases[$typeNode->name]; + $typeNode = $aliasEntry instanceof GenericTypeAlias + ? DocblockParser::substituteAliases($typeNode, $aliases) + : $aliasEntry; } $itemTypeNode = null; @@ -494,7 +498,7 @@ private static function wrapGenerator(iterable $iterable, \Closure $typeCheckCal /** * Extracts the unique matching Traversable/iterable TypeNode from a direct, nullable, or union TypeNode. * - * @param array $aliases + * @param array $aliases */ private static function extractTraversableTypeNode(TypeNode $typeNode, mixed $iterable = null, array $aliases = []): ?TypeNode { @@ -530,7 +534,7 @@ private static function extractTraversableTypeNode(TypeNode $typeNode, mixed $it } /** - * @param array $aliases + * @param array $aliases * @param list $matches */ private static function collectTraversableBranches( @@ -545,7 +549,10 @@ private static function collectTraversableBranches( } if ($typeNode instanceof IdentifierTypeNode && isset($aliases[$typeNode->name])) { - $typeNode = $aliases[$typeNode->name]; + $aliasEntry = $aliases[$typeNode->name]; + $typeNode = $aliasEntry instanceof GenericTypeAlias + ? DocblockParser::substituteAliases($typeNode, $aliases) + : $aliasEntry; while ($typeNode instanceof NullableTypeNode) { $typeNode = $typeNode->type; } diff --git a/tests/Internal/Docblock/DocblockParserTest.php b/tests/Internal/Docblock/DocblockParserTest.php index 35fe6175..96cf9046 100644 --- a/tests/Internal/Docblock/DocblockParserTest.php +++ b/tests/Internal/Docblock/DocblockParserTest.php @@ -17,6 +17,8 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use PHPStan\PhpDocParser\Parser\TokenIterator; +use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Util\Config; use TypePHP\Tests\Fixtures\IgnoreTags\IgnoredMethod; @@ -342,4 +344,60 @@ function sampleParamOutDocblockFunction(mixed &$id): void ; }); }); + + describe('Generic Type Aliases (substituteAliases)', function () { + test('expands parameterized alias with all arguments and sequential defaults (Pair)', function () { + $doc = '/** @phpstan-type Pair array{TFirst, TSecond} */'; + $phpDocNode = DocblockExtractor::parseDocString($doc); + $aliases = []; + DocblockExtractor::extractAliases($phpDocNode, $aliases, new ReflectionClass(UserService::class)); + + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + + $twoArgs = $typeParser->parse(new TokenIterator($lexer->tokenize('Pair'))); + expect((string) DocblockParser::substituteAliases($twoArgs, $aliases)) + ->toBe('array{int, string}') + ; + + $oneArg = $typeParser->parse(new TokenIterator($lexer->tokenize('Pair'))); + expect((string) DocblockParser::substituteAliases($oneArg, $aliases)) + ->toBe('array{positive-int, positive-int}') + ; + + $nested = $typeParser->parse(new TokenIterator($lexer->tokenize('Pair>'))); + expect((string) DocblockParser::substituteAliases($nested, $aliases)) + ->toBe('array{int, array{string, bool}}') + ; + }); + + test('expands recursive generic alias (Tree) and binds cyclic placeholder', function () { + $doc = '/** @phpstan-type Tree array{value: T, children: list>} */'; + $phpDocNode = DocblockExtractor::parseDocString($doc); + $aliases = []; + DocblockExtractor::extractAliases($phpDocNode, $aliases, new ReflectionClass(UserService::class)); + + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $treeInt = $typeParser->parse(new TokenIterator($lexer->tokenize('Tree'))); + $expanded = DocblockParser::substituteAliases($treeInt, $aliases); + + expect($expanded)->toBeInstanceOf(ArrayShapeNode::class); + $childrenGeneric = $expanded->items[1]->valueType; + expect($childrenGeneric)->toBeInstanceOf(GenericTypeNode::class); + $placeholder = $childrenGeneric->genericTypes[0]; + expect($placeholder->getAttribute('typephp_recursive_alias'))->toBe($expanded); + }); + + test('prevents infinite expansion on non-regular polymorphic recursion', function () { + $doc = '/** @phpstan-type Bad array{x: Bad>} */'; + $phpDocNode = DocblockExtractor::parseDocString($doc); + $aliases = []; + DocblockExtractor::extractAliases($phpDocNode, $aliases, new ReflectionClass(UserService::class)); + + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $node = $typeParser->parse(new TokenIterator($lexer->tokenize('Bad'))); + $expanded = DocblockParser::substituteAliases($node, $aliases); + + expect($expanded)->toBeInstanceOf(ArrayShapeNode::class); + }); + }); }); diff --git a/tests/TypeChecking/Generics/GenericTypeAliasTest.php b/tests/TypeChecking/Generics/GenericTypeAliasTest.php new file mode 100644 index 00000000..24816311 --- /dev/null +++ b/tests/TypeChecking/Generics/GenericTypeAliasTest.php @@ -0,0 +1,716 @@ + + * to verify local alias templates shadow same-namespace class names. + */ +final class AliasShadowTarget +{ +} + +/** + * @phpstan-type PosId positive-int + * @phpstan-type Pair array{TFirst, TSecond} + * @phpstan-type IntPair Pair + * @phpstan-type Record array{id: PosId, data: T} + * @phpstan-type ApiResponse array{ok: true, data: TData}|array{ok: false, error: non-empty-string} + * + * @psalm-type Wrapped = array{wrapped: T} + * + * @phpstan-type IntBox array{value: T} + * @phpstan-type AnimalCage array{pet: T} + * @phpstan-type HierarchyPair array{parent: TBase, child: TChild} + * @phpstan-type Tree array{value: T, children: list>} + * @phpstan-type EvenNode array{even: T, next?: OddNode} + * @phpstan-type OddNode array{odd: T, next?: EvenNode} + * @phpstan-type AliasShadowTarget string + * @phpstan-type ShadowBox array{val: AliasShadowTarget} + */ +final class GenericAliasProvider +{ + /** + * @var Pair + */ + public const DEFAULT_PAIR = [1, 'ok']; + + /** + * @var Pair + */ + public array $pair = [1, 'initial']; + + /** + * @param Pair $pair + * + * @return Pair + */ + public function echoPair(array $pair): array + { + return $pair; + } + + /** + * @param Pair $pair + * + * @return Pair + */ + public function echoSamePair(array $pair): array + { + return $pair; + } + + /** + * @param Pair> $nested + * + * @return Pair> + */ + public function echoNestedPair(array $nested): array + { + return $nested; + } + + /** + * @param IntPair $pair + */ + public function acceptIntPairAlias(array $pair): void + { + } + + /** + * @param Record $record + */ + public function acceptDefaultRecord(array $record): void + { + } + + /** + * @param Record $record + */ + public function acceptStringRecord(array $record): void + { + } + + /** + * @param ApiResponse $response + * + * @return ApiResponse + */ + public function handleApiResponse(array $response): array + { + return $response; + } + + /** + * @param Wrapped $wrapped + */ + public function acceptPsalmWrapped(array $wrapped): void + { + } + + /** + * @param IntBox $box + */ + public function acceptPositiveIntBox(array $box): void + { + } + + /** + * @param IntBox $box + */ + public function acceptUnparameterizedIntBox(array $box): void + { + } + + /** + * @param IntBox $box + */ + public function acceptInvalidIntBoxBound(array $box): void + { + } + + /** + * @param AnimalCage $cage + */ + public function acceptDogCage(array $cage): void + { + } + + /** + * @param AnimalCage $cage + */ + public function acceptInvalidCageBound(array $cage): void + { + } + + /** + * @param HierarchyPair $pair + */ + public function acceptHierarchyPair(array $pair): void + { + } + + /** + * @template T + * + * @param Pair $pair + * + * @return T + */ + public function firstOfPair(array $pair): mixed + { + return $pair[0]; + } + + /** + * @template T + * + * @param Pair $pair + * + * @return T + */ + public function brokenFirstOfPair(array $pair, mixed $wrongReturn): mixed + { + return $wrongReturn; + } + + /** + * @param Tree $tree + * + * @return Tree + */ + public function acceptPositiveTree(array $tree): array + { + return $tree; + } + + /** + * @template U + * + * @param U $seed + * @param Tree $tree + * + * @return U + */ + public function acceptGenericTree(mixed $seed, array $tree): mixed + { + return $tree['value']; + } + + /** + * @param EvenNode $node + */ + public function acceptMutuallyRecursiveNodes(array $node): void + { + } + + /** + * @param ShadowBox $box + */ + public function acceptShadowBox(array $box): void + { + } + + /** + * @param AliasShadowTarget $value + */ + public function acceptPlainShadowAlias(string $value): void + { + } + + /** + * @phpstan-type MethodResult array{ok: true, value: T} + * + * @param MethodResult $result + * + * @return MethodResult + */ + public function handleMethodLevelAlias(array $result): array + { + return $result; + } + + /** + * @param array $input + * + * @return Pair + */ + public function validateInlineVar(array $input): array + { + /** @var Pair $localPair */ + $localPair = $input; + + return $localPair; + } + + public function mutateInlineVarInvalid(): void + { + /** @var Pair $localPair */ + $localPair = [10, 'valid']; + $localPair[0] = -1; + } +} + +/** + * @template TItem + * + * @phpstan-type BoxedPayload array{item: T} + */ +final class GenericAliasClassTemplateHolder +{ + /** + * @var BoxedPayload + */ + private array $payload; + + /** + * @param BoxedPayload $payload + */ + public function __construct(array $payload) + { + $this->payload = $payload; + } + + /** + * @param BoxedPayload $payload + */ + public function replace(array $payload): void + { + $this->payload = $payload; + } + + /** + * @return BoxedPayload + */ + public function get(): array + { + return $this->payload; + } +} + +/** + * @phpstan-import-type Pair from GenericAliasProvider + * @phpstan-import-type Tree from GenericAliasProvider as ImportedTree + * @phpstan-import-type EvenNode from GenericAliasProvider as ImportedEven + */ +final class GenericAliasImporter +{ + /** + * @param Pair $pair + */ + public function acceptImportedPair(array $pair): void + { + } + + /** + * @param Pair $pair + */ + public function acceptImportedDefaultPair(array $pair): void + { + } + + /** + * @param ImportedTree $tree + */ + public function acceptRenamedRecursiveTree(array $tree): void + { + } + + /** + * @param ImportedEven $node + */ + public function acceptImportedMutualNode(array $node): void + { + } +} + +/** + * @phpstan-type FuncPair array{0: TFirst, 1: TSecond} + * + * @param FuncPair $pair + * + * @return FuncPair + */ +function standaloneGenericAliasFunction(array $pair): array +{ + return $pair; +} + +describe('Generic Type Aliases (@phpstan-type Name)', function () { + describe('1. Basic Parameterized Aliases, Sequential Defaults & Nesting', function () { + test('enforces multi-parameter generic alias Pair', function () { + $provider = new GenericAliasProvider(); + + expect($provider->echoPair([10, 'hello']))->toBe([10, 'hello']); + + expect(fn () => $provider->echoPair([-1, 'hello'])) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => $provider->echoPair([10, ''])) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + + test('applies sequential default type arguments (TSecond = TFirst)', function () { + $provider = new GenericAliasProvider(); + + expect($provider->echoSamePair([1, 2]))->toBe([1, 2]); + + expect(fn () => $provider->echoSamePair([1, -2])) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('expands nested instantiations of the same generic alias (Pair>)', function () { + $provider = new GenericAliasProvider(); + + expect($provider->echoNestedPair([42, ['ok', true]]))->toBe([42, ['ok', true]]); + + expect(fn () => $provider->echoNestedPair([42, ['ok', 'not_a_bool']])) + ->toThrow(TypeError::class, 'bool') + ; + }); + + test('expands plain aliases defined from generic aliases and defaults referencing plain aliases', function () { + $provider = new GenericAliasProvider(); + + $provider->acceptIntPairAlias([1, 2]); + expect(fn () => $provider->acceptIntPairAlias([1, 0])) + ->toThrow(TypeError::class, 'positive-int') + ; + + $provider->acceptDefaultRecord(['id' => 1, 'data' => 99]); + expect(fn () => $provider->acceptDefaultRecord(['id' => 1, 'data' => -5])) + ->toThrow(TypeError::class, 'positive-int') + ; + + $provider->acceptStringRecord(['id' => 1, 'data' => 'valid']); + expect(fn () => $provider->acceptStringRecord(['id' => 1, 'data' => ''])) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + + test('enforces union generic alias (ApiResponse) and @psalm-type with =', function () { + $provider = new GenericAliasProvider(); + + expect($provider->handleApiResponse(['ok' => true, 'data' => 123])) + ->toBe(['ok' => true, 'data' => 123]) + ; + expect($provider->handleApiResponse(['ok' => false, 'error' => 'failed'])) + ->toBe(['ok' => false, 'error' => 'failed']) + ; + + expect(fn () => $provider->handleApiResponse(['ok' => true, 'data' => -1])) + ->toThrow(TypeError::class, 'positive-int') + ; + expect(fn () => $provider->handleApiResponse(['ok' => false, 'error' => ''])) + ->toThrow(TypeError::class, 'non-empty-string') + ; + + $provider->acceptPsalmWrapped(['wrapped' => 'ok']); + expect(fn () => $provider->acceptPsalmWrapped(['wrapped' => ''])) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + }); + + describe('2. Upper Bounds (of) & Dependent Bounds', function () { + test('accepts valid subtypes, falls back to upper bound when omitted, and rejects violated concrete bounds', function () { + $provider = new GenericAliasProvider(); + + $provider->acceptPositiveIntBox(['value' => 10]); + expect(fn () => $provider->acceptPositiveIntBox(['value' => 0])) + ->toThrow(TypeError::class, 'positive-int') + ; + + // Omitted arg falls back to bound `int` + $provider->acceptUnparameterizedIntBox(['value' => -42]); + expect(fn () => $provider->acceptUnparameterizedIntBox(['value' => 'not_int'])) + ->toThrow(TypeError::class, 'int') + ; + + // Concrete argument `string` violates `T of int` + expect(fn () => $provider->acceptInvalidIntBoxBound(['value' => 'hello'])) + ->toThrow(TypeError::class) + ; + }); + + test('enforces class hierarchy upper bounds and dependent bounds (U of T)', function () { + $provider = new GenericAliasProvider(); + + $provider->acceptDogCage(['pet' => new AliasDog()]); + expect(fn () => $provider->acceptDogCage(['pet' => new AliasCat()])) + ->toThrow(TypeError::class, AliasDog::class) + ; + + // Concrete argument AliasCar violates `T of AliasAnimal` + expect(fn () => $provider->acceptInvalidCageBound(['pet' => new AliasCar()])) + ->toThrow(TypeError::class) + ; + + $provider->acceptHierarchyPair(['parent' => new AliasCat(), 'child' => new AliasDog()]); + expect(fn () => $provider->acceptHierarchyPair(['parent' => new AliasCat(), 'child' => new AliasCat()])) + ->toThrow(TypeError::class, AliasDog::class) + ; + }); + }); + + describe('3. Composition with Method & Class @template', function () { + test('infers method @template T through generic alias Pair and enforces both param and return', function () { + $provider = new GenericAliasProvider(); + + expect($provider->firstOfPair([10, 20]))->toBe(10) + ->and($provider->firstOfPair(['a', 'b']))->toBe('a') + ; + + expect(fn () => $provider->firstOfPair([10, 'mismatch'])) + ->toThrow(TypeError::class, 'int') + ; + + expect(fn () => $provider->brokenFirstOfPair([10, 20], 'wrong_return')) + ->toThrow(TypeError::class, 'int') + ; + }); + + test('composes generic type alias with reified class-level @template', function () { + $holder = new GenericAliasClassTemplateHolder(['item' => 42]); + + expect($holder->get())->toBe(['item' => 42]); + + $holder->replace(['item' => 99]); + expect($holder->get())->toBe(['item' => 99]); + + expect(fn () => $holder->replace(['item' => 'not_an_int'])) + ->toThrow(TypeError::class, 'int') + ; + }); + }); + + describe('4. Recursive & Mutually Recursive Generic Type Aliases', function () { + test('validates arbitrarily nested recursive Tree and rejects deep leaf violations', function () { + $provider = new GenericAliasProvider(); + + $validTree = [ + 'value' => 1, + 'children' => [ + [ + 'value' => 2, + 'children' => [ + ['value' => 3, 'children' => []], + ], + ], + ], + ]; + expect($provider->acceptPositiveTree($validTree))->toBe($validTree); + + $invalidTree = [ + 'value' => 1, + 'children' => [ + [ + 'value' => 2, + 'children' => [ + ['value' => -5, 'children' => []], + ], + ], + ], + ]; + expect(fn () => $provider->acceptPositiveTree($invalidTree)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('substitutes outer @template U into cyclic targets of recursive Tree', function () { + $provider = new GenericAliasProvider(); + + $validIntTree = [ + 'value' => 1, + 'children' => [ + [ + 'value' => 2, + 'children' => [ + ['value' => 3, 'children' => []], + ], + ], + ], + ]; + expect($provider->acceptGenericTree(10, $validIntTree))->toBe(1); + + $invalidDeepLeafTree = [ + 'value' => 1, + 'children' => [ + [ + 'value' => 2, + 'children' => [ + ['value' => 'not_an_int', 'children' => []], + ], + ], + ], + ]; + expect(fn () => $provider->acceptGenericTree(10, $invalidDeepLeafTree)) + ->toThrow(TypeError::class, 'int') + ; + }); + + test('validates mutually recursive generic aliases (EvenNode <-> OddNode)', function () { + $provider = new GenericAliasProvider(); + + $validChain = [ + 'even' => 2, + 'next' => [ + 'odd' => 3, + 'next' => [ + 'even' => 4, + ], + ], + ]; + $provider->acceptMutuallyRecursiveNodes($validChain); + expect(true)->toBeTrue(); + + $invalidDeepEven = [ + 'even' => 2, + 'next' => [ + 'odd' => 3, + 'next' => [ + 'even' => -4, + ], + ], + ]; + expect(fn () => $provider->acceptMutuallyRecursiveNodes($invalidDeepEven)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + }); + + describe('5. Cross-Class @phpstan-import-type (Direct, Renamed & Recursive)', function () { + test('enforces imported generic aliases with explicit and defaulted arguments', function () { + $importer = new GenericAliasImporter(); + + $importer->acceptImportedPair([5, 'ok']); + expect(fn () => $importer->acceptImportedPair([-5, 'ok'])) + ->toThrow(TypeError::class, 'positive-int') + ; + + $importer->acceptImportedDefaultPair([5, 6]); + expect(fn () => $importer->acceptImportedDefaultPair([5, -6])) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('enforces imported and renamed self-recursive Tree alias (as ImportedTree)', function () { + $importer = new GenericAliasImporter(); + + $importer->acceptRenamedRecursiveTree([ + 'value' => 1, + 'children' => [ + ['value' => 2, 'children' => []], + ], + ]); + + expect(fn () => $importer->acceptRenamedRecursiveTree([ + 'value' => 1, + 'children' => [ + ['value' => -9, 'children' => []], + ], + ]))->toThrow(TypeError::class, 'positive-int'); + }); + + test('enforces imported mutually recursive alias even when sibling alias is not explicitly imported', function () { + $importer = new GenericAliasImporter(); + + $importer->acceptImportedMutualNode([ + 'even' => 2, + 'next' => [ + 'odd' => 3, + 'next' => [ + 'even' => 4, + ], + ], + ]); + + expect(fn () => $importer->acceptImportedMutualNode([ + 'even' => 2, + 'next' => [ + 'odd' => -3, + ], + ]))->toThrow(TypeError::class, 'positive-int'); + }); + }); + + describe('6. Method-Level, Function-Level, Inline @var, Properties & Constants', function () { + test('enforces method-level and standalone function-level generic type aliases', function () { + $provider = new GenericAliasProvider(); + + expect($provider->handleMethodLevelAlias(['ok' => true, 'value' => 10])) + ->toBe(['ok' => true, 'value' => 10]) + ; + expect(fn () => $provider->handleMethodLevelAlias(['ok' => true, 'value' => -1])) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(standaloneGenericAliasFunction([7, 'seven']))->toBe([7, 'seven']); + expect(fn () => standaloneGenericAliasFunction([0, 'zero'])) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('enforces inline @var local variables, mutations, class properties, and constants', function () { + $provider = new GenericAliasProvider(); + + expect(GenericAliasProvider::DEFAULT_PAIR)->toBe([1, 'ok']); + + expect($provider->validateInlineVar([10, 'valid']))->toBe([10, 'valid']); + expect(fn () => $provider->validateInlineVar([-10, 'valid'])) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => $provider->mutateInlineVarInvalid()) + ->toThrow(TypeError::class, 'positive-int') + ; + + $provider->pair = [5, 'updated']; + expect($provider->pair)->toBe([5, 'updated']); + + expect(fn () => $provider->pair = [5, '']) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + }); + + describe('7. Template Parameter Shadowing', function () { + test('local generic alias template shadows both plain aliases and same-namespace classes', function () { + $provider = new GenericAliasProvider(); + + $provider->acceptShadowBox(['val' => 42]); + expect(fn () => $provider->acceptShadowBox(['val' => 'string_should_fail'])) + ->toThrow(TypeError::class, 'positive-int') + ; + expect(fn () => $provider->acceptShadowBox(['val' => new AliasShadowTarget()])) + ->toThrow(TypeError::class, 'positive-int') + ; + + $provider->acceptPlainShadowAlias('plain_string_ok'); + expect(true)->toBeTrue(); + }); + }); +}); From e9f183739b7acf41274c89317a3d6e2066ca524f Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 6 Dec 2026 01:04:56 +0800 Subject: [PATCH 2/3] Implement support for 'new' type in generics and enhance type resolution for class-string --- src/Internal/Checker/InlineChecker.php | 8 +- src/Internal/Checker/ParamChecker.php | 41 +- src/Internal/Docblock/DocblockParser.php | 2 +- src/Internal/Generics/TemplateManager.php | 42 ++ src/Internal/Generics/TemplateSubstitutor.php | 226 ++++++++++- src/Internal/Resolver/SpecialTypeResolver.php | 21 +- src/Internal/Validator/ConstValidator.php | 8 + src/Internal/Validator/GenericValidator.php | 22 ++ .../Generics/TemplateSubstitutorTest.php | 36 ++ .../Generics/NewUtilityTypeTest.php | 363 ++++++++++++++++++ 10 files changed, 749 insertions(+), 20 deletions(-) create mode 100644 tests/TypeChecking/Generics/NewUtilityTypeTest.php diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 4241bf27..c162400f 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -253,7 +253,9 @@ public static function checkVariable( $isObjectGeneric = false; if ($typeNode instanceof GenericTypeNode) { $baseName = strtolower((string) $typeNode->type); - $isObjectGeneric = ! isset(self::ARRAY_TYPES[$baseName]) && ! isset(self::SCALAR_GENERIC_TYPES[$baseName]); + $isObjectGeneric = ! isset(self::ARRAY_TYPES[$baseName]) + && ! isset(self::SCALAR_GENERIC_TYPES[$baseName]) + && $baseName !== 'new'; if ($isObjectGeneric) { if (! Config::isInlineGenericsEnabled() && Config::isInlineObjectsEnabled()) { @@ -1221,6 +1223,10 @@ private static function shouldValidateType(TypeNode $node): bool return Config::isInlineScalarsEnabled(); } + if ($lower === 'new') { + return Config::isInlineObjectsEnabled(); + } + if (Config::isInlineGenericsEnabled()) { return true; } diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 022d501a..77bc9654 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -386,8 +386,34 @@ private static function refineInferredTypeFromBound(mixed $val, TypeNode $bound, return self::refineInferredTypeFromBound($val, $bound->type, $defaultInferred); } + if ($bound instanceof IdentifierTypeNode && strtolower($bound->name) === 'class-string') { + if (\is_string($val) && ClassNameValidator::isValidClassString($val)) { + return new \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode( + new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode( + ltrim($val, '\\'), + \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode::SINGLE_QUOTED + ) + ); + } + + return $defaultInferred; + } + if ($bound instanceof GenericTypeNode) { $base = strtolower((string) $bound->type); + if ($base === 'class-string') { + if (\is_string($val) && ClassNameValidator::isValidClassString($val)) { + return new \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode( + new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode( + ltrim($val, '\\'), + \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode::SINGLE_QUOTED + ) + ); + } + + return $defaultInferred; + } + if ($base === 'key-of' || $base === 'value-of') { $expanded = TemplateManager::expandKeyOrValueOf($bound); if ($expanded !== null) { @@ -404,6 +430,9 @@ private static function refineInferredTypeFromBound(mixed $val, TypeNode $bound, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode => true, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode => false, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode => null, + $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode + && $bound->constExpr->className !== '' + && strtolower($bound->constExpr->name) === 'class' => ltrim($bound->constExpr->className, '\\'), default => null, }; @@ -3078,9 +3107,13 @@ private static function typeContainsConst(TypeNode $node): bool return true; } + if ($node instanceof IdentifierTypeNode) { + return strtolower($node->name) === 'class-string'; + } + if ($node instanceof GenericTypeNode) { $base = strtolower((string) $node->type); - if ($base === 'key-of' || $base === 'value-of') { + if ($base === 'key-of' || $base === 'value-of' || $base === 'class-string') { return true; } } @@ -3258,7 +3291,11 @@ private static function tryWidenTemplate( $boundErr = $registry->validate($val, $resolvedBound, $context . ' (template ' . $templateName . ')'); if ($boundErr === null) { - $newInferred = TemplateManager::inferTypeFromValue($val); + $newInferred = self::refineInferredTypeFromBound( + $val, + $resolvedBound, + TemplateManager::inferTypeFromValue($val) + ); $unifiedType = self::unifyTypes($currentType, $newInferred); TemplateManager::bindTemplate($function, $targetObj, $templateName, $unifiedType); diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index 8e1301e1..76953d30 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -373,7 +373,7 @@ private static function computeContractFlags( if (! ($inner instanceof IdentifierTypeNode)) { if ($inner instanceof GenericTypeNode) { $base = strtolower((string) $inner->type); - if (! \in_array($base, ['class-string', 'int', 'integer', 'float', 'double', 'int-mask', 'int-mask-of', 'key-of', 'value-of'], true)) { + if (! \in_array($base, ['class-string', 'int', 'integer', 'float', 'double', 'int-mask', 'int-mask-of', 'key-of', 'value-of', 'new'], true)) { $paramsNeedPreInference = true; } } else { diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index bf9cfbc9..d58023a8 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -3470,6 +3470,17 @@ private static function extractLiteralConstValue(ConstTypeNode $node, bool &$ok) return null; } + if ($expr instanceof ConstFetchNode) { + if ($expr->className !== '' && strtolower($expr->name) === 'class') { + return ltrim($expr->className, '\\'); + } + + $constVal = self::resolveRawConstantValue($expr->className, $expr->name); + if ($constVal !== null) { + return $constVal; + } + } + $ok = false; return null; @@ -3572,6 +3583,12 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::checkVariance($existing, $expandedExpected, $variance); } } + if ($baseExpected === 'new' && isset($expected->genericTypes[0])) { + $resolvedNew = TemplateSubstitutor::resolveNewType($expected->genericTypes[0]); + if ($resolvedNew !== null) { + return self::checkVariance($existing, $resolvedNew, $variance); + } + } } if ($existing instanceof GenericTypeNode) { @@ -3582,6 +3599,12 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::checkVariance($expandedExisting, $expected, $variance); } } + if ($baseExisting === 'new' && isset($existing->genericTypes[0])) { + $resolvedNew = TemplateSubstitutor::resolveNewType($existing->genericTypes[0]); + if ($resolvedNew !== null) { + return self::checkVariance($resolvedNew, $expected, $variance); + } + } } if ($expected instanceof IdentifierTypeNode) { @@ -3601,6 +3624,25 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } } + if ($existing instanceof ConstTypeNode) { + $litOk = false; + $litVal = self::extractLiteralConstValue($existing, $litOk); + if ($litOk && \is_string($litVal) && ClassNameValidator::isValidClassString($litVal)) { + if ($expected instanceof IdentifierTypeNode && strtolower($expected->name) === 'class-string') { + return true; + } + + if ($expected instanceof GenericTypeNode && strtolower((string) $expected->type) === 'class-string') { + $targetBound = $expected->genericTypes[0] ?? null; + if ($targetBound === null) { + return true; + } + + return self::checkVariance(new IdentifierTypeNode(ltrim($litVal, '\\')), $targetBound, GenericTypeNode::VARIANCE_COVARIANT); + } + } + } + if ($variance === GenericTypeNode::VARIANCE_INVARIANT && $existing::class === $expected::class) { if ((string) $existing === (string) $expected) { return true; diff --git a/src/Internal/Generics/TemplateSubstitutor.php b/src/Internal/Generics/TemplateSubstitutor.php index 7f6559e9..ad7a2726 100644 --- a/src/Internal/Generics/TemplateSubstitutor.php +++ b/src/Internal/Generics/TemplateSubstitutor.php @@ -6,6 +6,7 @@ use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; @@ -25,7 +26,10 @@ use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use TypePHP\Internal\Diagnostic\DebugLog; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; /** * @internal Recursively substitutes template placeholders (like T) with their bound concrete types (like int). @@ -377,6 +381,148 @@ private static function substituteParameterConditional( ); } + /** + * @param array $boundTemplates + * @param array $declaredTemplates + * @param array $visited + * @param array $recursiveMemo + */ + /** + * Evaluates the inner type argument of `new` into its instantiated object TypeNode, + * or returns null if the argument still contains unresolved templates. + */ + public static function resolveNewType(TypeNode $arg): ?TypeNode + { + while ($arg instanceof NullableTypeNode) { + $arg = $arg->type; + } + + if ($arg instanceof UnionTypeNode) { + $resolvedMembers = []; + foreach ($arg->types as $member) { + $resolved = self::resolveNewType($member); + if ($resolved === null) { + return null; + } + $resolvedMembers[] = $resolved; + } + + return $resolvedMembers !== [] ? self::normalizeUnion($resolvedMembers) : new IdentifierTypeNode('object'); + } + + if ($arg instanceof ConstTypeNode) { + $expr = $arg->constExpr; + if ($expr instanceof ConstExprStringNode) { + $className = ltrim($expr->value, '\\'); + if (ClassNameValidator::isValidClassString($className)) { + $resolved = new IdentifierTypeNode($className); + $resolved->setAttribute('typephp_resolved', true); + + return $resolved; + } + + return null; + } + + if ($expr instanceof ConstFetchNode) { + if ($expr->className !== '' && strtolower($expr->name) === 'class') { + $className = ltrim($expr->className, '\\'); + $lowerClass = strtolower($className); + if ( + $lowerClass !== 'self' + && $lowerClass !== 'static' + && $lowerClass !== 'parent' + && $lowerClass !== '$this' + && ClassNameValidator::isValid($className) + ) { + $resolved = new IdentifierTypeNode($className); + $resolved->setAttribute('typephp_resolved', true); + + return $resolved; + } + + return null; + } + + $rawVal = self::resolveConstantFetchString($expr->className, $expr->name); + if ($rawVal !== null) { + $className = ltrim($rawVal, '\\'); + if (ClassNameValidator::isValidClassString($className)) { + $resolved = new IdentifierTypeNode($className); + $resolved->setAttribute('typephp_resolved', true); + + return $resolved; + } + } + + return null; + } + + return null; + } + + if ($arg instanceof GenericTypeNode) { + $base = strtolower((string) $arg->type); + if ($base === 'class-string') { + return $arg->genericTypes[0] ?? new IdentifierTypeNode('object'); + } + + if ($base === 'value-of' || $base === 'key-of') { + $expanded = TemplateManager::expandKeyOrValueOf($arg); + if ($expanded !== null) { + return self::resolveNewType($expanded); + } + } + + return null; + } + + if ($arg instanceof IdentifierTypeNode) { + $lower = strtolower($arg->name); + if ($lower === 'class-string' || $lower === 'mixed' || $lower === 'string' || $lower === 'object') { + return new IdentifierTypeNode('object'); + } + + return null; + } + + return null; + } + + private static function resolveConstantFetchString(string $fqcn, string $constName): ?string + { + try { + if ($fqcn !== '') { + $lowerClass = strtolower($fqcn); + if ($lowerClass === 'self' || $lowerClass === 'static' || $lowerClass === 'parent' || $lowerClass === '$this') { + return null; + } + + if (ClassNameValidator::isValid($fqcn) && (class_exists($fqcn) || interface_exists($fqcn) || enum_exists($fqcn))) { + /** @var class-string $fqcn */ + $refClass = new \ReflectionClass($fqcn); + if ($refClass->hasConstant($constName)) { + $val = $refClass->getConstant($constName); + + return \is_string($val) ? $val : null; + } + } + + return null; + } + + if (\defined($constName)) { + $val = \constant($constName); + + return \is_string($val) ? $val : null; + } + } catch (\Throwable $e) { + DebugLog::swallowed($e); // @codeCoverageIgnore + } + + return null; + } + /** * @param array $boundTemplates * @param array $declaredTemplates @@ -389,7 +535,7 @@ private static function substituteGeneric( array $declaredTemplates, array $visited, array &$recursiveMemo - ): GenericTypeNode { + ): TypeNode { $type = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); $changed = ($type !== $node->type); $genericTypes = []; @@ -401,12 +547,20 @@ private static function substituteGeneric( $genericTypes[] = $sub; } + $baseType = $type instanceof IdentifierTypeNode ? $type : $node->type; + if ($baseType instanceof IdentifierTypeNode && strtolower($baseType->name) === 'new' && isset($genericTypes[0])) { + $resolvedNew = self::resolveNewType($genericTypes[0]); + if ($resolvedNew !== null) { + return $resolvedNew; + } + } + if (! $changed) { return $node; } return new GenericTypeNode( - $type instanceof IdentifierTypeNode ? $type : $node->type, + $baseType, $genericTypes, $node->variances ); @@ -491,18 +645,41 @@ private static function substituteOffsetAccess( $baseType = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); $offsetType = self::substituteNode($node->offset, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); - if ($baseType instanceof ArrayShapeNode) { - $offsetKey = null; - if ($offsetType instanceof ConstTypeNode) { - if ($offsetType->constExpr instanceof ConstExprStringNode) { - $offsetKey = $offsetType->constExpr->value; - } elseif ($offsetType->constExpr instanceof ConstExprIntegerNode) { - $offsetKey = (int) $offsetType->constExpr->value; + if ($offsetType instanceof UnionTypeNode) { + $unionResults = []; + $allResolved = true; + foreach ($offsetType->types as $offsetMember) { + $memberResult = self::resolveSingleOffset($baseType, $offsetMember); + if ($memberResult === null) { + $allResolved = false; + + break; } - } elseif ($offsetType instanceof IdentifierTypeNode) { - $offsetKey = $offsetType->name; + $unionResults[] = $memberResult; } + if ($allResolved && $unionResults !== []) { + return self::normalizeUnion($unionResults); + } + } else { + $resolved = self::resolveSingleOffset($baseType, $offsetType); + if ($resolved !== null) { + return $resolved; + } + } + + if ($baseType === $node->type && $offsetType === $node->offset) { + return $node; + } + + return new OffsetAccessTypeNode($baseType, $offsetType); + } + + private static function resolveSingleOffset(TypeNode $baseType, TypeNode $offsetType): ?TypeNode + { + if ($baseType instanceof ArrayShapeNode) { + $offsetKey = self::extractOffsetKey($offsetType); + if ($offsetKey !== null) { $autoIdx = 0; foreach ($baseType->items as $item) { @@ -526,6 +703,15 @@ private static function substituteOffsetAccess( return $baseType->unsealedType->valueType; } } + } elseif ($baseType instanceof ConstTypeNode && $baseType->constExpr instanceof ConstFetchNode) { + $offsetKey = self::extractOffsetKey($offsetType); + if ($offsetKey !== null) { + return SpecialTypeResolver::resolveConstantOffsetValue( + $baseType->constExpr->className, + $baseType->constExpr->name, + $offsetKey + ); + } } elseif ($baseType instanceof GenericTypeNode) { $baseName = strtolower((string) $baseType->type); if (\in_array($baseName, ['list', 'non-empty-list', 'non-empty-array-list'], true)) { @@ -538,10 +724,22 @@ private static function substituteOffsetAccess( return $baseType->type; } - if ($baseType === $node->type && $offsetType === $node->offset) { - return $node; + return null; + } + + private static function extractOffsetKey(TypeNode $offsetType): string|int|null + { + if ($offsetType instanceof ConstTypeNode) { + if ($offsetType->constExpr instanceof ConstExprStringNode) { + return $offsetType->constExpr->value; + } + if ($offsetType->constExpr instanceof ConstExprIntegerNode) { + return (int) $offsetType->constExpr->value; + } + } elseif ($offsetType instanceof IdentifierTypeNode) { + return $offsetType->name; } - return new OffsetAccessTypeNode($baseType, $offsetType); + return null; } } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 83e3018d..534c0aab 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -103,6 +103,7 @@ final class SpecialTypeResolver 'value-of' => true, 'int-mask' => true, 'int-mask-of' => true, + 'new' => true, 'number' => true, 'numeric' => true, 'truthy' => true, @@ -1178,13 +1179,17 @@ private static function extractItemKey(mixed $keyName): string|int|null */ private static function getClassConstant(string $fqcn, string $constName, bool $autoload = true): mixed { + if ($fqcn === '') { + return \defined($constName) ? \constant($constName) : null; + } + if (! isset(self::$classConstantCache[$fqcn][$constName]) && ! \array_key_exists($constName, self::$classConstantCache[$fqcn] ?? [])) { if (! $autoload && ! self::symbolExists($fqcn, false)) { return null; } $val = null; - if ($fqcn !== '' && self::symbolExists($fqcn, $autoload)) { + if (self::symbolExists($fqcn, $autoload)) { try { /** @var class-string $fqcn */ $refClass = new \ReflectionClass($fqcn); @@ -1201,7 +1206,7 @@ private static function getClassConstant(string $fqcn, string $constName, bool $ return self::$classConstantCache[$fqcn][$constName]; } - private static function resolveConstantOffsetValue(string $fqcn, string $constName, string|int $offsetKey, bool $autoload = true): ?TypeNode + public static function resolveConstantOffsetValue(string $fqcn, string $constName, string|int $offsetKey, bool $autoload = true): ?TypeNode { $constValue = self::getClassConstant($fqcn, $constName, $autoload); if (\is_array($constValue) && \array_key_exists($offsetKey, $constValue)) { @@ -1212,6 +1217,18 @@ private static function resolveConstantOffsetValue(string $fqcn, string $constNa if (\is_int($val)) { return new ConstTypeNode(new ConstExprIntegerNode((string) $val)); } + if (\is_float($val)) { + return new ConstTypeNode(new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode((string) $val)); + } + if ($val === true) { + return new ConstTypeNode(new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode()); + } + if ($val === false) { + return new ConstTypeNode(new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode()); + } + if ($val === null) { + return new ConstTypeNode(new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode()); + } } return null; diff --git a/src/Internal/Validator/ConstValidator.php b/src/Internal/Validator/ConstValidator.php index f8e7e938..08fbe58f 100644 --- a/src/Internal/Validator/ConstValidator.php +++ b/src/Internal/Validator/ConstValidator.php @@ -117,6 +117,14 @@ private static function resolveSingleConstantValue(string $className, string $co return [false, null]; } + if (strtolower($constName) === 'class') { + if (ClassNameValidator::isValid($className)) { + return self::$classConstantCache[$className][$constName] = [true, ltrim($className, '\\')]; + } + + return self::$classConstantCache[$className][$constName] = [false, null]; + } + if (isset(self::$classConstantCache[$className]) && \array_key_exists($constName, self::$classConstantCache[$className])) { return self::$classConstantCache[$className][$constName]; } diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 4f202854..85856acf 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -22,6 +22,7 @@ use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Generics\TemplateManager; +use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; @@ -44,6 +45,7 @@ final class GenericValidator implements TypeValidatorInterface private const KIND_INT_MASK_OF = 10; private const KIND_OBJECT_GENERIC = 11; private const KIND_FLOAT_RANGE = 12; + private const KIND_NEW_OBJECT = 13; private const BUILTIN_GENERICS = [ 'int' => true, @@ -64,6 +66,7 @@ final class GenericValidator implements TypeValidatorInterface 'value-of' => true, 'int-mask' => true, 'int-mask-of' => true, + 'new' => true, ]; /** @@ -263,6 +266,19 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return $this->validateIntMaskOf($value, $genericNode, $context, $isSensitive); } + if ($kind === self::KIND_NEW_OBJECT) { + $resolvedTarget = $compiled[1]; + if ($resolvedTarget instanceof TypeNode) { + return $registry->validate($value, $resolvedTarget, $context, $isSensitive); + } + + if (! \is_object($value)) { + return ErrorFactory::createError($context . ' must be of type object, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + return null; + } + if ($kind === self::KIND_OBJECT_GENERIC) { $targetClass = $compiled[1]; if (! \is_string($targetClass)) { @@ -317,6 +333,12 @@ private function compileGeneric(GenericTypeNode $node): array 'value-of' => [self::KIND_VALUE_OF, null], 'int-mask' => [self::KIND_INT_MASK, null], 'int-mask-of' => [self::KIND_INT_MASK_OF, null], + 'new' => [ + self::KIND_NEW_OBJECT, + isset($node->genericTypes[0]) + ? TemplateSubstitutor::resolveNewType($node->genericTypes[0]) + : new IdentifierTypeNode('object'), + ], default => [ self::KIND_OBJECT_GENERIC, ClassNameValidator::isValid($typeName) ? $typeName : null, diff --git a/tests/Internal/Generics/TemplateSubstitutorTest.php b/tests/Internal/Generics/TemplateSubstitutorTest.php index 39002dfe..918215ea 100644 --- a/tests/Internal/Generics/TemplateSubstitutorTest.php +++ b/tests/Internal/Generics/TemplateSubstitutorTest.php @@ -240,4 +240,40 @@ expect((string) $result2->items[0]->valueType)->toBe('string'); }); + + test('resolves new for literal class-strings, ::class fetches, class-string, unions, and constant array offsets', function () { + $newT = new GenericTypeNode(new IdentifierTypeNode('new'), [new IdentifierTypeNode('T')]); + + $resString = TemplateSubstitutor::substitute($newT, [ + 'T' => new PHPStan\PhpDocParser\Ast\Type\ConstTypeNode( + new ConstExprStringNode(stdClass::class, ConstExprStringNode::SINGLE_QUOTED) + ), + ]); + expect((string) $resString)->toBe(stdClass::class); + + $resClassConst = TemplateSubstitutor::substitute($newT, [ + 'T' => new PHPStan\PhpDocParser\Ast\Type\ConstTypeNode( + new PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode(DateTimeImmutable::class, 'class') + ), + ]); + expect((string) $resClassConst)->toBe(DateTimeImmutable::class); + + $resClassString = TemplateSubstitutor::substitute($newT, [ + 'T' => new GenericTypeNode(new IdentifierTypeNode('class-string'), [new IdentifierTypeNode(DateTimeInterface::class)]), + ]); + expect((string) $resClassString)->toBe(DateTimeInterface::class); + + $resBareClassString = TemplateSubstitutor::substitute($newT, [ + 'T' => new IdentifierTypeNode('class-string'), + ]); + expect((string) $resBareClassString)->toBe('object'); + + $resUnion = TemplateSubstitutor::substitute($newT, [ + 'T' => new UnionTypeNode([ + new PHPStan\PhpDocParser\Ast\Type\ConstTypeNode(new PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode(DateTime::class, 'class')), + new PHPStan\PhpDocParser\Ast\Type\ConstTypeNode(new PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode(DateTimeImmutable::class, 'class')), + ]), + ]); + expect((string) $resUnion)->toBe('(DateTime | DateTimeImmutable)'); + }); }); diff --git a/tests/TypeChecking/Generics/NewUtilityTypeTest.php b/tests/TypeChecking/Generics/NewUtilityTypeTest.php new file mode 100644 index 00000000..815b220b --- /dev/null +++ b/tests/TypeChecking/Generics/NewUtilityTypeTest.php @@ -0,0 +1,363 @@ +, cat: class-string} + */ +final class NewUtilityFactory +{ + public const DEFAULT_PET_CLASS = NewDog::class; + + public const CLASS_MAP = [ + 'dog' => NewDog::class, + 'cat' => NewCat::class, + ]; + + /** + * @template T of class-string + * + * @param T $class + * + * @return new + */ + public function create(string $class): NewAnimal + { + return new $class(); + } + + /** + * @template T of class-string + * + * @param T $class + * + * @return new + */ + public function createBroken(string $class, NewAnimal $wrongInstance): NewAnimal + { + return $wrongInstance; + } + + /** + * @template T of class-string + * + * @param T $class + * + * @return new + */ + public function createAny(string $class): object + { + return new $class(); + } + + /** + * @template T of class-string + * + * @param T $class + * @param new $instance + */ + public function registerInstance(string $class, NewAnimal $instance): void + { + } + + /** + * @template T of class-string + * + * @param T $first + * @param T $second + * + * @return new + */ + public function pickOne(string $first, string $second, NewAnimal $returned): NewAnimal + { + return $returned; + } + + /** + * @return new + */ + public function returnConcreteClassConst(object $value): object + { + return $value; + } + + /** + * @return new + */ + public function returnFromClassConstant(object $value): object + { + return $value; + } + + /** + * @return new> + */ + public function returnFromClassStringBound(object $value): object + { + return $value; + } + + /** + * @return new + */ + public function returnFromUnionClassConst(object $value): object + { + return $value; + } + + /** + * @template K of key-of + * + * @param K $key + * + * @return new + */ + public function createFromShapeAlias(string $key, NewAnimal $instance): NewAnimal + { + return $instance; + } + + /** + * @template K of key-of + * + * @param K $key + * + * @return new + */ + public function createFromBoundedShapeAlias(string $key, NewAnimal $instance): NewAnimal + { + return $instance; + } + + /** + * @template K of key-of + * + * @param K $key + * + * @return new + */ + public function createFromConstArray(string $key, NewAnimal $instance): NewAnimal + { + return $instance; + } + + /** + * @return new> + */ + public function returnFromValueOfConstMap(object $instance): object + { + return $instance; + } + + public function checkInlineNewVar(object $value): object + { + /** @var new $dog */ + $dog = $value; + + return $dog; + } +} + +/** + * @template T of class-string + */ +final class TypedClassFactory +{ + /** + * @param T $class + */ + public function __construct(private string $class) + { + } + + /** + * @return new + */ + public function make(): NewAnimal + { + return new ($this->class)(); + } + + /** + * @return new + */ + public function makeWrong(NewAnimal $wrong): NewAnimal + { + return $wrong; + } + + /** + * @param new $instance + */ + public function accept(NewAnimal $instance): void + { + } +} + +/** + * @param TypedClassFactory $factory + */ +function acceptDogFactory(TypedClassFactory $factory): NewAnimal +{ + return $factory->make(); +} + +describe('new Utility Type', function () { + describe('1. Standalone Method Templates (@template T of class-string)', function () { + test('instantiates and enforces exact runtime class for new return type', function () { + $factory = new NewUtilityFactory(); + + expect($factory->create(NewDog::class))->toBeInstanceOf(NewDog::class) + ->and($factory->create(NewCat::class))->toBeInstanceOf(NewCat::class) + ->and($factory->createAny(stdClass::class))->toBeInstanceOf(stdClass::class) + ; + + expect(fn () => $factory->createBroken(NewDog::class, new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect(fn () => $factory->create(NewCar::class)) + ->toThrow(TypeError::class, NewAnimal::class) + ; + }); + + test('enforces new on subsequent parameters using bound class-string template T', function () { + $factory = new NewUtilityFactory(); + + $factory->registerInstance(NewDog::class, new NewDog()); + expect(true)->toBeTrue(); + + expect(fn () => $factory->registerInstance(NewDog::class, new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + }); + + test('widens template T across two class-string parameters and distributes new over union', function () { + $factory = new NewUtilityFactory(); + + expect($factory->pickOne(NewDog::class, NewCat::class, new NewDog()))->toBeInstanceOf(NewDog::class) + ->and($factory->pickOne(NewDog::class, NewCat::class, new NewCat()))->toBeInstanceOf(NewCat::class) + ; + + expect(fn () => $factory->pickOne(NewDog::class, NewCat::class, new NewAnimal())) + ->toThrow(TypeError::class) + ; + }); + }); + + describe('2. Concrete & Utility Arguments Inside new<...>', function () { + test('enforces new, new, new>, and new', function () { + $factory = new NewUtilityFactory(); + + expect($factory->returnConcreteClassConst(new NewDog()))->toBeInstanceOf(NewDog::class); + expect(fn () => $factory->returnConcreteClassConst(new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect($factory->returnFromClassConstant(new NewDog()))->toBeInstanceOf(NewDog::class); + expect(fn () => $factory->returnFromClassConstant(new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect($factory->returnFromClassStringBound(new NewCat()))->toBeInstanceOf(NewCat::class); + expect(fn () => $factory->returnFromClassStringBound(new NewCar())) + ->toThrow(TypeError::class, NewAnimal::class) + ; + + expect($factory->returnFromUnionClassConst(new NewDog()))->toBeInstanceOf(NewDog::class) + ->and($factory->returnFromUnionClassConst(new NewCat()))->toBeInstanceOf(NewCat::class) + ; + expect(fn () => $factory->returnFromUnionClassConst(new NewCar())) + ->toThrow(TypeError::class) + ; + }); + + test('enforces new on array shape aliases, constant arrays, and value-of', function () { + $factory = new NewUtilityFactory(); + + expect($factory->createFromShapeAlias('dog', new NewDog()))->toBeInstanceOf(NewDog::class) + ->and($factory->createFromShapeAlias('cat', new NewCat()))->toBeInstanceOf(NewCat::class) + ; + expect(fn () => $factory->createFromShapeAlias('dog', new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect($factory->createFromBoundedShapeAlias('cat', new NewCat()))->toBeInstanceOf(NewCat::class); + expect(fn () => $factory->createFromBoundedShapeAlias('cat', new NewDog())) + ->toThrow(TypeError::class, NewCat::class) + ; + + expect($factory->createFromConstArray('dog', new NewDog()))->toBeInstanceOf(NewDog::class) + ->and($factory->createFromConstArray('cat', new NewCat()))->toBeInstanceOf(NewCat::class) + ; + expect(fn () => $factory->createFromConstArray('dog', new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect($factory->returnFromValueOfConstMap(new NewDog()))->toBeInstanceOf(NewDog::class); + expect(fn () => $factory->returnFromValueOfConstMap(new NewCar())) + ->toThrow(TypeError::class) + ; + }); + + test('enforces inline @var new', function () { + $factory = new NewUtilityFactory(); + + expect($factory->checkInlineNewVar(new NewDog()))->toBeInstanceOf(NewDog::class); + expect(fn () => $factory->checkInlineNewVar(new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + }); + }); + + describe('3. Class-Level Generic Factory with @template T of class-string', function () { + test('binds literal class-string on instance and enforces new on methods and generic parameters', function () { + $dogFactory = new TypedClassFactory(NewDog::class); + $catFactory = new TypedClassFactory(NewCat::class); + + expect($dogFactory->make())->toBeInstanceOf(NewDog::class) + ->and($catFactory->make())->toBeInstanceOf(NewCat::class) + ->and(acceptDogFactory($dogFactory))->toBeInstanceOf(NewDog::class) + ; + + $dogFactory->accept(new NewDog()); + expect(fn () => $dogFactory->accept(new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect(fn () => $dogFactory->makeWrong(new NewCat())) + ->toThrow(TypeError::class, NewDog::class) + ; + + expect(fn () => acceptDogFactory($catFactory)) + ->toThrow(TypeError::class) + ; + + /** @var TypedClassFactory $preBound */ + $preBound = new TypedClassFactory(NewDog::class); + expect($preBound->make())->toBeInstanceOf(NewDog::class); + }); + }); +}); From c829488f88c5dd5a6ed8b97469005ecd209df6c1 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 6 Dec 2026 01:20:13 +0800 Subject: [PATCH 3/3] Implement Support for enforcement of class-string-map<...>, array, and Unsealed Shapes array{..., ...} annoations --- .../Elimination/EliminationSafetyPolicy.php | 6 + src/Internal/Checker/ConditionalChecker.php | 104 ++++- src/Internal/Checker/InlineChecker.php | 4 +- src/Internal/Docblock/DocblockParser.php | 117 ++++- src/Internal/Generics/TemplateManager.php | 49 ++- src/Internal/Generics/TemplateSubstitutor.php | 40 +- src/Internal/Resolver/SpecialTypeResolver.php | 69 ++- .../Validator/ArrayShapeValidator.php | 37 ++ src/Internal/Validator/GenericValidator.php | 259 ++++++++++- .../KeyDeclaredTemplateArrayTest.php | 411 ++++++++++++++++++ 10 files changed, 1028 insertions(+), 68 deletions(-) create mode 100644 tests/TypeChecking/ArraysAndShapes/KeyDeclaredTemplateArrayTest.php diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index 42a4117a..611a824c 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -19,6 +19,7 @@ use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -48,6 +49,7 @@ final class EliminationSafetyPolicy 'array' => true, 'non-empty-array' => true, 'iterable' => true, + 'class-string-map' => true, ]; /** @@ -176,6 +178,10 @@ public static function containsObjectGeneric(TypeNode $typeNode): bool $typeNode = $typeNode->type; } + if ($typeNode instanceof TemplateDeclarationTypeNode) { + return self::containsObjectGeneric($typeNode->bound); + } + if ($typeNode instanceof GenericTypeNode) { $baseName = strtolower((string) $typeNode->type); if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) { diff --git a/src/Internal/Checker/ConditionalChecker.php b/src/Internal/Checker/ConditionalChecker.php index ddd3365f..3bb53c9f 100644 --- a/src/Internal/Checker/ConditionalChecker.php +++ b/src/Internal/Checker/ConditionalChecker.php @@ -19,6 +19,7 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionClass; @@ -55,6 +56,10 @@ public static function containsConditional(TypeNode $node): bool return true; } + if ($node instanceof TemplateDeclarationTypeNode) { + return self::containsConditional($node->bound); + } + self::$containsConditionalCache ??= new \WeakMap(); if (isset(self::$containsConditionalCache[$node])) { return self::$containsConditionalCache[$node]; @@ -73,6 +78,10 @@ private static function computeContainsConditional(TypeNode $node): bool return true; } + if ($node instanceof TemplateDeclarationTypeNode) { + return self::containsConditional($node->bound); + } + if ($node instanceof GenericTypeNode) { if (self::containsConditional($node->type)) { return true; @@ -142,20 +151,22 @@ private static function computeContainsConditional(TypeNode $node): bool * * @param array $vars * @param array $boundTemplates + * @param array $deferredTemplates */ public static function resolve( TypeNode $typeNode, array $vars, array $boundTemplates, TypeValidatorRegistry $registry, - string $function = '' + string $function = '', + array $deferredTemplates = [] ): TypeNode { if ($typeNode instanceof ConditionalTypeForParameterNode) { - return self::resolveParameterConditional($typeNode, $vars, $boundTemplates, $registry, $function); + return self::resolveParameterConditional($typeNode, $vars, $boundTemplates, $registry, $function, $deferredTemplates); } if ($typeNode instanceof ConditionalTypeNode) { - return self::resolveTemplateConditional($typeNode, $vars, $boundTemplates, $registry, $function); + return self::resolveTemplateConditional($typeNode, $vars, $boundTemplates, $registry, $function, $deferredTemplates); } if (! self::containsConditional($typeNode)) { @@ -163,18 +174,42 @@ public static function resolve( } if ($typeNode instanceof NullableTypeNode) { - return new NullableTypeNode(self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function)); + return new NullableTypeNode(self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function, $deferredTemplates)); } if ($typeNode instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function)); + return new ArrayTypeNode(self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function, $deferredTemplates)); + } + + if ($typeNode instanceof TemplateDeclarationTypeNode) { + $resolvedBound = self::resolve($typeNode->bound, $vars, $boundTemplates, $registry, $function, $deferredTemplates); + + return $resolvedBound === $typeNode->bound + ? $typeNode + : new TemplateDeclarationTypeNode($typeNode->name, $resolvedBound); } if ($typeNode instanceof GenericTypeNode) { - $genericType = self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function); + $genericType = self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function, $deferredTemplates); + $isClassStringMap = $genericType instanceof IdentifierTypeNode + && strtolower($genericType->name) === 'class-string-map'; + + $argBound = $boundTemplates; + $argDeferred = $deferredTemplates; $genericTypes = []; - foreach ($typeNode->genericTypes as $gt) { - $genericTypes[] = self::resolve($gt, $vars, $boundTemplates, $registry, $function); + + foreach ($typeNode->genericTypes as $idx => $gt) { + if ($idx === 0 && $gt instanceof TemplateDeclarationTypeNode) { + $genericTypes[] = self::resolve($gt, $vars, $boundTemplates, $registry, $function, $deferredTemplates); + unset($argBound[$gt->name]); + $argDeferred[$gt->name] = true; + } elseif ($idx === 0 && $isClassStringMap && $gt instanceof IdentifierTypeNode) { + $genericTypes[] = $gt; + unset($argBound[$gt->name]); + $argDeferred[$gt->name] = true; + } else { + $genericTypes[] = self::resolve($gt, $vars, $argBound, $registry, $function, $argDeferred); + } } return new GenericTypeNode( @@ -187,7 +222,7 @@ public static function resolve( if ($typeNode instanceof UnionTypeNode) { $types = []; foreach ($typeNode->types as $t) { - $types[] = self::resolve($t, $vars, $boundTemplates, $registry, $function); + $types[] = self::resolve($t, $vars, $boundTemplates, $registry, $function, $deferredTemplates); } return new UnionTypeNode($types); @@ -196,7 +231,7 @@ public static function resolve( if ($typeNode instanceof IntersectionTypeNode) { $types = []; foreach ($typeNode->types as $t) { - $types[] = self::resolve($t, $vars, $boundTemplates, $registry, $function); + $types[] = self::resolve($t, $vars, $boundTemplates, $registry, $function, $deferredTemplates); } return new IntersectionTypeNode($types); @@ -208,16 +243,22 @@ public static function resolve( $newItems[] = new ArrayShapeItemNode( $item->keyName, $item->optional, - self::resolve($item->valueType, $vars, $boundTemplates, $registry, $function) + self::resolve($item->valueType, $vars, $boundTemplates, $registry, $function, $deferredTemplates) ); } $newUnsealed = null; if ($typeNode->unsealedType !== null) { + $valBound = $boundTemplates; + $valDeferred = $deferredTemplates; $unsealedKey = $typeNode->unsealedType->keyType !== null - ? self::resolve($typeNode->unsealedType->keyType, $vars, $boundTemplates, $registry, $function) + ? self::resolve($typeNode->unsealedType->keyType, $vars, $boundTemplates, $registry, $function, $deferredTemplates) : null; - $unsealedVal = self::resolve($typeNode->unsealedType->valueType, $vars, $boundTemplates, $registry, $function); + if ($typeNode->unsealedType->keyType instanceof TemplateDeclarationTypeNode) { + unset($valBound[$typeNode->unsealedType->keyType->name]); + $valDeferred[$typeNode->unsealedType->keyType->name] = true; + } + $unsealedVal = self::resolve($typeNode->unsealedType->valueType, $vars, $valBound, $registry, $function, $valDeferred); $newUnsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey); } @@ -234,7 +275,7 @@ public static function resolve( $newItems[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::resolve($item->valueType, $vars, $boundTemplates, $registry, $function) + self::resolve($item->valueType, $vars, $boundTemplates, $registry, $function, $deferredTemplates) ); } @@ -245,7 +286,7 @@ public static function resolve( $parameters = []; foreach ($typeNode->parameters as $param) { $parameters[] = new CallableTypeParameterNode( - self::resolve($param->type, $vars, $boundTemplates, $registry, $function), + self::resolve($param->type, $vars, $boundTemplates, $registry, $function, $deferredTemplates), $param->isReference, $param->isVariadic, $param->parameterName, @@ -253,7 +294,7 @@ public static function resolve( ); } - $returnType = self::resolve($typeNode->returnType, $vars, $boundTemplates, $registry, $function); + $returnType = self::resolve($typeNode->returnType, $vars, $boundTemplates, $registry, $function, $deferredTemplates); return new CallableTypeNode( $typeNode->identifier, @@ -265,8 +306,8 @@ public static function resolve( if ($typeNode instanceof OffsetAccessTypeNode) { return new OffsetAccessTypeNode( - self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function), - self::resolve($typeNode->offset, $vars, $boundTemplates, $registry, $function) + self::resolve($typeNode->type, $vars, $boundTemplates, $registry, $function, $deferredTemplates), + self::resolve($typeNode->offset, $vars, $boundTemplates, $registry, $function, $deferredTemplates) ); } @@ -278,13 +319,15 @@ public static function resolve( * * @param array $vars * @param array $boundTemplates + * @param array $deferredTemplates */ public static function resolveParameterConditional( ConditionalTypeForParameterNode $node, array $vars, array $boundTemplates, TypeValidatorRegistry $registry, - string $function = '' + string $function = '', + array $deferredTemplates = [] ): TypeNode { $paramName = ltrim($node->parameterName, '$'); $paramValue = null; @@ -378,7 +421,7 @@ public static function resolveParameterConditional( $selectedBranch = $isTargetMatch ? $node->if : $node->else; - return self::resolve($selectedBranch, $vars, $boundTemplates, $registry, $function); + return self::resolve($selectedBranch, $vars, $boundTemplates, $registry, $function, $deferredTemplates); } /** @@ -386,14 +429,31 @@ public static function resolveParameterConditional( * * @param array $vars * @param array $boundTemplates + * @param array $deferredTemplates */ public static function resolveTemplateConditional( ConditionalTypeNode $node, array $vars, array $boundTemplates, TypeValidatorRegistry $registry, - string $function = '' + string $function = '', + array $deferredTemplates = [] ): TypeNode { + if ( + $deferredTemplates !== [] + && ( + DocblockParser::typeReferencesTemplate($node->subjectType, $deferredTemplates) + || DocblockParser::typeReferencesTemplate($node->targetType, $deferredTemplates) + ) + ) { + return new ConditionalTypeNode( + self::resolve($node->subjectType, $vars, $boundTemplates, $registry, $function, $deferredTemplates), + self::resolve($node->targetType, $vars, $boundTemplates, $registry, $function, $deferredTemplates), + self::resolve($node->if, $vars, $boundTemplates, $registry, $function, $deferredTemplates), + self::resolve($node->else, $vars, $boundTemplates, $registry, $function, $deferredTemplates), + $node->negated + ); + } $subjectTypeNode = $node->subjectType; if ($subjectTypeNode instanceof IdentifierTypeNode) { if (isset($boundTemplates[$subjectTypeNode->name])) { @@ -437,7 +497,7 @@ public static function resolveTemplateConditional( $selectedBranch = $isTargetMatch ? $node->if : $node->else; - return self::resolve($selectedBranch, $vars, $boundTemplates, $registry, $function); + return self::resolve($selectedBranch, $vars, $boundTemplates, $registry, $function, $deferredTemplates); } /** diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index c162400f..ad8d273e 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -16,6 +16,7 @@ use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -205,6 +206,7 @@ public static function reset(): void 'non-empty-array' => true, 'non-empty-list' => true, 'non-empty-array-list' => true, + 'class-string-map' => true, ]; /** @@ -1059,7 +1061,7 @@ private static function needsContextResolution(TypeNode $node): bool $node = $node->type; } - if ($node instanceof ThisTypeNode || $node instanceof OffsetAccessTypeNode || $node instanceof ConditionalTypeNode || $node instanceof ConditionalTypeForParameterNode) { + if ($node instanceof ThisTypeNode || $node instanceof OffsetAccessTypeNode || $node instanceof ConditionalTypeNode || $node instanceof ConditionalTypeForParameterNode || $node instanceof TemplateDeclarationTypeNode) { return true; } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index 76953d30..60febbf9 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -21,6 +21,7 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Checker\ConditionalChecker; @@ -215,12 +216,36 @@ public static function typeReferencesTemplate(?TypeNode $node, array $templateNa return isset($templateNames[$node->name]); } + if ($node instanceof TemplateDeclarationTypeNode) { + return self::typeReferencesTemplate($node->bound, $templateNames); + } + if ($node instanceof GenericTypeNode) { if (isset($templateNames[(string) $node->type])) { return true; } - foreach ($node->genericTypes as $gt) { - if (self::typeReferencesTemplate($gt, $templateNames)) { + + $isClassStringMap = $node->type instanceof IdentifierTypeNode + && strtolower($node->type->name) === 'class-string-map'; + $argTemplates = $templateNames; + + foreach ($node->genericTypes as $idx => $gt) { + if ($idx === 0 && $gt instanceof TemplateDeclarationTypeNode) { + if (self::typeReferencesTemplate($gt->bound, $templateNames)) { + return true; + } + unset($argTemplates[$gt->name]); + + continue; + } + + if ($idx === 0 && $isClassStringMap && $gt instanceof IdentifierTypeNode) { + unset($argTemplates[$gt->name]); + + continue; + } + + if (self::typeReferencesTemplate($gt, $argTemplates)) { return true; } } @@ -264,11 +289,17 @@ public static function typeReferencesTemplate(?TypeNode $node, array $templateNa } if ($node->unsealedType !== null) { - if ($node->unsealedType->keyType !== null && self::typeReferencesTemplate($node->unsealedType->keyType, $templateNames)) { - return true; + $valTemplates = $templateNames; + if ($node->unsealedType->keyType !== null) { + if (self::typeReferencesTemplate($node->unsealedType->keyType, $templateNames)) { + return true; + } + if ($node->unsealedType->keyType instanceof TemplateDeclarationTypeNode) { + unset($valTemplates[$node->unsealedType->keyType->name]); + } } - return self::typeReferencesTemplate($node->unsealedType->valueType, $templateNames); + return self::typeReferencesTemplate($node->unsealedType->valueType, $valTemplates); } return false; @@ -2023,6 +2054,12 @@ public static function bindRecursiveAliases(TypeNode $node, array $aliases): Typ return $node; } + if ($node instanceof TemplateDeclarationTypeNode) { + self::bindRecursiveAliases($node->bound, $aliases); + + return $node; + } + if ($node instanceof GenericTypeNode) { self::bindRecursiveAliases($node->type, $aliases); foreach ($node->genericTypes as $gt) { @@ -2198,25 +2235,53 @@ private static function substituteAliasesInternal( return new ArrayTypeNode(self::substituteAliasesInternal($node->type, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth)); } + if ($node instanceof TemplateDeclarationTypeNode) { + $bound = self::substituteAliasesInternal($node->bound, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + + return $bound === $node->bound ? $node : new TemplateDeclarationTypeNode($node->name, $bound); + } + if ($node instanceof GenericTypeNode) { - $genericTypes = []; - foreach ($node->genericTypes as $gt) { - $genericTypes[] = self::substituteAliasesInternal($gt, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + $isGenericAliasCall = $node->type instanceof IdentifierTypeNode + && isset($aliases[$node->type->name]) + && $aliases[$node->type->name] instanceof GenericTypeAlias; + + if ($isGenericAliasCall) { + /** @var IdentifierTypeNode $aliasIdent */ + $aliasIdent = $node->type; + /** @var GenericTypeAlias $entry */ + $entry = $aliases[$aliasIdent->name]; + $genericTypes = []; + foreach ($node->genericTypes as $gt) { + $genericTypes[] = self::substituteAliasesInternal($gt, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + } + + return self::expandGenericAlias( + $aliasIdent->name, + $entry, + $genericTypes, + $aliases, + $visited, + $hasRecursivePlaceholder, + $resolverContext, + $genericDepth + ); } - if ($node->type instanceof IdentifierTypeNode && isset($aliases[$node->type->name])) { - $entry = $aliases[$node->type->name]; - if ($entry instanceof GenericTypeAlias) { - return self::expandGenericAlias( - $node->type->name, - $entry, - $genericTypes, - $aliases, - $visited, - $hasRecursivePlaceholder, - $resolverContext, - $genericDepth - ); + $isClassStringMap = $node->type instanceof IdentifierTypeNode + && strtolower($node->type->name) === 'class-string-map'; + $argAliases = $aliases; + $genericTypes = []; + + foreach ($node->genericTypes as $idx => $gt) { + if ($idx === 0 && $gt instanceof TemplateDeclarationTypeNode) { + $genericTypes[] = self::substituteAliasesInternal($gt, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + unset($argAliases[$gt->name]); + } elseif ($idx === 0 && $isClassStringMap && $gt instanceof IdentifierTypeNode) { + $genericTypes[] = $gt; + unset($argAliases[$gt->name]); + } else { + $genericTypes[] = self::substituteAliasesInternal($gt, $argAliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); } } @@ -2281,10 +2346,14 @@ private static function substituteAliasesInternal( $newUnsealed = null; if ($node->unsealedType !== null) { + $valAliases = $aliases; $unsealedKey = $node->unsealedType->keyType !== null ? self::substituteAliasesInternal($node->unsealedType->keyType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth) : null; - $unsealedVal = self::substituteAliasesInternal($node->unsealedType->valueType, $aliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); + if ($node->unsealedType->keyType instanceof TemplateDeclarationTypeNode) { + unset($valAliases[$node->unsealedType->keyType->name]); + } + $unsealedVal = self::substituteAliasesInternal($node->unsealedType->valueType, $valAliases, $visited, $hasRecursivePlaceholder, $resolverContext, $genericDepth); $newUnsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey); } @@ -2490,6 +2559,10 @@ private static function isConcreteTypeForBoundCheck(TypeNode $node): bool return self::isConcreteTypeForBoundCheck($node->type); } + if ($node instanceof TemplateDeclarationTypeNode) { + return self::isConcreteTypeForBoundCheck($node->bound); + } + if ($node instanceof GenericTypeNode) { if (! self::isConcreteTypeForBoundCheck($node->type)) { return false; diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index d58023a8..fbdc44ab 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -26,6 +26,7 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -392,6 +393,7 @@ final class TemplateManager 'list' => true, 'non-empty-array' => true, 'non-empty-list' => true, + 'class-string-map' => true, ], 'list' => [ 'list' => true, @@ -404,10 +406,14 @@ final class TemplateManager 'non-empty-array' => true, 'non-empty-list' => true, 'traversable' => true, + 'class-string-map' => true, ], 'traversable' => [ 'traversable' => true, ], + 'class-string-map' => [ + 'class-string-map' => true, + ], ]; /** @@ -3225,10 +3231,23 @@ private static function expandKeyOfTarget(TypeNode $target): ?TypeNode return self::$intNode ??= new IdentifierTypeNode('int'); } + if ($base === 'class-string-map') { + $first = $target->genericTypes[0] ?? null; + $bound = $first instanceof TemplateDeclarationTypeNode + ? $first->bound + : new IdentifierTypeNode('object'); + + return new GenericTypeNode(new IdentifierTypeNode('class-string'), [$bound]); + } + if (\in_array($base, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { - return \count($target->genericTypes) >= 2 - ? $target->genericTypes[0] - : new IdentifierTypeNode('array-key'); + if (\count($target->genericTypes) >= 2) { + $k = $target->genericTypes[0]; + + return $k instanceof TemplateDeclarationTypeNode ? $k->bound : $k; + } + + return new IdentifierTypeNode('array-key'); } return null; @@ -3320,10 +3339,32 @@ private static function expandValueOfTarget(TypeNode $target): ?TypeNode return $target->genericTypes[0] ?? (self::$mixedNode ??= new IdentifierTypeNode('mixed')); } + if ($base === 'class-string-map') { + $first = $target->genericTypes[0] ?? null; + $second = $target->genericTypes[1] ?? null; + if ($second === null) { + return self::$mixedNode ??= new IdentifierTypeNode('mixed'); + } + if ($first instanceof TemplateDeclarationTypeNode) { + return TemplateSubstitutor::substitute($second, [$first->name => $first->bound]); + } + if ($first instanceof IdentifierTypeNode) { + return TemplateSubstitutor::substitute($second, [$first->name => new IdentifierTypeNode('object')]); + } + + return $second; + } + if (\in_array($base, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { $count = \count($target->genericTypes); if ($count >= 2) { - return $target->genericTypes[1]; + $k = $target->genericTypes[0]; + $v = $target->genericTypes[1]; + if ($k instanceof TemplateDeclarationTypeNode) { + return TemplateSubstitutor::substitute($v, [$k->name => $k->bound]); + } + + return $v; } if ($count === 1) { return $target->genericTypes[0]; diff --git a/src/Internal/Generics/TemplateSubstitutor.php b/src/Internal/Generics/TemplateSubstitutor.php index ad7a2726..da0934df 100644 --- a/src/Internal/Generics/TemplateSubstitutor.php +++ b/src/Internal/Generics/TemplateSubstitutor.php @@ -24,6 +24,7 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Diagnostic\DebugLog; @@ -182,6 +183,12 @@ private static function substituteNode( return $inner === $node->type ? $node : new ArrayTypeNode($inner); } + if ($node instanceof TemplateDeclarationTypeNode) { + $bound = self::substituteNode($node->bound, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); + + return $bound === $node->bound ? $node : new TemplateDeclarationTypeNode($node->name, $bound); + } + if ($node instanceof GenericTypeNode) { return self::substituteGeneric($node, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); } @@ -538,16 +545,30 @@ private static function substituteGeneric( ): TypeNode { $type = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); $changed = ($type !== $node->type); + $baseType = $type instanceof IdentifierTypeNode ? $type : $node->type; + $isClassStringMap = $baseType instanceof IdentifierTypeNode && strtolower($baseType->name) === 'class-string-map'; + + $argBound = $boundTemplates; + $argDeclared = $declaredTemplates; $genericTypes = []; - foreach ($node->genericTypes as $gt) { - $sub = self::substituteNode($gt, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); + + foreach ($node->genericTypes as $idx => $gt) { + if ($idx === 0 && $gt instanceof TemplateDeclarationTypeNode) { + $sub = self::substituteNode($gt, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); + unset($argBound[$gt->name], $argDeclared[$gt->name]); + } elseif ($idx === 0 && $isClassStringMap && $gt instanceof IdentifierTypeNode) { + $sub = $gt; + unset($argBound[$gt->name], $argDeclared[$gt->name]); + } else { + $sub = self::substituteNode($gt, $argBound, $argDeclared, $visited, $recursiveMemo); + } + if ($sub !== $gt) { $changed = true; } $genericTypes[] = $sub; } - $baseType = $type instanceof IdentifierTypeNode ? $type : $node->type; if ($baseType instanceof IdentifierTypeNode && strtolower($baseType->name) === 'new' && isset($genericTypes[0])) { $resolvedNew = self::resolveNewType($genericTypes[0]); if ($resolvedNew !== null) { @@ -559,11 +580,7 @@ private static function substituteGeneric( return $node; } - return new GenericTypeNode( - $baseType, - $genericTypes, - $node->variances - ); + return new GenericTypeNode($baseType, $genericTypes, $node->variances); } /** @@ -590,10 +607,15 @@ private static function substituteArrayShape( $newUnsealed = null; if ($node->unsealedType !== null) { + $valBound = $boundTemplates; + $valDeclared = $declaredTemplates; $unsealedKey = $node->unsealedType->keyType !== null ? self::substituteNode($node->unsealedType->keyType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo) : null; - $unsealedVal = self::substituteNode($node->unsealedType->valueType, $boundTemplates, $declaredTemplates, $visited, $recursiveMemo); + if ($node->unsealedType->keyType instanceof TemplateDeclarationTypeNode) { + unset($valBound[$node->unsealedType->keyType->name], $valDeclared[$node->unsealedType->keyType->name]); + } + $unsealedVal = self::substituteNode($node->unsealedType->valueType, $valBound, $valDeclared, $visited, $recursiveMemo); $newUnsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey); } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 534c0aab..b3d3b5f9 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -23,6 +23,7 @@ use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -103,6 +104,7 @@ final class SpecialTypeResolver 'value-of' => true, 'int-mask' => true, 'int-mask-of' => true, + 'class-string-map' => true, 'new' => true, 'number' => true, 'numeric' => true, @@ -309,12 +311,33 @@ private static function resolveWithContext( return self::resolveConstType($node, $declaringClass, $ref); } + if ($node instanceof TemplateDeclarationTypeNode) { + $resolvedBound = self::resolveWithContext($node->bound, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); + + return $resolvedBound === $node->bound + ? $node + : new TemplateDeclarationTypeNode($node->name, $resolvedBound); + } + if ($node instanceof GenericTypeNode) { $genericType = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); $changed = ($genericType !== $node->type); + $isClassStringMap = $genericType instanceof IdentifierTypeNode + && strtolower($genericType->name) === 'class-string-map'; + + $argIgnored = $ignoredTemplates; $innerTypes = []; - foreach ($node->genericTypes as $gt) { - $resGt = self::resolveWithContext($gt, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); + foreach ($node->genericTypes as $idx => $gt) { + if ($idx === 0 && $gt instanceof TemplateDeclarationTypeNode) { + $resGt = self::resolveWithContext($gt, $ref, $declaringClass, $context, $thisObj, $ignoredTemplates); + $argIgnored[$gt->name] = true; + } elseif ($idx === 0 && $isClassStringMap && $gt instanceof IdentifierTypeNode) { + $resGt = $gt; + $argIgnored[$gt->name] = true; + } else { + $resGt = self::resolveWithContext($gt, $ref, $declaringClass, $context, $thisObj, $argIgnored); + } + if ($resGt !== $gt) { $changed = true; } @@ -476,11 +499,31 @@ public static function resolveForFile( return self::resolveConstTypeForFile($node, $file, $namespace, $autoload); } + if ($node instanceof TemplateDeclarationTypeNode) { + $resolvedBound = self::resolveForFile($node->bound, $file, $namespace, $autoload, $ignoredTemplates); + + return $resolvedBound === $node->bound + ? $node + : new TemplateDeclarationTypeNode($node->name, $resolvedBound); + } + if ($node instanceof GenericTypeNode) { $genericType = self::resolveForFile($node->type, $file, $namespace, $autoload, $ignoredTemplates); + $isClassStringMap = $genericType instanceof IdentifierTypeNode + && strtolower($genericType->name) === 'class-string-map'; + + $argIgnored = $ignoredTemplates; $innerTypes = []; - foreach ($node->genericTypes as $gt) { - $innerTypes[] = self::resolveForFile($gt, $file, $namespace, $autoload, $ignoredTemplates); + foreach ($node->genericTypes as $idx => $gt) { + if ($idx === 0 && $gt instanceof TemplateDeclarationTypeNode) { + $innerTypes[] = self::resolveForFile($gt, $file, $namespace, $autoload, $ignoredTemplates); + $argIgnored[$gt->name] = true; + } elseif ($idx === 0 && $isClassStringMap && $gt instanceof IdentifierTypeNode) { + $innerTypes[] = $gt; + $argIgnored[$gt->name] = true; + } else { + $innerTypes[] = self::resolveForFile($gt, $file, $namespace, $autoload, $argIgnored); + } } return new GenericTypeNode( @@ -860,8 +903,13 @@ private static function resolveArrayShape( $unsealedType = null; if ($node->unsealedType !== null) { - $unsealedKey = $node->unsealedType->keyType !== null ? self::resolve($node->unsealedType->keyType, $context, $thisObj, $ignoredTemplates) : null; - $unsealedValue = self::resolve($node->unsealedType->valueType, $context, $thisObj, $ignoredTemplates); + $rawKey = $node->unsealedType->keyType; + $unsealedKey = $rawKey !== null ? self::resolve($rawKey, $context, $thisObj, $ignoredTemplates) : null; + $valIgnored = $ignoredTemplates; + if ($rawKey instanceof TemplateDeclarationTypeNode) { + $valIgnored[$rawKey->name] = true; + } + $unsealedValue = self::resolve($node->unsealedType->valueType, $context, $thisObj, $valIgnored); $unsealedType = new ArrayShapeUnsealedTypeNode($unsealedValue, $unsealedKey); } @@ -1060,8 +1108,13 @@ private static function resolveArrayShapeForFile( $unsealedType = null; if ($node->unsealedType !== null) { - $unsealedKey = $node->unsealedType->keyType !== null ? self::resolveForFile($node->unsealedType->keyType, $file, $namespace, $autoload, $ignoredTemplates) : null; - $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace, $autoload, $ignoredTemplates); + $rawKey = $node->unsealedType->keyType; + $unsealedKey = $rawKey !== null ? self::resolveForFile($rawKey, $file, $namespace, $autoload, $ignoredTemplates) : null; + $valIgnored = $ignoredTemplates; + if ($rawKey instanceof TemplateDeclarationTypeNode) { + $valIgnored[$rawKey->name] = true; + } + $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace, $autoload, $valIgnored); $unsealedType = new ArrayShapeUnsealedTypeNode($unsealedValue, $unsealedKey); } diff --git a/src/Internal/Validator/ArrayShapeValidator.php b/src/Internal/Validator/ArrayShapeValidator.php index e070832e..f3734364 100644 --- a/src/Internal/Validator/ArrayShapeValidator.php +++ b/src/Internal/Validator/ArrayShapeValidator.php @@ -13,11 +13,14 @@ use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; +use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Util\ClassNameValidator; use WeakMap; @@ -197,6 +200,40 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali $unsealedKeyType = $compiled['unsealedKeyType']; $unsealedValueType = $compiled['unsealedValueType']; + if ($unsealedKeyType instanceof TemplateDeclarationTypeNode) { + $tName = $unsealedKeyType->name; + $keyBound = $unsealedKeyType->bound; + $hasConditional = ConditionalChecker::containsConditional($unsealedValueType); + + foreach ($value as $k => $v) { + if (isset($knownKeys[$k])) { + continue; + } + + $err = $registry->validate($k, $keyBound, ''); + if ($err !== null) { + return ErrorFactory::createError($context . " extra key '{$k}'" . $err->getMessage()); + } + + $keyLiteral = \is_int($k) + ? new ConstTypeNode(new ConstExprIntegerNode((string) $k)) + : new ConstTypeNode(new ConstExprStringNode($k, ConstExprStringNode::SINGLE_QUOTED)); + + $bindings = [$tName => $keyLiteral]; + $resolvedValType = TemplateSubstitutor::substitute($unsealedValueType, $bindings); + if ($hasConditional || (! ($resolvedValType instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($resolvedValType))) { + $resolvedValType = ConditionalChecker::resolve($resolvedValType, [], $bindings, $registry); + } + + $err = $registry->validate($v, $resolvedValType, '', $isSensitive); + if ($err !== null) { + return ErrorFactory::createError($context . "['{$k}']" . $err->getMessage()); + } + } + + return null; + } + foreach ($value as $k => $v) { if (isset($knownKeys[$k])) { continue; diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 85856acf..bab3c806 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -16,8 +16,10 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; @@ -46,6 +48,8 @@ final class GenericValidator implements TypeValidatorInterface private const KIND_OBJECT_GENERIC = 11; private const KIND_FLOAT_RANGE = 12; private const KIND_NEW_OBJECT = 13; + private const KIND_CLASS_STRING_MAP = 14; + private const KIND_DEPENDENT_ARRAY = 15; private const BUILTIN_GENERICS = [ 'int' => true, @@ -66,6 +70,7 @@ final class GenericValidator implements TypeValidatorInterface 'value-of' => true, 'int-mask' => true, 'int-mask-of' => true, + 'class-string-map' => true, 'new' => true, ]; @@ -191,6 +196,20 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return $this->validateArrayWithPlan($value, $plan, $context, $registry, $isSensitive); } + if ($kind === self::KIND_CLASS_STRING_MAP) { + /** @var array{templateName: ?string, keyContract: GenericTypeNode, valNode: ?TypeNode, isIdentityValue: bool, valHasConditional: bool} $plan */ + $plan = $compiled[1]; + + return $this->validateClassStringMap($value, $plan, $context, $registry, $isSensitive); + } + + if ($kind === self::KIND_DEPENDENT_ARRAY) { + /** @var array{requireNonEmpty: bool, baseName: string, templateName: string, keyBound: TypeNode, valNode: TypeNode, valHasConditional: bool} $plan */ + $plan = $compiled[1]; + + return $this->validateDependentArray($value, $plan, $context, $registry, $isSensitive); + } + if ($kind === self::KIND_INT_RANGE) { if (! \is_int($value)) { return ErrorFactory::createError($context . ' must be of type int, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); @@ -312,8 +331,13 @@ private function compileGeneric(GenericTypeNode $node): array return match ($baseType) { 'list' => [self::KIND_LIST, $node->genericTypes[0] ?? null], 'non-empty-list', 'non-empty-array-list' => [self::KIND_NON_EMPTY_LIST, $node->genericTypes[0] ?? null], - 'array', 'iterable', 'traversable', 'generator', 'iterator' => [self::KIND_ARRAY, $this->compileArrayPlan($node, $typeName, false)], - 'non-empty-array' => [self::KIND_NON_EMPTY_ARRAY, $this->compileArrayPlan($node, $typeName, true)], + 'class-string-map' => [self::KIND_CLASS_STRING_MAP, $this->compileClassStringMapPlan($node)], + 'array', 'iterable', 'traversable', 'generator', 'iterator' => isset($node->genericTypes[0], $node->genericTypes[1]) && $node->genericTypes[0] instanceof TemplateDeclarationTypeNode + ? [self::KIND_DEPENDENT_ARRAY, $this->compileDependentArrayPlan($node, $typeName, false)] + : [self::KIND_ARRAY, $this->compileArrayPlan($node, $typeName, false)], + 'non-empty-array' => isset($node->genericTypes[0], $node->genericTypes[1]) && $node->genericTypes[0] instanceof TemplateDeclarationTypeNode + ? [self::KIND_DEPENDENT_ARRAY, $this->compileDependentArrayPlan($node, $typeName, true)] + : [self::KIND_NON_EMPTY_ARRAY, $this->compileArrayPlan($node, $typeName, true)], 'int', 'integer' => [ self::KIND_INT_RANGE, [ @@ -1425,4 +1449,235 @@ private function resolveConstantValue(string $fqcn, string $constName): mixed return self::$constantCache[$cacheKey]; } + + /** + * @return array{ + * templateName: ?string, + * keyContract: GenericTypeNode, + * valNode: ?TypeNode, + * isIdentityValue: bool, + * valHasConditional: bool + * } + */ + private function compileClassStringMapPlan(GenericTypeNode $node): array + { + $keyArg = $node->genericTypes[0] ?? null; + $valNode = $node->genericTypes[1] ?? null; + + $templateName = null; + $classBound = new IdentifierTypeNode('object'); + + if ($keyArg instanceof TemplateDeclarationTypeNode) { + $templateName = $keyArg->name; + $classBound = $keyArg->bound; + } elseif ($keyArg instanceof IdentifierTypeNode) { + $templateName = $keyArg->name; + } + + $keyContract = new GenericTypeNode(new IdentifierTypeNode('class-string'), [$classBound]); + $isIdentityValue = $templateName !== null + && $valNode instanceof IdentifierTypeNode + && $valNode->name === $templateName; + + return [ + 'templateName' => $templateName, + 'keyContract' => $keyContract, + 'valNode' => $valNode, + 'isIdentityValue' => $isIdentityValue, + 'valHasConditional' => $valNode !== null && ConditionalChecker::containsConditional($valNode), + ]; + } + + /** + * @return array{ + * requireNonEmpty: bool, + * baseName: string, + * templateName: string, + * keyBound: TypeNode, + * valNode: TypeNode, + * valHasConditional: bool + * } + */ + private function compileDependentArrayPlan(GenericTypeNode $node, string $baseName, bool $requireNonEmpty): array + { + /** @var TemplateDeclarationTypeNode $keyDecl */ + $keyDecl = $node->genericTypes[0]; + /** @var TypeNode $valNode */ + $valNode = $node->genericTypes[1]; + + return [ + 'requireNonEmpty' => $requireNonEmpty, + 'baseName' => $baseName, + 'templateName' => $keyDecl->name, + 'keyBound' => $keyDecl->bound, + 'valNode' => $valNode, + 'valHasConditional' => ConditionalChecker::containsConditional($valNode), + ]; + } + + /** + * @param array{ + * templateName: ?string, + * keyContract: GenericTypeNode, + * valNode: ?TypeNode, + * isIdentityValue: bool, + * valHasConditional: bool + * } $plan + */ + private function validateClassStringMap( + mixed $value, + array $plan, + string $context, + TypeValidatorRegistry $registry, + bool $isSensitive = false + ): ?ErrorMessage { + if (! \is_array($value)) { + return ErrorFactory::createError($context . ' must be of type class-string-map, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + $count = \count($value); + if ($count === 0) { + return null; + } + + $entries = $value; + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + $keys = array_keys($value); + $sampleKeys = [$keys[0], $keys[$count - 1]]; + $samplesToTake = min(3, $count - 2); + for ($i = 0; $i < $samplesToTake; $i++) { + $sampleKeys[] = $keys[mt_rand(1, $count - 2)]; + } + $entries = []; + foreach ($sampleKeys as $sk) { + $entries[$sk] = $value[$sk]; + } + } + + $keyContract = $plan['keyContract']; + $templateName = $plan['templateName']; + $valNode = $plan['valNode']; + $isIdentityValue = $plan['isIdentityValue']; + $valHasConditional = $plan['valHasConditional']; + + foreach ($entries as $k => $v) { + $keyErr = $this->validateClassString($k, $keyContract, '', $isSensitive); + if ($keyErr !== null) { + return ErrorFactory::createError($context . ' key' . $keyErr->getMessage()); + } + + if (! \is_string($k) || $valNode === null) { + continue; + } + + $fqcn = ltrim($k, '\\'); + + if ($isIdentityValue) { + if (! \is_object($v) || ! ($v instanceof $fqcn)) { + return ErrorFactory::createError($context . "['" . $k . "'] must be of type " . $fqcn . ', ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); + } + + continue; + } + + if ($templateName !== null) { + $keyClassNode = new IdentifierTypeNode($fqcn); + $keyClassNode->setAttribute('typephp_resolved', true); + $bindings = [$templateName => $keyClassNode]; + $resolvedValType = TemplateSubstitutor::substitute($valNode, $bindings); + + if ($valHasConditional || (! ($resolvedValType instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($resolvedValType))) { + $resolvedValType = ConditionalChecker::resolve($resolvedValType, [], $bindings, $registry); + } + } else { + $resolvedValType = $valNode; + } + + $valErr = $registry->validate($v, $resolvedValType, '', $isSensitive); + if ($valErr !== null) { + return ErrorFactory::createError($context . "['" . $k . "']" . $valErr->getMessage()); + } + } + + return null; + } + + /** + * @param array{ + * requireNonEmpty: bool, + * baseName: string, + * templateName: string, + * keyBound: TypeNode, + * valNode: TypeNode, + * valHasConditional: bool + * } $plan + */ + private function validateDependentArray( + mixed $value, + array $plan, + string $context, + TypeValidatorRegistry $registry, + bool $isSensitive = false + ): ?ErrorMessage { + if (! \is_array($value) && ! ($value instanceof \Traversable)) { + return ErrorFactory::createError($context . ' must be of type ' . $plan['baseName'] . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + if (! \is_array($value)) { + return null; + } + + $count = \count($value); + if ($plan['requireNonEmpty'] && $count === 0) { + return ErrorFactory::createError($context . ' must be a non-empty array, empty array given'); + } + + if ($count === 0) { + return null; + } + + $entries = $value; + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + $keys = array_keys($value); + $sampleKeys = [$keys[0], $keys[$count - 1]]; + $samplesToTake = min(3, $count - 2); + for ($i = 0; $i < $samplesToTake; $i++) { + $sampleKeys[] = $keys[mt_rand(1, $count - 2)]; + } + $entries = []; + foreach ($sampleKeys as $sk) { + $entries[$sk] = $value[$sk]; + } + } + + $templateName = $plan['templateName']; + $keyBound = $plan['keyBound']; + $valNode = $plan['valNode']; + $valHasConditional = $plan['valHasConditional']; + + foreach ($entries as $k => $v) { + $keyErr = $registry->validate($k, $keyBound, ''); + if ($keyErr !== null) { + return ErrorFactory::createError($context . ' key' . $keyErr->getMessage()); + } + + $keyLiteralNode = \is_int($k) + ? new ConstTypeNode(new ConstExprIntegerNode((string) $k)) + : new ConstTypeNode(new ConstExprStringNode($k, ConstExprStringNode::SINGLE_QUOTED)); + + $bindings = [$templateName => $keyLiteralNode]; + $resolvedValType = TemplateSubstitutor::substitute($valNode, $bindings); + + if ($valHasConditional || (! ($resolvedValType instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($resolvedValType))) { + $resolvedValType = ConditionalChecker::resolve($resolvedValType, [], $bindings, $registry); + } + + $valErr = $registry->validate($v, $resolvedValType, '', $isSensitive); + if ($valErr !== null) { + return ErrorFactory::createError($context . "['" . $k . "']" . $valErr->getMessage()); + } + } + + return null; + } } diff --git a/tests/TypeChecking/ArraysAndShapes/KeyDeclaredTemplateArrayTest.php b/tests/TypeChecking/ArraysAndShapes/KeyDeclaredTemplateArrayTest.php new file mode 100644 index 00000000..46e51a92 --- /dev/null +++ b/tests/TypeChecking/ArraysAndShapes/KeyDeclaredTemplateArrayTest.php @@ -0,0 +1,411 @@ + array, TConfig[K]> + * @phpstan-type ServiceRegistry class-string-map + */ +final class KeyDeclaredTemplateService +{ + public const ENTITY_MAP = [ + 'dog' => MapDog::class, + 'cat' => MapCat::class, + ]; + + /** + * @var class-string-map + */ + public array $animals = []; + + /** + * @param class-string-map $map + * + * @return class-string-map + */ + public function acceptAnimalMap(array $map): array + { + return $map; + } + + /** + * @param class-string-map $map + */ + public function acceptUnboundedClassStringMap(array $map): void + { + } + + /** + * @param class-string-map> $grouped + */ + public function acceptGroupedAnimalMap(array $grouped): void + { + } + + /** + * @param class-string-map> $repos + */ + public function acceptGenericRepoMap(array $repos): void + { + } + + /** + * @param array, new> $map + */ + public function acceptDesugaredClassStringMap(array $map): void + { + } + + /** + * @param array, AppConfig[K]> $overrides + * + * @return array, AppConfig[K]> + */ + public function acceptConfigOverrides(array $overrides): array + { + return $overrides; + } + + /** + * @param non-empty-array> $buckets + */ + public function acceptNonEmptyLiteralBuckets(array $buckets): void + { + } + + /** + * @param array, new> $instances + */ + public function acceptConstClassMapInstances(array $instances): void + { + } + + /** + * @param array, array, NestedConfig[K][M]>> $nested + */ + public function acceptNestedDependentMap(array $nested): void + { + } + + /** + * @param array{version: positive-int, ..., AppConfig[K]>} $payload + */ + public function acceptUnsealedDependentShape(array $payload): void + { + } + + /** + * @param array $entries + */ + public function acceptConditionalDependentMap(array $entries): void + { + } + + /** + * @param TypedConfigMap $overrides + */ + public function acceptGenericAliasConfigMap(array $overrides): void + { + } + + /** + * @param ServiceRegistry $registry + */ + public function acceptGenericAliasServiceRegistry(array $registry): void + { + } + + /** + * @template TBase of object + * + * @param class-string $base + * @param class-string-map $map + */ + public function acceptOuterTemplateBoundMap(string $base, array $map): void + { + } + + /** + * @param array $input + */ + public function checkInlineDependentVar(array $input): void + { + /** @var array, AppConfig[K]> $cfg */ + $cfg = $input; + } +} + +describe('Key-Declared Dependent Templates (TemplateDeclarationTypeNode)', function () { + describe('1. class-string-map and array, new>', function () { + test('enforces class-string-map for valid and mismatched entries', function () { + $service = new KeyDeclaredTemplateService(); + + $valid = [ + MapDog::class => new MapDog(), + MapCat::class => new MapCat(), + ]; + expect($service->acceptAnimalMap([]))->toBe([]) + ->and($service->acceptAnimalMap($valid))->toBe($valid) + ; + + // Key violates `of MapAnimal` + expect(fn () => $service->acceptAnimalMap([MapCar::class => new MapCar()])) + ->toThrow(TypeError::class, MapAnimal::class) + ; + + // Value instance does not match key class (MapCat stored under MapDog::class) + expect(fn () => $service->acceptAnimalMap([MapDog::class => new MapCat()])) + ->toThrow(TypeError::class, MapDog::class) + ; + + // Non-class-string key + expect(fn () => $service->acceptAnimalMap(['not_a_class' => new MapDog()])) + ->toThrow(TypeError::class, 'class-string') + ; + }); + + test('supports unbounded class-string-map defaulting bound to object', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptUnboundedClassStringMap([ + stdClass::class => new stdClass(), + MapCar::class => new MapCar(), + ]); + expect(true)->toBeTrue(); + + expect(fn () => $service->acceptUnboundedClassStringMap([ + stdClass::class => new MapCar(), + ]))->toThrow(TypeError::class, stdClass::class); + }); + + test('supports complex value types referencing T (list and generic Repository)', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptGroupedAnimalMap([ + MapDog::class => [new MapDog(), new MapDog()], + MapCat::class => [new MapCat()], + ]); + + expect(fn () => $service->acceptGroupedAnimalMap([ + MapDog::class => [new MapDog(), new MapCat()], + ]))->toThrow(TypeError::class, MapDog::class); + + $service->acceptGenericRepoMap([ + MapDog::class => new MapRepository(new MapDog()), + MapCat::class => new MapRepository(new MapCat()), + ]); + + expect(fn () => $service->acceptGenericRepoMap([ + MapDog::class => new MapRepository(new MapCat()), + ]))->toThrow(TypeError::class); + }); + + test('enforces desugared form array, new> identically', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptDesugaredClassStringMap([ + MapDog::class => new MapDog(), + MapCat::class => new MapCat(), + ]); + + expect(fn () => $service->acceptDesugaredClassStringMap([ + MapDog::class => new MapCat(), + ]))->toThrow(TypeError::class, MapDog::class); + + expect(fn () => $service->acceptDesugaredClassStringMap([ + MapCar::class => new MapCar(), + ]))->toThrow(TypeError::class, MapAnimal::class); + }); + }); + + describe('2. array, Config[K]> & Dependent Maps', function () { + test('enforces partial config overrides against shape alias Config[K]', function () { + $service = new KeyDeclaredTemplateService(); + + expect($service->acceptConfigOverrides([]))->toBe([]) + ->and($service->acceptConfigOverrides(['host' => '127.0.0.1', 'port' => 3306, 'debug' => true])) + ->toBe(['host' => '127.0.0.1', 'port' => 3306, 'debug' => true]) + ; + + // Unknown key not in key-of + expect(fn () => $service->acceptConfigOverrides(['unknown' => 'x'])) + ->toThrow(TypeError::class, 'key of the specified array shape') + ; + + // Wrong value type for 'port' (positive-int) + expect(fn () => $service->acceptConfigOverrides(['port' => -1])) + ->toThrow(TypeError::class, 'positive-int') + ; + + // Wrong value type for 'host' (non-empty-string) + expect(fn () => $service->acceptConfigOverrides(['host' => ''])) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + + test('enforces non-empty-array>', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptNonEmptyLiteralBuckets([ + 'a' => ['a', 'a'], + 'b' => ['b'], + ]); + + // Empty array rejected + expect(fn () => $service->acceptNonEmptyLiteralBuckets([])) + ->toThrow(TypeError::class, 'non-empty array') + ; + + // Key 'c' rejected + expect(fn () => $service->acceptNonEmptyLiteralBuckets(['c' => ['c']])) + ->toThrow(TypeError::class) + ; + + // Element 'b' inside bucket 'a' rejected (must match literal 'a') + expect(fn () => $service->acceptNonEmptyLiteralBuckets(['a' => ['a', 'b']])) + ->toThrow(TypeError::class, "literal 'a'") + ; + }); + + test('enforces constant array + new and nested dependent maps', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptConstClassMapInstances([ + 'dog' => new MapDog(), + 'cat' => new MapCat(), + ]); + + expect(fn () => $service->acceptConstClassMapInstances([ + 'dog' => new MapCat(), + ]))->toThrow(TypeError::class, MapDog::class); + + $service->acceptNestedDependentMap([ + 'db' => ['host' => 'localhost', 'port' => 5432], + 'cache' => ['ttl' => 60], + ]); + + expect(fn () => $service->acceptNestedDependentMap([ + 'db' => ['port' => -5], + ]))->toThrow(TypeError::class, 'positive-int'); + + expect(fn () => $service->acceptNestedDependentMap([ + 'cache' => ['host' => 'wrong_section'], + ]))->toThrow(TypeError::class, 'key of the specified array shape'); + }); + }); + + describe('3. Unsealed Dependent Array Shapes, Conditionals, Generic Aliases & Outer Templates', function () { + test('enforces array{version: positive-int, ..., AppConfig[K]>}', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptUnsealedDependentShape([ + 'version' => 1, + 'host' => 'db.local', + 'port' => 5432, + ]); + + expect(fn () => $service->acceptUnsealedDependentShape([ + 'version' => -1, + ]))->toThrow(TypeError::class, 'positive-int'); + + expect(fn () => $service->acceptUnsealedDependentShape([ + 'version' => 1, + 'port' => 'not_an_int', + ]))->toThrow(TypeError::class, 'positive-int'); + + expect(fn () => $service->acceptUnsealedDependentShape([ + 'version' => 1, + 'invalid_extra' => 'nope', + ]))->toThrow(TypeError::class, "extra key 'invalid_extra'"); + }); + + test('enforces conditional value types dependent on key template K', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptConditionalDependentMap([ + 'port' => 8080, + 'host' => 'example.com', + ]); + + expect(fn () => $service->acceptConditionalDependentMap([ + 'port' => '8080', + ]))->toThrow(TypeError::class, 'positive-int'); + + expect(fn () => $service->acceptConditionalDependentMap([ + 'host' => '', + ]))->toThrow(TypeError::class, 'non-empty-string'); + }); + + test('composes generic type aliases with dependent maps, outer @template bounds, properties, and inline @var', function () { + $service = new KeyDeclaredTemplateService(); + + $service->acceptGenericAliasConfigMap(['host' => 'ok', 'port' => 80]); + expect(fn () => $service->acceptGenericAliasConfigMap(['port' => 0])) + ->toThrow(TypeError::class, 'positive-int') + ; + + $service->acceptGenericAliasServiceRegistry([MapDog::class => new MapDog()]); + expect(fn () => $service->acceptGenericAliasServiceRegistry([MapDog::class => new MapCat()])) + ->toThrow(TypeError::class, MapDog::class) + ; + + $service->acceptOuterTemplateBoundMap(MapAnimal::class, [MapDog::class => new MapDog()]); + expect(fn () => $service->acceptOuterTemplateBoundMap(MapAnimal::class, [MapCar::class => new MapCar()])) + ->toThrow(TypeError::class, MapAnimal::class) + ; + + $service->animals = [MapDog::class => new MapDog()]; + expect(fn () => $service->animals = [MapDog::class => new MapCat()]) + ->toThrow(TypeError::class, MapDog::class) + ; + + $service->checkInlineDependentVar(['port' => 443]); + expect(fn () => $service->checkInlineDependentVar(['port' => -443])) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + }); +});