Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions conf/bleedingEdge.neon
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ parameters:
checkConditionalParameterTypes: true
checkMixedWitnessTypes: true
recursiveLoopTypes: true
checkConsistentTemplates: true
1 change: 1 addition & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ parameters:
checkConditionalParameterTypes: false
checkMixedWitnessTypes: false
recursiveLoopTypes: false
checkConsistentTemplates: false
fileExtensions:
- php
checkAdvancedIsset: false
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ parametersSchema:
checkConditionalParameterTypes: bool()
checkMixedWitnessTypes: bool()
recursiveLoopTypes: bool()
checkConsistentTemplates: bool()
])
fileExtensions: listOf(string())
checkAdvancedIsset: bool()
Expand Down
20 changes: 19 additions & 1 deletion src/Analyser/ExprHandler/NewHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\TemplateTypeApplication;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
Expand Down Expand Up @@ -531,7 +532,24 @@ private function resolveReturnType(MutatingScope $scope, Expr $expr, ?Parameters
if ($classExprType === null) {
throw new ShouldNotHappenException();
}
return $classExprType->getObjectTypeOrClassStringObjectType();
$objectType = $classExprType->getObjectTypeOrClassStringObjectType();
if ($preResolvedAcceptor === null) {
return $objectType;
}

// new $class(…) on a class-string<TColl>: TColl<…> with the arguments the constructor infers
$application = TemplateTypeApplication::ofInstantiation($objectType);
if ($application === null) {
return $objectType;
}

$frame = $allowUnresolved ? $scope->getCurrentTemplateArgumentFrame() : null;
$arguments = TypeTraverser::map($application->getApplication(), new GenericTypeTemplateTraverser($preResolvedAcceptor->getResolvedTemplateTypeMap(), $expr, $frame, $allowUnresolved));
if (!$arguments instanceof GenericStaticType) {
return $objectType;
}

return new TemplateTypeApplication($application->getConstructor(), $arguments, true);
}

