Skip to content

Commit d8381c0

Browse files
committed
Carry narrowings through tracked comparison verdicts
A narrowed `$a === $b` or integer `$a < $b` narrowed each operand once, against the other one's type at that moment. A later narrowing of one operand did not reach the other, so the order of the conditions mattered: `if ($b > 0) { if ($a === $b) … }` gave `int<1, max>`, the reverse order `int`. The verdict of such a comparison between variables, properties, offsets or count() is now kept in the scope, and applySpecifiedTypes() narrows the other operand when one operand narrows. A count() that cannot be 0 any more makes its array non-empty. RuleTestCase compared two strings it had just checked to be identical; the two early returns are merged. Amp-Thread-ID: https://ampcode.com/threads/T-01a17eac-1199-74a6-b3f7-dfbd8a084465
1 parent 7e3b7e2 commit d8381c0

5 files changed

Lines changed: 378 additions & 8 deletions

File tree

‎src/Analyser/ExprHandler/BinaryOpHandler.php‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Countable;
66
use DivisionByZeroError;
7+
use PhpParser\Node;
78
use PhpParser\Node\Expr;
89
use PhpParser\Node\Expr\BinaryOp;
910
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
@@ -733,7 +734,9 @@ static function () use ($expr, $nativeTypesPromoted, $typeCallback): Type {
733734
$specifiedTypes = $specifyTypesCallback($context, $nativeTypesPromoted);
734735
$scope = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
735736

736-
return $this->specifyRememberedComparisonForms($specifiedTypes, $scope, $expr, $leftResult, $rightResult, $context);
737+
$specifiedTypes = $this->specifyRememberedComparisonForms($specifiedTypes, $scope, $expr, $leftResult, $rightResult, $context);
738+
739+
return $this->rememberRelationalFact($specifiedTypes, $expr, $leftResult, $rightResult, $context, $nativeTypesPromoted);
737740
},
738741
dependencies: Dependencies::merge($leftResult->getDependencies(), $rightResult->getDependencies()),
739742
);
@@ -808,6 +811,81 @@ private function specifyRememberedComparisonForms(SpecifiedTypes $specifiedTypes
808811
return $specifiedTypes->unionWith(new SpecifiedTypes($sureTypes, []));
809812
}
810813

