syntree/node/siblings.rs
1use core::fmt;
2use core::iter::FusedIterator;
3
4use crate::flavor::Flavor;
5use crate::node::{Element, Id, Node, NodeOrToken, SkipTokens};
6use crate::tree::Tree;
7
8/// An iterator over an element and its following siblings, nodes and tokens
9/// in order. Previous siblings are not included.
10///
11/// Note that this iterator also implements [Default], allowing it to
12/// effectively create an empty iterator in case a particular sibling is not
13/// available:
14///
15/// ```
16/// let mut tree = syntree::tree! {
17/// "root" => {
18/// "child1" => {
19/// "child2" => {
20/// "token1"
21/// }
22/// },
23/// "child3" => {
24/// "token2"
25/// }
26/// }
27/// };
28///
29/// let mut it = tree.first().and_then(|n| n.next()).map(|n| n.siblings()).unwrap_or_default();
30/// assert_eq!(it.next().map(|n| n.value()), None);
31/// # Ok::<_, Box<dyn core::error::Error>>(())
32/// ```
33///
34/// See [`Node::siblings`] or [`Token::siblings`][crate::Token::siblings].
35///
36/// # Examples
37///
38/// ```
39/// let mut tree = syntree::tree! {
40/// "root" => {
41/// "child1" => {
42/// "child2" => {
43/// "token1"
44/// }
45/// },
46/// "child3" => {
47/// "token2"
48/// }
49/// },
50/// "root2" => {
51/// "child4" => {
52/// "token3"
53/// }
54/// }
55/// };
56///
57/// let root = tree.first().ok_or("missing root")?;
58///
59/// assert_eq!(
60/// root.siblings().map(|n| n.value()).collect::<Vec<_>>(),
61/// ["root", "root2"]
62/// );
63/// # Ok::<_, Box<dyn core::error::Error>>(())
64/// ```
65pub struct Siblings<'a, T, F>
66where
67 T: Copy,
68 F: Flavor,
69{
70 tree: Option<&'a Tree<T, F>>,
71 /// The node whose children are iterated, `None` at the root.
72 parent: Option<F::Pointer>,
73 /// The next element.
74 next: Option<Id<F::Pointer>>,
75 /// The next interior node at the level, when `next` is a token.
76 node: Option<F::Pointer>,
77 /// Whether trivia tokens are yielded.
78 trivia: bool,
79}
80
81impl<'a, T, F> Siblings<'a, T, F>
82where
83 T: Copy,
84 F: Flavor,
85{
86 /// Construct a new sibling iterator starting at `start`, where `node` is
87 /// the next interior node at its level if it is a token.
88 #[inline]
89 pub(crate) const fn new(
90 tree: &'a Tree<T, F>,
91 parent: Option<F::Pointer>,
92 start: Id<F::Pointer>,
93 node: Option<F::Pointer>,
94 ) -> Self {
95 Self {
96 tree: Some(tree),
97 parent,
98 next: Some(start),
99 node,
100 trivia: false,
101 }
102 }
103
104 /// Include trivia tokens, which this iterator skips by default.
105 ///
106 /// See [`Builder::trivia`][crate::Builder::trivia].
107 ///
108 /// # Examples
109 ///
110 /// ```
111 /// let mut tree = syntree::Builder::new();
112 /// tree.token("a", 1)?;
113 /// tree.trivia("ws", 1)?;
114 /// tree.token("b", 1)?;
115 /// let tree = tree.build()?;
116 ///
117 /// let a = tree.first().ok_or("missing a")?;
118 ///
119 /// let values = a.siblings().map(|e| e.value()).collect::<Vec<_>>();
120 /// assert_eq!(values, ["a", "b"]);
121 ///
122 /// let values = a.siblings().with_trivia().map(|e| e.value()).collect::<Vec<_>>();
123 /// assert_eq!(values, ["a", "ws", "b"]);
124 /// # Ok::<_, Box<dyn core::error::Error>>(())
125 /// ```
126 #[must_use]
127 pub const fn with_trivia(mut self) -> Self {
128 self.trivia = true;
129 self
130 }
131
132 /// Construct a [`SkipTokens`] iterator from the remainder of this iterator.
133 /// This filters out tokens and yields only interior [`Node`]s.
134 ///
135 /// See [`SkipTokens`] for documentation.
136 #[must_use]
137 pub const fn skip_tokens(self) -> SkipTokens<Self> {
138 SkipTokens::new(self)
139 }
140
141 /// Get the next interior node from the iterator, advancing past tokens.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// let tree = syntree::tree! {
147 /// ("token1", 1),
148 /// "child1" => {
149 /// "token2"
150 /// },
151 /// ("token3", 1),
152 /// "child2" => {
153 /// "token4"
154 /// },
155 /// ("token5", 1),
156 /// "child3" => {
157 /// "token6"
158 /// },
159 /// ("token7", 1)
160 /// };
161 ///
162 /// let first = tree.first().ok_or("missing first")?;
163 ///
164 /// let mut it = first.siblings();
165 /// let mut out = Vec::new();
166 ///
167 /// while let Some(n) = it.next_node() {
168 /// out.push(n.value());
169 /// }
170 ///
171 /// assert_eq!(out, ["child1", "child2", "child3"]);
172 ///
173 /// let mut it = first.siblings();
174 ///
175 /// let c1 = it.next_node().ok_or("missing child1")?;
176 /// let c2 = it.next_node().ok_or("missing child2")?;
177 /// let c3 = it.next_node().ok_or("missing child3")?;
178 ///
179 /// assert_eq!([c1.value(), c2.value(), c3.value()], ["child1", "child2", "child3"]);
180 /// # Ok::<_, Box<dyn core::error::Error>>(())
181 /// ```
182 #[inline]
183 pub fn next_node(&mut self) -> Option<Node<'a, T, F>> {
184 self.find_map(NodeOrToken::into_node)
185 }
186}
187
188impl<'a, T, F> Iterator for Siblings<'a, T, F>
189where
190 T: Copy,
191 F: Flavor,
192{
193 type Item = Element<'a, T, F>;
194
195 #[inline]
196 fn next(&mut self) -> Option<Self::Item> {
197 let tree = self.tree?;
198
199 loop {
200 let id = self.next.take()?;
201 let (tok, node) = tree.after(id, self.node)?;
202 self.next = tree.next_at(self.parent, tok, node);
203 self.node = node;
204
205 if self.trivia || !tree.is_trivia(id) {
206 return tree.element(id);
207 }
208 }
209 }
210
211 #[inline]
212 fn size_hint(&self) -> (usize, Option<usize>) {
213 let len = self.tree.map_or(0, Tree::len);
214 (usize::from(self.next.is_some()), Some(len))
215 }
216}
217
218impl<T, F> FusedIterator for Siblings<'_, T, F>
219where
220 T: Copy,
221 F: Flavor,
222{
223}
224
225impl<T, F> Clone for Siblings<'_, T, F>
226where
227 T: Copy,
228 F: Flavor,
229{
230 #[inline]
231 fn clone(&self) -> Self {
232 Self {
233 tree: self.tree,
234 parent: self.parent,
235 next: self.next,
236 node: self.node,
237 trivia: self.trivia,
238 }
239 }
240}
241
242impl<T, F> Default for Siblings<'_, T, F>
243where
244 T: Copy,
245 F: Flavor,
246{
247 #[inline]
248 fn default() -> Self {
249 Self {
250 tree: None,
251 parent: None,
252 next: None,
253 node: None,
254 trivia: false,
255 }
256 }
257}
258
259impl<T, F> fmt::Debug for Siblings<'_, T, F>
260where
261 T: Copy + fmt::Debug,
262 F: Flavor<Index: fmt::Debug>,
263{
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 let next = self.tree.zip(self.next).and_then(|(t, id)| t.element(id));
266 f.debug_struct("Siblings").field("next", &next).finish()
267 }
268}