Skip to content

Understand that new Foo() cannot be a subclass #3853

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2025
Merged
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
47 changes: 37 additions & 10 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -5599,6 +5599,10 @@ private function exactInstantiation(New_ $node, string $className): ?Type
}

$classReflection = $this->reflectionProvider->getClass($resolvedClassName);
$nonFinalClassReflection = $classReflection;
if (!$isStatic) {
$classReflection = $classReflection->asFinal();
}
if ($classReflection->hasConstructor()) {
$constructorMethod = $classReflection->getConstructor();
} else {
Expand Down Expand Up @@ -5648,7 +5652,7 @@ private function exactInstantiation(New_ $node, string $className): ?Type
return $methodResult;
}

$objectType = $isStatic ? new StaticType($classReflection) : new ObjectType($resolvedClassName);
$objectType = $isStatic ? new StaticType($classReflection) : new ObjectType($resolvedClassName, null, $classReflection);
if (!$classReflection->isGeneric()) {
return $objectType;
}
Expand All @@ -5674,7 +5678,8 @@ private function exactInstantiation(New_ $node, string $className): ?Type

if (count($classTemplateTypes) === count($originalClassTemplateTypes)) {
$propertyType = TypeCombinator::removeNull($this->getType($assignedToProperty));
if ($objectType->isSuperTypeOf($propertyType)->yes()) {
$nonFinalObjectType = $isStatic ? new StaticType($nonFinalClassReflection) : new ObjectType($resolvedClassName, null, $nonFinalClassReflection);
if ($nonFinalObjectType->isSuperTypeOf($propertyType)->yes()) {
return $propertyType;
}
}
Expand All @@ -5689,9 +5694,13 @@ private function exactInstantiation(New_ $node, string $className): ?Type
[],
);
}

$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds());
return new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds()),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
}

Expand All @@ -5706,9 +5715,12 @@ private function exactInstantiation(New_ $node, string $className): ?Type
);
}

$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds());
return new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds()),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
}
$newType = new GenericObjectType($resolvedClassName, $classReflection->typeMapToList($classReflection->getTemplateTypeMap()));
Expand All @@ -5723,9 +5735,12 @@ private function exactInstantiation(New_ $node, string $className): ?Type
);
}

$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds());
return new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds()),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
}
$ancestorClassReflections = $ancestorType->getObjectClassReflections();
Expand All @@ -5739,9 +5754,12 @@ private function exactInstantiation(New_ $node, string $className): ?Type
);
}

$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds());
return new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds()),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
}

Expand All @@ -5758,9 +5776,12 @@ private function exactInstantiation(New_ $node, string $className): ?Type
);
}

$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds());
return new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds()),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
}
$newParentTypeClassReflection = $newParentTypeClassReflections[0];
Expand Down Expand Up @@ -5803,9 +5824,12 @@ private function exactInstantiation(New_ $node, string $className): ?Type
);
}

$types = $classReflection->typeMapToList(new TemplateTypeMap($resolvedTypeMap));
return new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList(new TemplateTypeMap($resolvedTypeMap)),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
}

Expand All @@ -5817,14 +5841,17 @@ private function exactInstantiation(New_ $node, string $className): ?Type
);

$resolvedTemplateTypeMap = $parametersAcceptor->getResolvedTemplateTypeMap();
$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap());
$newGenericType = new GenericObjectType(
$resolvedClassName,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()),
$types,
null,
$classReflection->withTypes($types)->asFinal(),
);
if ($isStatic) {
$newGenericType = new GenericStaticType(
$classReflection,
$classReflection->typeMapToList($classReflection->getTemplateTypeMap()),
$types,
null,
[],
);
Expand Down
51 changes: 51 additions & 0 deletions src/Reflection/ClassReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ public function __construct(
private array $universalObjectCratesClasses,
private ?string $extraCacheKey = null,
private ?TemplateTypeVarianceMap $resolvedCallSiteVarianceMap = null,
private ?bool $finalByKeywordOverride = null,
)
{
}
Expand Down Expand Up @@ -306,6 +307,10 @@ public function getCacheKey(): string
$cacheKey .= '<' . implode(',', $templateTypes) . '>';
}

