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
24 changes: 15 additions & 9 deletions src/Analyser/ExprHandler/Helper/IdenticalNarrowingHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,7 @@ private function specifyEqualAgainstConstantSide(
if (in_array($funcName, ['gettype', 'get_class', 'get_debug_type'], true) && $constantType->isString()->yes()) {
return $this->specifyIdentical($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
if ($context->true() && $funcName === 'preg_match' && (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()) {
if ($value === 1 && $this->isOnlyTruthyResultOne($subjectResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted))) {
return $this->specifyIdentical($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
}
Expand All @@ -835,6 +835,15 @@ private function specifyEqualAgainstConstantSide(
return false;
}

private function isOnlyTruthyResultOne(Type $callType): bool
{
if ($callType->toBoolean()->isFalse()->yes()) {
return false;
}

return TypeCombinator::remove($callType, new ConstantIntegerType(1))->toBoolean()->isFalse()->yes();
}

/**
* The function-family compositions, shared by the literal and the
* TYPE-based constant sides: a family answer, null to fall back to the
Expand All @@ -858,16 +867,13 @@ private function specifyFuncCallFamilies(
return false;
}

// preg_match(...) === 1 is the call's own truthy narrowing - the
// type-specifying extensions narrow the by-ref \$matches argument
// f(...) === 1 narrows like the truthy call when 1 is its only truthy result
if (
$call->name->toLowerString() === 'preg_match'
$context->true()
&& (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()
&& $this->isOnlyTruthyResultOne($subjectResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted))
) {
if ($context->true() && (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()) {
return $subjectResult->getSpecifiedTypesForScope($evaluationScope, $context);
}

// other constants and contexts only pin the call below
return $subjectResult->getSpecifiedTypesForScope($evaluationScope, $context);
}

// a trimmed string that is not '' was a non-empty string already
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
services:
-
class: PHPStan\Tests\MatchesIntFunctionTypeSpecifyingExtension
tags:
- phpstan.typeSpecifier.functionTypeSpecifyingExtension
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php declare(strict_types = 1);

namespace PHPStan\Analyser;

use PHPStan\Testing\TypeInferenceTestCase;
use PHPUnit\Framework\Attributes\RequiresPhp;

class TypeSpecifyingExtensionIdenticalFunctionCallTest extends TypeInferenceTestCase
{

#[RequiresPhp('>= 8.0.0')]
public function testAsserts(): void
{
// gathered here instead of in a data provider, so that mutation testing sees the coverage
foreach (self::gatherAssertTypes(__DIR__ . '/data/type-specifying-extensions-identical-function-call.php') as $args) {
$this->assertFileAsserts(...$args);
}
}

public static function getAdditionalConfigFiles(): array
{
return [
__DIR__ . '/TypeSpecifyingExtensionIdenticalFunctionCall.neon',
];
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?php // lint >= 8.0

namespace IdenticalFunctionCallExtension;

use function PHPStan\Testing\assertType;

/** @return 0|1 */
function matchesInt(mixed $value): int
{
return is_int($value) ? 1 : 0;
}

/** @return 0|1|false */
function matchesIntOrFails(mixed $value): int|false
{
return is_int($value) ? 1 : 0;
}

function matchesIntOrFalse(mixed $value): int|false
{
return is_int($value) ? 1 : false;
}

/** @return 0 */
function neverMatches(mixed $value): int
{
return 0;
}

function truthy(mixed $value): void
{
if (matchesInt($value)) {
assertType('int', $value);
}
}

function identicalToOne(mixed $value): void
{
if (matchesInt($value) === 1) {
assertType('int', $value);
}
if (1 === matchesInt($value)) {
assertType('int', $value);
}
if (matchesIntOrFails($value) === 1) {
assertType('int', $value);
}
}

function looselyEqualToOne(mixed $value): void
{
if (matchesInt($value) == 1) {
assertType('int', $value);
}
if (1 == matchesIntOrFails($value)) {
assertType('int', $value);
}
}

function notIdenticalToOne(mixed $value): void
{
if (matchesInt($value) !== 1) {
return;
}
assertType('int', $value);
}

function notIdenticalToOneIsTrue(mixed $value): void
{
if ((matchesInt($value) !== 1) === true) {
assertType('mixed', $value);
}
if ((matchesInt($value) != 1) === true) {
assertType('mixed', $value);
}
}

function otherConstants(mixed $value): void
{
if (matchesInt($value) === 0) {
assertType('mixed', $value);
}
if (matchesIntOrFalse($value) === 1) {
assertType('mixed', $value);
}
if (matchesIntOrFalse($value) == 1) {
assertType('mixed', $value);
}
if (matchesInt($value) === 2) {
assertType('mixed', $value);
}
if (neverMatches($value) === 1) {
assertType('mixed', $value);
}
if (neverMatches($value) == 1) {
assertType('mixed', $value);
}
}

function looselyEqualToZero(mixed $value): void
{
if (matchesIntOrFails($value) == 0) {
assertType('0|false', matchesIntOrFails($value));
}
}

function constantsIncludingOne(mixed $value, bool $flag): void
{
$oneOrTwo = $flag ? 1 : 2;
if (matchesInt($value) === $oneOrTwo) {
assertType('mixed', $value);
}
if (matchesInt($value) == $oneOrTwo) {
assertType('mixed', $value);
}
}

/**
* @return 0|1
* @phpstan-assert-if-true int $value
*/
function isIntish(mixed $value): int
{
return is_int($value) ? 1 : 0;
}

function assertIfTrue(mixed $value): void
{
if (isIntish($value) === 1) {
assertType('int', $value);
}
if (isIntish($value) == 1) {
assertType('int', $value);
}
}
36 changes: 36 additions & 0 deletions tests/PHPStan/Tests/MatchesIntFunctionTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php declare(strict_types = 1);

namespace PHPStan\Tests;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
use PHPStan\Analyser\TypeSpecifierAwareExtension;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\FunctionTypeSpecifyingExtension;
use PHPStan\Type\IntegerType;
use function in_array;

class MatchesIntFunctionTypeSpecifyingExtension implements FunctionTypeSpecifyingExtension, TypeSpecifierAwareExtension
{

private TypeSpecifier $typeSpecifier;

public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
{
$this->typeSpecifier = $typeSpecifier;
}

public function isFunctionSupported(FunctionReflection $functionReflection, FuncCall $node, TypeSpecifierContext $context): bool
{
return in_array($functionReflection->getName(), ['IdenticalFunctionCallExtension\\matchesInt', 'IdenticalFunctionCallExtension\\matchesIntOrFails', 'IdenticalFunctionCallExtension\\matchesIntOrFalse', 'IdenticalFunctionCallExtension\\neverMatches'], true) && !$context->null();
}

public function specifyTypes(FunctionReflection $functionReflection, FuncCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
{
return $this->typeSpecifier->create($node->getArgs()[0]->value, new IntegerType(), $context, $scope);
}

}
56 changes: 40 additions & 16 deletions turbo-ext/src/IdenticalNarrowingHelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,28 @@ zv::Val constantStringValue(zval *constantString)
return true;
}

/* the twin's isOnlyTruthyResultOne(): $callType can be truthy and
* removing 1 leaves only falsy results; false = pending exception */
[[nodiscard]] bool isOnlyTruthyResultOne(zval *callType, bool &out)
{
out = false;
zv::Val callBool = typeCall(callType, "toBoolean", PT_LC("toboolean"));
if (UNEXPECTED(callBool.isUndef())) return false;
zend_long alwaysFalse = PT_INH_IS_FALSE(callBool.raw());
if (UNEXPECTED(alwaysFalse < 0)) return false;
if (alwaysFalse == PT_TRI_YES) return true;
zv::Val one = newConstantInteger(1);
if (UNEXPECTED(one.isUndef())) return false;
zv::Val remaining = pt_type_combinator_remove(callType, one.raw());
if (UNEXPECTED(remaining.isUndef())) return false;
zv::Val remainingBool = typeCall(remaining.raw(), "toBoolean", PT_LC("toboolean"));
if (UNEXPECTED(remainingBool.isUndef())) return false;
zend_long isFalse = PT_INH_IS_FALSE(remainingBool.raw());
if (UNEXPECTED(isFalse < 0)) return false;
out = isFalse == PT_TRI_YES;
return true;
}

/* IntegerRangeType::fromInterval($min, $max)->isSuperTypeOf($type)->yes() */
[[nodiscard]] bool rangeContains(phpstanturbo::NullableLong min, phpstanturbo::NullableLong max, zval *type, bool &out)
{
Expand Down Expand Up @@ -1370,12 +1392,12 @@ class IdenticalNarrowingHelper
if (UNEXPECTED(isString < 0)) return zv::Val();
if (isString == PT_TRI_YES) return specifyIdentical(nodeScopeResolver, left, right, leftResult, rightResult, context, evaluationScope, leftArgResult, rightArgResult, identicalTypeCallback);
}
bool isTrue;
if (UNEXPECTED(!ctxTrue(context, isTrue))) return zv::Val();
if (isTrue && funcName != NULL && lowerNameIs(funcName, "preg_match")) {
bool one;
if (UNEXPECTED(!constantIntegerContains(1, constantType, one))) return zv::Val();
if (one) return specifyIdentical(nodeScopeResolver, left, right, leftResult, rightResult, context, evaluationScope, leftArgResult, rightArgResult, identicalTypeCallback);
if (Z_TYPE_P(value) == IS_LONG && Z_LVAL_P(value) == 1) {
zv::Val callType = typeOnScope(subjectResult, evaluationScope);
if (UNEXPECTED(callType.isUndef())) return zv::Val();
bool onlyTruthyOne;
if (UNEXPECTED(!isOnlyTruthyResultOne(callType.raw(), onlyTruthyOne))) return zv::Val();
if (onlyTruthyOne) return specifyIdentical(nodeScopeResolver, left, right, leftResult, rightResult, context, evaluationScope, leftArgResult, rightArgResult, identicalTypeCallback);
}
}
}
Expand Down Expand Up @@ -1437,17 +1459,19 @@ class IdenticalNarrowingHelper
zend_string *name = identifierString(nameOf(call));
if (UNEXPECTED(name == NULL)) return zv::Val::boolean(false);

// preg_match(...) === 1 is the call's own truthy narrowing
if (lowerNameIs(name, "preg_match")) {
bool isTrue;
if (UNEXPECTED(!ctxTrue(context, isTrue))) return zv::Val();
if (isTrue) {
bool one;
if (UNEXPECTED(!constantIntegerContains(1, constantType, one))) return zv::Val();
if (one) return pt_expression_result_get_specified_types_for_scope(subjectResult, evaluationScope, context);
// f(...) === 1 narrows like the truthy call when 1 is its only truthy result
bool isTrue;
if (UNEXPECTED(!ctxTrue(context, isTrue))) return zv::Val();
if (isTrue) {
bool one;
if (UNEXPECTED(!constantIntegerContains(1, constantType, one))) return zv::Val();
if (one) {
zv::Val callType = typeOnScope(subjectResult, evaluationScope);
if (UNEXPECTED(callType.isUndef())) return zv::Val();
bool onlyTruthyOne;
if (UNEXPECTED(!isOnlyTruthyResultOne(callType.raw(), onlyTruthyOne))) return zv::Val();
if (onlyTruthyOne) return pt_expression_result_get_specified_types_for_scope(subjectResult, evaluationScope, context);
}

// other constants and contexts only pin the call below
}

// a trimmed string that is not '' was a non-empty string already
Expand Down
Loading
Loading