Skip to main content

syntree/
tree.rs

1use core::fmt;
2use core::ops::Range;
3
4use crate::links::{NodeLinks, TokenLinks};
5use crate::node::{Children, Element, Event, Id, Node, NodeOrToken, Token, Walk, WalkEvents};
6use crate::{Error, Flavor, Index, Pointer, Span, Storage};
7
8/// A syntax tree.
9///
10/// A tree is constructed through a [Builder][crate::Builder] or by modifying an
11/// existing tree through a [ChangeSet][crate::edit::ChangeSet].
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` is the [Flavor], declared with [`flavor!`][crate::flavor!]. Its
18///   [`Index`][Flavor::Index] determines the numerical bounds of spans, and if
19///   set to [Empty][crate::Empty] the tree does not store any spans. Its
20///   [`Width`][Flavor::Width] determines the bounds of pointers in the tree,
21///   which decides how many nodes can be stored in it. It also selects the
22///   [`Storage`][Flavor::Storage] used and its error type.
23///
24/// To use the default values, use the [Builder::new][crate::Builder::new]
25/// constructor.
26/// # Layout
27///
28/// Tokens are stored in a flat array in source order, and interior nodes (the
29/// ones opened with [`Builder::open`][crate::Builder::open] or wrapped with
30/// [`Builder::close_at`][crate::Builder::close_at]) in a second array. Node and
31/// token ids are indexes into their own array, so they are not dense: token ids
32/// skip the internal entries which carry the gaps explicit spans leave between
33/// tokens.
34pub struct Tree<T, F>
35where
36    T: Copy,
37    F: Flavor,
38{
39    /// Interior nodes.
40    nodes: F::Storage<NodeLinks<T, F::Index, F::Pointer>>,
41    /// Tokens and gap entries, in source order.
42    tokens: F::Storage<TokenLinks<T, F::Index, F::Pointer>>,
43    /// The span of the whole tree.
44    span: Span<F::Index>,
45    /// The first interior node at the root.
46    first: Option<F::Pointer>,
47    /// The last interior node at the root.
48    last: Option<F::Pointer>,
49    /// The number of gap entries in `tokens`.
50    gaps: usize,
51}
52
53impl<T, F> Tree<T, F>
54where
55    T: Copy,
56    F: Flavor,
57{
58    /// Construct a new empty tree.
59    pub(crate) const fn new_with() -> Self {
60        Self {
61            nodes: F::Storage::EMPTY,
62            tokens: F::Storage::EMPTY,
63            span: Span::point(F::Index::EMPTY),
64            first: None,
65            last: None,
66            gaps: 0,
67        }
68    }
69
70    /// Construct a new tree with capacity for `nodes` interior nodes and
71    /// `tokens` tokens.
72    pub(crate) fn with_capacity(nodes: usize, tokens: usize) -> Result<Self, Error<F::Error>> {
73        Ok(Self {
74            nodes: F::Storage::with_capacity(nodes)?,
75            tokens: F::Storage::with_capacity(tokens)?,
76            span: Span::point(F::Index::EMPTY),
77            first: None,
78            last: None,
79            gaps: 0,
80        })
81    }
82
83    /// Reserve capacity for `nodes` more interior nodes and `tokens` more
84    /// tokens.
85    pub(crate) fn reserve(&mut self, nodes: usize, tokens: usize) -> Result<(), Error<F::Error>> {
86        self.nodes.reserve(nodes)?;
87        self.tokens.reserve(tokens)?;
88        Ok(())
89    }
90
91    /// Get the span of the current node. The span of a node is the complete
92    /// span of all its children.
93    ///
94    /// # Examples
95    ///
96    /// ```
97    /// use syntree::Span;
98    ///
99    /// let tree = syntree::tree! {
100    ///     "root" => {
101    ///         "number" => {
102    ///             ("lit", 5)
103    ///         },
104    ///         "ident" => {
105    ///             ("lit", 3)
106    ///         }
107    ///     },
108    ///     "root2" => {
109    ///         ("whitespace", 5)
110    ///     }
111    /// };
112    ///
113    /// assert_eq!(tree.span(), Span::new(0, 13));
114    /// # Ok::<_, Box<dyn core::error::Error>>(())
115    /// ```
116    pub const fn span(&self) -> &Span<F::Index> {
117        &self.span
118    }
119
120    /// Get mutable span from the tree.
121    pub(crate) fn span_mut(&mut self) -> &mut Span<F::Index> {
122        &mut self.span
123    }
124
125    /// The total number of elements in the tree.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// let mut tree: syntree::Builder<()> = syntree::Builder::new();
131    /// let tree = tree.build()?;
132    ///
133    /// assert_eq!(tree.len(), 0);
134    ///
135    /// let mut tree = syntree::tree! {
136    ///     "root" => {
137    ///         "child" => {
138    ///             ("token", 2)
139    ///         },
140    ///         ("whitespace", 1),
141    ///         "child2" => {}
142    ///     }
143    /// };
144    ///
145    /// assert_eq!(tree.len(), 5);
146    /// # Ok::<_, Box<dyn core::error::Error>>(())
147    /// ```
148    pub fn len(&self) -> usize {
149        self.nodes
150            .len()
151            .saturating_add(self.tokens.len().saturating_sub(self.gaps))
152    }
153
154    /// The number of interior nodes and of tokens (excluding gap entries).
155    #[cfg(feature = "std")]
156    pub(crate) fn counts(&self) -> (usize, usize) {
157        (
158            self.nodes.len(),
159            self.tokens.len().saturating_sub(self.gaps),
160        )
161    }
162
163    /// Check if the current tree is empty. In that it doesn't have any
164    /// children at the root of the tree.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// let mut tree: syntree::Builder<()> = syntree::Builder::new();
170    /// let tree = tree.build()?;
171    /// assert!(tree.is_empty());
172    /// # Ok::<_, Box<dyn core::error::Error>>(())
173    /// ```
174    pub fn is_empty(&self) -> bool {
175        self.nodes.is_empty() && self.tokens.is_empty()
176    }
177
178    /// Get the capacity of the tree.
179    ///
180    /// # Examples
181    ///
182    /// ```
183    /// let mut tree: syntree::Builder<()> = syntree::Builder::new();
184    /// let tree = tree.build()?;
185    ///
186    /// assert_eq!(tree.capacity(), 0);
187    ///
188    /// let mut tree = syntree::tree! {
189    ///     "root" => {
190    ///         "child" => {
191    ///             ("token", 2)
192    ///         },
193    ///         ("whitespace", 1),
194    ///         "child2" => {}
195    ///     }
196    /// };
197    ///
198    /// assert!(tree.capacity() >= 5);
199    /// # Ok::<_, Box<dyn core::error::Error>>(())
200    /// ```
201    pub fn capacity(&self) -> usize {
202        self.nodes.capacity().saturating_add(self.tokens.capacity())
203    }
204
205    /// Get all root nodes in the tree.
206    ///
207    /// See [Children] for documentation.
208    pub fn children(&self) -> Children<'_, T, F> {
209        Children::new(self, None, (0, self.first), (self.tokens.len(), self.last))
210    }
211
212    /// Walk the tree forwards in a depth-first fashion visiting every node
213    /// once.
214    ///
215    /// See [`Walk`] for documentation.
216    pub fn walk(&self) -> Walk<'_, T, F> {
217        Walk::tree(self, self.first_id(), self.first)
218    }
219
220    /// Walk the tree forwards in a depth-first fashion emitting events
221    /// indicating how the tree is being traversed.
222    ///
223    /// See [`WalkEvents`] for documentation.
224    pub fn walk_events(&self) -> WalkEvents<'_, T, F> {
225        WalkEvents::new(self, self.first_id(), self.first, Event::Next)
226    }
227
228    /// Get the first child node in the tree.
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// let tree = syntree::tree! {
234    ///     "root" => {},
235    ///     "root2" => {}
236    /// };
237    ///
238    /// let root = tree.first().ok_or("missing root")?;
239    /// assert_eq!(root.value(), "root");
240    /// # Ok::<_, Box<dyn core::error::Error>>(())
241    /// ```
242    #[inline]
243    pub fn first(&self) -> Option<Element<'_, T, F>> {
244        self.element(self.first_id()?)
245    }
246
247    /// Get the last child node in the tree.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// let tree = syntree::tree! {
253    ///     "root" => {},
254    ///     "root2" => {}
255    /// };
256    ///
257    /// let root = tree.last().ok_or("missing root")?;
258    /// assert_eq!(root.value(), "root2");
259    /// # Ok::<_, Box<dyn core::error::Error>>(())
260    /// ```
261    #[inline]
262    pub fn last(&self) -> Option<Element<'_, T, F>> {
263        self.element(self.prev_at(None, self.tokens.len(), self.last)?)
264    }
265
266    /// The id of the first element in the tree.
267    fn first_id(&self) -> Option<Id<F::Pointer>> {
268        self.next_at(None, 0, self.first)
269    }
270
271    /// The interior nodes of the tree.
272    pub(crate) fn nodes(&self) -> &[NodeLinks<T, F::Index, F::Pointer>] {
273        &self.nodes
274    }
275
276    /// The token entries of the tree, gap entries included.
277    pub(crate) fn tokens(&self) -> &[TokenLinks<T, F::Index, F::Pointer>] {
278        &self.tokens
279    }
280
281    /// The first and last interior nodes at the root, mutably.
282    pub(crate) fn links_mut(&mut self) -> (&mut Option<F::Pointer>, &mut Option<F::Pointer>) {
283        (&mut self.first, &mut self.last)
284    }
285
286    /// Get an interior node.
287    pub(crate) fn node_links(&self, id: F::Pointer) -> Option<&NodeLinks<T, F::Index, F::Pointer>> {
288        self.nodes.get(id.get())
289    }
290
291    /// Get an interior node mutably.
292    pub(crate) fn node_links_mut(
293        &mut self,
294        id: F::Pointer,
295    ) -> Option<&mut NodeLinks<T, F::Index, F::Pointer>> {
296        self.nodes.get_mut(id.get())
297    }
298
299    /// Get the token entries mutably.
300    pub(crate) fn tokens_mut(&mut self) -> &mut [TokenLinks<T, F::Index, F::Pointer>] {
301        &mut self.tokens
302    }
303
304    /// Push an interior node.
305    pub(crate) fn push_node(
306        &mut self,
307        links: NodeLinks<T, F::Index, F::Pointer>,
308    ) -> Result<(), F::Error> {
309        self.nodes.push(links)
310    }
311
312    /// Push a token entry.
313    pub(crate) fn push_token(
314        &mut self,
315        links: TokenLinks<T, F::Index, F::Pointer>,
316    ) -> Result<(), F::Error> {
317        if links.is_gap() {
318            self.gaps = self.gaps.saturating_add(1);
319        }
320
321        self.tokens.push(links)
322    }
323
324    /// Test if `id` is a trivia token.
325    #[inline]
326    pub(crate) fn is_trivia(&self, id: Id<F::Pointer>) -> bool {
327        match id {
328            Id::Node(..) => false,
329            Id::Token(t) => self.tokens.get(t.get()).is_some_and(TokenLinks::is_trivia),
330        }
331    }
332
333    /// The start of the token entry at `index`, which is the end of the entry
334    /// before it.
335    pub(crate) fn token_start(&self, index: usize) -> F::Index {
336        match index.checked_sub(1).and_then(|n| self.tokens.get(n)) {
337            Some(prev) => prev.end,
338            None => F::Index::EMPTY,
339        }
340    }
341
342    /// The end of the last token entry.
343    pub(crate) fn tokens_end(&self) -> F::Index {
344        self.token_start(self.tokens.len())
345    }
346
347    /// The element at a level which follows the position before token entry
348    /// `tok`, where `node` is the next interior node at the level, if any.
349    ///
350    /// This is the merge step between the token array and a chain of interior
351    /// nodes: an interior node comes first if its tokens start at or before
352    /// `tok`.
353    pub(crate) fn next_at(
354        &self,
355        parent: Option<F::Pointer>,
356        tok: usize,
357        node: Option<F::Pointer>,
358    ) -> Option<Id<F::Pointer>> {
359        if let Some(id) = node {
360            if self.node_links(id)?.tok_start.get() <= tok {
361                return Some(Id::Node(id));
362            }
363        }
364
365        let mut index = tok;
366        let mut links = self.tokens.get(index)?;
367
368        // A gap entry is always directly followed by its token.
369        if links.is_gap() {
370            index = index.checked_add(1)?;
371            links = self.tokens.get(index)?;
372        }
373
374        if links.parent() != parent {
375            return None;
376        }
377
378        Some(Id::Token(F::Pointer::new(index)?))
379    }
380
381    /// The element at a level which precedes the position before token entry
382    /// `tok`, where `node` is the previous interior node at the level, if any.
383    pub(crate) fn prev_at(
384        &self,
385        parent: Option<F::Pointer>,
386        tok: usize,
387        node: Option<F::Pointer>,
388    ) -> Option<Id<F::Pointer>> {
389        let mut tok = tok;
390
391        // A position right after a gap entry is the same as the one before it,
392        // since nothing is ever placed between a gap and its token.
393        if let Some(index) = tok.checked_sub(1) {
394            if self.tokens.get(index).is_some_and(|links| links.is_gap()) {
395                tok = index;
396            }
397        }
398
399        if let Some(id) = node {
400            if self.node_links(id)?.tok_end.get() >= tok {
401                return Some(Id::Node(id));
402            }
403        }
404
405        let index = tok.checked_sub(1)?;
406        let links = self.tokens.get(index)?;
407
408        if links.is_gap() || links.parent() != parent {
409            return None;
410        }
411
412        Some(Id::Token(F::Pointer::new(index)?))
413    }
414
415    /// The position at a level after `id`, where `node` is the next interior
416    /// node at the level if `id` is a token. This is what [`Tree::next_at`]
417    /// takes to find the element which follows `id`.
418    pub(crate) fn after(
419        &self,
420        id: Id<F::Pointer>,
421        node: Option<F::Pointer>,
422    ) -> Option<(usize, Option<F::Pointer>)> {
423        match id {
424            Id::Node(n) => {
425                let links = self.node_links(n)?;
426                Some((links.tok_end.get(), links.next))
427            }
428            Id::Token(t) => Some((t.get().checked_add(1)?, node)),
429        }
430    }
431
432    /// The first interior node at a level.
433    pub(crate) fn level_first(&self, parent: Option<F::Pointer>) -> Option<F::Pointer> {
434        match parent {
435            Some(id) => self.node_links(id)?.first,
436            None => self.first,
437        }
438    }
439
440    /// The interior nodes at a level immediately before and after token entry
441    /// `index`.
442    ///
443    /// This walks the chain of interior nodes at the level, so it is linear in
444    /// their number.
445    pub(crate) fn nodes_around(
446        &self,
447        parent: Option<F::Pointer>,
448        index: usize,
449    ) -> (Option<F::Pointer>, Option<F::Pointer>) {
450        let mut prev = None;
451        let mut cur = self.level_first(parent);
452
453        while let Some(id) = cur {
454            let Some(links) = self.node_links(id) else {
455                break;
456            };
457
458            if links.tok_start.get() > index {
459                break;
460            }
461
462            prev = Some(id);
463            cur = links.next;
464        }
465
466        (prev, cur)
467    }
468
469    /// Construct an element handle.
470    pub(crate) fn element(&self, id: Id<F::Pointer>) -> Option<Element<'_, T, F>> {
471        match id {
472            Id::Node(id) => Some(NodeOrToken::Node(self.get(id)?)),
473            Id::Token(id) => Some(NodeOrToken::Token(self.token(id)?)),
474        }
475    }
476
477    /// Get the node at the given index.
478    ///
479    /// Note that an id might be re-used across different trees. This behavior
480    /// is never unsafe, but is not well-defined.
481    ///
482    /// # Examples
483    ///
484    /// ```
485    /// let tree = syntree::tree! {
486    ///     "root" => {
487    ///         "number" => {
488    ///             ("lit", 5)
489    ///         },
490    ///         "ident" => {
491    ///             ("lit", 3)
492    ///         }
493    ///     },
494    ///     "root2" => {
495    ///         ("whitespace", 5)
496    ///     }
497    /// };
498    ///
499    /// let node = tree.first().and_then(|n| n.last()).ok_or("missing ident")?;
500    /// assert_eq!(node.value(), "ident");
501    ///
502    /// let id = node.into_node().ok_or("ident is a node")?.id();
503    /// let node = tree.get(id).ok_or("missing ident")?;
504    /// assert_eq!(node.value(), "ident");
505    /// # Ok::<_, Box<dyn core::error::Error>>(())
506    /// ```
507    pub fn get(&self, id: F::Pointer) -> Option<Node<'_, T, F>> {
508        Node::new(self, id)
509    }
510
511    /// Get the token with the given id.
512    ///
513    /// Token ids are not dense, so not every id below the number of tokens
514    /// refers to a token.
515    ///
516    /// # Examples
517    ///
518    /// ```
519    /// let mut tree = syntree::Builder::new();
520    /// let id = tree.token("lit", 3)?;
521    /// let tree = tree.build()?;
522    ///
523    /// let token = tree.token(id).ok_or("missing token")?;
524    /// assert_eq!(token.value(), "lit");
525    /// # Ok::<_, Box<dyn core::error::Error>>(())
526    /// ```
527    pub fn token(&self, id: F::Pointer) -> Option<Token<'_, T, F>> {
528        Token::new(self, id)
529    }
530
531    /// Access the [Span] of the node as a [Range].
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// let tree = syntree::tree! {
537    ///     "root" => {
538    ///         "number" => {
539    ///             ("lit", 5)
540    ///         },
541    ///         "ident" => {
542    ///             ("lit", 3)
543    ///         }
544    ///     },
545    ///     "root2" => {
546    ///         ("whitespace", 5)
547    ///     }
548    /// };
549    ///
550    /// assert_eq!(tree.range(), 0..13);
551    /// # Ok::<_, Box<dyn core::error::Error>>(())
552    /// ```
553    #[must_use]
554    pub fn range(&self) -> Range<usize> {
555        self.span.range()
556    }
557
558    /// Query for the smallest node which contains the given [Range].
559    ///
560    /// A node contains the range when it starts at or before `range.start`,
561    /// ends at or after `range.end`, and `range.start` lies before its end.
562    /// Tokens are nodes too, so a range within a single token returns that
563    /// token, however deeply it is nested.
564    ///
565    /// * Returns `None` if `range.start > range.end`, or if no node contains
566    ///   the range, such as one which spans two nodes at the root of the tree.
567    /// * An empty range on the boundary between two tokens belongs to the token
568    ///   which starts there. An empty range at the end of the tree is contained
569    ///   by no node and returns `None`.
570    /// * Only tokens with a non-empty span and their ancestors are considered,
571    ///   so empty nodes and empty tokens are never returned.
572    ///
573    /// Tokens are looked up by binary search, which assumes they were added
574    /// to the tree in non-decreasing order of their spans.
575    ///
576    /// # Examples
577    ///
578    /// ```
579    /// let tree = syntree::tree! {
580    ///     "root" => {
581    ///         "child1" => {
582    ///             ("token1", 3)
583    ///         },
584    ///         "child2" => {
585    ///             "nested1" => {
586    ///                 ("token2", 4),
587    ///             },
588    ///             ("token3", 1),
589    ///         },
590    ///         "child3" => {
591    ///             ("token4", 5)
592    ///         }
593    ///     },
594    ///     "root2" => {}
595    /// };
596    ///
597    /// let node = tree.node_with_range(0..0).ok_or("missing 0")?;
598    /// assert_eq!(node.value(), "token1");
599    ///
600    /// let node = tree.node_with_range(0..3).ok_or("missing 0..3")?;
601    /// assert_eq!(node.value(), "token1");
602    ///
603    /// let node = tree.node_with_range(3..3).ok_or("missing 3")?;
604    /// assert_eq!(node.value(), "token2");
605    ///
606    /// let node = tree.node_with_range(3..7).ok_or("missing 3..7")?;
607    /// assert_eq!(node.value(), "token2");
608    /// assert_eq!(node.parent().map(|n| n.value()), Some("nested1"));
609    ///
610    /// let node = tree.node_with_range(7..8).ok_or("missing 7..8")?;
611    /// assert_eq!(node.value(), "token3");
612    ///
613    /// let node = tree.node_with_range(3..8).ok_or("missing 3..8")?;
614    /// assert_eq!(node.value(), "child2");
615    ///
616    /// let node = tree.node_with_range(8..13).ok_or("missing 8..13")?;
617    /// assert_eq!(node.value(), "token4");
618    ///
619    /// let node = tree.node_with_range(2..4).ok_or("missing 2..4")?;
620    /// assert_eq!(node.value(), "root");
621    ///
622    /// // The end of the tree, where the empty "root2" sits.
623    /// assert!(tree.node_with_range(13..13).is_none());
624    /// assert!(tree.node_with_range(0..14).is_none());
625    /// assert!(tree.node_with_range(4..2).is_none());
626    /// # Ok::<_, Box<dyn core::error::Error>>(())
627    /// ```
628    ///
629    /// Range queries work as expected with checkpoints:
630    ///
631    /// ```
632    /// let mut tree = syntree::Builder::new();
633    ///
634    /// let c = tree.checkpoint()?;
635    /// tree.open("child")?;
636    /// tree.token("lit", 3)?;
637    /// tree.close()?;
638    /// tree.close_at(c, "root")?;
639    /// tree.token("sibling", 3)?;
640    ///
641    /// let tree = tree.build()?;
642    ///
643    /// let lit = tree.node_with_range(0..3).ok_or("missing at 0..3")?;
644    /// assert_eq!(lit.value(), "lit");
645    /// assert_eq!(lit.parent().map(|n| n.value()), Some("child"));
646    ///
647    /// assert!(tree.node_with_range(2..4).is_none());
648    /// # Ok::<_, Box<dyn core::error::Error>>(())
649    /// ```
650    #[must_use]
651    pub fn node_with_range(&self, span: Range<usize>) -> Option<Element<'_, T, F>> {
652        let start = F::Index::from_usize(span.start)?;
653        let end = F::Index::from_usize(span.end)?;
654        self.node_with_span_internal(start, end)
655    }
656
657    /// Query for the smallest node which contains the given [Span].
658    ///
659    /// This behaves like [Tree::node_with_range]: tokens are returned when
660    /// they contain the span, and `None` is returned if `span.start >
661    /// span.end`, if no node contains the span, or for an empty span at the
662    /// end of the tree. Empty nodes and empty tokens are never returned.
663    ///
664    /// Tokens are looked up by binary search, which assumes they were added
665    /// to the tree in non-decreasing order of their spans.
666    ///
667    /// # Examples
668    ///
669    /// ```
670    /// use syntree::Span;
671    ///
672    /// let tree = syntree::tree! {
673    ///     "root" => {
674    ///         "child1" => {
675    ///             ("token1", 3)
676    ///         },
677    ///         "child2" => {
678    ///             "nested1" => {
679    ///                 ("token2", 4),
680    ///             },
681    ///             ("token3", 1),
682    ///         },
683    ///         "child3" => {
684    ///             ("token4", 5)
685    ///         }
686    ///     },
687    ///     "root2" => {}
688    /// };
689    ///
690    /// let node = tree.node_with_span(Span::point(0)).ok_or("missing 0")?;
691    /// assert_eq!(node.value(), "token1");
692    ///
693    /// let node = tree.node_with_span(Span::new(0, 3)).ok_or("missing 0..3")?;
694    /// assert_eq!(node.value(), "token1");
695    ///
696    /// let node = tree.node_with_span(Span::point(3)).ok_or("missing 3")?;
697    /// assert_eq!(node.value(), "token2");
698    ///
699    /// let node = tree.node_with_span(Span::new(3, 7)).ok_or("missing 3..7")?;
700    /// assert_eq!(node.value(), "token2");
701    ///
702    /// let node = tree.node_with_span(Span::new(7, 8)).ok_or("missing 7..8")?;
703    /// assert_eq!(node.value(), "token3");
704    ///
705    /// let node = tree.node_with_span(Span::new(3, 8)).ok_or("missing 3..8")?;
706    /// assert_eq!(node.value(), "child2");
707    ///
708    /// let node = tree.node_with_span(Span::new(8, 13)).ok_or("missing 8..13")?;
709    /// assert_eq!(node.value(), "token4");
710    ///
711    /// let node = tree.node_with_span(Span::new(2, 4)).ok_or("missing 2..4")?;
712    /// assert_eq!(node.value(), "root");
713    ///
714    /// assert!(tree.node_with_span(Span::point(13)).is_none());
715    /// assert!(tree.node_with_span(Span::new(4, 2)).is_none());
716    /// # Ok::<_, Box<dyn core::error::Error>>(())
717    /// ```
718    ///
719    /// Range queries work as expected with checkpoints:
720    ///
721    /// ```
722    /// use syntree::{Span, Builder};
723    ///
724    /// let mut tree = Builder::new();
725    ///
726    /// let c = tree.checkpoint()?;
727    ///
728    /// tree.open("child1")?;
729    /// tree.token("lit1", 3)?;
730    /// tree.close()?;
731    ///
732    /// tree.open("child2")?;
733    /// tree.token("lit2", 2)?;
734    /// tree.close()?;
735    ///
736    /// tree.close_at(c, "root")?;
737    ///
738    /// let tree = tree.build()?;
739    ///
740    /// let node = tree.node_with_span(Span::point(0)).ok_or("missing at point 0")?;
741    /// assert_eq!(node.value(), "lit1");
742    ///
743    /// let node = tree.node_with_span(Span::new(0, 3)).ok_or("missing at 0..3")?;
744    /// assert_eq!(node.value(), "lit1");
745    /// assert_eq!(node.parent().map(|n| n.value()), Some("child1"));
746    ///
747    /// let node = tree.node_with_span(Span::point(3)).ok_or("missing at point 3")?;
748    /// assert_eq!(node.value(), "lit2");
749    ///
750    /// let node = tree.node_with_span(Span::new(3, 5)).ok_or("missing at 3..5")?;
751    /// assert_eq!(node.value(), "lit2");
752    ///
753    /// let node = tree.node_with_span(Span::new(2, 5)).ok_or("missing at 2..5")?;
754    /// assert_eq!(node.value(), "root");
755    /// # Ok::<_, Box<dyn core::error::Error>>(())
756    /// ```
757    #[must_use]
758    pub fn node_with_span(&self, span: Span<F::Index>) -> Option<Element<'_, T, F>> {
759        self.node_with_span_internal(span.start, span.end)
760    }
761
762    fn node_with_span_internal(&self, start: F::Index, end: F::Index) -> Option<Element<'_, T, F>> {
763        if start > end {
764            return None;
765        }
766
767        // Index of the first entry which ends after `start`. Empty tokens
768        // never qualify, since the entry before them ends where they do.
769        let n = self.tokens.partition_point(|t| t.end <= start);
770
771        let mut next = n;
772
773        // `start` falls in a gap left by an explicit span, so the token after
774        // it starts after `start`.
775        let in_gap = match self.tokens.get(n) {
776            Some(links) if links.is_gap() => {
777                next = n.checked_add(1)?;
778                true
779            }
780            Some(..) => false,
781            None => true,
782        };
783
784        let found = F::Pointer::new(next)
785            .and_then(|id| self.element(Id::Token(id)))
786            .and_then(|e| smallest_containing(e, start, end));
787
788        if !in_gap {
789            return found;
790        }
791
792        // A node spanning the gap can instead contain the closest preceding
793        // token with a non-empty span.
794        let mut index = n;
795
796        let preceding = loop {
797            let Some(i) = index.checked_sub(1) else {
798                break None;
799            };
800
801            index = i;
802
803            let Some(links) = self.tokens.get(i) else {
804                break None;
805            };
806
807            if links.is_gap() || links.end <= self.token_start(i) {
808                continue;
809            }
810
811            break F::Pointer::new(i)
812                .and_then(|id| self.element(Id::Token(id)))
813                .and_then(|e| smallest_containing(e, start, end));
814        };
815
816        match (found, preceding) {
817            (Some(a), Some(b))
818                if a.span().start <= b.span().start && b.span().end <= a.span().end =>
819            {
820                Some(b)
821            }
822            (None, b) => b,
823            (a, _) => a,
824        }
825    }
826}
827
828/// Climb from `element` to the first element which contains `start..end`,
829/// where `start` must lie strictly before the end of the element.
830fn smallest_containing<'a, T, F>(
831    element: Element<'a, T, F>,
832    start: F::Index,
833    end: F::Index,
834) -> Option<Element<'a, T, F>>
835where
836    T: Copy,
837    F: Flavor,
838{
839    let mut element = element;
840
841    loop {
842        let span = element.span();
843
844        if span.start <= start && start < span.end && end <= span.end {
845            return Some(element);
846        }
847
848        element = NodeOrToken::Node(element.parent()?);
849    }
850}
851
852impl<T, F> Clone for Tree<T, F>
853where
854    T: Copy,
855    F: Flavor,
856    F::Storage<NodeLinks<T, F::Index, F::Pointer>>: Clone,
857    F::Storage<TokenLinks<T, F::Index, F::Pointer>>: Clone,
858{
859    #[inline]
860    fn clone(&self) -> Self {
861        Self {
862            nodes: self.nodes.clone(),
863            tokens: self.tokens.clone(),
864            span: self.span,
865            first: self.first,
866            last: self.last,
867            gaps: self.gaps,
868        }
869    }
870}
871
872impl<T, F> Default for Tree<T, F>
873where
874    T: Copy,
875    F: Flavor,
876{
877    #[inline]
878    fn default() -> Self {
879        Self::new_with()
880    }
881}
882
883impl<T, A, B> PartialEq<Tree<T, A>> for Tree<T, B>
884where
885    T: Copy + PartialEq,
886    A: Flavor,
887    B: Flavor<Index: PartialEq<A::Index>>,
888{
889    fn eq(&self, other: &Tree<T, A>) -> bool {
890        struct Item<'a, T, F>((isize, Element<'a, T, F>))
891        where
892            T: Copy,
893            F: Flavor;
894
895        // NB: this is needed because the constraints on tuples doesn't allow
896        // for `A` and `B` to be different.
897        impl<'a, T, A, B> PartialEq<Item<'a, T, A>> for Item<'a, T, B>
898        where
899            T: Copy + PartialEq,
900            A: Flavor,
901            B: Flavor<Index: PartialEq<A::Index>>,
902        {
903            #[inline]
904            fn eq(&self, other: &Item<'a, T, A>) -> bool {
905                self.0 .0 == other.0 .0 && self.0 .1.eq(&other.0 .1)
906            }
907        }
908
909        self.walk().with_trivia().with_depths().map(Item).eq(other
910            .walk()
911            .with_trivia()
912            .with_depths()
913            .map(Item))
914    }
915}
916
917impl<T, F> Eq for Tree<T, F>
918where
919    T: Copy + Eq,
920    F: Flavor<Index: Eq>,
921{
922}
923
924impl<T, F> fmt::Debug for Tree<T, F>
925where
926    T: Copy + fmt::Debug,
927    F: Flavor<Index: fmt::Debug>,
928{
929    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
930        struct List<'a, T, F>(&'a Tree<T, F>)
931        where
932            T: Copy,
933            F: Flavor;
934
935        impl<T, F> fmt::Debug for List<'_, T, F>
936        where
937            T: Copy + fmt::Debug,
938            F: Flavor<Index: fmt::Debug>,
939        {
940            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941                f.debug_list()
942                    .entries(self.0.walk().with_trivia().with_depths())
943                    .finish()
944            }
945        }
946
947        f.debug_tuple("Tree").field(&List(self)).finish()
948    }
949}