Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to format a SyntaxTree in memory?

Tags:

c#

roslyn

The existing Roslyn documentation is very thin so I'm hoping someone knows how to do this, or at least point me in the right direction. I tried a number of things, including the following to format the sourceCode but it didn't work:

var tree = CSharpSyntaxTree.ParseText(soureCode);
var root = (CSharpSyntaxNode)tree.GetRoot();
return root.ToFullString();

Any help in this regard would be greatly appreciated....

like image 294
Louis S. Berman Avatar asked Dec 15 '15 04:12

Louis S. Berman


1 Answers

If you're just trying to get a pretty-print version of your SyntaxTree, you can call root.NormalizeWhitespace().ToFullString();.

NormalizeWhitespace() is an extension method, so you'll have to add:

using Microsoft.CodeAnalysis;

If you're looking to format the tree in memory, you're probably looking for the Formatter class. This class has a few different overloads depending on whether you want to format the entire document or just certain spans.

Unfortunately, it requires either a Document or a Workspace to format the whitespace. It might be nice if there was an overload that just applied generic formatting rules to a tree.

like image 52
JoshVarty Avatar answered Oct 25 '22 23:10

JoshVarty