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

in_array returns false in strict mode if types are incompatibles #7141

Merged
merged 1 commit into from Dec 12, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Psalm/Internal/Provider/FunctionReturnTypeProvider.php
Expand Up @@ -75,6 +75,7 @@ public function __construct()
$this->registerClass(ReturnTypeProvider\MinMaxReturnTypeProvider::class);
$this->registerClass(ReturnTypeProvider\TriggerErrorReturnTypeProvider::class);
$this->registerClass(ReturnTypeProvider\RandReturnTypeProvider::class);
$this->registerClass(ReturnTypeProvider\InArrayReturnTypeProvider::class);
}

/**
Expand Down
@@ -0,0 +1,82 @@
<?php
namespace Psalm\Internal\Provider\ReturnTypeProvider;

use Psalm\Internal\Type\Comparator\UnionTypeComparator;
use Psalm\Plugin\EventHandler\Event\FunctionReturnTypeProviderEvent;
use Psalm\Plugin\EventHandler\FunctionReturnTypeProviderInterface;
use Psalm\Type;
use Psalm\Type\Atomic\TArray;
use Psalm\Type\Atomic\TKeyedArray;
use Psalm\Type\Atomic\TList;

class InArrayReturnTypeProvider implements FunctionReturnTypeProviderInterface
{
/**
* @return array<lowercase-string>
*/
public static function getFunctionIds(): array
{
return ['in_array'];
}

