Skip to content
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

ResolvedPhpDocBlock: fix parent return tag merging #2803

Merged
merged 7 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions build/baseline-7.4.neon
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ parameters:
message: "#^Class PHPStan\\\\PhpDoc\\\\ResolvedPhpDocBlock has an uninitialized property \\$phpDocNodeResolver\\. Give it default value or assign it in the constructor\\.$#"
count: 1
path: ../src/PhpDoc/ResolvedPhpDocBlock.php

-
message: "#^Class PHPStan\\\\PhpDoc\\\\ResolvedPhpDocBlock has an uninitialized property \\$reflectionProvider\\. Give it default value or assign it in the constructor\\.$#"
count: 1
path: ../src/PhpDoc/ResolvedPhpDocBlock.php

-
message: "#^Class PHPStan\\\\Reflection\\\\BetterReflection\\\\SourceLocator\\\\CachingVisitor has an uninitialized property \\$fileName\\. Give it default value or assign it in the constructor\\.$#"
count: 1
Expand Down
36 changes: 32 additions & 4 deletions src/PhpDoc/ResolvedPhpDocBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@
use PHPStan\PhpDoc\Tag\UsesTag;
use PHPStan\PhpDoc\Tag\VarTag;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ConditionalTypeForParameter;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\StaticType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeTraverser;
use function array_key_exists;
Expand Down Expand Up @@ -58,6 +61,8 @@ class ResolvedPhpDocBlock

private PhpDocNodeResolver $phpDocNodeResolver;

private ReflectionProvider $reflectionProvider;

/** @var array<(string|int), VarTag>|false */
private array|false $varTags = false;

