You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
DanielGrunwald edited this page Sep 8, 2009
·
4 revisions
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.