Skip to content

Commit 23c5fc4

Browse files
committed
Reduce false positives about constant conditions in traits
2 parents 3d36763 + b47a204 commit 23c5fc4

84 files changed

Lines changed: 3124 additions & 335 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/e2e-tests.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,12 @@ jobs:
267267
cd e2e/bug-11857
268268
composer install
269269
../../bin/phpstan
270+
- script: |
271+
cd e2e/in-trait
272+
OUTPUT=$(../bashunit -a exit_code "1" "../../bin/phpstan --error-format=raw")
273+
../bashunit -a contains 'FooTrait.php:10:Strict comparison using === between int<0, max> and false will always evaluate to false.' "$OUTPUT"
274+
../bashunit -a contains 'FooTrait.php (in context of class E2EInTrait\Bar):18:Strict comparison using === between E2EInTrait\Bar and null will always evaluate to false.' "$OUTPUT"
275+
../bashunit -a contains 'FooTrait.php (in context of class E2EInTrait\Foo):18:Strict comparison using === between E2EInTrait\Foo and null will always evaluate to false.' "$OUTPUT"
270276
- script: |
271277
cd e2e/result-cache-meta-extension
272278
composer install

‎build/baseline-8.0.neon‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,24 +12,12 @@ parameters:
1212
count: 1
1313
path: ../src/Type/ClosureTypeFactory.php
1414

15-
-
16-
message: '#^Strict comparison using \=\=\= between list\<non\-falsy\-string\> and false will always evaluate to false\.$#'
17-
identifier: identical.alwaysFalse
18-
count: 1
19-
path: ../src/Type/Php/MbFunctionsReturnTypeExtension.php
20-
2115
-
2216
message: '#^Strict comparison using \=\=\= between int\<0, max\> and false will always evaluate to false\.$#'
2317
identifier: identical.alwaysFalse
2418
count: 1
2519
path: ../src/Type/Php/MbStrlenFunctionReturnTypeExtension.php
2620

27-
-
28-
message: '#^Strict comparison using \=\=\= between list\<non\-falsy\-string\> and false will always evaluate to false\.$#'
29-
identifier: identical.alwaysFalse
30-
count: 1
31-
path: ../src/Type/Php/MbStrlenFunctionReturnTypeExtension.php
32-
3321
-
3422
message: '#^Strict comparison using \=\=\= between list\<non\-falsy\-string\> and false will always evaluate to false\.$#'
3523
identifier: identical.alwaysFalse

‎e2e/in-trait/phpstan.neon‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
parameters:
2+
level: 8
3+
paths:
4+
- src

‎e2e/in-trait/src/Bar.php‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace E2EInTrait;
4+
5+
class Bar
6+
{
7+
8+
use FooTrait;
9+
10+
public function getSth(): ?self
11+
{
12+
return rand(0, 1) ? $this : null;
13+
}
14+
15+
public function getSth2(): self
16+
{
17+
return $this;
18+
}
19+
20+
}

‎e2e/in-trait/src/Foo.php‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace E2EInTrait;
4+
5+
class Foo
6+
{
7+
8+
use FooTrait;
9+
10+
public function getSth(): self
11+
{
12+
return $this;
13+
}
14+
15+
public function getSth2(): self
16+
{
17+
return $this;
18+
}
19+
20+
}

‎e2e/in-trait/src/FooTrait.php‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace E2EInTrait;
4+
5+
trait FooTrait
6+
{
7+
8+
public function doFoo(int $i): void
9+
{
10+
if (abs($i) === false) {
11+
12+
}
13+
14+
if ($this->getSth() === null) {
15+
16+
}
17+
18+
if ($this->getSth2() === null) {
19+
20+
}
21+
}
22+
23+
}

‎src/Analyser/Error.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,28 @@ public function changeTraitFilePath(string $newFilePath): self
106106
);
107107
}
108108

