Skip to main content

syntree/node/
walk.rs

1use core::fmt;
2use core::iter::FusedIterator;
3
4use crate::flavor::Flavor;
5use crate::node::{Element, Event, Id, SkipTokens, WalkEvents};
6use crate::tree::Tree;
7
8/// An iterator that walks over the entire tree in depth-first order, visiting
9/// every node and token exactly once.
10///
11/// See [`Tree::walk`][crate::Tree::walk], [`Node::walk`][crate::Node::walk]
12/// or [`Token::walk`][crate::Token::walk].
13///
14/// # Examples
15///
16/// ```
17/// let tree = syntree::tree! {
18///     "root" => {
19///         "c1" => {
20///             "c2" => {},
21///             "c3" => {},
22///             "c4" => {},
23///         },
24///         "c5" => {},
25///         "c6" => {
26///            "c7" => {},
27///         }
28///     }
29/// };
30///
31/// // Walk the entire tree.
32/// assert_eq!(
33///     tree.walk().map(|n| n.value()).collect::<Vec<_>>(),
34///     ["root", "c1", "c2", "c3", "c4", "c5", "c6", "c7"],
35/// );
36///
37/// // Walk from the root.
38/// let root = tree.first().ok_or("missing root node")?;
39///
40/// assert_eq!(
41///     root.walk().map(|n| n.value()).collect::<Vec<_>>(),
42///     ["root", "c1", "c2", "c3", "c4", "c5", "c6", "c7"],
43/// );
44///
45/// // Walk from c1 and visit siblings.
46/// let c1 = root.first().ok_or("missing c1 node")?;
47///
48/// assert_eq!(
49///     c1.walk().map(|n| n.value()).collect::<Vec<_>>(),
50///     ["c1", "c2", "c3", "c4", "c5", "c6", "c7"],
51/// );
52///
53/// assert_eq!(
54///     c1.walk_from().map(|n| n.value()).collect::<Vec<_>>(),
55///     ["c5", "c6", "c7"],
56/// );
57///
58/// // Walk from c4 and visit parent siblings.
59/// let c4 = c1.last().ok_or("missing c1 node")?;
60///
61/// assert_eq!(
62///     c4.walk().map(|n| n.value()).collect::<Vec<_>>(),
63///     ["c4", "c5", "c6", "c7"],
64/// );
65///
66/// assert_eq!(
67///     c4.walk_from().map(|n| n.value()).collect::<Vec<_>>(),
68///     ["c5", "c6", "c7"],
69/// );
70///
71/// // Walk from c5 and visit siblings.
72/// let c5 = c1.next().ok_or("missing c5 node")?;
73///
74/// assert_eq!(
75///     c5.walk().map(|n| n.value()).collect::<Vec<_>>(),
76///     ["c5", "c6", "c7"],
77/// );
78///
79/// assert_eq!(
80///     c5.walk_from().map(|n| n.value()).collect::<Vec<_>>(),
81///     ["c6", "c7"],
82/// );
83/// # Ok::<_, Box<dyn core::error::Error>>(())
84/// ```
85pub struct Walk<'a, T, F>
86where
87    T: Copy,
88    F: Flavor,
89{
90    iter: WalkEvents<'a, T, F>,
91    // A tree-level walk has no single node to stay inside, so `inside` must
92    // not stop when the walk climbs back to the top level.
93    bounded: bool,
94}
95
96impl<'a, T, F> Walk<'a, T, F>
97where
98    T: Copy,
99    F: Flavor,
100{
101    /// Construct a new walk starting at an element, where `next` is the next
102    /// interior node at the level of `start` if it is a token.
103    #[inline]
104    pub(crate) fn new(
105        tree: &'a Tree<T, F>,
106        start: Option<Id<F::Pointer>>,
107        next: Option<F::Pointer>,
108        e: Event,
109    ) -> Self {
110        Self {
111            iter: WalkEvents::new(tree, start, next, e),
112            bounded: true,
113        }
114    }
115
116    /// Construct a new walk over every root of a tree.
117    #[inline]
118    pub(crate) fn tree(
119        tree: &'a Tree<T, F>,
120        start: Option<Id<F::Pointer>>,
121        next: Option<F::Pointer>,
122    ) -> Self {
123        Self {
124            iter: WalkEvents::new(tree, start, next, Event::Next),
125            bounded: false,
126        }
127    }
128
129    /// Convert this iterator into one that limits the walk to inside the
130    /// node it started at, visiting every node exactly once.
131    ///
132    /// The scope is the node the walk was constructed from, such as through
133    /// [`Node::walk`][crate::Node::walk] or [`Node::walk_from`][crate::Node::walk_from], even if this iterator has already
134    /// been advanced. A walk constructed through
135    /// [`Tree::walk`][crate::Tree::walk] has the whole tree as its scope, so it
136    /// visits the remaining nodes under every root.
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// let tree = syntree::tree! {
142    ///     "n1" => {
143    ///         "n3" => {
144    ///             "n4" => {},
145    ///             "n5" => {},
146    ///         }
147    ///     },
148    ///     "n6" => {
149    ///         "n7"
150    ///     }
151    /// };
152    ///
153    /// let values = tree.walk().map(|n| n.value()).collect::<Vec<_>>();
154    /// assert_eq!(values, ["n1", "n3", "n4", "n5", "n6", "n7"]);
155    ///
156    /// let n1 = tree.first().ok_or("missing n1")?;
157    ///
158    /// let values = n1.walk().map(|n| n.value()).collect::<Vec<_>>();
159    /// assert_eq!(values, ["n1", "n3", "n4", "n5", "n6", "n7"]);
160    ///
161    /// let values = n1.walk().inside().map(|n| n.value()).collect::<Vec<_>>();
162    /// assert_eq!(values, ["n1", "n3", "n4", "n5"]);
163    ///
164    /// let values = n1.walk_from().inside().map(|n| n.value()).collect::<Vec<_>>();
165    /// let empty: [&str; 0] = [];
166    /// assert_eq!(values, empty);
167    ///
168    /// let values = tree.walk().inside().map(|n| n.value()).collect::<Vec<_>>();
169    /// assert_eq!(values, ["n1", "n3", "n4", "n5", "n6", "n7"]);
170    ///
171    /// let mut walk = n1.walk();
172    /// assert_eq!(walk.next().map(|n| n.value()), Some("n1"));
173    /// assert_eq!(walk.next().map(|n| n.value()), Some("n3"));
174    /// let values = walk.inside().map(|n| n.value()).collect::<Vec<_>>();
175    /// assert_eq!(values, ["n4", "n5"]);
176    ///
177    /// # Ok::<_, Box<dyn core::error::Error>>(())
178    /// ```
179    #[inline]
180    #[must_use]
181    pub fn inside(self) -> Inside<'a, T, F> {
182        Inside {
183            iter: self.iter,
184            bounded: self.bounded,
185        }
186    }
187
188    /// Convert this iterator into one which includes depths.
189    ///
190    /// See [`WithDepths`] for how depths are counted.
191    ///
192    /// # Examples
193    ///
194    /// ```
195    /// let tree = syntree::tree! {
196    ///     "root" => {
197    ///         "c1" => {
198    ///             "c2" => {},
199    ///             "c3" => {},
200    ///         }
201    ///     }
202    /// };
203    ///
204    /// let mut it = tree.walk().with_depths().map(|(d, n)| (d, n.value()));
205    /// assert!(it.eq([(0, "root"), (1, "c1"), (2, "c2"), (2, "c3")]));
206    ///
207    /// # Ok::<_, Box<dyn core::error::Error>>(())
208    /// ```
209    #[inline]
210    #[must_use]
211    pub fn with_depths(self) -> WithDepths<'a, T, F> {
212        WithDepths { iter: self.iter }
213    }
214
215    /// Include trivia tokens, which this iterator skips by default.
216    ///
217    /// See [`Builder::trivia`][crate::Builder::trivia].
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// let mut tree = syntree::Builder::new();
223    /// tree.open("root")?;
224    /// tree.token("a", 1)?;
225    /// tree.trivia("ws", 1)?;
226    /// tree.token("b", 1)?;
227    /// tree.close()?;
228    /// let tree = tree.build()?;
229    ///
230    /// let values = tree.walk().map(|e| e.value()).collect::<Vec<_>>();
231    /// assert_eq!(values, ["root", "a", "b"]);
232    ///
233    /// let values = tree.walk().with_trivia().map(|e| e.value()).collect::<Vec<_>>();
234    /// assert_eq!(values, ["root", "a", "ws", "b"]);
235    /// # Ok::<_, Box<dyn core::error::Error>>(())
236    /// ```
237    #[inline]
238    #[must_use]
239    pub fn with_trivia(self) -> Self {
240        Self {
241            iter: self.iter.with_trivia(),
242            bounded: self.bounded,
243        }
244    }
245
246    /// Construct a [`SkipTokens`] iterator from the remainder of this iterator.
247    /// This filters out tokens and yields only interior [`Node`][crate::Node]s.
248    ///
249    /// See [`SkipTokens`] for documentation.
250    #[inline]
251    #[must_use]
252    pub fn skip_tokens(self) -> SkipTokens<Self> {
253        SkipTokens::new(self)
254    }
255
256    /// Get the next node with a corresponding depth.
257    ///
258    /// Depths are relative to the node the walk started at and become negative
259    /// once a walk started from a [`Node`][crate::Node] leaves that node's subtree, see
260    /// [`WithDepths`].
261    ///
262    /// Alternatively you can use [`WithDepths`] through [`Walk::with_depths`].
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// use std::iter;
268    ///
269    /// let tree = syntree::tree! {
270    ///     "root" => {
271    ///         "c1" => {
272    ///             "c2" => {},
273    ///             "c3" => {},
274    ///         }
275    ///     }
276    /// };
277    ///
278    /// let mut it = tree.walk();
279    /// let it = iter::from_fn(move || it.next_with_depth());
280    /// let it = it.map(|(d, n)| (d, n.value()));
281    ///
282    /// assert!(it.eq([(0, "root"), (1, "c1"), (2, "c2"), (2, "c3")]));
283    ///
284    /// # Ok::<_, Box<dyn core::error::Error>>(())
285    /// ```
286    #[inline]
287    #[must_use]
288    pub fn next_with_depth(&mut self) -> Option<(isize, Element<'a, T, F>)> {
289        next_with_depth(&mut self.iter)
290    }
291}
292
293impl<T, F> Clone for Walk<'_, T, F>
294where
295    T: Copy,
296    F: Flavor,
297{
298    #[inline]
299    fn clone(&self) -> Self {
300        Self {
301            iter: self.iter.clone(),
302            bounded: self.bounded,
303        }
304    }
305}
306
307impl<T, F> Default for Walk<'_, T, F>
308where
309    T: Copy,
310    F: Flavor,
311{
312    #[inline]
313    fn default() -> Self {
314        Self {
315            iter: WalkEvents::default(),
316            bounded: true,
317        }
318    }
319}
320
321impl<'a, T, F> Iterator for Walk<'a, T, F>
322where
323    T: Copy,
324    F: Flavor,
325{
326    type Item = Element<'a, T, F>;
327
328    #[inline]
329    fn next(&mut self) -> Option<Self::Item> {
330        loop {
331            let (event, node) = self.iter.next()?;
332
333            if !matches!(event, Event::Up) {
334                return Some(node);
335            }
336        }
337    }
338}
339
340impl<T, F> FusedIterator for Walk<'_, T, F>
341where
342    T: Copy,
343    F: Flavor,
344{
345}
346
347/// An iterator that walks over the entire tree, visiting every node exactly
348/// once and yielding each node together with its depth. This is constructed
349/// with [`Walk::with_depths`].
350///
351/// Depths are relative to the node the walk started at, which has depth `0`.
352/// A walk started from a [`Node`][crate::Node] continues past the end of that node's
353/// subtree into the following siblings of its ancestors, and those nodes have
354/// negative depths. This is why depths are [`isize`]. A walk started through
355/// [`Tree::walk`][crate::Tree::walk] gives every root depth `0`.
356///
357/// # Examples
358///
359/// ```
360/// let tree = syntree::tree! {
361///     "root" => {
362///         "c1" => {
363///             "c2" => {},
364///             "c3" => {},
365///             "c4" => {},
366///         },
367///         "c5" => {},
368///         "c6" => {}
369///     }
370/// };
371///
372/// assert_eq!(
373///     tree.walk().with_depths().map(|(d, n)| (d, n.value())).collect::<Vec<_>>(),
374///     [
375///         (0, "root"),
376///         (1, "c1"),
377///         (2, "c2"),
378///         (2, "c3"),
379///         (2, "c4"),
380///         (1, "c5"),
381///         (1, "c6")
382///     ]
383/// );
384///
385/// let root = tree.first().ok_or("missing root node")?;
386///
387/// assert_eq!(
388///     root.walk().with_depths().map(|(d, n)| (d, n.value())).collect::<Vec<_>>(),
389///     [
390///         (0, "root"),
391///         (1, "c1"),
392///         (2, "c2"),
393///         (2, "c3"),
394///         (2, "c4"),
395///         (1, "c5"),
396///         (1, "c6")
397///     ]
398/// );
399/// # Ok::<_, Box<dyn core::error::Error>>(())
400/// ```
401///
402/// Leaving the subtree of the starting node gives negative depths:
403///
404/// ```
405/// let tree = syntree::tree! {
406///     "root" => {
407///         "b" => {
408///             "b1" => {}
409///         },
410///         "c" => {},
411///         "d" => {}
412///     },
413///     "root2" => {
414///         "e" => {}
415///     }
416/// };
417///
418/// let b1 = tree.walk().find(|n| n.value() == "b1").ok_or("missing b1")?;
419///
420/// assert_eq!(
421///     b1.walk().with_depths().map(|(d, n)| (d, n.value())).collect::<Vec<_>>(),
422///     [(0, "b1"), (-1, "c"), (-1, "d"), (-2, "root2"), (-1, "e")]
423/// );
424///
425/// assert_eq!(
426///     tree.walk().with_depths().map(|(d, n)| (d, n.value())).collect::<Vec<_>>(),
427///     [(0, "root"), (1, "b"), (2, "b1"), (1, "c"), (1, "d"), (0, "root2"), (1, "e")]
428/// );
429/// # Ok::<_, Box<dyn core::error::Error>>(())
430/// ```
431pub struct WithDepths<'a, T, F>
432where
433    T: Copy,
434    F: Flavor,
435{
436    iter: WalkEvents<'a, T, F>,
437}
438
439impl<'a, T, F> Iterator for WithDepths<'a, T, F>
440where
441    T: Copy,
442    F: Flavor,
443{
444    type Item = (isize, Element<'a, T, F>);
445
446    #[inline]
447    fn next(&mut self) -> Option<Self::Item> {
448        next_with_depth(&mut self.iter)
449    }
450}
451
452#[inline]
453fn next_with_depth<'a, T, F>(iter: &mut WalkEvents<'a, T, F>) -> Option<(isize, Element<'a, T, F>)>
454where
455    T: Copy,
456    F: Flavor,
457{
458    loop {
459        let (depth, event, node) = iter.next_with(false)?;
460
461        if !matches!(event, Event::Up) {
462            return Some((depth, node));
463        }
464    }
465}
466
467impl<T, F> FusedIterator for WithDepths<'_, T, F>
468where
469    T: Copy,
470    F: Flavor,
471{
472}
473
474impl<T, F> Clone for WithDepths<'_, T, F>
475where
476    T: Copy,
477    F: Flavor,
478{
479    #[inline]
480    fn clone(&self) -> Self {
481        Self {
482            iter: self.iter.clone(),
483        }
484    }
485}
486
487impl<T, F> Default for WithDepths<'_, T, F>
488where
489    T: Copy,
490    F: Flavor,
491{
492    #[inline]
493    fn default() -> Self {
494        Self {
495            iter: WalkEvents::default(),
496        }
497    }
498}
499
500/// An iterator that limits the walk to inside the node it started at, visiting
501/// every node exactly once. This is constructed with [`Walk::inside`].
502///
503/// The scope is the node the [`Walk`] was constructed from, even if it was
504/// advanced before calling [`Walk::inside`]. For a walk constructed through
505/// [`Tree::walk`][crate::Tree::walk] the scope is the whole tree, covering
506/// every root.
507///
508/// # Examples
509///
510/// ```
511/// let tree = syntree::tree! {
512///     "n1" => {
513///         "n3" => {
514///             "n4" => {},
515///             "n5" => {},
516///         }
517///     },
518///     "n6" => {
519///         "n7"
520///     }
521/// };
522///
523/// let values = tree.walk().map(|n| n.value()).collect::<Vec<_>>();
524/// assert_eq!(values, ["n1", "n3", "n4", "n5", "n6", "n7"]);
525///
526/// let n1 = tree.first().ok_or("missing n1")?;
527///
528/// let values = n1.walk().map(|n| n.value()).collect::<Vec<_>>();
529/// assert_eq!(values, ["n1", "n3", "n4", "n5", "n6", "n7"]);
530///
531/// let values = n1.walk().inside().map(|n| n.value()).collect::<Vec<_>>();
532/// assert_eq!(values, ["n1", "n3", "n4", "n5"]);
533///
534/// let values = n1.walk_from().inside().map(|n| n.value()).collect::<Vec<_>>();
535/// let empty: [&str; 0] = [];
536/// assert_eq!(values, empty);
537///
538/// let values = tree.walk().inside().map(|n| n.value()).collect::<Vec<_>>();
539/// assert_eq!(values, ["n1", "n3", "n4", "n5", "n6", "n7"]);
540///
541/// # Ok::<_, Box<dyn core::error::Error>>(())
542/// ```
543///
544/// The iterator can be named, for example to store it in a struct:
545///
546/// ```
547/// use syntree::node::Inside;
548/// use syntree::FlavorDefault;
549///
550/// struct Values<'a> {
551///     iter: Inside<'a, &'static str, FlavorDefault>,
552/// }
553///
554/// impl Iterator for Values<'_> {
555///     type Item = &'static str;
556///
557///     fn next(&mut self) -> Option<Self::Item> {
558///         Some(self.iter.next()?.value())
559///     }
560/// }
561///
562/// let tree = syntree::tree! {
563///     "n1" => {
564///         "n2" => {}
565///     },
566///     "n3" => {}
567/// };
568///
569/// let n1 = tree.first().ok_or("missing n1")?;
570/// let values = Values { iter: n1.walk().inside() };
571/// assert_eq!(values.collect::<Vec<_>>(), ["n1", "n2"]);
572/// # Ok::<_, Box<dyn core::error::Error>>(())
573/// ```
574pub struct Inside<'a, T, F>
575where
576    T: Copy,
577    F: Flavor,
578{
579    iter: WalkEvents<'a, T, F>,
580    bounded: bool,
581}
582
583impl<'a, T, F> Iterator for Inside<'a, T, F>
584where
585    T: Copy,
586    F: Flavor,
587{
588    type Item = Element<'a, T, F>;
589
590    #[inline]
591    fn next(&mut self) -> Option<Self::Item> {
592        loop {
593            let (_, event, node) = self.iter.next_with(self.bounded)?;
594
595            if !matches!(event, Event::Up) {
596                return Some(node);
597            }
598        }
599    }
600}
601
602impl<T, F> FusedIterator for Inside<'_, T, F>
603where
604    T: Copy,
605    F: Flavor,
606{
607}
608
609impl<T, F> Clone for Inside<'_, T, F>
610where
611    T: Copy,
612    F: Flavor,
613{
614    #[inline]
615    fn clone(&self) -> Self {
616        Self {
617            iter: self.iter.clone(),
618            bounded: self.bounded,
619        }
620    }
621}
622
623impl<T, F> Default for Inside<'_, T, F>
624where
625    T: Copy,
626    F: Flavor,
627{
628    #[inline]
629    fn default() -> Self {
630        Self {
631            iter: WalkEvents::default(),
632            bounded: true,
633        }
634    }
635}
636
637impl<T, F> fmt::Debug for Walk<'_, T, F>
638where
639    T: Copy + fmt::Debug,
640    F: Flavor<Index: fmt::Debug>,
641{
642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643        f.debug_struct("Walk")
644            .field("events", &self.iter)
645            .finish_non_exhaustive()
646    }
647}
648
649impl<T, F> fmt::Debug for WithDepths<'_, T, F>
650where
651    T: Copy + fmt::Debug,
652    F: Flavor<Index: fmt::Debug>,
653{
654    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655        f.debug_struct("WithDepths")
656            .field("events", &self.iter)
657            .finish()
658    }
659}
660
661impl<T, F> fmt::Debug for Inside<'_, T, F>
662where
663    T: Copy + fmt::Debug,
664    F: Flavor<Index: fmt::Debug>,
665{
666    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
667        f.debug_struct("Inside")
668            .field("events", &self.iter)
669            .finish_non_exhaustive()
670    }
671}