Skip to content

Commit

Permalink
Do not suggest passing IFormatProvider to certain Convert methods (#7244
Browse files Browse the repository at this point in the history
)

* Do not suggest passing IFormatProvider to certain Convert methods

* Implement PR suggestions
  • Loading branch information
CollinAlpert committed Aug 30, 2024
1 parent 68eda2d commit 372f0d4
Show file tree
Hide file tree
Showing 2 changed files with 551 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
Expand Down Expand Up @@ -151,6 +152,25 @@ protected override void InitializeWorker(CompilationStartAnalysisContext context

var guidParseMethods = guidType?.GetMembers("Parse") ?? ImmutableArray<ISymbol>.Empty;

var convertType = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConvert);
ImmutableHashSet<IMethodSymbol> superfluousFormatProviderOverloads = ImmutableHashSet<IMethodSymbol>.Empty;
if (convertType != null)
{
superfluousFormatProviderOverloads = convertType.GetMembers(nameof(Convert.ToString))
.OfType<IMethodSymbol>()
.Where(m => m.Parameters is [{ Type.SpecialType: SpecialType.System_String or SpecialType.System_Boolean or SpecialType.System_Char }, var possibleFormatProvider]
&& possibleFormatProvider.Type.Equals(iformatProviderType, SymbolEqualityComparer.Default)).ToImmutableHashSet();
superfluousFormatProviderOverloads = superfluousFormatProviderOverloads
.Add(convertType.GetMembers(nameof(Convert.ToChar))
.OfType<IMethodSymbol>()
.First(m => m.Parameters is [{ Type.SpecialType: SpecialType.System_String }, var possibleFormatProvider]
&& possibleFormatProvider.Type.Equals(iformatProviderType, SymbolEqualityComparer.Default)))
.Add(convertType.GetMembers(nameof(Convert.ToBoolean))
.OfType<IMethodSymbol>()
.First(m => m.Parameters is [{ Type.SpecialType: SpecialType.System_String }, var possibleFormatProvider]
&& possibleFormatProvider.Type.Equals(iformatProviderType, SymbolEqualityComparer.Default)));
}

#endregion

context.RegisterOperationAction(oaContext =>
Expand Down Expand Up @@ -211,7 +231,7 @@ protected override void InitializeWorker(CompilationStartAnalysisContext context
// Sample message for IFormatProviderAlternateRule: Because the behavior of Convert.ToInt64(string) could vary based on the current user's locale settings,
// replace this call in IFormatProviderStringTest.TestMethod() with a call to Convert.ToInt64(string, IFormatProvider).
if (correctOverload != null)
if (correctOverload != null && !superfluousFormatProviderOverloads.Contains(correctOverload))
{
oaContext.ReportDiagnostic(
invocationExpression.Syntax.CreateDiagnostic(
Expand Down
Loading

0 comments on commit 372f0d4

Please sign in to comment.