814+
/**
815+
* Narrowing `$a === $b` or an integer `$a < $b` also keeps its verdict in
816+
* the scope, which narrows each operand again when the other one narrows
817+
* later (MutatingScope::applySpecifiedTypes()). An operand with a constant
818+
* value relates to nothing - its own narrowing is all there is.
819+
*/
820+
private function rememberRelationalFact(SpecifiedTypes $specifiedTypes, BinaryOp $expr, ExpressionResult $leftResult, ExpressionResult $rightResult, TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes
821+
{
822+
if ($context->true() === $context->false()) {
823+
return $specifiedTypes;
824+
}
825+
826+
$isIdentity = $expr instanceof BinaryOp\Identical || $expr instanceof BinaryOp\NotIdentical;
827+
if (
828+
!$isIdentity
829+
&& !$expr instanceof BinaryOp\Smaller
830+
&& !$expr instanceof BinaryOp\SmallerOrEqual
831+
&& !$expr instanceof BinaryOp\Greater
832+
&& !$expr instanceof BinaryOp\GreaterOrEqual
833+
) {
834+
return $specifiedTypes;
835+
}
836+
837+
// an identity relates the operands only when it holds
838+
if ($isIdentity && $context->true() !== $expr instanceof BinaryOp\Identical) {
839+
return $specifiedTypes;
840+
}
841+
if (!self::isRelatableOperand($expr->left) || !self::isRelatableOperand($expr->right)) {
842+
return $specifiedTypes;
843+
}
844+
$leftType = $nativeTypesPromoted ? $leftResult->getNativeType() : $leftResult->getType();
845+
$rightType = $nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType();
846+
if (count($leftType->getFiniteTypes()) === 1 || count($rightType->getFiniteTypes()) === 1) {
847+
return $specifiedTypes;
848+
}
849+
if (!$isIdentity && (!$leftType->isInteger()->yes() || !$rightType->isInteger()->yes())) {
850+
return $specifiedTypes;
851+
}
852+
853+
return $specifiedTypes->unionWith(new SpecifiedTypes([
854+
$this->exprPrinter->printExpr($expr) => [$expr, new ConstantBooleanType($context->true())],
855+
], []));
856+
}
857+
858+
/** A variable, a property or offset fetched from one, or its count(). */
859+
private static function isRelatableOperand(Expr $expr): bool
860+
{
861+
if (
862+
$expr instanceof Expr\FuncCall
863+
&& $expr->name instanceof Name
864+
&& in_array($expr->name->toLowerString(), ['count', 'sizeof'], true)
865+
&& !$expr->isFirstClassCallable()
866+
&& count($expr->getArgs()) === 1
867+
&& !$expr->getArgs()[0]->unpack
868+
) {
869+
$expr = $expr->getArgs()[0]->value;
870+
}
871+
872+
while (true) {
873+
if ($expr instanceof Variable) {
874+
return is_string($expr->name);
875+
}
876+
if ($expr instanceof Expr\PropertyFetch && $expr->name instanceof Node\Identifier) {
877+
$expr = $expr->var;
878+
continue;
879+
}
880+
if ($expr instanceof Expr\ArrayDimFetch && $expr->dim !== null && ($expr->dim instanceof Node\Scalar || $expr->dim instanceof Variable)) {
881+
$expr = $expr->var;
882+
continue;
883+
}
884+
885+
return false;
886+
}
887+
}
888+
811889
/**
812890
* The forms of a comparison that always evaluate to the same value, each
813891
* paired with whether it is the complement (always the opposite value).

‎src/Analyser/MutatingScope.php‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PhpParser\Node\ComplexType;
88
use PhpParser\Node\Expr;
99
use PhpParser\Node\Expr\Array_;
10+
use PhpParser\Node\Expr\BinaryOp;
1011
use PhpParser\Node\Expr\CallLike;
1112
use PhpParser\Node\Expr\ClassConstFetch;
1213
use PhpParser\Node\Expr\ConstFetch;
@@ -112,6 +113,7 @@
112113
use function array_filter;
113114
use function array_intersect_key;
114115
use function array_key_exists;
116+
use function array_key_first;
115117
use function array_keys;
116118
use function array_last;
117119
use function array_map;
@@ -159,6 +161,9 @@ class MutatingScope implements Scope, NodeCallbackInvoker, CollectedDataEmitter,
159161
/** Past this array nesting, widening between loop passes turns an array value whose nesting grew into mixed. */
160162
private const GENERALIZED_ARRAY_DEPTH_LIMIT = 2;
161163

164+
/** Rounds of carrying a narrowing through tracked comparison verdicts per application, a chain `$a < $b < $c` takes one per link. */
165+
private const RELATIONAL_FACT_ROUNDS_LIMIT = 4;
166+
162167
/** Magic methods that let the author decide which properties survive a serialize()/unserialize() round trip. */
163168
private const CUSTOM_SERIALIZATION_METHODS = ['__sleep', '__serialize', '__unserialize'];
164169

@@ -4158,6 +4163,58 @@ public function applySpecifiedTypes(SpecifiedTypes $specifiedTypes): self
41584163
$specifiedExpressions[$exprString] = ExpressionTypeHolder::createYes($expr, $holderType);
41594164
}
41604165

