syntree/node/ancestors.rs
1use core::fmt;
2use core::iter::FusedIterator;
3
4use crate::flavor::Flavor;
5use crate::node::{Element, Node, NodeOrToken, SkipTokens};
6
7/// An iterator over an element and its ancestors, starting with the element
8/// itself and following [`Node::parent`] up to the root.
9///
10/// It yields [`Element`]s, since the first one may be a token. Every element
11/// after the first is a node.
12///
13/// Note that this iterator also implements [Default], allowing it to
14/// effectively create an empty iterator in case a particular ancestor is not
15/// available:
16///
17/// ```
18/// let mut tree = syntree::tree! {
19/// "root" => {
20/// "child1" => {},
21/// "child3" => {}
22/// }
23/// };
24///
25/// let mut it = tree.first().and_then(|n| n.first()).and_then(|n| n.first()).map(|n| n.ancestors()).unwrap_or_default();
26/// assert!(it.next().is_none());
27/// # Ok::<_, Box<dyn core::error::Error>>(())
28/// ```
29///
30/// See [`Node::ancestors`] or [`Token::ancestors`][crate::Token::ancestors].
31///
32/// # Examples
33///
34/// ```
35/// let mut tree = syntree::tree! {
36/// "root" => {
37/// "child1" => {
38/// "child2" => {}
39/// },
40/// "child3" => {}
41/// }
42/// };
43///
44/// let child2 = tree.first().and_then(|n| n.first()).and_then(|n| n.first()).ok_or("missing child2")?;
45/// assert_eq!(child2.value(), "child2");
46///
47/// assert_eq!(
48/// child2.ancestors().map(|n| n.value()).collect::<Vec<_>>(),
49/// ["child2", "child1", "root"]
50/// );
51/// # Ok::<_, Box<dyn core::error::Error>>(())
52/// ```
53pub struct Ancestors<'a, T, F>
54where
55 T: Copy,
56 F: Flavor,
57{
58 node: Option<Element<'a, T, F>>,
59}
60
61impl<'a, T, F> Ancestors<'a, T, F>
62where
63 T: Copy,
64 F: Flavor,
65{
66 /// Construct a new ancestor iterator.
67 #[inline]
68 pub(crate) const fn new(node: Option<Element<'a, T, F>>) -> Self {
69 Self { node }
70 }
71
72 /// Construct a [`SkipTokens`] iterator from the remainder of this iterator.
73 /// This filters out tokens and yields only interior [`Node`]s.
74 ///
75 /// See [`SkipTokens`] for documentation.
76 #[inline]
77 #[must_use]
78 pub const fn skip_tokens(self) -> SkipTokens<Self> {
79 SkipTokens::new(self)
80 }
81
82 /// Get the next interior node from the iterator, advancing past tokens.
83 ///
84 /// # Examples
85 ///
86 /// ```
87 /// let tree = syntree::tree! {
88 /// "root" => {
89 /// "child" => {
90 /// ("lit", 3)
91 /// }
92 /// }
93 /// };
94 ///
95 /// let lit = tree.first().and_then(|n| n.first()?.first()).ok_or("missing lit")?;
96 /// assert_eq!(lit.value(), "lit");
97 ///
98 /// let mut it = lit.ancestors();
99 /// let mut out = Vec::new();
100 ///
101 /// while let Some(n) = it.next_node() {
102 /// out.push(n.value());
103 /// }
104 ///
105 /// assert_eq!(out, ["child", "root"]);
106 ///
107 /// let mut it = lit.ancestors();
108 ///
109 /// let child = it.next_node().ok_or("missing child")?;
110 /// let root = it.next_node().ok_or("missing root")?;
111 ///
112 /// assert_eq!([child.value(), root.value()], ["child", "root"]);
113 /// # Ok::<_, Box<dyn core::error::Error>>(())
114 /// ```
115 #[inline]
116 pub fn next_node(&mut self) -> Option<Node<'a, T, F>> {
117 self.find_map(NodeOrToken::into_node)
118 }
119}
120
121impl<'a, T, F> Iterator for Ancestors<'a, T, F>
122where
123 T: Copy,
124 F: Flavor,
125{
126 type Item = Element<'a, T, F>;
127
128 #[inline]
129 fn next(&mut self) -> Option<Self::Item> {
130 let node = self.node.take()?;
131 self.node = node.parent().map(NodeOrToken::Node);
132 Some(node)
133 }
134
135 #[inline]
136 fn size_hint(&self) -> (usize, Option<usize>) {
137 (usize::from(self.node.is_some()), None)
138 }
139}
140
141impl<T, F> FusedIterator for Ancestors<'_, T, F>
142where
143 T: Copy,
144 F: Flavor,
145{
146}
147
148impl<T, F> Clone for Ancestors<'_, T, F>
149where
150 T: Copy,
151 F: Flavor,
152{
153 #[inline]
154 fn clone(&self) -> Self {
155 Self { node: self.node }
156 }
157}
158
159impl<T, F> Default for Ancestors<'_, T, F>
160where
161 T: Copy,
162 F: Flavor,
163{
164 #[inline]
165 fn default() -> Self {
166 Self { node: None }
167 }
168}
169
170impl<T, F> fmt::Debug for Ancestors<'_, T, F>
171where
172 T: Copy + fmt::Debug,
173 F: Flavor<Index: fmt::Debug>,
174{
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.debug_struct("Ancestors")
177 .field("next", &self.node)
178 .finish()
179 }
180}