Visual Studio代码分析器:查找零引用的类型

Rob*_*ade 6 c# roslyn visual-studio-2015

我正在尝试编写一个代码分析器,用于查找Visual Studio 2015解决方案中未从任何其他类型引用的类型.

我的问题是我无法弄清楚如何找到未引用类型的列表.

我已经尝试过DOM,你可以从下面的代码中看到,但我不知道在哪里导航,当前的代码似乎已经很慢了.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;

namespace AlphaSolutions.CodeAnalysis
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class ZeroReferencesDiagnosticAnalyzer : DiagnosticAnalyzer
    {
        public const string DiagnosticId = "ZeroReferences";

        private static DiagnosticDescriptor rule = new DiagnosticDescriptor(
            DiagnosticId,
            title: "Type has zero code references",
            messageFormat: "Type '{0}' is not referenced within the solution",
            category: "Naming",
            defaultSeverity: DiagnosticSeverity.Warning,
            isEnabledByDefault: true,
            description: "Type should have references."
            );

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                return ImmutableArray.Create(rule);
            }
        }

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterSyntaxNodeAction(this.AnalyzeSyntaxNode, SyntaxKind.ClassDeclaration);
        }

        private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext obj)
        {
            var classDeclaration = obj.Node as ClassDeclarationSyntax;
            if(classDeclaration == null)
            {
                return;
            }

            var identifierNameSyntaxes = classDeclaration
                .DescendantNodes()
                .OfType<IdentifierNameSyntax>()
                .ToArray()
                ;
            if (identifierNameSyntaxes.Length == 0)
            {
                return;
            }

            //SymbolFinder.FindReferencesAsync(namedTypeSymbol, solution);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也试过,SymbolFinder.FindReferencesAsync(namedTypeSymbol, solution)但我无法弄清楚如何获得参考Solution.

Microsoft Answers上的回复甚至建议使用程序集中的FindReferences方法Roslyn.Services.但看起来该程序集已被弃用.

我知道CodeLens我计算引用,访问该计数器可能是一个更好的解决方案,但我猜这是不可能的.

在任何人建议重复帖子之前,这篇文章不是这个,这个或这个的重复.我的帖子专门针对Roslyn编译器的分析器.

Jas*_*ski 5

Roslyn诊断分析仪目前不允许您进行解决方案范围(即跨项目)分析,这就是我们不为您提供Solution对象的原因.这部分是出于性能方面的考虑:如果你试图在任何地方调用FindReferencesAsync,那么你的CPU就会被严重盯住.对于CodeLens,我们使用了多少CPU的反馈,我们不希望10个诊断都消耗相同数量的CPU.(想象一下你可怜的笔记本电池...)

如果您对此更加有限,可以说找到他们所在项目中未使用的内部类型,请查看我们编写的这个分析器.