Skip to content

Commit

Permalink
Simplify '!(x is null)' to 'x is not null' (RCS1068)
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt committed Nov 12, 2021
1 parent c6845ed commit 9e6851b
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ private static ExpressionSyntax GetNewNode(PrefixUnaryExpressionSyntax logicalNo

return SyntaxRefactorings.ChangeInvokedMethodName(newNode, (memberAccessExpression.Name.Identifier.ValueText == "All") ? "Any" : "All");
}
case SyntaxKind.IsPatternExpression:
{
var isPatternExpression = (IsPatternExpressionSyntax)expression;

var pattern = (ConstantPatternSyntax)isPatternExpression.Pattern;

UnaryPatternSyntax newPattern = NotPattern(pattern.WithoutTrivia()).WithTriviaFrom(pattern);

return isPatternExpression.WithPattern(newPattern)
.PrependToLeadingTrivia(logicalNot.GetLeadingTrivia())
.AppendToTrailingTrivia(logicalNot.GetTrailingTrivia());
}
}

return null;
Expand Down
16 changes: 16 additions & 0 deletions src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,22 @@ private static void AnalyzeLogicalNotExpression(SyntaxNodeAnalysisContext contex
ReportDiagnostic();
}

break;
}
case SyntaxKind.IsPatternExpression:
{
if (((CSharpParseOptions)expression.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9)
{
var isPatternExpression = (IsPatternExpressionSyntax)expression;

if (isPatternExpression.Pattern is ConstantPatternSyntax constantPattern
&& constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression))
{
ReportDiagnostic();
}
}


break;
}
}
Expand Down
30 changes: 30 additions & 0 deletions src/Tests/Analyzers.Tests/RCS1068SimplifyLogicalNegationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,36 @@ void M()
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.SimplifyLogicalNegation)]
public async Task Test_IsNotNullPattern()
{
await VerifyDiagnosticAndFixAsync(@"
class C
{
void M()
{
string x = null;
if (
[|!(x is null)|] //x
) { }
}
}
", @"
class C
{
void M()
{
string x = null;
if (
x is not null //x
) { }
}
}
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.SimplifyLogicalNegation)]
public async Task TestNoDiagnostic_NotEqualsOperator()
{
Expand Down

0 comments on commit 9e6851b

Please sign in to comment.