/**
Expand Down
3 changes: 3 additions & 0 deletions src/DependencyInjection/ValidateIgnoredErrorsExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\TypeParser;
use PHPStan\PhpDocParser\ParserConfig;
use PHPStan\Reflection\ConsistentTemplatesHelper;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Reflection\MissingStaticAccessorInstanceException;
use PHPStan\Reflection\PhpVersionStaticAccessor;
Expand Down Expand Up @@ -134,6 +135,8 @@ public function resolveTypeAliasWithArguments(string $aliasName, array $argument
new InitializerExprTypeResolver($constantResolver, $reflectionProviderProvider, new PhpVersion(PHP_VERSION_ID), new OperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new UnaryOperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new OversizedArrayBuilder(), true, $valueDependencyCollector),
reportUnsafeArrayStringKeyCasting: null,
valueDependencyCollector: $valueDependencyCollector,
consistentTemplatesHelper: new ConsistentTemplatesHelper(),
checkConsistentTemplates: false,
),
),
);
Expand Down
11 changes: 11 additions & 0 deletions src/PhpDoc/PhpDocNodeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,17 @@ public function resolveHasConsistentConstructor(PhpDocNode $phpDocNode): bool
return false;
}

public function resolveHasConsistentTemplates(PhpDocNode $phpDocNode): bool
{
foreach (['@phpstan-consistent-templates', '@psalm-consistent-templates'] as $tagName) {
if (count($phpDocNode->getTagsByName($tagName)) > 0) {
return true;
}
}

return false;
}

public function resolveAcceptsNamedArguments(PhpDocNode $phpDocNode): bool
{
return count($phpDocNode->getTagsByName('@no-named-arguments')) === 0;
Expand Down
11 changes: 11 additions & 0 deletions src/PhpDoc/ResolvedPhpDocBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ final class ResolvedPhpDocBlock

private ?bool $hasConsistentConstructor = null;

private ?bool $hasConsistentTemplates = null;

private ?bool $acceptsNamedArguments = null;

private function __construct()
Expand Down Expand Up @@ -254,6 +256,7 @@ public static function createEmpty(): self
$self->isImmutable = false;
$self->isAllowedPrivateMutation = false;
$self->hasConsistentConstructor = false;
$self->hasConsistentTemplates = false;
$self->acceptsNamedArguments = true;

return $self;
Expand Down Expand Up @@ -312,6 +315,7 @@ public function merge(ResolvedPhpDocBlock $parent, InheritedPhpDocParameterMappi
$result->isImmutable = $this->isImmutable();
$result->isAllowedPrivateMutation = $this->isAllowedPrivateMutation();
$result->hasConsistentConstructor = $this->hasConsistentConstructor();
$result->hasConsistentTemplates = $this->hasConsistentTemplates();
$result->acceptsNamedArguments = $acceptsNamedArguments;

return $result;
Expand Down Expand Up @@ -828,6 +832,13 @@ public function hasConsistentConstructor(): bool
);
}

public function hasConsistentTemplates(): bool
{
return $this->hasConsistentTemplates ??= $this->phpDocNodeResolver->resolveHasConsistentTemplates(
$this->phpDocNode,
);
}

public function acceptsNamedArguments(): bool
{
return $this->acceptsNamedArguments ??= $this->phpDocNodeResolver->resolveAcceptsNamedArguments(
Expand Down
35 changes: 35 additions & 0 deletions src/PhpDoc/TypeNodeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use PHPStan\Reflection\Assertions;
use PHPStan\Reflection\Callables\SimpleImpurePoint;
use PHPStan\Reflection\ConsistentTemplatesHelper;
use PHPStan\Reflection\InitializerExprContext;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Reflection\Native\NativeParameterReflection;
Expand Down Expand Up @@ -87,6 +88,7 @@
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateSelfReferenceTarget;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\TemplateTypeApplication;
use PHPStan\Type\Generic\TemplateTypeFactory;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeScope;
Expand Down Expand Up @@ -177,6 +179,9 @@ public function __construct(
#[AutowiredParameter]
private ?string $reportUnsafeArrayStringKeyCasting,
private ValueDependencyCollector $valueDependencyCollector,
private ConsistentTemplatesHelper $consistentTemplatesHelper,
#[AutowiredParameter(ref: '%featureToggles.checkConsistentTemplates%')]
private bool $checkConsistentTemplates,
)
{
}
Expand Down Expand Up @@ -1029,6 +1034,12 @@ static function (string $variance): TemplateTypeVariance {
$mainType = $typeNode->type instanceof NameNode
? $this->resolveNameNode($typeNode->type, $nameScope)
: $this->resolveIdentifierTypeNode($typeNode->type, $nameScope);
if ($mainType instanceof TemplateType) {
$application = $this->resolveTemplateTypeApplication($mainType, $genericTypes, $variances);
if ($application !== null) {
return $application;
}
}
$mainTypeObjectClassNames = $mainType->getObjectClassNames();
if (count($mainTypeObjectClassNames) > 1) {
if ($mainType instanceof TemplateType) {
Expand Down Expand Up @@ -1448,6 +1459,30 @@ private function resolveTemplateTagsInDeclaration(array $valueNodes, NameScope $
return $tags;
}

/**
* `TColl<string>` for `@template TColl of Coll`: the class TColl is with other type
* arguments, which only a class with @phpstan-consistent-templates guarantees exists.
* Without it, the type is the bound with the arguments, as it always was.
*
* @param array<int, Type> $genericTypes
* @param array<int, TemplateTypeVariance> $variances
*/
private function resolveTemplateTypeApplication(TemplateType $templateType, array $genericTypes, array $variances): ?Type
{
$classReflections = $templateType->getBound()->getObjectClassReflections();
if (count($classReflections) !== 1 || !$classReflections[0]->isGeneric()) {
return null;
}

$consistent = $this->consistentTemplatesHelper->findConsistentTemplatesClass($classReflections[0]) !== null;
if (!$consistent && !$this->checkConsistentTemplates) {
return null;
}

// the bound with the type arguments for a class without the tag, which the PHPDoc checks report
return new TemplateTypeApplication($templateType, new GenericStaticType($classReflections[0], $genericTypes, null, $variances), $consistent);
}

