Skip to main content

syntree/
builder.rs

1mod checkpoint;
2
3use core::cell::Cell;
4use core::fmt;
5
6use crate::links::{NodeLinks, TokenLinks};
7use crate::{Error, Flavor, FlavorDefault, Index, Length, Pointer, Span, Storage, Tree};
8
9pub use self::checkpoint::Checkpoint;
10use self::checkpoint::Inner;
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 two type parameters of the builder determine the following properties:
20/// * `T` is the data stored in the tree.
21/// * `F` is the [Flavor], declared with [`flavor!`][crate::flavor!]. Its
22///   [`Index`][Flavor::Index] determines the numerical bounds of spans, and if
23///   set to [Empty][crate::Empty] the tree does not store any spans. Its
24///   [`Width`][Flavor::Width] determines the bounds of pointers in the tree,
25///   which decides how many nodes can be stored in it. It also selects the
26///   [`Storage`][Flavor::Storage] used and its error type.
27///
28/// To use the default values, use the [Builder::new][Builder::new] constructor.
29///
30/// # Errors
31///
32/// Besides the errors documented on each method, any method which adds a node
33/// or token can fail with [`Error::Flavor`] if the flavor's storage fails to
34/// grow.
35///
36/// # Examples
37///
38/// ```
39/// let mut tree = syntree::Builder::new();
40///
41/// tree.open("root")?;
42/// tree.open("child")?;
43/// tree.close()?;
44/// tree.open("child")?;
45/// tree.close()?;
46/// tree.close()?;
47///
48/// let tree = tree.build()?;
49///
50/// let expected = syntree::tree! {
51///     "root" => {
52///         "child" => {},
53///         "child" => {}
54///     }
55/// };
56///
57/// assert_eq!(tree, expected);
58/// # Ok::<_, Box<dyn core::error::Error>>(())
59/// ```
60pub struct Builder<T, F = FlavorDefault>
61where
62    T: Copy,
63    F: Flavor,
64{
65    /// Data in the tree being built.
66    tree: Tree<T, F>,
67    /// The state of every checkpoint handed out, indexed by [`Checkpoint`].
68    checkpoints: F::Storage<Inner<F::Pointer>>,
69    /// Reference the current parent to the node being built. It itself has its
70    /// parent set in the tree, so that is what is used to traverse ancestors of
71    /// a node.
72    parent: Option<F::Pointer>,
73    /// The last interior node at the current level.
74    sibling: Option<F::Pointer>,
75    /// The current cursor.
76    cursor: F::Index,
77}
78
79impl<T> Builder<T, FlavorDefault>
80where
81    T: Copy,
82{
83    /// Construct a new tree with a default [`Span`] based on `u32`.
84    ///
85    /// For a constructor that can use custom bounds, use [Builder::new_with].
86    ///
87    /// # Examples
88    ///
89    /// ```
90    /// let mut tree = syntree::Builder::new();
91    ///
92    /// tree.open("root")?;
93    ///
94    /// tree.open("child")?;
95    /// tree.token("token", 5)?;
96    /// tree.close()?;
97    ///
98    /// tree.open("child2")?;
99    /// tree.close()?;
100    ///
101    /// tree.close()?;
102    ///
103    /// let tree = tree.build()?;
104    ///
105    /// let expected = syntree::tree! {
106    ///     "root" => {
107    ///         "child" => {
108    ///             ("token", 5)
109    ///         },
110    ///         "child2" => {}
111    ///     }
112    /// };
113    ///
114    /// assert_eq!(tree, expected);
115    /// # Ok::<_, Box<dyn core::error::Error>>(())
116    /// ```
117    #[must_use]
118    pub const fn new() -> Self {
119        Self::new_with()
120    }
121}
122
123impl<T, F> Builder<T, F>
124where
125    T: Copy,
126    F: Flavor,
127{
128    /// Construct a new tree with a custom span.
129    ///
130    /// To build a tree with default bounds, see [Builder::new]. Also see the
131    /// [Builder] documentation for what the different bounds means.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// use syntree::{Builder, Empty, Tree};
137    ///
138    /// syntree::flavor! {
139    ///     struct FlavorEmpty {
140    ///         type Index = Empty;
141    ///         type Width = u32;
142    ///     }
143    /// }
144    ///
145    /// let mut tree: Builder<_, FlavorEmpty> = Builder::new_with();
146    ///
147    /// tree.open("root")?;
148    ///
149    /// tree.open("child")?;
150    /// tree.token("token", Empty)?;
151    /// tree.close()?;
152    ///
153    /// tree.open("child2")?;
154    /// tree.close()?;
155    ///
156    /// tree.close()?;
157    ///
158    /// let tree = tree.build()?;
159    ///
160    /// let expected: Tree<_, FlavorEmpty> = syntree::tree_with! {
161    ///     "root" => {
162    ///         "child" => {
163    ///             "token"
164    ///         },
165    ///         "child2" => {}
166    ///     }
167    /// };
168    ///
169    /// assert_eq!(tree, expected);
170    /// # Ok::<_, Box<dyn core::error::Error>>(())
171    /// ```
172    #[must_use]
173    pub const fn new_with() -> Self {
174        Builder {
175            tree: Tree::new_with(),
176            parent: None,
177            checkpoints: Storage::EMPTY,
178            sibling: None,
179            cursor: F::Index::EMPTY,
180        }
181    }
182
183    /// Construct a new builder with capacity for `tokens` tokens.
184    ///
185    /// Every call to [`Builder::token`] (and its variants) adds one token,
186    /// and a token with an explicit span which leaves a gap after the previous
187    /// token takes one more entry. Interior nodes, added by [`Builder::open`]
188    /// and [`Builder::close_at`], are sized separately through
189    /// [`Builder::with_capacities`].
190    ///
191    /// # Errors
192    ///
193    /// Errors with [`Error::Flavor`] if the flavor's storage can't hold
194    /// `tokens` tokens.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use syntree::{Builder, FlavorDefault};
200    ///
201    /// let mut tree = Builder::<_, FlavorDefault>::with_capacity(2)?;
202    ///
203    /// tree.open("root")?;
204    /// tree.token("token", 5)?;
205    /// tree.close()?;
206    ///
207    /// let tree = tree.build()?;
208    /// assert_eq!(tree.len(), 2);
209    /// assert!(tree.capacity() >= 2);
210    /// # Ok::<_, Box<dyn core::error::Error>>(())
211    /// ```
212    pub fn with_capacity(tokens: usize) -> Result<Self, Error<F::Error>> {
213        Self::with_capacities(0, tokens)
214    }
215
216    /// Construct a new builder with capacity for `nodes` interior nodes and
217    /// `tokens` tokens.
218    ///
219    /// See [`Builder::with_capacity`] for what the counts mean.
220    ///
221    /// # Errors
222    ///
223    /// Errors with [`Error::Flavor`] if the flavor's storage can't hold
224    /// `nodes` nodes or `tokens` tokens.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// use syntree::{Builder, FlavorDefault};
230    ///
231    /// let source = "a b";
232    /// // At most one token per byte, and a root node.
233    /// let mut tree = Builder::<_, FlavorDefault>::with_capacities(1, source.len())?;
234    ///
235    /// tree.open("root")?;
236    /// tree.token("word", 1)?;
237    /// tree.token("ws", 1)?;
238    /// tree.token("word", 1)?;
239    /// tree.close()?;
240    ///
241    /// let tree = tree.build()?;
242    /// assert_eq!(tree.len(), 4);
243    /// assert_eq!(tree.capacity(), 4);
244    /// # Ok::<_, Box<dyn core::error::Error>>(())
245    /// ```
246    pub fn with_capacities(nodes: usize, tokens: usize) -> Result<Self, Error<F::Error>> {
247        Ok(Builder {
248            tree: Tree::with_capacity(nodes, tokens)?,
249            parent: None,
250            checkpoints: Storage::EMPTY,
251            sibling: None,
252            cursor: F::Index::EMPTY,
253        })
254    }
255
256    /// Reserve capacity for at least `nodes` more interior nodes and `tokens`
257    /// more tokens.
258    ///
259    /// See [`Builder::with_capacity`] for what the counts mean.
260    ///
261    /// # Errors
262    ///
263    /// Errors with [`Error::Flavor`] if the flavor's storage can't hold that
264    /// many more nodes or tokens.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// let mut tree = syntree::Builder::new();
270    /// tree.reserve(1, 1)?;
271    ///
272    /// tree.open("root")?;
273    /// tree.token("token", 5)?;
274    /// tree.close()?;
275    ///
276    /// let tree = tree.build()?;
277    /// assert_eq!(tree.len(), 2);
278    /// # Ok::<_, Box<dyn core::error::Error>>(())
279    /// ```
280    pub fn reserve(&mut self, nodes: usize, tokens: usize) -> Result<(), Error<F::Error>> {
281        self.tree.reserve(nodes, tokens)
282    }
283
284    /// Reserve room for at least `additional` more checkpoints.
285    ///
286    /// Checkpoints are stored in the builder, so a parser which knows roughly
287    /// how many it will take can size that storage up front instead of growing
288    /// it.
289    ///
290    /// Errors with [`Error::Flavor`] if the flavor's storage can't hold that
291    /// many more checkpoints.
292    ///
293    /// # Examples
294    ///
295    /// ```
296    /// let mut tree = syntree::Builder::new();
297    /// tree.reserve_checkpoints(2)?;
298    ///
299    /// let c = tree.checkpoint()?;
300    /// tree.token("token", 5)?;
301    /// tree.close_at(c, "wrapper")?;
302    ///
303    /// let tree = tree.build()?;
304    /// assert_eq!(tree.len(), 2);
305    /// # Ok::<_, Box<dyn core::error::Error>>(())
306    /// ```
307    pub fn reserve_checkpoints(&mut self, additional: usize) -> Result<(), Error<F::Error>> {
308        self.checkpoints.reserve(additional)?;
309        Ok(())
310    }
311
312    /// Get a reference to the current cursor position of the syntax tree.
313    ///
314    /// The cursor position is the position in which it's been advanced so far
315    /// as a result of calls to [Builder::token] and indicates the current
316    /// starting index of the next span.
317    ///
318    /// # Examples
319    ///
320    /// ```
321    /// let mut tree = syntree::Builder::new();
322    ///
323    /// assert_eq!(*tree.cursor(), 0);
324    /// tree.open("child")?;
325    /// assert_eq!(*tree.cursor(), 0);
326    /// tree.token("lit", 4)?;
327    /// assert_eq!(*tree.cursor(), 4);
328    /// tree.close()?;
329    /// assert_eq!(*tree.cursor(), 4);
330    ///
331    /// let tree = tree.build()?;
332    ///
333    /// let expected = syntree::tree! {
334    ///     "child" => {
335    ///         ("lit", 4)
336    ///     }
337    /// };
338    ///
339    /// assert_eq!(tree, expected);
340    /// # Ok::<_, Box<dyn core::error::Error>>(())
341    /// ```
342    #[inline]
343    pub const fn cursor(&self) -> &F::Index {
344        &self.cursor
345    }
346
347    /// Set the cursor position of the syntax tree.
348    ///
349    /// This is used to implicitly set spans when using spanless constructions
350    /// methods. Range queries such as [`Tree::node_with_range`] assume that
351    /// tokens are added in non-decreasing order, so the cursor should not be
352    /// moved backwards past an already added token.
353    ///
354    /// # Examples
355    ///
356    /// ```
357    /// use syntree::Span;
358    ///
359    /// let mut tree = syntree::Builder::new();
360    ///
361    /// tree.open("child")?;
362    /// tree.token("lit", 4)?;
363    /// // Skip two units of input which are not part of the tree.
364    /// tree.set_cursor(6);
365    /// assert_eq!(*tree.cursor(), 6);
366    /// tree.token("lit", 2)?;
367    /// tree.close()?;
368    ///
369    /// let tree = tree.build()?;
370    ///
371    /// let child = tree.first().ok_or("missing child")?;
372    /// assert_eq!(child.span(), &Span::new(0, 8));
373    ///
374    /// let spans = child.children().map(|n| n.span()).collect::<Vec<_>>();
375    /// assert_eq!(spans, [Span::new(0, 4), Span::new(6, 8)]);
376    /// # Ok::<_, Box<dyn core::error::Error>>(())
377    /// ```
378    pub fn set_cursor(&mut self, cursor: F::Index) {
379        self.cursor = cursor;
380    }
381
382    /// Start a node with the given `data`.
383    ///
384    /// This pushes a new link with the given type onto the stack which links
385    /// itself onto the last sibling node that was introduced either through
386    /// [`Builder::close`], [`Builder::close_at`], or
387    /// [`Builder::close_at_with`].
388    ///
389    /// # Errors
390    ///
391    /// Errors with [`Error::Overflow`] in case we run out of node
392    /// identifiers.
393    ///
394    /// # Examples
395    ///
396    /// ```
397    /// let mut tree = syntree::Builder::new();
398    ///
399    /// tree.open("root")?;
400    ///
401    /// tree.open("child")?;
402    /// tree.close()?;
403    ///
404    /// tree.open("child")?;
405    /// tree.close()?;
406    ///
407    /// tree.close()?;
408    /// # Ok::<_, Box<dyn core::error::Error>>(())
409    /// ```
410    pub fn open(&mut self, data: T) -> Result<F::Pointer, Error<F::Error>> {
411        let id = self.insert(data, Span::point(self.cursor))?;
412        self.parent = Some(id);
413        Ok(id)
414    }
415
416    /// Start a node with the given `data` and span.
417    ///
418    /// This pushes a new link with the given type onto the stack which links
419    /// itself onto the last sibling node that was introduced either through
420    /// [`Builder::close`], [`Builder::close_at`] or [`Builder::close_at_with`].
421    ///
422    /// This does not advance the cursor position, in order to fix tree
423    /// construction use [`Builder::set_cursor`].
424    ///
425    /// # Errors
426    ///
427    /// Errors with [`Error::Overflow`] in case we run out of node
428    /// identifiers.
429    ///
430    /// # Examples
431    ///
432    /// ```
433    /// use syntree::Span;
434    ///
435    /// let mut tree = syntree::Builder::new();
436    ///
437    /// tree.open("root")?;
438    ///
439    /// tree.open_with("child", Span::new(0, 3))?;
440    /// tree.close()?;
441    ///
442    /// tree.open_with("child", Span::new(3, 6))?;
443    /// tree.close()?;
444    ///
445    /// tree.close()?;
446    ///
447    /// let tree = tree.build()?;
448    ///
449    /// let expected = syntree::tree! {
450    ///     ("root", (0, 6)) => {
451    ///         ("child", (0, 3)) => {},
452    ///         ("child", (3, 6)) => {}
453    ///     }
454    /// };
455    ///
456    /// assert_eq!(tree, expected);
457    /// # Ok::<_, Box<dyn core::error::Error>>(())
458    /// ```
459    pub fn open_with(
460        &mut self,
461        data: T,
462        span: Span<F::Index>,
463    ) -> Result<F::Pointer, Error<F::Error>> {
464        let id = self.insert(data, span)?;
465        self.parent = Some(id);
466        Ok(id)
467    }
468
469    /// End a node being built.
470    ///
471    /// This will pop a value of the stack, and set that value as the next
472    /// sibling which will be used with [`Builder::open`].
473    ///
474    /// # Errors
475    ///
476    /// This call must be balanced with a prior call to [`Builder::open`].
477    /// If not this will result in an [`Error::CloseError`] being raised.
478    ///
479    /// # Examples
480    ///
481    /// ```
482    /// let mut tree = syntree::Builder::new();
483    ///
484    /// tree.open("root")?;
485    ///
486    /// tree.open("child")?;
487    /// tree.close()?;
488    ///
489    /// tree.open("child")?;
490    /// tree.close()?;
491    ///
492    /// tree.close()?;
493    /// # Ok::<_, Box<dyn core::error::Error>>(())
494    /// ```
495    pub fn close(&mut self) -> Result<(), Error<F::Error>> {
496        let head = self.parent.ok_or(Error::CloseError)?;
497        let tok_end = F::Pointer::new(self.tree.tokens().len()).ok_or(Error::Overflow)?;
498
499        let links = self
500            .tree
501            .node_links_mut(head)
502            .ok_or_else(|| Error::MissingNode(head.get()))?;
503
504        links.tok_end = tok_end;
505        let parent = links.parent;
506        let span = links.span;
507
508        if let Some(id) = parent {
509            let parent = self
510                .tree
511                .node_links_mut(id)
512                .ok_or_else(|| Error::MissingNode(id.get()))?;
513
514            parent.span = parent.span.join(&span);
515        }
516
517        self.parent = parent;
518        self.sibling = Some(head);
519        self.cursor = span.end;
520        Ok(())
521    }
522
523    /// Declare a token with the specified `value` and a corresponding `len`.
524    ///
525    /// A token is always a terminating element without children.
526    ///
527    /// # Errors
528    ///
529    /// Errors with [`Error::Overflow`] in case we run out of token
530    /// identifiers, or [`Error::TokenOrder`] if the token would start before
531    /// the end of the previous token, which happens after
532    /// [`Builder::set_cursor`] moves the cursor back.
533    ///
534    /// # Examples
535    ///
536    /// ```
537    /// let mut tree = syntree::Builder::new();
538    ///
539    /// tree.open("child")?;
540    /// tree.token("lit", 4)?;
541    /// tree.close()?;
542    ///
543    /// let tree = tree.build()?;
544    ///
545    /// let expected = syntree::tree! {
546    ///     "child" => {
547    ///         ("lit", 4)
548    ///     }
549    /// };
550    ///
551    /// assert_eq!(tree, expected);
552    /// # Ok::<_, Box<dyn core::error::Error>>(())
553    /// ```
554    pub fn token(&mut self, value: T, len: F::Length) -> Result<F::Pointer, Error<F::Error>> {
555        let start = self.cursor;
556
557        let end = if len.is_empty() {
558            start
559        } else {
560            start.checked_add_len(len).ok_or(Error::Overflow)?
561        };
562
563        self.insert_token(value, Span::new(start, end), false)
564    }
565
566    /// Insert a token with a custom span.
567    ///
568    /// The span is joined into the spans of the enclosing nodes and the tree.
569    /// Tokens are stored in source order, so a token can't start before the
570    /// end of the previous one, but it may leave a gap after it.
571    ///
572    /// # Errors
573    ///
574    /// Errors with [`Error::Overflow`] in case we run out of token
575    /// identifiers, or [`Error::TokenOrder`] if `span` starts before the end
576    /// of the previous token or ends before it starts.
577    ///
578    /// # Examples
579    ///
580    /// ```
581    /// use syntree::Span;
582    ///
583    /// let mut tree = syntree::Builder::new();
584    ///
585    /// tree.open_with("child", Span::new(0, 10))?;
586    /// tree.token_with("lit", Span::new(2, 4))?;
587    /// tree.token_with("lit2", Span::new(4, 6))?;
588    /// tree.close()?;
589    ///
590    /// let tree = tree.build()?;
591    ///
592    /// let child = tree.first().ok_or("missing child")?;
593    /// assert_eq!(child.span(), &Span::new(0, 10));
594    ///
595    /// let spans = child.children().map(|n| (n.value(), n.span())).collect::<Vec<_>>();
596    /// assert_eq!(spans, [("lit", Span::new(2, 4)), ("lit2", Span::new(4, 6))]);
597    ///
598    /// assert_eq!(tree.span(), &Span::new(0, 10));
599    /// # Ok::<_, Box<dyn core::error::Error>>(())
600    /// ```
601    ///
602    /// Tokens with spans forces the cursor to be set to the end of the span.
603    ///
604    /// ```
605    /// use syntree::Span;
606    ///
607    /// let mut tree = syntree::Builder::new();
608    ///
609    /// tree.open("child")?;
610    /// tree.token_with("lit", Span::new(2, 4))?;
611    /// tree.token_with("lit2", Span::new(4, 6))?;
612    /// assert_eq!(*tree.cursor(), 6);
613    /// tree.token("lit3", 6)?;
614    /// tree.close()?;
615    ///
616    /// let tree = tree.build()?;
617    ///
618    /// let child = tree.first().ok_or("missing child")?;
619    /// assert_eq!(child.span(), &Span::new(0, 12));
620    ///
621    /// let lit3 = child.last().ok_or("missing lit3")?;
622    /// assert_eq!(lit3.value(), "lit3");
623    /// assert_eq!(lit3.span(), &Span::new(6, 12));
624    ///
625    /// assert_eq!(tree.span(), &Span::new(0, 12));
626    /// # Ok::<_, Box<dyn core::error::Error>>(())
627    /// ```
628    pub fn token_with(
629        &mut self,
630        value: T,
631        span: Span<F::Index>,
632    ) -> Result<F::Pointer, Error<F::Error>> {
633        self.insert_token(value, span, false)
634    }
635
636    /// Declare a token with the specified `value` and an empty length.
637    ///
638    /// A token is always a terminating element without children.
639    ///
640    /// # Errors
641    ///
642    /// Errors with [`Error::Overflow`] in case we run out of token
643    /// identifiers, or [`Error::TokenOrder`] if the token would start before
644    /// the end of the previous token, which happens after
645    /// [`Builder::set_cursor`] moves the cursor back.
646    ///
647    /// # Examples
648    ///
649    /// ```
650    /// let mut tree = syntree::Builder::new();
651    ///
652    /// tree.open("child")?;
653    /// tree.token_empty("lit")?;
654    /// tree.close()?;
655    ///
656    /// let tree = tree.build()?;
657    ///
658    /// let expected = syntree::tree! {
659    ///     "child" => {
660    ///         "lit"
661    ///     }
662    /// };
663    ///
664    /// assert_eq!(tree, expected);
665    /// # Ok::<_, Box<dyn core::error::Error>>(())
666    /// ```
667    pub fn token_empty(&mut self, value: T) -> Result<F::Pointer, Error<F::Error>> {
668        self.token(value, F::Length::EMPTY)
669    }
670
671    /// Insert a trivia token with the given length, such as whitespace or a
672    /// comment.
673    ///
674    /// Trivia is stored like any other token, so the spans of the enclosing
675    /// nodes and of the tree cover it and the source round-trips losslessly.
676    /// It is only hidden from iteration: [`Node::children`], [`Node::walk`]
677    /// and the other iterators skip trivia unless asked to include it with
678    /// `with_trivia()`. Point accessors such as [`Node::first`] or
679    /// [`Token::next`] are structural and do see it. Use [`Token::is_trivia`]
680    /// to tell it apart.
681    ///
682    /// [`Node::children`]: crate::Node::children
683    /// [`Node::walk`]: crate::Node::walk
684    /// [`Node::first`]: crate::Node::first
685    /// [`Token::next`]: crate::Token::next
686    /// [`Token::is_trivia`]: crate::Token::is_trivia
687    ///
688    /// # Errors
689    ///
690    /// Errors like [`Builder::token`].
691    ///
692    /// # Examples
693    ///
694    /// ```
695    /// let mut tree = syntree::Builder::new();
696    ///
697    /// tree.open("call")?;
698    /// tree.token("ident", 3)?;
699    /// tree.trivia("whitespace", 1)?;
700    /// tree.token("paren", 2)?;
701    /// tree.close()?;
702    ///
703    /// let tree = tree.build()?;
704    ///
705    /// let call = tree.first().and_then(|e| e.into_node()).ok_or("missing call")?;
706    /// assert_eq!(call.span(), &syntree::Span::new(0, 6));
707    ///
708    /// let kinds = call.children().map(|e| e.value()).collect::<Vec<_>>();
709    /// assert_eq!(kinds, ["ident", "paren"]);
710    ///
711    /// let kinds = call.children().with_trivia().map(|e| e.value()).collect::<Vec<_>>();
712    /// assert_eq!(kinds, ["ident", "whitespace", "paren"]);
713    /// # Ok::<_, Box<dyn core::error::Error>>(())
714    /// ```
715    pub fn trivia(&mut self, value: T, len: F::Length) -> Result<F::Pointer, Error<F::Error>> {
716        let start = self.cursor;
717
718        let end = if len.is_empty() {
719            start
720        } else {
721            start.checked_add_len(len).ok_or(Error::Overflow)?
722        };
723
724        self.insert_token(value, Span::new(start, end), true)
725    }
726
727    /// Insert a trivia token with a custom span. This is [`Builder::trivia`]
728    /// with an explicit span, like [`Builder::token_with`] is to
729    /// [`Builder::token`].
730    ///
731    /// # Errors
732    ///
733    /// Errors like [`Builder::token_with`].
734    ///
735    /// # Examples
736    ///
737    /// ```
738    /// use syntree::Span;
739    ///
740    /// let mut tree = syntree::Builder::new();
741    ///
742    /// tree.token_with("ident", Span::new(0, 3))?;
743    /// tree.trivia_with("comment", Span::new(4, 9))?;
744    ///
745    /// let tree = tree.build()?;
746    ///
747    /// assert_eq!(tree.span(), &Span::new(0, 9));
748    /// assert_eq!(tree.children().count(), 1);
749    ///
750    /// let comment = tree.last().and_then(|e| e.into_token()).ok_or("missing comment")?;
751    /// assert!(comment.is_trivia());
752    /// assert_eq!(comment.span(), Span::new(4, 9));
753    /// # Ok::<_, Box<dyn core::error::Error>>(())
754    /// ```
755    pub fn trivia_with(
756        &mut self,
757        value: T,
758        span: Span<F::Index>,
759    ) -> Result<F::Pointer, Error<F::Error>> {
760        self.insert_token(value, span, true)
761    }
762
763    /// Get a checkpoint corresponding to the current position in the tree.
764    ///
765    /// Checkpoints are only meaningful to the builder that handed them out. A
766    /// checkpoint used on another builder refers to that builder's checkpoint
767    /// with the same index, or raises [`Error::MissingCheckpoint`] if it has
768    /// none.
769    ///
770    /// # Errors
771    ///
772    /// Errors with [`Error::Flavor`] if the checkpoint can't be stored.
773    ///
774    /// # Examples
775    ///
776    /// ```
777    /// let mut tree = syntree::Builder::new();
778    ///
779    /// let c = tree.checkpoint()?;
780    /// tree.open("child")?;
781    /// tree.token("lit", 3)?;
782    /// tree.close()?;
783    /// tree.close_at(c, "root")?;
784    ///
785    /// let tree = tree.build()?;
786    ///
787    /// let expected = syntree::tree! {
788    ///     "root" => {
789    ///         "child" => {
790    ///             ("lit", 3)
791    ///         }
792    ///     }
793    /// };
794    ///
795    /// assert_eq!(tree, expected);
796    /// # Ok::<_, Box<dyn core::error::Error>>(())
797    /// ```
798    pub fn checkpoint(&mut self) -> Result<Checkpoint<F::Pointer>, Error<F::Error>> {
799        let inner = Inner {
800            tok: self.tree.tokens().len(),
801            before: self.sibling,
802            parent: self.parent,
803        };
804
805        // Reuse the last checkpoint if it is at the same position.
806        let index = self.checkpoints.len();
807
808        if let Some(last) = index.checked_sub(1) {
809            if self.checkpoints.last() == Some(&inner) {
810                return Ok(Checkpoint::new(last));
811            }
812        }
813
814        self.checkpoints.push(inner)?;
815        Ok(Checkpoint::new(index))
816    }
817
818    /// Insert a node that wraps from the given checkpointed location.
819    ///
820    /// # Errors
821    ///
822    /// The checkpoint being closed *must* be a sibling. Otherwise a
823    /// [`Error::CloseAtError`] will be raised.
824    ///
825    /// A checkpoint this builder did not hand out raises
826    /// [`Error::MissingCheckpoint`].
827    ///
828    /// # Examples
829    ///
830    /// ```
831    /// let mut tree = syntree::Builder::new();
832    ///
833    /// let c = tree.checkpoint()?;
834    /// tree.token("lit", 3)?;
835    /// tree.close_at(c, "root")?;
836    ///
837    /// let tree = tree.build()?;
838    ///
839    /// let expected = syntree::tree! {
840    ///     "root" => {
841    ///         ("lit", 3)
842    ///     }
843    /// };
844    ///
845    /// assert_eq!(tree, expected);
846    /// # Ok::<_, Box<dyn core::error::Error>>(())
847    /// ```
848    ///
849    /// More complex example:
850    ///
851    /// ```
852    /// let mut tree = syntree::Builder::new();
853    ///
854    /// let c = tree.checkpoint()?;
855    ///
856    /// tree.open("number")?;
857    /// tree.token("lit", 3)?;
858    /// tree.close()?;
859    ///
860    /// tree.token("whitespace", 1)?;
861    ///
862    /// tree.open("number")?;
863    /// tree.token("lit", 2)?;
864    /// tree.close()?;
865    ///
866    /// tree.close_at(c, "root")?;
867    ///
868    /// let tree = tree.build()?;
869    ///
870    /// let expected = syntree::tree! {
871    ///     "root" => {
872    ///         "number" => {
873    ///             ("lit", 3)
874    ///         },
875    ///         ("whitespace", 1),
876    ///         "number" => {
877    ///             ("lit", 2)
878    ///         },
879    ///     }
880    /// };
881    ///
882    /// assert_eq!(tree, expected);
883    /// # Ok::<_, Box<dyn core::error::Error>>(())
884    /// ```
885    ///
886    /// Adding a token after a checkpoint:
887    ///
888    /// ```
889    /// let mut tree = syntree::Builder::new();
890    ///
891    /// let c = tree.checkpoint()?;
892    /// tree.open("child")?;
893    /// tree.token("lit", 3)?;
894    /// tree.close()?;
895    /// tree.close_at(c, "root")?;
896    /// tree.token("sibling", 3)?;
897    ///
898    /// let tree = tree.build()?;
899    ///
900    /// let lit = tree.node_with_range(0..3).ok_or("missing at 0..3")?;
901    /// assert_eq!(lit.value(), "lit");
902    ///
903    /// let child = lit.parent().ok_or("missing child")?;
904    /// assert_eq!(child.value(), "child");
905    ///
906    /// let root = lit.ancestors().last().ok_or("missing root")?;
907    /// assert_eq!(root.value(), "root");
908    /// assert_eq!(root.parent(), None);
909    ///
910    /// let expected = syntree::tree! {
911    ///     "root" => {
912    ///         "child" => {
913    ///             ("lit", 3)
914    ///         }
915    ///     },
916    ///     ("sibling", 3)
917    /// };
918    ///
919    /// assert_eq!(tree, expected);
920    /// # Ok::<_, Box<dyn core::error::Error>>(())
921    /// ```
922    pub fn close_at(
923        &mut self,
924        c: Checkpoint<F::Pointer>,
925        data: T,
926    ) -> Result<F::Pointer, Error<F::Error>> {
927        self.close_at_inner(c, data, None)
928    }
929
930    /// Insert a node with a custom length.
931    ///
932    /// # Errors
933    ///
934    /// The checkpoint being closed *must* be a sibling. Otherwise a
935    /// [`Error::CloseAtError`] will be raised.
936    ///
937    /// A checkpoint this builder did not hand out raises
938    /// [`Error::MissingCheckpoint`].
939    ///
940    /// # Examples
941    ///
942    /// ```
943    /// use syntree::Span;
944    ///
945    /// let mut tree = syntree::Builder::new();
946    ///
947    /// let c = tree.checkpoint()?;
948    /// tree.token_with("lit", Span::new(1, 3))?;
949    /// tree.close_at_with(c, "custom", Span::new(0, 6))?;
950    /// tree.token_with("lit2", Span::new(6, 8))?;
951    ///
952    /// let tree = tree.build()?;
953    ///
954    /// let root = tree.first().ok_or("missing root")?;
955    /// assert_eq!(root.value(), "custom");
956    /// assert_eq!(root.span(), &Span::new(0, 6));
957    /// assert_eq!(tree.span(), &Span::new(0, 8));
958    /// # Ok::<_, Box<dyn core::error::Error>>(())
959    /// ```
960    pub fn close_at_with(
961        &mut self,
962        c: Checkpoint<F::Pointer>,
963        data: T,
964        span: Span<F::Index>,
965    ) -> Result<F::Pointer, Error<F::Error>> {
966        self.close_at_inner(c, data, Some(span))
967    }
968
969    /// Wrap everything since the checkpoint in a new node, using `span` or the
970    /// span covered by the wrapped nodes when it is `None`.
971    fn close_at_inner(
972        &mut self,
973        c: Checkpoint<F::Pointer>,
974        data: T,
975        span: Option<Span<F::Index>>,
976    ) -> Result<F::Pointer, Error<F::Error>> {
977        let Some(&Inner {
978            tok,
979            before,
980            parent,
981        }) = self.checkpoints.get(c.index())
982        else {
983            return Err(Error::MissingCheckpoint(c.index()));
984        };
985
986        if parent != self.parent {
987            return Err(Error::CloseAtError);
988        }
989
990        let tokens = self.tree.tokens().len();
991
992        if tok > tokens {
993            return Err(Error::MissingCheckpoint(c.index()));
994        }
995
996        let new_id = self.next_node_id()?;
997        let tok_start = F::Pointer::new(tok).ok_or(Error::Overflow)?;
998        let tok_end = F::Pointer::new(tokens).ok_or(Error::Overflow)?;
999
1000        // Each node consulted is looked up once: the parent for the ends of
1001        // its chain of interior children, the node before the checkpoint, and
1002        // the first and last wrapped interior nodes.
1003        let (level_first, level_last) = match parent {
1004            Some(id) => {
1005                let links = self
1006                    .tree
1007                    .node_links(id)
1008                    .ok_or_else(|| Error::MissingNode(id.get()))?;
1009
1010                (links.first, links.last)
1011            }
1012            None => {
1013                let (first, last) = self.tree.links_mut();
1014                (*first, *last)
1015            }
1016        };
1017
1018        // The first interior node to wrap. A checkpoint whose position was
1019        // since wrapped by another `close_at` is stale: its interior sibling
1020        // has a new parent, or the interior node now at its position starts
1021        // before it.
1022        let first = match before {
1023            Some(id) => {
1024                let links = self
1025                    .tree
1026                    .node_links(id)
1027                    .ok_or_else(|| Error::MissingNode(id.get()))?;
1028
1029                if links.parent != parent {
1030                    return Err(Error::CloseAtError);
1031                }
1032
1033                links.next
1034            }
1035            None => level_first,
1036        };
1037
1038        // The token position and span start of the first wrapped interior node.
1039        let first_start = match first {
1040            Some(id) => {
1041                let links = self
1042                    .tree
1043                    .node_links(id)
1044                    .ok_or_else(|| Error::MissingNode(id.get()))?;
1045
1046                let start = links.tok_start.get();
1047
1048                if start < tok {
1049                    return Err(Error::CloseAtError);
1050                }
1051
1052                Some((start, links.span.start))
1053            }
1054            None => None,
1055        };
1056
1057        // The span of what is wrapped, from the first wrapped element to the
1058        // last. Nothing is wrapped if no token or interior node was added at
1059        // this level since the checkpoint. This is the merge of
1060        // `Tree::next_at` and `Tree::prev_at` with the spans of what they
1061        // find, reusing the links already read.
1062        let wrapped = if first.is_some() || tok < tokens {
1063            let start = match first_start {
1064                Some((start, span_start)) if start <= tok => Some(span_start),
1065                _ => self.token_start_at(parent, tok),
1066            };
1067
1068            let end = self.wrapped_end(parent, tokens, level_last);
1069
1070            match (start, end) {
1071                (Some(start), Some(end)) => Some(Span::new(start, end)),
1072                _ => return Err(Error::MissingNode(tok)),
1073            }
1074        } else {
1075            None
1076        };
1077
1078        let node_span = match (span, wrapped) {
1079            (Some(span), _) => span,
1080            (None, Some(wrapped)) => wrapped,
1081            (None, None) => Span::point(self.cursor),
1082        };
1083
1084        // Re-parent the wrapped interior nodes, and the wrapped tokens in the
1085        // gaps between them. Tokens inside wrapped interior nodes keep their
1086        // parents, so each node's token range is skipped in one step to keep
1087        // this linear in the number of direct children. The first wrapped node
1088        // also loses its previous sibling.
1089        let mut cur = first;
1090        let mut pos = tok;
1091        let mut is_first = true;
1092
1093        while let Some(id) = cur {
1094            let links = self
1095                .tree
1096                .node_links_mut(id)
1097                .ok_or_else(|| Error::MissingNode(id.get()))?;
1098            links.parent = Some(new_id);
1099
1100            if is_first {
1101                links.prev = None;
1102                is_first = false;
1103            }
1104
1105            cur = links.next;
1106            let (start, end) = (links.tok_start.get(), links.tok_end.get());
1107
1108            self.reparent_tokens(pos, start, parent, new_id);
1109            pos = pos.max(end);
1110        }
1111
1112        self.reparent_tokens(pos, tokens, parent, new_id);
1113
1114        // The wrapper takes everything from the checkpoint onwards, so it is
1115        // always the last interior node at its level.
1116        if let Some(links) = before.and_then(|id| self.tree.node_links_mut(id)) {
1117            links.next = Some(new_id);
1118        }
1119
1120        // An explicit span, or an empty wrapper, may reach outside of what
1121        // the enclosing node and the tree already cover.
1122        let join = span.is_some() || wrapped.is_none();
1123
1124        match parent {
1125            Some(id) => {
1126                if let Some(links) = self.tree.node_links_mut(id) {
1127                    if before.is_none() {
1128                        links.first = Some(new_id);
1129                    }
1130
1131                    links.last = Some(new_id);
1132
1133                    if join {
1134                        links.span = links.span.join(&node_span);
1135                    }
1136                }
1137            }
1138            None => {
1139                let (level_first, level_last) = self.tree.links_mut();
1140
1141                if before.is_none() {
1142                    *level_first = Some(new_id);
1143                }
1144
1145                *level_last = Some(new_id);
1146            }
1147        }
1148
1149        if join {
1150            self.join_tree_span(&node_span);
1151        }
1152
1153        self.tree.push_node(NodeLinks {
1154            data: Cell::new(data),
1155            span: node_span,
1156            tok_start,
1157            tok_end,
1158            parent,
1159            prev: before,
1160            next: None,
1161            first,
1162            last: first.and(level_last),
1163        })?;
1164
1165        self.sibling = Some(new_id);
1166        Ok(new_id)
1167    }
1168
1169    /// Build a [Tree] from the current state of the builder.
1170    ///
1171    /// # Errors
1172    ///
1173    /// This requires the stack in the builder to be empty. Otherwise a
1174    /// [`Error::BuildError`] will be raised.
1175    ///
1176    /// # Examples
1177    ///
1178    /// ```
1179    /// let mut tree = syntree::Builder::new();
1180    ///
1181    /// tree.open("child")?;
1182    /// tree.token("number", 3)?;
1183    /// tree.close()?;
1184    /// tree.open("child")?;
1185    /// tree.close()?;
1186    ///
1187    /// let tree = tree.build()?;
1188    ///
1189    /// let expected = syntree::tree! {
1190    ///     "child" => {
1191    ///         ("number", 3)
1192    ///     },
1193    ///     "child" => {},
1194    /// };
1195    ///
1196    /// assert_eq!(tree, expected);
1197    /// # Ok::<_, Box<dyn core::error::Error>>(())
1198    /// ```
1199    ///
1200    /// If a tree is unbalanced during construction, building will fail with an error:
1201    ///
1202    /// ```
1203    /// use syntree::{Error, Span, Builder};
1204    ///
1205    /// let mut tree = syntree::Builder::new();
1206    ///
1207    /// tree.open("number")?;
1208    /// tree.token("lit", 3)?;
1209    /// tree.close()?;
1210    ///
1211    /// tree.open("number")?;
1212    ///
1213    /// // "number" is left open.
1214    /// assert!(matches!(tree.build(), Err(Error::BuildError)));
1215    /// # Ok::<_, Box<dyn core::error::Error>>(())
1216    /// ```
1217    pub fn build(self) -> Result<Tree<T, F>, Error<F::Error>> {
1218        if self.parent.is_some() {
1219            return Err(Error::BuildError);
1220        }
1221
1222        Ok(self.tree)
1223    }
1224
1225    /// Insert a new node.
1226    fn insert(&mut self, data: T, span: Span<F::Index>) -> Result<F::Pointer, Error<F::Error>> {
1227        let new = self.next_node_id()?;
1228        let tok = F::Pointer::new(self.tree.tokens().len()).ok_or(Error::Overflow)?;
1229
1230        let prev = self.sibling;
1231
1232        self.tree.push_node(NodeLinks {
1233            data: Cell::new(data),
1234            span,
1235            tok_start: tok,
1236            tok_end: tok,
1237            parent: self.parent,
1238            prev,
1239            next: None,
1240            first: None,
1241            last: None,
1242        })?;
1243
1244        self.sibling = None;
1245
1246        if let Some(id) = self.parent {
1247            if let Some(node) = self.tree.node_links_mut(id) {
1248                if node.first.is_none() {
1249                    node.first = Some(new);
1250                }
1251
1252                node.last = Some(new);
1253                node.span = node.span.join(&span);
1254            }
1255        } else {
1256            let (first, last) = self.tree.links_mut();
1257
1258            if first.is_none() {
1259                *first = Some(new);
1260            }
1261
1262            *last = Some(new);
1263        }
1264
1265        if let Some(node) = prev.and_then(|id| self.tree.node_links_mut(id)) {
1266            node.next = Some(new);
1267        }
1268
1269        self.join_tree_span(&span);
1270        Ok(new)
1271    }
1272
1273    /// The start of the token at level `parent` which follows the position
1274    /// before token entry `tok`, as `Tree::next_at` finds it when no interior
1275    /// node comes first. `None` if there is no such token at the level.
1276    fn token_start_at(&self, parent: Option<F::Pointer>, tok: usize) -> Option<F::Index> {
1277        let tokens = self.tree.tokens();
1278        let mut links = tokens.get(tok)?;
1279        let mut start = None;
1280
1281        // A gap entry is always directly followed by its token, and ends
1282        // where that token starts.
1283        if links.is_gap() {
1284            start = Some(links.end);
1285            links = tokens.get(tok.checked_add(1)?)?;
1286        }
1287
1288        if links.parent() != parent {
1289            return None;
1290        }
1291
1292        Some(match start {
1293            Some(start) => start,
1294            None => self.tree.token_start(tok),
1295        })
1296    }
1297
1298    /// The end of the element at level `parent` which precedes the position
1299    /// before token entry `tok`, where `last` is the last interior node at the
1300    /// level. Mirrors `Tree::prev_at` followed by `Tree::span_of`.
1301    fn wrapped_end(
1302        &self,
1303        parent: Option<F::Pointer>,
1304        tok: usize,
1305        last: Option<F::Pointer>,
1306    ) -> Option<F::Index> {
1307        let tokens = self.tree.tokens();
1308        let mut tok = tok;
1309
1310        // A position right after a gap entry is the same as the one before it.
1311        if let Some(index) = tok.checked_sub(1) {
1312            if tokens.get(index).is_some_and(|links| links.is_gap()) {
1313                tok = index;
1314            }
1315        }
1316
1317        if let Some(id) = last {
1318            let links = self.tree.node_links(id)?;
1319
1320            if links.tok_end.get() >= tok {
1321                return Some(links.span.end);
1322            }
1323        }
1324
1325        let links = tokens.get(tok.checked_sub(1)?)?;
1326
1327        if links.is_gap() || links.parent() != parent {
1328            return None;
1329        }
1330
1331        Some(links.end)
1332    }
1333
1334    /// Move the tokens in `start..end` which belong to `from` to `to`. An
1335    /// empty or out of bounds range moves nothing.
1336    fn reparent_tokens(
1337        &mut self,
1338        start: usize,
1339        end: usize,
1340        from: Option<F::Pointer>,
1341        to: F::Pointer,
1342    ) {
1343        let Some(tokens) = self.tree.tokens_mut().get_mut(start..end) else {
1344            return;
1345        };
1346
1347        for links in tokens {
1348            if !links.is_gap() && links.parent() == from {
1349                links.set_parent(Some(to));
1350            }
1351        }
1352    }
1353
1354    /// The id of the next interior node. Node ids leave the top bit of a
1355    /// pointer clear, since tokens store their trivia flag there.
1356    fn next_node_id(&self) -> Result<F::Pointer, Error<F::Error>> {
1357        match F::Pointer::new(self.tree.nodes().len()) {
1358            Some(id) if id.is_node_id() => Ok(id),
1359            _ => Err(Error::Overflow),
1360        }
1361    }
1362
1363    /// Insert a token, preceded by a gap entry if it doesn't start where the
1364    /// previous token ends.
1365    fn insert_token(
1366        &mut self,
1367        data: T,
1368        span: Span<F::Index>,
1369        trivia: bool,
1370    ) -> Result<F::Pointer, Error<F::Error>> {
1371        let prev_end = self.tree.tokens_end();
1372
1373        if span.start < prev_end || span.end < span.start {
1374            return Err(Error::TokenOrder);
1375        }
1376
1377        let gap = span.start > prev_end;
1378
1379        let mut index = self.tree.tokens().len();
1380
1381        if gap {
1382            index = index.checked_add(1).ok_or(Error::Overflow)?;
1383        }
1384
1385        let id = F::Pointer::new(index).ok_or(Error::Overflow)?;
1386
1387        // The number of tokens must itself fit in a pointer, since it is the
1388        // end of the token range of the enclosing nodes.
1389        let end = index.checked_add(1).ok_or(Error::Overflow)?;
1390        F::Pointer::new(end).ok_or(Error::Overflow)?;
1391
1392        if gap {
1393            self.tree.push_token(TokenLinks::gap(data, span.start))?;
1394        }
1395
1396        self.tree
1397            .push_token(TokenLinks::token(data, span.end, self.parent, trivia))?;
1398
1399        if let Some(node) = self.parent.and_then(|id| self.tree.node_links_mut(id)) {
1400            node.span = node.span.join(&span);
1401        }
1402
1403        self.join_tree_span(&span);
1404        self.cursor = span.end;
1405        Ok(id)
1406    }
1407
1408    /// Extend the span of the whole tree to cover `span`. Empty spans are
1409    /// ignored, like they are when indexing tokens.
1410    fn join_tree_span(&mut self, span: &Span<F::Index>) {
1411        if !span.is_empty() {
1412            let tree = self.tree.span_mut();
1413            *tree = tree.join(span);
1414        }
1415    }
1416}
1417
1418impl<T, F> Clone for Builder<T, F>
1419where
1420    T: Copy,
1421    F: Flavor,
1422    F::Storage<NodeLinks<T, F::Index, F::Pointer>>: Clone,
1423    F::Storage<TokenLinks<T, F::Index, F::Pointer>>: Clone,
1424    F::Storage<Inner<F::Pointer>>: Clone,
1425{
1426    #[inline]
1427    fn clone(&self) -> Self {
1428        Self {
1429            tree: self.tree.clone(),
1430            parent: self.parent,
1431            checkpoints: self.checkpoints.clone(),
1432            sibling: self.sibling,
1433            cursor: self.cursor,
1434        }
1435    }
1436}
1437
1438impl<T, F> fmt::Debug for Builder<T, F>
1439where
1440    T: Copy + fmt::Debug,
1441    F: Flavor<Index: fmt::Debug>,
1442{
1443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1444        f.debug_struct("Builder")
1445            .field("tree", &self.tree)
1446            .field("checkpoints", &&*self.checkpoints)
1447            .field("parent", &self.parent)
1448            .field("sibling", &self.sibling)
1449            .field("cursor", &self.cursor)
1450            .finish()
1451    }
1452}
1453
1454impl<T, F> Default for Builder<T, F>
1455where
1456    T: Copy,
1457    F: Flavor,
1458{
1459    #[inline]
1460    fn default() -> Self {
1461        Self::new_with()
1462    }
1463}