We try to figure out how to generate code with Roslyn. I'm not speaking about something like CSharpSyntaxTree.ParseText
that will take some strings and convert them into an AST. Instead, I would like to build my model somehow like this (pseudo code):
- Create
file
as compilation unit - Add class
MyClass
tofile
- Add method
DoSomething
toMyClass
- Set body of
DoSomething
in a similar fashion likeSystem.Linq.Expressions
We recently discovered Microsoft.CodeAnalysis.CSharp.SyntaxFactory
, and it seemed to be promising. However, obviously we have to add trivia ourselves.
After building a tree with SyntaxFactory.CompilationUnit()
and adding some members back and forth, the output of ToFullString()
is just a bunch of text, that is neither readable, nor compilable (e.g., missing braces). Do we miss something when generating the text from the model?
EDIT:
When using workspaces, you can set options affecting the whitespace behavior:
public string Generate (CompilationNode rootNode)
{
var cw = new CustomWorkspace();
cw.Options.WithChangedOption (CSharpFormattingOptions.IndentBraces, true);
var formattedCode = Formatter.Format (CreateFile(rootNode), cw);
return formattedCode.ToFullString();
}
This already yields a better result. Can someone confirm this as a good solution or is it rather a hack?
One problem remains. We want to generate an auto-property, currently using SF.AccessorDeclaration
but it misses the semicolon when converting to the full string.