/
UnusedReferencesAnalyzer.cs
127 lines (108 loc) · 4.8 KB
/
UnusedReferencesAnalyzer.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using HellBrick.Diagnostics.Utils;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace HellBrick.Diagnostics.UnusedReferences
{
[DiagnosticAnalyzer( LanguageNames.CSharp )]
public class UnusedReferencesAnalyzer : DiagnosticAnalyzer
{
private const string _diagnosticID = IDPrefix.Value + "UnusedReferences";
private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor( _diagnosticID, "Unused reference", "{0} reference is not used", "Architecture", DiagnosticSeverity.Info, true );
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( _rule );
public override void Initialize( AnalysisContext context )
{
context.ConfigureGeneratedCodeAnalysis( GeneratedCodeAnalysisFlags.None );
context.RegisterCompilationAction( FindUnusedReferences );
}
private void FindUnusedReferences( CompilationAnalysisContext context )
{
Debug.WriteLine( $"----------------------------------------" );
Debug.WriteLine( $"Analyzing {context.Compilation.AssemblyName}..." );
HashSet<AssemblyIdentity> compilationReferences = context.Compilation.ExternalReferences
.OfType<CompilationReference>()
.Select( r => r.Compilation.Assembly.Identity )
.ToHashSet();
try
{
using ( IEnumerator<SyntaxTree> syntaxTreeEnumerator = context.Compilation.SyntaxTrees.GetEnumerator() )
{
while ( compilationReferences.Count > 0 && syntaxTreeEnumerator.MoveNext() && !context.CancellationToken.IsCancellationRequested )
{
SyntaxTree syntaxTree = syntaxTreeEnumerator.Current;
SemanticModel semanticModel = context.Compilation.GetSemanticModel( syntaxTree );
ReferenceDiscarder referenceFinder = new ReferenceDiscarder( compilationReferences, syntaxTree, semanticModel, context.CancellationToken );
referenceFinder.DiscardUsedReferencesAsync().GetAwaiter().GetResult();
}
}
}
catch ( TaskCanceledException )
{
// ReferenceDiscarder can throw on cancellation if it occurs during getting the root.
}
// I've no idea when this happens, but if it does, it means we haven't discarded all the used references.
// Thus the results can't be trusted and we shouldn't report any diagnostics.
if ( context.CancellationToken.IsCancellationRequested )
return;
Debug.WriteLine( $"{compilationReferences.Count} unused references" );
foreach ( AssemblyIdentity assembly in compilationReferences )
context.ReportDiagnostic( Diagnostic.Create( _rule, null, assembly.Name ) );
}
private class ReferenceDiscarder : CSharpSyntaxWalker
{
private readonly HashSet<AssemblyIdentity> _references;
private readonly SemanticModel _semanticModel;
private readonly SyntaxTree _syntaxTree;
private readonly CancellationToken _cancellationToken;
public ReferenceDiscarder( HashSet<AssemblyIdentity> references, SyntaxTree syntaxTree, SemanticModel semanticModel, CancellationToken cancellationToken )
{
_references = references;
_syntaxTree = syntaxTree;
_semanticModel = semanticModel;
_cancellationToken = cancellationToken;
}
public async Task DiscardUsedReferencesAsync()
{
SyntaxNode root = await _syntaxTree.GetRootAsync( _cancellationToken ).ConfigureAwait( false );
Visit( root );
}
public override void Visit( SyntaxNode node )
{
if ( _references.Count == 0 || _cancellationToken.IsCancellationRequested )
return;
base.Visit( node );
}
public override void DefaultVisit( SyntaxNode node )
{
ISymbol symbol = _semanticModel.GetSymbolInfo( node ).Symbol;
TryDiscard( symbol );
ITypeSymbol returnTypeSymbol = ( symbol as IPropertySymbol )?.Type ?? ( symbol as IMethodSymbol )?.ReturnType;
TryDiscard( returnTypeSymbol );
ImmutableArray<ITypeSymbol> genericArgumentTypes = ( returnTypeSymbol as INamedTypeSymbol )?.TypeArguments ?? ImmutableArray<ITypeSymbol>.Empty;
foreach ( ITypeSymbol genericArgumentType in genericArgumentTypes )
TryDiscard( genericArgumentType );
base.DefaultVisit( node );
}
private void TryDiscard( ISymbol symbol )
{
AssemblyIdentity symbolAssembly = symbol?.ContainingAssembly?.Identity;
if ( symbolAssembly != null )
{
bool removed = _references.Remove( symbolAssembly );
if ( removed )
Debug.WriteLine( $"Removed {symbolAssembly} because of {symbol}" );
}
}
public override void VisitUsingDirective( UsingDirectiveSyntax node )
{
}
}
}
}