4166+
// a tracked comparison verdict carries the narrowing of one operand
4167+
// over to the other one
4168+
$changedExpressions = $specifiedExpressions;
4169+
for ($round = 0; $changedExpressions !== [] && $round < self::RELATIONAL_FACT_ROUNDS_LIMIT; $round++) {
4170+
$derivedTypes = $scope->deriveFromRelationalFacts($changedExpressions);
4171+
$changedExpressions = [];
4172+
while ($derivedTypes !== []) {
4173+
$exprString = (string) array_key_first($derivedTypes); // @phpstan-ignore cast.useless
4174+
[$expr, $type] = $derivedTypes[$exprString];
4175+
unset($derivedTypes[$exprString]);
4176+
if (
4177+
!array_key_exists($exprString, $scope->expressionTypes)
4178+
|| !$scope->expressionTypes[$exprString]->getCertainty()->yes()
4179+
) {
4180+
continue;
4181+
}
4182+
$trackedType = $scope->expressionTypes[$exprString]->getType();
4183+
$newType = TypeCombinator::intersect($type, $trackedType);
4184+
if ($newType->equals($trackedType)) {
4185+
continue;
4186+
}
4187+
$trackedNativeType = array_key_exists($exprString, $scope->nativeExpressionTypes) && $scope->nativeExpressionTypes[$exprString]->getCertainty()->yes()
4188+
? $scope->nativeExpressionTypes[$exprString]->getType()
4189+
: null;
4190+
$newNativeType = $trackedNativeType !== null ? TypeCombinator::intersect($type, $trackedNativeType) : $type;
4191+
if (!$scopeIsWorkingCopy) {
4192+
$scope = $scope->openSpecificationScope();
4193+
$scopeIsWorkingCopy = true;
4194+
}
4195+
$scope->specifyExpressionTypeInPlace($expr, $newType, $newNativeType, TrinaryLogic::createYes());
4196+
4197+
$holder = ExpressionTypeHolder::createYes($expr, $scope->expressionTypes[$exprString]->getType());
4198+
$changedExpressions[$exprString] = $holder;
4199+
$specifiedExpressions[$exprString] = $holder;
4200+
4201+
// a count() that cannot be 0 any more makes its array non-empty
4202+
if (
4203+
!$expr instanceof FuncCall
4204+
|| !$expr->name instanceof Name
4205+
|| !in_array($expr->name->toLowerString(), ['count', 'sizeof'], true)
4206+
|| $expr->isFirstClassCallable()
4207+
|| count($expr->getArgs()) !== 1
4208+
|| $expr->getArgs()[0]->unpack
4209+
|| !(new ConstantIntegerType(0))->isSuperTypeOf($newType)->no()
4210+
) {
4211+
continue;
4212+
}
4213+
$countedExpr = $expr->getArgs()[0]->value;
4214+
$derivedTypes[$scope->getNodeKey($countedExpr)] = [$countedExpr, new NonEmptyArrayType()];
4215+
}
4216+
}
4217+
41614218
$scope = $scope->processConditionalExpressionsAfterSpecifying($specifiedExpressions);
41624219

41634220
$newConditionalExpressionHolders = $specifiedTypes->getNewConditionalExpressionHolders();
@@ -4194,6 +4251,95 @@ public function applySpecifiedTypes(SpecifiedTypes $specifiedTypes): self
41944251
);
41954252
}
41964253

