3

I am using Roslyn in order to generate a tree from another one. So we are dealing with AST transformation. I am using SyntaxFactory in order to generate nodes.

In the specific case I want to create a u using directive that should look like this:

using MyNamespace.SubNamespace;

So I do:

var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyNamespace.SubNamespace"));
var newNode = mynode.AddUsings(new[] { usingDirective });

But if I inspect the final tree newNode which is generated (the string source code generated by simply calling newNode.ToString()), I see that my directive has been added like this:

usingMyNamespace.SubNamespace;

I can see the same thing if I just do: usingDirective.ToString(). It seems very wrong, a space is needed and that should trigger a syntax error. What is going on?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andry
  • 16,172
  • 27
  • 138
  • 246

1 Answers1

4

Add this to fix the problem:

SyntaxFactory.UsingDirective(
    SyntaxFactory.ParseName("MyNamespace.SubNamespace")).NormalizeWhitespace();
Dudi Keleti
  • 2,946
  • 18
  • 33
  • Thanks man! So it this whitespace thing just a visual trivia, so it does not really change anything (not harmful for both parsing and semantic analysis) or it is making any demage? – Andry Nov 27 '16 at 20:59
  • 1
    The syntax tree of Roslyn is not abstract, but concrete, that means that everything of source code is included in the three (so whitespace, comments, xml doc, everything). This is to make it possible to turn the three back into the original three. In your case, the three generated is not really valid, and needs the appropriate whitespace (though, I expect it to generate valid IL), which does NormalizeWhitespace. Alternatively, you can add WithAdditionalAnnotations(Formatter.Annotation), if this is in a CodeFix, to indicate that the resulting node requires appropriate whitespace formatting. – Ties Nov 27 '16 at 21:44
  • Like a found out here: http://stackoverflow.com/questions/40578806/what-is-the-canonical-way-to-convert-a-methoddeclarationsyntax-to-a-constructord ;) On the wiki of Roslyn, you can find more on nodes, tokes, and trivia (this topic): https://github.com/dotnet/roslyn/wiki/Roslyn%20Overview#syntax-trivia – Ties Nov 27 '16 at 21:46