Skip to main content

syntree/node/
walk_events.rs

1use core::fmt;
2use core::iter::FusedIterator;
3
4use crate::flavor::Flavor;
5use crate::node::{Element, Id};
6use crate::pointer::Pointer;
7use crate::tree::Tree;
8
9/// An event indicating how a tree is being walked with [`WalkEvents`].
10///
11/// See [`WalkEvents`] for documentation.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum Event {
14    /// Walk the next sibling node. This is also the initial event being emitted
15    /// when entering the iterator.
16    Next,
17    /// Walk down the first child of a sub tree.
18    Down,
19    /// Walk up a single step from a sub tree.
20    Up,
21}
22
23/// The next element of a walk, how it is reached, and the next interior node
24/// at its level.
25type State<P> = (Id<P>, Event, Option<P>);
26
27/// A low-level iterator which walks the tree while emitting [Event] instances
28/// indicating *how* the structure is being navigated.
29///
30/// See [`Tree::walk_events`][crate::Tree::walk_events] or
31/// [`Node::walk_events`][crate::Node::walk_events].
32///
33/// # Examples
34///
35/// ```
36/// use syntree::node::Event::*;
37///
38/// let tree = syntree::tree! {
39///     "root" => {
40///         "c1" => {
41///             "c2" => {},
42///             "c3" => {},
43///             "c4" => {},
44///         },
45///         "c5" => {},
46///         "c6" => {}
47///     }
48/// };
49///
50/// assert_eq!(
51///     tree.walk_events().map(|(e, n)| (e, n.value())).collect::<Vec<_>>(),
52///     [
53///         (Next, "root"),
54///         (Down, "c1"),
55///         (Down, "c2"),
56///         (Next, "c3"),
57///         (Next, "c4"),
58///         (Up, "c1"),
59///         (Next, "c5"),
60///         (Next, "c6"),
61///         (Up, "root")
62///     ]
63/// );
64///
65/// let root = tree.first().ok_or("missing root")?;
66///
67/// assert_eq!(
68///     root.walk_events().map(|(e, n)| (e, n.value())).collect::<Vec<_>>(),
69///     [
70///         (Next, "root"),
71///         (Down, "c1"),
72///         (Down, "c2"),
73///         (Next, "c3"),
74///         (Next, "c4"),
75///         (Up, "c1"),
76///         (Next, "c5"),
77///         (Next, "c6"),
78///         (Up, "root"),
79///     ]
80/// );
81///
82/// let c1 = root.first().ok_or("missing c1")?;
83///
84/// assert_eq!(
85///     c1.walk_events().map(|(e, n)| (e, n.value())).collect::<Vec<_>>(),
86///     [
87///         (Next, "c1"),
88///         (Down, "c2"),
89///         (Next, "c3"),
90///         (Next, "c4"),
91///         (Up, "c1"),
92///         (Next, "c5"),
93///         (Next, "c6"),
94///         (Up, "root"),
95///     ]
96/// );
97/// # Ok::<_, Box<dyn core::error::Error>>(())
98/// ```
99///
100/// Example showcasing how we can use events to keep track of the depth in which
101/// nodes are being traversed:
102///
103/// ```
104/// use syntree::node::Event::*;
105///
106/// let tree = syntree::tree! {
107///     "root" => {
108///         "c1" => {
109///             "c2" => {},
110///             "c3" => {},
111///         }
112///     }
113/// };
114///
115/// let mut it = tree.walk_events();
116/// let mut depth = 0;
117///
118/// let mut nodes = Vec::new();
119///
120/// while let Some((event, node)) = it.next() {
121///     // Only register each node once.
122///     match event {
123///         Up => {
124///             depth -= 1;
125///         }
126///         Down => {
127///             depth += 1;
128///             nodes.push((depth, node.value()));
129///         }
130///         Next => {
131///             nodes.push((depth, node.value()));
132///         }
133///     }
134/// }
135///
136/// assert_eq!(depth, 0);
137///
138/// assert_eq!(
139///     nodes,
140///     [(0, "root"), (1, "c1"), (2, "c2"), (2, "c3")]
141/// );
142/// # Ok::<_, Box<dyn core::error::Error>>(())
143/// ```
144pub struct WalkEvents<'a, T, F>
145where
146    T: Copy,
147    F: Flavor,
148{
149    tree: Option<&'a Tree<T, F>>,
150    /// The next element, how it is reached, and the next interior node at its
151    /// level, which is only used when the element is a token.
152    node: Option<State<F::Pointer>>,
153    /// Current depth being walked.
154    depth: isize,
155    /// Whether trivia tokens are yielded.
156    trivia: bool,
157}
158
159impl<'a, T, F> WalkEvents<'a, T, F>
160where
161    T: Copy,
162    F: Flavor,
163{
164    /// Walk from `start`, where `next` is the next interior node at the level
165    /// of `start` if it is a token.
166    ///
167    /// The first element is reached with `event`. With [`Event::Up`] the walk
168    /// does not descend into `start`.
169    #[inline]
170    pub(crate) fn new(
171        tree: &'a Tree<T, F>,
172        start: Option<Id<F::Pointer>>,
173        next: Option<F::Pointer>,
174        event: Event,
175    ) -> Self {
176        Self {
177            tree: Some(tree),
178            node: start.map(|id| (id, event, next)),
179            depth: 0,
180            trivia: false,
181        }
182    }
183
184    /// Include trivia tokens, which this iterator skips by default.
185    ///
186    /// Skipping trivia keeps the events balanced: a node whose only children
187    /// are trivia is walked like a node without children, so it gets neither
188    /// a [`Event::Down`] into it nor an [`Event::Up`] out of it.
189    ///
190    /// See [`Builder::trivia`][crate::Builder::trivia].
191    ///
192    /// # Examples
193    ///
194    /// ```
195    /// use syntree::node::Event::*;
196    ///
197    /// let mut tree = syntree::Builder::new();
198    /// tree.open("a")?;
199    /// tree.trivia("ws", 1)?;
200    /// tree.close()?;
201    /// tree.open("b")?;
202    /// tree.trivia("ws", 1)?;
203    /// tree.token("lit", 1)?;
204    /// tree.close()?;
205    /// let tree = tree.build()?;
206    ///
207    /// let events = tree.walk_events().map(|(e, n)| (e, n.value())).collect::<Vec<_>>();
208    /// assert_eq!(events, [(Next, "a"), (Next, "b"), (Down, "lit"), (Up, "b")]);
209    ///
210    /// let events = tree
211    ///     .walk_events()
212    ///     .with_trivia()
213    ///     .map(|(e, n)| (e, n.value()))
214    ///     .collect::<Vec<_>>();
215    ///
216    /// assert_eq!(
217    ///     events,
218    ///     [
219    ///         (Next, "a"),
220    ///         (Down, "ws"),
221    ///         (Up, "a"),
222    ///         (Next, "b"),
223    ///         (Down, "ws"),
224    ///         (Next, "lit"),
225    ///         (Up, "b"),
226    ///     ]
227    /// );
228    /// # Ok::<_, Box<dyn core::error::Error>>(())
229    /// ```
230    #[must_use]
231    pub const fn with_trivia(mut self) -> Self {
232        self.trivia = true;
233        self
234    }
235
236    /// The next event with the depth it is at, skipping trivia unless it is
237    /// included. With `inside` the walk ends once it is back at depth zero or
238    /// above, which is what [`Walk::inside`][crate::node::Walk::inside]
239    /// does.
240    pub(crate) fn next_with(&mut self, inside: bool) -> Option<(isize, Event, Element<'a, T, F>)> {
241        let tree = self.tree?;
242        // A `Down` into a skipped trivia token, which the next element at its
243        // level takes over.
244        let mut down = false;
245
246        loop {
247            let depth = self.depth;
248            let (id, mut event, next) = self.node.take()?;
249            self.node = self.step(tree, id, event, next);
250
251            if inside && self.depth <= 0 {
252                self.node = None;
253            }
254
255            if !self.trivia && tree.is_trivia(id) {
256                down |= matches!(event, Event::Down);
257                continue;
258            }
259
260            if down {
261                down = false;
262
263                match event {
264                    Event::Next => event = Event::Down,
265                    // Every child was trivia, so the node was never entered.
266                    Event::Up => continue,
267                    Event::Down => {}
268                }
269            }
270
271            return Some((depth, event, tree.element(id)?));
272        }
273    }
274
275    /// Get the depth of the node that the next call to [`next`] returns,
276    /// relative to the node the walk started at, which has depth `0`.
277    ///
278    /// A node emitted with [`Event::Up`] has the depth of the node being
279    /// returned to. When a walk started at a node leaves that node's subtree,
280    /// for example by climbing up to its parent, the depth becomes negative.
281    ///
282    /// Once the iterator is exhausted, the depth is that of the last node it
283    /// returned.
284    ///
285    /// [`next`]: Iterator::next
286    ///
287    /// # Examples
288    ///
289    /// ```
290    /// use syntree::node::Event::*;
291    ///
292    /// let tree = syntree::tree! {
293    ///     "root" => {
294    ///         "c1" => {
295    ///             "c2" => {},
296    ///         },
297    ///         "c3" => {}
298    ///     }
299    /// };
300    ///
301    /// let mut it = tree.walk_events();
302    /// let mut out = Vec::new();
303    ///
304    /// loop {
305    ///     let depth = it.depth();
306    ///     let Some((event, node)) = it.next() else { break };
307    ///     out.push((depth, event, node.value()));
308    /// }
309    ///
310    /// assert_eq!(
311    ///     out,
312    ///     [
313    ///         (0, Next, "root"),
314    ///         (1, Down, "c1"),
315    ///         (2, Down, "c2"),
316    ///         (1, Up, "c1"),
317    ///         (1, Next, "c3"),
318    ///         (0, Up, "root"),
319    ///     ]
320    /// );
321    ///
322    /// let c1 = tree.first().and_then(|n| n.first()).ok_or("missing c1")?;
323    ///
324    /// let mut it = c1.walk_events();
325    /// let mut out = Vec::new();
326    ///
327    /// loop {
328    ///     let depth = it.depth();
329    ///     let Some((event, node)) = it.next() else { break };
330    ///     out.push((depth, event, node.value()));
331    /// }
332    ///
333    /// assert_eq!(
334    ///     out,
335    ///     [
336    ///         (0, Next, "c1"),
337    ///         (1, Down, "c2"),
338    ///         (0, Up, "c1"),
339    ///         (0, Next, "c3"),
340    ///         (-1, Up, "root"),
341    ///     ]
342    /// );
343    /// # Ok::<_, Box<dyn core::error::Error>>(())
344    /// ```
345    #[inline]
346    #[must_use]
347    pub const fn depth(&self) -> isize {
348        self.depth
349    }
350
351    fn step(
352        &mut self,
353        tree: &'a Tree<T, F>,
354        id: Id<F::Pointer>,
355        event: Event,
356        next: Option<F::Pointer>,
357    ) -> Option<State<F::Pointer>> {
358        let parent = match id {
359            Id::Node(n) => {
360                let links = tree.node_links(n)?;
361
362                if !matches!(event, Event::Up) {
363                    if let Some(first) = tree.next_at(Some(n), links.tok_start.get(), links.first) {
364                        self.depth = self.depth.checked_add(1)?;
365                        return Some((first, Event::Down, links.first));
366                    }
367                }
368
369                if let Some(id) = tree.next_at(links.parent, links.tok_end.get(), links.next) {
370                    return Some((id, Event::Next, links.next));
371                }
372
373                links.parent
374            }
375            Id::Token(t) => {
376                let index = t.get();
377                let links = tree.tokens().get(index)?;
378
379                if let Some(id) = tree.next_at(links.parent(), index.checked_add(1)?, next) {
380                    return Some((id, Event::Next, next));
381                }
382
383                links.parent()
384            }
385        };
386
387        let parent = parent?;
388        self.depth = self.depth.checked_sub(1)?;
389        Some((Id::Node(parent), Event::Up, None))
390    }
391}
392
393impl<T, F> Clone for WalkEvents<'_, T, F>
394where
395    T: Copy,
396    F: Flavor,
397{
398    #[inline]
399    fn clone(&self) -> Self {
400        Self {
401            tree: self.tree,
402            node: self.node,
403            depth: self.depth,
404            trivia: self.trivia,
405        }
406    }
407}
408
409impl<T, F> Default for WalkEvents<'_, T, F>
410where
411    T: Copy,
412    F: Flavor,
413{
414    #[inline]
415    fn default() -> Self {
416        Self {
417            tree: None,
418            node: None,
419            depth: 0,
420            trivia: false,
421        }
422    }
423}
424
425impl<'a, T, F> Iterator for WalkEvents<'a, T, F>
426where
427    T: Copy,
428    F: Flavor,
429{
430    type Item = (Event, Element<'a, T, F>);
431
432    fn next(&mut self) -> Option<Self::Item> {
433        let (_, event, element) = self.next_with(false)?;
434        Some((event, element))
435    }
436
437    #[inline]
438    fn size_hint(&self) -> (usize, Option<usize>) {
439        (usize::from(self.node.is_some()), None)
440    }
441}
442
443impl<T, F> FusedIterator for WalkEvents<'_, T, F>
444where
445    T: Copy,
446    F: Flavor,
447{
448}
449
450impl<T, F> fmt::Debug for WalkEvents<'_, T, F>
451where
452    T: Copy + fmt::Debug,
453    F: Flavor<Index: fmt::Debug>,
454{
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        let next = self
457            .tree
458            .zip(self.node)
459            .and_then(|(tree, (id, event, _))| Some((event, tree.element(id)?)));
460
461        f.debug_struct("WalkEvents")
462            .field("next", &next)
463            .field("depth", &self.depth)
464            .finish()
465    }
466}