创建 Roslyn 分析器来检测 .cs 文件中的“Sleep()”方法调用

问题描述 投票:0回答:1

我问这个问题是延续这个一个

我想创建一个 roslyn 分析器来检测 .cs 文件中 sleep 方法的使用。有人可以帮我纠正我的代码吗?

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

namespace SleepCustomRule
{
 [DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SleepCustomRuleAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "SleepCheck";
    private const string Title = "Sleep function use in forbidden";
    private const string MessageFormat = "Remove this usage of sleep function";
    private const string Description = "Sleep function forbidden";
    private const string Category = "Usage";

    private static readonly ISet<string> Bannedfunctions = ImmutableHashSet.Create("Sleep");

    private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, 
        DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);


    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);


    public override void Initialize(AnalysisContext context)
    {
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName);
    }


    private static void AnalyzeNode(SymbolAnalysisContext context)
    {

        var tree = CSharpSyntaxTree.ParseText(@"
public class Sample
{
public string FooProperty {get; set;}
public void FooMethod()
{
}
 }");

        var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
            syntaxTrees: new[] { tree }, references: new[] { mscorlib });
        var semanticModel = compilation.GetSemanticModel(tree);

        var methods = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>();

        foreach (var node in methods)
        {
            if (node != null)
            {
                // node – is your current syntax node
                // semanticalModel – is your semantical model
                ISymbol symbol = semanticModel.GetSymbolInfo(node).Symbol ?? semanticModel.GetDeclaredSymbol(node);
                if (symbol.Kind == SymbolKind.Method)
                {
                    string methodName = "sleep";
                    if ((symbol as IMethodSymbol).Name.ToLower() == methodName)
                    {
                        // you find your method
                        var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
                        context.ReportDiagnostic(Diagnostic.Create(Rule, node.Identifier.GetLocation()));

                    }
                }
            }
        }

    }

}
}

我有两个无法纠正的错误:

1- 在

中注册SyntaxNodeAction
    context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName);

2- 组装于

var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

3-此外,我想从给定文件而不是我制作的 var 树中检测 sleep 方法的使用。

提前非常感谢!

c# roslyn roslyn-code-analysis
1个回答
0
投票

根据 Kris 建议的解决方案,其外观如下:

    public override void Initialize(AnalysisContext context)
    {
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.InvocationExpression);
    }


    private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        var invocationExpr = (InvocationExpressionSyntax)context.Node;
        var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax;

        if (memberAccessExpr?.Name.ToString().ToLower() != "sleep")
            return;

        context.ReportDiagnostic(Diagnostic.Create(Rule, invocationExpr.GetLocation()));
    }
© www.soinside.com 2019 - 2024. All rights reserved.