Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/Analyser/ExprHandler/CoalesceHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,12 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
// the coalesce's own key is emitted alongside the left-side
// narrowing (createForExpr's double-key, like the nullsafe
// handlers) - consumers summing the checked expression's own
// entry (ImpossibleCheckTypeHelper) rely on it
return $this->defaultNarrowingHelper->createSubjectTypes($s, $expr->left, $condResult, $type, $context)
// entry (ImpossibleCheckTypeHelper) rely on it;
// a null left side would make the coalesce the right
// side, which the type rules out, so the left side is
// not null either
$leftType = $context->true() ? TypeCombinator::removeNull($type) : TypeCombinator::addNull($type);
return $this->defaultNarrowingHelper->createSubjectTypes($s, $expr->left, $condResult, $leftType, $context)
->unionWith($this->defaultNarrowingHelper->createSubjectTypes($s, $expr, null, $type, $context));
}
}
Expand Down
8 changes: 6 additions & 2 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ private function createForExpr(
}

$originalExpr = $expr;
$exprType = $type;
if (isset($containsNull) && !$containsNull) {
$expr = NullsafeOperatorHelper::getNullsafeShortcircuitedExpr($expr);
}
Expand All @@ -191,6 +192,9 @@ private function createForExpr(
|| ($context->false() && $type->isSuperTypeOf($scope->getType($expr->right))->yes())
) {
$expr = $expr->left;
// a null left side would make the coalesce the right side,
// which the type rules out, so the left side is not null either
$exprType = $context->true() ? TypeCombinator::removeNull($type) : TypeCombinator::addNull($type);
}
}