if ($this->hasFinalByKeywordOverride()) {
$cacheKey .= '-f=' . ($this->isFinalByKeyword() ? 't' : 'f');
}

if ($this->extraCacheKey !== null) {
$cacheKey .= '-' . $this->extraCacheKey;
}
Expand Down Expand Up @@ -1276,12 +1281,21 @@ public function acceptsNamedArguments(): bool
return $this->acceptsNamedArguments;
}

public function hasFinalByKeywordOverride(): bool
{
return $this->isClass() && $this->finalByKeywordOverride !== null;
}

public function isFinalByKeyword(): bool
{
if ($this->isAnonymous()) {
return true;
}

if ($this->isClass() && $this->finalByKeywordOverride !== null) {
return $this->finalByKeywordOverride;
}

return $this->reflection->isFinal();
}

Expand Down Expand Up @@ -1543,6 +1557,7 @@ public function withTypes(array $types): self
$this->universalObjectCratesClasses,
null,
$this->resolvedCallSiteVarianceMap,
$this->finalByKeywordOverride,
);
}

Expand Down Expand Up @@ -1573,6 +1588,42 @@ public function withVariances(array $variances): self
$this->universalObjectCratesClasses,
null,
$this->varianceMapFromList($variances),
$this->finalByKeywordOverride,
);
}

public function asFinal(): self
{
if ($this->getNativeReflection()->isFinal()) {
return $this;
}
if ($this->finalByKeywordOverride === true) {
return $this;
}

return new self(
$this->reflectionProvider,
$this->initializerExprTypeResolver,
$this->fileTypeMapper,
$this->stubPhpDocProvider,
$this->phpDocInheritanceResolver,
$this->phpVersion,
$this->signatureMapProvider,
$this->attributeReflectionFactory,
$this->propertiesClassReflectionExtensions,
$this->methodsClassReflectionExtensions,
$this->allowedSubTypesClassReflectionExtensions,
$this->requireExtendsPropertiesClassReflectionExtension,
$this->requireExtendsMethodsClassReflectionExtension,
$this->displayName,
$this->reflection,
$this->anonymousFilename,
$this->resolvedTemplateTypeMap,
$this->stubPhpDocBlock,
$this->universalObjectCratesClasses,
null,
$this->resolvedCallSiteVarianceMap,
true,
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Type/Constant/ConstantStringType.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ public function isCallable(): TrinaryLogic
return TrinaryLogic::createYes();
}

if (!$classRef->getNativeReflection()->isFinal()) {
if (!$classRef->isFinalByKeyword()) {
return TrinaryLogic::createMaybe();
}

Expand Down Expand Up @@ -265,7 +265,7 @@ public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope)
return FunctionCallableVariant::createFromVariants($method, $method->getVariants());
}

if (!$classReflection->getNativeReflection()->isFinal()) {
if (!$classReflection->isFinalByKeyword()) {
return [new TrivialParametersAcceptor()];
}
}
Expand Down
42 changes: 31 additions & 11 deletions src/Type/ObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -377,21 +377,37 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
throw new ShouldNotHappenException();
}

if ($thatClassNames[0] === $thisClassName) {
return $transformResult(IsSuperTypeOfResult::createYes());
}

$reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
$thisClassReflection = $this->getClassReflection();
$thatClassReflections = $type->getObjectClassReflections();
if (count($thatClassReflections) === 1) {
$thatClassReflection = $thatClassReflections[0];
} else {
$thatClassReflection = null;
}

if ($thisClassReflection === null || !$reflectionProvider->hasClass($thatClassNames[0])) {
if ($thisClassReflection === null || $thatClassReflection === null) {
if ($thatClassNames[0] === $thisClassName) {
return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
}
return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
}

$thatClassReflection = $reflectionProvider->getClass($thatClassNames[0]);
if ($thatClassNames[0] === $thisClassName) {
if ($thisClassReflection->getNativeReflection()->isFinal()) {
return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
}

if ($thisClassReflection->hasFinalByKeywordOverride()) {
if (!$thatClassReflection->hasFinalByKeywordOverride()) {
return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createMaybe());
}
}

return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
}

