syntree/
builder.rs

1mod checkpoint;
2
3use core::cell::Cell;
4
5use crate::links::Links;
6use crate::{
7    Error, Flavor, FlavorDefault, Index, Length, Pointer, Span, Storage, Tree, TreeIndex, Width,
8};
9
10pub use self::checkpoint::Checkpoint;
11
12/// A builder for a [Tree].
13///
14/// This maintains a stack of nodes being built which has to be balanced with
15/// calls to [`Builder::open`] and [`Builder::close`].
16///
17/// # Type parameters and bounds
18///
19/// The three type parameters of the tree determines the following properties:
20/// * `T` is the data stored in the tree.
21/// * `I` determines the numerical bounds of spans stored in the tree through
22///   the [Index] trait, if set to [Empty][crate::Empty] the tree does not store
23///   any spans.
24/// * `W` determines the bounds of pointers in the tree through the [Width]
25///   trait, this decides how many elements that can be stored in the tree.
26///
27/// To use the default values, use the [Builder::new][Builder::new] constructor.
28///
29/// # Examples
30///
31/// ```
32/// let mut tree = syntree::Builder::new();
33///
34/// tree.open("root")?;
35/// tree.open("child")?;
36/// tree.close()?;
37/// tree.open("child")?;
38/// tree.close()?;
39/// tree.close()?;
40///
41/// let tree = tree.build()?;
42///
43/// let expected = syntree::tree! {
44///     "root" => {
45///         "child" => {},
46///         "child" => {}
47///     }
48/// };
49///
50/// assert_eq!(tree, expected);
51/// # Ok::<_, Box<dyn core::error::Error>>(())
52/// ```
53#[derive(Debug)]
54pub struct Builder<T, F = FlavorDefault>
55where
56    T: Copy,
57    F: Flavor,
58{
59    /// Data in the tree being built.
60    tree: Tree<T, F>,
61    /// The last checkpoint that was handed out.
62    checkpoint: Option<Checkpoint<F::Pointer>>,
63    /// Reference the current parent to the node being built. It itself has its
64    /// parent set in the tree, so that is what is used to traverse ancestors of
65    /// a node.
66    parent: Option<F::Pointer>,
67    /// Reference to last sibling inserted.
68    sibling: Option<F::Pointer>,
69    /// The current cursor.
70    cursor: F::Index,
71}
72
73impl<T> Builder<T, FlavorDefault>
74where
75    T: Copy,
76{
77    /// Construct a new tree with a default [`Span`] based on `u32`.
78    ///
79    /// For a constructor that can use custom bounds, use [Builder::new_with].
80    ///
81    /// # Examples
82    ///
83    /// ```
84    /// let mut tree = syntree::Builder::new();
85    ///
86    /// tree.open("root")?;
87    ///
88    /// tree.open("child")?;
89    /// tree.token("token", 5)?;
90    /// tree.close()?;
91    ///
92    /// tree.open("child2")?;
93    /// tree.close()?;
94    ///
95    /// tree.close()?;
96    ///
97    /// let tree = tree.build()?;
98    ///
99    /// let expected = syntree::tree! {
100    ///     "root" => {
101    ///         "child" => {
102    ///             ("token", 5)
103    ///         },
104    ///         "child2" => {}
105    ///     }
106    /// };
107    ///
108    /// assert_eq!(tree, expected);
109    /// # Ok::<_, Box<dyn core::error::Error>>(())
110    /// ```
111    #[must_use]
112    pub const fn new() -> Self {
113        Self::new_with()
114    }
115}
116
117impl<T, F> Builder<T, F>
118where
119    T: Copy,
120    F: Flavor,
121{
122    /// Construct a new tree with a custom span.
123    ///
124    /// To build a tree with default bounds, see [Builder::new]. Also see the
125    /// [Builder] documentation for what the different bounds means.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use syntree::{Builder, Empty, EmptyVec, TreeIndex, Tree};
131    ///
132    /// syntree::flavor! {
133    ///     struct FlavorEmpty {
134    ///         type Index = Empty;
135    ///         type Width = u32;
136    ///         type Indexes = EmptyVec<TreeIndex<Self>>;
137    ///     }
138    /// }
139    ///
140    /// let mut tree: Builder<_, FlavorEmpty> = Builder::new_with();
141    ///
142    /// tree.open("root")?;
143    ///
144    /// tree.open("child")?;
145    /// tree.token("token", Empty)?;
146    /// tree.close()?;
147    ///
148    /// tree.open("child2")?;
149    /// tree.close()?;
150    ///
151    /// tree.close()?;
152    ///
153    /// let tree = tree.build()?;
154    ///
155    /// let expected: Tree<_, FlavorEmpty> = syntree::tree_with! {
156    ///     "root" => {
157    ///         "child" => {
158    ///             "token"
159    ///         },
160    ///         "child2" => {}
161    ///     }
162    /// };
163    ///
164    /// assert_eq!(tree, expected);
165    /// # Ok::<_, Box<dyn core::error::Error>>(())
166    /// ```
167    #[must_use]
168    pub const fn new_with() -> Self {
169        Builder {
170            tree: Tree::new_with(),
171            parent: None,
172            checkpoint: None,
173            sibling: None,
174            cursor: F::Index::EMPTY,
175        }
176    }
177
178    /// Get a reference to the current cursor position of the syntax tree.
179    ///
180    /// The cursor position is the position in which it's been advanced so far
181    /// as a result of calls to [Builder::token] and indicates the current
182    /// starting index of the next span.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// let mut tree = syntree::Builder::new();
188    ///
189    /// assert_eq!(*tree.cursor(), 0);
190    /// tree.open("child")?;
191    /// assert_eq!(*tree.cursor(), 0);
192    /// tree.token("lit", 4)?;
193    /// assert_eq!(*tree.cursor(), 4);
194    /// tree.close()?;
195    /// assert_eq!(*tree.cursor(), 4);
196    ///
197    /// let tree = tree.build()?;
198    ///
199    /// let expected = syntree::tree! {
200    ///     "child" => {
201    ///         ("lit", 4)
202    ///     }
203    /// };
204    ///
205    /// assert_eq!(tree, expected);
206    /// # Ok::<_, Box<dyn core::error::Error>>(())
207    /// ```
208    #[inline]
209    pub const fn cursor(&self) -> &F::Index {
210        &self.cursor
211    }
212
213    /// Set the cursor position of the syntax tree.
214    ///
215    /// This is used to implicitly set spans when using spanless constructions
216    /// methods.
217    ///
218    /// # Examples
219    ///
220    /// ```
221    /// let mut tree = syntree::Builder::new();
222    ///
223    /// assert_eq!(*tree.cursor(), 0);
224    /// tree.open("child")?;
225    /// assert_eq!(*tree.cursor(), 0);
226    /// tree.token("lit", 4)?;
227    /// assert_eq!(*tree.cursor(), 4);
228    /// tree.close()?;
229    /// assert_eq!(*tree.cursor(), 4);
230    ///
231    /// let tree = tree.build()?;
232    ///
233    /// let expected = syntree::tree! {
234    ///     "child" => {
235    ///         ("lit", 4)
236    ///     }
237    /// };
238    ///
239    /// assert_eq!(tree, expected);
240    /// # Ok::<_, Box<dyn core::error::Error>>(())
241    /// ```
242    pub fn set_cursor(&mut self, cursor: F::Index) {
243        self.cursor = cursor;
244    }
245
246    /// Start a node with the given `data`.
247    ///
248    /// This pushes a new link with the given type onto the stack which links
249    /// itself onto the last sibling node that ben introduced either through
250    /// [`Builder::close`], [`Builder::close_at`], or
251    /// [`Builder::close_at_with`].
252    ///
253    /// # Errors
254    ///
255    /// Errors with [`Error::Overflow`] in case we run out of node
256    /// identifiers.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// let mut tree = syntree::Builder::new();
262    ///
263    /// tree.open("root")?;
264    ///
265    /// tree.open("child")?;
266    /// tree.close()?;
267    ///
268    /// tree.open("child")?;
269    /// tree.close()?;
270    ///
271    /// tree.close()?;
272    /// # Ok::<_, Box<dyn core::error::Error>>(())
273    /// ```
274    pub fn open(&mut self, data: T) -> Result<F::Pointer, Error<F::Error>> {
275        let id = self.insert(data, Span::point(self.cursor))?;
276        self.parent = Some(id);
277        Ok(id)
278    }
279
280    /// Start a node with the given `data` and span.
281    ///
282    /// This pushes a new link with the given type onto the stack which links
283    /// itself onto the last sibling node that ben introduced either through
284    /// [`Builder::close`], [`Builder::close_at`] or [`Builder::close_at_with`].
285    ///
286    /// This does not advance the cursor position, in order to fix tree
287    /// construction use [`Builder::set_cursor`].
288    ///
289    /// # Errors
290    ///
291    /// Errors with [`Error::Overflow`] in case we run out of node
292    /// identifiers.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use syntree::Span;
298    ///
299    /// let mut tree = syntree::Builder::new();
300    ///
301    /// tree.open("root")?;
302    ///
303    /// tree.open_with("child", Span::new(0, 3))?;
304    /// tree.close()?;
305    ///
306    /// tree.open_with("child", Span::new(3, 6))?;
307    /// tree.close()?;
308    ///
309    /// tree.close()?;
310    ///
311    /// let tree = tree.build()?;
312    ///
313    /// let expected = syntree::tree! {
314    ///     ("root", (0, 6)) => {
315    ///         ("child", (0, 3)) => {},
316    ///         ("child", (3, 6)) => {}
317    ///     }
318    /// };
319    ///
320    /// assert_eq!(tree, expected);
321    /// # Ok::<_, Box<dyn core::error::Error>>(())
322    /// ```
323    pub fn open_with(
324        &mut self,
325        data: T,
326        span: Span<F::Index>,
327    ) -> Result<F::Pointer, Error<F::Error>> {
328        let id = self.insert(data, span)?;
329        self.parent = Some(id);
330        Ok(id)
331    }
332
333    /// End a node being built.
334    ///
335    /// This will pop a value of the stack, and set that value as the next
336    /// sibling which will be used with [`Builder::open`].
337    ///
338    /// # Errors
339    ///
340    /// This call must be balanced with a prior call to [`Builder::open`].
341    /// If not this will result in an [`Error::CloseError`] being raised.
342    ///
343    /// # Examples
344    ///
345    /// ```
346    /// let mut tree = syntree::Builder::new();
347    ///
348    /// tree.open("root")?;
349    ///
350    /// tree.open("child")?;
351    /// tree.close()?;
352    ///
353    /// tree.open("child")?;
354    /// tree.close()?;
355    ///
356    /// tree.close()?;
357    /// # Ok::<_, Box<dyn core::error::Error>>(())
358    /// ```
359    pub fn close(&mut self) -> Result<(), Error<F::Error>> {
360        let head = self.parent.take().ok_or(Error::CloseError)?;
361
362        self.sibling = Some(head);
363
364        let &mut Links { parent, span, .. } = self
365            .tree
366            .get_mut(head)
367            .ok_or_else(|| Error::MissingNode(head.get()))?;
368
369        if let Some(id) = parent {
370            let parent = self
371                .tree
372                .get_mut(id)
373                .ok_or_else(|| Error::MissingNode(id.get()))?;
374
375            parent.span = parent.span.join(&span);
376            self.parent = Some(id);
377        }
378
379        self.cursor = span.end;
380        Ok(())
381    }
382
383    /// Declare a token with the specified `value` and a corresponding `len`.
384    ///
385    /// A token is always a terminating element without children.
386    ///
387    /// # Errors
388    ///
389    /// Errors with [`Error::Overflow`] in case we run out of node
390    /// identifiers.
391    ///
392    /// # Examples
393    ///
394    /// ```
395    /// let mut tree = syntree::Builder::new();
396    ///
397    /// tree.open("child")?;
398    /// tree.token("lit", 4)?;
399    /// tree.close()?;
400    ///
401    /// let tree = tree.build()?;
402    ///
403    /// let expected = syntree::tree! {
404    ///     "child" => {
405    ///         ("lit", 4)
406    ///     }
407    /// };
408    ///
409    /// assert_eq!(tree, expected);
410    /// # Ok::<_, Box<dyn core::error::Error>>(())
411    /// ```
412    pub fn token(&mut self, value: T, len: F::Length) -> Result<F::Pointer, Error<F::Error>> {
413        let start = self.cursor;
414
415        if !len.is_empty() {
416            self.cursor = self.cursor.checked_add_len(len).ok_or(Error::Overflow)?;
417            self.tree.span_mut().end = self.cursor;
418        }
419
420        let id = self.insert(value, Span::new(start, self.cursor))?;
421        self.sibling = Some(id);
422
423        if !len.is_empty() {
424            self.tree.indexes_mut().push(TreeIndex {
425                index: self.cursor,
426                id,
427            })?;
428        }
429
430        Ok(id)
431    }
432
433    /// Insert a token with a custom span.
434    ///
435    /// # Errors
436    ///
437    /// Errors with [`Error::Overflow`] in case we run out of node identifiers.
438    ///
439    /// # Examples
440    ///
441    /// ```
442    /// use syntree::Span;
443    ///
444    /// let mut tree = syntree::Builder::new();
445    ///
446    /// tree.open_with("child", Span::new(0, 10))?;
447    /// tree.token_with("lit", Span::new(2, 4))?;
448    /// tree.token_with("lit2", Span::new(4, 6))?;
449    /// tree.close()?;
450    ///
451    /// let tree = tree.build()?;
452    ///
453    /// let expected = syntree::tree! {
454    ///     ("child", (0, 10)) => {
455    ///         ("lit", (2, 4)),
456    ///         ("lit2", (4, 6)),
457    ///     }
458    /// };
459    ///
460    /// assert_eq!(tree, expected);
461    /// # Ok::<_, Box<dyn core::error::Error>>(())
462    /// ```
463    ///
464    /// Tokens with spans forces the cursor to be set to the end of the span.
465    ///
466    /// ```
467    /// use syntree::Span;
468    ///
469    /// let mut tree = syntree::Builder::new();
470    ///
471    /// tree.open("child")?;
472    /// tree.token_with("lit", Span::new(2, 4))?;
473    /// tree.token_with("lit2", Span::new(4, 6))?;
474    /// tree.token("lit3", 6)?;
475    /// tree.close()?;
476    ///
477    /// let tree = tree.build()?;
478    ///
479    /// let expected = syntree::tree! {
480    ///     ("child", (0, 6)) => {
481    ///         ("lit", (2, 4)),
482    ///         ("lit2", (4, 6)),
483    ///         ("lit3", (6, 12)),
484    ///     }
485    /// };
486    ///
487    /// assert_eq!(tree, expected);
488    /// # Ok::<_, Box<dyn core::error::Error>>(())
489    /// ```
490    pub fn token_with(
491        &mut self,
492        value: T,
493        span: Span<F::Index>,
494    ) -> Result<F::Pointer, Error<F::Error>> {
495        let id = self.insert(value, span)?;
496
497        self.sibling = Some(id);
498        self.tree.indexes_mut().push(TreeIndex {
499            index: span.start,
500            id,
501        })?;
502
503        if let Some(parent) = self.parent.and_then(|id| self.tree.get_mut(id)) {
504            parent.span = parent.span.join(&span);
505        }
506
507        self.cursor = span.end;
508        Ok(id)
509    }
510
511    /// Declare a token with the specified `value` and an empty length.
512    ///
513    /// A token is always a terminating element without children.
514    ///
515    /// # Errors
516    ///
517    /// Errors with [`Error::Overflow`] in case we run out of node
518    /// identifiers.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// let mut tree = syntree::Builder::new();
524    ///
525    /// tree.open("child")?;
526    /// tree.token_empty("lit")?;
527    /// tree.close()?;
528    ///
529    /// let tree = tree.build()?;
530    ///
531    /// let expected = syntree::tree! {
532    ///     "child" => {
533    ///         "lit"
534    ///     }
535    /// };
536    ///
537    /// assert_eq!(tree, expected);
538    /// # Ok::<_, Box<dyn core::error::Error>>(())
539    /// ```
540    pub fn token_empty(&mut self, value: T) -> Result<F::Pointer, Error<F::Error>> {
541        self.token(value, F::Length::EMPTY)
542    }
543
544    /// Get a checkpoint corresponding to the current position in the tree.
545    ///
546    /// # Mixing checkpoints
547    ///
548    /// Note that using checkpoints from a different tree doesn't have a
549    /// well-specified behavior - it might seemingly work or it might raise an
550    /// error during closing such as [`Error::MissingNode`].
551    ///
552    /// The following *is not* well-defined, here we're using a checkpoint for a
553    /// different tree but it "just happens" to work because both trees have
554    /// identical internal topologies:
555    ///
556    /// ```
557    /// use syntree::{Builder, Error};
558    ///
559    /// let mut a = Builder::new();
560    /// let mut b = Builder::new();
561    ///
562    /// let c = b.checkpoint()?;
563    ///
564    /// a.open("child")?;
565    /// a.close()?;
566    ///
567    /// b.open("child")?;
568    /// b.close()?;
569    ///
570    /// // Checkpoint use from different tree.
571    /// a.close_at(&c, "root")?;
572    ///
573    /// let unexpected = syntree::tree! {
574    ///     "root" => {
575    ///         "child"
576    ///     }
577    /// };
578    ///
579    /// assert_eq!(a.build()?, unexpected);
580    /// # Ok::<_, Box<dyn core::error::Error>>(())
581    /// ```
582    ///
583    /// # Errors
584    ///
585    /// Errors with [`Error::Overflow`] in case we run out of node
586    /// identifiers.
587    ///
588    /// # Panics
589    ///
590    /// This panics if the number of nodes are too many to fit in a vector on
591    /// your architecture. This corresponds to [`usize::MAX`].
592    ///
593    /// # Examples
594    ///
595    /// ```
596    /// let mut tree = syntree::Builder::new();
597    ///
598    /// let c = tree.checkpoint()?;
599    /// tree.open("child")?;
600    /// tree.token("lit", 3)?;
601    /// tree.close()?;
602    /// tree.close_at(&c, "root")?;
603    ///
604    /// let tree = tree.build()?;
605    ///
606    /// let expected = syntree::tree! {
607    ///     "root" => {
608    ///         "child" => {
609    ///             ("lit", 3)
610    ///         }
611    ///     }
612    /// };
613    ///
614    /// assert_eq!(tree, expected);
615    /// # Ok::<_, Box<dyn core::error::Error>>(())
616    /// ```
617    pub fn checkpoint(&mut self) -> Result<Checkpoint<F::Pointer>, Error<F::Error>> {
618        let node = F::Pointer::new(self.tree.len()).ok_or(Error::Overflow)?;
619
620        if let Some(c) = &self.checkpoint {
621            if c.node() == node {
622                return Ok(c.clone());
623            }
624        }
625
626        let c = Checkpoint::new(node, self.parent);
627        self.checkpoint = Some(c.clone());
628        Ok(c)
629    }
630
631    /// Insert a node that wraps from the given checkpointed location.
632    ///
633    /// # Errors
634    ///
635    /// The checkpoint being closed *must* be a sibling. Otherwise a
636    /// [`Error::CloseAtError`] will be raised.
637    ///
638    /// This might also sporadically error with [`Error::MissingNode`], in case
639    /// a checkpoint is used that was constructed from another tree.
640    ///
641    /// # Examples
642    ///
643    /// ```
644    /// let mut tree = syntree::Builder::new();
645    ///
646    /// let c = tree.checkpoint()?;
647    /// tree.token("lit", 3)?;
648    /// tree.close_at(&c, "root")?;
649    ///
650    /// let tree = tree.build()?;
651    ///
652    /// let expected = syntree::tree! {
653    ///     "root" => {
654    ///         ("lit", 3)
655    ///     }
656    /// };
657    ///
658    /// assert_eq!(tree, expected);
659    /// # Ok::<_, Box<dyn core::error::Error>>(())
660    /// ```
661    ///
662    /// More complex example:
663    ///
664    /// ```
665    /// let mut tree = syntree::Builder::new();
666    ///
667    /// let c = tree.checkpoint()?;
668    ///
669    /// tree.open("number")?;
670    /// tree.token("lit", 3)?;
671    /// tree.close()?;
672    ///
673    /// tree.token("whitespace", 1)?;
674    ///
675    /// tree.open("number")?;
676    /// tree.token("lit", 2)?;
677    /// tree.close()?;
678    ///
679    /// tree.close_at(&c, "root")?;
680    ///
681    /// let tree = tree.build()?;
682    ///
683    /// let expected = syntree::tree! {
684    ///     "root" => {
685    ///         "number" => {
686    ///             ("lit", 3)
687    ///         },
688    ///         ("whitespace", 1),
689    ///         "number" => {
690    ///             ("lit", 2)
691    ///         },
692    ///     }
693    /// };
694    ///
695    /// assert_eq!(tree, expected);
696    /// # Ok::<_, Box<dyn core::error::Error>>(())
697    /// ```
698    ///
699    /// Adding a token after a checkpoint:
700    ///
701    /// ```
702    /// let mut tree = syntree::Builder::new();
703    ///
704    /// let c = tree.checkpoint()?;
705    /// tree.open("child")?;
706    /// tree.token("lit", 3)?;
707    /// tree.close()?;
708    /// tree.close_at(&c, "root")?;
709    /// tree.token("sibling", 3)?;
710    ///
711    /// let tree = tree.build()?;
712    ///
713    /// let child = tree.node_with_range(0..3).ok_or("missing at 0..3")?;
714    /// assert_eq!(child.value(), "child");
715    ///
716    /// let lit = tree.first().and_then(|n| n.first()).and_then(|n| n.first()).ok_or("expected lit")?;
717    /// assert_eq!(lit.value(), "lit");
718    ///
719    /// let root = lit.ancestors().last().ok_or("missing root")?;
720    /// assert_eq!(root.value(), "root");
721    /// assert_eq!(root.parent(), None);
722    ///
723    /// let expected = syntree::tree! {
724    ///     "root" => {
725    ///         "child" => {
726    ///             ("lit", 3)
727    ///         }
728    ///     },
729    ///     ("sibling", 3)
730    /// };
731    ///
732    /// assert_eq!(tree, expected);
733    /// # Ok::<_, Box<dyn core::error::Error>>(())
734    /// ```
735    pub fn close_at(
736        &mut self,
737        c: &Checkpoint<F::Pointer>,
738        data: T,
739    ) -> Result<F::Pointer, Error<F::Error>> {
740        let (id, parent) = c.get();
741
742        if parent != self.parent {
743            return Err(Error::CloseAtError);
744        }
745
746        let new_id = F::Pointer::new(self.tree.len()).ok_or(Error::Overflow)?;
747
748        let Some(links) = self.tree.get_mut(id) else {
749            let new_id = self.insert(data, Span::point(self.cursor))?;
750
751            if new_id != id {
752                return Err(Error::MissingNode(new_id.get()));
753            }
754
755            self.sibling = Some(new_id);
756            return Ok(new_id);
757        };
758
759        let parent = links.parent.replace(new_id);
760        let prev = links.prev.take();
761
762        // Restructuring is necessary to calculate the full span of the newly
763        // inserted node and update parent references to point to the newly
764        // inserted node.
765        let (last, span) = if let Some(next) = links.next {
766            let span = links.span;
767            let (last, end) = restructure_close_at(&mut self.tree, new_id, next)?;
768            (last, Span::new(span.start, end))
769        } else {
770            (id, links.span)
771        };
772
773        if let Some(parent) = parent.and_then(|id| self.tree.get_mut(id)) {
774            if parent.first == Some(id) {
775                parent.first = Some(new_id);
776            }
777
778            if parent.last == Some(id) {
779                parent.last = Some(new_id);
780            }
781        }
782
783        if let Some(prev) = prev.and_then(|id| self.tree.get_mut(id)) {
784            prev.next = Some(new_id);
785        }
786
787        // If we're replacing the first node of the tree, the newly inserted
788        // node should be set as the first node.
789        let (first, _) = self.tree.links_mut();
790
791        if *first == Some(id) {
792            *first = Some(new_id);
793        }
794
795        // Do necessary accounting.
796        self.tree.push(Links {
797            data: Cell::new(data),
798            span,
799            prev,
800            parent,
801            next: None,
802            first: Some(id),
803            last: Some(last),
804        })?;
805
806        self.sibling = Some(new_id);
807        c.set(new_id, parent);
808        Ok(new_id)
809    }
810
811    /// Insert a node with a custom length.
812    ///
813    /// # Errors
814    ///
815    /// The checkpoint being closed *must* be a sibling. Otherwise a
816    /// [`Error::CloseAtError`] will be raised.
817    ///
818    /// This might also sporadically error with [`Error::MissingNode`], in case
819    /// a checkpoint is used that was constructed from another tree.
820    ///
821    /// # Examples
822    ///
823    /// ```
824    /// use syntree::Span;
825    ///
826    /// let mut tree = syntree::Builder::new();
827    ///
828    /// let c = tree.checkpoint()?;
829    /// tree.token_with("lit", Span::new(1, 3))?;
830    /// tree.close_at_with(&c, "custom", Span::new(0, 6))?;
831    /// tree.token_with("lit2", Span::new(6, 8))?;
832    ///
833    /// let tree = tree.build()?;
834    ///
835    /// let root = tree.first().ok_or("missing root")?;
836    /// assert_eq!(root.value(), "custom");
837    /// assert_eq!(root.span().start, 0);
838    /// assert_eq!(root.span().end, 6);
839    ///
840    /// # Ok::<_, Box<dyn core::error::Error>>(())
841    /// ```
842    pub fn close_at_with(
843        &mut self,
844        c: &Checkpoint<F::Pointer>,
845        data: T,
846        span: Span<F::Index>,
847    ) -> Result<F::Pointer, Error<F::Error>> {
848        let (id, parent) = c.get();
849
850        if parent != self.parent {
851            return Err(Error::CloseAtError);
852        }
853
854        let new_id = F::Pointer::new(self.tree.len()).ok_or(Error::Overflow)?;
855
856        let Some(links) = self.tree.get_mut(id) else {
857            let new_id = self.insert(data, span)?;
858
859            if new_id != id {
860                return Err(Error::MissingNode(new_id.get()));
861            }
862
863            self.sibling = Some(new_id);
864            return Ok(new_id);
865        };
866
867        let parent = links.parent.replace(new_id);
868        let prev = links.prev.take();
869
870        // Restructuring is necessary to calculate the full span of the newly
871        // inserted node and update parent references to point to the newly
872        // inserted node.
873        let last = if let Some(next) = links.next {
874            let (last, _) = restructure_close_at(&mut self.tree, new_id, next)?;
875            last
876        } else {
877            id
878        };
879
880        if let Some(parent) = parent.and_then(|id| self.tree.get_mut(id)) {
881            if parent.first == Some(id) {
882                parent.first = Some(new_id);
883            }
884
885            if parent.last == Some(id) {
886                parent.last = Some(new_id);
887            }
888        }
889
890        if let Some(prev) = prev.and_then(|id| self.tree.get_mut(id)) {
891            prev.next = Some(new_id);
892        }
893
894        // If we're replacing the first node of the tree, the newly inserted
895        // node should be set as the first node.
896        let (first, _) = self.tree.links_mut();
897
898        if *first == Some(id) {
899            *first = Some(new_id);
900        }
901
902        // Do necessary accounting.
903        self.tree.push(Links {
904            data: Cell::new(data),
905            span,
906            prev,
907            parent,
908            next: None,
909            first: Some(id),
910            last: Some(last),
911        })?;
912
913        self.sibling = Some(new_id);
914        c.set(new_id, parent);
915        Ok(new_id)
916    }
917
918    /// Build a [Tree] from the current state of the builder.
919    ///
920    /// # Errors
921    ///
922    /// This requires the stack in the builder to be empty. Otherwise a
923    /// [`Error::BuildError`] will be raised.
924    ///
925    /// # Examples
926    ///
927    /// ```
928    /// let mut tree = syntree::Builder::new();
929    ///
930    /// tree.open("child")?;
931    /// tree.token("number", 3)?;
932    /// tree.close()?;
933    /// tree.open("child")?;
934    /// tree.close()?;
935    ///
936    /// let tree = tree.build()?;
937    ///
938    /// let expected = syntree::tree! {
939    ///     "child" => {
940    ///         ("number", 3)
941    ///     },
942    ///     "child" => {},
943    /// };
944    ///
945    /// assert_eq!(tree, expected);
946    /// # Ok::<_, Box<dyn core::error::Error>>(())
947    /// ```
948    ///
949    /// If a tree is unbalanced during construction, building will fail with an error:
950    ///
951    /// ```
952    /// use syntree::{Error, Span, Builder};
953    ///
954    /// let mut tree = syntree::Builder::new();
955    ///
956    /// tree.open("number")?;
957    /// tree.token("lit", 3)?;
958    /// tree.close()?;
959    ///
960    /// tree.open("number")?;
961    ///
962    /// // "number" is left open.
963    /// assert!(matches!(tree.build(), Err(Error::BuildError)));
964    /// # Ok::<_, Box<dyn core::error::Error>>(())
965    /// ```
966    pub fn build(self) -> Result<Tree<T, F>, Error<F::Error>> {
967        if self.parent.is_some() {
968            return Err(Error::BuildError);
969        }
970
971        Ok(self.tree)
972    }
973
974    /// Insert a new node.
975    fn insert(&mut self, data: T, span: Span<F::Index>) -> Result<F::Pointer, Error<F::Error>> {
976        let new = F::Pointer::new(self.tree.len()).ok_or(Error::Overflow)?;
977
978        let prev = self.sibling.take();
979
980        self.tree.push(Links {
981            data: Cell::new(data),
982            span,
983            parent: self.parent,
984            prev,
985            next: None,
986            first: None,
987            last: None,
988        })?;
989
990        if let Some(id) = self.parent {
991            if let Some(node) = self.tree.links_at_mut(id) {
992                if node.first.is_none() {
993                    node.first = Some(new);
994                }
995
996                node.last = Some(new);
997                node.span.end = span.end;
998            }
999        } else {
1000            let (first, last) = self.tree.links_mut();
1001
1002            if first.is_none() {
1003                *first = Some(new);
1004            }
1005
1006            *last = Some(new);
1007        }
1008
1009        if let Some(node) = prev.and_then(|id| self.tree.links_at_mut(id)) {
1010            node.next = Some(new);
1011        }
1012
1013        Ok(new)
1014    }
1015}
1016
1017impl<T, F> Clone for Builder<T, F>
1018where
1019    T: Copy,
1020    F: Flavor<Indexes: Clone, Width: Width<Pointer: Clone>>,
1021    F::Storage<Links<T, F::Index, F::Pointer>>: Clone,
1022{
1023    #[inline]
1024    fn clone(&self) -> Self {
1025        Self {
1026            tree: self.tree.clone(),
1027            parent: self.parent,
1028            checkpoint: self.checkpoint.clone(),
1029            sibling: self.sibling,
1030            cursor: self.cursor,
1031        }
1032    }
1033}
1034
1035impl<T, F> Default for Builder<T, F>
1036where
1037    T: Copy,
1038    F: Flavor,
1039{
1040    #[inline]
1041    fn default() -> Self {
1042        Self::new_with()
1043    }
1044}
1045
1046// Adjust span to encapsulate all children and check that we just inserted the
1047// checkpointed node in the right location which should be the tail sibling of
1048// the replaced node.
1049#[allow(clippy::type_complexity)]
1050fn restructure_close_at<T, F>(
1051    tree: &mut Tree<T, F>,
1052    parent_id: F::Pointer,
1053    next: F::Pointer,
1054) -> Result<(F::Pointer, F::Index), Error<F::Error>>
1055where
1056    T: Copy,
1057    F: Flavor,
1058{
1059    let mut links = tree
1060        .get_mut(next)
1061        .ok_or_else(|| Error::MissingNode(next.get()))?;
1062    let mut last = (next, links.span.end);
1063    links.parent = Some(parent_id);
1064
1065    while let Some(next) = links.next {
1066        links = tree
1067            .get_mut(next)
1068            .ok_or_else(|| Error::MissingNode(next.get()))?;
1069        last = (next, links.span.end);
1070        links.parent = Some(parent_id);
1071    }
1072
1073    Ok(last)
1074}