Skip to content
DanielGrunwald edited this page Aug 27, 2011 · 4 revisions

This page is about NRefactory up to version 4.

NRefactory 5 is a completely rewritten version which also includes semantic analysis, but (currently) supports only C# and not VB.

ICSharpCode.NRefactory is a parser library for C# and VB.

It consists of a single Abstract Syntax Tree (AST) that can represent all constructs that are available in C# or VB (unlike System.CodeDom, which only represents constructs common to C# and VB).

Please try samples\NRefactoryDemo in the SharpDevelop source code to take a look at the AST

To parse source code, use: {{ 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"); } } }}

Now you can analyze and/or transform the AST.

Should you want to re-create source code from the (modified) AST, use an output visitor: {{ CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(); // re-insert the comments we saved from the parser into the output using (SpecialNodesInserter.Install(specials, outputVisitor)) { astView.Unit.AcceptVisitor(outputVisitor, null); } codeTextBox.Text = outputVisitor.Text; }}

By using the C# parser and a VB output visitor (or vice versa), you can build a code converter. Of course, the real Code Converter in SharpDevelop also transforms the AST to fix cases where C# and VB semantics differ.

Clone this wiki locally