-
Notifications
You must be signed in to change notification settings - Fork 22
/
JsonParamBinderAnalyzer.cs
85 lines (65 loc) · 2.54 KB
/
JsonParamBinderAnalyzer.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
using System.Collections.Immutable;
using D2L.CodeStyle.Analyzers.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace D2L.CodeStyle.Analyzers.ApiUsage.JsonParamBinderAttribute {
[DiagnosticAnalyzer( LanguageNames.CSharp )]
public class JsonParamBinderAnalyzer : DiagnosticAnalyzer {
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
Diagnostics.ObsoleteJsonParamBinder,
Diagnostics.UnnecessaryAllowedListEntry
);
public override void Initialize( AnalysisContext context ) {
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis( GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics );
context.RegisterCompilationStartAction( RegisterAnalysis );
}
private void RegisterAnalysis( CompilationStartAnalysisContext context ) {
var attributeType = context.Compilation.GetTypeByMetadataName( "D2L.LP.Web.Rest.Attributes.JsonParamBinder" );
if( attributeType == null ) {
// Attribute is presumably not being used, so no need to register our analyzer
return;
}
AllowedTypeList allowedTypeList = AllowedTypeList.CreateFromAnalyzerOptions(
allowedListFileName: "LegacyJsonParamBinderAllowedList.txt",
analyzerOptions: context.Options
);
context.RegisterOperationAction(
ctx => AnalyzeAttribute( ctx, attributeType, allowedTypeList ),
OperationKind.Attribute
);
context.RegisterSymbolAction(
allowedTypeList.CollectSymbolIfContained,
SymbolKind.NamedType
);
context.RegisterCompilationEndAction(
allowedTypeList.ReportUnnecessaryEntries
);
}
private static void AnalyzeAttribute(
OperationAnalysisContext context,
INamedTypeSymbol jsonParamBinderT,
AllowedTypeList allowedList
) {
IAttributeOperation operation = ( IAttributeOperation )context.Operation;
if( operation.Operation is not IObjectCreationOperation attributeCreationOperation ) {
return;
}
if( !SymbolEqualityComparer.Default.Equals( jsonParamBinderT, attributeCreationOperation.Type ) ) {
return;
}
if( context.ContainingSymbol.ContainingType is not INamedTypeSymbol containingType ) {
return;
}
if( allowedList.Contains( containingType ) ) {
return;
}
Location location = operation.Syntax.GetLocation();
context.ReportDiagnostic(
Diagnostics.ObsoleteJsonParamBinder,
location
);
}
}
}