Boas Enkler Boas Enkler - 4 months ago 12
C# Question

SyntaxWalker doesn't visit trivia

Given:

With a simple syntax walker I want to visit trivias (EndOfLineTrivia to be exact)

public sealed class MyWalker : SyntaxWalker
{
public int Lines { get; set; }

public int Trivia { get; set; }

public int Node { get; set; }

public override void Visit(SyntaxNode node)
{
Node++;
base.Visit(node);
}

protected override void VisitTrivia(SyntaxTrivia trivia)
{
Trivia++;
base.VisitTrivia(trivia);
}
}


I call the Walker like this:

SyntaxTree node = CSharpSyntaxTree.ParseText(sourceCode);
var root = node.GetRoot();
var walker = new LocWalker();


Problem

The overriden VisitTrivia Method is never called.

Answer

What you need is to set the Depth of the walker to SyntaxWalkerDepth.Trivia (or SyntaxWalkerDepth.StructuredTrivia). The default Depth is SyntaxWalkerDepth.Node, which means that trivia is not visited.

To do that, call the base constructor:

public MyWalker() : base(SyntaxWalkerDepth.Trivia)
{
}