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.
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.
If you are going to compile C# v3.5 to .net assemblies:
http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx
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.
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 :
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
Mono (open source) includes C# compiler (and of course parser)
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:
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):