syntree/node/node_impl.rs
1use core::fmt;
2use core::ops::Range;
3
4use crate::flavor::Flavor;
5use crate::links::NodeLinks;
6use crate::node::{
7 Ancestors, Children, Element, Event, Id, NodeOrToken, Siblings, Walk, WalkEvents,
8};
9use crate::pointer::Pointer;
10use crate::span::Span;
11use crate::tree::Tree;
12
13/// An interior node in the tree, one which was opened with
14/// [`Builder::open`][crate::Builder::open] or wrapped with
15/// [`Builder::close_at`][crate::Builder::close_at].
16///
17/// Tokens are [`Token`][crate::node::Token]s, and an iterator which mixes both
18/// yields [`Element`]s. An [`Element`] has most of the methods of a node, so a
19/// child can usually be used without first checking what it is.
20///
21/// # Type parameters and bounds
22///
23/// The two type parameters of the tree determine the following properties:
24/// * `T` is the data stored in the tree.
25/// * `F` determines the [Flavor] of the tree, defining numerical bounds of
26/// spans and node identifiers stored in the tree.
27///
28/// A tree built through [Builder::new][crate::Builder::new] uses
29/// [`FlavorDefault`][crate::FlavorDefault].
30pub struct Node<'a, T, F>
31where
32 T: Copy,
33 F: Flavor,
34{
35 tree: &'a Tree<T, F>,
36 links: &'a NodeLinks<T, F::Index, F::Pointer>,
37 id: F::Pointer,
38}
39
40impl<'a, T, F> Node<'a, T, F>
41where
42 T: Copy,
43 F: Flavor,
44{
45 /// Construct a handle to the node with the given id.
46 pub(crate) fn new(tree: &'a Tree<T, F>, id: F::Pointer) -> Option<Self> {
47 let links = tree.node_links(id)?;
48 Some(Self { tree, links, id })
49 }
50
51 /// Construct a handle from links already looked up for `id`.
52 #[inline]
53 pub(crate) const fn from_links(
54 tree: &'a Tree<T, F>,
55 links: &'a NodeLinks<T, F::Index, F::Pointer>,
56 id: F::Pointer,
57 ) -> Self {
58 Self { tree, links, id }
59 }
60
61 /// Access the data associated with the node.
62 ///
63 /// # Examples
64 ///
65 /// ```
66 /// let tree = syntree::tree! {
67 /// "root" => {
68 /// ("number", 5),
69 /// ("ident", 3),
70 /// }
71 /// };
72 ///
73 /// let root = tree.first().and_then(|e| e.into_node()).ok_or("missing root")?;
74 /// assert_eq!(root.value(), "root");
75 ///
76 /// let number = root.first().ok_or("missing number")?;
77 /// assert_eq!(number.value(), "number");
78 ///
79 /// let ident = number.next().ok_or("missing ident")?;
80 /// assert_eq!(ident.value(), "ident");
81 /// # Ok::<_, Box<dyn core::error::Error>>(())
82 /// ```
83 #[must_use]
84 pub fn value(&self) -> T {
85 self.links.data.get()
86 }
87
88 /// Replace the value of the node with a new one, returning the old value.
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// let tree = syntree::tree! {
94 /// "root" => {
95 /// "number" => {},
96 /// ("ident", 3),
97 /// }
98 /// };
99 ///
100 /// let root = tree.first().and_then(|e| e.into_node()).ok_or("missing root")?;
101 /// assert_eq!(root.value(), "root");
102 ///
103 /// let number = root.first().and_then(|e| e.into_node()).ok_or("missing number")?;
104 /// assert_eq!(number.value(), "number");
105 /// assert_eq!(number.replace("other"), "number");
106 /// assert_eq!(number.value(), "other");
107 ///
108 /// let ident = number.next().ok_or("missing ident")?;
109 /// assert_eq!(ident.value(), "ident");
110 /// # Ok::<_, Box<dyn core::error::Error>>(())
111 /// ```
112 pub fn replace(&self, value: T) -> T {
113 self.links.data.replace(value)
114 }
115
116 /// Get the identifier of the node.
117 ///
118 /// Node ids index the interior nodes of the tree and are separate from
119 /// [token ids][crate::Token::id], so a node and a token can share an id.
120 /// Use [`Tree::get`] to get the node back. An id might be re-used across
121 /// different trees. This behavior is never unsafe, but is not
122 /// well-defined.
123 ///
124 /// This can be used to register a change in a [`ChangeSet`] later.
125 ///
126 /// ```
127 /// let mut tree = syntree::Builder::new();
128 /// let root_id = tree.open("root")?;
129 /// let child_id = tree.open("child")?;
130 /// tree.close()?;
131 ///
132 /// let child2_id = tree.open("child2")?;
133 /// tree.close()?;
134 /// tree.close()?;
135 ///
136 /// let tree = tree.build()?;
137 /// let root = tree.first().and_then(|e| e.into_node()).ok_or("missing root")?;
138 /// let child = root.first().and_then(|e| e.into_node()).ok_or("missing child")?;
139 /// let child2 = child.next().and_then(|e| e.into_node()).ok_or("missing child2")?;
140 ///
141 /// assert_eq!(root.id(), root_id);
142 /// assert_eq!(child.id(), child_id);
143 /// assert_eq!(child2.id(), child2_id);
144 /// # Ok::<_, Box<dyn core::error::Error>>(())
145 /// ```
146 ///
147 /// [`Tree::get`]: crate::Tree::get
148 /// [`ChangeSet`]: crate::edit::ChangeSet
149 #[must_use]
150 pub fn id(&self) -> F::Pointer {
151 self.id
152 }
153
154 /// Get the span of the node. The span of a node is the complete span of
155 /// all its children.
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// use syntree::Span;
161 ///
162 /// let tree = syntree::tree! {
163 /// "root" => {
164 /// "number" => {
165 /// ("lit", 5)
166 /// },
167 /// "ident" => {
168 /// ("lit", 3)
169 /// }
170 /// },
171 /// "root2" => {
172 /// ("whitespace", 5)
173 /// }
174 /// };
175 ///
176 /// let root = tree.first().and_then(|e| e.into_node()).ok_or("missing root")?;
177 /// assert_eq!(*root.span(), Span::new(0, 8));
178 ///
179 /// let root2 = root.next().ok_or("missing second root")?;
180 /// assert_eq!(root2.span(), Span::new(8, 13));
181 /// # Ok::<_, Box<dyn core::error::Error>>(())
182 /// ```
183 #[must_use]
184 pub const fn span(&self) -> &Span<F::Index> {
185 &self.links.span
186 }
187
188 /// Access the [Span] of the node as a [Range].
189 ///
190 /// # Examples
191 ///
192 /// ```
193 /// let tree = syntree::tree! {
194 /// "root" => {
195 /// "number" => {
196 /// ("lit", 5)
197 /// },
198 /// "ident" => {
199 /// ("lit", 3)
200 /// }
201 /// },
202 /// "root2" => {
203 /// ("whitespace", 5)
204 /// }
205 /// };
206 ///
207 /// let root = tree.first().ok_or("missing root")?;
208 /// assert_eq!(root.range(), 0..8);
209 ///
210 /// let root2 = root.next().ok_or("missing second root")?;
211 /// assert_eq!(root2.range(), 8..13);
212 /// # Ok::<_, Box<dyn core::error::Error>>(())
213 /// ```
214 #[must_use]
215 #[inline]
216 pub fn range(&self) -> Range<usize> {
217 self.links.span.range()
218 }
219
220 /// Check if the node has children, tokens or nodes.
221 ///
222 /// # Examples
223 ///
224 /// ```
225 /// let tree = syntree::tree! {
226 /// "root" => {
227 /// ("number", 5),
228 /// ("ident", 3),
229 /// }
230 /// };
231 ///
232 /// let root = tree.first().ok_or("missing root")?;
233 /// assert!(root.has_children());
234 /// assert!(root.children().all(|n| !n.has_children()));
235 /// # Ok::<_, Box<dyn core::error::Error>>(())
236 /// ```
237 #[must_use]
238 pub fn has_children(&self) -> bool {
239 self.first().is_some()
240 }
241
242 /// Check if the node is empty, in that it has no children.
243 ///
244 /// # Examples
245 ///
246 /// ```
247 /// let mut tree = syntree::tree! {
248 /// "root" => {},
249 /// "root2" => {
250 /// ("token2", 5)
251 /// }
252 /// };
253 ///
254 /// let first = tree.first().and_then(|e| e.into_node()).ok_or("missing root")?;
255 /// let last = tree.last().and_then(|e| e.into_node()).ok_or("missing root2")?;
256 ///
257 /// assert!(first.is_empty());
258 /// assert!(!last.is_empty());
259 /// # Ok::<_, Box<dyn core::error::Error>>(())
260 /// ```
261 #[must_use]
262 pub fn is_empty(&self) -> bool {
263 !self.has_children()
264 }
265
266 /// Get the parent node, `None` at the root of the tree.
267 ///
268 /// # Examples
269 ///
270 /// ```
271 /// let tree = syntree::tree! {
272 /// "root" => {
273 /// "number" => {
274 /// ("lit", 5)
275 /// },
276 /// "ident" => {
277 /// ("lit", 3)
278 /// }
279 /// },
280 /// "root2" => {
281 /// ("whitespace", 5)
282 /// }
283 /// };
284 ///
285 /// let root = tree.first().ok_or("missing root")?;
286 /// assert_eq!(root.value(), "root");
287 /// assert!(root.parent().is_none());
288 ///
289 /// let number = root.first().ok_or("missing number")?;
290 /// assert_eq!(number.value(), "number");
291 ///
292 /// let root = number.parent().ok_or("missing parent")?;
293 /// assert_eq!(root.value(), "root");
294 /// # Ok::<_, Box<dyn core::error::Error>>(())
295 /// ```
296 #[must_use]
297 pub fn parent(&self) -> Option<Node<'a, T, F>> {
298 Node::new(self.tree, self.links.parent?)
299 }
300
301 /// Get the previous sibling, a node or a token.
302 ///
303 /// # Examples
304 ///
305 /// ```
306 /// let tree = syntree::tree! {
307 /// "root" => {
308 /// ("lit", 5),
309 /// "ident" => {
310 /// ("lit", 3)
311 /// }
312 /// }
313 /// };
314 ///
315 /// let ident = tree.first().and_then(|n| n.last()).ok_or("missing ident")?;
316 /// assert_eq!(ident.value(), "ident");
317 ///
318 /// let lit = ident.prev().ok_or("missing lit")?;
319 /// assert_eq!(lit.value(), "lit");
320 /// assert!(lit.is_token());
321 /// assert!(lit.prev().is_none());
322 /// # Ok::<_, Box<dyn core::error::Error>>(())
323 /// ```
324 #[must_use]
325 pub fn prev(&self) -> Option<Element<'a, T, F>> {
326 let id = self.tree.prev_at(
327 self.links.parent,
328 self.links.tok_start.get(),
329 self.links.prev,
330 )?;
331 self.tree.element(id)
332 }
333
334 /// Get the next sibling, a node or a token.
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// let tree = syntree::tree! {
340 /// "root" => {
341 /// "number" => {
342 /// ("lit", 5)
343 /// },
344 /// ("ident", 3)
345 /// }
346 /// };
347 ///
348 /// let root = tree.first().ok_or("missing root")?;
349 /// assert_eq!(root.value(), "root");
350 ///
351 /// let number = root.first().ok_or("missing number")?;
352 /// assert_eq!(number.value(), "number");
353 ///
354 /// let ident = number.next().ok_or("missing ident")?;
355 /// assert_eq!(ident.value(), "ident");
356 /// assert!(ident.is_token());
357 /// # Ok::<_, Box<dyn core::error::Error>>(())
358 /// ```
359 #[must_use]
360 pub fn next(&self) -> Option<Element<'a, T, F>> {
361 let id = self
362 .tree
363 .next_at(self.links.parent, self.links.tok_end.get(), self.links.next)?;
364 self.tree.element(id)
365 }
366
367 /// Get the first child, a node or a token.
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// let tree = syntree::tree! {
373 /// "root" => {
374 /// "number" => {
375 /// ("lit", 5)
376 /// },
377 /// "ident" => {
378 /// ("lit", 3)
379 /// }
380 /// },
381 /// "root2" => {
382 /// ("whitespace", 5)
383 /// }
384 /// };
385 ///
386 /// let root = tree.first().ok_or("missing root")?;
387 /// assert_eq!(root.value(), "root");
388 ///
389 /// let number = root.first().ok_or("missing number")?;
390 /// assert_eq!(number.value(), "number");
391 /// # Ok::<_, Box<dyn core::error::Error>>(())
392 /// ```
393 #[must_use]
394 pub fn first(&self) -> Option<Element<'a, T, F>> {
395 let id = self
396 .tree
397 .next_at(Some(self.id), self.links.tok_start.get(), self.links.first)?;
398 self.tree.element(id)
399 }
400
401 /// Get the last child, a node or a token.
402 ///
403 /// # Examples
404 ///
405 /// ```
406 /// let tree = syntree::tree! {
407 /// "root" => {
408 /// "number" => {
409 /// ("lit", 5)
410 /// },
411 /// "ident" => {
412 /// ("lit", 3)
413 /// }
414 /// },
415 /// "root2" => {
416 /// ("whitespace", 5)
417 /// }
418 /// };
419 ///
420 /// let root2 = tree.last().ok_or("missing root2")?;
421 /// assert_eq!(root2.value(), "root2");
422 ///
423 /// let whitespace = root2.last().ok_or("missing whitespace")?;
424 /// assert_eq!(whitespace.value(), "whitespace");
425 /// # Ok::<_, Box<dyn core::error::Error>>(())
426 /// ```
427 #[must_use]
428 pub fn last(&self) -> Option<Element<'a, T, F>> {
429 let id = self
430 .tree
431 .prev_at(Some(self.id), self.links.tok_end.get(), self.links.last)?;
432 self.tree.element(id)
433 }
434
435 /// Get an iterator over this node and its ancestors, starting with the
436 /// node itself and ending with its root.
437 ///
438 /// See [Ancestors] for documentation.
439 #[must_use]
440 pub fn ancestors(&self) -> Ancestors<'a, T, F> {
441 Ancestors::new(Some(NodeOrToken::Node(*self)))
442 }
443
444 /// Get an iterator over this node and its following siblings, nodes and
445 /// tokens.
446 ///
447 /// Previous siblings are not included.
448 ///
449 /// See [Siblings] for documentation.
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// let tree = syntree::tree! {
455 /// "root" => {
456 /// "a",
457 /// "b" => {},
458 /// "c",
459 /// "d",
460 /// }
461 /// };
462 ///
463 /// let b = tree.first().and_then(|n| n.first()).and_then(|n| n.next()).ok_or("missing b")?;
464 /// assert_eq!(b.value(), "b");
465 ///
466 /// assert_eq!(
467 /// b.siblings().map(|n| n.value()).collect::<Vec<_>>(),
468 /// ["b", "c", "d"]
469 /// );
470 /// # Ok::<_, Box<dyn core::error::Error>>(())
471 /// ```
472 #[must_use]
473 pub fn siblings(&self) -> Siblings<'a, T, F> {
474 Siblings::new(self.tree, self.links.parent, Id::Node(self.id), None)
475 }
476
477 /// Iterate over the children of the node, nodes and tokens in order.
478 ///
479 /// See [Children] for documentation.
480 #[must_use]
481 pub fn children(&self) -> Children<'a, T, F> {
482 Children::new(
483 self.tree,
484 Some(self.id),
485 (self.links.tok_start.get(), self.links.first),
486 (self.links.tok_end.get(), self.links.last),
487 )
488 }
489
490 /// Walk the tree forward in depth-first order starting with the current
491 /// node.
492 ///
493 /// The walk does not stop at the end of this node's subtree, it continues
494 /// with the following siblings of this node and of its ancestors. Use
495 /// [`Walk::inside`] to only visit this node and its descendants.
496 ///
497 /// See [Walk] for documentation.
498 #[must_use]
499 pub fn walk(&self) -> Walk<'a, T, F> {
500 Walk::new(self.tree, Some(Id::Node(self.id)), None, Event::Next)
501 }
502
503 /// Walk from the current node forwards and upwards through the tree.
504 ///
505 /// This does not include the current node or its descendants in the walk.
506 ///
507 /// See [Walk] for documentation.
508 #[must_use]
509 pub fn walk_from(&self) -> Walk<'a, T, F> {
510 Walk::new(self.tree, Some(Id::Node(self.id)), None, Event::Up)
511 }
512
513 /// Walk the node forwards in a depth-first fashion emitting events
514 /// indicating how the rest of the tree is being traversed.
515 ///
516 /// See [`WalkEvents`] for documentation.
517 #[must_use]
518 pub fn walk_events(&self) -> WalkEvents<'a, T, F> {
519 WalkEvents::new(self.tree, Some(Id::Node(self.id)), None, Event::Next)
520 }
521
522 /// Find a preceding element which matches the given predicate.
523 ///
524 /// A "preceding element" is one whose tokens immediately precede the
525 /// tokens of the current node. This is found in two steps:
526 ///
527 /// 1. Starting with the current node and moving through its ancestors, find
528 /// the first [`prev`][Node::prev] sibling which matches the predicate.
529 /// 2. From that sibling, descend through [`last`][Node::last] children for
530 /// as long as each matches the predicate, and return the last match.
531 ///
532 /// Step 2 stops at the first last child which does not match, so a
533 /// matching element nested below a non-matching last child is not found.
534 ///
535 /// See [`Element::find_preceding`] for an example.
536 pub fn find_preceding<P>(&self, predicate: P) -> Option<Element<'a, T, F>>
537 where
538 P: FnMut(Element<'a, T, F>) -> bool,
539 {
540 NodeOrToken::Node(*self).find_preceding(predicate)
541 }
542}
543
544impl<T, F> fmt::Debug for Node<'_, T, F>
545where
546 T: Copy + fmt::Debug,
547 F: Flavor<Index: fmt::Debug>,
548{
549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 f.debug_struct("Node")
551 .field("data", &self.links.data.get())
552 .field("span", &self.links.span)
553 .finish()
554 }
555}
556
557impl<T, F> Clone for Node<'_, T, F>
558where
559 T: Copy,
560 F: Flavor,
561{
562 #[inline]
563 fn clone(&self) -> Self {
564 *self
565 }
566}
567
568impl<T, F> Copy for Node<'_, T, F>
569where
570 T: Copy,
571 F: Flavor,
572{
573}
574
575/// Nodes compare equal when their [values][Node::value] and
576/// [spans][Node::span] are equal, regardless of their position in a tree.
577///
578/// Compare [`Node::id`] to check whether two nodes are the same node.
579///
580/// # Examples
581///
582/// ```
583/// let tree = syntree::tree! {
584/// "x" => {
585/// "x" => {}
586/// }
587/// };
588///
589/// let root = tree.first().and_then(|e| e.into_node()).ok_or("missing root")?;
590/// let child = root.first().and_then(|e| e.into_node()).ok_or("missing child")?;
591///
592/// assert_eq!(root, child);
593/// assert_ne!(root.id(), child.id());
594/// # Ok::<_, Box<dyn core::error::Error>>(())
595/// ```
596impl<T, A, B> PartialEq<Node<'_, T, A>> for Node<'_, T, B>
597where
598 T: Copy + PartialEq,
599 A: Flavor,
600 B: Flavor<Index: PartialEq<A::Index>>,
601{
602 fn eq(&self, other: &Node<'_, T, A>) -> bool {
603 self.links.data.get() == other.links.data.get() && self.links.span == other.links.span
604 }
605}
606
607impl<T, F> Eq for Node<'_, T, F>
608where
609 T: Copy + Eq,
610 F: Flavor<Index: Eq>,
611{
612}