Yesterday, I added a snippet parser to NRefactory. It tries to parse the input code as a compilation unit (full file containing class definitions), class body (=list of methods, properties, ...), statement list and expression. The result that produces the least number of syntax errors gets chosen.
This is useful for our online code converter, because often one wants to convert a simple code snippet and not a full file.
Here is the example code that converts the string "input" from C# to VB.NET:
SnippetParser parser
= new SnippetParser(SupportedLanguage.CSharp);
INode node = parser.Parse(input);
// parser.Errors.ErrorOutput contains syntax errors, if any
// parser.Specials is the list of comments, preprocessor directives etc.
PreprocessingDirective.CSharpToVB(parser.Specials);
// Convert C# constructs to VB.NET:
node.AcceptVisitor(new CSharpConstructsVisitor(), null);
node.AcceptVisitor(new ToVBNetConvertVisitor(), null);
VBNetOutputVisitor output = new VBNetOutputVisitor();
using (SpecialNodesInserter.Install(parser.Specials, output)) {
node.AcceptVisitor(output, null);
}
// output.Errors.ErrorOutput contains conversion errors, if any
// output.Text contains the converted code