109+
public function removeTraitContext(): self
110+
{
111+
if ($this->traitFilePath === null) {
112+
throw new ShouldNotHappenException();
113+
}
114+
115+
return new self(
116+
$this->message,
117+
$this->traitFilePath,
118+
$this->line,
119+
$this->canBeIgnored,
120+
$this->filePath,
121+
null,
122+
$this->tip,
123+
$this->nodeLine,
124+
$this->nodeType,
125+
$this->identifier,
126+
$this->metadata,
127+
$this->fixedErrorDiff,
128+
);
129+
}
130+
109131
public function getTraitFilePath(): ?string
110132
{
111133
return $this->traitFilePath;

‎src/Analyser/RuleErrorTransformer.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use PHPStan\Rules\MetadataRuleError;
2323
use PHPStan\Rules\NonIgnorableRuleError;
2424
use PHPStan\Rules\RuleError;
25+
use PHPStan\Rules\RuleErrors\TransformedRuleError;
2526
use PHPStan\Rules\TipRuleError;
2627
use PHPStan\ShouldNotHappenException;
2728
use SebastianBergmann\Diff\Differ;
@@ -55,6 +56,10 @@ public function transform(
5556
Node $node,
5657
): Error
5758
{
59+
if ($ruleError instanceof TransformedRuleError) {
60+
return $ruleError->getError();
61+
}
62+
5863
$line = $node->getStartLine();
5964
$canBeIgnored = true;
6065
$fileName = $scope->getFileDescription();

‎src/Rules/Classes/ImpossibleInstanceOfRule.php‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@
33
namespace PHPStan\Rules\Classes;
44

55
use PhpParser\Node;
6+
use PHPStan\Analyser\CollectedDataEmitter;
7+
use PHPStan\Analyser\NodeCallbackInvoker;
68
use PHPStan\Analyser\Scope;
79
use PHPStan\DependencyInjection\AutowiredParameter;
810
use PHPStan\DependencyInjection\RegisteredRule;
911
use PHPStan\Parser\LastConditionVisitor;
12+
use PHPStan\Rules\Comparison\ConstantConditionInTraitHelper;
13+
use PHPStan\Rules\Comparison\PossiblyImpureTipHelper;
1014
use PHPStan\Rules\Rule;
1115
use PHPStan\Rules\RuleErrorBuilder;
1216
use PHPStan\Rules\RuleLevelHelper;
@@ -29,6 +33,8 @@ final class ImpossibleInstanceOfRule implements Rule
2933

3034
public function __construct(
3135
private RuleLevelHelper $ruleLevelHelper,
36+
private PossiblyImpureTipHelper $possiblyImpureTipHelper,
37+
private ConstantConditionInTraitHelper $constantConditionInTraitHelper,
3238
#[AutowiredParameter]
3339
private bool $treatPhpDocTypesAsCertain,
3440
#[AutowiredParameter]
@@ -44,7 +50,7 @@ public function getNodeType(): string
4450
return Node\Expr\Instanceof_::class;
4551
}
4652

47-
public function processNode(Node $node, Scope $scope): array
53+
public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array
4854
{
4955
if ($node->class instanceof Node\Name) {
5056
$className = $scope->resolveName($node->class);
@@ -74,40 +80,48 @@ public function processNode(Node $node, Scope $scope): array
7480

7581
$instanceofType = $this->treatPhpDocTypesAsCertain ? $scope->getType($node) : $scope->getNativeType($node);
7682
if (!$instanceofType instanceof ConstantBooleanType) {
83+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $node);
7784
return [];
7885
}
7986

8087
$addTip = function (RuleErrorBuilder $ruleErrorBuilder) use ($scope, $node): RuleErrorBuilder {
8188
if (!$this->treatPhpDocTypesAsCertain) {
82-
return $ruleErrorBuilder;
89+
return $this->possiblyImpureTipHelper->addTip($scope, $node, $ruleErrorBuilder);
8390
}
8491

8592
$instanceofTypeWithoutPhpDocs = $scope->getNativeType($node);
8693
if ($instanceofTypeWithoutPhpDocs instanceof ConstantBooleanType) {
87-
return $ruleErrorBuilder;
94+
return $this->possiblyImpureTipHelper->addTip($scope, $node, $ruleErrorBuilder);
8895
}
8996

9097
if (!$this->treatPhpDocTypesAsCertainTip) {
91-
return $ruleErrorBuilder;
98+
return $this->possiblyImpureTipHelper->addTip($scope, $node, $ruleErrorBuilder);
9299
}
93100

94-
return $ruleErrorBuilder->treatPhpDocTypesAsCertainTip();
101+
$ruleErrorBuilder = $ruleErrorBuilder->treatPhpDocTypesAsCertainTip();
102+
103+
return $this->possiblyImpureTipHelper->addTip($scope, $node, $ruleErrorBuilder);
95104
};
96105

97106
if (!$instanceofType->getValue()) {
98107
$exprType = $this->treatPhpDocTypesAsCertain ? $scope->getType($node->expr) : $scope->getNativeType($node->expr);
99108

100-
return [
101-
$addTip(RuleErrorBuilder::message(sprintf(
102-
'Instanceof between %s and %s will always evaluate to false.',
103-
$exprType->describe(VerbosityLevel::typeOnly()),
104-
$classType->describe(VerbosityLevel::getRecommendedLevelByType($classType)),
105-
)))->identifier('instanceof.alwaysFalse')->build(),
106-
];
109+
$ruleError = $addTip(RuleErrorBuilder::message(sprintf(
110+
'Instanceof between %s and %s will always evaluate to false.',
111+
$exprType->describe(VerbosityLevel::typeOnly()),
112+
$classType->describe(VerbosityLevel::getRecommendedLevelByType($classType)),
113+
)))->identifier('instanceof.alwaysFalse')->build();
114+
if ($scope->isInTrait()) {
115+
$this->constantConditionInTraitHelper->emitError(self::class, $scope, $node, false, $ruleError);
116+
return [];
117+
}
118+
119+
return [$ruleError];
107120
}
108121

109122
$isLast = $node->getAttribute(LastConditionVisitor::ATTRIBUTE_NAME);
110123
if ($isLast === true && !$this->reportAlwaysTrueInLastCondition) {
124+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $node);
111125
return [];
112126
}
113127

@@ -123,7 +137,13 @@ public function processNode(Node $node, Scope $scope): array
123137

124138
$errorBuilder->identifier('instanceof.alwaysTrue');
125139

126-
return [$errorBuilder->build()];
140+
$ruleError = $errorBuilder->build();
141+
if ($scope->isInTrait()) {
142+
$this->constantConditionInTraitHelper->emitError(self::class, $scope, $node, true, $ruleError);
143+
return [];
144+
}
145+
146+
return [$ruleError];
127147
}
128148

129149
}