Expand Down Expand Up @@ -138,6 +143,7 @@ public static function create(
TemplateTypeMap $templateTypeMap,
array $templateTags,
PhpDocNodeResolver $phpDocNodeResolver,
ReflectionProvider $reflectionProvider,
): self
{
// new property also needs to be added to createEmpty() and merge()
Expand All @@ -150,6 +156,7 @@ public static function create(
$self->templateTypeMap = $templateTypeMap;
$self->templateTags = $templateTags;
$self->phpDocNodeResolver = $phpDocNodeResolver;
$self->reflectionProvider = $reflectionProvider;

return $self;
}
Expand Down Expand Up @@ -199,6 +206,11 @@ public static function createEmpty(): self
*/
public function merge(array $parents, array $parentPhpDocBlocks): self
{
$className = $this->nameScope !== null ? $this->nameScope->getClassName() : null;
$classReflection = $className !== null && $this->reflectionProvider->hasClass($className)
? $this->reflectionProvider->getClass($className)
: null;

// new property also needs to be added to createEmpty()
$result = new self();
// we will resolve everything on $this here so these properties don't have to be populated
Expand Down Expand Up @@ -226,7 +238,7 @@ public function merge(array $parents, array $parentPhpDocBlocks): self
$result->usesTags = $this->getUsesTags();
$result->paramTags = self::mergeParamTags($this->getParamTags(), $parents, $parentPhpDocBlocks);
$result->paramOutTags = self::mergeParamOutTags($this->getParamOutTags(), $parents, $parentPhpDocBlocks);
$result->returnTag = self::mergeReturnTags($this->getReturnTag(), $parents, $parentPhpDocBlocks);
$result->returnTag = self::mergeReturnTags($this->getReturnTag(), $classReflection, $parents, $parentPhpDocBlocks);
$result->throwsTag = self::mergeThrowsTags($this->getThrowsTag(), $parents);
$result->mixinTags = $this->getMixinTags();
$result->typeAliasTags = $this->getTypeAliasTags();
Expand Down Expand Up @@ -312,6 +324,7 @@ public function changeParameterNamesByMapping(array $parameterNameMapping): self
$self->templateTypeMap = $this->templateTypeMap;
$self->templateTags = $this->templateTags;
$self->phpDocNodeResolver = $this->phpDocNodeResolver;
$self->reflectionProvider = $this->reflectionProvider;
$self->varTags = $this->varTags;
$self->methodTags = $this->methodTags;
$self->propertyTags = $this->propertyTags;
Expand Down Expand Up @@ -797,14 +810,14 @@ private static function mergeOneParentParamTags(array $paramTags, self $parent,
* @param array<int, PhpDocBlock> $parentPhpDocBlocks
* @return ReturnTag|Null
*/
private static function mergeReturnTags(?ReturnTag $returnTag, array $parents, array $parentPhpDocBlocks): ?ReturnTag
private static function mergeReturnTags(?ReturnTag $returnTag, ?ClassReflection $classReflection, array $parents, array $parentPhpDocBlocks): ?ReturnTag
{
if ($returnTag !== null) {
return $returnTag;
}

foreach ($parents as $i => $parent) {
$result = self::mergeOneParentReturnTag($returnTag, $parent, $parentPhpDocBlocks[$i]);
$result = self::mergeOneParentReturnTag($returnTag, $classReflection, $parent, $parentPhpDocBlocks[$i]);
if ($result === null) {
continue;
}
Expand All @@ -815,7 +828,7 @@ private static function mergeReturnTags(?ReturnTag $returnTag, array $parents, a
return null;
}

private static function mergeOneParentReturnTag(?ReturnTag $returnTag, self $parent, PhpDocBlock $phpDocBlock): ?ReturnTag
private static function mergeOneParentReturnTag(?ReturnTag $returnTag, ?ClassReflection $classReflection, self $parent, PhpDocBlock $phpDocBlock): ?ReturnTag
{
$parentReturnTag = $parent->getReturnTag();
if ($parentReturnTag === null) {
Expand All @@ -824,6 +837,21 @@ private static function mergeOneParentReturnTag(?ReturnTag $returnTag, self $par

$parentType = $parentReturnTag->getType();

if ($classReflection !== null) {
$parentType = TypeTraverser::map(
$parentType,
static function (Type $type, callable $traverse) use ($classReflection): Type {
if ($type instanceof StaticType) {
return $type->changeBaseClass($classReflection);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, I'd fix this the same way so 👍

I just hate adding new properties to this class but I didn't figure out a better solution. yet. Merging this.

}

return $traverse($type);
},
);

$parentReturnTag = $parentReturnTag->withType($parentType);
}

// Each parent would overwrite the previous one except if it returns a less specific type.
// Do not care for incompatible types as there is a separate rule for that.
if ($returnTag !== null && $parentType->isSuperTypeOf($returnTag->getType())->yes()) {
Expand Down
1 change: 1 addition & 0 deletions src/Type/FileTypeMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ private function createResolvedPhpDocBlock(string $phpDocKey, NameScope $nameSco
new TemplateTypeMap($phpDocTemplateTypes),
$templateTags,
$this->phpDocNodeResolver,
$this->reflectionProviderProvider->getReflectionProvider(),
);
$this->resolvedPhpDocBlockCacheCount++;

Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2378.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9985.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6294.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6462.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2580.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9753.php');

Expand Down
57 changes: 57 additions & 0 deletions tests/PHPStan/Analyser/data/bug-6462.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php declare(strict_types = 1);

namespace Bug6462;

use function PHPStan\Testing\assertType;

class Base
{
/**
* @return $this
*/
public function getThis(): self
{
return $this;
}
}

class Child extends Base
{
/**
* {@inheritDoc}
*/
public function getThis(): self
{
return $this;
}
}

class FixedChild extends Base
{
/**
* @return $this
*/
public function getThis(): self
{
return $this;
}
}

$base = new Base();
$child = new Child();
$fixedChild = new FixedChild();

assertType('Bug6462\Base', $base->getThis());
assertType('Bug6462\Child', $child->getThis());

if ($base instanceof \Traversable) {
assertType('Bug6462\Base&Traversable', $base->getThis());
}

if ($child instanceof \Traversable) {
assertType('Bug6462\Child&Traversable', $child->getThis());
}

if ($fixedChild instanceof \Traversable) {
assertType('Bug6462\FixedChild&Traversable', $fixedChild->getThis());
}
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -474,4 +474,19 @@ public function testBug10184(): void
$this->analyse([__DIR__ . '/data/bug-10184.php'], []);
}

public function testParentReturnTypeMergingFix(): void
{
if (PHP_VERSION_ID < 70400) {
$this->markTestSkipped('Test requires PHP 7.4.');
}

$this->reportMaybes = true;
$this->reportStatic = true;

$this->analyse([__DIR__ . '/data/bug-10208.php'], []);
janedbal marked this conversation as resolved.
Show resolved Hide resolved
$this->analyse([__DIR__ . '/data/bug-6462.php'], []);
$this->analyse([__DIR__ . '/data/bug-4396.php'], []);
$this->analyse([__DIR__ . '/data/bug-3580.php'], []);
}

}
24 changes: 24 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-10208.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php declare(strict_types = 1);

namespace Bug10208;

abstract class AbstractScope
{
/**
* @return $this
*/
abstract public function clear(): self;
}

class Condition extends AbstractScope
{
/** @var string|null */
public $key;

public function clear(): self
{
$this->key = null;

return $this;
}
}
32 changes: 32 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-3580.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);

namespace Bug3580;

interface TheBaseFoo {
/**
* @return static
*/
public function getClone(): self;
}

interface TheFoo extends TheBaseFoo {
}

abstract class BaseFoo implements TheBaseFoo {
public function getClone(): self {
return clone $this;
}
}

final class Foo extends BaseFoo implements TheFoo {
}

final class TheFooMaker {
public Foo $foo;

public function make(): TheFoo {
return $this->foo->getClone();
}
}


38 changes: 38 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-4396.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Bug4396;

interface TheInterface
{
/** @return static */
public static function fromString(string $value);
}

abstract class ClassC implements TheInterface
{
private string $value;

final private function __construct(string $value)
{
$this->value = $value;
}

final public static function fromString(string $value): self
{
return new static($value);
}
}

final class ClassB extends ClassC
{
}

final class ClassA
{
public function classB(): ClassB
{
return ClassB::fromString("any");
}
}
35 changes: 35 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-6462.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php declare(strict_types = 1);

namespace Bug6462;

interface ThisInterface {
/**
* @return $this
*/
public function t() : self;
}

class ThisImplementer implements ThisInterface
{
/**
* {@inheritdoc}
*/
public function t() : self {
return $this;
}
}


interface NonThisInterface {
public function t() : self;
}

class NonThisImplementer implements NonThisInterface
{
/**
* {@inheritdoc}
*/
public function t() : self {
return $this;
}
}