2017-08-09 199 views
1

Roslyn文档给出了下面的示例,作为编译某些代码并显示任何编译错误的一种方式。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); 
        } 
       } 
      } 
     } 
    } 
} 
+0

StyleCop.Analyzers是一套规则和分析你的项目代码。当您尝试编译源代码时,此规则会分析C#代码。如果您查看'.csproj'文件并找到像这样的'。因此StyleCop.Analyzers不能分析包含代码的静态或动态(sourceCode1 + sourceCode2)字符串。 –

+0

谢谢@GeorgeAlexandria – eslsys

回答

2

其实这是绝对有可能的。

您需要使用WithAnalyzers method将分析器引用添加到Roslyn Compilation

为了做到这一点,您需要在项目中添加对StyleCop.Analy‌zers的正常引用,然后在其中创建各种DiagnosticAnalyzer的实例。由于他们是internal,你需要反思。

+0

这是非常有用的信息,因为我不知道['CompilationWithAnalyzers'](http://source.roslyn.io/#Microsoft.CodeAnalysis/DiagnosticAnalyzer/CompilationWithAnalyzers.cs105),所以给了不正确的建议。谢谢。 –

+0

太棒了,非常感谢@Slaks - 像乔治我不知道CompilationWithAnalyzers,但觉得这肯定是可能的。 – eslsys