Skip to content

Narrow native types by conditional expression holders - #7177

Merged
ondrejmirtes merged 1 commit into
2.3.xfrom
native-conditional-holders
Nov 26, 2026
Merged

ondrejmirtes merged 1 commit into
2.3.xfrom
native-conditional-holders

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

Conditional expression holders narrowed only the PHPDoc type of their target, never the native type:

function f(?int $x): void
{
	$ok = $x !== null;
	if ($ok) {
		\PHPStan\dumpType($x);       // int
		\PHPStan\dumpNativeType($x); // int|null
		if ($x === null) {           // reported with "Because the type is coming from a PHPDoc..."
		}
	}
}

The function has no PHPDoc, so the tip is wrong, and with treatPhpDocTypesAsCertain: false the always-false comparison is not reported at all. Branch-merge holders (if ($b) { $y = $x ?? 1; } else { $y = null; } if ($b) …) behave the same.

A matched holder now narrows the native type too when the target and every guard currently have native types equal to their PHPDoc types. The holder's type may carry PHPDoc knowledge from where it was created, but then the native type implies everything the PHPDoc type does, so intersecting with it adds no PHPDoc assumption. A PHPDoc-typed target or guard keeps its native type unnarrowed (covered in nsrt/conditional-expression-native-types.php).

This is the reduced product of the two analyses (Cousot & Cousot 1979): every transfer function updates both components.

Two existing expectations lose the PHPDoc tip they had wrongly: ImpossibleInstanceOfRuleTest::testBug3632 and BooleanNotConstantConditionRuleTest::testBug11903, neither of which has any PHPDoc.

turbo-ext mirrors the change.

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant