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
74 changes: 67 additions & 7 deletions src/Type/Generic/TemplateTypeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PHPStan\Type\NonAcceptingNeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;

final class TemplateTypeHelper
Expand Down Expand Up @@ -146,16 +147,75 @@

public static function generalizeInferredTemplateType(TemplateType $templateType, Type $type): Type
{
if (!$templateType->getVariance()->covariant()) {
$isArrayKey = $templateType->getBound()->describe(VerbosityLevel::precise()) === '(int|string)';
if ($type->isScalar()->yes() && $isArrayKey) {
$type = $type->generalize(GeneralizePrecision::templateArgument());
} elseif ($type->isConstantValue()->yes() && (!$templateType->getBound()->isScalar()->yes() || $isArrayKey)) {
$type = $type->generalize(GeneralizePrecision::templateArgument());
if ($templateType->getVariance()->covariant()) {
return $type;
}

$bound = $templateType->getBound();
$isArrayKey = $bound->describe(VerbosityLevel::precise()) === '(int|string)';
if ($bound->isScalar()->yes() && !$isArrayKey) {

Check warning on line 156 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ $bound = $templateType->getBound(); $isArrayKey = $bound->describe(VerbosityLevel::precise()) === '(int|string)'; - if ($bound->isScalar()->yes() && !$isArrayKey) { + if (!$bound->isScalar()->no() && !$isArrayKey) { return $type; }

Check warning on line 156 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ $bound = $templateType->getBound(); $isArrayKey = $bound->describe(VerbosityLevel::precise()) === '(int|string)'; - if ($bound->isScalar()->yes() && !$isArrayKey) { + if (!$bound->isScalar()->no() && !$isArrayKey) { return $type; }
return $type;
}

if ($type->isScalar()->yes() && $isArrayKey) {

Check warning on line 160 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ return $type; } - if ($type->isScalar()->yes() && $isArrayKey) { + if (!$type->isScalar()->no() && $isArrayKey) { $type = $type->generalize(GeneralizePrecision::templateArgument()); } elseif ($type->isConstantValue()->yes()) { $type = $type->generalize(GeneralizePrecision::templateArgument());

Check warning on line 160 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ return $type; } - if ($type->isScalar()->yes() && $isArrayKey) { + if (!$type->isScalar()->no() && $isArrayKey) { $type = $type->generalize(GeneralizePrecision::templateArgument()); } elseif ($type->isConstantValue()->yes()) { $type = $type->generalize(GeneralizePrecision::templateArgument());
$type = $type->generalize(GeneralizePrecision::templateArgument());
} elseif ($type->isConstantValue()->yes()) {

Check warning on line 162 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ if ($type->isScalar()->yes() && $isArrayKey) { $type = $type->generalize(GeneralizePrecision::templateArgument()); - } elseif ($type->isConstantValue()->yes()) { + } elseif (!$type->isConstantValue()->no()) { $type = $type->generalize(GeneralizePrecision::templateArgument()); }

Check warning on line 162 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ if ($type->isScalar()->yes() && $isArrayKey) { $type = $type->generalize(GeneralizePrecision::templateArgument()); - } elseif ($type->isConstantValue()->yes()) { + } elseif (!$type->isConstantValue()->no()) { $type = $type->generalize(GeneralizePrecision::templateArgument()); }
$type = $type->generalize(GeneralizePrecision::templateArgument());
}

return self::widenToBoundType($bound, $type);
}

/**
* An invariant template type argument that merely refines one of the bound's
* alternatives is unusable - Foo<array{string}> is not accepted by Foo<list<string>>.
* Such a type is widened to the bound alternative it refines.
*/
private static function widenToBoundType(Type $bound, Type $type): Type
{
$boundTypes = $bound instanceof UnionType ? $bound->getTypes() : [$bound];

$widenedType = null;
foreach ($boundTypes as $boundType) {
if (!self::onlyRefinesType($boundType, $type)) {
continue;
}

if ($type->isSuperTypeOf($boundType)->yes()) {
// the type is already as general as the bound alternative
return $type;
}

if ($widenedType !== null) {
return $type;
}

$widenedType = $boundType;
}

return $widenedType ?? $type;
}

/**
* Does $type say the same thing as $superType, only with more precision
* (accessory types, array shapes, literal values)?
*/
private static function onlyRefinesType(Type $superType, Type $type): bool
{
if (!$superType->isSuperTypeOf($type)->yes()) {

Check warning on line 205 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ */ private static function onlyRefinesType(Type $superType, Type $type): bool { - if (!$superType->isSuperTypeOf($type)->yes()) { + if ($superType->isSuperTypeOf($type)->no()) { return false; }
return false;
}

// arrays refine the bound with their shape, so they're compared key type to key type
// and value type to value type instead. Object types are excluded to not lose the class.
// An empty array has never key and value types, which say more than any bound does,
// so array{} is never widened - the class author may well have written Foo<array{}>.
if ($type->isArray()->yes() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) {

Check warning on line 213 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ // and value type to value type instead. Object types are excluded to not lose the class. // An empty array has never key and value types, which say more than any bound does, // so array{} is never widened - the class author may well have written Foo<array{}>. - if ($type->isArray()->yes() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) { + if ($type->isArray()->yes() && !$superType->isIterable()->no() && $superType->getObjectClassNames() === []) { return self::onlyRefinesType($superType->getIterableKeyType(), $type->getIterableKeyType()) && self::onlyRefinesType($superType->getIterableValueType(), $type->getIterableValueType()); }

Check warning on line 213 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ // and value type to value type instead. Object types are excluded to not lose the class. // An empty array has never key and value types, which say more than any bound does, // so array{} is never widened - the class author may well have written Foo<array{}>. - if ($type->isArray()->yes() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) { + if (!$type->isArray()->no() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) { return self::onlyRefinesType($superType->getIterableKeyType(), $type->getIterableKeyType()) && self::onlyRefinesType($superType->getIterableValueType(), $type->getIterableValueType()); }

Check warning on line 213 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ // and value type to value type instead. Object types are excluded to not lose the class. // An empty array has never key and value types, which say more than any bound does, // so array{} is never widened - the class author may well have written Foo<array{}>. - if ($type->isArray()->yes() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) { + if (!$type->isArray()->no() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) { return self::onlyRefinesType($superType->getIterableKeyType(), $type->getIterableKeyType()) && self::onlyRefinesType($superType->getIterableValueType(), $type->getIterableValueType()); }

Check warning on line 213 in src/Type/Generic/TemplateTypeHelper.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ // and value type to value type instead. Object types are excluded to not lose the class. // An empty array has never key and value types, which say more than any bound does, // so array{} is never widened - the class author may well have written Foo<array{}>. - if ($type->isArray()->yes() && $superType->isIterable()->yes() && $superType->getObjectClassNames() === []) { + if ($type->isArray()->yes() && !$superType->isIterable()->no() && $superType->getObjectClassNames() === []) { return self::onlyRefinesType($superType->getIterableKeyType(), $type->getIterableKeyType()) && self::onlyRefinesType($superType->getIterableValueType(), $type->getIterableValueType()); }
return self::onlyRefinesType($superType->getIterableKeyType(), $type->getIterableKeyType())
&& self::onlyRefinesType($superType->getIterableValueType(), $type->getIterableValueType());
}

return $type;
return $type->generalize(GeneralizePrecision::lessSpecific())->isSuperTypeOf($superType)->yes();
}

}
225 changes: 225 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-15027.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
<?php // lint >= 8.0

namespace Bug15027;

use function PHPStan\Testing\assertType;

/**
* @template Value of string|list<string>
*/
final class LanguageProperty
{
/** @var Value */
public $value;

/**
* @param Value $value
*/
public function __construct($value)
{
$this->value = $value;
}

/**
* @template T of string|list<string>
* @param T $value
* @return self<T>
*/
public static function create($value): self
{
return new self($value);
}
}

/**
* @template T
*/
final class Unbounded
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of array
*/
final class BoundToArray
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template TData of array = array<array-key, mixed>
*/
final class DefaultedArgument
{
/** @param TData $data */
public function __construct(public array $data = [], public ?string $alias = null)
{
}
}

/**
* @template T of array<string, mixed>
*/
final class BoundToMixedMap
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of array<string, string>
*/
final class BoundToStringMap
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of list<string>
*/
final class BoundToList
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of string|list<list<string>>
*/
final class BoundToNestedList
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of iterable<int, string>
*/
final class BoundToIterable
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of int|list<int>
*/
final class BoundToIntOrList
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of \DateTimeInterface|string
*/
final class BoundToObjectOrString
{
/** @param T $value */
public function __construct(public $value)
{
}
}

/**
* @template T of \Traversable
*/
final class BoundToTraversable
{
/** @param T $value */
public function __construct(public $value)
{
}
}

function doFoo(): string
{
return 'hallo';
}

/**
* @template T of string|list<string>
* @param T $value
* @return LanguageProperty<T>
*/
function createLanguageProperty($value): LanguageProperty
{
return new LanguageProperty($value);
}

/**
* @param non-empty-list<string> $nonEmptyList
* @param numeric-string $numericString
* @param int<1, 5> $intRange
* @param array<string, string> $stringMap
*/
function test(
string $s,
array $nonEmptyList,
string $numericString,
int $intRange,
array $stringMap,
\DateTimeImmutable $date,
\ArrayIterator $iterator
): void
{
assertType('Bug15027\LanguageProperty<list<string>>', new LanguageProperty(['abc']));
assertType('Bug15027\LanguageProperty<list<string>>', new LanguageProperty([$s]));
assertType('Bug15027\LanguageProperty<list<string>>', new LanguageProperty($nonEmptyList));
assertType('Bug15027\LanguageProperty<string>', new LanguageProperty('abc'));
assertType('Bug15027\LanguageProperty<string>', new LanguageProperty('abc' . doFoo()));
assertType('Bug15027\LanguageProperty<string>', new LanguageProperty($numericString));

// the same widening applies when the generic type is created by a factory
assertType('Bug15027\LanguageProperty<list<string>>', LanguageProperty::create(['abc']));
assertType('Bug15027\LanguageProperty<string>', LanguageProperty::create('abc' . doFoo()));
assertType('Bug15027\LanguageProperty<list<string>>', createLanguageProperty(['abc']));
assertType('Bug15027\LanguageProperty<string>', createLanguageProperty('abc' . doFoo()));

assertType('Bug15027\BoundToList<list<string>>', new BoundToList(['abc']));
assertType('Bug15027\BoundToNestedList<list<list<string>>>', new BoundToNestedList([['abc']]));
assertType('Bug15027\BoundToIterable<iterable<int, string>>', new BoundToIterable(['abc']));
assertType('Bug15027\BoundToIntOrList<int>', new BoundToIntOrList($intRange));
assertType('Bug15027\BoundToIntOrList<list<int>>', new BoundToIntOrList([1, 2]));
assertType('Bug15027\BoundToStringMap<array<string, string>>', new BoundToStringMap(['a' => 'b']));
assertType('Bug15027\BoundToStringMap<array<string, string>>', new BoundToStringMap($stringMap));

// bounds that say more than the argument does keep the precise type
assertType('Bug15027\Unbounded<array{string}>', new Unbounded(['abc']));
assertType('Bug15027\Unbounded<string>', new Unbounded('abc'));
assertType('Bug15027\BoundToArray<array{string}>', new BoundToArray(['abc']));
assertType('Bug15027\BoundToMixedMap<array{foo: string, bar: int}>', new BoundToMixedMap(['foo' => 'abc', 'bar' => 1]));

// an empty array says more than any array bound does, so it is not widened either -
// both when written explicitly and when it comes from an optional parameter's default value
assertType('Bug15027\LanguageProperty<array{}>', new LanguageProperty([]));
assertType('Bug15027\BoundToList<array{}>', new BoundToList([]));
assertType('Bug15027\DefaultedArgument<array{}>', new DefaultedArgument());
assertType('Bug15027\DefaultedArgument<array{}>', new DefaultedArgument([]));
assertType('Bug15027\DefaultedArgument<array{a: int}>', new DefaultedArgument(['a' => 1]));

// class precision is not lost
assertType('Bug15027\BoundToObjectOrString<DateTimeImmutable>', new BoundToObjectOrString($date));
assertType('Bug15027\BoundToObjectOrString<string>', new BoundToObjectOrString('abc' . doFoo()));
assertType('Bug15027\BoundToTraversable<ArrayIterator>', new BoundToTraversable($iterator));
}
Original file line number Diff line number Diff line change
Expand Up @@ -1067,4 +1067,9 @@ public function testBug10749(): void
$this->analyse([__DIR__ . '/data/bug-10749.php'], []);
}

public function testBug15027(): void
{
$this->analyse([__DIR__ . '/data/bug-15027.php'], []);
}

}
43 changes: 43 additions & 0 deletions tests/PHPStan/Rules/Properties/data/bug-15027.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Bug15027Property;

/**
* @template Value of string|list<string>
*/
final class LanguageProperty
{
/** @var Value */
public $value;

/**
* @param Value $value
*/
public function __construct($value)
{
$this->value = $value;
}
}

class Holder
{

/** @var LanguageProperty<list<string>>|null */
public $lp = null;

/** @var LanguageProperty<string>|null */
public static $lps = null;

}

function doFoo(): string
{
return 'hallo';
}

function test(): void
{
$h = new Holder();
$h->lp = new LanguageProperty(['abc']);
Holder::$lps = new LanguageProperty('abc' . doFoo());
}
Loading