diff --git a/src/Analyser/ExprHandler/CoalesceHandler.php b/src/Analyser/ExprHandler/CoalesceHandler.php index af404f8c4c5..e6cb2c9a103 100644 --- a/src/Analyser/ExprHandler/CoalesceHandler.php +++ b/src/Analyser/ExprHandler/CoalesceHandler.php @@ -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)); } } diff --git a/src/Analyser/TypeSpecifier.php b/src/Analyser/TypeSpecifier.php index b3816021a37..d2bfa507e32 100644 --- a/src/Analyser/TypeSpecifier.php +++ b/src/Analyser/TypeSpecifier.php @@ -178,6 +178,7 @@ private function createForExpr( } $originalExpr = $expr; + $exprType = $type; if (isset($containsNull) && !$containsNull) { $expr = NullsafeOperatorHelper::getNullsafeShortcircuitedExpr($expr); } @@ -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); } } @@ -214,7 +218,7 @@ 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); @@ -222,7 +226,7 @@ private function createForExpr( } } elseif ($context->true()) { $exprString = $this->exprPrinter->printExpr($expr); - $sureTypes[$exprString] = [$expr, $type]; + $sureTypes[$exprString] = [$expr, $exprType]; if ($expr !== $originalExpr) { $originalExprString = $this->exprPrinter->printExpr($originalExpr); diff --git a/tests/PHPStan/Analyser/TypeSpecifierTest.php b/tests/PHPStan/Analyser/TypeSpecifierTest.php index d1d9fcfdcf6..d8baa03cea5 100644 --- a/tests/PHPStan/Analyser/TypeSpecifierTest.php +++ b/tests/PHPStan/Analyser/TypeSpecifierTest.php @@ -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; @@ -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; @@ -1383,6 +1385,43 @@ public static function dataCondition(): iterable ]; } + /** + * @param array $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}> + */ + 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[] */ diff --git a/tests/PHPStan/Analyser/nsrt/bug-15748.php b/tests/PHPStan/Analyser/nsrt/bug-15748.php new file mode 100644 index 00000000000..3c18d74418c --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-15748.php @@ -0,0 +1,97 @@ +|int<1, max>', $x); +} + +function intStrictCase(?int $x) { + if (($x ?? 0) === 0) + return null; + assertType('int|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); + } +} diff --git a/tests/PHPStan/Analyser/nsrt/bug-9946.php b/tests/PHPStan/Analyser/nsrt/bug-9946.php new file mode 100644 index 00000000000..056c7dd058c --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-9946.php @@ -0,0 +1,25 @@ += 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|int<1, max>', $bObj->valA->value); + $test = $bObj->valA->value; +} diff --git a/tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php b/tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php index 11329e9f8b5..1a3d6a1b364 100644 --- a/tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php +++ b/tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php @@ -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'], []); + } + } diff --git a/turbo-ext/src/CoalesceHandler.cpp b/turbo-ext/src/CoalesceHandler.cpp index 893786a856a..55e8dcc98c8 100644 --- a/turbo-ext/src/CoalesceHandler.cpp +++ b/turbo-ext/src/CoalesceHandler.cpp @@ -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())); diff --git a/turbo-ext/src/TypeSpecifier.cpp b/turbo-ext/src/TypeSpecifier.cpp index df161374d42..42ccd8cbabf 100644 --- a/turbo-ext/src/TypeSpecifier.cpp +++ b/turbo-ext/src/TypeSpecifier.cpp @@ -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) { @@ -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(); } } @@ -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(); } } @@ -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); }