-
-
Notifications
You must be signed in to change notification settings - Fork 63
MA0169 - Detect equality operators that should be replaced with Equals method #805
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
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| # MA0169 - Use Equals method instead of operator | ||
|
|
||
| Using `==` or `!=` operator on a type that overrides `Equals` method, but not the operators, is not recommended. | ||
|
|
||
| ````c# | ||
| Sample a = default; | ||
| Sample b = default; | ||
|
|
||
| _ = a == b; // ok as Equals is not overridden | ||
|
|
||
| class Sample { } | ||
| ```` | ||
|
|
||
| ````c# | ||
| Sample a = default; | ||
| Sample b = default; | ||
|
|
||
| _ = a == b; // ok the equality operator are defined | ||
|
|
||
|
|
||
| class Sample | ||
| { | ||
| public static bool operator ==(Sample a, Sample b) => true; | ||
| public static bool operator !=(Sample a, Sample b) => false; | ||
| public override bool Equals(object obj) => true; | ||
| public override int GetHashCode() => 0; | ||
| } | ||
| ```` | ||
|
|
||
| ````c# | ||
| Sample a = default; | ||
| Sample b = default; | ||
|
|
||
| _ = a.Equals(b); // ok | ||
| _ = object.Reference`Equals(a, b); // ok | ||
| _ = a == b; // non-compliant | ||
|
|
||
| class Sample | ||
| { | ||
| public override bool Equals(object obj) => true; | ||
| public override int GetHashCode() => 0; | ||
| } | ||
| ```` | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
94 changes: 94 additions & 0 deletions
94
src/Meziantou.Analyzer/Rules/UseEqualsMethodInsteadOfOperatorAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Linq; | ||
| using Meziantou.Analyzer.Internals; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace Meziantou.Analyzer.Rules; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class UseEqualsMethodInsteadOfOperatorAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| private static readonly DiagnosticDescriptor Rule = new( | ||
| RuleIdentifiers.UseEqualsMethodInsteadOfOperator, | ||
| title: "Use Equals method instead of operator", | ||
| messageFormat: "Use Equals method instead of == or != operator", | ||
| RuleCategories.Design, | ||
| DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true, | ||
| description: "", | ||
| helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.UseEqualsMethodInsteadOfOperator)); | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
|
||
| context.RegisterCompilationStartAction(context => | ||
| { | ||
| if (context.Compilation.GetSpecialType(SpecialType.System_Object).GetMembers("Equals").FirstOrDefault() is not IMethodSymbol objectEqualsSymbol) | ||
| return; | ||
|
|
||
| context.RegisterOperationAction(context => AnalyzerBinaryOperation(context, objectEqualsSymbol), OperationKind.Binary); | ||
| }); | ||
| } | ||
|
|
||
| private static void AnalyzerBinaryOperation(OperationAnalysisContext context, IMethodSymbol objectEqualsSymbol) | ||
| { | ||
| var operation = (IBinaryOperation)context.Operation; | ||
| if (operation is { OperatorKind: BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals, OperatorMethod: null }) | ||
| { | ||
| if (IsNull(operation.LeftOperand) || IsNull(operation.RightOperand)) | ||
| return; | ||
|
|
||
| var leftType = operation.LeftOperand.UnwrapImplicitConversionOperations().Type; | ||
| if (operation.IsLifted) | ||
| { | ||
| leftType = leftType.GetUnderlyingNullableTypeOrSelf(); | ||
| } | ||
|
|
||
| if (leftType is null) | ||
| return; | ||
|
|
||
| if (leftType.IsValueType) | ||
| return; | ||
|
|
||
| switch (leftType.SpecialType) | ||
| { | ||
| case SpecialType.System_Boolean: | ||
| case SpecialType.System_Char: | ||
| case SpecialType.System_DateTime: | ||
| case SpecialType.System_SByte: | ||
| case SpecialType.System_Int16: | ||
| case SpecialType.System_Int32: | ||
| case SpecialType.System_Int64: | ||
| case SpecialType.System_IntPtr: | ||
| case SpecialType.System_Byte: | ||
| case SpecialType.System_UInt16: | ||
| case SpecialType.System_UInt32: | ||
| case SpecialType.System_UInt64: | ||
| case SpecialType.System_UIntPtr: | ||
| case SpecialType.System_Single: | ||
| case SpecialType.System_Double: | ||
| case SpecialType.System_Decimal: | ||
| case SpecialType.System_Enum: | ||
| case SpecialType.System_Object: | ||
| case SpecialType.System_String: | ||
| return; | ||
| } | ||
|
|
||
| // Check if the type have an Equals method | ||
| var overrideEqualsSymbol = leftType.GetMembers("Equals").OfType<IMethodSymbol>().FirstOrDefault(m => m.IsOrOverrideMethod(objectEqualsSymbol)); | ||
meziantou marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (overrideEqualsSymbol is not null) | ||
| { | ||
| context.ReportDiagnostic(Rule, operation); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public static bool IsNull(IOperation operation) | ||
| => operation.UnwrapConversionOperations() is ILiteralOperation { ConstantValue: { HasValue: true, Value: null } }; | ||
| } | ||
86 changes: 86 additions & 0 deletions
86
tests/Meziantou.Analyzer.Test/Rules/UseEqualsMethodInsteadOfOperatorAnalyzerTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| using System.Threading.Tasks; | ||
| using Meziantou.Analyzer.Rules; | ||
| using TestHelper; | ||
| using Xunit; | ||
|
|
||
| namespace Meziantou.Analyzer.Test.Rules; | ||
| public class UseEqualsMethodInsteadOfOperatorAnalyzerTests | ||
| { | ||
| private static ProjectBuilder CreateProjectBuilder() | ||
| { | ||
| return new ProjectBuilder() | ||
| .WithTargetFramework(Helpers.TargetFramework.Net9_0) | ||
| .WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication) | ||
| .WithAnalyzer<UseEqualsMethodInsteadOfOperatorAnalyzer>(); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("System.Net.IPAddress")] | ||
| public async Task Report_EqualsOperator(string type) | ||
| { | ||
| await CreateProjectBuilder() | ||
| .WithSourceCode($$""" | ||
| {{type}} a = null; | ||
| {{type}} b = null; | ||
| _ = [|a == b|]; | ||
| """) | ||
| .ValidateAsync(); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("char")] | ||
| [InlineData("string")] | ||
| [InlineData("sbyte")] | ||
| [InlineData("byte")] | ||
| [InlineData("short")] | ||
| [InlineData("ushort")] | ||
| [InlineData("int")] | ||
| [InlineData("uint")] | ||
| [InlineData("long")] | ||
| [InlineData("ulong")] | ||
| [InlineData("System.Int128")] | ||
| [InlineData("System.UInt128")] | ||
| [InlineData("System.Half")] | ||
| [InlineData("float")] | ||
| [InlineData("double")] | ||
| [InlineData("decimal")] | ||
| [InlineData("System.DayOfWeek")] | ||
| public async Task NoReport_EqualsOperator(string type) | ||
| { | ||
| await CreateProjectBuilder() | ||
| .WithSourceCode($$""" | ||
| {{type}} a = default; | ||
| {{type}} b = default; | ||
| _ = a == b; | ||
| """) | ||
| .ValidateAsync(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ClassWithoutEqualsMethod() | ||
| { | ||
| await CreateProjectBuilder() | ||
| .WithSourceCode($$""" | ||
| Sample a = default; | ||
| Sample b = default; | ||
| _ = a == b; | ||
|
|
||
| class Sample {} | ||
| """) | ||
| .ValidateAsync(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RecordWithoutEqualsMethod() | ||
| { | ||
| await CreateProjectBuilder() | ||
| .WithSourceCode($$""" | ||
| Sample a = default; | ||
| Sample b = default; | ||
| _ = a == b; // Operator is implemented by the record | ||
|
|
||
| record Sample {} | ||
| """) | ||
| .ValidateAsync(); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.