syntree/builder/checkpoint.rs
1use core::fmt;
2use core::marker::PhantomData;
3
4/// A checkpoint as returned by [`Builder::checkpoint`], used to wrap
5/// everything added since it was taken with [`Builder::close_at`].
6///
7/// A checkpoint is a `Copy` index into the builder that handed it out, and the
8/// builder holds its state. Closing it moves it onto the new wrapping node, so
9/// closing it again wraps the wrapper.
10///
11/// # Checkpoints and cloned builders
12///
13/// A cloned [`Builder`] clones the state of every checkpoint, so a checkpoint
14/// taken before cloning can be used on both and moves independently in each.
15///
16/// ```
17/// let mut a = syntree::Builder::new();
18/// let c = a.checkpoint()?;
19///
20/// let mut b = a.clone();
21/// b.token("lit", 1)?;
22/// b.close_at(c, "speculative")?;
23///
24/// a.token("lit", 1)?;
25/// a.close_at(c, "root")?;
26///
27/// assert_eq!(a.build()?, syntree::tree! { "root" => { ("lit", 1) } });
28/// assert_eq!(b.build()?, syntree::tree! { "speculative" => { ("lit", 1) } });
29/// # Ok::<_, Box<dyn core::error::Error>>(())
30/// ```
31///
32/// [`Builder`]: crate::Builder
33/// [`Builder::close_at`]: crate::Builder::close_at
34/// [`Builder::checkpoint`]: crate::Builder::checkpoint
35#[repr(transparent)]
36pub struct Checkpoint<P> {
37 index: usize,
38 _marker: PhantomData<fn() -> P>,
39}
40
41impl<P> Checkpoint<P> {
42 #[inline]
43 pub(crate) const fn new(index: usize) -> Self {
44 Self {
45 index,
46 _marker: PhantomData,
47 }
48 }
49
50 #[inline]
51 pub(crate) const fn index(self) -> usize {
52 self.index
53 }
54}
55
56impl<P> Clone for Checkpoint<P> {
57 #[inline]
58 fn clone(&self) -> Self {
59 *self
60 }
61}
62
63impl<P> Copy for Checkpoint<P> {}
64
65impl<P> PartialEq for Checkpoint<P> {
66 #[inline]
67 fn eq(&self, other: &Self) -> bool {
68 self.index == other.index
69 }
70}
71
72impl<P> Eq for Checkpoint<P> {}
73
74impl<P> fmt::Debug for Checkpoint<P> {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.debug_tuple("Checkpoint").field(&self.index).finish()
77 }
78}
79
80/// The state of a checkpoint, stored in the builder.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub(crate) struct Inner<P> {
83 /// The number of token entries when the checkpoint was taken.
84 pub(crate) tok: usize,
85 /// The last interior node at the level when the checkpoint was taken.
86 pub(crate) before: Option<P>,
87 /// The node being built when the checkpoint was taken.
88 pub(crate) parent: Option<P>,
89}