Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance supported cases for 'remove redundant operators' #72522

Merged
merged 2 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,23 @@ public bool M1(bool x)
[Fact]
public async Task TestSimpleCaseForEqualsFalse_NoDiagnostics()
{
var code = """
await VerifyCS.VerifyCodeFixAsync("""
public class C
{
public bool M1(bool x)
{
return x == false;
return x [|==|] false;
}
}
""";
await VerifyCS.VerifyAnalyzerAsync(code);
""", """
public class C
{
public bool M1(bool x)
{
return !x;
}
}
""");
}

[Fact]
Expand Down Expand Up @@ -83,16 +90,23 @@ public bool M1(bool x)
[Fact]
public async Task TestSimpleCaseForNotEqualsTrue_NoDiagnostics()
{
var code = """
await VerifyCS.VerifyCodeFixAsync("""
public class C
{
public bool M1(bool x)
{
return x != true;
return x [|!=|] true;
}
}
""";
await VerifyCS.VerifyAnalyzerAsync(code);
""", """
public class C
{
public bool M1(bool x)
{
return !x;
}
}
""");
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,13 @@

namespace Microsoft.CodeAnalysis.RemoveRedundantEquality;

internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: AbstractBuiltInCodeStyleDiagnosticAnalyzer(
IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId,
EnforceOnBuildValues.RemoveRedundantEquality,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
private readonly ISyntaxFacts _syntaxFacts;

protected AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: base(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId,
EnforceOnBuildValues.RemoveRedundantEquality,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
}

public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;

Expand All @@ -35,19 +28,15 @@ private void AnalyzeBinaryOperator(OperationAnalysisContext context)
if (ShouldSkipAnalysis(context, notification: null))
return;

// We shouldn't report diagnostic on overloaded operator as the behavior can change.
var operation = (IBinaryOperation)context.Operation;
if (operation.OperatorMethod is not null)
{
// We shouldn't report diagnostic on overloaded operator as the behavior can change.
return;
}

if (operation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals))
{
return;
}

if (!_syntaxFacts.IsBinaryExpression(operation.Syntax))
if (!syntaxFacts.IsBinaryExpression(operation.Syntax))
{
return;
}
Expand All @@ -56,9 +45,7 @@ private void AnalyzeBinaryOperator(OperationAnalysisContext context)
var leftOperand = operation.LeftOperand;

if (rightOperand.Type is null || leftOperand.Type is null)
{
return;
}

if (rightOperand.Type.SpecialType != SpecialType.System_Boolean ||
leftOperand.Type.SpecialType != SpecialType.System_Boolean)
Expand All @@ -67,34 +54,43 @@ private void AnalyzeBinaryOperator(OperationAnalysisContext context)
}

var isOperatorEquals = operation.OperatorKind == BinaryOperatorKind.Equals;
_syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _);
syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _);

var properties = ImmutableDictionary.CreateBuilder<string, string?>();
if (TryGetLiteralValue(rightOperand) == isOperatorEquals)
if (TryGetLiteralValue(rightOperand) is bool rightBool)
{
properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Right);
if (rightBool != isOperatorEquals)
properties.Add(RedundantEqualityConstants.Negate, RedundantEqualityConstants.Negate);
}
else if (TryGetLiteralValue(leftOperand) == isOperatorEquals)
else if (TryGetLiteralValue(leftOperand) is bool leftBool)
{
properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Left);
if (leftBool != isOperatorEquals)
properties.Add(RedundantEqualityConstants.Negate, RedundantEqualityConstants.Negate);
}

if (properties.Count == 1)
else
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor,
operatorToken.GetLocation(),
additionalLocations: [operation.Syntax.GetLocation()],
properties: properties.ToImmutable()));
return;
}

context.ReportDiagnostic(Diagnostic.Create(Descriptor,
operatorToken.GetLocation(),
additionalLocations: [operation.Syntax.GetLocation()],
properties: properties.ToImmutable()));

return;

static bool? TryGetLiteralValue(IOperation operand)
{
// Make sure we only simplify literals to avoid changing
// something like the following example:
// const bool Activated = true; ... if (state == Activated)
if (operand.ConstantValue.HasValue && operand.Kind == OperationKind.Literal &&
operand.ConstantValue.Value is bool constValue)
if (operand is
{
Kind: OperationKind.Literal,
ConstantValue: { HasValue: true, Value: bool constValue }
})
{
return constValue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ internal static class RedundantEqualityConstants
public const string RedundantSide = nameof(RedundantSide);
public const string Left = nameof(Left);
public const string Right = nameof(Right);
public const string Negate = nameof(Negate);
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,54 +21,49 @@ namespace Microsoft.CodeAnalysis.RemoveRedundantEquality;
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared]
[method: ImportingConstructor]
[method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
internal sealed class RemoveRedundantEqualityCodeFixProvider() : SyntaxEditorBasedCodeFixProvider
internal sealed class RemoveRedundantEqualityCodeFixProvider() : ForkingSyntaxEditorBasedCodeFixProvider<SyntaxNode>
{
public override ImmutableArray<string> FixableDiagnosticIds => [IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId];

public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
RegisterCodeFix(context, AnalyzersResources.Remove_redundant_equality, nameof(AnalyzersResources.Remove_redundant_equality), diagnostic);
}
protected override (string title, string equivalenceKey) GetTitleAndEquivalenceKey(CodeFixContext context)
=> (AnalyzersResources.Remove_redundant_equality, nameof(AnalyzersResources.Remove_redundant_equality));

return Task.CompletedTask;
}

protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
protected override async Task FixAsync(
Document document,
SyntaxEditor editor,
CodeActionOptionsProvider fallbackOptions,
SyntaxNode node,
ImmutableDictionary<string, string?> properties,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();

var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);

foreach (var diagnostic in diagnostics)
editor.ReplaceNode(node, WithElasticTrailingTrivia(RewriteNode()));

return;

SyntaxNode RewriteNode()
{
var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
// This should happen only in error cases.
if (!syntaxFacts.IsBinaryExpression(node))
return node;

editor.ReplaceNode(node, (n, _) =>
{
if (!syntaxFacts.IsBinaryExpression(n))
{
// This should happen only in error cases.
return n;
}
syntaxFacts.GetPartsOfBinaryExpression(node, out var left, out var right);
var rewritten =
properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right ? left :
properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left ? right : node;

syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right);
if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right)
{
return WithElasticTrailingTrivia(left);
}
else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left)
{
return WithElasticTrailingTrivia(right);
}
if (properties.ContainsKey(RedundantEqualityConstants.Negate))
rewritten = generator.Negate(generatorInternal, rewritten, semanticModel, cancellationToken);

return n;
});
return rewritten;
}

return;

static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node)
{
return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,19 @@ End Module

<Fact>
Public Async Function TestSimpleCaseForEqualsFalse_NoDiagnostics() As Task
Dim code = "
Await VerifyVB.VerifyCodeFixAsync("
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x = False
Return x [|=|] False
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
", "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return Not x
End Function
End Module
")
End Function

<Fact>
Expand All @@ -60,14 +65,19 @@ End Module

<Fact>
Public Async Function TestSimpleCaseForNotEqualsTrue_NoDiagnostics() As Task
Dim code = "
Await VerifyVB.VerifyCodeFixAsync("
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x <> True
Return x [|<>|] True
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
", "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return Not x
End Function
End Module
")
End Function

<Fact>
Expand Down
Loading