-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathMaxDepthVisitor.cs
More file actions
59 lines (49 loc) · 1.58 KB
/
MaxDepthVisitor.cs
File metadata and controls
59 lines (49 loc) · 1.58 KB
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
using GraphQLParser.AST;
namespace GraphQLParser.Visitors;
/// <summary>
/// Gets the maximum depth for the specified AST node.
/// Minimum depth is 1.
/// </summary>
/// <typeparam name="TContext">Type of the context object passed into all VisitXXX methods.</typeparam>
public class MaxDepthVisitor<TContext> : ASTVisitor<TContext>
where TContext : IMaxDepthContext
{
/// <inheritdoc/>
public override async ValueTask VisitAsync(ASTNode? node, TContext context)
{
if (node != null)
{
context.Parents.Push(node);
if (context.Parents.Count > context.MaxDepth)
context.MaxDepth = context.Parents.Count;
await base.VisitAsync(node, context).ConfigureAwait(false);
context.Parents.Pop();
}
}
}
/// <summary>
/// Context used by <see cref="MaxDepthVisitor{TContext}"/>.
/// </summary>
public interface IMaxDepthContext : IASTVisitorContext
{
/// <summary>
/// Maximum depth of AST found. Minimum depth is 1.
/// </summary>
public int MaxDepth { get; set; }
/// <summary>
/// Stack of AST nodes to track the current visitor position.
/// </summary>
public Stack<ASTNode> Parents { get; }
}
/// <summary>
/// Default implementation for <see cref="IMaxDepthContext"/>.
/// </summary>
public class DefaultMaxDepthContext : IMaxDepthContext
{
/// <inheritdoc/>
public CancellationToken CancellationToken { get; set; }
/// <inheritdoc/>
public int MaxDepth { get; set; }
/// <inheritdoc/>
public Stack<ASTNode> Parents { get; set; } = new Stack<ASTNode>();
}