if ($thisClassReflection->isTrait() || $thatClassReflection->isTrait()) {
return IsSuperTypeOfResult::createNo();
return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createNo();
}

if ($thisClassReflection->getName() === $thatClassReflection->getName()) {
Expand All @@ -406,11 +422,11 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
}

if ($thisClassReflection->isInterface() && !$thatClassReflection->getNativeReflection()->isFinal()) {
if ($thisClassReflection->isInterface() && !$thatClassReflection->isFinalByKeyword()) {
return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
}

if ($thatClassReflection->isInterface() && !$thisClassReflection->getNativeReflection()->isFinal()) {
if ($thatClassReflection->isInterface() && !$thisClassReflection->isFinalByKeyword()) {
return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
}

Expand Down Expand Up @@ -550,6 +566,10 @@ private function describeCache(): string
$description .= '-';
$description .= (string) $reflection->getNativeReflection()->getStartLine();
$description .= '-';

if ($reflection->hasFinalByKeywordOverride()) {
$description .= 'f=' . ($reflection->isFinalByKeyword() ? 't' : 'f');
}
}

return $this->cachedDescription = $description;
Expand Down Expand Up @@ -1331,7 +1351,7 @@ private function findCallableParametersAcceptors(): ?array
);
}

if (!$classReflection->getNativeReflection()->isFinal()) {
if (!$classReflection->isFinalByKeyword()) {
return [new TrivialParametersAcceptor()];
}

Expand Down
2 changes: 1 addition & 1 deletion tests/PHPStan/Analyser/nsrt/get-debug-type.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function doFoo(bool $b, int $i, float $f, $d, $r, string $s, array $a, $intOrStr
assertType("'float'", get_debug_type($d));
assertType("'string'", get_debug_type($s));
assertType("'array'", get_debug_type($a));
assertType("string", get_debug_type($o));
assertType("'stdClass'", get_debug_type($o));
assertType("string", get_debug_type($std));
assertType("'GetDebugType\\\\A'", get_debug_type($A));
assertType("string", get_debug_type($r));
Expand Down
11 changes: 11 additions & 0 deletions tests/PHPStan/Rules/Classes/ImpossibleInstanceOfRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -504,4 +504,15 @@ public function testBug3632(): void
]);
}

public function testNewIsAlwaysFinalClass(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/data/impossible-instanceof-new-is-always-final.php'], [
[
'Instanceof between ImpossibleInstanceofNewIsAlwaysFinal\Bar and ImpossibleInstanceofNewIsAlwaysFinal\Foo will always evaluate to false.',
17,
],
]);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace ImpossibleInstanceofNewIsAlwaysFinal;

interface Foo
{

}

class Bar
{

}

function (): void {
$bar = new Bar();
if ($bar instanceof Foo) {

}
};

function (Bar $bar): void {
if ($bar instanceof Foo) {

}
};
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ public function testImpossibleCheckTypeFunctionCall(): void
'Call to function is_string() with string will always evaluate to true.',
140,
],
[
'Call to function method_exists() with CheckTypeFunctionCall\Foo and \'test\' will always evaluate to false.',
176,
],
[
'Call to function method_exists() with CheckTypeFunctionCall\Foo and \'doFoo\' will always evaluate to true.',
179,
Expand Down Expand Up @@ -172,6 +176,10 @@ public function testImpossibleCheckTypeFunctionCall(): void
'Call to function method_exists() with CheckTypeFunctionCall\MethodExists and \'testWithNewObjectIn…\' will always evaluate to true.',
620,
],
[
'Call to function method_exists() with CheckTypeFunctionCall\MethodExists and \'undefinedMethod\' will always evaluate to false.',
623,
],
[
'Call to function method_exists() with CheckTypeFunctionCall\MethodExists and \'testWithNewObjectIn…\' will always evaluate to true.',
635,
Expand Down
Loading
Loading