syntree/node/token.rs
1use core::fmt;
2use core::ops::Range;
3
4use crate::flavor::Flavor;
5use crate::links::TokenLinks;
6use crate::node::{Ancestors, Element, Event, Id, Node, NodeOrToken, Siblings, Walk, WalkEvents};
7use crate::pointer::Pointer;
8use crate::span::Span;
9use crate::tree::Tree;
10
11/// A token in the tree, one which was added with
12/// [`Builder::token`][crate::Builder::token] or its variants.
13///
14/// Tokens have no children.
15pub struct Token<'a, T, F>
16where
17 T: Copy,
18 F: Flavor,
19{
20 tree: &'a Tree<T, F>,
21 links: &'a TokenLinks<T, F::Index, F::Pointer>,
22 id: F::Pointer,
23}
24
25impl<'a, T, F> Token<'a, T, F>
26where
27 T: Copy,
28 F: Flavor,
29{
30 /// Construct a handle to the token with the given id. Gap entries are not
31 /// tokens.
32 pub(crate) fn new(tree: &'a Tree<T, F>, id: F::Pointer) -> Option<Self> {
33 let links = tree.tokens().get(id.get())?;
34
35 if links.is_gap() {
36 return None;
37 }
38
39 Some(Self { tree, links, id })
40 }
41
42 /// Construct a handle from links already looked up for `id`, which must
43 /// not be a gap entry.
44 #[inline]
45 pub(crate) const fn from_links(
46 tree: &'a Tree<T, F>,
47 links: &'a TokenLinks<T, F::Index, F::Pointer>,
48 id: F::Pointer,
49 ) -> Self {
50 Self { tree, links, id }
51 }
52
53 /// Access the data associated with the token.
54 #[must_use]
55 pub fn value(&self) -> T {
56 self.links.data.get()
57 }
58
59 /// Replace the value of the token with a new one, returning the old
60 /// value.
61 pub fn replace(&self, value: T) -> T {
62 self.links.data.replace(value)
63 }
64
65 /// Get the identifier of the token, see [`Tree::token`].
66 ///
67 /// Token ids index the token array of the tree and are separate from
68 /// [node ids][Node::id]. They are not dense: an explicit span which leaves
69 /// a gap after the previous token takes an internal id for the gap.
70 #[must_use]
71 pub fn id(&self) -> F::Pointer {
72 self.id
73 }
74
75 /// Test if this is a trivia token, inserted with [`Builder::trivia`] or
76 /// [`Builder::trivia_with`]. Iterators skip trivia unless asked to
77 /// include it with `with_trivia()`.
78 ///
79 /// [`Builder::trivia`]: crate::Builder::trivia
80 /// [`Builder::trivia_with`]: crate::Builder::trivia_with
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// let mut tree = syntree::Builder::new();
86 /// tree.token("ident", 3)?;
87 /// tree.trivia("whitespace", 1)?;
88 /// let tree = tree.build()?;
89 ///
90 /// let ident = tree.first().and_then(|e| e.into_token()).ok_or("missing ident")?;
91 /// let ws = tree.last().and_then(|e| e.into_token()).ok_or("missing whitespace")?;
92 ///
93 /// assert!(!ident.is_trivia());
94 /// assert!(ws.is_trivia());
95 /// # Ok::<_, Box<dyn core::error::Error>>(())
96 /// ```
97 #[must_use]
98 pub fn is_trivia(&self) -> bool {
99 self.links.is_trivia()
100 }
101
102 /// Get the span of the token.
103 #[must_use]
104 pub fn span(&self) -> Span<F::Index> {
105 Span::new(self.tree.token_start(self.id.get()), self.links.end)
106 }
107
108 /// Access the [Span] of the token as a [Range].
109 #[must_use]
110 #[inline]
111 pub fn range(&self) -> Range<usize> {
112 self.span().range()
113 }
114
115 /// Get the parent node, `None` at the root of the tree.
116 #[must_use]
117 pub fn parent(&self) -> Option<Node<'a, T, F>> {
118 Node::new(self.tree, self.links.parent()?)
119 }
120
121 /// Get the previous sibling, a node or a token.
122 ///
123 /// This is linear in the number of interior nodes which are siblings of
124 /// the token. Iterators such as [`Node::children`] step in constant time.
125 #[must_use]
126 pub fn prev(&self) -> Option<Element<'a, T, F>> {
127 let index = self.id.get();
128 let (prev, _) = self.tree.nodes_around(self.links.parent(), index);
129 let id = self.tree.prev_at(self.links.parent(), index, prev)?;
130 self.tree.element(id)
131 }
132
133 /// Get the next sibling, a node or a token.
134 ///
135 /// This is linear in the number of interior nodes which are siblings of
136 /// the token. Iterators such as [`Node::children`] step in constant time.
137 #[must_use]
138 pub fn next(&self) -> Option<Element<'a, T, F>> {
139 let index = self.id.get();
140 let (_, next) = self.tree.nodes_around(self.links.parent(), index);
141 let id = self
142 .tree
143 .next_at(self.links.parent(), index.checked_add(1)?, next)?;
144 self.tree.element(id)
145 }
146
147 /// The next interior node at the level of the token.
148 ///
149 /// This walks the chain of interior nodes at the level.
150 fn next_node(&self) -> Option<F::Pointer> {
151 self.tree.nodes_around(self.links.parent(), self.id.get()).1
152 }
153
154 /// Get an iterator over this token and its ancestors, starting with the
155 /// token itself and ending with its root.
156 ///
157 /// See [Ancestors] for documentation.
158 #[must_use]
159 pub fn ancestors(&self) -> Ancestors<'a, T, F> {
160 Ancestors::new(Some(NodeOrToken::Token(*self)))
161 }
162
163 /// Get an iterator over this token and its following siblings, nodes and
164 /// tokens.
165 ///
166 /// Constructing it is linear in the number of interior nodes which are
167 /// siblings of the token, stepping it is constant.
168 ///
169 /// See [Siblings] for documentation.
170 #[must_use]
171 pub fn siblings(&self) -> Siblings<'a, T, F> {
172 Siblings::new(
173 self.tree,
174 self.links.parent(),
175 Id::Token(self.id),
176 self.next_node(),
177 )
178 }
179
180 /// Walk the tree forward in depth-first order starting with this token,
181 /// then continue with what follows it in the tree.
182 ///
183 /// Constructing it is linear in the number of interior nodes which are
184 /// siblings of the token.
185 ///
186 /// See [Walk] for documentation.
187 #[must_use]
188 pub fn walk(&self) -> Walk<'a, T, F> {
189 Walk::new(
190 self.tree,
191 Some(Id::Token(self.id)),
192 self.next_node(),
193 Event::Next,
194 )
195 }
196
197 /// Walk from this token forwards and upwards through the tree, not
198 /// including the token itself.
199 ///
200 /// See [Walk] for documentation.
201 #[must_use]
202 pub fn walk_from(&self) -> Walk<'a, T, F> {
203 Walk::new(
204 self.tree,
205 Some(Id::Token(self.id)),
206 self.next_node(),
207 Event::Up,
208 )
209 }
210
211 /// Walk forward from this token, emitting events indicating how the rest
212 /// of the tree is being traversed.
213 ///
214 /// See [`WalkEvents`] for documentation.
215 #[must_use]
216 pub fn walk_events(&self) -> WalkEvents<'a, T, F> {
217 WalkEvents::new(
218 self.tree,
219 Some(Id::Token(self.id)),
220 self.next_node(),
221 Event::Next,
222 )
223 }
224
225 /// Find a preceding element which matches the given predicate.
226 ///
227 /// See [`Element::find_preceding`].
228 pub fn find_preceding<P>(&self, predicate: P) -> Option<Element<'a, T, F>>
229 where
230 P: FnMut(Element<'a, T, F>) -> bool,
231 {
232 NodeOrToken::Token(*self).find_preceding(predicate)
233 }
234}
235
236impl<T, F> fmt::Debug for Token<'_, T, F>
237where
238 T: Copy + fmt::Debug,
239 F: Flavor<Index: fmt::Debug>,
240{
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 let mut s = f.debug_struct("Token");
243 s.field("data", &self.links.data.get());
244 s.field("span", &self.span());
245
246 // Only shown when set, to keep the common case short.
247 if self.is_trivia() {
248 s.field("trivia", &true);
249 }
250
251 s.finish()
252 }
253}
254
255impl<T, F> Clone for Token<'_, T, F>
256where
257 T: Copy,
258 F: Flavor,
259{
260 #[inline]
261 fn clone(&self) -> Self {
262 *self
263 }
264}
265
266impl<T, F> Copy for Token<'_, T, F>
267where
268 T: Copy,
269 F: Flavor,
270{
271}
272
273impl<T, A, B> PartialEq<Token<'_, T, A>> for Token<'_, T, B>
274where
275 T: Copy + PartialEq,
276 A: Flavor,
277 B: Flavor<Index: PartialEq<A::Index>>,
278{
279 fn eq(&self, other: &Token<'_, T, A>) -> bool {
280 self.links.data.get() == other.links.data.get()
281 && self.is_trivia() == other.is_trivia()
282 && self.span() == other.span()
283 }
284}
285
286impl<T, F> Eq for Token<'_, T, F>
287where
288 T: Copy + Eq,
289 F: Flavor<Index: Eq>,
290{
291}