问题
I'm looking for an alternative for CSharpCodeProvider.Parse
. The method was supposed to parse a [C#] code source and return a CompileUnit
object. However, the method isn't implemented in any .Net framework.
My purpose is to be able to navigate a C# CodeDOM without having to compile it. I'm writing a application that does some code analysis but I won't necessarily have all external references, which means I can't compile it.
回答1:
SharpDevelop (the open source IDE commonly used for Mono) has a library called NRefactory that allows you to parse C# code and convert it into an AST: http://wiki.sharpdevelop.net/NRefactory.ashx (Excerpt from that link follows):
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");
}
}
回答2:
There are many free C# parsers, the most popular apparently being:
- CsParser (on CodePlex)
回答3:
Actual (2017-2018) info:
More info available at https://github.com/icsharpcode/SharpDevelop/wiki/NRefactory
Download nuget package: "ICSharpCode.NRefactory"
And here is code snippet:
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); } } }
回答4:
Our DMS Software Reengineering Toolkit is a tool for building analysis tools for arbitrary languages. DMS provides generalized parsing, AST navigation and modification, regeneration of source from a modified tree, symbol table support, and various kinds of analysis support as well as the ability to write source-to-source transformations that modify the ASTs directly in terms of surface syntax.
Its C# Front End provides a full C# 4.0 parser (including LINQ) that builds a full abstract syntax tree containing every item of the source text, including comments captured as annotations on source tree nodes that the comments decorate.
来源:https://stackoverflow.com/questions/3631909/an-alternative-for-csharpcodeprovider-parse