‎src/Rules/Comparison/BooleanAndConstantConditionRule.php‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
namespace PHPStan\Rules\Comparison;
44

55
use PhpParser\Node;
6+
use PHPStan\Analyser\CollectedDataEmitter;
7+
use PHPStan\Analyser\NodeCallbackInvoker;
68
use PHPStan\Analyser\Scope;
79
use PHPStan\DependencyInjection\AutowiredParameter;
810
use PHPStan\DependencyInjection\RegisteredRule;
@@ -24,6 +26,7 @@ final class BooleanAndConstantConditionRule implements Rule
2426
public function __construct(
2527
private ConstantConditionRuleHelper $helper,
2628
private PossiblyImpureTipHelper $possiblyImpureTipHelper,
29+
private ConstantConditionInTraitHelper $constantConditionInTraitHelper,
2730
#[AutowiredParameter]
2831
private bool $treatPhpDocTypesAsCertain,
2932
#[AutowiredParameter]
@@ -41,14 +44,16 @@ public function getNodeType(): string
4144

4245
public function processNode(
4346
Node $node,
44-
Scope $scope,
47+
Scope&NodeCallbackInvoker&CollectedDataEmitter $scope,
4548
): array
4649
{
4750
$errors = [];
4851
$originalNode = $node->getOriginalNode();
4952
$nodeText = $originalNode->getOperatorSigil();
5053
$leftType = $this->helper->getBooleanType($scope, $originalNode->left);
5154
$identifierType = $originalNode instanceof Node\Expr\BinaryOp\BooleanAnd ? 'booleanAnd' : 'logicalAnd';
55+
$isInTrait = $scope->isInTrait();
56+
$hasLeftOrRightError = false;
5257
if ($leftType instanceof ConstantBooleanType) {
5358
$addTipLeft = function (RuleErrorBuilder $ruleErrorBuilder) use ($scope, $originalNode): RuleErrorBuilder {
5459
if (!$this->treatPhpDocTypesAsCertain) {
@@ -80,8 +85,18 @@ public function processNode(
8085
if ($leftType->getValue() && $isLast === false && !$this->reportAlwaysTrueInLastCondition) {
8186
$errorBuilder->tip('Remove remaining cases below this one and this error will disappear too.');
8287
}
83-
$errors[] = $errorBuilder->build();
88+
$ruleError = $errorBuilder->build();
89+
$hasLeftOrRightError = true;
90+
if ($isInTrait) {
91+
$this->constantConditionInTraitHelper->emitError(self::class, $scope, $originalNode->left, $leftType->getValue(), $ruleError);
92+
} else {
93+
$errors[] = $ruleError;
94+
}
95+
} else {
96+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $originalNode->left);
8497
}
98+
} else {
99+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $originalNode->left);
85100
}
86101

87102
$rightScope = $node->getRightScope();
@@ -123,11 +138,21 @@ public function processNode(
123138
if ($rightType->getValue() && $isLast === false && !$this->reportAlwaysTrueInLastCondition) {
124139
$errorBuilder->tip('Remove remaining cases below this one and this error will disappear too.');
125140
}
126-
$errors[] = $errorBuilder->build();
141+
$ruleError = $errorBuilder->build();
142+
$hasLeftOrRightError = true;
143+
if ($isInTrait) {
144+
$this->constantConditionInTraitHelper->emitError(self::class, $scope, $originalNode->right, $rightType->getValue(), $ruleError);
145+
} else {
146+
$errors[] = $ruleError;
147+
}
148+
} else {
149+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $originalNode->right);
127150
}
151+
} else {
152+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $originalNode->right);
128153
}
129154

