Skip to content

Improve the return type of array_map() for constant arrays #3156

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

Draft
wants to merge 3 commits into
base: 1.12.x
Choose a base branch
from
Draft
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
39 changes: 30 additions & 9 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@
use function is_string;
use function ltrim;
use function md5;
use function preg_match;
use function sprintf;
use function str_starts_with;
use function strlen;
Expand Down Expand Up @@ -2224,25 +2225,45 @@
}

if ($node instanceof FuncCall) {
if ($node->name instanceof Expr) {
$functionName = null;

Check failure on line 2228 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.2, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2228 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.2, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.
if ($node->name instanceof Name) {
$functionName = $node->name;
} elseif ($node->name instanceof Expr) {
$calledOnType = $this->getType($node->name);
if ($calledOnType->isCallable()->no()) {
return new ErrorType();
}

return ParametersAcceptorSelector::selectFromArgs(
$this,
$node->getArgs(),
$calledOnType->getCallableParametersAcceptors($this),
null,
)->getReturnType();
if ($node->name instanceof String_) {
/** @var non-empty-string $name */
$name = $node->name->value;
$functionName = new Name($name);
} elseif ($node->name instanceof FuncCall && $node->name->isFirstClassCallable() &&
$node->name->getAttribute('phpstan_cache_printer') !== null &&
preg_match('/\A(?<name>\\\\?[^()]+)\(...\)\z/', $node->name->getAttribute('phpstan_cache_printer'), $m) === 1
) {
/** @var non-falsy-string $name */
$name = $m['name'];
$functionName = new Name($name);
} else {
return ParametersAcceptorSelector::selectFromArgs(
$this,
$node->getArgs(),
$calledOnType->getCallableParametersAcceptors($this),
null,
)->getReturnType();
}
}

if ($functionName === null) {

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.4)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.2)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.3)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan with result cache (8.1)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2258 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.
throw new ShouldNotHappenException();
}

if (!$this->reflectionProvider->hasFunction($node->name, $this)) {
if (!$this->reflectionProvider->hasFunction($functionName, $this)) {
return new ErrorType();
}

$functionReflection = $this->reflectionProvider->getFunction($node->name, $this);
$functionReflection = $this->reflectionProvider->getFunction($functionName, $this);
if ($this->nativeTypesPromoted) {
return ParametersAcceptorSelector::combineAcceptors($functionReflection->getVariants())->getNativeReturnType();
}
Expand Down Expand Up @@ -2285,7 +2306,7 @@

return new MixedType();
}

Check failure on line 2309 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2309 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.
private function getNullsafeShortCircuitingType(Expr $expr, Type $type): Type
{
if ($expr instanceof Expr\NullsafePropertyFetch || $expr instanceof Expr\NullsafeMethodCall) {
Expand Down Expand Up @@ -2419,7 +2440,7 @@

$nativeType = $propertyReflection->getNativeType();
if (!$nativeType instanceof MixedType) {
if (!$this->hasExpressionType($expr)->yes()) {

Check failure on line 2443 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.3, ubuntu-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.

Check failure on line 2443 in src/Analyser/MutatingScope.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.3, windows-latest)

Strict comparison using === between PhpParser\Node\Name and null will always evaluate to false.
if ($expr instanceof Node\Expr\PropertyFetch) {
return $this->issetCheckUndefined($expr->var);
}
Expand Down
12 changes: 11 additions & 1 deletion src/Type/Php/ArrayMapFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

namespace PHPStan\Type\Php;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Expr\TypeExpr;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
Expand Down Expand Up @@ -37,13 +41,15 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
$singleArrayArgument = !isset($functionCall->getArgs()[2]);
$callableType = $scope->getType($functionCall->getArgs()[0]->value);
$callableIsNull = $callableType->isNull()->yes();
$callback = null;

if ($callableType->isCallable()->yes()) {
$valueTypes = [new NeverType()];
foreach ($callableType->getCallableParametersAcceptors($scope) as $parametersAcceptor) {
$valueTypes[] = $parametersAcceptor->getReturnType();
}
$valueType = TypeCombinator::union(...$valueTypes);
$callback = $functionCall->getArgs()[0]->value;
} elseif ($callableIsNull) {
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
foreach (array_slice($functionCall->getArgs(), 1) as $index => $arg) {
Expand Down Expand Up @@ -73,7 +79,11 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
foreach ($constantArray->getKeyTypes() as $i => $keyType) {
$returnedArrayBuilder->setOffsetValueType(
$keyType,
$valueType,
$callback === null
? $valueType
: $scope->getType(new FuncCall($callback, [
new Arg(new TypeExpr($constantArray->getValueTypes()[$i])),
])),
$constantArray->isOptionalKey($i),
);
}
Expand Down
43 changes: 43 additions & 0 deletions tests/PHPStan/Analyser/nsrt/array-map-callable81.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace ArrayMapCallable81;

use function PHPStan\Testing\assertType;
use function strval as str;

class Foo
{
/**
* @template T of int
* @param T $n
* @return (T is 3 ? 'Fizz' : (T is 5 ? 'Buzz' : T))
*/
public static function fizzbuzz(int $n): int|string
{
return match ($n) {
3 => 'Fizz',
5 => 'Buzz',
default => $n,
};
}

public function doFoo(): void
{
$a = range(0, 1);

assertType("array{'0', '1'}", array_map('strval', $a));
assertType("array{'0', '1'}", array_map(strval(...), $a));
assertType("array{'0', '1'}", array_map(str(...), $a));
assertType("array{'0'|'1', '0'|'1'}", array_map(fn ($v) => strval($v), $a));
assertType("array{'0'|'1', '0'|'1'}", array_map(fn ($v) => (string)$v, $a));
}

public function doFizzBuzz(): void
{
assertType("array{1, 2, 'Fizz', 4, 'Buzz', 6}", array_map([__CLASS__, 'fizzbuzz'], range(1, 6)));
assertType("array{1, 2, 'Fizz', 4, 'Buzz', 6}", array_map([$this, 'fizzbuzz'], range(1, 6)));
assertType("array{1|'Buzz'|'Fizz', 2|'Buzz'|'Fizz', 3|'Buzz'|'Fizz', 4|'Buzz'|'Fizz', 5|'Buzz'|'Fizz', 6|'Buzz'|'Fizz'}", array_map(self::fizzbuzz(...), range(1, 6)));
assertType("array{1|'Buzz'|'Fizz', 2|'Buzz'|'Fizz', 3|'Buzz'|'Fizz', 4|'Buzz'|'Fizz', 5|'Buzz'|'Fizz', 6|'Buzz'|'Fizz'}", array_map($this->fizzbuzz(...), range(1, 6)));
}

}
Loading