Skip to main content

syntree/node/
children.rs

1use core::fmt;
2use core::iter::FusedIterator;
3
4use crate::flavor::Flavor;
5use crate::links::TokenLinks;
6use crate::node::{Element, Id, Node, NodeOrToken, SkipTokens, Token};
7use crate::pointer::Pointer;
8use crate::tree::Tree;
9
10/// An iterator over the children of a node or the root of a tree, nodes and
11/// tokens in order.
12///
13/// The children of a level are its tokens merged in source order with its
14/// chain of interior nodes, so both directions step in constant time.
15///
16/// Note that this iterator also implements [Default], allowing it to
17/// effectively create an empty iterator in case a particular sibling is not
18/// available:
19///
20/// ```
21/// let mut tree = syntree::tree! {
22///     "root" => {
23///         "child1" => {
24///             "child2" => {
25///                 "token1"
26///             }
27///         },
28///         "child3" => {}
29///     }
30/// };
31///
32/// let mut it = tree.first().and_then(|n| n.last()).map(|n| n.children()).unwrap_or_default();
33/// assert_eq!(it.next().map(|n| n.value()), None);
34/// # Ok::<_, Box<dyn core::error::Error>>(())
35/// ```
36///
37/// See [`Tree::children`][crate::Tree::children] or [`Node::children`][crate::Node::children].
38///
39/// # Examples
40///
41/// ```
42/// let mut tree = syntree::tree! {
43///     "root" => {
44///         "child1" => {
45///             "child2" => {}
46///         },
47///         "child3" => {}
48///     },
49///     "root2" => {
50///         "child4" => {}
51///     }
52/// };
53///
54/// assert_eq!(
55///     tree.children().map(|n| n.value()).collect::<Vec<_>>(),
56///     ["root", "root2"]
57/// );
58///
59/// assert_eq!(
60///     tree.children().rev().map(|n| n.value()).collect::<Vec<_>>(),
61///     ["root2", "root"]
62/// );
63///
64/// let root = tree.first().ok_or("missing root node")?;
65///
66/// assert_eq!(
67///     root.children().map(|n| n.value()).collect::<Vec<_>>(),
68///     ["child1", "child3"]
69/// );
70///
71/// assert_eq!(
72///     root.children().rev().map(|n| n.value()).collect::<Vec<_>>(),
73///     ["child3", "child1"]
74/// );
75/// # Ok::<_, Box<dyn core::error::Error>>(())
76/// ```
77pub struct Children<'a, T, F>
78where
79    T: Copy,
80    F: Flavor,
81{
82    tree: Option<&'a Tree<T, F>>,
83    /// The node whose children are iterated, `None` at the root.
84    parent: Option<F::Pointer>,
85    /// The token position and next interior node at the front.
86    front: (usize, Option<F::Pointer>),
87    /// The token position and previous interior node at the back.
88    back: (usize, Option<F::Pointer>),
89    /// The last element yielded from the front.
90    front_last: Option<Id<F::Pointer>>,
91    /// The last element yielded from the back.
92    back_last: Option<Id<F::Pointer>>,
93    done: bool,
94    /// Whether trivia tokens are yielded.
95    trivia: bool,
96}
97
98impl<'a, T, F> Children<'a, T, F>
99where
100    T: Copy,
101    F: Flavor,
102{
103    #[inline]
104    pub(crate) fn new(
105        tree: &'a Tree<T, F>,
106        parent: Option<F::Pointer>,
107        front: (usize, Option<F::Pointer>),
108        back: (usize, Option<F::Pointer>),
109    ) -> Self {
110        Self {
111            tree: Some(tree),
112            parent,
113            front,
114            back,
115            front_last: None,
116            back_last: None,
117            done: false,
118            trivia: false,
119        }
120    }
121
122    /// Include trivia tokens, which this iterator skips by default.
123    ///
124    /// See [`Builder::trivia`][crate::Builder::trivia].
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// let mut tree = syntree::Builder::new();
130    /// tree.token("a", 1)?;
131    /// tree.trivia("ws", 1)?;
132    /// tree.token("b", 1)?;
133    /// let tree = tree.build()?;
134    ///
135    /// let values = tree.children().map(|e| e.value()).collect::<Vec<_>>();
136    /// assert_eq!(values, ["a", "b"]);
137    ///
138    /// let values = tree.children().with_trivia().map(|e| e.value()).collect::<Vec<_>>();
139    /// assert_eq!(values, ["a", "ws", "b"]);
140    ///
141    /// let values = tree.children().with_trivia().rev().map(|e| e.value()).collect::<Vec<_>>();
142    /// assert_eq!(values, ["b", "ws", "a"]);
143    /// # Ok::<_, Box<dyn core::error::Error>>(())
144    /// ```
145    #[must_use]
146    pub const fn with_trivia(mut self) -> Self {
147        self.trivia = true;
148        self
149    }
150
151    /// Construct a [`SkipTokens`] iterator from the remainder of this iterator.
152    /// This filters out tokens and yields only interior [`Node`]s.
153    ///
154    /// See [`SkipTokens`] for documentation.
155    #[must_use]
156    pub const fn skip_tokens(self) -> SkipTokens<Self> {
157        SkipTokens::new(self)
158    }
159
160    /// Get the next interior node from the iterator, advancing past tokens.
161    ///
162    /// # Examples
163    ///
164    /// ```
165    /// let tree = syntree::tree! {
166    ///     ("token1", 1),
167    ///     "child1" => {
168    ///         "token2"
169    ///     },
170    ///     ("token3", 1),
171    ///     "child2" => {
172    ///         "token4"
173    ///     },
174    ///     ("token5", 1),
175    ///     "child3" => {
176    ///         "token6"
177    ///     },
178    ///     ("token7", 1)
179    /// };
180    ///
181    /// let mut it = tree.children();
182    /// let mut out = Vec::new();
183    ///
184    /// while let Some(n) = it.next_node() {
185    ///     out.push(n.value());
186    /// }
187    ///
188    /// assert_eq!(out, ["child1", "child2", "child3"]);
189    ///
190    /// let mut it = tree.children();
191    ///
192    /// let c1 = it.next_node().ok_or("missing child1")?;
193    /// let c2 = it.next_node().ok_or("missing child2")?;
194    /// let c3 = it.next_node().ok_or("missing child3")?;
195    ///
196    /// assert_eq!([c1.value(), c2.value(), c3.value()], ["child1", "child2", "child3"]);
197    /// # Ok::<_, Box<dyn core::error::Error>>(())
198    /// ```
199    #[inline]
200    pub fn next_node(&mut self) -> Option<Node<'a, T, F>> {
201        self.find_map(NodeOrToken::into_node)
202    }
203
204    /// Peek the next element from the front.
205    fn peek_front(&self) -> Option<Id<F::Pointer>> {
206        if self.done {
207            return None;
208        }
209
210        let id = self
211            .tree?
212            .next_at(self.parent, self.front.0, self.front.1)?;
213
214        if Some(id) == self.back_last {
215            return None;
216        }
217
218        Some(id)
219    }
220
221    /// Peek the next element from the back.
222    fn peek_back(&self) -> Option<Id<F::Pointer>> {
223        if self.done {
224            return None;
225        }
226
227        let id = self.tree?.prev_at(self.parent, self.back.0, self.back.1)?;
228
229        if Some(id) == self.front_last {
230            return None;
231        }
232
233        Some(id)
234    }
235}
236
237/// The outcome of a single step of [`Children`].
238enum Step<'a, T, F>
239where
240    T: Copy,
241    F: Flavor,
242{
243    /// An element to yield.
244    Yield(Element<'a, T, F>),
245    /// A trivia token was stepped over.
246    Skip,
247    /// The iterator is exhausted.
248    End,
249}
250
251impl<'a, T, F> Children<'a, T, F>
252where
253    T: Copy,
254    F: Flavor,
255{
256    /// Step from the front.
257    ///
258    /// This is [`Tree::next_at`], [`Tree::after`], the trivia test and the
259    /// element lookup fused, so each step looks its entry up once.
260    #[inline]
261    fn step_front(&mut self, tree: &'a Tree<T, F>) -> Step<'a, T, F> {
262        let (tok, node) = self.front;
263
264        if let Some(id) = node {
265            let Some(links) = tree.node_links(id) else {
266                return Step::End;
267            };
268
269            if links.tok_start.get() <= tok {
270                let next = Id::Node(id);
271
272                if Some(next) == self.back_last {
273                    return Step::End;
274                }
275
276                self.front = (links.tok_end.get(), links.next);
277                self.front_last = Some(next);
278                return Step::Yield(NodeOrToken::Node(Node::from_links(tree, links, id)));
279            }
280        }
281
282        let tokens = tree.tokens();
283        let mut index = tok;
284
285        let Some(mut links) = tokens.get(index) else {
286            return Step::End;
287        };
288
289        // A gap entry is always directly followed by its token.
290        if links.is_gap() {
291            let Some((n, l)) = index.checked_add(1).and_then(|n| Some((n, tokens.get(n)?))) else {
292                return Step::End;
293            };
294
295            index = n;
296            links = l;
297        }
298
299        if links.parent() != self.parent {
300            return Step::End;
301        }
302
303        let (Some(id), Some(after)) = (F::Pointer::new(index), index.checked_add(1)) else {
304            return Step::End;
305        };
306
307        let next = Id::Token(id);
308
309        if Some(next) == self.back_last {
310            return Step::End;
311        }
312
313        self.front = (after, node);
314        self.front_last = Some(next);
315
316        if !self.trivia && links.is_trivia() {
317            return Step::Skip;
318        }
319
320        Step::Yield(NodeOrToken::Token(Token::from_links(tree, links, id)))
321    }
322
323    /// Step from the back, the mirror of [`Children::step_front`] fusing
324    /// [`Tree::prev_at`] with the position before the element.
325    #[inline]
326    fn step_back(&mut self, tree: &'a Tree<T, F>) -> Step<'a, T, F> {
327        let (mut tok, node) = self.back;
328        let tokens = tree.tokens();
329
330        // A position right after a gap entry is the same as the one before it,
331        // since nothing is ever placed between a gap and its token.
332        if let Some(index) = tok.checked_sub(1) {
333            if tokens.get(index).is_some_and(TokenLinks::is_gap) {
334                tok = index;
335            }
336        }
337
338        if let Some(id) = node {
339            let Some(links) = tree.node_links(id) else {
340                return Step::End;
341            };
342
343            if links.tok_end.get() >= tok {
344                let prev = Id::Node(id);
345
346                if Some(prev) == self.front_last {
347                    return Step::End;
348                }
349
350                self.back = (links.tok_start.get(), links.prev);
351                self.back_last = Some(prev);
352                return Step::Yield(NodeOrToken::Node(Node::from_links(tree, links, id)));
353            }
354        }
355
356        let Some(index) = tok.checked_sub(1) else {
357            return Step::End;
358        };
359
360        let Some(links) = tokens.get(index) else {
361            return Step::End;
362        };
363
364        if links.is_gap() || links.parent() != self.parent {
365            return Step::End;
366        }
367
368        let Some(id) = F::Pointer::new(index) else {
369            return Step::End;
370        };
371
372        let prev = Id::Token(id);
373
374        if Some(prev) == self.front_last {
375            return Step::End;
376        }
377
378        self.back = (index, node);
379        self.back_last = Some(prev);
380
381        if !self.trivia && links.is_trivia() {
382            return Step::Skip;
383        }
384
385        Step::Yield(NodeOrToken::Token(Token::from_links(tree, links, id)))
386    }
387}
388
389impl<'a, T, F> Iterator for Children<'a, T, F>
390where
391    T: Copy,
392    F: Flavor,
393{
394    type Item = Element<'a, T, F>;
395
396    #[inline]
397    fn next(&mut self) -> Option<Self::Item> {
398        let tree = self.tree?;
399
400        while !self.done {
401            match self.step_front(tree) {
402                Step::Yield(element) => return Some(element),
403                Step::Skip => {}
404                Step::End => self.done = true,
405            }
406        }
407
408        None
409    }
410
411    #[inline]
412    fn size_hint(&self) -> (usize, Option<usize>) {
413        if self.done {
414            return (0, Some(0));
415        }
416
417        let len = self.tree.map_or(0, Tree::len);
418        (usize::from(self.peek_front().is_some()), Some(len))
419    }
420}
421
422impl<T, F> DoubleEndedIterator for Children<'_, T, F>
423where
424    T: Copy,
425    F: Flavor,
426{
427    #[inline]
428    fn next_back(&mut self) -> Option<Self::Item> {
429        let tree = self.tree?;
430
431        while !self.done {
432            match self.step_back(tree) {
433                Step::Yield(element) => return Some(element),
434                Step::Skip => {}
435                Step::End => self.done = true,
436            }
437        }
438
439        None
440    }
441}
442
443impl<T, F> FusedIterator for Children<'_, T, F>
444where
445    T: Copy,
446    F: Flavor,
447{
448}
449
450impl<T, F> Clone for Children<'_, T, F>
451where
452    T: Copy,
453    F: Flavor,
454{
455    #[inline]
456    fn clone(&self) -> Self {
457        Self {
458            tree: self.tree,
459            parent: self.parent,
460            front: self.front,
461            back: self.back,
462            front_last: self.front_last,
463            back_last: self.back_last,
464            done: self.done,
465            trivia: self.trivia,
466        }
467    }
468}
469
470impl<T, F> Default for Children<'_, T, F>
471where
472    T: Copy,
473    F: Flavor,
474{
475    #[inline]
476    fn default() -> Self {
477        Self {
478            tree: None,
479            parent: None,
480            front: (0, None),
481            back: (0, None),
482            front_last: None,
483            back_last: None,
484            done: true,
485            trivia: false,
486        }
487    }
488}
489
490impl<T, F> fmt::Debug for Children<'_, T, F>
491where
492    T: Copy + fmt::Debug,
493    F: Flavor<Index: fmt::Debug>,
494{
495    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496        let element = |id| self.tree.and_then(|tree| tree.element(id));
497
498        f.debug_struct("Children")
499            .field("first", &self.peek_front().and_then(element))
500            .field("last", &self.peek_back().and_then(element))
501            .finish()
502    }
503}