4254+
/**
4255+
* The narrowings the tracked `$a === $b` and integer `$a < $b` verdicts
4256+
* imply for one operand when the other one is among the changed
4257+
* expressions. A verdict changed itself was narrowed together with its
4258+
* operands.
4259+
*
4260+
* @param array<string, ExpressionTypeHolder> $changedExpressions
4261+
* @return array<string, array{Expr, Type}>
4262+
*/
4263+
private function deriveFromRelationalFacts(array $changedExpressions): array
4264+
{
4265+
$derivedTypes = [];
4266+
foreach ($this->expressionTypes as $factString => $factHolder) {
4267+
$fact = $factHolder->getExpr();
4268+
if (!$fact instanceof BinaryOp || array_key_exists((string) $factString, $changedExpressions)) { // @phpstan-ignore cast.useless
4269+
continue;
4270+
}
4271+
$isIdentical = $fact instanceof BinaryOp\Identical;
4272+
$isIdentity = $isIdentical || $fact instanceof BinaryOp\NotIdentical;
4273+
$isSmaller = $fact instanceof BinaryOp\Smaller || $fact instanceof BinaryOp\SmallerOrEqual;
4274+
if (!$isIdentity && !$isSmaller && !$fact instanceof BinaryOp\Greater && !$fact instanceof BinaryOp\GreaterOrEqual) {
4275+
continue;
4276+
}
4277+
if (!$factHolder->getCertainty()->yes()) {
4278+
continue;
4279+
}
4280+
$verdict = $factHolder->getType();
4281+
if ($verdict->isTrue()->yes()) {
4282+
$holds = true;
4283+
} elseif ($verdict->isFalse()->yes()) {
4284+
$holds = false;
4285+
} else {
4286+
continue;
4287+
}
4288+
4289+
$leftKey = $this->getNodeKey($fact->left);
4290+
$rightKey = $this->getNodeKey($fact->right);
4291+
$leftChanged = array_key_exists($leftKey, $changedExpressions);
4292+
$rightChanged = array_key_exists($rightKey, $changedExpressions);
4293+
if (!$leftChanged && !$rightChanged) {
4294+
continue;
4295+
}
4296+
4297+
$implied = [];
4298+
if ($isIdentity) {
4299+
if ($holds !== $isIdentical) {
4300+
continue;
4301+
}
4302+
if ($leftChanged) {
4303+
$implied[] = [$rightKey, $fact->right, $changedExpressions[$leftKey]->getType()];
4304+
}
4305+
if ($rightChanged) {
4306+
$implied[] = [$leftKey, $fact->left, $changedExpressions[$rightKey]->getType()];
4307+
}
4308+
} else {
4309+
// normalized to `$smaller < $larger` / `$smaller <= $larger`;
4310+
// a false verdict of integers is the inverse comparison
4311+
$orEqual = $fact instanceof BinaryOp\SmallerOrEqual || $fact instanceof BinaryOp\GreaterOrEqual;
4312+
[$smaller, $larger, $smallerKey, $largerKey] = $isSmaller
4313+
? [$fact->left, $fact->right, $leftKey, $rightKey]
4314+
: [$fact->right, $fact->left, $rightKey, $leftKey];
4315+
if (!$holds) {
4316+
[$smaller, $larger, $smallerKey, $largerKey] = [$larger, $smaller, $largerKey, $smallerKey];
4317+
$orEqual = !$orEqual;
4318+
}
4319+
if (array_key_exists($smallerKey, $changedExpressions)) {
4320+
$smallerType = $changedExpressions[$smallerKey]->getType();
4321+
if ($smallerType->isInteger()->yes()) {
4322+
$implied[] = [$largerKey, $larger, $orEqual ? $smallerType->getGreaterOrEqualType($this->services->phpVersion) : $smallerType->getGreaterType($this->services->phpVersion)];
4323+
}
4324+
}
4325+
if (array_key_exists($largerKey, $changedExpressions)) {
4326+
$largerType = $changedExpressions[$largerKey]->getType();
4327+
if ($largerType->isInteger()->yes()) {
4328+
$implied[] = [$smallerKey, $smaller, $orEqual ? $largerType->getSmallerOrEqualType($this->services->phpVersion) : $largerType->getSmallerType($this->services->phpVersion)];
4329+
}
4330+
}
4331+
}
4332+
4333+
foreach ($implied as [$impliedKey, $impliedExpr, $impliedType]) {
4334+
$derivedTypes[$impliedKey] = array_key_exists($impliedKey, $derivedTypes)
4335+
? [$impliedExpr, TypeCombinator::intersect($derivedTypes[$impliedKey][1], $impliedType)]
4336+
: [$impliedExpr, $impliedType];
4337+
}
4338+
}
4339+
4340+
return $derivedTypes;
4341+
}
4342+
41974343
/**
41984344
* Matches already-registered conditional expressions against the just-specified
41994345
* expression type holders and applies the matching consequences.

‎src/Testing/RuleTestCase.php‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -224,12 +224,7 @@ static function (Error $error) use ($strictlyTypedSprintf): string {
224224
$expectedErrorsString = implode("\n", $expectedErrors) . "\n";
225225
$actualErrorsString = implode("\n", $actualErrors) . "\n";
226226

227-
if (count($delayedErrors) === 0) {
228-
$this->assertSame($expectedErrorsString, $actualErrorsString);
229-
return;
230-
}
231-
232-
if ($expectedErrorsString === $actualErrorsString) {
227+
if (count($delayedErrors) === 0 || $expectedErrorsString === $actualErrorsString) {
233228
$this->assertSame($expectedErrorsString, $actualErrorsString);
234229
return;
235230
}

‎tests/PHPStan/Analyser/TypeSpecifierTest.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ public static function dataCondition(): iterable
495495
new Variable('foo'),
496496
new Variable('bar'),
497497
),
498-
['$foo' => 'Bar', '$bar' => 'mixed'], // could be '$bar' => 'Bar'
498+
['$foo' => 'Bar', '$bar' => 'mixed', '$foo === $bar' => 'true'], // could be '$bar' => 'Bar'
499499
[],
500500
],
501501
[

0 commit comments

Comments
 (0)