103

Which parsers are available for parsing C# code?

I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code.

0

15 Answers 15

121

Works on source code:

Works on assembly:

The problem with assembly "parsing" is that we have less informations about line and file (the informations is based on .pdb file, and Pdb contains lines informations only for methods)

I personnaly recommend Mono.Cecil and NRefactory.

Sign up to request clarification or add additional context in comments.

2 Comments

CS-Script(csscript.net) - the C# Script Engine may suite this list. Sample of "Introducing the Microsoft “Roslyn” CTP" is very like CS-script can do.
While you're mentioning costs, note that Roslyn requires at least the Pro version of Visual Studio.
7

Mono (open source) includes C# compiler (and of course parser)

1 Comment

What is the advantage of using Mono over other parser? Can i get info of the AST of a C# program using a visitor? If so, can u direct me to the page that shows the page for that?
6

If you are going to compile C# v3.5 to .net assemblies:

var cp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });

http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx

2 Comments

Particularly look at the CodeDomProvider.Parse() method.
No, don't look at the CodeDomProvider.Parse() method which throws a NotImplemented exception in public builds! (Visual Studio uses a proprietary internal parser).
5

I've implemented just what you are asking (AST Parsing of C# code) at the OWASP O2 Platform project using SharpDevelop AST APIs.

In order to make it easier to consume I wrote a quick API that exposes a number of key source code elements (using statements, types, methods, properties, fields, comments) and is able to rewrite the original C# code into C# and into VBNET.

You can see this API in action on this O2 XRule script file: ascx_View_SourceCode_AST.cs.o2 .

For example this is how you process a C# source code text and populate a number of TreeViews & TextBoxes:

    public void updateView(string sourceCode)
    {   
        var ast = new Ast_CSharp(sourceCode);
        ast_TreeView.show_Ast(ast);
        types_TreeView.show_List(ast.astDetails.Types, "Text");
        usingDeclarations_TreeView.show_List(ast.astDetails.UsingDeclarations,"Text");
        methods_TreeView.show_List(ast.astDetails.Methods,"Text");
        fields_TreeView.show_List(ast.astDetails.Fields,"Text");
        properties_TreeView.show_List(ast.astDetails.Properties,"Text");
        comments_TreeView.show_List(ast.astDetails.Comments,"Text");

        rewritenCSharpCode_SourceCodeEditor.setDocumentContents(ast.astDetails.CSharpCode, ".cs");
        rewritenVBNet_SourceCodeEditor.setDocumentContents(ast.astDetails.VBNetCode, ".vb");                                
    }

The example on ascx_View_SourceCode_AST.cs.o2 also shows how you can then use the information gathered from the AST to select on the source code a type, method, comment, etc..

For reference here is the API code that wrote (note that this is my first pass at using SharpDevelop's C# AST parser, and I am still getting my head around how it works):

1 Comment

Yep this seems to be the easiest of the solutions at least based on what I have seen. I was looking for a decent parser and stumbled upon this blog svengrand.blogspot.com/2010/10/… which also details how to use SharpDevelop's C# parser.
5

If you're familiar with ANTLR, you can use Antlr C# grammar.

Comments

4

You should definitely check out Roslyn since MS just opened (or will soon open) the code with an Apache 2 license here. You can also check out a way to parse this info with this code from GitHub.

Comments

3

We have recently released a C# parser that handles all C# 4.0 features plus the new async feature: C# Parser and CodeDOM

This library generates a semantic object model which retains comments and formatting information and can be modified and saved. It also supports the use of LINQ queries to analyze source code.

Comments

2

SharpDevelop, an open source IDE, comes with a visitor-based code parser which works really well. It can be used independently of the IDE.

Comments

2

Consider to use reflection on a built binary instead of parsing the C# code directly. The reflection API is really easy to use and perhaps you can get all the information you need?

3 Comments

Reflection is a bad way to do static analysis; it provides only the information that the reflection-logic can extract (e.g., "names of methods in class". It does not provide detail information ("what's the right hand side of this assignment?") and so severely limits that kind of static analysis one can do.
@Ira Baxter There are some limitations, but remember that you can also get the IL code via reflection. This means you can understand what methods are called, what are assigned to which variables, etc. I cannot think of many cases where it isn't enough. Just look at what all the Reflector plugins can do.
how do you get the actual IL code via Reflection? As far as I'm aware Reflection doesn't provide this and you need to use CCI See: stackoverflow.com/questions/2824086/…
2

Maybe you could try with Irony on irony.codeplex.com.

It's very fast and a c# grammar already exists.

The grammar itself is written directly in c# in a BNF like way (acheived with some operators overloads)

The best thing with it is that the "grammar" produces the AST directly.

1 Comment

The comment in Irony.Samples/CSharp/CSharpGrammar.cs says "NOTE: This grammar is just a demo, and it is a broken demo". So it's not a complete implementation at least.
1

http://www.codeplex.com/csparser

1 Comment

Seems to only support C# 1 and 2.
1

Have a look at Gold Parser. It has a very intuitive IU that lets you interactively test your grammar and generate C# code. There are plenty of examples available with it and it is completely free.

1 Comment

The OP asked for something that can parser C#, not something in C# that parse something else.
0

Something that is gaining momentum and very appropriate for the job is Nemerle

you can see how it could solve it in these videos from NDC :

2 Comments

Nemerle is a programming language. A nice programming language, I agree, but the question was how to parse C# code inside C#!
you create rules in nemerle, and use it from C#, nothing said the parser has to be in C#, but whatever, downvote away.
0

Not in C#, but a full C# 2/3/4 parser that builds full ASTs is available with our DMS Software Reengineering Toolkit.

DMS provides a vast infrastructure for parsing, tree building, construction of symbol tables and flow analyses, source-to-source transformation, and regeneration of source code from the (modified) ASTs. (It also handles many other languages than just C#.)

EDIT (September) 2013: This answer hasn't been updated recently. DMS has long handled C# 5.0

Comments

-2

GPPG might be of use, if you are willing to write your own parser (which is fun).

1 Comment

Link in answer is dead - "This site can’t be reached | DNS_PROBE_FINISHED_NXDOMAIN".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.