[英]Static code analysis on Roslyn in-memory code
Roslyn文檔以下面的示例作為編譯某些代碼並顯示任何編譯錯誤的方式。
我想知道是否有人知道在下面的示例中對變量sourceCode中包含的代碼執行一些靜態代碼分析的方法。 我已經將StyleCop.Analyzers添加到我的測試項目中,但是在此階段我看不到如何將其用於執行樣式分析(例如,可讀性)。
使用StyleCop.Analyzers做到這一點是否可行,還是有其他替代方法? 任何建議均感激不盡。
謝謝。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace SemanticsCS
{
class Program
{
static void Main(string[] args)
{
var sourceCode = @"using System;
using System.Collections.Generic;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}";
SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);
var root = (CompilationUnitSyntax)tree.GetRoot();
var compilation = CSharpCompilation.Create("HelloWorld")
.AddReferences(
MetadataReference.CreateFromFile(
typeof(object).Assembly.Location))
.AddSyntaxTrees(tree);
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.WriteLine(diagnostic.ToString());
Console.Error.WriteLine("{0}({1})", diagnostic.GetMessage(), diagnostic.Id);
}
}
}
}
}
}
實際上,這絕對是可能的。
您需要使用WithAnalyzers
方法將分析器引用添加到Roslyn Compilation
。
要使此工作正常進行,您需要在項目中添加對StyleCop.Analyzers
的常規引用,然后在其中創建各種DiagnosticAnalyzer
的實例。 由於它們是internal
,因此您需要反思。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.