public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $event): Type\Union
{
$call_args = $event->getCallArgs();
$bool = Type::getBool();

if (!isset($call_args[0]) || !isset($call_args[1])) {
return $bool;
}

$needle_type = $event->getStatementsSource()->getNodeTypeProvider()->getType($call_args[0]->value);
$haystack_type = $event->getStatementsSource()->getNodeTypeProvider()->getType($call_args[1]->value);

if ($needle_type === null || $haystack_type === null) {
return $bool;
}

$false = Type::getFalse();
$false->from_docblock = $bool->from_docblock = $needle_type->from_docblock || $haystack_type->from_docblock;

if (!isset($call_args[2])) {
return $bool;
}

$strict_type = $event->getStatementsSource()->getNodeTypeProvider()->getType($call_args[2]->value);

if ($strict_type === null || !$strict_type->isTrue()) {
return $bool;
}

/**
* @var TKeyedArray|TArray|TList|null
*/
$array_arg_type = ($types = $haystack_type->getAtomicTypes()) && isset($types['array'])
? $types['array']
: null;

if ($array_arg_type instanceof TKeyedArray) {
$array_arg_type = $array_arg_type->getGenericArrayType();
}

if ($array_arg_type instanceof TList) {
$array_arg_type = new TArray([Type::getInt(), $array_arg_type->type_param]);
}

if (!$array_arg_type instanceof TArray) {
return $bool;
}

$haystack_item_type = $array_arg_type->type_params[1];

if (UnionTypeComparator::canExpressionTypesBeIdentical(
$event->getStatementsSource()->getCodebase(),
$needle_type,
$haystack_item_type
)) {
return $bool;
}

return $false;
}
}
5 changes: 0 additions & 5 deletions src/Psalm/Internal/Type/TypeCombiner.php
Expand Up @@ -63,7 +63,6 @@
use function array_values;
use function count;
use function get_class;
use function in_array;
use function is_int;
use function is_numeric;
use function strpos;
Expand Down Expand Up @@ -93,10 +92,6 @@ public static function combine(
bool $allow_mixed_union = true,
int $literal_limit = 500
): Union {
if (in_array(null, $types, true)) {
mathroc marked this conversation as resolved.
Show resolved Hide resolved
return Type::getMixed();
}

if (count($types) === 1) {
$union_type = new Union([$types[0]]);

Expand Down
66 changes: 66 additions & 0 deletions tests/ReturnTypeProvider/InArrayTest.php
@@ -0,0 +1,66 @@
<?php

namespace Psalm\Tests\ReturnTypeProvider;

use Psalm\Tests\TestCase;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;

class InArrayTest extends TestCase
{
use ValidCodeAnalysisTestTrait;

public function providerValidCodeParse(): iterable
{
yield 'inArrayNonStrictCallReturnsBoolWhenTypesAreCompatible' => [
'<?php
/**
* @return string[]
*/
function f(): array {
return ["1"];
}
$ret = in_array("1", f());
',
['$ret' => 'bool'],
];

yield 'inArrayNonStrictCallReturnsBoolWhenTypesAreIncompatible' => [
'<?php
/**
* @return string[]
*/
function f(): array {
return ["1"];
}
$ret = in_array(1, f());
',
['$ret' => 'bool'],
];

yield 'inArrayStrictCallReturnsFalseWhenTypesAreIncompatible' => [
'<?php
/**
* @return string[]
*/
function f(): array {
return ["1"];
}
$ret = in_array(1, f(), true);
',
['$ret' => 'false'],
];

yield 'inArrayStrictCallReturnsBoolWhenTypesAreCompatible' => [
'<?php
/**
* @return string[]
*/
function f(): array {
return ["1"];
}
$ret = in_array("1", f(), true);
',
['$ret' => 'bool'],
];
}
}
47 changes: 7 additions & 40 deletions tests/TypeReconciliation/InArrayTest.php
Expand Up @@ -122,7 +122,7 @@ function assertInArray($x, $y) {
return $x;
}',
'assertions' => [],
'error_level' => ['RedundantConditionGivenDocblockType'],
'error_level' => ['RedundantConditionGivenDocblockType', 'DocblockTypeContradiction'],
],
'assertNegatedInArrayOfNotIntersectingTypeReturnsOriginalType' => [
'<?php
Expand Down Expand Up @@ -312,7 +312,7 @@ function assertInArray($x, $y) {

return $x;
}',
'error_message' => 'RedundantConditionGivenDocblockType - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:29 - Docblock-defined type int for $x is never string',
'error_message' => 'DocblockTypeContradiction - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:29 - Operand of type false is always false',
],
'assertNegatedInArrayOfNotIntersectingTypeTriggersRedundantCondition' => [
'<?php
Expand All @@ -328,9 +328,9 @@ function assertInArray($x, $y) {

throw new \Exception();
}',
'error_message' => 'RedundantConditionGivenDocblockType - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:30 - Docblock-defined type int for $x is never string',
'error_message' => 'RedundantConditionGivenDocblockType - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:29 - Operand of type true is always true',
],
'assertInArrayOfNotIntersectingTypeTriggersRedundantCondition' => [
'assertInArrayOfNotIntersectingTypeTriggersDocblockTypeContradiction' => [
'<?php
/**
* @param int $x
Expand All @@ -344,9 +344,9 @@ function assertInArray($x, $y) {

throw new \Exception();
}',
'error_message' => 'RedundantConditionGivenDocblockType - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:29 - Docblock-defined type int for $x is never string',
'error_message' => 'DocblockTypeContradiction - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:29 - Operand of type false is always false',
],
'assertInArrayOfNotIntersectingTypeReturnsTriggersMixedReturnStatement' => [
'assertInArrayOfNotIntersectingTypeReturnsTriggersDocblockTypeContradiction' => [
'<?php
/**
* @param int $x
Expand All @@ -360,42 +360,9 @@ function assertInArray($x, $y) {

throw new \Exception();
}',
'error_message' => 'MixedReturnStatement - src' . DIRECTORY_SEPARATOR . 'somefile.php:9:36 - Could not infer a return type',
'error_message' => 'DocblockTypeContradiction - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:29 - Operand of type false is always false',
'error_levels' => ['RedundantConditionGivenDocblockType'],
],
'assertNegatedInArrayOfNotIntersectingTypeTriggersTypeContradiction' => [
'<?php
/**
* @param int $x
* @param list<string> $y
* @return string
*/
function assertInArray($x, $y) {
if (!in_array($x, $y, true)) {
throw new \Exception();
}

return $x;
}',
'error_message' => 'RedundantConditionGivenDocblockType - src' . DIRECTORY_SEPARATOR . 'somefile.php:8:30 - Docblock-defined type int for $x is never string',
],
'assertNegatedInArrayOfNotIntersectingTypeTriggersMixedReturnStatement' => [
Copy link
Contributor Author

Choose a reason for hiding this comment

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

would become the same as assertNegatedInArrayOfNotIntersectingTypeTriggersRedundantCondition L317

'<?php
/**
* @param int $x
* @param list<string> $y
* @return string
*/
function assertInArray($x, $y) {
if (!in_array($x, $y, true)) {
throw new \Exception();
}

return $x;
}',
'error_message' => 'MixedReturnStatement - src' . DIRECTORY_SEPARATOR . 'somefile.php:12:32 - Could not infer a return type',
'error_level' => ['RedundantConditionGivenDocblockType'],
],
'inArrayDetectType' => [
'<?php
function x($foo, string $bar): void {
Expand Down