private function resolveCallableTypeNode(CallableTypeNode $typeNode, NameScope $nameScope): Type
{
$templateTags = [];
Expand Down
51 changes: 51 additions & 0 deletions src/Reflection/ConsistentTemplatesHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php declare(strict_types = 1);

namespace PHPStan\Reflection;

use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Turbo\ReferencedByTurboExtension;
use function array_shift;

/**
* `@phpstan-consistent-templates` on a class or an interface makes every class below it
* declare the same template types and pass them on in the same order, so that the
* class of an object together with other type arguments is a type, like `static<U>`.
*/
#[AutowiredService]
#[ReferencedByTurboExtension(key: 'consistentTemplatesHelper')]
final class ConsistentTemplatesHelper
{

/**
* The class itself or the ancestor with `@phpstan-consistent-templates`, the nearest one first.
* Breadth-first, each ancestor once: interfaces that extend each other form diamonds.
*/
public function findConsistentTemplatesClass(ClassReflection $classReflection): ?ClassReflection
{
$queue = [$classReflection];
$visited = [];
while ($queue !== []) {
$current = array_shift($queue);
if (isset($visited[$current->getName()])) {
continue;
}
$visited[$current->getName()] = true;

$resolvedPhpDoc = $current->getResolvedPhpDoc();
if ($resolvedPhpDoc !== null && $resolvedPhpDoc->hasConsistentTemplates()) {
return $current;
}

$parent = $current->getParentClass();
if ($parent !== null) {
$queue[] = $parent;
}
foreach ($current->getImmediateInterfaces() as $interface) {
$queue[] = $interface;
}
}

return null;
}

}
4 changes: 3 additions & 1 deletion src/Reflection/ResolvedFunctionVariantWithOriginal.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\TemplateTypeApplication;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
Expand Down Expand Up @@ -337,7 +338,8 @@ private function resolveResolvableTemplateTypes(Type $type, TemplateTypeVariance
};

return TypeTraverser::map($type, function (Type $type, callable $traverse) use ($references, $objectCb): Type {
if ($type instanceof GenericObjectType || $type instanceof GenericStaticType) {
// TColl<…> holds its arguments like the object it will be
if ($type instanceof GenericObjectType || $type instanceof GenericStaticType || $type instanceof TemplateTypeApplication) {
return TypeTraverser::map($type, $objectCb);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PHPStan\Reflection\ResolvedMethodReflection;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateTypeApplication;
use PHPStan\Type\StaticType;
use PHPStan\Type\ThisType;
use PHPStan\Type\Type;
Expand Down Expand Up @@ -148,8 +149,13 @@ private function transformStaticType(Type $type): Type
$calledOnTypeReflections = $this->calledOnType->getObjectClassReflections();
if (count($calledOnTypeReflections) === 1) {
$calledOnTypeReflection = $calledOnTypeReflections[0];
$changed = $type->changeBaseClass($calledOnTypeReflection);
$application = TemplateTypeApplication::ofCalledOnType($this->calledOnType, $changed);
if ($application !== null) {
return $application;
}

return $traverse($type->changeBaseClass($calledOnTypeReflection)->getStaticObjectType());
return $traverse($changed->getStaticObjectType());
}

return $this->calledOnType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PHPStan\Reflection\ResolvedPropertyReflection;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateTypeApplication;
use PHPStan\Type\StaticType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeTraverser;
Expand Down Expand Up @@ -90,7 +91,13 @@ private function transformStaticType(Type $type): Type
if ($type instanceof GenericStaticType) {
$fetchedOnTypeReflections = $this->fetchedOnType->getObjectClassReflections();
if (count($fetchedOnTypeReflections) === 1) {
return $traverse($type->changeBaseClass($fetchedOnTypeReflections[0])->getStaticObjectType());
$changed = $type->changeBaseClass($fetchedOnTypeReflections[0]);
$application = TemplateTypeApplication::ofCalledOnType($this->fetchedOnType, $changed);
if ($application !== null) {
return $application;
}

return $traverse($changed->getStaticObjectType());
}

return $this->fetchedOnType;
Expand Down
Loading
Loading