-
-
Notifications
You must be signed in to change notification settings - Fork 65
Add MA0193 Round mode analyzer and code fixes #1104
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
Merged
Changes from 3 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,43 @@ | ||
| # MA0193 - Use an overload with a MidpointRounding argument | ||
| <!-- sources --> | ||
| Sources: [UseAnOverloadThatHasMidpointRoundingAnalyzer.cs](https://github.com/meziantou/Meziantou.Analyzer/blob/main/src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasMidpointRoundingAnalyzer.cs), [UseAnOverloadThatHasMidpointRoundingFixer.cs](https://github.com/meziantou/Meziantou.Analyzer/blob/main/src/Meziantou.Analyzer.CodeFixers/Rules/UseAnOverloadThatHasMidpointRoundingFixer.cs) | ||
| <!-- sources --> | ||
|
|
||
| `Round` overloads without a `MidpointRounding` argument use the default midpoint behavior (`ToEven`), which can be surprising. Prefer an overload that specifies the rounding mode explicitly. | ||
|
|
||
| This rule reports calls to: | ||
|
|
||
| - `Math.Round(...)` | ||
| - `MathF.Round(...)` | ||
| - `decimal.Round(...)` | ||
| - `IFloatingPoint<TSelf>.Round(...)` and implementations of those members | ||
|
|
||
| ## Non-compliant code | ||
|
|
||
| ````csharp | ||
| class Sample | ||
| { | ||
| void M(decimal value) | ||
| { | ||
| _ = Math.Round(2.5); | ||
| _ = MathF.Round(2.5f); | ||
| _ = decimal.Round(value, 2); | ||
| } | ||
| } | ||
| ```` | ||
|
|
||
| ## Compliant code | ||
|
|
||
| ````csharp | ||
| class Sample | ||
| { | ||
| void M(decimal value) | ||
| { | ||
| _ = Math.Round(2.5, MidpointRounding.AwayFromZero); | ||
| _ = MathF.Round(2.5f, MidpointRounding.AwayFromZero); | ||
| _ = decimal.Round(value, 2, MidpointRounding.AwayFromZero); | ||
| } | ||
| } | ||
| ```` | ||
|
|
||
| The code fix suggests one action for each available `System.MidpointRounding` enum value. | ||
118 changes: 118 additions & 0 deletions
118
src/Meziantou.Analyzer.CodeFixers/Rules/UseAnOverloadThatHasMidpointRoundingFixer.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,118 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Linq; | ||
| using Meziantou.Analyzer.Internals; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace Meziantou.Analyzer.Rules; | ||
|
|
||
| [ExportCodeFixProvider(LanguageNames.CSharp), Shared] | ||
| public sealed class UseAnOverloadThatHasMidpointRoundingFixer : CodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(RuleIdentifiers.UseAnOverloadThatHasMidpointRounding); | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true); | ||
| if (nodeToFix is null) | ||
| return; | ||
|
|
||
| var invocationExpression = nodeToFix as InvocationExpressionSyntax ?? nodeToFix.FirstAncestorOrSelf<InvocationExpressionSyntax>(); | ||
| if (invocationExpression is null) | ||
| return; | ||
|
|
||
| var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (semanticModel is null) | ||
| return; | ||
|
|
||
| if (semanticModel.GetOperation(invocationExpression, context.CancellationToken) is not IInvocationOperation invocationOperation) | ||
| return; | ||
|
|
||
| var midpointRoundingSymbol = semanticModel.Compilation.GetBestTypeByMetadataName("System.MidpointRounding"); | ||
| if (midpointRoundingSymbol is null) | ||
| return; | ||
|
|
||
| if (!TryGetMidpointRoundingParameterInfo(semanticModel.Compilation, invocationOperation, midpointRoundingSymbol, out var parameterInfo)) | ||
| return; | ||
|
|
||
| foreach (var midpointRoundingMember in midpointRoundingSymbol.GetMembers().OfType<IFieldSymbol>()) | ||
| { | ||
| if (midpointRoundingMember is { IsImplicitlyDeclared: true, Name: "value__" }) | ||
| continue; | ||
|
|
||
| if (!midpointRoundingMember.HasConstantValue) | ||
| continue; | ||
|
|
||
| var midpointRoundingMemberName = midpointRoundingMember.Name; | ||
| var title = "Add MidpointRounding." + midpointRoundingMemberName; | ||
| var codeAction = CodeAction.Create( | ||
| title, | ||
| ct => AddMidpointRounding(context.Document, invocationExpression, parameterInfo, midpointRoundingSymbol, midpointRoundingMemberName, ct), | ||
| equivalenceKey: title); | ||
|
|
||
| context.RegisterCodeFix(codeAction, context.Diagnostics); | ||
| } | ||
| } | ||
|
|
||
| private static bool TryGetMidpointRoundingParameterInfo(Compilation compilation, IInvocationOperation invocationOperation, INamedTypeSymbol midpointRoundingSymbol, out AdditionalParameterInfo parameterInfo) | ||
| { | ||
| var overloadFinder = new OverloadFinder(compilation); | ||
| var overload = overloadFinder.FindOverloadWithAdditionalParameterOfType(invocationOperation, new OverloadOptions(IncludeObsoleteMembers: false, AllowOptionalParameters: true), [midpointRoundingSymbol]); | ||
| if (overload is null) | ||
| { | ||
| parameterInfo = default; | ||
| return false; | ||
| } | ||
|
|
||
| for (var i = 0; i < overload.Parameters.Length; i++) | ||
| { | ||
| if (overload.Parameters[i].Type.IsEqualTo(midpointRoundingSymbol)) | ||
| { | ||
| parameterInfo = new AdditionalParameterInfo(i, overload.Parameters[i].Name); | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| parameterInfo = default; | ||
| return false; | ||
| } | ||
|
|
||
| private static async Task<Document> AddMidpointRounding(Document document, InvocationExpressionSyntax invocationExpression, AdditionalParameterInfo parameterInfo, INamedTypeSymbol midpointRoundingSymbol, string midpointRoundingMember, CancellationToken cancellationToken) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
| var generator = editor.Generator; | ||
|
|
||
| var midpointRoundingExpression = generator.MemberAccessExpression( | ||
| generator.TypeExpression(midpointRoundingSymbol, addImport: true), | ||
| midpointRoundingMember); | ||
|
|
||
| var newArgument = (ArgumentSyntax)generator.Argument(midpointRoundingExpression); | ||
|
|
||
| InvocationExpressionSyntax newInvocation; | ||
| if (parameterInfo.ParameterIndex > invocationExpression.ArgumentList.Arguments.Count) | ||
| { | ||
| var namedArgument = (ArgumentSyntax)generator.Argument(parameterInfo.ParameterName, RefKind.None, midpointRoundingExpression); | ||
| var newArguments = invocationExpression.ArgumentList.Arguments.Add(namedArgument); | ||
| newInvocation = invocationExpression.WithArgumentList(SyntaxFactory.ArgumentList(newArguments)); | ||
| } | ||
| else | ||
| { | ||
| var newArguments = invocationExpression.ArgumentList.Arguments.Insert(parameterInfo.ParameterIndex, newArgument); | ||
| newInvocation = invocationExpression.WithArgumentList(SyntaxFactory.ArgumentList(newArguments)); | ||
| } | ||
|
|
||
| editor.ReplaceNode(invocationExpression, newInvocation); | ||
| return editor.GetChangedDocument(); | ||
| } | ||
|
|
||
| private readonly record struct AdditionalParameterInfo(int ParameterIndex, string? ParameterName); | ||
| } |
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
121 changes: 121 additions & 0 deletions
121
src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasMidpointRoundingAnalyzer.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,121 @@ | ||
| 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 UseAnOverloadThatHasMidpointRoundingAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| private static readonly DiagnosticDescriptor Rule = new( | ||
| RuleIdentifiers.UseAnOverloadThatHasMidpointRounding, | ||
| title: "Use an overload with a MidpointRounding argument", | ||
| messageFormat: "Use an overload with a MidpointRounding argument", | ||
| RuleCategories.Usage, | ||
| DiagnosticSeverity.Info, | ||
| isEnabledByDefault: true, | ||
| description: "", | ||
| helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.UseAnOverloadThatHasMidpointRounding)); | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
|
||
| context.RegisterCompilationStartAction(context => | ||
| { | ||
| var midpointRoundingSymbol = context.Compilation.GetBestTypeByMetadataName("System.MidpointRounding"); | ||
| if (midpointRoundingSymbol is null) | ||
| return; | ||
|
|
||
| var ifloatingPointSymbol = context.Compilation.GetBestTypeByMetadataName("System.Numerics.IFloatingPoint`1"); | ||
| var mathSymbol = context.Compilation.GetBestTypeByMetadataName("System.Math"); | ||
| var mathFSymbol = context.Compilation.GetBestTypeByMetadataName("System.MathF"); | ||
| if (ifloatingPointSymbol is null && mathSymbol is null && mathFSymbol is null) | ||
| return; | ||
|
|
||
| context.RegisterOperationAction(context => AnalyzeInvocation(context, midpointRoundingSymbol, ifloatingPointSymbol, mathSymbol, mathFSymbol), OperationKind.Invocation); | ||
| }); | ||
| } | ||
|
|
||
| private static void AnalyzeInvocation( | ||
| OperationAnalysisContext context, | ||
| INamedTypeSymbol midpointRoundingSymbol, | ||
| INamedTypeSymbol? ifloatingPointSymbol, | ||
| INamedTypeSymbol? mathSymbol, | ||
| INamedTypeSymbol? mathFSymbol) | ||
| { | ||
| var operation = (IInvocationOperation)context.Operation; | ||
| var method = operation.TargetMethod; | ||
| if (!IsRoundMethodWithoutMidpointRounding(method, midpointRoundingSymbol)) | ||
| return; | ||
|
|
||
| if (method.ContainingType.IsEqualTo(mathSymbol) || method.ContainingType.IsEqualTo(mathFSymbol)) | ||
| { | ||
| context.ReportDiagnostic(Rule, operation); | ||
| return; | ||
| } | ||
|
|
||
| if (method.ContainingType.SpecialType is SpecialType.System_Decimal) | ||
| { | ||
| context.ReportDiagnostic(Rule, operation); | ||
| return; | ||
| } | ||
|
|
||
| if (IsIFloatingPointRoundMethod(method, midpointRoundingSymbol, ifloatingPointSymbol) || | ||
| IsIFloatingPointRoundImplementation(method, midpointRoundingSymbol, ifloatingPointSymbol)) | ||
| { | ||
| context.ReportDiagnostic(Rule, operation); | ||
| } | ||
| } | ||
|
|
||
| private static bool IsRoundMethodWithoutMidpointRounding(IMethodSymbol method, INamedTypeSymbol midpointRoundingSymbol) | ||
| { | ||
| return method.Name is "Round" && | ||
| !method.Parameters.Any(parameter => parameter.Type.IsEqualTo(midpointRoundingSymbol)); | ||
| } | ||
|
|
||
| private static bool IsIFloatingPointRoundMethod(IMethodSymbol method, INamedTypeSymbol midpointRoundingSymbol, INamedTypeSymbol? ifloatingPointSymbol) | ||
| { | ||
| if (ifloatingPointSymbol is null) | ||
| return false; | ||
|
|
||
| return IsRoundMethodWithoutMidpointRounding(method, midpointRoundingSymbol) && | ||
| method.ContainingType.OriginalDefinition.IsEqualTo(ifloatingPointSymbol); | ||
| } | ||
|
|
||
| private static bool IsIFloatingPointRoundImplementation(IMethodSymbol method, INamedTypeSymbol midpointRoundingSymbol, INamedTypeSymbol? ifloatingPointSymbol) | ||
| { | ||
| if (ifloatingPointSymbol is null || method.ContainingType is null) | ||
| return false; | ||
|
|
||
| foreach (var explicitImplementation in method.ExplicitInterfaceImplementations) | ||
| { | ||
| if (IsIFloatingPointRoundMethod(explicitImplementation, midpointRoundingSymbol, ifloatingPointSymbol)) | ||
| return true; | ||
| } | ||
|
|
||
| foreach (var interfaceType in method.ContainingType.AllInterfaces) | ||
| { | ||
| if (!interfaceType.OriginalDefinition.IsEqualTo(ifloatingPointSymbol)) | ||
| continue; | ||
|
|
||
| foreach (var interfaceMethod in interfaceType.GetMembers(method.Name).OfType<IMethodSymbol>()) | ||
| { | ||
| if (!IsIFloatingPointRoundMethod(interfaceMethod, midpointRoundingSymbol, ifloatingPointSymbol)) | ||
| continue; | ||
|
|
||
| var implementation = method.ContainingType.FindImplementationForInterfaceMember(interfaceMethod); | ||
| if (implementation is IMethodSymbol implementationMethod && implementationMethod.OriginalDefinition.IsEqualTo(method.OriginalDefinition)) | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
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.