linked_syntax_tree/
lib.rs

1#![warn(clippy::pedantic, missing_debug_implementations, missing_docs)]
2
3//! A doubly-linked syntax tree.
4//!
5//! Offers functionality similar to [`std::collections::LinkedList`](https://doc.rust-lang.org/std/collections/struct.LinkedList.html).
6//!
7//! ## Example
8//!
9//! ```text
10//! x = -10
11//! loop
12//!     x = x + 1
13//!     if x
14//!         break
15//! x = 2
16//! ```
17//!
18//! can be represented as:
19//!
20//! ```text
21//! ┌──────────┐
22//! │x = -10   │
23//! └──────────┘
24//! │
25//! ┌──────────┐
26//! │loop      │
27//! └──────────┘
28//! │           ╲
29//! ┌──────────┐ ┌─────────┐
30//! │x = 2     │ │x = x + 1│
31//! └──────────┘ └─────────┘
32//!              │
33//!              ┌─────────┐
34//!              │if x     │
35//!              └─────────┘
36//!                         ╲
37//!                          ┌─────────┐
38//!                          │break    │
39//!                          └─────────┘
40//! ```
41//! which can be constructed with:
42//! ```rust
43//! # use linked_syntax_tree::*;
44//! let mut root = SyntaxTree::default();
45//! let mut cursor = root.cursor_mut();
46//! cursor.insert_next("x = -10"); // Inserts "x = -10" as the root element.
47//! cursor.insert_next("loop"); // Inserts "loop" as the next element.
48//! cursor.move_next(); // Moves the cursor to "loop".
49//! cursor.insert_child("x = x + 1"); // Inserts "x = x + 1" as the child element.
50//! cursor.move_child(); // Moves the cursor to "x = x + 1".
51//! cursor.insert_next("if x"); // Inserts "if x" as the next element.
52//! cursor.move_next(); // Moves the cursor to "if x".
53//! cursor.insert_child("break"); // Inserts "break" as the child element.
54//! cursor.move_parent(); // Moves the cursor to "if x".
55//! cursor.move_parent(); // Moves the cursor to "loop".
56//! cursor.insert_next("x = 2");
57//! assert_eq!(root.to_string(), r#"x = -10
58//! loop
59//!     x = x + 1
60//!     if x
61//!         break
62//! x = 2
63//! "#);
64//! ```
65//!
66//! ## Terminology
67//!
68//! - **next**: `loop` is the *next* element of `x = -10`.
69//! - **previous**: `x = -10` is the *previous* element of `loop`.
70//! - **child**: `x = x + 1` is the *child* element of `loop`.
71//! - **parent**: `loop` is the *parent* element of `x = x + 1`.
72//! - **preceding**: All *previous* elements and *parent* elements are *preceding* elements.
73//!   A *preceding* element may be a *previous* element or a *parent* element.
74//! - **predecessor**: The previous element if the tree is flattened e.g. `break` is the
75//!   *predecessor* of `x = 2`.
76//! - **successor**: The next element if the tree is flattened e.g. `x = 2` is the *successor* of
77//!   `break`.
78//!
79//! ## Use-case
80//!
81//! I'm using this to contain an AST for compile-time evaluation in my personal WIP language.
82
83use std::alloc;
84use std::fmt;
85use std::ptr;
86use std::ptr::NonNull;
87
88/// A doubly linked syntax tree.
89#[derive(Debug)]
90pub struct SyntaxTree<T>(OptionalNode<T>);
91
92type OptionalNode<T> = Option<NonNull<Node<T>>>;
93type NodePredecessor<T> = Preceding<NonNull<Node<T>>>;
94
95impl<T> PartialEq for SyntaxTree<T> {
96    fn eq(&self, other: &Self) -> bool {
97        self.0 == other.0
98    }
99}
100impl<T> Eq for SyntaxTree<T> {}
101
102/// The string used for depth in the [`SyntaxTree`] [`std::fmt::Display`] implementation.
103pub const INDENT: &str = "    ";
104
105impl<T: fmt::Display> fmt::Display for SyntaxTree<T> {
106    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107        for Element { item, depth } in self.iter() {
108            writeln!(f, "{}{item}", INDENT.repeat(depth))?;
109        }
110        Ok(())
111    }
112}
113
114impl<T> SyntaxTree<T> {
115    /// Provides a cursor at the front element.
116    #[must_use]
117    pub fn cursor(&self) -> Cursor<T> {
118        Cursor {
119            preceding: None,
120            current: self.0,
121            root: &self.0,
122            succeeding_bound: None,
123        }
124    }
125
126    /// Provides a cursor with editing operation at the root element.
127    pub fn cursor_mut(&mut self) -> CursorMut<T> {
128        CursorMut {
129            preceding: None,
130            current: self.0,
131            root: &mut self.0,
132        }
133    }
134
135    /// Returns the length of the `OptionalNode`.
136    ///
137    /// This operation should compute in *O*(n) time.
138    #[must_use]
139    pub fn len(&self) -> usize {
140        self.iter().count()
141    }
142
143    /// Returns true if the tree contains no elements.
144    #[must_use]
145    pub fn is_empty(&self) -> bool {
146        self.0.is_some()
147    }
148
149    /// Returns a depth-first iterator with references.
150    #[must_use]
151    pub fn iter(&self) -> Iter<'_, T> {
152        let stack = if let Some(root) = self.0 {
153            vec![(root, 0)]
154        } else {
155            Vec::new()
156        };
157        Iter {
158            stack,
159            __marker: self,
160        }
161    }
162
163    /// Returns a depth-first iterator with mutable references.
164    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
165        let stack = if let Some(root) = self.0 {
166            vec![(root, 0)]
167        } else {
168            Vec::new()
169        };
170        IterMut {
171            stack,
172            __marker: self,
173        }
174    }
175}
176impl<T> Default for SyntaxTree<T> {
177    fn default() -> Self {
178        Self(None)
179    }
180}
181impl<T: Clone> Clone for SyntaxTree<T> {
182    fn clone(&self) -> Self {
183        if let Some(root) = self.0 {
184            unsafe {
185                let root_ptr = {
186                    let ptr: *mut Node<T> =
187                        alloc::alloc(alloc::Layout::new::<Node<T>>()).cast::<Node<T>>();
188                    ptr::copy_nonoverlapping(root.as_ptr(), ptr, 1);
189                    NonNull::new(ptr).unwrap()
190                };
191
192                // TODO Like the other cases, this will only ever be 2 elements make this more efficient.
193                let mut stack = vec![root_ptr];
194                while let Some(mut current) = stack.pop() {
195                    if let Some(next) = &mut current.as_mut().next {
196                        let next_ptr = {
197                            let ptr =
198                                alloc::alloc(alloc::Layout::new::<Node<T>>()).cast::<Node<T>>();
199                            ptr::copy_nonoverlapping(next.as_ptr(), ptr, 1);
200                            NonNull::new(ptr).unwrap()
201                        };
202                        *next = next_ptr;
203                        stack.push(next_ptr);
204                    }
205                    if let Some(child) = &mut current.as_mut().child {
206                        let child_ptr = {
207                            let ptr =
208                                alloc::alloc(alloc::Layout::new::<Node<T>>()).cast::<Node<T>>();
209                            ptr::copy_nonoverlapping(child.as_ptr(), ptr, 1);
210                            NonNull::new(ptr).unwrap()
211                        };
212                        *child = child_ptr;
213                        stack.push(child_ptr);
214                    }
215                }
216
217                Self(Some(root_ptr))
218            }
219        } else {
220            Self(None)
221        }
222    }
223}
224impl<T> From<T> for SyntaxTree<T> {
225    fn from(element: T) -> Self {
226        let ptr = unsafe {
227            let ptr = alloc::alloc(alloc::Layout::new::<Node<T>>()).cast();
228            ptr::write(
229                ptr,
230                Node {
231                    element,
232                    preceding: None,
233                    child: None,
234                    next: None,
235                },
236            );
237            NonNull::new_unchecked(ptr)
238        };
239        Self(Some(ptr))
240    }
241}
242impl<T> Drop for SyntaxTree<T> {
243    fn drop(&mut self) {
244        if let Some(current) = self.0 {
245            let mut stack = vec![current];
246            // Deallocate all child nodes of the old current node.
247            unsafe {
248                while let Some(next) = stack.pop() {
249                    if let Some(child) = next.as_ref().child {
250                        stack.push(child);
251                    }
252                    if let Some(next) = next.as_ref().next {
253                        stack.push(next);
254                    }
255                    alloc::dealloc(next.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
256                }
257            }
258        }
259    }
260}
261
262/// Iterates through elements depth-first in a [`OptionalNode`] returning references.
263#[derive(Debug)]
264pub struct Iter<'a, T> {
265    stack: Vec<(NonNull<Node<T>>, usize)>,
266    __marker: &'a SyntaxTree<T>,
267}
268impl<'a, T> Iterator for Iter<'a, T> {
269    type Item = Element<&'a T>;
270    fn next(&mut self) -> Option<Self::Item> {
271        let current_opt = self.stack.pop();
272        unsafe {
273            if let Some((current, depth)) = current_opt {
274                if let Some(next) = current.as_ref().next {
275                    self.stack.push((next, depth));
276                }
277                if let Some(child) = current.as_ref().child {
278                    self.stack.push((child, depth + 1));
279                }
280                Some(Element {
281                    item: &current.as_ref().element,
282                    depth,
283                })
284            } else {
285                None
286            }
287        }
288    }
289}
290
291/// Iterates through elements depth-first in a [`OptionalNode`] returning mutable references.
292#[derive(Debug)]
293pub struct IterMut<'a, T> {
294    stack: Vec<(NonNull<Node<T>>, usize)>,
295    __marker: &'a mut SyntaxTree<T>,
296}
297impl<'a, T> Iterator for IterMut<'a, T> {
298    type Item = Element<&'a mut T>;
299    fn next(&mut self) -> Option<Self::Item> {
300        let current_opt = self.stack.pop();
301        unsafe {
302            if let Some((mut current, depth)) = current_opt {
303                if let Some(next) = current.as_ref().next {
304                    self.stack.push((next, depth));
305                }
306                if let Some(child) = current.as_ref().child {
307                    self.stack.push((child, depth + 1));
308                }
309                Some(Element {
310                    item: &mut current.as_mut().element,
311                    depth,
312                })
313            } else {
314                None
315            }
316        }
317    }
318}
319
320/// An element in a [`OptionalNode`] with a known depth.
321#[derive(Debug, Eq, PartialEq)]
322pub struct Element<T> {
323    /// The data within the node.
324    pub item: T,
325    /// The depth of the node.
326    pub depth: usize,
327}
328
329/// A cursor which can be used to mutate element, but only in such a way that it does not remove
330/// elements in `self.guarded_nodes`. This allows for a semi-mutable cursor on the upper portion of
331/// a syntax tree while maintaining a mutable cursor on the lower portion.
332#[derive(Debug)]
333pub struct RestrictedCursor<'a, T> {
334    /// The preceding element, mutably accessing this is unsafe.
335    pub preceding: Option<NodePredecessor<T>>,
336    /// The current element, mutably accessing this is unsafe.
337    pub current: OptionalNode<T>,
338    /// The current root element, mutably accessing this is unsafe.
339    pub root: &'a mut OptionalNode<T>,
340    /// The set of nodes which cannot be removed, mutably accessing this is unsafe.
341    pub guarded_nodes: Vec<NonNull<Node<T>>>,
342}
343impl<'a, T> From<RestrictedCursor<'a, T>> for Cursor<'a, T> {
344    fn from(cursor: RestrictedCursor<'a, T>) -> Cursor<'a, T> {
345        Cursor {
346            preceding: cursor.preceding,
347            current: cursor.current,
348            root: cursor.root,
349            succeeding_bound: cursor.guarded_nodes.first().copied(),
350        }
351    }
352}
353impl<'a, T> RestrictedCursor<'a, T> {
354    /// Get the current element.
355    ///
356    /// Returns `None` if the current element is `None` or if the current element is the lower bound.
357    #[must_use]
358    pub fn current(&self) -> Option<&T> {
359        self.current.map(|ptr| unsafe { &ptr.as_ref().element })
360    }
361
362    /// Moves the cursor to the preceding element returning a reference to the new element if one is present, otherwise returning `None`.
363    pub fn peek_move_preceding(&mut self) -> Option<&T> {
364        if self.current == *self.root {
365            None
366        } else if let Some(preceding) = self.preceding {
367            // If we move to a parent node, we add this parent to the guarded nodes to specify that
368            // it cannot be removed (removing it would remove its children which would remove nodes
369            // borrowed by a mutable cursor).
370            if let Preceding::Parent(parent) = preceding {
371                self.guarded_nodes.push(parent);
372            }
373
374            self.current = Some(preceding.unwrap());
375            let temp = unsafe { preceding.unwrap().as_ref() };
376            self.preceding = temp.preceding;
377            Some(&temp.element)
378        } else {
379            None
380        }
381    }
382
383    /// Moves the cursor to the preceding element.
384    ///
385    /// If there is no preceding element the cursor is not moved.
386    pub fn move_preceding(&mut self) -> bool {
387        if self.current == *self.root {
388            false
389        } else if let Some(preceding) = self.preceding {
390            // If we move to a parent node, we add this parent to the guarded nodes to specify that
391            // it cannot be removed (removing it would remove its children which would remove nodes
392            // borrowed by a mutable cursor).
393            if let Preceding::Parent(parent) = preceding {
394                self.guarded_nodes.push(parent);
395            }
396
397            self.current = Some(preceding.unwrap());
398            self.preceding = unsafe { preceding.unwrap().as_ref().preceding.as_ref().copied() };
399            true
400        } else {
401            false
402        }
403    }
404
405    /// Moves the cursor to the next element if there is some current element and the next element
406    /// is within the bounds of the cursor (when splitting a mutable cursor, an immutable cursor is
407    /// produced where its bound restrict it to element above the mutable cursor).
408    pub fn move_next(&mut self) {
409        if let Some(current) = self.current {
410            // We cannot move past the 1st guarded node (as all nodes past this are borrowed by a
411            // mutable cursor).
412            if Some(current) == self.guarded_nodes.first().copied() {
413                return;
414            }
415            self.preceding = Some(Preceding::Previous(current));
416            self.current = unsafe { current.as_ref().next };
417        }
418    }
419
420    /// Moves the cursor to the child element if there is some current element and the child element
421    /// is within the bounds of the cursor (when splitting a mutable cursor, an immutable cursor is
422    /// produced where its bound restrict it to element above the mutable cursor).
423    pub fn move_child(&mut self) {
424        if let Some(current) = self.current {
425            // We can pop the latest parent node from the guarded nodes.
426            self.guarded_nodes.pop();
427
428            self.preceding = Some(Preceding::Parent(current));
429            self.current = unsafe { current.as_ref().child };
430        }
431    }
432
433    /// Moves the cursor through preceding elements until reaching a parent, if no parent is found,
434    /// the cursor is reset to its original position.
435    ///
436    /// Returns `true` if the cursor was moved to a parent, or `false` if not.
437    pub fn move_parent(&mut self) -> bool {
438        let cache_preceding = self.preceding;
439        let cache_current = self.current;
440        loop {
441            match self.preceding {
442                Some(Preceding::Previous(previous)) => {
443                    if Some(previous) == *self.root {
444                        break;
445                    }
446                    self.current = Some(previous);
447                    self.preceding = unsafe { previous.as_ref().preceding };
448                }
449                Some(Preceding::Parent(parent)) => {
450                    // If we move to a parent node, we add this parent to the guarded nodes to specify that
451                    // it cannot be removed (removing it would remove its children which would remove nodes
452                    // borrowed by a mutable cursor).
453                    self.guarded_nodes.push(parent);
454
455                    self.current = Some(parent);
456                    self.preceding = unsafe { parent.as_ref().preceding };
457                    return true;
458                }
459                None => break,
460            }
461        }
462        self.current = cache_current;
463        self.preceding = cache_preceding;
464        false
465    }
466
467    /// Moves the cursor to the successor element if one can be found. If there is no successor
468    /// element the cursor is reset to its original position and is not moved.
469    ///
470    /// Returns `true` if the cursor was moved to a successor, or `false` if not.
471    pub fn move_successor(&mut self) -> bool {
472        if self.peek_child().is_some() {
473            self.move_child();
474            true
475        } else if self.peek_next().is_some() {
476            self.move_next();
477            true
478        } else {
479            // If the element has a parent and the cursor was moved to it.
480            if self.move_parent() {
481                if self.peek_child().is_some() {
482                    self.move_child();
483                    true
484                } else if self.peek_next().is_some() {
485                    self.move_next();
486                    true
487                } else {
488                    false
489                }
490            } else {
491                false
492            }
493        }
494    }
495
496    /// Moves the cursor to the predecessor element if one can be found. If there is no predecessor
497    /// element the cursor is reset to its original position and is not moved.
498    ///
499    /// Returns `true` if the cursor was moved to a predecessor, or `false` if not.
500    pub fn move_predecessor(&mut self) -> bool {
501        match self.peek_preceding() {
502            Some(Preceding::Parent(_)) => {
503                self.move_preceding();
504                true
505            }
506            Some(Preceding::Previous(_)) => {
507                self.move_preceding();
508
509                loop {
510                    if self.peek_child().is_some() {
511                        self.move_child();
512                        while self.peek_next().is_some() {
513                            self.move_next();
514                        }
515                    } else {
516                        break;
517                    }
518                }
519
520                true
521            }
522            None => false,
523        }
524    }
525
526    /// Returns a reference to the next element.
527    #[must_use]
528    pub fn peek_next(&self) -> Option<&T> {
529        if let Some(current) = self.current {
530            // We cannot obtain a reference to the next node after the first guarded node as this
531            // would be a reference to a node which a mutable cursor could have a mutable reference
532            // to (and thus could remove invalidating our reference here).
533            if Some(current) == self.guarded_nodes.first().copied() {
534                return None;
535            }
536
537            unsafe { current.as_ref().next.map(|n| &n.as_ref().element) }
538        } else {
539            None
540        }
541    }
542
543    /// Returns a reference to the parent element.
544    ///
545    /// Wrapper around `self.peek_preceding().and_then(Preceding::parent)`.
546    #[must_use]
547    pub fn peek_parent(&self) -> Option<&T> {
548        self.peek_preceding().and_then(Preceding::parent)
549    }
550
551    /// Returns a reference to the previous element.
552    ///
553    /// Wrapper around `self.peek_preceding().and_then(Preceding::previous)`
554    /// .
555    #[must_use]
556    pub fn peek_previous(&self) -> Option<&T> {
557        self.peek_preceding().and_then(Preceding::previous)
558    }
559
560    /// Returns a reference to the preceding element.
561    #[must_use]
562    pub fn peek_preceding(&self) -> Option<Preceding<&T>> {
563        self.preceding
564            .map(|p| unsafe { p.map(|p| &p.as_ref().element) })
565    }
566
567    /// Returns a reference to the child element.
568    #[must_use]
569    pub fn peek_child(&self) -> Option<&T> {
570        if let Some(current) = self.current {
571            // We cannot obtain a reference to the next node after the first guarded node as this
572            // would be a reference to a node which a mutable cursor could have a mutable reference
573            // to (and thus could remove invalidating our reference here).
574            if Some(current) == self.guarded_nodes.first().copied() {
575                return None;
576            }
577
578            unsafe { current.as_ref().child.map(|n| &n.as_ref().element) }
579        } else {
580            None
581        }
582    }
583
584    /// Get the current element.
585    pub fn current_mut(&self) -> Option<&mut T> {
586        self.current
587            .map(|mut ptr| unsafe { &mut ptr.as_mut().element })
588    }
589
590    /// Removes the current node if it is not a guarded node.
591    ///
592    /// When removing a node with a child node, the child node is removed.
593    ///
594    /// Returns if the node was removed.
595    pub fn remove_current(&mut self) {
596        // We cannot remove the last guarded node, as this node is the n'th parent of the 1st
597        // guarded node which is the preceding node of the root node of a mutable cursor. In this
598        // case removing this node would deallocate nodes borrowed by the mutable cursor.
599        if self.current == self.guarded_nodes.last().copied() {
600            return;
601        }
602
603        match (self.current, self.preceding) {
604            (Some(current), Some(preceding)) => unsafe {
605                self.current = current.as_ref().next;
606                match preceding {
607                    Preceding::Parent(mut parent) => {
608                        parent.as_mut().child = current.as_ref().next;
609                    }
610                    Preceding::Previous(mut previous) => {
611                        previous.as_mut().next = current.as_ref().next;
612                    }
613                }
614                if let Some(mut next) = current.as_ref().next {
615                    next.as_mut().preceding = Some(preceding);
616                }
617
618                // Deallocate all child nodes of the old current node.
619                if let Some(child) = current.as_ref().child {
620                    // TODO This will never be greater than 2 elements, do something more
621                    // performant.
622                    let mut stack = vec![child];
623                    while let Some(next) = stack.pop() {
624                        if let Some(child) = next.as_ref().child {
625                            stack.push(child);
626                        }
627                        if let Some(next) = next.as_ref().next {
628                            stack.push(next);
629                        }
630                        alloc::dealloc(next.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
631                    }
632                }
633                alloc::dealloc(current.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
634            },
635            (Some(current), None) => unsafe {
636                self.current = current.as_ref().next;
637                *self.root = current.as_ref().next;
638                if let Some(mut next) = current.as_ref().next {
639                    next.as_mut().preceding = None;
640                }
641
642                // Deallocate all child nodes of the old current node.
643                if let Some(child) = current.as_ref().child {
644                    // TODO This will never be greater than 2 elements, do something more
645                    // performant.
646                    let mut stack = vec![child];
647                    while let Some(next) = stack.pop() {
648                        if let Some(child) = next.as_ref().child {
649                            stack.push(child);
650                        }
651                        if let Some(next) = next.as_ref().next {
652                            stack.push(next);
653                        }
654                        alloc::dealloc(next.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
655                    }
656                }
657                alloc::dealloc(current.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
658            },
659            (None, _) => {}
660        }
661    }
662}
663
664/// Roughly matches [`std::collections::linked_list::Cursor`].
665#[derive(Debug)]
666pub struct Cursor<'a, T> {
667    /// The preceding element, mutably accessing this is unsafe.
668    pub preceding: Option<NodePredecessor<T>>,
669    /// The current element, mutably accessing this is unsafe.
670    pub current: OptionalNode<T>,
671    /// The current root element, mutably accessing this is unsafe.
672    pub root: &'a OptionalNode<T>,
673    /// `self.current` can be equal to `self.succeeding_bound` but it cannot be moved after this,
674    /// `self.preceding` cannot be equal to `self.succeeding_bound`.
675    pub succeeding_bound: OptionalNode<T>,
676}
677impl<'a, T> Clone for Cursor<'a, T> {
678    fn clone(&self) -> Self {
679        Self {
680            preceding: self.preceding,
681            current: self.current,
682            root: self.root,
683            succeeding_bound: self.succeeding_bound,
684        }
685    }
686}
687impl<'a, T> Cursor<'a, T> {
688    /// Get the current element.
689    ///
690    /// Returns `None` if the current element is `None` or if the current element is the lower bound.
691    #[must_use]
692    pub fn current(&self) -> Option<&T> {
693        self.current.map(|ptr| unsafe { &ptr.as_ref().element })
694    }
695
696    /// Moves the cursor to the preceding element returning a reference to the new element if one is present, otherwise returning `None`.
697    pub fn peek_move_preceding(&mut self) -> Option<&T> {
698        if self.current == *self.root {
699            None
700        } else if let Some(preceding) = self.preceding {
701            self.current = Some(preceding.unwrap());
702            let temp = unsafe { preceding.unwrap().as_ref() };
703            self.preceding = temp.preceding;
704            Some(&temp.element)
705        } else {
706            None
707        }
708    }
709
710    /// Moves the cursor to the preceding element.
711    ///
712    /// If there is no preceding element the cursor is not moved.
713    pub fn move_preceding(&mut self) -> bool {
714        if self.current == *self.root {
715            false
716        } else if let Some(preceding) = self.preceding {
717            self.current = Some(preceding.unwrap());
718            self.preceding = unsafe { preceding.unwrap().as_ref().preceding.as_ref().copied() };
719            true
720        } else {
721            false
722        }
723    }
724
725    /// Moves the cursor to the next element if there is some current element and the next element
726    /// is within the bounds of the cursor (when splitting a mutable cursor, an immutable cursor is
727    /// produced where its bound restrict it to element above the mutable cursor).
728    pub fn move_next(&mut self) {
729        if let Some(current) = self.current {
730            self.preceding = Some(Preceding::Previous(current));
731            self.current = unsafe { current.as_ref().next };
732        }
733    }
734
735    /// Moves the cursor to the child element if there is some current element and the child element
736    /// is within the bounds of the cursor (when splitting a mutable cursor, an immutable cursor is
737    /// produced where its bound restrict it to element above the mutable cursor).
738    pub fn move_child(&mut self) {
739        if let Some(current) = self.current {
740            self.preceding = Some(Preceding::Parent(current));
741            self.current = unsafe { current.as_ref().child };
742        }
743    }
744
745    /// Moves the cursor through preceding elements until reaching a parent, if no parent is found,
746    /// the cursor is reset to its original position.
747    ///
748    /// Returns `true` if the cursor was moved to a parent, or `false` if not.
749    pub fn move_parent(&mut self) -> bool {
750        let cache_preceding = self.preceding;
751        let cache_current = self.current;
752        loop {
753            match self.preceding {
754                Some(Preceding::Previous(previous)) => {
755                    if Some(previous) == *self.root {
756                        break;
757                    }
758                    self.current = Some(previous);
759                    self.preceding = unsafe { previous.as_ref().preceding };
760                }
761                Some(Preceding::Parent(parent)) => {
762                    self.current = Some(parent);
763                    self.preceding = unsafe { parent.as_ref().preceding };
764                    return true;
765                }
766                None => break,
767            }
768        }
769        self.preceding = cache_preceding;
770        self.current = cache_current;
771        false
772    }
773
774    /// Moves the cursor to the successor element if one can be found. If there is no successor
775    /// element the cursor is reset to its original position and is not moved.
776    ///
777    /// Returns `true` if the cursor was moved to a successor, or `false` if not.
778    pub fn move_successor(&mut self) -> bool {
779        if self.peek_child().is_some() {
780            self.move_child();
781            true
782        } else if self.peek_next().is_some() {
783            self.move_next();
784            true
785        } else {
786            // If the element has a parent and the cursor was moved to it.
787            if self.move_parent() {
788                if self.peek_child().is_some() {
789                    self.move_child();
790                    true
791                } else if self.peek_next().is_some() {
792                    self.move_next();
793                    true
794                } else {
795                    false
796                }
797            } else {
798                false
799            }
800        }
801    }
802
803    /// Moves the cursor to the predecessor element if one can be found. If there is no predecessor
804    /// element the cursor is reset to its original position and is not moved.
805    ///
806    /// Returns `true` if the cursor was moved to a predecessor, or `false` if not.
807    pub fn move_predecessor(&mut self) -> bool {
808        match self.peek_preceding() {
809            Some(Preceding::Parent(_)) => {
810                self.move_preceding();
811                true
812            }
813            Some(Preceding::Previous(_)) => {
814                self.move_preceding();
815
816                loop {
817                    if self.peek_child().is_some() {
818                        self.move_child();
819                        while self.peek_next().is_some() {
820                            self.move_next();
821                        }
822                    } else {
823                        break;
824                    }
825                }
826
827                true
828            }
829            None => false,
830        }
831    }
832
833    /// Returns a reference to the next element.
834    #[must_use]
835    pub fn peek_next(&self) -> Option<&T> {
836        if let Some(current) = self.current {
837            // We cannot obtain a reference to the next node after the succeeding bound node as this
838            // would be a reference to a node which a mutable cursor could have a mutable reference
839            // to (and thus could remove invalidating our reference here).
840            if Some(current) == self.succeeding_bound {
841                return None;
842            }
843
844            unsafe { current.as_ref().next.map(|n| &n.as_ref().element) }
845        } else {
846            None
847        }
848    }
849
850    /// Returns a reference to the parent element.
851    ///
852    /// Wrapper around `self.peek_preceding().and_then(Preceding::parent)`.
853    #[must_use]
854    pub fn peek_parent(&self) -> Option<&T> {
855        self.peek_preceding().and_then(Preceding::parent)
856    }
857
858    /// Returns a reference to the previous element.
859    ///
860    /// Wrapper around `self.peek_preceding().and_then(Preceding::previous)`
861    /// .
862    #[must_use]
863    pub fn peek_previous(&self) -> Option<&T> {
864        self.peek_preceding().and_then(Preceding::previous)
865    }
866
867    /// Returns a reference to the preceding element.
868    #[must_use]
869    pub fn peek_preceding(&self) -> Option<Preceding<&T>> {
870        self.preceding
871            .map(|p| unsafe { p.map(|p| &p.as_ref().element) })
872    }
873
874    /// Returns a reference to the child element.
875    #[must_use]
876    pub fn peek_child(&self) -> Option<&T> {
877        if let Some(current) = self.current {
878            // We cannot obtain a reference to the next node after the succeeding bound node as this
879            // would be a reference to a node which a mutable cursor could have a mutable reference
880            // to (and thus could remove invalidating our reference here).
881            if Some(current) == self.succeeding_bound {
882                return None;
883            }
884
885            unsafe { current.as_ref().child.map(|n| &n.as_ref().element) }
886        } else {
887            None
888        }
889    }
890}
891
892/// Roughly matches [`std::collections::linked_list::CursorMut`].
893#[derive(Debug)]
894pub struct CursorMut<'a, T> {
895    /// The preceding element, mutably accessing this is unsafe.
896    pub preceding: Option<NodePredecessor<T>>,
897    /// The current element, mutably accessing this is unsafe.
898    pub current: OptionalNode<T>,
899    /// This can also be a bound where `self.current` can be equal to `self.root` but it cannot be moved before this.
900    pub root: &'a mut OptionalNode<T>,
901}
902impl<'a, T> CursorMut<'a, T> {
903    /// Gets a syntax tree where the root is the current node.
904    #[must_use]
905    pub fn subtree(&self) -> &SyntaxTree<T> {
906        unsafe { &*(std::ptr::addr_of!(self.current).cast()) }
907    }
908
909    /// Splits the cursor at the current element, where the returned mutable cursor points to the
910    /// current element and the return immutable cursor points to the preceding element.
911    pub fn split_restricted(&mut self) -> (CursorMut<'_, T>, RestrictedCursor<'_, T>) {
912        let cursor = RestrictedCursor {
913            preceding: self
914                .preceding
915                .and_then(|p| unsafe { p.unwrap().as_ref().preceding }),
916            current: self.preceding.map(Preceding::unwrap),
917            root: self.root,
918            guarded_nodes: if let Some(p) = self.preceding.map(Preceding::unwrap) {
919                vec![p]
920            } else {
921                Vec::new()
922            },
923        };
924        let mutable_cursor = CursorMut {
925            preceding: self.preceding,
926            current: self.current,
927            root: &mut self.current,
928        };
929        (mutable_cursor, cursor)
930    }
931
932    /// Splits the tree at the current element.
933    pub fn split_next(&mut self) -> OptionalNode<T> {
934        match self.current {
935            Some(mut current) => unsafe {
936                if let Some(next) = current.as_ref().next {
937                    current.as_mut().next = None;
938                    Some(next)
939                } else {
940                    None
941                }
942            },
943            None => None,
944        }
945    }
946
947    /// Splits the cursor at the current element, where the returned mutable cursor points to the
948    /// current element and the return immutable cursor points to the preceding element.
949    pub fn split(&mut self) -> (CursorMut<'_, T>, Cursor<'_, T>) {
950        let cursor = Cursor {
951            preceding: self.current.and_then(|c| unsafe { c.as_ref().preceding }),
952            current: self.preceding.map(Preceding::unwrap),
953            root: self.root,
954            succeeding_bound: self.preceding.map(Preceding::unwrap),
955        };
956        let mutable_cursor = CursorMut {
957            preceding: self.preceding,
958            current: self.current,
959            root: &mut self.current,
960        };
961        (mutable_cursor, cursor)
962    }
963
964    /// Get the current element.
965    ///
966    /// Returns `None` if the current element is `None` or if the current element is the lower bound.
967    #[must_use]
968    pub fn current(&self) -> Option<&T> {
969        self.current.map(|ptr| unsafe { &ptr.as_ref().element })
970    }
971
972    /// Moves the cursor to the preceding element returning a reference to the new element if one is present, otherwise returning `None`.
973    pub fn peek_move_preceding(&mut self) -> Option<&T> {
974        if self.current == *self.root {
975            None
976        } else if let Some(preceding) = self.preceding {
977            self.current = Some(preceding.unwrap());
978            let temp = unsafe { preceding.unwrap().as_ref() };
979            self.preceding = temp.preceding;
980            Some(&temp.element)
981        } else {
982            None
983        }
984    }
985
986    /// Moves the cursor to the preceding element.
987    ///
988    /// If there is no preceding element or the cursor is at its `preceding_bound` it doesn't move.
989    pub fn move_preceding(&mut self) -> bool {
990        if self.current == *self.root {
991            false
992        } else if let Some(preceding) = self.preceding {
993            self.current = Some(preceding.unwrap());
994            self.preceding = unsafe { preceding.unwrap().as_ref().preceding.as_ref().copied() };
995            true
996        } else {
997            false
998        }
999    }
1000
1001    /// Moves the cursor to the next element.
1002    pub fn move_next(&mut self) {
1003        if let Some(current) = self.current {
1004            self.preceding = Some(Preceding::Previous(current));
1005            self.current = unsafe { current.as_ref().next };
1006        }
1007    }
1008
1009    /// Moves the cursor to the child element.
1010    pub fn move_child(&mut self) {
1011        if let Some(current) = self.current {
1012            self.preceding = Some(Preceding::Parent(current));
1013            self.current = unsafe { current.as_ref().child };
1014        }
1015    }
1016
1017    /// Moves the cursor through preceding elements until reaching a parent, if no parent is found,
1018    /// the cursor is reset to its original position.
1019    ///
1020    /// Returns `true` if the cursor was moved to a parent, or `false` if not.
1021    pub fn move_parent(&mut self) -> bool {
1022        let cache_preceding = self.preceding;
1023        let cache_current = self.current;
1024        loop {
1025            match self.preceding {
1026                Some(Preceding::Previous(previous)) => {
1027                    if Some(previous) == *self.root {
1028                        break;
1029                    }
1030                    self.current = Some(previous);
1031                    self.preceding = unsafe { previous.as_ref().preceding };
1032                }
1033                Some(Preceding::Parent(parent)) => {
1034                    self.current = Some(parent);
1035                    self.preceding = unsafe { parent.as_ref().preceding };
1036                    return true;
1037                }
1038                None => break,
1039            }
1040        }
1041        self.preceding = cache_preceding;
1042        self.current = cache_current;
1043        false
1044    }
1045
1046    /// Moves the cursor to the successor element if one can be found. If there is no successor
1047    /// element the cursor is reset to its original position and is not moved.
1048    ///
1049    /// Returns `true` if the cursor was moved to a successor, or `false` if not.
1050    pub fn move_successor(&mut self) -> bool {
1051        if self.peek_child().is_some() {
1052            self.move_child();
1053            true
1054        } else if self.peek_next().is_some() {
1055            self.move_next();
1056            true
1057        } else {
1058            // If the element has a parent and the cursor was moved to it.
1059            if self.move_parent() {
1060                if self.peek_child().is_some() {
1061                    self.move_child();
1062                    true
1063                } else if self.peek_next().is_some() {
1064                    self.move_next();
1065                    true
1066                } else {
1067                    false
1068                }
1069            } else {
1070                false
1071            }
1072        }
1073    }
1074
1075    /// Moves the cursor to the predecessor element if one can be found. If there is no predecessor
1076    /// element the cursor is reset to its original position and is not moved.
1077    ///
1078    /// Returns `true` if the cursor was moved to a predecessor, or `false` if not.
1079    pub fn move_predecessor(&mut self) -> bool {
1080        match self.peek_preceding() {
1081            Some(Preceding::Parent(_)) => {
1082                self.move_preceding();
1083                true
1084            }
1085            Some(Preceding::Previous(_)) => {
1086                self.move_preceding();
1087
1088                loop {
1089                    if self.peek_child().is_some() {
1090                        self.move_child();
1091                        while self.peek_next().is_some() {
1092                            self.move_next();
1093                        }
1094                    } else {
1095                        break;
1096                    }
1097                }
1098
1099                true
1100            }
1101            None => false,
1102        }
1103    }
1104
1105    /// Returns a reference to the next element.
1106    #[must_use]
1107    pub fn peek_next(&self) -> Option<&T> {
1108        if let Some(current) = self.current {
1109            unsafe { current.as_ref().next.map(|n| &n.as_ref().element) }
1110        } else {
1111            None
1112        }
1113    }
1114
1115    /// Returns a reference to the parent element.
1116    ///
1117    /// Wrapper around `self.peek_preceding().and_then(Preceding::parent)`.
1118    #[must_use]
1119    pub fn peek_parent(&self) -> Option<&T> {
1120        self.peek_preceding().and_then(Preceding::parent)
1121    }
1122
1123    /// Returns a reference to the previous element.
1124    ///
1125    /// Wrapper around `self.peek_preceding().and_then(Preceding::previous)`
1126    /// .
1127    #[must_use]
1128    pub fn peek_previous(&self) -> Option<&T> {
1129        self.peek_preceding().and_then(Preceding::previous)
1130    }
1131
1132    /// Returns a reference to the preceding element.
1133    #[must_use]
1134    pub fn peek_preceding(&self) -> Option<Preceding<&T>> {
1135        if *self.root == self.current {
1136            return None;
1137        }
1138
1139        self.preceding
1140            .map(|p| unsafe { p.map(|p| &p.as_ref().element) })
1141    }
1142
1143    /// Returns a reference to the child element.
1144    #[must_use]
1145    pub fn peek_child(&self) -> Option<&T> {
1146        if let Some(current) = self.current {
1147            unsafe { current.as_ref().child.map(|n| &n.as_ref().element) }
1148        } else {
1149            None
1150        }
1151    }
1152
1153    /// Get the current element.
1154    pub fn current_mut(&mut self) -> Option<&mut T> {
1155        self.current
1156            .map(|mut ptr| unsafe { &mut ptr.as_mut().element })
1157    }
1158
1159    /// Inserts an element before the current element.
1160    ///
1161    /// If the cursor has `None` current element it is set to the inserted element.
1162    pub fn insert_preceding(&mut self, item: T) {
1163        let ptr = unsafe { alloc::alloc(alloc::Layout::new::<Node<T>>()).cast::<Node<T>>() };
1164        match (self.current, self.preceding) {
1165            (Some(mut current), Some(previous)) => unsafe {
1166                ptr::write(
1167                    ptr,
1168                    Node {
1169                        element: item,
1170                        preceding: Some(previous),
1171                        child: None,
1172                        next: Some(current),
1173                    },
1174                );
1175                let ptr = NonNull::new(ptr).unwrap_unchecked();
1176                match previous {
1177                    Preceding::Parent(mut parent) => {
1178                        parent.as_mut().child = Some(ptr);
1179                    }
1180                    Preceding::Previous(mut previous) => {
1181                        previous.as_mut().next = Some(ptr);
1182                    }
1183                }
1184                let pred = Some(Preceding::Previous(ptr));
1185                current.as_mut().preceding = pred;
1186                self.preceding = pred;
1187            },
1188            (Some(mut current), None) => unsafe {
1189                ptr::write(
1190                    ptr,
1191                    Node {
1192                        element: item,
1193                        preceding: None,
1194                        child: None,
1195                        next: Some(current),
1196                    },
1197                );
1198                let ptr = NonNull::new(ptr).unwrap_unchecked();
1199                let pred = Some(Preceding::Previous(ptr));
1200                current.as_mut().preceding = pred;
1201                self.preceding = pred;
1202                *self.root = Some(ptr);
1203            },
1204            (None, Some(previous)) => unsafe {
1205                ptr::write(
1206                    ptr,
1207                    Node {
1208                        element: item,
1209                        preceding: Some(previous),
1210                        child: None,
1211                        next: None,
1212                    },
1213                );
1214                let ptr = NonNull::new(ptr).unwrap_unchecked();
1215                match previous {
1216                    Preceding::Parent(mut parent) => {
1217                        parent.as_mut().child = Some(ptr);
1218                    }
1219                    Preceding::Previous(mut previous) => {
1220                        previous.as_mut().next = Some(ptr);
1221                    }
1222                }
1223                self.current = Some(ptr);
1224            },
1225            (None, None) => unsafe {
1226                ptr::write(
1227                    ptr,
1228                    Node {
1229                        element: item,
1230                        preceding: None,
1231                        child: None,
1232                        next: None,
1233                    },
1234                );
1235                let ptr = NonNull::new(ptr).unwrap_unchecked();
1236                self.current = Some(ptr);
1237                *self.root = Some(ptr);
1238            },
1239        }
1240    }
1241
1242    /// Inserts an element after the current element.
1243    ///
1244    /// If the cursor has `None` current element it is set to the inserted element.
1245    pub fn insert_next(&mut self, item: T) {
1246        let ptr = unsafe { alloc::alloc(alloc::Layout::new::<Node<T>>()).cast::<Node<T>>() };
1247        match (self.current, self.preceding) {
1248            (Some(mut current), _) => unsafe {
1249                ptr::write(
1250                    ptr,
1251                    Node {
1252                        element: item,
1253                        preceding: Some(Preceding::Previous(current)),
1254                        child: None,
1255                        next: current.as_ref().next,
1256                    },
1257                );
1258                let ptr = NonNull::new(ptr).unwrap_unchecked();
1259                if let Some(mut next) = current.as_ref().next {
1260                    next.as_mut().preceding = Some(Preceding::Previous(ptr));
1261                }
1262                current.as_mut().next = Some(ptr);
1263            },
1264            (None, Some(preceding)) => match preceding {
1265                Preceding::Parent(mut parent) => unsafe {
1266                    ptr::write(
1267                        ptr,
1268                        Node {
1269                            element: item,
1270                            preceding: Some(Preceding::Parent(parent)),
1271                            child: None,
1272                            next: None,
1273                        },
1274                    );
1275                    let ptr = NonNull::new(ptr).unwrap_unchecked();
1276                    parent.as_mut().child = Some(ptr);
1277                    self.current = Some(ptr);
1278                },
1279                Preceding::Previous(mut previous) => unsafe {
1280                    ptr::write(
1281                        ptr,
1282                        Node {
1283                            element: item,
1284                            preceding: Some(Preceding::Previous(previous)),
1285                            child: None,
1286                            next: None,
1287                        },
1288                    );
1289                    let ptr = NonNull::new(ptr).unwrap_unchecked();
1290                    previous.as_mut().next = Some(ptr);
1291                    self.current = Some(ptr);
1292                },
1293            },
1294            (None, None) => unsafe {
1295                ptr::write(
1296                    ptr,
1297                    Node {
1298                        element: item,
1299                        preceding: None,
1300                        child: None,
1301                        next: None,
1302                    },
1303                );
1304                let ptr = NonNull::new(ptr).unwrap_unchecked();
1305                self.current = Some(ptr);
1306                *self.root = Some(ptr);
1307            },
1308        }
1309    }
1310
1311    /// Inserts an element as a child of the current element.
1312    ///
1313    /// If the cursor has `None` current element it is set to the inserted element.
1314    pub fn insert_child(&mut self, item: T) {
1315        let ptr = unsafe { alloc::alloc(alloc::Layout::new::<Node<T>>()).cast::<Node<T>>() };
1316        match (self.current, self.preceding) {
1317            (Some(mut current), _) => unsafe {
1318                ptr::write(
1319                    ptr,
1320                    Node {
1321                        element: item,
1322                        preceding: Some(Preceding::Parent(current)),
1323                        child: None,
1324                        next: current.as_ref().next,
1325                    },
1326                );
1327                let ptr = NonNull::new(ptr).unwrap_unchecked();
1328                if let Some(mut child) = current.as_ref().child {
1329                    child.as_mut().preceding = Some(Preceding::Previous(ptr));
1330                }
1331                current.as_mut().child = Some(ptr);
1332            },
1333            (None, Some(preceding)) => match preceding {
1334                Preceding::Parent(mut parent) => unsafe {
1335                    ptr::write(
1336                        ptr,
1337                        Node {
1338                            element: item,
1339                            preceding: Some(Preceding::Parent(parent)),
1340                            child: None,
1341                            next: None,
1342                        },
1343                    );
1344                    let ptr = NonNull::new(ptr).unwrap_unchecked();
1345                    parent.as_mut().child = Some(ptr);
1346                    self.current = Some(ptr);
1347                },
1348                Preceding::Previous(mut previous) => unsafe {
1349                    ptr::write(
1350                        ptr,
1351                        Node {
1352                            element: item,
1353                            preceding: Some(Preceding::Previous(previous)),
1354                            child: None,
1355                            next: None,
1356                        },
1357                    );
1358                    let ptr = NonNull::new(ptr).unwrap_unchecked();
1359                    previous.as_mut().next = Some(ptr);
1360                    self.current = Some(ptr);
1361                },
1362            },
1363            (None, None) => unsafe {
1364                ptr::write(
1365                    ptr,
1366                    Node {
1367                        element: item,
1368                        preceding: None,
1369                        child: None,
1370                        next: None,
1371                    },
1372                );
1373                let ptr = NonNull::new(ptr).unwrap_unchecked();
1374                self.current = Some(ptr);
1375                *self.root = Some(ptr);
1376            },
1377        }
1378    }
1379
1380    /// Removes the current node.
1381    ///
1382    /// When removing a node with a child node, the child node is removed.
1383    pub fn remove_current(&mut self) {
1384        match (self.current, self.preceding) {
1385            (Some(current), Some(preceding)) => unsafe {
1386                self.current = current.as_ref().next;
1387                match preceding {
1388                    Preceding::Parent(mut parent) => {
1389                        parent.as_mut().child = current.as_ref().next;
1390                    }
1391                    Preceding::Previous(mut previous) => {
1392                        previous.as_mut().next = current.as_ref().next;
1393                    }
1394                }
1395                if let Some(mut next) = current.as_ref().next {
1396                    next.as_mut().preceding = Some(preceding);
1397                }
1398
1399                // Deallocate all child nodes of the old current node.
1400                if let Some(child) = current.as_ref().child {
1401                    // TODO This will never be greater than 2 elements, do something more
1402                    // performant.
1403                    let mut stack = vec![child];
1404                    while let Some(next) = stack.pop() {
1405                        if let Some(child) = next.as_ref().child {
1406                            stack.push(child);
1407                        }
1408                        if let Some(next) = next.as_ref().next {
1409                            stack.push(next);
1410                        }
1411                        alloc::dealloc(next.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
1412                    }
1413                }
1414                alloc::dealloc(current.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
1415            },
1416            (Some(current), None) => unsafe {
1417                self.current = current.as_ref().next;
1418                *self.root = current.as_ref().next;
1419                if let Some(mut next) = current.as_ref().next {
1420                    next.as_mut().preceding = None;
1421                }
1422
1423                // Deallocate all child nodes of the old current node.
1424                if let Some(child) = current.as_ref().child {
1425                    // TODO This will never be greater than 2 elements, do something more
1426                    // performant.
1427                    let mut stack = vec![child];
1428                    while let Some(next) = stack.pop() {
1429                        if let Some(child) = next.as_ref().child {
1430                            stack.push(child);
1431                        }
1432                        if let Some(next) = next.as_ref().next {
1433                            stack.push(next);
1434                        }
1435                        alloc::dealloc(next.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
1436                    }
1437                }
1438                alloc::dealloc(current.as_ptr().cast(), alloc::Layout::new::<Node<T>>());
1439            },
1440            (None, _) => {}
1441        }
1442    }
1443
1444    /// Moves the children of the current element to next elements.
1445    pub fn flatten(&self) {
1446        unsafe {
1447            if let Some(mut current) = self.current {
1448                if let Some(mut child) = current.as_ref().child {
1449                    let mut last_child = child;
1450                    while let Some(next_child) = last_child.as_ref().next {
1451                        last_child = next_child;
1452                    }
1453                    if let Some(mut next) = current.as_mut().next {
1454                        next.as_mut().preceding = Some(Preceding::Previous(last_child));
1455                        last_child.as_mut().next = Some(next);
1456                    }
1457                    current.as_mut().next = Some(child);
1458                    child.as_mut().preceding = Some(Preceding::Previous(current));
1459                    current.as_mut().child = None;
1460                }
1461            }
1462        }
1463    }
1464}
1465
1466/// A statement in an AST may have:
1467/// - A previous statement
1468/// - A next statement
1469/// - A child statement
1470/// - A parent statement
1471///
1472/// Consider the example:
1473/// ```text
1474/// x = -10
1475/// loop
1476///     x = x + 1
1477///     if x
1478///         break
1479/// x = 2
1480/// ```
1481/// this can be represented as:
1482/// ```text
1483/// ┌──────────┐
1484/// │x = -10   │
1485/// └──────────┘
1486/// │
1487/// ┌──────────┐
1488/// │loop      │
1489/// └──────────┘
1490/// │           ╲
1491/// ┌──────────┐ ┌─────────┐
1492/// │x = 2     │ │x = x + 1│
1493/// └──────────┘ └─────────┘
1494///              │
1495///              ┌─────────┐
1496///              │if x     │
1497///              └─────────┘
1498///                         ╲
1499///                          ┌─────────┐
1500///                          │break    │
1501///                          └─────────┘
1502/// ```
1503/// this is a simplified tree structure.
1504#[derive(Debug, Clone, Copy, Eq, PartialEq)]
1505pub enum Preceding<T> {
1506    /// A parent element.
1507    Parent(T),
1508    /// A previous element.
1509    Previous(T),
1510}
1511#[allow(dead_code)]
1512impl<T> Preceding<T> {
1513    /// Returns if self is a parent.
1514    pub fn is_parent(&self) -> bool {
1515        match self {
1516            Self::Parent(_) => true,
1517            Self::Previous(_) => false,
1518        }
1519    }
1520    /// Returns if self is a previous.
1521    pub fn is_previous(&self) -> bool {
1522        match self {
1523            Self::Parent(_) => false,
1524            Self::Previous(_) => true,
1525        }
1526    }
1527    /// Unwrap to a parent.
1528    pub fn parent(self) -> Option<T> {
1529        match self {
1530            Self::Parent(x) => Some(x),
1531            Self::Previous(_) => None,
1532        }
1533    }
1534    /// Unwraps to a previous.
1535    pub fn previous(self) -> Option<T> {
1536        match self {
1537            Self::Parent(_) => None,
1538            Self::Previous(x) => Some(x),
1539        }
1540    }
1541    /// Unwraps.
1542    pub fn unwrap(self) -> T {
1543        match self {
1544            Self::Previous(x) | Self::Parent(x) => x,
1545        }
1546    }
1547    /// Returns `Preceding<&T>`.
1548    pub fn as_ref(&self) -> Preceding<&T> {
1549        match self {
1550            Self::Parent(x) => Preceding::Parent(x),
1551            Self::Previous(x) => Preceding::Previous(x),
1552        }
1553    }
1554    /// Returns `Preceding<&mut T>`.
1555    pub fn as_mut(&mut self) -> Preceding<&mut T> {
1556        match self {
1557            Self::Parent(x) => Preceding::Parent(x),
1558            Self::Previous(x) => Preceding::Previous(x),
1559        }
1560    }
1561    /// Maps to `Preceding<P>`.
1562    pub fn map<P>(self, f: impl Fn(T) -> P) -> Preceding<P> {
1563        match self {
1564            Self::Previous(x) => Preceding::Previous(f(x)),
1565            Self::Parent(x) => Preceding::Parent(f(x)),
1566        }
1567    }
1568}
1569
1570/// A tree node.
1571#[derive(Debug)]
1572pub struct Node<T> {
1573    /// The element.
1574    pub element: T,
1575    /// The preceding node.
1576    pub preceding: Option<NodePredecessor<T>>,
1577    /// The child node.
1578    pub child: Option<NonNull<Node<T>>>,
1579    /// The next node.
1580    pub next: Option<NonNull<Node<T>>>,
1581}
1582
1583#[cfg(test)]
1584mod tests {
1585    use super::*;
1586
1587    #[test]
1588    fn display() {
1589        let mut tree = SyntaxTree::<u8>::default();
1590        let mut cursor = tree.cursor_mut();
1591        assert_eq!(cursor.peek_preceding(), None);
1592        assert_eq!(cursor.current(), None);
1593        assert_eq!(cursor.peek_next(), None);
1594        assert_eq!(cursor.peek_child(), None);
1595
1596        cursor.insert_next(0);
1597        assert_eq!(cursor.peek_preceding(), None);
1598        assert_eq!(cursor.current(), Some(&0));
1599        assert_eq!(cursor.peek_next(), None);
1600        assert_eq!(cursor.peek_child(), None);
1601
1602        cursor.insert_child(1);
1603        assert_eq!(cursor.peek_preceding(), None);
1604        assert_eq!(cursor.current(), Some(&0));
1605        assert_eq!(cursor.peek_next(), None);
1606        assert_eq!(cursor.peek_child(), Some(&1));
1607
1608        cursor.move_child();
1609        assert_eq!(cursor.peek_preceding(), Some(Preceding::Parent(&0)));
1610        assert_eq!(cursor.current(), Some(&1));
1611        assert_eq!(cursor.peek_next(), None);
1612        assert_eq!(cursor.peek_child(), None);
1613
1614        cursor.insert_next(2);
1615        assert_eq!(cursor.peek_preceding(), Some(Preceding::Parent(&0)));
1616        assert_eq!(cursor.current(), Some(&1));
1617        assert_eq!(cursor.peek_next(), Some(&2));
1618        assert_eq!(cursor.peek_child(), None);
1619
1620        cursor.move_next();
1621        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1622        assert_eq!(cursor.current(), Some(&2));
1623        assert_eq!(cursor.peek_next(), None);
1624        assert_eq!(cursor.peek_child(), None);
1625
1626        cursor.insert_child(3);
1627        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1628        assert_eq!(cursor.current(), Some(&2));
1629        assert_eq!(cursor.peek_next(), None);
1630        assert_eq!(cursor.peek_child(), Some(&3));
1631
1632        cursor.move_parent();
1633        assert_eq!(cursor.peek_preceding(), None);
1634        assert_eq!(cursor.current(), Some(&0));
1635        assert_eq!(cursor.peek_next(), None);
1636        assert_eq!(cursor.peek_child(), Some(&1));
1637
1638        cursor.insert_next(4);
1639        assert_eq!(cursor.peek_preceding(), None);
1640        assert_eq!(cursor.current(), Some(&0));
1641        assert_eq!(cursor.peek_next(), Some(&4));
1642        assert_eq!(cursor.peek_child(), Some(&1));
1643
1644        cursor.move_next();
1645        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&0)));
1646        assert_eq!(cursor.current(), Some(&4));
1647        assert_eq!(cursor.peek_next(), None);
1648        assert_eq!(cursor.peek_child(), None);
1649
1650        cursor.insert_child(5);
1651        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&0)));
1652        assert_eq!(cursor.current(), Some(&4));
1653        assert_eq!(cursor.peek_next(), None);
1654        assert_eq!(cursor.peek_child(), Some(&5));
1655
1656        cursor.move_child();
1657        assert_eq!(cursor.peek_preceding(), Some(Preceding::Parent(&4)));
1658        assert_eq!(cursor.current(), Some(&5));
1659        assert_eq!(cursor.peek_next(), None);
1660        assert_eq!(cursor.peek_child(), None);
1661
1662        cursor.insert_next(6);
1663        assert_eq!(cursor.peek_preceding(), Some(Preceding::Parent(&4)));
1664        assert_eq!(cursor.current(), Some(&5));
1665        assert_eq!(cursor.peek_next(), Some(&6));
1666        assert_eq!(cursor.peek_child(), None);
1667
1668        cursor.move_next();
1669        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&5)));
1670        assert_eq!(cursor.current(), Some(&6));
1671        assert_eq!(cursor.peek_next(), None);
1672        assert_eq!(cursor.peek_child(), None);
1673
1674        cursor.insert_child(7);
1675        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&5)));
1676        assert_eq!(cursor.current(), Some(&6));
1677        assert_eq!(cursor.peek_next(), None);
1678        assert_eq!(cursor.peek_child(), Some(&7));
1679
1680        let mut iter = tree.iter();
1681        assert_eq!(iter.next(), Some(Element { item: &0, depth: 0 }));
1682        assert_eq!(iter.next(), Some(Element { item: &1, depth: 1 }));
1683        assert_eq!(iter.next(), Some(Element { item: &2, depth: 1 }));
1684        assert_eq!(iter.next(), Some(Element { item: &3, depth: 2 }));
1685        assert_eq!(iter.next(), Some(Element { item: &4, depth: 0 }));
1686        assert_eq!(iter.next(), Some(Element { item: &5, depth: 1 }));
1687        assert_eq!(iter.next(), Some(Element { item: &6, depth: 1 }));
1688        assert_eq!(iter.next(), Some(Element { item: &7, depth: 2 }));
1689
1690        let expected = format!(
1691            "\
1692            0\n\
1693            {INDENT}1\n\
1694            {INDENT}2\n\
1695            {INDENT}{INDENT}3\n\
1696            4\n\
1697            {INDENT}5\n\
1698            {INDENT}6\n\
1699            {INDENT}{INDENT}7\n\
1700        "
1701        );
1702        assert_eq!(tree.to_string(), expected);
1703    }
1704
1705    #[test]
1706    fn insert_preceding() {
1707        let mut tree = SyntaxTree::<u8>::default();
1708        let mut cursor = tree.cursor_mut();
1709        assert_eq!(cursor.peek_preceding(), None);
1710        assert_eq!(cursor.current(), None);
1711        assert_eq!(cursor.peek_next(), None);
1712
1713        cursor.insert_preceding(1);
1714        assert_eq!(cursor.peek_preceding(), None);
1715        assert_eq!(cursor.current(), Some(&1));
1716        assert_eq!(cursor.peek_next(), None);
1717
1718        cursor.insert_preceding(2);
1719        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1720        assert_eq!(cursor.current(), Some(&1));
1721        assert_eq!(cursor.peek_next(), None);
1722
1723        cursor.move_next();
1724        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1725        assert_eq!(cursor.current(), None);
1726        assert_eq!(cursor.peek_next(), None);
1727
1728        cursor.move_next();
1729        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1730        assert_eq!(cursor.current(), None);
1731        assert_eq!(cursor.peek_next(), None);
1732
1733        cursor.move_preceding();
1734        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1735        assert_eq!(cursor.current(), Some(&1));
1736        assert_eq!(cursor.peek_next(), None);
1737
1738        cursor.move_preceding();
1739        assert_eq!(cursor.peek_preceding(), None);
1740        assert_eq!(cursor.current(), Some(&2));
1741        assert_eq!(cursor.peek_next(), Some(&1));
1742
1743        cursor.insert_preceding(3);
1744        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&3)));
1745        assert_eq!(cursor.current(), Some(&2));
1746        assert_eq!(cursor.peek_next(), Some(&1));
1747
1748        cursor.move_next();
1749        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1750        assert_eq!(cursor.current(), Some(&1));
1751        assert_eq!(cursor.peek_next(), None);
1752
1753        cursor.move_next();
1754        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1755        assert_eq!(cursor.current(), None);
1756        assert_eq!(cursor.peek_next(), None);
1757
1758        cursor.move_next();
1759        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1760        assert_eq!(cursor.current(), None);
1761        assert_eq!(cursor.peek_next(), None);
1762
1763        cursor.move_preceding();
1764        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1765        assert_eq!(cursor.current(), Some(&1));
1766        assert_eq!(cursor.peek_next(), None);
1767
1768        cursor.move_preceding();
1769        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&3)));
1770        assert_eq!(cursor.current(), Some(&2));
1771        assert_eq!(cursor.peek_next(), Some(&1));
1772
1773        cursor.move_preceding();
1774        assert_eq!(cursor.peek_preceding(), None);
1775        assert_eq!(cursor.current(), Some(&3));
1776        assert_eq!(cursor.peek_next(), Some(&2));
1777
1778        cursor.move_preceding();
1779        assert_eq!(cursor.peek_preceding(), None);
1780        assert_eq!(cursor.current(), Some(&3));
1781        assert_eq!(cursor.peek_next(), Some(&2));
1782    }
1783
1784    #[test]
1785    fn insert_next() {
1786        let mut tree = SyntaxTree::<u8>::default();
1787        let mut cursor = tree.cursor_mut();
1788        assert_eq!(cursor.peek_preceding(), None);
1789        assert_eq!(cursor.current(), None);
1790        assert_eq!(cursor.peek_next(), None);
1791
1792        cursor.insert_next(1);
1793        assert_eq!(cursor.peek_preceding(), None);
1794        assert_eq!(cursor.current(), Some(&1));
1795        assert_eq!(cursor.peek_next(), None);
1796
1797        cursor.insert_next(2);
1798        assert_eq!(cursor.peek_preceding(), None);
1799        assert_eq!(cursor.current(), Some(&1));
1800        assert_eq!(cursor.peek_next(), Some(&2));
1801
1802        cursor.move_next();
1803        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1804        assert_eq!(cursor.current(), Some(&2));
1805        assert_eq!(cursor.peek_next(), None);
1806
1807        cursor.move_next();
1808        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1809        assert_eq!(cursor.current(), None);
1810        assert_eq!(cursor.peek_next(), None);
1811
1812        cursor.move_preceding();
1813        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1814        assert_eq!(cursor.current(), Some(&2));
1815        assert_eq!(cursor.peek_next(), None);
1816
1817        cursor.move_preceding();
1818        assert_eq!(cursor.peek_preceding(), None);
1819        assert_eq!(cursor.current(), Some(&1));
1820        assert_eq!(cursor.peek_next(), Some(&2));
1821
1822        cursor.insert_next(3);
1823        assert_eq!(cursor.peek_preceding(), None);
1824        assert_eq!(cursor.current(), Some(&1));
1825        assert_eq!(cursor.peek_next(), Some(&3));
1826
1827        cursor.move_next();
1828        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1829        assert_eq!(cursor.current(), Some(&3));
1830        assert_eq!(cursor.peek_next(), Some(&2));
1831
1832        cursor.move_next();
1833        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&3)));
1834        assert_eq!(cursor.current(), Some(&2));
1835        assert_eq!(cursor.peek_next(), None);
1836
1837        cursor.move_next();
1838        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1839        assert_eq!(cursor.current(), None);
1840        assert_eq!(cursor.peek_next(), None);
1841
1842        cursor.move_next();
1843        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
1844        assert_eq!(cursor.current(), None);
1845        assert_eq!(cursor.peek_next(), None);
1846
1847        cursor.move_preceding();
1848        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&3)));
1849        assert_eq!(cursor.current(), Some(&2));
1850        assert_eq!(cursor.peek_next(), None);
1851
1852        cursor.move_preceding();
1853        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1854        assert_eq!(cursor.current(), Some(&3));
1855        assert_eq!(cursor.peek_next(), Some(&2));
1856
1857        cursor.move_preceding();
1858        assert_eq!(cursor.peek_preceding(), None);
1859        assert_eq!(cursor.current(), Some(&1));
1860        assert_eq!(cursor.peek_next(), Some(&3));
1861
1862        cursor.move_preceding();
1863        assert_eq!(cursor.peek_preceding(), None);
1864        assert_eq!(cursor.current(), Some(&1));
1865        assert_eq!(cursor.peek_next(), Some(&3));
1866    }
1867
1868    #[test]
1869    fn remove() {
1870        let mut tree = SyntaxTree::<u8>::default();
1871        let mut cursor = tree.cursor_mut();
1872        assert_eq!(cursor.peek_preceding(), None);
1873        assert_eq!(cursor.current(), None);
1874        assert_eq!(cursor.peek_next(), None);
1875
1876        cursor.insert_next(1);
1877        assert_eq!(cursor.peek_preceding(), None);
1878        assert_eq!(cursor.current(), Some(&1));
1879        assert_eq!(cursor.peek_next(), None);
1880
1881        cursor.insert_next(2);
1882        assert_eq!(cursor.peek_preceding(), None);
1883        assert_eq!(cursor.current(), Some(&1));
1884        assert_eq!(cursor.peek_next(), Some(&2));
1885
1886        cursor.insert_next(3);
1887        assert_eq!(cursor.peek_preceding(), None);
1888        assert_eq!(cursor.current(), Some(&1));
1889        assert_eq!(cursor.peek_next(), Some(&3));
1890
1891        cursor.move_next();
1892        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1893        assert_eq!(cursor.current(), Some(&3));
1894        assert_eq!(cursor.peek_next(), Some(&2));
1895
1896        cursor.move_next();
1897        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&3)));
1898        assert_eq!(cursor.current(), Some(&2));
1899        assert_eq!(cursor.peek_next(), None);
1900
1901        cursor.move_preceding();
1902        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
1903        assert_eq!(cursor.current(), Some(&3));
1904        assert_eq!(cursor.peek_next(), Some(&2));
1905
1906        cursor.move_preceding();
1907        assert_eq!(cursor.peek_preceding(), None);
1908        assert_eq!(cursor.current(), Some(&1));
1909        assert_eq!(cursor.peek_next(), Some(&3));
1910
1911        cursor.remove_current();
1912        assert_eq!(cursor.peek_preceding(), None);
1913        assert_eq!(cursor.current(), Some(&3));
1914        assert_eq!(cursor.peek_next(), Some(&2));
1915
1916        cursor.remove_current();
1917        assert_eq!(cursor.peek_preceding(), None);
1918        assert_eq!(cursor.current(), Some(&2));
1919        assert_eq!(cursor.peek_next(), None);
1920    }
1921
1922    #[test]
1923    fn clone() {
1924        let mut tree = SyntaxTree::<u8>::default();
1925        let mut cursor = tree.cursor_mut();
1926        cursor.insert_next(1);
1927        cursor.insert_preceding(2);
1928        cursor.insert_next(3);
1929        cursor.insert_preceding(4);
1930        cursor.insert_next(5);
1931
1932        let tree_clone = tree.clone();
1933        tree.iter().zip(tree_clone.iter()).all(|(a, b)| a == b);
1934    }
1935
1936    #[test]
1937    fn indexing() {
1938        let mut tree = SyntaxTree::<u8>::default();
1939        let mut iter = tree.iter();
1940        assert_eq!(iter.next(), None);
1941        assert_eq!(iter.next(), None);
1942        assert_eq!(tree.len(), 0);
1943
1944        tree.cursor_mut().insert_next(1);
1945        let mut iter = tree.iter();
1946        assert_eq!(iter.next(), Some(Element { item: &1, depth: 0 }));
1947        assert_eq!(iter.next(), None);
1948        assert_eq!(iter.next(), None);
1949        assert_eq!(tree.len(), 1);
1950
1951        tree.cursor_mut().insert_preceding(2);
1952        let mut iter = tree.iter();
1953        assert_eq!(iter.next(), Some(Element { item: &2, depth: 0 }));
1954        assert_eq!(iter.next(), Some(Element { item: &1, depth: 0 }));
1955        assert_eq!(iter.next(), None);
1956        assert_eq!(iter.next(), None);
1957        assert_eq!(tree.len(), 2);
1958
1959        tree.cursor_mut().insert_next(3);
1960        let mut iter = tree.iter();
1961        assert_eq!(iter.next(), Some(Element { item: &2, depth: 0 }));
1962        assert_eq!(iter.next(), Some(Element { item: &3, depth: 0 }));
1963        assert_eq!(iter.next(), Some(Element { item: &1, depth: 0 }));
1964        assert_eq!(iter.next(), None);
1965        assert_eq!(iter.next(), None);
1966        assert_eq!(tree.len(), 3);
1967
1968        tree.cursor_mut().insert_preceding(4);
1969        let mut iter = tree.iter();
1970        assert_eq!(iter.next(), Some(Element { item: &4, depth: 0 }));
1971        assert_eq!(iter.next(), Some(Element { item: &2, depth: 0 }));
1972        assert_eq!(iter.next(), Some(Element { item: &3, depth: 0 }));
1973        assert_eq!(iter.next(), Some(Element { item: &1, depth: 0 }));
1974        assert_eq!(iter.next(), None);
1975        assert_eq!(iter.next(), None);
1976        assert_eq!(tree.len(), 4);
1977
1978        tree.cursor_mut().insert_next(5);
1979        let mut iter = tree.iter();
1980        assert_eq!(iter.next(), Some(Element { item: &4, depth: 0 }));
1981        assert_eq!(iter.next(), Some(Element { item: &5, depth: 0 }));
1982        assert_eq!(iter.next(), Some(Element { item: &2, depth: 0 }));
1983        assert_eq!(iter.next(), Some(Element { item: &3, depth: 0 }));
1984        assert_eq!(iter.next(), Some(Element { item: &1, depth: 0 }));
1985        assert_eq!(iter.next(), None);
1986        assert_eq!(tree.len(), 5);
1987    }
1988
1989    #[test]
1990    fn move_parent() {
1991        let mut tree_one = SyntaxTree::<u8>::default();
1992        let mut cursor = tree_one.cursor_mut();
1993        assert_eq!(cursor.peek_preceding(), None);
1994        assert_eq!(cursor.current(), None);
1995        assert_eq!(cursor.peek_next(), None);
1996
1997        cursor.insert_next(1);
1998        assert_eq!(cursor.peek_preceding(), None);
1999        assert_eq!(cursor.current(), Some(&1));
2000        assert_eq!(cursor.peek_next(), None);
2001
2002        cursor.insert_next(2);
2003        assert_eq!(cursor.peek_preceding(), None);
2004        assert_eq!(cursor.current(), Some(&1));
2005        assert_eq!(cursor.peek_next(), Some(&2));
2006
2007        cursor.move_next();
2008        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
2009        assert_eq!(cursor.current(), Some(&2));
2010        assert_eq!(cursor.peek_next(), None);
2011
2012        cursor.insert_next(3);
2013        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&1)));
2014        assert_eq!(cursor.current(), Some(&2));
2015        assert_eq!(cursor.peek_next(), Some(&3));
2016
2017        cursor.move_next();
2018        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
2019        assert_eq!(cursor.current(), Some(&3));
2020        assert_eq!(cursor.peek_next(), None);
2021
2022        cursor.move_child();
2023        assert_eq!(cursor.peek_preceding(), Some(Preceding::Parent(&3)));
2024        assert_eq!(cursor.current(), None);
2025        assert_eq!(cursor.peek_next(), None);
2026
2027        cursor.insert_next(4);
2028        assert_eq!(cursor.peek_preceding(), Some(Preceding::Parent(&3)));
2029        assert_eq!(cursor.current(), Some(&4));
2030        assert_eq!(cursor.peek_next(), None);
2031
2032        cursor.move_next();
2033        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&4)));
2034        assert_eq!(cursor.current(), None);
2035        assert_eq!(cursor.peek_next(), None);
2036
2037        cursor.insert_next(5);
2038        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&4)));
2039        assert_eq!(cursor.current(), Some(&5));
2040        assert_eq!(cursor.peek_next(), None);
2041
2042        cursor.move_next();
2043        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&5)));
2044        assert_eq!(cursor.current(), None);
2045        assert_eq!(cursor.peek_next(), None);
2046
2047        cursor.insert_next(6);
2048        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&5)));
2049        assert_eq!(cursor.current(), Some(&6));
2050        assert_eq!(cursor.peek_next(), None);
2051
2052        assert_eq!(cursor.move_parent(), true);
2053        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
2054        assert_eq!(cursor.current(), Some(&3));
2055        assert_eq!(cursor.peek_next(), None);
2056
2057        assert_eq!(cursor.move_parent(), false);
2058        assert_eq!(cursor.peek_preceding(), Some(Preceding::Previous(&2)));
2059        assert_eq!(cursor.current(), Some(&3));
2060        assert_eq!(cursor.peek_next(), None);
2061    }
2062}