From 7afd84febc76a75a3ed1be75c57ff35d7b8b3de6 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 11 Aug 2018 12:28:59 +0300 Subject: visitor --- crates/libsyntax2/src/algo/mod.rs | 1 + crates/libsyntax2/src/algo/visit.rs | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 crates/libsyntax2/src/algo/visit.rs (limited to 'crates/libsyntax2/src/algo') diff --git a/crates/libsyntax2/src/algo/mod.rs b/crates/libsyntax2/src/algo/mod.rs index d2de70fd4..263b58d97 100644 --- a/crates/libsyntax2/src/algo/mod.rs +++ b/crates/libsyntax2/src/algo/mod.rs @@ -1,4 +1,5 @@ pub mod walk; +pub mod visit; use {SyntaxNodeRef, TextUnit, TextRange}; diff --git a/crates/libsyntax2/src/algo/visit.rs b/crates/libsyntax2/src/algo/visit.rs new file mode 100644 index 000000000..dc5afa5a9 --- /dev/null +++ b/crates/libsyntax2/src/algo/visit.rs @@ -0,0 +1,52 @@ +use std::marker::PhantomData; +use {SyntaxNodeRef, AstNode, SyntaxRoot}; + + +pub fn visitor<'a, T>() -> impl Visitor<'a, Output=T> { + EmptyVisitor { ph: PhantomData } +} + +pub trait Visitor<'a>: Sized { + type Output; + fn accept(self, node: SyntaxNodeRef<'a>) -> Option; + fn visit(self, f: F) -> Vis + where N: AstNode<&'a SyntaxRoot>, + F: FnOnce(N) -> Self::Output, + { + Vis { inner: self, f, ph: PhantomData } + } +} + +#[derive(Debug)] +struct EmptyVisitor { + ph: PhantomData T> +} + +impl<'a, T> Visitor<'a> for EmptyVisitor { + type Output = T; + + fn accept(self, _node: SyntaxNodeRef<'a>) -> Option { + None + } +} + +#[derive(Debug)] +pub struct Vis { + inner: V, + f: F, + ph: PhantomData, +} + +impl<'a, V, N, F> Visitor<'a> for Vis + where + V: Visitor<'a>, + N: AstNode<&'a SyntaxRoot>, + F: FnOnce(N) -> >::Output, +{ + type Output = >::Output; + + fn accept(self, node: SyntaxNodeRef<'a>) -> Option { + let Vis { inner, f, .. } = self; + inner.accept(node).or_else(|| N::cast(node).map(f)) + } +} -- cgit v1.2.3