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