Expand All @@ -214,15 +218,15 @@ private function createForExpr(
$sureNotTypes = [];
if ($context->false()) {
$exprString = $this->exprPrinter->printExpr($expr);
$sureNotTypes[$exprString] = [$expr, $type];
$sureNotTypes[$exprString] = [$expr, $exprType];

if ($expr !== $originalExpr) {
$originalExprString = $this->exprPrinter->printExpr($originalExpr);
$sureNotTypes[$originalExprString] = [$originalExpr, $type];
}
} elseif ($context->true()) {
$exprString = $this->exprPrinter->printExpr($expr);
$sureTypes[$exprString] = [$expr, $type];
$sureTypes[$exprString] = [$expr, $exprType];

if ($expr !== $originalExpr) {
$originalExprString = $this->exprPrinter->printExpr($originalExpr);
Expand Down
39 changes: 39 additions & 0 deletions tests/PHPStan/Analyser/TypeSpecifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use PHPStan\Type\ArrayType;
use PHPStan\Type\ClassStringType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\FloatType;
use PHPStan\Type\Generic\GenericClassStringType;
use PHPStan\Type\IntegerType;
Expand All @@ -35,6 +36,7 @@
use PHPStan\Type\ObjectType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;
Expand Down Expand Up @@ -1383,6 +1385,43 @@ public static function dataCondition(): iterable
];
}

/**
* @param array<string, string> $expectedResult
*/
#[DataProvider('dataCreateForCoalesce')]
public function testCreateForCoalesce(Expr\BinaryOp\Coalesce $expr, Type $type, TypeSpecifierContext $context, array $expectedResult): void
{
$specifiedTypes = $this->typeSpecifier->create($expr, $type, $context, $this->scope);
$this->assertSame($expectedResult, $this->toReadableResult($specifiedTypes));
}

/**
* @return iterable<array{Expr\BinaryOp\Coalesce, Type, TypeSpecifierContext, array<string, string>}>
*/
public static function dataCreateForCoalesce(): iterable
{
// a null left side would make the coalesce the right side, which the
// type rules out, so the left side is narrowed to non-null
yield [
new Expr\BinaryOp\Coalesce(new Variable('stringOrNull'), new LNumber(1)),
new UnionType([new ConstantStringType('a'), new NullType()]),
TypeSpecifierContext::createTrue(),
[
'$stringOrNull' => '\'a\'',
'$stringOrNull ?? 1' => '\'a\'|null',
],
];
yield [
new Expr\BinaryOp\Coalesce(new Variable('stringOrNull'), new String_('')),
new StringType(),
TypeSpecifierContext::createFalse(),
[
'$stringOrNull' => '~string|null',
'$stringOrNull ?? \'\'' => '~string',
],
];
}

/**
* @return mixed[]
*/
Expand Down
97 changes: 97 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-15748.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php declare(strict_types = 1);

namespace Bug15748;

use function PHPStan\Testing\assertType;

function foo(?string $x) {
if (($x ?? '') == '')
return null;
assertType('non-empty-string', $x);
$y = explode(':', $x);
// ...
}

function bar(?string $x) {
if (($x ?? '') != '') {
assertType('non-empty-string', $x);
}
}

function baz(?string $x) {
if (($x ?? '') === '')
return null;
assertType('non-empty-string', $x);
}

function qux(?string $x) {
if (($x ?? '') !== '') {
assertType('non-empty-string', $x);
}
}

function intCase(?int $x) {
if (($x ?? 0) == 0)
return null;
assertType('int<min, -1>|int<1, max>', $x);
}

function intStrictCase(?int $x) {
if (($x ?? 0) === 0)
return null;
assertType('int<min, -1>|int<1, max>', $x);
}

class Foo
{
public ?string $bar = null;
}

/** @param array{k?: string|null} $a */
function analogous(array $a, ?string $x, ?int $i, ?bool $b, ?Foo $o) {
if (($a['k'] ?? '') !== '') {
assertType('array{k: non-empty-string}', $a);
}
if (($i ?? 0) > 0) {
assertType('int<1, max>', $i);
}
if (($b ?? false) !== false) {
assertType('true', $b);
}
if (!in_array($x ?? '', ['', 'foo'], true)) {
assertType('non-empty-string', $x);
}
if (($o?->bar ?? '') !== '') {
assertType('Bug15748\Foo', $o);
assertType('non-empty-string', $o->bar);
}
if (($x ?? 'a') === null) {
assertType('*NEVER*', $x);
}
if (($x ?? '') !== 'abc') {
assertType('string|null', $x);
}
}

/** @param int|string|null $z */
function typeSpecifyingExtensions(?string $x, $z) {
if (is_callable($x ?? 1)) {
assertType('callable-string', $x);
}
if (is_callable($x ?? 'strlen') !== true) {
assertType('string', $x);
}
if (!is_array($z ?? [])) {
assertType('int|string', $z);
}
}

function negatedTrueContext(?string $x, bool $c) {
if ((($x ?? '') === '') !== true) {
assertType('non-empty-string', $x);
}
$w = $c ? '' : ($x ?? '');
if ($w !== '') {
assertType('non-empty-string', $x);
}
}
25 changes: 25 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-9946.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php // lint >= 8.0

declare(strict_types = 1);

namespace Bug9946;

use function PHPStan\Testing\assertType;

class A {
public null|int $value = null;
}

class B
{
public null|A $valA = null;
}

$aObj = new A();
$bObj = new B();

if (($bObj->valA?->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}
Comment on lines +21 to +25

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PHPStan reports this ?-> access is not necessary.

we should assert the types when people don't use ?-> in addition:

Suggested change
if (($bObj->valA?->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}
if (($bObj->valA?->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}
// without null-safe operator
if (($bObj->valA->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I added the case you suggested, without ?->, to tests/PHPStan/Analyser/nsrt/bug-9946.php. It failed: PHPStan inferred Bug9946\A|null for $bObj->valA, and the rule test reported "Cannot access property $value on Bug9946\A|null" twice. So I fixed that as well, in one local commit (c45842962). It isn't pushed.

The gap: ($bObj->valA->value ?? 0) !== 0 narrowed $bObj->valA->value, but not $bObj->valA. Without the fix, ($b->a->value ?? null) !== null doesn't narrow $b->a either. If the comparison rules out the right side of ??, the left side was set. So $bObj->valA can't be null, which is what isset($bObj->valA->value) already concludes.

The fix:

  • src/Analyser/ExprHandler/CoalesceHandler.php: in createTypesCallback, when the comparison type rules the right side in or out, the result now also includes the narrowing that isset() applies to every link in the left chain (createIssetTruthyChainTypes).
  • turbo-ext/src/CoalesceHandler.cpp: the same change in the native version. Its createTypesCallback now also captures $chainResults, like the PHP closure.

Checks:

  • bug-9946.php and AccessPropertiesRuleTest::testBug9946 failed before the fix and pass after it, with and without the extension. bug-15748.php still passes.
  • make tests passes (23863 tests, 116 skipped). The full suite also passes with the turbo extension loaded.
  • The extension builds with the strict warning flags, and tests/smoke.php prints ALL OK.
  • make phpstan reports no errors.

One case is still not narrowed: a bare truthy check like if ($b->a->value ?? false) leaves $b->a as A|null. It goes through a different callback, so I left it out of this PR.

I couldn't see the details of the mutant from the earlier CI run. If the mutation testing job still reports it after this push, the log will show which line needs another test.

9 changes: 9 additions & 0 deletions tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1321,4 +1321,13 @@ public function testBug15002(): void
$this->analyse([__DIR__ . '/data/bug-15002.php'], []);
}

#[RequiresPhp('>= 8.0.0')]
public function testBug9946(): void
{
$this->checkThisOnly = false;
$this->checkUnionTypes = true;
$this->checkDynamicProperties = false;
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-9946.php'], []);
}

}
9 changes: 7 additions & 2 deletions turbo-ext/src/CoalesceHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -498,10 +498,15 @@ class CoalesceHandler
// the coalesce's own key is emitted alongside the left-side
// narrowing (createForExpr's double-key, like the nullsafe
// handlers) - consumers summing the checked expression's own
// entry (ImpossibleCheckTypeHelper) rely on it
// entry (ImpossibleCheckTypeHelper) rely on it;
// a null left side would make the coalesce the right
// side, which the type rules out, so the left side is
// not null either
zval *left = ptoh::binaryOpLeft(expr);
if (UNEXPECTED(left == NULL)) return zv::Val();
zv::Val leftTypes = pt_default_narrowing_helper_create_subject_types(defaultNarrowingHelper, s.raw(), left, condResult, type, context);
zv::Val leftType = contextTrue ? pt_type_combinator_remove_null(type) : pt_type_combinator_add_null(type);
if (UNEXPECTED(leftType.isUndef())) return zv::Val();
zv::Val leftTypes = pt_default_narrowing_helper_create_subject_types(defaultNarrowingHelper, s.raw(), left, condResult, leftType.raw(), context);
if (UNEXPECTED(leftTypes.isUndef())) return zv::Val();
if (UNEXPECTED(Z_TYPE_P(leftTypes.raw()) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function unionWith() on %s", zend_zval_value_name(leftTypes.raw()));
Expand Down
18 changes: 12 additions & 6 deletions turbo-ext/src/TypeSpecifier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@ class TypeSpecifier

bool isNullContext;
if (UNEXPECTED(!pt_type_specifier_context_null(Z_OBJ_P(context), isNullContext))) return zv::Val();
zv::Val exprType = zv::Val::copyOf(zv::Ref(type));
bool isCoalesce;
if (UNEXPECTED(!isA(expr.raw(), PT_CLASS_COALESCE_EXPR, isCoalesce))) return zv::Val();
if (!isNullContext && isCoalesce) {
Expand Down Expand Up @@ -599,6 +600,10 @@ class TypeSpecifier
}
if (unwrap) {
expr = zv::Val::copyOf(zv::Ref(left));
// a null left side would make the coalesce the right side,
// which the type rules out, so the left side is not null either
exprType = isTrue ? pt_type_combinator_remove_null(type) : pt_type_combinator_add_null(type);
if (UNEXPECTED(exprType.isUndef())) return zv::Val();
}
}

Expand Down Expand Up @@ -628,12 +633,12 @@ class TypeSpecifier
bool isFalse;
if (UNEXPECTED(!pt_type_specifier_context_false(Z_OBJ_P(context), isFalse))) return zv::Val();
if (isFalse) {
if (UNEXPECTED(!addEntries(sureNotTypes, expr.raw(), originalExpr, type))) return zv::Val();
if (UNEXPECTED(!addEntries(sureNotTypes, expr.raw(), exprType.raw(), originalExpr, type))) return zv::Val();
} else {
bool isTrue;
if (UNEXPECTED(!pt_type_specifier_context_true(Z_OBJ_P(context), isTrue))) return zv::Val();
if (isTrue) {
if (UNEXPECTED(!addEntries(sureTypes, expr.raw(), originalExpr, type))) return zv::Val();
if (UNEXPECTED(!addEntries(sureTypes, expr.raw(), exprType.raw(), originalExpr, type))) return zv::Val();
}
}

Expand Down Expand Up @@ -812,11 +817,12 @@ class TypeSpecifier
return isNotPure(isPure == PT_TRI_YES ? PT_TRI_NO : (isPure == PT_TRI_NO ? PT_TRI_YES : PT_TRI_MAYBE));
}

/* $types[$printer->printExpr($expr)] = [$expr, $type], then the same for
* $originalExpr when the unwrap replaced it; false = pending exception */
[[nodiscard]] bool addEntries(zv::Arr &table, zval *expr, zval *originalExpr, zval *type) const
/* $types[$printer->printExpr($expr)] = [$expr, $exprType ?? $type], then
* [$originalExpr, $type] when the unwrap replaced it; false = pending
* exception */
[[nodiscard]] bool addEntries(zv::Arr &table, zval *expr, zval *exprType, zval *originalExpr, zval *type) const
{
if (UNEXPECTED(!addEntry(table, expr, type))) return false;
if (UNEXPECTED(!addEntry(table, expr, exprType))) return false;
if (Z_OBJ_P(expr) != Z_OBJ_P(originalExpr)) {
return addEntry(table, originalExpr, type);
}
Expand Down
Loading