我正在寻找CSharpCodeProvider.Parse
. 该方法应该解析 [C#] 代码源并返回一个CompileUnit
对象。但是,该方法并未在任何 .Net 框架中实现。
我的目的是能够导航 C# CodeDOM 而无需编译它。我正在编写一个执行一些代码分析的应用程序,但我不一定拥有所有外部引用,这意味着我无法编译它。
SharpDevelop(Mono 常用的开源 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");
}
}
有许多免费的 C# 解析器,最流行的显然是:
实际(2017-2018)信息:
更多信息可在https://github.com/icharpcode/SharpDevelop/wiki/NRefactory
下载nuget包:“ICSharpCode.NRefactory”
这是代码片段:
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);
}
}
}
我们的DMS Software Reengineering Toolkit是一个为任意语言构建分析工具的工具。DMS 提供通用解析、AST 导航和修改、从修改后的树中重新生成源、符号表支持和各种分析支持,以及编写直接根据表面修改 AST 的源到源转换的能力句法。
它的C# 前端提供了一个完整的 C# 4.0 解析器(包括 LINQ),该解析器构建了一个完整的抽象语法树,其中包含源文本的每个项目,包括作为注释捕获的注释,这些注释装饰在源树节点上。