130-
if (count($errors) === 0 && !$scope->isInFirstLevelStatement()) {
155+
if (count($errors) === 0 && !$hasLeftOrRightError && !$scope->isInFirstLevelStatement()) {
131156
$nodeType = $this->treatPhpDocTypesAsCertain ? $scope->getType($originalNode) : $scope->getNativeType($originalNode);
132157
if ($nodeType instanceof ConstantBooleanType) {
133158
$addTip = function (RuleErrorBuilder $ruleErrorBuilder) use ($scope, $originalNode): RuleErrorBuilder {
@@ -161,8 +186,17 @@ public function processNode(
161186

162187
$errorBuilder->identifier(sprintf('%s.always%s', $identifierType, $nodeType->getValue() ? 'True' : 'False'));
163188

164-
$errors[] = $errorBuilder->build();
189+
$ruleError = $errorBuilder->build();
190+
if ($isInTrait) {
191+
$this->constantConditionInTraitHelper->emitError(self::class, $scope, $originalNode, $nodeType->getValue(), $ruleError);
192+
} else {
193+
$errors[] = $ruleError;
194+
}
195+
} else {
196+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $originalNode);
165197
}
198+
} else {
199+
$this->constantConditionInTraitHelper->emitNoError(self::class, $scope, $originalNode);
166200
}
167201
}
168202

0 commit comments

Comments
 (0)