tags:

views:

50

answers:

3

Hello all,

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.

A: 

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.

Ira Baxter
+1  A: 

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");
    }
}
Kirk Woll
A: 

There are many free C# parsers, the most popular apparently being:

Timwi