diff --git a/e2e/result-cache-function-import-type/alias.patch b/e2e/result-cache-function-import-type/alias.patch new file mode 100644 index 00000000000..e822f5ba125 --- /dev/null +++ b/e2e/result-cache-function-import-type/alias.patch @@ -0,0 +1,11 @@ +--- src/Aliases.php ++++ src/Aliases.php +@@ -3,7 +3,7 @@ + namespace ResultCacheE2EFunctionImportType; + + /** +- * @phpstan-type Id int ++ * @phpstan-type Id string + */ + final class Aliases + { diff --git a/e2e/result-cache-function-import-type/phpstan.neon b/e2e/result-cache-function-import-type/phpstan.neon new file mode 100644 index 00000000000..6daefc8c39c --- /dev/null +++ b/e2e/result-cache-function-import-type/phpstan.neon @@ -0,0 +1,5 @@ +parameters: + level: 8 + tmpDir: tmp + paths: + - src diff --git a/e2e/result-cache-function-import-type/result-cache-function-import-type_test.sh b/e2e/result-cache-function-import-type/result-cache-function-import-type_test.sh new file mode 100644 index 00000000000..0a18b5c3746 --- /dev/null +++ b/e2e/result-cache-function-import-type/result-cache-function-import-type_test.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# @tags result-cache + +# A type alias imported above a function or a method is only in its PHPDoc, so nothing else ties +# the files below to Aliases.php. Changing the alias there has to re-analyse: +# - body.php, whose function uses the alias in its body, +# - useFunction.php, which calls a function returning the alias, +# - useMethod.php, which calls a method returning the alias. +# Without the dependencies, their stale results come from the cache. + +function set_up() { + e2e::set_up +} + +function tear_down() { + e2e::tear_down +} + +function test_result_cache_function_import_type() { + ../../bin/phpstan analyse + patch -b -p0 < alias.patch + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>/dev/null | sed "s|$(pwd)/||" | sort || true) + echo "$OUTPUT" + assert_contains 'src/body.php:11:Function ResultCacheE2EFunctionImportType\idInBody() should return int but returns string.' "$OUTPUT" + assert_contains 'src/useFunction.php:7:Function ResultCacheE2EFunctionImportType\useFunction() should return int but returns string.' "$OUTPUT" + assert_contains 'src/useMethod.php:7:Function ResultCacheE2EFunctionImportType\useMethod() should return int but returns string.' "$OUTPUT" + + ../../bin/phpstan clear-result-cache + UNCACHED=$(../../bin/phpstan analyse --error-format raw 2>/dev/null | sed "s|$(pwd)/||" | sort || true) + assert_same "$UNCACHED" "$OUTPUT" +} diff --git a/e2e/result-cache-function-import-type/src/Aliases.php b/e2e/result-cache-function-import-type/src/Aliases.php new file mode 100644 index 00000000000..5a520516d59 --- /dev/null +++ b/e2e/result-cache-function-import-type/src/Aliases.php @@ -0,0 +1,11 @@ +getId(1); +} diff --git a/e2e/result-cache-function-import-type/tmp/.gitignore b/e2e/result-cache-function-import-type/tmp/.gitignore new file mode 100644 index 00000000000..125e34294bf --- /dev/null +++ b/e2e/result-cache-function-import-type/tmp/.gitignore @@ -0,0 +1,2 @@ +* +!.* diff --git a/src/Analyser/IntermediaryNameScope.php b/src/Analyser/IntermediaryNameScope.php index 75eb2abd8c7..966d03d36ff 100644 --- a/src/Analyser/IntermediaryNameScope.php +++ b/src/Analyser/IntermediaryNameScope.php @@ -3,6 +3,8 @@ namespace PHPStan\Analyser; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; final class IntermediaryNameScope @@ -13,6 +15,8 @@ final class IntermediaryNameScope * @param array $typeAliasesMap * @param array{string, string, string, string|null, string|null}|null $traitData * @param array $localTypeAliasNodes the type aliases declared next to the @template tags, inlined into their bounds + * @param array $functionTypeAliasTagValueNodes the type aliases declared above a function or a method + * @param array $functionTypeAliasImportTagValueNodes the type aliases imported above a function or a method, by their local names */ public function __construct( private NamespaceUses $namespaceUses, @@ -25,6 +29,8 @@ public function __construct( private ?string $typeAliasClassName = null, private ?array $traitData = null, private array $localTypeAliasNodes = [], + private array $functionTypeAliasTagValueNodes = [], + private array $functionTypeAliasImportTagValueNodes = [], ) { } @@ -84,6 +90,8 @@ public function withTraitData(string $fileName, string $className, string $trait $this->typeAliasClassName, [$fileName, $className, $traitName, $lookForTraitName, $docComment], $this->localTypeAliasNodes, + $this->functionTypeAliasTagValueNodes, + $this->functionTypeAliasImportTagValueNodes, ); } @@ -107,6 +115,8 @@ public function unsetTemplatePhpDocNodes(array $namesToUnset): self $this->typeAliasClassName, $this->traitData, $this->localTypeAliasNodes, + $this->functionTypeAliasTagValueNodes, + $this->functionTypeAliasImportTagValueNodes, ); } @@ -139,6 +149,22 @@ public function getLocalTypeAliasNodes(): array return $this->localTypeAliasNodes; } + /** + * @return array + */ + public function getFunctionTypeAliasTagValueNodes(): array + { + return $this->functionTypeAliasTagValueNodes; + } + + /** + * @return array + */ + public function getFunctionTypeAliasImportTagValueNodes(): array + { + return $this->functionTypeAliasImportTagValueNodes; + } + public function shouldBypassTypeAliases(): bool { return $this->bypassTypeAliases; diff --git a/src/Analyser/NameScope.php b/src/Analyser/NameScope.php index 874008314e6..10555cc1435 100644 --- a/src/Analyser/NameScope.php +++ b/src/Analyser/NameScope.php @@ -3,9 +3,11 @@ namespace PHPStan\Analyser; use PHPStan\PhpDoc\Tag\TemplateTag; +use PHPStan\PhpDoc\Tag\TypeAliasImportTag; use PHPStan\Type\Generic\TemplateTypeMap; use PHPStan\Type\Generic\TemplateTypeScope; use PHPStan\Type\Type; +use PHPStan\Type\TypeAlias; use function array_key_exists; use function array_merge; use function array_shift; @@ -32,6 +34,7 @@ final class NameScope * @param array $constUses alias(string) => fullName(string) * @param array $templateTags * @param array $typeAliasesMap + * @param array $functionTypeAliases aliases declared or imported above the enclosing functions and methods, with the key they are cached under */ public function __construct( private ?string $namespace, @@ -45,6 +48,7 @@ public function __construct( private array $constUses = [], private ?string $typeAliasClassName = null, private ?string $fileName = null, + private array $functionTypeAliases = [], ) { $this->templateTypeMap = $templateTypeMap ?? TemplateTypeMap::createEmpty(); @@ -211,6 +215,7 @@ public function withTemplateTypeMap(TemplateTypeMap $map, array $templateTags): $this->bypassTypeAliases, $this->constUses, fileName: $this->fileName, + functionTypeAliases: $this->functionTypeAliases, ); } @@ -227,6 +232,7 @@ public function withoutNamespaceAndUses(): self $this->bypassTypeAliases, $this->constUses, fileName: $this->fileName, + functionTypeAliases: $this->functionTypeAliases, ); } @@ -243,6 +249,7 @@ public function withClassName(string $className): self $this->bypassTypeAliases, $this->constUses, fileName: $this->fileName, + functionTypeAliases: $this->functionTypeAliases, ); } @@ -264,12 +271,13 @@ public function unsetTemplateType(string $name): self $this->bypassTypeAliases, $this->constUses, fileName: $this->fileName, + functionTypeAliases: $this->functionTypeAliases, ); } public function bypassTypeAliases(): self { - return new self($this->namespace, $this->uses, $this->className, $this->functionName, $this->templateTypeMap, $this->templateTags, $this->typeAliasesMap, true, $this->constUses, fileName: $this->fileName); + return new self($this->namespace, $this->uses, $this->className, $this->functionName, $this->templateTypeMap, $this->templateTags, $this->typeAliasesMap, true, $this->constUses, fileName: $this->fileName, functionTypeAliases: $this->functionTypeAliases); } public function shouldBypassTypeAliases(): bool @@ -279,7 +287,38 @@ public function shouldBypassTypeAliases(): bool public function hasTypeAlias(string $alias): bool { - return array_key_exists($alias, $this->typeAliasesMap); + return array_key_exists($alias, $this->typeAliasesMap) || array_key_exists($alias, $this->functionTypeAliases); + } + + /** + * An alias declared or imported above an enclosing function or method, with the key it is cached under. + * It takes precedence over an alias of the class. + * + * @return array{TypeAlias|TypeAliasImportTag, string}|null + */ + public function getFunctionTypeAlias(string $alias): ?array + { + return $this->functionTypeAliases[$alias] ?? null; + } + + /** + * @return array + */ + public function getFunctionTypeAliases(): array + { + return $this->functionTypeAliases; + } + + /** + * @param callable(self): array $createFunctionTypeAliases gets the new name scope, + * which the aliases declared in it resolve in + */ + public function withFunctionTypeAliases(callable $createFunctionTypeAliases): self + { + $self = clone $this; + $self->functionTypeAliases = $createFunctionTypeAliases($self); + + return $self; } } diff --git a/src/Rules/Classes/FunctionTypeAliasesRule.php b/src/Rules/Classes/FunctionTypeAliasesRule.php new file mode 100644 index 00000000000..2477c9b8ed2 --- /dev/null +++ b/src/Rules/Classes/FunctionTypeAliasesRule.php @@ -0,0 +1,72 @@ + + */ +#[RegisteredRule(level: 0)] +#[ValidatesStubFiles] +final class FunctionTypeAliasesRule implements Rule +{ + + public function __construct( + private FileTypeMapper $fileTypeMapper, + private LocalTypeAliasesCheck $check, + ) + { + } + + public function getNodeType(): string + { + return Node\FunctionLike::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if ($node instanceof Node\Stmt\Function_) { + if (!isset($node->namespacedName)) { + return []; + } + $className = null; + $traitName = null; + $functionName = (string) $node->namespacedName; + $description = sprintf('function %s()', $functionName); + } elseif ($node instanceof Node\Stmt\ClassMethod) { + if (!$scope->isInClass()) { + return []; + } + $classReflection = $scope->getClassReflection(); + $className = $classReflection->getName(); + $traitName = $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null; + $functionName = $node->name->toString(); + $description = sprintf('method %s::%s()', $classReflection->getDisplayName(), $functionName); + } else { + return []; + } + + $docComment = $node->getDocComment(); + if ($docComment === null) { + return []; + } + + $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc( + $scope->getFile(), + $className, + $traitName, + $functionName, + $docComment->getText(), + ); + + return $this->check->checkFunction($scope, $resolvedPhpDoc, $description, $node); + } + +} diff --git a/src/Rules/Classes/LocalTypeAliasesCheck.php b/src/Rules/Classes/LocalTypeAliasesCheck.php index 48661331a15..3cdcd6a55c3 100644 --- a/src/Rules/Classes/LocalTypeAliasesCheck.php +++ b/src/Rules/Classes/LocalTypeAliasesCheck.php @@ -2,12 +2,15 @@ namespace PHPStan\Rules\Classes; +use PhpParser\Node; use PhpParser\Node\Stmt\ClassLike; use PHPStan\Analyser\NameScope; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\Internal\SprintfHelper; +use PHPStan\PhpDoc\ResolvedPhpDocBlock; +use PHPStan\PhpDoc\Tag\TypeAliasTag; use PHPStan\PhpDoc\TypeNodeResolver; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\Reflection\ClassReflection; @@ -34,6 +37,7 @@ use function sprintf; use function strtolower; use function trim; +use function ucfirst; #[AutowiredService] final class LocalTypeAliasesCheck @@ -89,6 +93,68 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra return []; } + return $this->checkDeclarations( + $phpDoc, + $reflection->getDisplayName(), + sprintf('%s %s', $reflection->getClassTypeDescription(), $reflection->getDisplayName()), + sprintf('%s %s', strtolower($reflection->getClassTypeDescription()), $reflection->getDisplayName(false)), + $reflection->getTemplateTypeMap()->getTypes(), + false, + ); + } + + /** + * The type aliases declared and imported above a function or a method, which only its PHPDoc + * and its body see. + * + * @param string $description like `function foo()` or `method Foo::doFoo()` + * @return list + */ + public function checkFunction( + Scope $scope, + ResolvedPhpDocBlock $phpDoc, + string $description, + Node $node, + ): array + { + if ($phpDoc->getTypeAliasTags() === [] && $phpDoc->getTypeAliasImportTags() === []) { + return []; + } + + $nameScope = $phpDoc->getNullableNameScope(); + + return array_merge( + $this->checkDeclarations( + $phpDoc, + $description, + ucfirst($description), + $description, + $nameScope !== null ? $nameScope->getTemplateTypeMap()->getTypes() : [], + true, + ), + $this->checkTypeAliasTagTypes($scope, $phpDoc->getTypeAliasTags(), $node), + ); + } + + /** + * @param string $scopeDescription where the alias is, for `Type alias X already exists as a class in scope of ...` + * @param string $ownerDescription the start of a sentence, like `Class Foo` or `Function foo()` + * @param string $templateOwnerDescription like `class Foo` or `function foo()` + * @param array $templateTypes the templates the aliases are declared next to + * @param bool $isFunction aliases above a function or a method: one named like a template in scope is reported here, + * for a class TemplateTypeCheck does that from the side of the template, and an alias imported + * from the class the function is in keeps the class's templates + * @return list + */ + private function checkDeclarations( + ResolvedPhpDocBlock $phpDoc, + string $scopeDescription, + string $ownerDescription, + string $templateOwnerDescription, + array $templateTypes, + bool $isFunction, + ): array + { $nameScope = $phpDoc->getNullableNameScope(); $resolveName = static function (string $name) use ($nameScope): string { if ($nameScope === null) { @@ -99,7 +165,7 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra }; $errors = []; - $className = $reflection->getDisplayName(); + $className = $scopeDescription; $importedAliases = []; @@ -155,24 +221,28 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra $importedAliases[] = $aliasName; - if (!$this->reportTemplateInImportedTypeAlias) { + if ($isFunction && array_key_exists($aliasName, $templateTypes)) { + $errors[] = $this->shadowsTemplateError($aliasName, $templateOwnerDescription, $templateTypes[$aliasName]); + } + + if (!$this->reportTemplateInImportedTypeAlias || ($isFunction && $importedFromReflection->getName() === $nameScope?->getClassName())) { continue; } - $templateTypes = []; - TypeTraverser::map($typeAliases[$importedAlias]->resolve($this->typeNodeResolver), static function (Type $type, callable $traverse) use ($importedFromReflection, &$templateTypes): Type { + $importedTemplateTypes = []; + TypeTraverser::map($typeAliases[$importedAlias]->resolve($this->typeNodeResolver), static function (Type $type, callable $traverse) use ($importedFromReflection, &$importedTemplateTypes): Type { if ( $type instanceof TemplateType && $type->getScope()->getFunctionName() === null && $type->getScope()->getClassName() === $importedFromReflection->getName() ) { - $templateTypes[$type->getName()] = $type; + $importedTemplateTypes[$type->getName()] = $type; } return $traverse($type); }); - foreach ($templateTypes as $templateType) { + foreach ($importedTemplateTypes as $templateType) { $errors[] = RuleErrorBuilder::message(sprintf( 'Imported type alias %s refers to template type %s of %s, which resolves to its bound %s in %s.', $aliasName, @@ -219,21 +289,23 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra continue; } + if ($isFunction && array_key_exists($aliasName, $templateTypes)) { + $errors[] = $this->shadowsTemplateError($aliasName, $templateOwnerDescription, $templateTypes[$aliasName]); + } + // the alias's own parameter wins in its body, like a method's template over the class's $typeAlias = $typeAliasTag->getTypeAlias(); - $classTemplateTypes = $reflection->getTemplateTypeMap()->getTypes(); foreach ($typeAlias->getTemplateNames() as $templateName) { - if (!array_key_exists($templateName, $classTemplateTypes)) { + if (!array_key_exists($templateName, $templateTypes)) { continue; } $errors[] = RuleErrorBuilder::message(sprintf( - 'PHPDoc tag @phpstan-type %s template %s shadows @template %s for %s %s.', + 'PHPDoc tag @phpstan-type %s template %s shadows @template %s for %s.', $typeAlias->describe(), $templateName, - $classTemplateTypes[$templateName]->describe(VerbosityLevel::typeOnly()), - strtolower($reflection->getClassTypeDescription()), - $reflection->getDisplayName(false), + $templateTypes[$templateName]->describe(VerbosityLevel::typeOnly()), + $templateOwnerDescription, ))->identifier('typeAlias.shadowTemplate')->build(); } @@ -248,9 +320,8 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($resolvedType) as $iterableTypeDescription) { $errors[] = RuleErrorBuilder::message(sprintf( - '%s %s has type alias %s with no value type specified in %s.', - $reflection->getClassTypeDescription(), - $reflection->getDisplayName(), + '%s has type alias %s with no value type specified in %s.', + $ownerDescription, $aliasName, $iterableTypeDescription, )) @@ -261,9 +332,8 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra foreach ($this->missingTypehintCheck->getNonGenericObjectTypesWithGenericClass($resolvedType) as [$name, $genericTypeNames]) { $errors[] = RuleErrorBuilder::message(sprintf( - '%s %s has type alias %s with generic %s but does not specify its types: %s', - $reflection->getClassTypeDescription(), - $reflection->getDisplayName(), + '%s has type alias %s with generic %s but does not specify its types: %s', + $ownerDescription, $aliasName, $name, $genericTypeNames, @@ -274,9 +344,8 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra foreach ($this->missingTypehintCheck->getCallablesWithMissingSignature($resolvedType) as $callableType) { $errors[] = RuleErrorBuilder::message(sprintf( - '%s %s has type alias %s with no signature specified for %s.', - $reflection->getClassTypeDescription(), - $reflection->getDisplayName(), + '%s has type alias %s with no signature specified for %s.', + $ownerDescription, $aliasName, $callableType->describe(VerbosityLevel::typeOnly()), ))->identifier('missingType.callable')->build(); @@ -305,9 +374,18 @@ public function checkInTraitUseContext( return []; } + return $this->checkTypeAliasTagTypes($scope, $phpDoc->getTypeAliasTags(), $node); + } + + /** + * @param array $typeAliasTags + * @return list + */ + private function checkTypeAliasTagTypes(Scope $scope, array $typeAliasTags, Node $node): array + { $errors = []; - foreach ($phpDoc->getTypeAliasTags() as $typeAliasTag) { + foreach ($typeAliasTags as $typeAliasTag) { $aliasName = $typeAliasTag->getAliasName(); $resolvedType = $typeAliasTag->getTypeAlias()->resolve($this->typeNodeResolver); $throwawayErrors = []; @@ -383,6 +461,19 @@ public function checkInTraitUseContext( return $errors; } + private function shadowsTemplateError(string $aliasName, string $ownerDescription, Type $templateType): IdentifierRuleError + { + $templateDescription = $templateType instanceof TemplateType ? $templateType->getScope()->describe() : $ownerDescription; + + return RuleErrorBuilder::message(sprintf( + 'Type alias %s of %s shadows @template %s of %s.', + $aliasName, + $ownerDescription, + $aliasName, + $templateDescription, + ))->identifier('typeAlias.shadowTemplate')->build(); + } + private function isAliasNameValid(string $aliasName, ?NameScope $nameScope): bool { if ($nameScope === null) { @@ -415,9 +506,13 @@ private function hasErrorType(Type $type, string $aliasName, array &$errors): bo } if ($type instanceof ErrorType) { - $errors[] = RuleErrorBuilder::message(sprintf('Invalid type definition detected in type alias %s.', $aliasName)) - ->identifier('typeAlias.invalidType') - ->build(); + $errorBuilder = RuleErrorBuilder::message(sprintf('Invalid type definition detected in type alias %s.', $aliasName)) + ->identifier('typeAlias.invalidType'); + $reason = $type->getReason(); + if ($reason !== null) { + $errorBuilder->tip($reason); + } + $errors[] = $errorBuilder->build(); $foundError = true; return $type; } diff --git a/src/Type/FileTypeMapper.php b/src/Type/FileTypeMapper.php index 252eebe737d..71306460899 100644 --- a/src/Type/FileTypeMapper.php +++ b/src/Type/FileTypeMapper.php @@ -24,9 +24,12 @@ use PHPStan\PhpDoc\PhpDocStringResolver; use PHPStan\PhpDoc\ResolvedPhpDocBlock; use PHPStan\PhpDoc\Tag\TemplateTag; +use PHPStan\PhpDoc\Tag\TypeAliasImportTag; use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode; use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\Reflection\ReflectionProvider\ReflectionProviderProvider; use PHPStan\ShouldNotHappenException; @@ -44,6 +47,7 @@ use function array_merge; use function array_pop; use function array_reverse; +use function array_values; use function count; use function in_array; use function is_array; @@ -269,8 +273,14 @@ public function getNameScope( $phpDocTemplateTypes = []; $templateTags = []; + $functionTypeAliases = []; $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider(); foreach (array_reverse($parents) as $parent) { + // an alias of an anonymous class shadows the one of the function it is declared in + foreach (array_keys($parent->getTypeAliasesMap()) as $classTypeAliasName) { + unset($functionTypeAliases[$classTypeAliasName]); + } + $nameScope = new NameScope( $parent->getNamespace(), $parent->getUses(), @@ -283,6 +293,7 @@ public function getNameScope( $parent->getConstUses(), $parent->getClassNameForTypeAlias(), $fileName, + $functionTypeAliases, ); if ($parent->getTraitData() !== null) { [$traitFileName, $traitClassName, $traitName, $lookForTraitName, $traitDocComment] = $parent->getTraitData(); @@ -336,6 +347,14 @@ public function getNameScope( continue; } + $hasLevelTypeAliases = $parent->getFunctionTypeAliasTagValueNodes() !== [] || $parent->getFunctionTypeAliasImportTagValueNodes() !== []; + if ($hasLevelTypeAliases) { + // the bounds and defaults of the templates declared next to the aliases may name them; + // the aliases that mention those templates are written into them, see TemplateBoundAliasInliner + $outerFunctionTypeAliases = $functionTypeAliases; + $nameScope = $nameScope->withFunctionTypeAliases(fn (NameScope $levelNameScope): array => $this->createFunctionTypeAliases($parent, $levelNameScope, $fileName, $outerFunctionTypeAliases, '#bounds')); + } + $this->inProcessNameScopes[$nameScopeKey] = $nameScope; $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($parent->getTemplatePhpDocNodes(), $nameScope, $templateTypeScope, $parent->getLocalTypeAliasNodes()); @@ -347,6 +366,25 @@ public function getNameScope( } $phpDocTemplateTypes[$name] = $templateType; } + + if (!$hasLevelTypeAliases) { + continue; + } + + $outerFunctionTypeAliases = $functionTypeAliases; + $functionTypeAliases = (new NameScope( + $parent->getNamespace(), + $parent->getUses(), + $parent->getClassName(), + $parent->getFunctionName(), + new TemplateTypeMap($phpDocTemplateTypes), + $templateTags, + $parent->getTypeAliasesMap(), + $parent->shouldBypassTypeAliases(), + $parent->getConstUses(), + $parent->getClassNameForTypeAlias(), + $fileName, + ))->withFunctionTypeAliases(fn (NameScope $levelNameScope): array => $this->createFunctionTypeAliases($parent, $levelNameScope, $fileName, $outerFunctionTypeAliases, ''))->getFunctionTypeAliases(); } return new NameScope( @@ -361,6 +399,7 @@ public function getNameScope( $intermediaryNameScope->getConstUses(), $intermediaryNameScope->getClassNameForTypeAlias(), $fileName, + $functionTypeAliases, ); } finally { unset($this->inProcess[$nameScopeKey]); @@ -371,6 +410,44 @@ public function getNameScope( } } + /** + * The aliases declared and imported above a function or a method, on top of those of the + * functions and methods around it, which they shadow. They resolve in $levelNameScope, so + * they may mention the templates of the function and of the class it is in. + * + * @param array $outerFunctionTypeAliases + * @return array + */ + private function createFunctionTypeAliases( + IntermediaryNameScope $level, + NameScope $levelNameScope, + string $fileName, + array $outerFunctionTypeAliases, + string $keySuffix, + ): array + { + $functionTypeAliases = $outerFunctionTypeAliases; + $keyPrefix = sprintf('%s::%s::%s::', $fileName, $level->getClassName() ?? '', $level->getFunctionName() ?? ''); + foreach ($level->getFunctionTypeAliasImportTagValueNodes() as $aliasName => $importTagValueNode) { + $functionTypeAliases[$aliasName] = [ + new TypeAliasImportTag( + $importTagValueNode->importedAlias, + $levelNameScope->resolveStringName((string) $importTagValueNode->importedFrom), + $importTagValueNode->importedAs, + ), + $keyPrefix . $aliasName . $keySuffix, + ]; + } + foreach ($level->getFunctionTypeAliasTagValueNodes() as $aliasName => $tagValueNode) { + $functionTypeAliases[$aliasName] = [ + new TypeAlias($tagValueNode->type, $levelNameScope, $aliasName, array_values($tagValueNode->templateTypes)), + $keyPrefix . $aliasName . $keySuffix, + ]; + } + + return $functionTypeAliases; + } + /** * @return array{array} */ @@ -395,7 +472,8 @@ private function getNameScopeMap(string $fileName): array // v7 entries may be built from it even under the key of the full AST // v9: the anonymous class names in the map depend on the PHPStan installation directory // v10: class-level IntermediaryNameScope carries the type alias nodes of the class - $variableCacheKey = sprintf('v10-%s-%s', ComposerHelper::getPhpDocParserVersion(), $this->anonymousClassNameHelper->getCacheKey()); + // v11: function-level IntermediaryNameScope carries the type aliases declared and imported above the function + $variableCacheKey = sprintf('v11-%s-%s', ComposerHelper::getPhpDocParserVersion(), $this->anonymousClassNameHelper->getCacheKey()); $cached = $this->loadCachedPhpDocNodeMap($cacheKey, $variableCacheKey); if ($cached === null) { [$nameScopeMap, $files] = $this->createPhpDocNodeMap($fileName, null, null, [], $fileName); @@ -571,7 +649,9 @@ function (Node $node) use ($fileName, $lookForTrait, &$traitFound, $traitMethodA $parentNameScope, array_last($typeAliasStack) ?? [], typeAliasClassName: $lookForTrait, - localTypeAliasNodes: $node instanceof Node\Stmt\ClassLike ? $this->getLocalTypeAliasNodes($phpDocNode) : [], + localTypeAliasNodes: $this->getLocalTypeAliasNodes($phpDocNode), + functionTypeAliasTagValueNodes: $node instanceof Node\Stmt\ClassLike ? [] : $this->getTypeAliasTagValueNodes($phpDocNode), + functionTypeAliasImportTagValueNodes: $node instanceof Node\Stmt\ClassLike ? [] : $this->getTypeAliasImportTagValueNodes($phpDocNode), ); } elseif ($node instanceof Node\Stmt\ClassLike) { $typeAliasStack[] = []; @@ -616,6 +696,8 @@ function (Node $node) use ($fileName, $lookForTrait, &$traitFound, $traitMethodA $typeAliasesMap, typeAliasClassName: $lookForTrait, localTypeAliasNodes: $parentNameScope !== null ? $parentNameScope->getLocalTypeAliasNodes() : [], + functionTypeAliasTagValueNodes: $parentNameScope !== null ? $parentNameScope->getFunctionTypeAliasTagValueNodes() : [], + functionTypeAliasImportTagValueNodes: $parentNameScope !== null ? $parentNameScope->getFunctionTypeAliasImportTagValueNodes() : [], ); } @@ -811,6 +893,36 @@ private function getLocalTypeAliasNodes(PhpDocNode $phpDocNode): array return $nodes; } + /** + * @return array + */ + private function getTypeAliasTagValueNodes(PhpDocNode $phpDocNode): array + { + $nodes = []; + foreach (['@phan-type', '@psalm-type', '@phpstan-type'] as $tagName) { + foreach ($phpDocNode->getTypeAliasTagValues($tagName) as $typeAliasTagValue) { + $nodes[$typeAliasTagValue->alias] = $typeAliasTagValue; + } + } + + return $nodes; + } + + /** + * @return array + */ + private function getTypeAliasImportTagValueNodes(PhpDocNode $phpDocNode): array + { + $nodes = []; + foreach (['@psalm-import-type', '@phpstan-import-type'] as $tagName) { + foreach ($phpDocNode->getTypeAliasImportTagValues($tagName) as $typeAliasImportTagValue) { + $nodes[$typeAliasImportTagValue->importedAs ?? $typeAliasImportTagValue->importedAlias] = $typeAliasImportTagValue; + } + } + + return $nodes; + } + /** * @return array */ diff --git a/src/Type/UsefulTypeAliasResolver.php b/src/Type/UsefulTypeAliasResolver.php index 05c67f7e495..1d62eeea497 100644 --- a/src/Type/UsefulTypeAliasResolver.php +++ b/src/Type/UsefulTypeAliasResolver.php @@ -113,6 +113,7 @@ public function resolveTypeAlias(string $aliasName, NameScope $nameScope): ?Type public function resolveTypeAliasWithArguments(string $aliasName, array $arguments, NameScope $nameScope): ?Type { $resolvedAlias = $this->resolveGlobalTypeAlias($aliasName, $arguments, $nameScope) + ?? $this->resolveFunctionTypeAlias($aliasName, $arguments, $nameScope) ?? $this->resolveLocalTypeAlias($aliasName, $arguments, $nameScope); if ($resolvedAlias === null) { return null; @@ -128,12 +129,21 @@ public function resolveTypeAliasWithArguments(string $aliasName, array $argument } $className = $nameScope->getClassNameForTypeAlias(); + $functionTypeAlias = $nameScope->getFunctionTypeAlias($aliasName); + if ($functionTypeAlias !== null && $functionTypeAlias[0] instanceof TypeAlias && !array_key_exists($aliasName, $this->getGlobalTypeAliasNames())) { + // declared where it is used, so every template it mentions means what it says + $adaptParameterType = static fn (Type $type): Type => $type; + } elseif ($className === null) { + $adaptParameterType = $functionTypeAlias !== null ? static fn (Type $type): Type => self::resolveAllClassTemplatesToBounds($type) : static fn (Type $type): Type => $type; + } else { + $adaptParameterType = static fn (Type $type): Type => self::resolveForeignTemplatesToBounds($type, $className); + } return $typeAlias->resolveWithArguments( $this->typeNodeResolver, $body, $arguments, - static fn (Type $type): Type => $className === null ? $type : self::resolveForeignTemplatesToBounds($type, $className), + $adaptParameterType, ); } @@ -198,6 +208,48 @@ private function getGlobalTypeAliasNames(): array return $this->globalTypeAliasNames = $names; } + /** + * An alias declared or imported above the function or method the PHPDoc is in, or above one around it. + * + * @param list $arguments + * @return array{TypeAlias, Type, bool}|null + */ + private function resolveFunctionTypeAlias(string $aliasName, array $arguments, NameScope $nameScope): ?array + { + $functionTypeAlias = $nameScope->getFunctionTypeAlias($aliasName); + if ($functionTypeAlias === null) { + return null; + } + + [$typeAliasOrImport, $key] = $functionTypeAlias; + if ($typeAliasOrImport instanceof TypeAlias) { + return $this->resolveAlias($key, $aliasName, $arguments, static fn (Type $type): Type => $type, static fn (): TypeAlias => $typeAliasOrImport); + } + + $className = $nameScope->getClassNameForTypeAlias(); + + return $this->resolveAlias( + $key, + $aliasName, + $arguments, + static fn (Type $type): Type => $className === null ? self::resolveAllClassTemplatesToBounds($type) : self::resolveForeignTemplatesToBounds($type, $className), + function () use ($typeAliasOrImport): ?TypeAlias { + $importedFrom = $typeAliasOrImport->getImportedFrom(); + if (!$this->reflectionProvider->hasClass($importedFrom)) { + return null; + } + + try { + $typeAliases = $this->reflectionProvider->getClass($importedFrom)->getTypeAliases(); + } catch (CircularTypeAliasDefinitionException) { + return TypeAlias::invalid(); + } + + return $typeAliases[$typeAliasOrImport->getImportedAlias()] ?? null; + }, + ); + } + /** * @param list $arguments * @return array{TypeAlias, Type, bool}|null @@ -294,10 +346,9 @@ private function resolveAlias(string $key, string $aliasName, array $arguments, if ($growingLink !== null) { return [$unresolvedAlias, new ErrorType(sprintf( - 'Type alias %s refers to %s with a type argument that contains a parameter of %s, so its expansion would never end.', - $unresolvedAlias->describe(), - $growingLink[1]->describe(), + 'Type alias %1$s refers to %2$s with a type argument that contains a parameter of %1$s, so its expansion would never end.', $growingLink[0]->describe(), + $growingLink[1]->describe(), )), true]; } @@ -516,6 +567,26 @@ private static function bindRecursion(Type $type, string $id, string $aliasName) return new RecursiveType($type, $id, $aliasName); } + /** + * An alias imported above a function outside of a class may mention the templates of the class + * it is imported from, which mean nothing there, so they are replaced by their bounds. + */ + private static function resolveAllClassTemplatesToBounds(Type $type): Type + { + return TypeTraverser::map($type, static function (Type $type, callable $traverse): Type { + if (!$type instanceof TemplateType) { + return $traverse($type); + } + + $scope = $type->getScope(); + if ($scope->getFunctionName() !== null || $scope->getClassName() === null) { + return $traverse($type); + } + + return $traverse($type->getBound()); + }); + } + /** * An alias imported from another class may mention that class's templates, * which mean nothing in $className, so they are replaced by their bounds. diff --git a/tests/PHPStan/Analyser/nsrt/bug-12208.php b/tests/PHPStan/Analyser/nsrt/bug-12208.php new file mode 100644 index 00000000000..fae4ed84cb8 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-12208.php @@ -0,0 +1,34 @@ +foo()); +}; diff --git a/tests/PHPStan/Analyser/nsrt/bug-13315.php b/tests/PHPStan/Analyser/nsrt/bug-13315.php new file mode 100644 index 00000000000..43c579d2472 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-13315.php @@ -0,0 +1,31 @@ += 8.0 + +declare(strict_types = 1); + +namespace Bug13315; + +use function PHPStan\Testing\assertType; + +/** + * @phpstan-type PassThroughArray array> + */ +final class View +{ + /** @param PassThroughArray $passThrough */ + public function __construct( + public array $passThrough = [], + ) {} +} + + +// functions.php + +/** + * @phpstan-import-type PassThroughArray from View + * @param PassThroughArray $data + */ +function view(array $data): View +{ + assertType('array|string>', $data); + return new View($data); +} diff --git a/tests/PHPStan/Analyser/nsrt/bug-9424.php b/tests/PHPStan/Analyser/nsrt/bug-9424.php new file mode 100644 index 00000000000..2903cdfbee8 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-9424.php @@ -0,0 +1,17 @@ +} + * @return FooResult + */ +function foo(): array { + return ['foo' => 1]; +} + +function (): void { + assertType('array{foo: int<0, max>}', foo()); +}; diff --git a/tests/PHPStan/Analyser/nsrt/function-type-aliases.php b/tests/PHPStan/Analyser/nsrt/function-type-aliases.php new file mode 100644 index 00000000000..bea36e1b6fc --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/function-type-aliases.php @@ -0,0 +1,174 @@ += 8.0 + +namespace FunctionTypeAliases; + +use function PHPStan\Testing\assertType; + +/** + * @phpstan-type BlockAttributes array{language: string, wrapLines: bool} + * @param BlockAttributes $attributes + */ +function render_block(array $attributes, mixed $value): void +{ + assertType('array{language: string, wrapLines: bool}', $attributes); + + /** @var BlockAttributes $value */ + assertType('array{language: string, wrapLines: bool}', $value); + + $f = function (mixed $inClosure): void { + /** @var BlockAttributes $inClosure */ + assertType('array{language: string, wrapLines: bool}', $inClosure); + }; +} + +/** + * @param BlockAttributes $attributes + */ +function after_render_block($attributes): void +{ + assertType('FunctionTypeAliases\BlockAttributes', $attributes); +} + +/** + * @template T of object + * @phpstan-type Source array{source: T} + * @phpstan-type Shared string + */ +class Src +{ +} + +/** + * @phpstan-import-type Source from Src + * @phpstan-import-type Source from Src as Renamed + * @param Source $a + * @param Renamed $b + */ +function imports($a, $b): void +{ + assertType('array{source: object}', $a); + assertType('array{source: object}', $b); +} + +/** + * @template T of int + * @phpstan-type Box array{T} + * @phpstan-type Pair array{A, B} + * @template V of Box = Box + * @param Box $box + * @param Pair $pair + * @param V $v + * @return V + */ +function templates(int $t, $box, $pair, $v) +{ + assertType('array{T of int (function FunctionTypeAliases\templates(), argument)}', $box); + assertType('array{T of int (function FunctionTypeAliases\templates(), argument), T of int (function FunctionTypeAliases\templates(), argument)}', $pair); + assertType('V of array{T of int (function FunctionTypeAliases\templates(), argument)} = array{T of int (function FunctionTypeAliases\templates(), argument)} (function FunctionTypeAliases\templates(), argument)', $v); + + return $v; +} + +function (): void { + assertType('array{1}', templates(1, [1], [1, 1], [1])); +}; + +/** + * @template T of object + * @phpstan-type ClassAlias array{class: T} + * @phpstan-type Shared int + */ +class Foo +{ + + /** + * @phpstan-type MethodAlias array{T, ClassAlias} + * @phpstan-type Tree array{value: int, children: list} + * @phpstan-type Shared float + * @phpstan-import-type Source from Src + * @template U of MethodAlias + * @param MethodAlias $m + * @param Tree $tree + * @param U $u + * @param Shared $shared + * @param Source $source + */ + public function doFoo($m, $tree, $u, $shared, $source): void + { + assertType('array{T of object (class FunctionTypeAliases\Foo, argument), array{class: T of object (class FunctionTypeAliases\Foo, argument)}}', $m); + assertType('array{value: int, children: list}', $tree); + assertType('U of array{T of object (class FunctionTypeAliases\Foo, argument), array{class: T of object (class FunctionTypeAliases\Foo, argument)}} (method FunctionTypeAliases\Foo::doFoo(), argument)', $u); + assertType('float', $shared); + assertType('array{source: object}', $source); + + $withPhpDoc = new + /** + * @phpstan-type AnonAlias string + * @phpstan-type Shared bool + */ + class { + + /** + * @param AnonAlias $a + * @param MethodAlias $m + * @param Shared $shared + */ + public function doBar($a, $m, $shared): void + { + assertType('string', $a); + assertType('array{T of object (class FunctionTypeAliases\Foo, argument), array{class: T of object (class FunctionTypeAliases\Foo, argument)}}', $m); + assertType('bool', $shared); + } + + }; + + $withoutPhpDoc = new class { + + /** + * @param MethodAlias $m + * @param Shared $shared + */ + public function doBar($m, $shared): void + { + assertType('array{T of object (class FunctionTypeAliases\Foo, argument), array{class: T of object (class FunctionTypeAliases\Foo, argument)}}', $m); + assertType('float', $shared); + } + + }; + } + + /** + * @param MethodAlias $m + * @param Shared $shared + */ + public function afterDoFoo($m, $shared): void + { + assertType('FunctionTypeAliases\MethodAlias', $m); + assertType('int', $shared); + } + +} + +trait FooTrait +{ + + /** + * @phpstan-type TraitMethodAlias array{int} + * @param TraitMethodAlias $a + */ + public function doFoo($a, mixed $b): void + { + assertType('array{int}', $a); + + /** @var TraitMethodAlias $b */ + assertType('array{int}', $b); + } + +} + +class UsesFooTrait +{ + + use FooTrait; + +} diff --git a/tests/PHPStan/Rules/Classes/FunctionTypeAliasesRuleTest.php b/tests/PHPStan/Rules/Classes/FunctionTypeAliasesRuleTest.php new file mode 100644 index 00000000000..0e4a9cde3aa --- /dev/null +++ b/tests/PHPStan/Rules/Classes/FunctionTypeAliasesRuleTest.php @@ -0,0 +1,118 @@ + + */ +class FunctionTypeAliasesRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + $reflectionProvider = self::createReflectionProvider(); + $container = self::getContainer(); + + return new FunctionTypeAliasesRule( + $container->getByType(FileTypeMapper::class), + new LocalTypeAliasesCheck( + ['GlobalTypeAlias' => 'int|string'], + $reflectionProvider, + $container->getByType(TypeNodeResolver::class), + new MissingTypehintCheck(true, [], true), + new ClassNameCheck( + new ClassCaseSensitivityCheck($reflectionProvider, true, true), + new ClassForbiddenNameCheck($container->getExtensionsCollection(ForbiddenClassNameExtension::class)), + $reflectionProvider, + $container->getExtensionsCollection(RestrictedClassNameUsageExtension::class), + ), + new UnresolvableTypeHelper(), + new GenericObjectTypeCheck(), + true, + true, + true, + true, + ), + ); + } + + public function testRule(): void + { + $this->analyse([__DIR__ . '/data/function-type-aliases.php'], [ + [ + 'Cannot import type alias ClassAlias: class FunctionTypeAliasesRule\\Nowhere does not exist.', + 32, + ], + [ + 'Cannot import type alias Nope: type alias does not exist in FunctionTypeAliasesRule\\Src.', + 32, + ], + [ + 'Circular definition detected in type alias Circ.', + 32, + ], + [ + 'Method FunctionTypeAliasesRule\\Foo::doFoo() has type alias Missing with no value type specified in iterable type array.', + 32, + MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, + ], + [ + 'PHPDoc tag @phpstan-type Gen template T shadows @template T for method FunctionTypeAliasesRule\\Foo::doFoo().', + 32, + ], + [ + 'Type alias Bad contains unknown class FunctionTypeAliasesRule\\Unknown.', + 32, + 'Learn more at https://phpstan.org/user-guide/discovering-symbols', + ], + [ + 'Type alias GlobalTypeAlias already exists as a global type alias.', + 32, + ], + [ + 'Type alias Over overwrites an imported type alias of the same name.', + 32, + ], + [ + 'Type alias Src already exists as a class in scope of method FunctionTypeAliasesRule\\Foo::doFoo().', + 32, + ], + [ + 'Type alias T of method FunctionTypeAliasesRule\\Foo::doFoo() shadows @template T of class FunctionTypeAliasesRule\\Foo.', + 32, + ], + [ + 'Type alias U of method FunctionTypeAliasesRule\\Foo::doFoo() shadows @template U of method FunctionTypeAliasesRule\\Foo::doFoo().', + 32, + ], + [ + 'Invalid type definition detected in type alias OutsideBound.', + 42, + 'Type \'x\' in type alias Bounded is not subtype of the bound int of its parameter B.', + ], + [ + 'Invalid type definition detected in type alias TooFewArguments.', + 42, + 'Type alias Pair takes 2 type arguments, 1 given.', + ], + [ + 'Type alias V of function FunctionTypeAliasesRule\\shadowedByImport() shadows @template V of function FunctionTypeAliasesRule\\shadowedByImport().', + 61, + ], + ]); + } + +} diff --git a/tests/PHPStan/Rules/Classes/LocalTypeAliasesRuleTest.php b/tests/PHPStan/Rules/Classes/LocalTypeAliasesRuleTest.php index c9de07be46d..415d34d6e3a 100644 --- a/tests/PHPStan/Rules/Classes/LocalTypeAliasesRuleTest.php +++ b/tests/PHPStan/Rules/Classes/LocalTypeAliasesRuleTest.php @@ -213,6 +213,7 @@ public function testGenericTypeAliasRecursion(): void [ 'Invalid type definition detected in type alias Growing.', 18, + 'Type alias Growing refers to Growing with a type argument that contains a parameter of Growing, so its expansion would never end.', ], [ 'Circular definition detected in type alias Circular.', @@ -221,14 +222,17 @@ public function testGenericTypeAliasRecursion(): void [ 'Invalid type definition detected in type alias GrowingThroughFixed.', 18, + 'Type alias GrowingThroughFixed refers to GrowingThroughFixed with a type argument that contains a parameter of GrowingThroughFixed, so its expansion would never end.', ], [ 'Invalid type definition detected in type alias Link.', 18, + 'Type alias Node refers to Link with a type argument that contains a parameter of Node, so its expansion would never end.', ], [ 'Invalid type definition detected in type alias Node.', 18, + 'Type alias Node refers to Link with a type argument that contains a parameter of Node, so its expansion would never end.', ], ]); } diff --git a/tests/PHPStan/Rules/Classes/data/function-type-aliases.php b/tests/PHPStan/Rules/Classes/data/function-type-aliases.php new file mode 100644 index 00000000000..7b018333259 --- /dev/null +++ b/tests/PHPStan/Rules/Classes/data/function-type-aliases.php @@ -0,0 +1,63 @@ + list + * @phpstan-type Missing array + * @phpstan-type Circ Circ + * @phpstan-type Src int + * @phpstan-type Bad Unknown + * @phpstan-type GlobalTypeAlias int + * @phpstan-import-type Nope from Src + * @phpstan-import-type ClassAlias from Nowhere + * @phpstan-import-type ClassAlias from Src as Over + * @phpstan-type Over int + * @param U $u + */ + public function doFoo($u): void + { + } + + /** + * @phpstan-type Pair array{A, B} + * @phpstan-type TooFewArguments Pair + * @phpstan-type Bounded list + * @phpstan-type OutsideBound Bounded<'x'> + */ + public function doBaz(): void + { + } + + /** + * @phpstan-type Fine array{int} + * @phpstan-import-type ClassAlias from Src + */ + public function doBar(): void + { + } + +} + +/** + * @template V + * @phpstan-import-type ClassAlias from Src as V + * @param V $v + */ +function shadowedByImport($v): void +{ +}