-
Notifications
You must be signed in to change notification settings - Fork 4k
/
CSharpSyntaxWalker.cs
102 lines (89 loc) · 3.03 KB
/
CSharpSyntaxWalker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Represents a <see cref="CSharpSyntaxVisitor"/> that descends an entire <see cref="CSharpSyntaxNode"/> graph
/// visiting each CSharpSyntaxNode and its child SyntaxNodes and <see cref="SyntaxToken"/>s in depth-first order.
/// </summary>
public abstract class CSharpSyntaxWalker : CSharpSyntaxVisitor
{
protected SyntaxWalkerDepth Depth { get; }
protected CSharpSyntaxWalker(SyntaxWalkerDepth depth = SyntaxWalkerDepth.Node)
{
this.Depth = depth;
}
private int _recursionDepth;
public override void Visit(SyntaxNode? node)
{
if (node != null)
{
_recursionDepth++;
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
((CSharpSyntaxNode)node).Accept(this);
_recursionDepth--;
}
}
public override void DefaultVisit(SyntaxNode node)
{
var childCnt = node.ChildNodesAndTokens().Count;
int i = 0;
do
{
var child = ChildSyntaxList.ItemInternal((CSharpSyntaxNode)node, i);
i++;
var asNode = child.AsNode();
if (asNode != null)
{
if (this.Depth >= SyntaxWalkerDepth.Node)
{
this.Visit(asNode);
}
}
else
{
if (this.Depth >= SyntaxWalkerDepth.Token)
{
this.VisitToken(child.AsToken());
}
}
} while (i < childCnt);
}
public virtual void VisitToken(SyntaxToken token)
{
if (this.Depth >= SyntaxWalkerDepth.Trivia)
{
this.VisitLeadingTrivia(token);
this.VisitTrailingTrivia(token);
}
}
public virtual void VisitLeadingTrivia(SyntaxToken token)
{
if (token.HasLeadingTrivia)
{
foreach (var tr in token.LeadingTrivia)
{
this.VisitTrivia(tr);
}
}
}
public virtual void VisitTrailingTrivia(SyntaxToken token)
{
if (token.HasTrailingTrivia)
{
foreach (var tr in token.TrailingTrivia)
{
this.VisitTrivia(tr);
}
}
}
public virtual void VisitTrivia(SyntaxTrivia trivia)
{
if (this.Depth >= SyntaxWalkerDepth.StructuredTrivia && trivia.HasStructure)
{
this.Visit((CSharpSyntaxNode)trivia.GetStructure()!);
}
}
}
}