2010-09-02 50 views
2

我在尋找替代品CSharpCodeProvider.Parse。該方法應該解析[C#]代碼源並返回一個CompileUnit對象。但是,該方法沒有在任何.Net框架中實現。「CSharpCodeProvider.Parse」的替代方案

我的目的是能夠瀏覽一個C#CodeDOM,而不必編譯它。我正在編寫一個應用程序,它執行一些代碼分析,但我不一定會擁有所有外部引用,這意味着我無法編譯它。

回答

2

的SharpDevelop(開源常用的單IDE)有一個名爲NRefactory庫,使您解析C#代碼,並將其轉換成AST:http://wiki.sharpdevelop.net/NRefactory.ashx(摘錄自該鏈接如下):

using (IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(sourceCode))) 
{ 
    parser.Parse(); 
    // this allows retrieving comments, preprocessor directives, etc. (stuff that isn't part of the syntax) 
    specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); 
    // this retrieves the root node of the result AST 
    result = parser.CompilationUnit; 
    if (parser.Errors.Count > 0) { 
     MessageBox.Show(parser.Errors.ErrorOutput, "Parse errors"); 
    } 
} 
-1

我們的DMS Software Reengineering Toolkit是一款用於構建任意語言分析工具的工具。 DMS提供了廣義的解析,AST導航和修改,從修改後的樹中重新生成源代碼,符號表支持以及各種分析支持,以及編寫源代碼到源代碼轉換的能力,這些轉換直接根據表面語法。

它的C# Front End提供了一個完整的C#4.0解析器(包括LINQ),它構建了一個完整的抽象語法樹,其中包含源文本的每一項,包括作爲註釋修飾的源樹節點上的註釋捕獲的註釋。

0

實際(2017至2018年)的信息:

  1. 更多的https://github.com/icsharpcode/SharpDevelop/wiki/NRefactory

  2. 下載NuGet包可用的信息: 「ICSharpCode.NRefactory」

  3. 這裏是代碼片段:

    using ICSharpCode.NRefactory.CSharp; 
    using System; 
    using System.Collections.Generic; 
    using System.IO; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 
    namespace Ns1 
    { 
        public class Foo 
        { 
         public void Go() 
         {  
          CSharpParser parser = new CSharpParser(); 
          string text = File.ReadAllText("myProgram.cs"); 
          SyntaxTree syntaxTree = parser.Parse(text); 
         } 
        } 
    }