syntree/node/
ancestors.rs

1use core::iter::FusedIterator;
2
3use crate::flavor::Flavor;
4use crate::node::{Node, SkipTokens};
5
6/// An iterator that iterates over the [`Node::parent`] elements of a node. This
7/// is used for iterating over the ancestors of a node.
8///
9/// Note that this iterator also implements [Default], allowing it to
10/// effectively create an empty iterator in case a particular ancestor is not
11/// available:
12///
13/// ```
14/// let mut tree = syntree::tree! {
15///     "root" => {
16///         "child1" => {},
17///         "child3" => {}
18///     }
19/// };
20///
21/// let mut it = tree.first().and_then(|n| n.first()).and_then(|n| n.first()).map(|n| n.ancestors()).unwrap_or_default();
22/// assert!(it.next().is_none());
23/// # Ok::<_, Box<dyn core::error::Error>>(())
24/// ```
25///
26/// See [`Node::ancestors`].
27///
28/// # Examples
29///
30/// ```
31/// let mut tree = syntree::tree! {
32///     "root" => {
33///         "child1" => {
34///             "child2" => {}
35///         },
36///         "child3" => {}
37///     }
38/// };
39///
40/// let child2 = tree.first().and_then(|n| n.first()).and_then(|n| n.first()).ok_or("missing child2")?;
41/// assert_eq!(child2.value(), "child2");
42///
43/// assert_eq!(
44///     child2.ancestors().map(|n| n.value()).collect::<Vec<_>>(),
45///     ["child2", "child1", "root"]
46/// );
47/// # Ok::<_, Box<dyn core::error::Error>>(())
48/// ```
49pub struct Ancestors<'a, T, F>
50where
51    T: Copy,
52    F: Flavor,
53{
54    node: Option<Node<'a, T, F>>,
55}
56
57impl<'a, T, F> Ancestors<'a, T, F>
58where
59    T: Copy,
60    F: Flavor,
61{
62    /// Construct a new ancestor iterator.
63    #[inline]
64    pub(crate) const fn new(node: Option<Node<'a, T, F>>) -> Self {
65        Self { node }
66    }
67
68    /// Construct a [`SkipTokens`] iterator from the remainder of this iterator.
69    /// This filters out childless nodes, also known as tokens.
70    ///
71    /// See [`SkipTokens`] for documentation.
72    #[inline]
73    #[must_use]
74    pub const fn skip_tokens(self) -> SkipTokens<Self> {
75        SkipTokens::new(self)
76    }
77
78    /// Get the next node from the iterator. This advances past all non-node
79    /// data.
80    ///
81    /// # Examples
82    ///
83    /// ```
84    /// let tree = syntree::tree! {
85    ///     "root" => {
86    ///         "child" => {
87    ///             ("lit", 3)
88    ///         }
89    ///     }
90    /// };
91    ///
92    /// let lit = tree.first().and_then(|n| n.first()?.first()).ok_or("missing lit")?;
93    /// assert_eq!(lit.value(), "lit");
94    ///
95    /// let mut it = lit.ancestors();
96    /// let mut out = Vec::new();
97    ///
98    /// while let Some(n) = it.next_node() {
99    ///     out.push(n.value());
100    /// }
101    ///
102    /// assert_eq!(out, ["child", "root"]);
103    ///
104    /// let mut it = lit.ancestors();
105    ///
106    /// let child = it.next_node().ok_or("missing child")?;
107    /// let root = it.next_node().ok_or("missing root")?;
108    ///
109    /// assert_eq!([child.value(), root.value()], ["child", "root"]);
110    /// # Ok::<_, Box<dyn core::error::Error>>(())
111    /// ```
112    #[inline]
113    pub fn next_node(&mut self) -> Option<Node<'a, T, F>> {
114        self.find(|n| n.has_children())
115    }
116}
117
118impl<'a, T, F> Iterator for Ancestors<'a, T, F>
119where
120    T: Copy,
121    F: Flavor,
122{
123    type Item = Node<'a, T, F>;
124
125    #[inline]
126    fn next(&mut self) -> Option<Self::Item> {
127        let node = self.node.take()?;
128        self.node = node.parent();
129        Some(node)
130    }
131}
132
133impl<T, F> FusedIterator for Ancestors<'_, T, F>
134where
135    T: Copy,
136    F: Flavor,
137{
138}
139
140impl<T, F> Clone for Ancestors<'_, T, F>
141where
142    T: Copy,
143    F: Flavor,
144{
145    #[inline]
146    fn clone(&self) -> Self {
147        Self { node: self.node }
148    }
149}
150
151impl<T, F> Default for Ancestors<'_, T, F>
152where
153    T: Copy,
154    F: Flavor,
155{
156    #[inline]
157    fn default() -> Self {
158        Self { node: None }
159    }
160}