Skip to main content

syntree/node/
node_impl.rs

1use core::fmt;
2use core::mem::size_of;
3use core::ops::Range;
4
5use crate::flavor::Flavor;
6use crate::links::Links;
7use crate::node::{Ancestors, Children, Event, Siblings, Walk, WalkEvents};
8use crate::pointer::Pointer;
9use crate::span::Span;
10
11/// A node in the tree.
12///
13/// # Type parameters and bounds
14///
15/// The two type parameters of the tree determine the following properties:
16/// * `T` is the data stored in the tree.
17/// * `F` determines the [Flavor] of the tree, defining numerical bounds of
18///   spans and node identifiers stored in the tree.
19///
20/// A tree built through [Builder::new][crate::Builder::new] uses
21/// [`FlavorDefault`][crate::FlavorDefault].
22pub struct Node<'a, T, F>
23where
24    T: Copy,
25    F: Flavor,
26{
27    links: &'a Links<T, F::Index, F::Pointer>,
28    tree: &'a [Links<T, F::Index, F::Pointer>],
29}
30
31impl<'a, T, F> Node<'a, T, F>
32where
33    T: Copy,
34    F: Flavor,
35{
36    pub(crate) const fn new(
37        links: &'a Links<T, F::Index, F::Pointer>,
38        tree: &'a [Links<T, F::Index, F::Pointer>],
39    ) -> Self {
40        Self { links, tree }
41    }
42
43    /// Access the data associated with the node.
44    ///
45    /// # Examples
46    ///
47    /// ```
48    /// let tree = syntree::tree! {
49    ///     "root" => {
50    ///         ("number", 5),
51    ///         ("ident", 3),
52    ///     }
53    /// };
54    ///
55    /// let root = tree.first().ok_or("missing root")?;
56    /// assert_eq!(root.value(), "root");
57    ///
58    /// let number = root.first().ok_or("missing number")?;
59    /// assert_eq!(number.value(), "number");
60    ///
61    /// let ident = number.next().ok_or("missing ident")?;
62    /// assert_eq!(ident.value(), "ident");
63    /// # Ok::<_, Box<dyn core::error::Error>>(())
64    /// ```
65    #[must_use]
66    pub fn value(&self) -> T {
67        self.links.data.get()
68    }
69
70    /// Replace the value of the node with a new one, returning the old value.
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// let tree = syntree::tree! {
76    ///     "root" => {
77    ///         ("number", 5),
78    ///         ("ident", 3),
79    ///     }
80    /// };
81    ///
82    /// let root = tree.first().ok_or("missing root")?;
83    /// assert_eq!(root.value(), "root");
84    ///
85    /// let number = root.first().ok_or("missing number")?;
86    /// assert_eq!(number.value(), "number");
87    /// assert_eq!(number.replace("other"), "number");
88    /// assert_eq!(number.value(), "other");
89    ///
90    /// let ident = number.next().ok_or("missing ident")?;
91    /// assert_eq!(ident.value(), "ident");
92    /// # Ok::<_, Box<dyn core::error::Error>>(())
93    /// ```
94    pub fn replace(&self, value: T) -> T {
95        self.links.data.replace(value)
96    }
97
98    /// Check if the current node has children or not.
99    ///
100    /// Nodes without children are also known as tokens.
101    ///
102    /// # Examples
103    ///
104    /// ```
105    /// let tree = syntree::tree! {
106    ///     "root" => {
107    ///         ("number", 5),
108    ///         ("ident", 3),
109    ///     }
110    /// };
111    ///
112    /// let root = tree.first().ok_or("missing root")?;
113    /// assert!(root.has_children());
114    /// assert!(root.children().all(|n| !n.has_children()));
115    /// # Ok::<_, Box<dyn core::error::Error>>(())
116    /// ```
117    #[must_use]
118    pub const fn has_children(&self) -> bool {
119        self.links.first.is_some()
120    }
121
122    /// Get the span of the current node. The span of a node is the complete
123    /// span of all its children.
124    ///
125    /// # Examples
126    ///
127    /// ```
128    /// use syntree::Span;
129    ///
130    /// let tree = syntree::tree! {
131    ///     "root" => {
132    ///         "number" => {
133    ///             ("lit", 5)
134    ///         },
135    ///         "ident" => {
136    ///             ("lit", 3)
137    ///         }
138    ///     },
139    ///     "root2" => {
140    ///         ("whitespace", 5)
141    ///     }
142    /// };
143    ///
144    /// let root = tree.first().ok_or("missing root")?;
145    /// assert_eq!(root.span(), Span::new(0, 8));
146    ///
147    /// let root2 = root.next().ok_or("missing second root")?;
148    /// assert_eq!(root2.span(), Span::new(8, 13));
149    /// # Ok::<_, Box<dyn core::error::Error>>(())
150    /// ```
151    #[must_use]
152    pub const fn span(&self) -> &Span<F::Index> {
153        &self.links.span
154    }
155
156    /// Check if the current node is empty. In that it doesn't have any
157    /// children.
158    ///
159    /// # Examples
160    ///
161    /// ```
162    /// let mut tree = syntree::tree! {
163    ///     "root",
164    ///     "root2" => {
165    ///         ("token2", 5)
166    ///     }
167    /// };
168    ///
169    /// let first = tree.first().ok_or("missing root")?;
170    /// let last = first.next().ok_or("missing root2")?;
171    ///
172    /// assert!(first.is_empty());
173    /// assert!(!last.is_empty());
174    /// # Ok::<_, Box<dyn core::error::Error>>(())
175    /// ```
176    #[must_use]
177    pub const fn is_empty(&self) -> bool {
178        self.links.first.is_none()
179    }
180
181    /// Get an iterator over this node and its ancestors, starting with the
182    /// node itself and ending with its root.
183    ///
184    /// See [Ancestors] for documentation.
185    #[must_use]
186    pub fn ancestors(&self) -> Ancestors<'a, T, F> {
187        Ancestors::new(Some(*self))
188    }
189
190    /// Get an iterator over this node and its following siblings.
191    ///
192    /// Previous siblings are not included.
193    ///
194    /// See [Siblings] for documentation.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// let tree = syntree::tree! {
200    ///     "root" => {
201    ///         "a",
202    ///         "b",
203    ///         "c",
204    ///         "d",
205    ///     }
206    /// };
207    ///
208    /// let c = tree.first().and_then(|n| n.last()).and_then(|n| n.prev()).ok_or("missing c")?;
209    /// assert_eq!(c.value(), "c");
210    ///
211    /// assert_eq!(
212    ///     c.siblings().map(|n| n.value()).collect::<Vec<_>>(),
213    ///     ["c", "d"]
214    /// );
215    /// # Ok::<_, Box<dyn core::error::Error>>(())
216    /// ```
217    #[must_use]
218    pub fn siblings(&self) -> Siblings<'a, T, F> {
219        Siblings::new(self.tree, self.links)
220    }
221
222    /// Get an iterator over the children of this node.
223    ///
224    /// See [Children] for documentation.
225    #[must_use]
226    pub fn children(&self) -> Children<'a, T, F> {
227        Children::new(self.tree, self.links.first, self.links.last)
228    }
229
230    /// Walk the tree forward in depth-first order starting with the current
231    /// node.
232    ///
233    /// The walk does not stop at the end of this node's subtree, it continues
234    /// with the following siblings of this node and of its ancestors. Use
235    /// [`Walk::inside`] to only visit this node and its descendants.
236    ///
237    /// See [Walk] for documentation.
238    #[must_use]
239    pub fn walk(&self) -> Walk<'a, T, F> {
240        Walk::new(self.tree, Some(self.id()), Event::Next)
241    }
242
243    /// Walk from the current node forwards and upwards through the tree.
244    ///
245    /// This does not include the current node in the walk.
246    ///
247    /// See [Walk] for documentation.
248    #[must_use]
249    pub fn walk_from(&self) -> Walk<'a, T, F> {
250        Walk::new(self.tree, Some(self.id()), Event::Up)
251    }
252
253    /// Walk the node forwards in a depth-first fashion emitting events
254    /// indicating how the rest of the tree is being traversed.
255    ///
256    /// See [`WalkEvents`] for documentation.
257    #[must_use]
258    pub fn walk_events(&self) -> WalkEvents<'a, T, F> {
259        WalkEvents::new(self.tree, Some(self.id()), Event::Next)
260    }
261}
262
263impl<'a, T, F> Node<'a, T, F>
264where
265    T: Copy,
266    F: Flavor,
267{
268    /// Get immediate parent to this node.
269    ///
270    /// # Examples
271    ///
272    /// ```
273    /// let tree = syntree::tree! {
274    ///     "root" => {
275    ///         "number" => {
276    ///             ("lit", 5)
277    ///         },
278    ///         "ident" => {
279    ///             ("lit", 3)
280    ///         }
281    ///     },
282    ///     "root2" => {
283    ///         ("whitespace", 5)
284    ///     }
285    /// };
286    ///
287    /// let root = tree.first().ok_or("missing root")?;
288    /// assert_eq!(root.value(), "root");
289    /// assert!(root.parent().is_none());
290    ///
291    /// let number = root.first().ok_or("missing number")?;
292    /// assert_eq!(number.value(), "number");
293    ///
294    /// let root = number.parent().ok_or("missing parent")?;
295    /// assert_eq!(root.value(), "root");
296    /// # Ok::<_, Box<dyn core::error::Error>>(())
297    /// ```
298    #[must_use]
299    pub fn parent(&self) -> Option<Node<'a, T, F>> {
300        self.node_at(self.links.parent?)
301    }
302
303    /// Get the previous sibling.
304    ///
305    /// # Examples
306    ///
307    /// ```
308    /// let tree = syntree::tree! {
309    ///     "root" => {
310    ///         "number" => {
311    ///             ("lit", 5)
312    ///         },
313    ///         "ident" => {
314    ///             ("lit", 3)
315    ///         }
316    ///     }
317    /// };
318    ///
319    /// let number = tree.first().and_then(|n| n.first()).ok_or("missing number")?;
320    /// assert_eq!(number.value(), "number");
321    /// assert!(number.prev().is_none());
322    ///
323    /// let ident = number.next().ok_or("missing ident")?;
324    /// assert_eq!(ident.value(), "ident");
325    ///
326    /// let number = ident.prev().ok_or("missing number")?;
327    /// assert_eq!(number.value(), "number");
328    /// # Ok::<_, Box<dyn core::error::Error>>(())
329    /// ```
330    #[must_use]
331    pub fn prev(&self) -> Option<Node<'a, T, F>> {
332        self.node_at(self.links.prev?)
333    }
334
335    /// Get the next sibling.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// let tree = syntree::tree! {
341    ///     "root" => {
342    ///         "number" => {
343    ///             ("lit", 5)
344    ///         },
345    ///         "ident" => {
346    ///             ("lit", 3)
347    ///         }
348    ///     }
349    /// };
350    ///
351    /// let root = tree.first().ok_or("missing root")?;
352    /// assert_eq!(root.value(), "root");
353    ///
354    /// let number = root.first().ok_or("missing second root")?;
355    /// assert_eq!(number.value(), "number");
356    ///
357    /// let ident = number.next().ok_or("missing second root")?;
358    /// assert_eq!(ident.value(), "ident");
359    /// # Ok::<_, Box<dyn core::error::Error>>(())
360    /// ```
361    #[must_use]
362    pub fn next(&self) -> Option<Node<'a, T, F>> {
363        self.node_at(self.links.next?)
364    }
365
366    /// Get the first child node.
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// let tree = syntree::tree! {
372    ///     "root" => {
373    ///         "number" => {
374    ///             ("lit", 5)
375    ///         },
376    ///         "ident" => {
377    ///             ("lit", 3)
378    ///         }
379    ///     },
380    ///     "root2" => {
381    ///         ("whitespace", 5)
382    ///     }
383    /// };
384    ///
385    /// let root = tree.first().ok_or("missing root")?;
386    /// assert_eq!(root.value(), "root");
387    ///
388    /// let number = root.first().ok_or("missing number")?;
389    /// assert_eq!(number.value(), "number");
390    /// # Ok::<_, Box<dyn core::error::Error>>(())
391    /// ```
392    #[must_use]
393    pub fn first(&self) -> Option<Node<'a, T, F>> {
394        self.node_at(self.links.first?)
395    }
396
397    /// Get the last child node.
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// let tree = syntree::tree! {
403    ///     "root" => {
404    ///         "number" => {
405    ///             ("lit", 5)
406    ///         },
407    ///         "ident" => {
408    ///             ("lit", 3)
409    ///         }
410    ///     },
411    ///     "root2" => {
412    ///         ("whitespace", 5)
413    ///     }
414    /// };
415    ///
416    /// let root2 = tree.last().ok_or("missing root2")?;
417    /// assert_eq!(root2.value(), "root2");
418    ///
419    /// let whitespace = root2.last().ok_or("missing whitespace")?;
420    /// assert_eq!(whitespace.value(), "whitespace");
421    /// # Ok::<_, Box<dyn core::error::Error>>(())
422    /// ```
423    #[must_use]
424    pub fn last(&self) -> Option<Node<'a, T, F>> {
425        self.node_at(self.links.last?)
426    }
427
428    /// Find a preceding node which matches the given predicate.
429    ///
430    /// A "preceding node" is one whose tokens immediately precede the tokens of
431    /// the current node. This is found in two steps:
432    ///
433    /// 1. Starting with the current node and moving through its ancestors, find
434    ///    the first [`Node::prev`] sibling which matches the predicate.
435    /// 2. From that sibling, descend through [`Node::last`] children for as
436    ///    long as each matches the predicate, and return the last match.
437    ///
438    /// Step 2 stops at the first [`Node::last`] child which does not match, so
439    /// a matching node nested below a non-matching last child is not found.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// let tree = syntree::tree! {
445    ///     "root" => {
446    ///         "child1" => {
447    ///             ("token2", 1),
448    ///             "child2" => {
449    ///                 ("token1", 2)
450    ///             }
451    ///         },
452    ///         "child3" => {
453    ///             "child4" => {
454    ///                 ("token1", 4),
455    ///             }
456    ///         }
457    ///     }
458    /// };
459    ///
460    /// let node = tree.node_with_range(3..3).ok_or("missing 3")?;
461    /// assert_eq!(node.value(), "token1");
462    ///
463    /// let found = node.find_preceding(|n| n.span().end == 3 && n.has_children());
464    /// let found = found.ok_or("expected preceding node")?;
465    /// assert_eq!(found.value(), "child2");
466    /// # Ok::<_, Box<dyn core::error::Error>>(())
467    /// ```
468    pub fn find_preceding<P>(&self, mut predicate: P) -> Option<Node<'a, T, F>>
469    where
470        P: FnMut(Node<'a, T, F>) -> bool,
471    {
472        let mut n = *self;
473
474        let mut n = loop {
475            if let Some(prev) = n.prev() {
476                if predicate(prev) {
477                    break prev;
478                }
479            }
480
481            n = n.parent()?;
482        };
483
484        loop {
485            let Some(last) = n.last() else {
486                return Some(n);
487            };
488
489            if !predicate(last) {
490                return Some(n);
491            }
492
493            n = last;
494        }
495    }
496
497    fn node_at(&self, id: F::Pointer) -> Option<Node<'a, T, F>> {
498        let cur = self.tree.get(id.get())?;
499
500        Some(Self {
501            links: cur,
502            tree: self.tree,
503        })
504    }
505
506    /// Get the identifier of the current node.
507    ///
508    /// Note that an id might be re-used across different trees. This behavior
509    /// is never unsafe, but is not well-defined.
510    ///
511    /// This can be used to register a change in a [`ChangeSet`] later.
512    ///
513    /// ```
514    /// let mut tree = syntree::Builder::new();
515    /// let root_id = tree.open("root")?;
516    /// let child_id = tree.open("child")?;
517    /// tree.close()?;
518    ///
519    /// let child2_id = tree.open("child2")?;
520    /// tree.close()?;
521    /// tree.close()?;
522    ///
523    /// let tree = tree.build()?;
524    /// let root = tree.first().ok_or("missing root")?;
525    /// let child = root.first().ok_or("missing child")?;
526    /// let child2 = child.next().ok_or("missing child2")?;
527    ///
528    /// assert_eq!(root.id(), root_id);
529    /// assert_eq!(child.id(), child_id);
530    /// assert_eq!(child2.id(), child2_id);
531    /// # Ok::<_, Box<dyn core::error::Error>>(())
532    /// ```
533    ///
534    /// [`ChangeSet`]: crate::edit::ChangeSet
535    #[must_use]
536    pub fn id(&self) -> F::Pointer {
537        // We're relying on the knowledge that the provided links reference is
538        // inside of the tree of links.
539        let current = self.links as *const _ as usize;
540        let base = self.tree.as_ptr() as usize;
541        let id = (current - base) / size_of::<Links<T, F::Index, F::Pointer>>();
542        debug_assert!(id < self.tree.len(), "identifier outside of tree length");
543        // SAFETY: `id < self.tree.len()`, and every push into the tree storage
544        // is gated by `Pointer::new(len)`, so `Pointer::new(id)` is `Some`.
545        unsafe { F::Pointer::new_unchecked(id) }
546    }
547}
548
549impl<T, F> Node<'_, T, F>
550where
551    T: Copy,
552    F: Flavor,
553{
554    /// Access the [Span] of the node as a [Range].
555    ///
556    /// # Examples
557    ///
558    /// ```
559    /// let tree = syntree::tree! {
560    ///     "root" => {
561    ///         "number" => {
562    ///             ("lit", 5)
563    ///         },
564    ///         "ident" => {
565    ///             ("lit", 3)
566    ///         }
567    ///     },
568    ///     "root2" => {
569    ///         ("whitespace", 5)
570    ///     }
571    /// };
572    ///
573    /// let root = tree.first().ok_or("missing root")?;
574    /// assert_eq!(root.range(), 0..8);
575    ///
576    /// let root2 = root.next().ok_or("missing second root")?;
577    /// assert_eq!(root2.range(), 8..13);
578    /// # Ok::<_, Box<dyn core::error::Error>>(())
579    /// ```
580    #[must_use]
581    #[inline]
582    pub fn range(&self) -> Range<usize> {
583        self.links.span.range()
584    }
585}
586
587impl<T, F> fmt::Debug for Node<'_, T, F>
588where
589    T: Copy + fmt::Debug,
590    F: Flavor<Index: fmt::Debug>,
591{
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        f.debug_struct("Node")
594            .field("data", &self.links.data.get())
595            .field("span", &self.links.span)
596            .finish()
597    }
598}
599
600impl<T, F> Clone for Node<'_, T, F>
601where
602    T: Copy,
603    F: Flavor,
604{
605    #[inline]
606    fn clone(&self) -> Self {
607        *self
608    }
609}
610
611impl<T, F> Copy for Node<'_, T, F>
612where
613    T: Copy,
614    F: Flavor,
615{
616}
617
618/// Nodes compare equal when their [values][Node::value] and
619/// [spans][Node::span] are equal, regardless of their position in a tree.
620///
621/// Compare [`Node::id`] to check whether two nodes are the same node.
622///
623/// # Examples
624///
625/// ```
626/// let tree = syntree::tree! {
627///     "x" => {
628///         ("x", 0)
629///     }
630/// };
631///
632/// let root = tree.first().ok_or("missing root")?;
633/// let child = root.first().ok_or("missing child")?;
634///
635/// assert_eq!(root, child);
636/// assert_ne!(root.id(), child.id());
637/// # Ok::<_, Box<dyn core::error::Error>>(())
638/// ```
639impl<T, A, B> PartialEq<Node<'_, T, A>> for Node<'_, T, B>
640where
641    T: Copy + PartialEq,
642    A: Flavor,
643    B: Flavor<Index: PartialEq<A::Index>>,
644{
645    fn eq(&self, other: &Node<'_, T, A>) -> bool {
646        self.links.data.get() == other.links.data.get() && self.links.span == other.links.span
647    }
648}
649
650impl<T, F> Eq for Node<'_, T, F>
651where
652    T: Copy + Eq,
653    F: Flavor<Index: Eq>,
654{
655}