我问这个问题与one
的连续性有关我想创建一个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-
中的RegisterSyntaxNodeAction context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName);
2-汇编
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
3-此外,我想从给定的文件中检测睡眠方法的使用,而不是从我制作的var树中使用。
提前非常感谢你!