1use crate::{AstNode, SyntaxNodeRef};
2
3use std::marker::PhantomData;
4
5pub fn visitor<'a, T>() -> impl Visitor<'a, Output = T> {
6 EmptyVisitor { ph: PhantomData }
7}
8
9pub fn visitor_ctx<'a, T, C>(ctx: C) -> impl VisitorCtx<'a, Output = T, Ctx = C> {
10 EmptyVisitorCtx {
11 ph: PhantomData,
12 ctx,
13 }
14}
15
16pub trait Visitor<'a>: Sized {
17 type Output;
18 fn accept(self, node: SyntaxNodeRef<'a>) -> Option<Self::Output>;
19 fn visit<N, F>(self, f: F) -> Vis<Self, N, F>
20 where
21 N: AstNode<'a>,
22 F: FnOnce(N) -> Self::Output,
23 {
24 Vis {
25 inner: self,
26 f,
27 ph: PhantomData,
28 }
29 }
30}
31
32pub trait VisitorCtx<'a>: Sized {
33 type Output;
34 type Ctx;
35 fn accept(self, node: SyntaxNodeRef<'a>) -> Result<Self::Output, Self::Ctx>;
36 fn visit<N, F>(self, f: F) -> VisCtx<Self, N, F>
37 where
38 N: AstNode<'a>,
39 F: FnOnce(N, Self::Ctx) -> Self::Output,
40 {
41 VisCtx {
42 inner: self,
43 f,
44 ph: PhantomData,
45 }
46 }
47}
48
49#[derive(Debug)]
50struct EmptyVisitor<T> {
51 ph: PhantomData<fn() -> T>,
52}
53
54impl<'a, T> Visitor<'a> for EmptyVisitor<T> {
55 type Output = T;
56
57 fn accept(self, _node: SyntaxNodeRef<'a>) -> Option<T> {
58 None
59 }
60}
61
62#[derive(Debug)]
63struct EmptyVisitorCtx<T, C> {
64 ctx: C,
65 ph: PhantomData<fn() -> T>,
66}
67
68impl<'a, T, C> VisitorCtx<'a> for EmptyVisitorCtx<T, C> {
69 type Output = T;
70 type Ctx = C;
71
72 fn accept(self, _node: SyntaxNodeRef<'a>) -> Result<T, C> {
73 Err(self.ctx)
74 }
75}
76
77#[derive(Debug)]
78pub struct Vis<V, N, F> {
79 inner: V,
80 f: F,
81 ph: PhantomData<fn(N)>,
82}
83
84impl<'a, V, N, F> Visitor<'a> for Vis<V, N, F>
85where
86 V: Visitor<'a>,
87 N: AstNode<'a>,
88 F: FnOnce(N) -> <V as Visitor<'a>>::Output,
89{
90 type Output = <V as Visitor<'a>>::Output;
91
92 fn accept(self, node: SyntaxNodeRef<'a>) -> Option<Self::Output> {
93 let Vis { inner, f, .. } = self;
94 inner.accept(node).or_else(|| N::cast(node).map(f))
95 }
96}
97
98#[derive(Debug)]
99pub struct VisCtx<V, N, F> {
100 inner: V,
101 f: F,
102 ph: PhantomData<fn(N)>,
103}
104
105impl<'a, V, N, F> VisitorCtx<'a> for VisCtx<V, N, F>
106where
107 V: VisitorCtx<'a>,
108 N: AstNode<'a>,
109 F: FnOnce(N, <V as VisitorCtx<'a>>::Ctx) -> <V as VisitorCtx<'a>>::Output,
110{
111 type Output = <V as VisitorCtx<'a>>::Output;
112 type Ctx = <V as VisitorCtx<'a>>::Ctx;
113
114 fn accept(self, node: SyntaxNodeRef<'a>) -> Result<Self::Output, Self::Ctx> {
115 let VisCtx { inner, f, .. } = self;
116 inner.accept(node).or_else(|ctx| match N::cast(node) {
117 None => Err(ctx),
118 Some(node) => Ok(f(node, ctx)),
119 })
120 }
121}