forked from dotnet/roslyn-analyzers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImmutableObjectMethodAnalyzer.cs
99 lines (87 loc) · 4.89 KB
/
ImmutableObjectMethodAnalyzer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// 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.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.Analyzers
{
using static CodeAnalysisDiagnosticsResources;
/// <summary>
/// RS1014: <inheritdoc cref="DoNotIgnoreReturnValueOnImmutableObjectMethodInvocationTitle"/>
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class ImmutableObjectMethodAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor DoNotIgnoreReturnValueDiagnosticRule = new(
DiagnosticIds.DoNotIgnoreReturnValueOnImmutableObjectMethodInvocation,
CreateLocalizableResourceString(nameof(DoNotIgnoreReturnValueOnImmutableObjectMethodInvocationTitle)),
CreateLocalizableResourceString(nameof(DoNotIgnoreReturnValueOnImmutableObjectMethodInvocationMessage)),
DiagnosticCategory.MicrosoftCodeAnalysisCorrectness,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: CreateLocalizableResourceString(nameof(DoNotIgnoreReturnValueOnImmutableObjectMethodInvocationDescription)),
customTags: WellKnownDiagnosticTagsExtensions.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(DoNotIgnoreReturnValueDiagnosticRule);
private const string SolutionFullName = @"Microsoft.CodeAnalysis.Solution";
private const string ProjectFullName = @"Microsoft.CodeAnalysis.Project";
private const string DocumentFullName = @"Microsoft.CodeAnalysis.Document";
private const string SyntaxNodeFullName = @"Microsoft.CodeAnalysis.SyntaxNode";
private const string CompilationFullName = @"Microsoft.CodeAnalysis.Compilation";
private static readonly ImmutableArray<string> s_immutableMethodNames = ImmutableArray.Create(
"Add",
"Remove",
"Replace",
"With");
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(context =>
{
var compilation = context.Compilation;
var builder = ImmutableArray.CreateBuilder<INamedTypeSymbol>();
var provider = WellKnownTypeProvider.GetOrCreate(compilation);
AddIfNotNull(builder, provider.GetOrCreateTypeByMetadataName(SolutionFullName));
AddIfNotNull(builder, provider.GetOrCreateTypeByMetadataName(ProjectFullName));
AddIfNotNull(builder, provider.GetOrCreateTypeByMetadataName(DocumentFullName));
AddIfNotNull(builder, provider.GetOrCreateTypeByMetadataName(SyntaxNodeFullName));
AddIfNotNull(builder, provider.GetOrCreateTypeByMetadataName(CompilationFullName));
var immutableTypeSymbols = builder.ToImmutable();
if (immutableTypeSymbols.Length > 0)
{
context.RegisterOperationAction(context => AnalyzeInvocationForIgnoredReturnValue(context, immutableTypeSymbols), OperationKind.Invocation);
}
});
static void AddIfNotNull(ImmutableArray<INamedTypeSymbol>.Builder builder, INamedTypeSymbol? symbol)
{
if (symbol is not null)
{
builder.Add(symbol);
}
}
}
public static void AnalyzeInvocationForIgnoredReturnValue(OperationAnalysisContext context, ImmutableArray<INamedTypeSymbol> immutableTypeSymbols)
{
var invocation = (IInvocationOperation)context.Operation;
if (invocation.Parent is not IExpressionStatementOperation)
{
return;
}
// If the method doesn't start with something like "With" or "Replace", quit
string methodName = invocation.TargetMethod.Name;
if (!s_immutableMethodNames.Any(n => methodName.StartsWith(n, StringComparison.Ordinal)))
{
return;
}
// If we're not in one of the known immutable types, quit
if (invocation.GetReceiverType(context.Compilation, beforeConversion: false, context.CancellationToken) is INamedTypeSymbol type
&& type.GetBaseTypesAndThis().Any(immutableTypeSymbols.Contains))
{
context.ReportDiagnostic(invocation.CreateDiagnostic(DoNotIgnoreReturnValueDiagnosticRule, type.Name, methodName));
}
}
}
}