|
| 1 | +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 2 | + |
| 3 | +using System.Collections.Immutable; |
| 4 | +using System.Linq; |
| 5 | +using Analyzer.Utilities; |
| 6 | +using Analyzer.Utilities.Extensions; |
| 7 | +using Microsoft.CodeAnalysis; |
| 8 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 9 | +using Microsoft.CodeAnalysis.Operations; |
| 10 | + |
| 11 | +namespace Microsoft.NetCore.Analyzers.Runtime |
| 12 | +{ |
| 13 | + /// <summary>CA1830: Prefer strongly-typed StringBuilder.Append overloads.</summary> |
| 14 | + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] |
| 15 | + public sealed class PreferTypedStringBuilderAppendOverloads : DiagnosticAnalyzer |
| 16 | + { |
| 17 | + internal const string RuleId = "CA1830"; |
| 18 | + |
| 19 | + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId, |
| 20 | + new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PreferTypedStringBuilderAppendOverloadsTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), |
| 21 | + new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PreferTypedStringBuilderAppendOverloadsMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), |
| 22 | + DiagnosticCategory.Performance, |
| 23 | + RuleLevel.IdeSuggestion, |
| 24 | + new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.PreferTypedStringBuilderAppendOverloadsDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)), |
| 25 | + isPortedFxCopRule: false, |
| 26 | + isDataflowRule: false); |
| 27 | + |
| 28 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); |
| 29 | + |
| 30 | + public sealed override void Initialize(AnalysisContext context) |
| 31 | + { |
| 32 | + context.EnableConcurrentExecution(); |
| 33 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 34 | + context.RegisterCompilationStartAction(compilationContext => |
| 35 | + { |
| 36 | + var typeProvider = WellKnownTypeProvider.GetOrCreate(compilationContext.Compilation); |
| 37 | + |
| 38 | + // Get the String and StringBuilder types. |
| 39 | + if (!typeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder, out var stringBuilderType)) |
| 40 | + { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + // Get all of the one-arg StringBuilder.Append methods and two-arg Insert methods. We skip over the object-based |
| 45 | + // overloads, as there's little benefit to removing such ToString calls. And we skip over arrays, to avoid |
| 46 | + // differences of behavior between Append(char[]) and Append(char[].ToString()). |
| 47 | + var appendMethods = stringBuilderType |
| 48 | + .GetMembers("Append") |
| 49 | + .OfType<IMethodSymbol>() |
| 50 | + .WhereAsArray(s => |
| 51 | + s.Parameters.Length == 1 && |
| 52 | + s.Parameters[0].Type.SpecialType != SpecialType.System_Object && |
| 53 | + s.Parameters[0].Type.TypeKind != TypeKind.Array); |
| 54 | + var insertMethods = stringBuilderType |
| 55 | + .GetMembers("Insert") |
| 56 | + .OfType<IMethodSymbol>() |
| 57 | + .WhereAsArray(s => |
| 58 | + s.Parameters.Length == 2 && |
| 59 | + s.Parameters[0].Type.SpecialType == SpecialType.System_Int32 && |
| 60 | + s.Parameters[1].Type.SpecialType != SpecialType.System_Object && |
| 61 | + s.Parameters[1].Type.TypeKind != TypeKind.Array); |
| 62 | + |
| 63 | + // Get the StringBuilder.Append(string)/Insert(int, string) method, for comparison purposes. |
| 64 | + var appendStringMethod = appendMethods.FirstOrDefault(s => |
| 65 | + s.Parameters[0].Type.SpecialType == SpecialType.System_String); |
| 66 | + var insertStringMethod = insertMethods.FirstOrDefault(s => |
| 67 | + s.Parameters[0].Type.SpecialType == SpecialType.System_Int32 && |
| 68 | + s.Parameters[1].Type.SpecialType == SpecialType.System_String); |
| 69 | + if (appendStringMethod is null || insertStringMethod is null) |
| 70 | + { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + // Check every invocation to see if it's StringBuilder.Append(string)/Insert(int, string). |
| 75 | + compilationContext.RegisterOperationAction(operationContext => |
| 76 | + { |
| 77 | + var invocation = (IInvocationOperation)operationContext.Operation; |
| 78 | + |
| 79 | + // We're interested in the string argument to Append(string) and Insert(int, string). |
| 80 | + // Get the argument position, or bail if this isn't either method. |
| 81 | + int stringParamIndex; |
| 82 | + if (appendStringMethod.Equals(invocation.TargetMethod)) |
| 83 | + { |
| 84 | + stringParamIndex = 0; |
| 85 | + } |
| 86 | + else if (insertStringMethod.Equals(invocation.TargetMethod)) |
| 87 | + { |
| 88 | + stringParamIndex = 1; |
| 89 | + } |
| 90 | + else |
| 91 | + { |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + // We're only interested if the string argument is a "string ToString()" call. |
| 96 | + if (invocation.Arguments.Length != stringParamIndex + 1 || |
| 97 | + !(invocation.Arguments[stringParamIndex] is IArgumentOperation argument) || |
| 98 | + !(argument.Value is IInvocationOperation toStringInvoke) || |
| 99 | + toStringInvoke.TargetMethod.Name != "ToString" || |
| 100 | + toStringInvoke.Type.SpecialType != SpecialType.System_String || |
| 101 | + toStringInvoke.TargetMethod.Parameters.Length != 0) |
| 102 | + { |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + // We're only interested if the receiver type of that ToString call has a corresponding strongly-typed overload. |
| 107 | + IMethodSymbol? stronglyTypedAppend = |
| 108 | + (stringParamIndex == 0 ? appendMethods : insertMethods) |
| 109 | + .FirstOrDefault(s => s.Parameters[stringParamIndex].Type.Equals(toStringInvoke.TargetMethod.ReceiverType)); |
| 110 | + if (stronglyTypedAppend is null) |
| 111 | + { |
| 112 | + return; |
| 113 | + } |
| 114 | + |
| 115 | + // Warn. |
| 116 | + operationContext.ReportDiagnostic(toStringInvoke.CreateDiagnostic(Rule)); |
| 117 | + }, OperationKind.Invocation); |
| 118 | + }); |
| 119 | + } |
| 120 | + } |
| 121 | +} |
0 commit comments