syntree/node/element.rs
1use core::fmt;
2use core::ops::Range;
3
4use crate::flavor::Flavor;
5use crate::node::{Ancestors, Children, Node, Siblings, Token, Walk, WalkEvents};
6use crate::span::Span;
7
8/// Either a node or a token.
9///
10/// Iterators which visit both nodes and tokens yield the [`Element`] instance
11/// of this. Its [`Debug`][fmt::Debug] output is that of the node or token it
12/// holds.
13#[derive(Clone, Copy, Hash)]
14pub enum NodeOrToken<N, K> {
15 /// An interior node.
16 Node(N),
17 /// A token.
18 Token(K),
19}
20
21/// A node or a token in a tree.
22///
23/// This is what [`Tree::first`][crate::Tree::first], [`Node::first`],
24/// [`Children`], [`Walk`] and the other mixed iterators yield. It has the
25/// navigation methods of a [`Node`], answering as an empty leaf when it is a
26/// token, so code like `tree.first()?.children()` works without first
27/// checking what the element is. Use [`into_node`][NodeOrToken::into_node] or
28/// [`into_token`][NodeOrToken::into_token] for what only one of them has,
29/// such as [`Node::id`] or [`Token::id`].
30///
31/// # Examples
32///
33/// ```
34/// let tree = syntree::tree! {
35/// "root" => {
36/// ("lit", 3),
37/// "child" => {
38/// ("ws", 1)
39/// }
40/// }
41/// };
42///
43/// let root = tree.first().ok_or("missing root")?;
44/// let values = root.children().map(|e| e.value()).collect::<Vec<_>>();
45/// assert_eq!(values, ["lit", "child"]);
46///
47/// let lit = root.first().ok_or("missing lit")?;
48/// assert!(lit.is_token());
49/// assert_eq!(lit.children().count(), 0);
50///
51/// let child = lit.next().and_then(|e| e.into_node()).ok_or("missing child")?;
52/// assert_eq!(tree.get(child.id()), Some(child));
53/// # Ok::<_, Box<dyn core::error::Error>>(())
54/// ```
55pub type Element<'a, T, F> = NodeOrToken<Node<'a, T, F>, Token<'a, T, F>>;
56
57/// The id of an element, internally.
58pub(crate) type Id<P> = NodeOrToken<P, P>;
59
60impl<N, K> NodeOrToken<N, K> {
61 /// Get the node, if this is one.
62 #[inline]
63 pub fn into_node(self) -> Option<N> {
64 match self {
65 NodeOrToken::Node(n) => Some(n),
66 NodeOrToken::Token(..) => None,
67 }
68 }
69
70 /// Get the token, if this is one.
71 #[inline]
72 pub fn into_token(self) -> Option<K> {
73 match self {
74 NodeOrToken::Node(..) => None,
75 NodeOrToken::Token(t) => Some(t),
76 }
77 }
78
79 /// Get a reference to the node, if this is one.
80 #[inline]
81 pub const fn as_node(&self) -> Option<&N> {
82 match self {
83 NodeOrToken::Node(n) => Some(n),
84 NodeOrToken::Token(..) => None,
85 }
86 }
87
88 /// Get a reference to the token, if this is one.
89 #[inline]
90 pub const fn as_token(&self) -> Option<&K> {
91 match self {
92 NodeOrToken::Node(..) => None,
93 NodeOrToken::Token(t) => Some(t),
94 }
95 }
96
97 /// Test if this is a node.
98 #[inline]
99 pub const fn is_node(&self) -> bool {
100 matches!(self, NodeOrToken::Node(..))
101 }
102
103 /// Test if this is a token.
104 #[inline]
105 pub const fn is_token(&self) -> bool {
106 matches!(self, NodeOrToken::Token(..))
107 }
108}
109
110impl<'a, T, F> NodeOrToken<Node<'a, T, F>, Token<'a, T, F>>
111where
112 T: Copy,
113 F: Flavor,
114{
115 /// Access the data associated with the element.
116 #[must_use]
117 pub fn value(&self) -> T {
118 match self {
119 NodeOrToken::Node(n) => n.value(),
120 NodeOrToken::Token(t) => t.value(),
121 }
122 }
123
124 /// Replace the value of the element with a new one, returning the old
125 /// value.
126 pub fn replace(&self, value: T) -> T {
127 match self {
128 NodeOrToken::Node(n) => n.replace(value),
129 NodeOrToken::Token(t) => t.replace(value),
130 }
131 }
132
133 /// Get the span of the element.
134 #[must_use]
135 pub fn span(&self) -> Span<F::Index> {
136 match self {
137 NodeOrToken::Node(n) => *n.span(),
138 NodeOrToken::Token(t) => t.span(),
139 }
140 }
141
142 /// Access the [Span] of the element as a [Range].
143 #[must_use]
144 pub fn range(&self) -> Range<usize> {
145 self.span().range()
146 }
147
148 /// Get the parent node, `None` at the root of the tree.
149 #[must_use]
150 pub fn parent(&self) -> Option<Node<'a, T, F>> {
151 match self {
152 NodeOrToken::Node(n) => n.parent(),
153 NodeOrToken::Token(t) => t.parent(),
154 }
155 }
156
157 /// Get the previous sibling.
158 #[must_use]
159 pub fn prev(&self) -> Option<Element<'a, T, F>> {
160 match self {
161 NodeOrToken::Node(n) => n.prev(),
162 NodeOrToken::Token(t) => t.prev(),
163 }
164 }
165
166 /// Get the next sibling.
167 #[must_use]
168 pub fn next(&self) -> Option<Element<'a, T, F>> {
169 match self {
170 NodeOrToken::Node(n) => n.next(),
171 NodeOrToken::Token(t) => t.next(),
172 }
173 }
174
175 /// Test if the element is a trivia token, see [`Token::is_trivia`]. A
176 /// node is never trivia.
177 #[must_use]
178 pub fn is_trivia(&self) -> bool {
179 match self {
180 NodeOrToken::Node(..) => false,
181 NodeOrToken::Token(t) => t.is_trivia(),
182 }
183 }
184
185 /// Check if the element has children, which a token never has.
186 #[must_use]
187 pub fn has_children(&self) -> bool {
188 match self {
189 NodeOrToken::Node(n) => n.has_children(),
190 NodeOrToken::Token(..) => false,
191 }
192 }
193
194 /// Get the first child, `None` for a token. See [`Node::first`].
195 #[must_use]
196 pub fn first(&self) -> Option<Element<'a, T, F>> {
197 self.as_node()?.first()
198 }
199
200 /// Get the last child, `None` for a token. See [`Node::last`].
201 #[must_use]
202 pub fn last(&self) -> Option<Element<'a, T, F>> {
203 self.as_node()?.last()
204 }
205
206 /// Iterate over the children of the element, which is empty for a token.
207 /// See [`Node::children`].
208 #[must_use]
209 pub fn children(&self) -> Children<'a, T, F> {
210 match self {
211 NodeOrToken::Node(n) => n.children(),
212 NodeOrToken::Token(..) => Children::default(),
213 }
214 }
215
216 /// Get an iterator over this element and its ancestors. See
217 /// [`Node::ancestors`].
218 #[must_use]
219 pub fn ancestors(&self) -> Ancestors<'a, T, F> {
220 Ancestors::new(Some(*self))
221 }
222
223 /// Get an iterator over this element and its following siblings. See
224 /// [`Node::siblings`].
225 #[must_use]
226 pub fn siblings(&self) -> Siblings<'a, T, F> {
227 match self {
228 NodeOrToken::Node(n) => n.siblings(),
229 NodeOrToken::Token(t) => t.siblings(),
230 }
231 }
232
233 /// Walk the tree forward in depth-first order starting with this element.
234 /// See [`Node::walk`].
235 #[must_use]
236 pub fn walk(&self) -> Walk<'a, T, F> {
237 match self {
238 NodeOrToken::Node(n) => n.walk(),
239 NodeOrToken::Token(t) => t.walk(),
240 }
241 }
242
243 /// Walk forwards and upwards from this element, not including it or its
244 /// descendants. See [`Node::walk_from`].
245 #[must_use]
246 pub fn walk_from(&self) -> Walk<'a, T, F> {
247 match self {
248 NodeOrToken::Node(n) => n.walk_from(),
249 NodeOrToken::Token(t) => t.walk_from(),
250 }
251 }
252
253 /// Walk forward from this element emitting events. See
254 /// [`Node::walk_events`].
255 #[must_use]
256 pub fn walk_events(&self) -> WalkEvents<'a, T, F> {
257 match self {
258 NodeOrToken::Node(n) => n.walk_events(),
259 NodeOrToken::Token(t) => t.walk_events(),
260 }
261 }
262
263 /// Find a preceding element which matches the given predicate.
264 ///
265 /// A "preceding element" is one whose tokens immediately precede the
266 /// tokens of the current element. This is found in two steps:
267 ///
268 /// 1. Starting with the current element and moving through its ancestors,
269 /// find the first [`prev`][Self::prev] sibling which matches the
270 /// predicate.
271 /// 2. From that sibling, descend through [`last`][Self::last] children for
272 /// as long as each matches the predicate, and return the last match.
273 ///
274 /// Step 2 stops at the first last child which does not match, so a
275 /// matching element nested below a non-matching last child is not found.
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// let tree = syntree::tree! {
281 /// "root" => {
282 /// "child1" => {
283 /// ("token2", 1),
284 /// "child2" => {
285 /// ("token1", 2)
286 /// }
287 /// },
288 /// "child3" => {
289 /// "child4" => {
290 /// ("token1", 4),
291 /// }
292 /// }
293 /// }
294 /// };
295 ///
296 /// let node = tree.node_with_range(3..3).ok_or("missing 3")?;
297 /// assert_eq!(node.value(), "token1");
298 ///
299 /// let found = node.find_preceding(|n| n.span().end == 3 && n.has_children());
300 /// let found = found.ok_or("expected preceding node")?;
301 /// assert_eq!(found.value(), "child2");
302 /// # Ok::<_, Box<dyn core::error::Error>>(())
303 /// ```
304 pub fn find_preceding<P>(&self, mut predicate: P) -> Option<Element<'a, T, F>>
305 where
306 P: FnMut(Element<'a, T, F>) -> bool,
307 {
308 let mut n = *self;
309
310 let mut n = loop {
311 if let Some(prev) = n.prev() {
312 if predicate(prev) {
313 break prev;
314 }
315 }
316
317 n = NodeOrToken::Node(n.parent()?);
318 };
319
320 loop {
321 let Some(last) = n.last() else {
322 return Some(n);
323 };
324
325 if !predicate(last) {
326 return Some(n);
327 }
328
329 n = last;
330 }
331 }
332}
333
334impl<N, K> fmt::Debug for NodeOrToken<N, K>
335where
336 N: fmt::Debug,
337 K: fmt::Debug,
338{
339 #[inline]
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 match self {
342 NodeOrToken::Node(n) => n.fmt(f),
343 NodeOrToken::Token(t) => t.fmt(f),
344 }
345 }
346}
347
348impl<A, B, C, D> PartialEq<NodeOrToken<C, D>> for NodeOrToken<A, B>
349where
350 A: PartialEq<C>,
351 B: PartialEq<D>,
352{
353 #[inline]
354 fn eq(&self, other: &NodeOrToken<C, D>) -> bool {
355 match (self, other) {
356 (NodeOrToken::Node(a), NodeOrToken::Node(b)) => a == b,
357 (NodeOrToken::Token(a), NodeOrToken::Token(b)) => a == b,
358 _ => false,
359 }
360 }
361}
362
363impl<N, K> Eq for NodeOrToken<N, K>
364where
365 N: Eq,
366 K: Eq,
367{
368}