Skip to content

Commit ce23f0d

Browse files
committed
Narrow native types by conditional expression holders
A holder narrowed only the PHPDoc type of its target, so `$ok = $x !== null; if ($ok)` left the native type of $x nullable: a later `$x === null` was reported with the PHPDoc tip in code without PHPDoc, and not at all with treatPhpDocTypesAsCertain: false. A matched holder now narrows the native type too when the target and every guard have native types equal to their PHPDoc types: the PHPDoc knowledge the holder's type carries is then implied by the native types. Amp-Thread-ID: https://ampcode.com/threads/T-01a17eac-1199-74a6-b3f7-dfbd8a084465
1 parent 51cdb8e commit ce23f0d

5 files changed

Lines changed: 160 additions & 3 deletions

File tree

‎src/Analyser/MutatingScope.php‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4173,6 +4173,20 @@ private function processConditionalExpressionsAfterSpecifying(array $specifiedEx
41734173
$type = TypeCombinator::intersect($type, $expressions[$i]->getTypeHolder()->getType());
41744174
}
41754175

4176+
// The holders' types were derived from PHPDoc types. Where the target
4177+
// and every guard have native types equal to their PHPDoc types, the
4178+
// PHPDoc knowledge the holder carries is implied by the native types
4179+
// too, so the holder narrows the native type the way the condition
4180+
// it was derived from would have
4181+
if ($scope->narrowsNativeTypeByHolders($conditionalExprString, $expressions)) {
4182+
$nativeHolder = $scope->nativeExpressionTypes[$conditionalExprString];
4183+
$scope->nativeExpressionTypes[$conditionalExprString] = new ExpressionTypeHolder(
4184+
$nativeHolder->getExpr(),
4185+
TypeCombinator::intersect($nativeHolder->getType(), $type),
4186+
$nativeHolder->getCertainty(),
4187+
);
4188+
}
4189+
41764190
$scope->expressionTypes[$conditionalExprString] = new ExpressionTypeHolder(
41774191
$scope->expressionTypes[$conditionalExprString]->getExpr(),
41784192
TypeCombinator::intersect($scope->expressionTypes[$conditionalExprString]->getType(), $type),
@@ -4187,6 +4201,33 @@ private function processConditionalExpressionsAfterSpecifying(array $specifiedEx
41874201
return $scope;
41884202
}
41894203

4204+
/**
4205+
* @param ConditionalExpressionHolder[] $holders
4206+
*/
4207+
private function narrowsNativeTypeByHolders(string $exprString, array $holders): bool
4208+
{
4209+
if (!$this->hasEqualNativeType($exprString)) {
4210+
return false;
4211+
}
4212+
4213+
foreach ($holders as $holder) {
4214+
foreach (array_keys($holder->getConditionExpressionTypeHolders()) as $guardExprString) {
4215+
if (!$this->hasEqualNativeType($guardExprString)) {
4216+
return false;
4217+
}
4218+
}
4219+
}
4220+
4221+
return true;
4222+
}
4223+
4224+
private function hasEqualNativeType(string $exprString): bool
4225+
{
4226+
return array_key_exists($exprString, $this->expressionTypes)
4227+
&& array_key_exists($exprString, $this->nativeExpressionTypes)
4228+
&& $this->expressionTypes[$exprString]->equalTypes($this->nativeExpressionTypes[$exprString]);
4229+
}
4230+
41904231
/**
41914232
* @return array<string, ConditionalExpressionHolder[]>
41924233
*/
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace ConditionalExpressionNativeTypes;
4+
5+
use function PHPStan\Testing\assertNativeType;
6+
use function PHPStan\Testing\assertType;
7+
8+
function storedCondition(?int $x): void
9+
{
10+
$ok = $x !== null;
11+
if ($ok) {
12+
assertType('int', $x);
13+
assertNativeType('int', $x);
14+
}
15+
}
16+
17+
function branchMerge(?int $x, bool $b): void
18+
{
19+
if ($b) {
20+
$y = $x ?? 1;
21+
} else {
22+
$y = null;
23+
}
24+
if ($b) {
25+
assertType('int', $y);
26+
assertNativeType('int', $y);
27+
}
28+
}
29+
30+
/** @param int|null $x */
31+
function phpDocTarget($x): void
32+
{
33+
$ok = $x !== null;
34+
if ($ok) {
35+
assertType('int', $x);
36+
assertNativeType('mixed', $x);
37+
}
38+
}
39+
40+
/** @param bool $b */
41+
function phpDocGuard(?int $x, $b): void
42+
{
43+
if ($b) {
44+
$y = $x ?? 1;
45+
} else {
46+
$y = null;
47+
}
48+
if ($b) {
49+
assertType('int', $y);
50+
assertNativeType('int|null', $y);
51+
}
52+
}
53+
54+
/** @param int|null $x */
55+
function nativeNarrowedLater($x): void
56+
{
57+
$ok = $x !== null;
58+
if (is_int($x) || $x === null) {
59+
if ($ok) {
60+
assertType('int', $x);
61+
assertNativeType('int', $x);
62+
}
63+
}
64+
}

‎tests/PHPStan/Rules/Classes/ImpossibleInstanceOfRuleTest.php‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,12 +411,10 @@ public function testBug10201(): void
411411

412412
public function testBug3632(): void
413413
{
414-
$tipText = 'Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.';
415414
$this->analyse([__DIR__ . '/data/bug-3632.php'], [
416415
[
417416
'Instanceof between null and Bug3632\NiceClass will always evaluate to false.',
418417
32,
419-
$tipText,
420418
],
421419
[
422420
'Instanceof between Bug3632\NiceClass and Bug3632\NiceClass will always evaluate to true.',

‎tests/PHPStan/Rules/Comparison/BooleanNotConstantConditionRuleTest.php‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,6 @@ public function testBug11903(): void
200200
[
201201
'Negated boolean expression is always true.',
202202
13,
203-
'Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.',
204203
],
205204
[
206205
'Negated boolean expression is always true.',

‎turbo-ext/src/MutatingScope.cpp‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8098,6 +8098,40 @@ class MutatingScope
80988098
return found != NULL && Z_TYPE_P(found) != IS_NULL;
80998099
}
81008100

8101+
/* $this->hasEqualNativeType($exprString): tracked in both tables with
8102+
* equal types; false = pending exception */
8103+
[[nodiscard]] bool hasEqualNativeType(zend_string *exprString, bool &out)
8104+
{
8105+
out = false;
8106+
zval *phpDoc = zend_symtable_find(Z_ARRVAL_P(slot(PT_MS_PROP_EXPRESSION_TYPES).raw()), exprString);
8107+
if (phpDoc == NULL) return true;
8108+
zval *native = zend_symtable_find(Z_ARRVAL_P(slot(PT_MS_PROP_NATIVE_EXPRESSION_TYPES).raw()), exprString);
8109+
if (native == NULL) return true;
8110+
ZVAL_DEREF(phpDoc);
8111+
ZVAL_DEREF(native);
8112+
return pt_holder_equal_types(phpDoc, native, &out);
8113+
}
8114+
8115+
/* $this->narrowsNativeTypeByHolders($exprString, $holders); false = pending
8116+
* exception */
8117+
[[nodiscard]] bool narrowsNativeTypeByHolders(zend_string *exprString, HashTable *holders, bool &out)
8118+
{
8119+
if (UNEXPECTED(!requireSlot(PT_MS_PROP_NATIVE_EXPRESSION_TYPES, "nativeExpressionTypes"))) return false;
8120+
if (UNEXPECTED(!hasEqualNativeType(exprString, out))) return false;
8121+
if (!out) return true;
8122+
for (auto holderEntry : zv::TableRef(holders)) {
8123+
zv::Val conditions = conditionalConditions(holderEntry.value());
8124+
if (UNEXPECTED(conditions.isUndef())) return false;
8125+
for (auto conditionEntry : zv::TableRef(Z_ARRVAL_P(conditions.raw()))) {
8126+
zend_string *skey = conditionEntry.stringKeyOrNull();
8127+
zv::Str guardExprString = zv::Str::adopt(skey != NULL ? zend_string_copy(skey) : zend_long_to_str((zend_long) conditionEntry.indexKey()));
8128+
if (UNEXPECTED(!hasEqualNativeType(guardExprString.get(), out))) return false;
8129+
if (!out) return true;
8130+
}
8131+
}
8132+
return true;
8133+
}
8134+
81018135
/*
81028136
* private (twin 4283) — matches the registered conditional expressions
81038137
* against the just-specified holders and applies the consequences.
@@ -8185,6 +8219,27 @@ class MutatingScope
81858219
if (UNEXPECTED(intersected.isUndef())) return zv::Val();
81868220
type = std::move(intersected);
81878221
}
8222+
/* the holders narrow the native type too where the target and every
8223+
* guard have equal native and PHPDoc types */
8224+
bool narrowsNative;
8225+
if (UNEXPECTED(!narrowsNativeTypeByHolders(conditionalExprString.get(), holders, narrowsNative))) return zv::Val();
8226+
if (narrowsNative) {
8227+
zval *nativeExisting = zend_symtable_find(Z_ARRVAL_P(slot(PT_MS_PROP_NATIVE_EXPRESSION_TYPES).raw()), conditionalExprString.get());
8228+
zv::Val nativeExpr = holderExpr(zv::Ref(nativeExisting));
8229+
zv::Val nativeType = holderType(zv::Ref(nativeExisting));
8230+
if (UNEXPECTED(nativeExpr.isUndef() || nativeType.isUndef())) return zv::Val();
8231+
zend_long nativeCertainty = holderCertainty(zv::Ref(nativeExisting));
8232+
if (UNEXPECTED(nativeCertainty < 0)) return zv::Val();
8233+
zv::Val nativeIntersected = intersectTypes(nativeType.raw(), type.raw());
8234+
if (UNEXPECTED(nativeIntersected.isUndef())) return zv::Val();
8235+
zval nativeHolder;
8236+
pt_holder_create(&nativeHolder, nativeExpr.raw(), nativeIntersected.raw(), nativeCertainty);
8237+
zv::Val nativeHolderValue = zv::Val::adopt(nativeHolder);
8238+
if (UNEXPECTED(!writeScopeTable(self, PT_MS_PROP_NATIVE_EXPRESSION_TYPES, PT_LC("nativeExpressionTypes"), conditionalExprString.get(), nativeHolderValue.raw()))) {
8239+
return zv::Val();
8240+
}
8241+
existing = zend_symtable_find(Z_ARRVAL_P(slot(PT_MS_PROP_EXPRESSION_TYPES).raw()), conditionalExprString.get());
8242+
}
81888243
zv::Val existingExpr = holderExpr(zv::Ref(existing));
81898244
zv::Val existingType = holderType(zv::Ref(existing));
81908245
if (UNEXPECTED(existingExpr.isUndef() || existingType.isUndef())) return zv::Val();

0 commit comments

Comments
 (0)