Skip to main content

flow_types/
nested.rs

1//! Trees nested however deep, walked on a native stack of bounded size.
2//!
3//! A type's depth is not bounded, and neither is that of anything written
4//! after one, such as its description or its schema. [`Nested`] walks any
5//! such tree the same way: the first few levels by native recursion, so a
6//! shallow tree, the common one, is walked with no allocation of the walk's
7//! own, and anything deeper over stacks on the heap.
8
9/// How many levels of a tree a walk over it recurses natively before it goes
10/// on over a stack on the heap: few enough that their frames, a few KiB each
11/// in an unoptimized build, fit a small thread's stack, and as deep as most
12/// types written in source nest.
13const NATIVE_DEPTH: usize = 8;
14
15/// A tree whose nodes each hold their parts, nested to no bound.
16pub trait Nested: Sized {
17    /// A node with no parts, left in a part's place when it is moved out.
18    const LEAF: Self;
19
20    /// The nodes `self` is made of, in order.
21    fn parts(&self) -> impl DoubleEndedIterator<Item = &Self>;
22
23    /// The parts only `self` holds, in [`Nested::parts`] order, for moving
24    /// out: none of those it shares with another tree.
25    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Self>;
26
27    /// What `fold` makes of `self`, built bottom-up.
28    ///
29    /// Each node is offered to [`Fold::open`] once, in pre-order, its parts
30    /// in [`Nested::parts`] order, and a node it opens is joined from what
31    /// its parts make. It takes time linear in the nodes opened, and the
32    /// native stack stays bounded however deep `self` is.
33    fn fold<F: Fold<Self>>(&self, fold: &mut F) -> F::Made {
34        fold_within(self, fold, NATIVE_DEPTH)
35    }
36
37    /// Whether `self` and `other` are alike node by node, by `same_node`,
38    /// which says whether two nodes are alike on their own, with as many
39    /// parts: with each node's count of parts, pre-order spells the tree.
40    fn same_tree(&self, other: &Self, mut same_node: impl FnMut(&Self, &Self) -> bool) -> bool {
41        same_within(self, other, &mut same_node, NATIVE_DEPTH)
42    }
43
44    /// Frees each part only `self` holds that has parts of its own, leaving
45    /// [`Nested::LEAF`] in its place: what dropping `self` does first, so a
46    /// tree nested however deep drops on a native stack of fixed size.
47    fn free_parts(&mut self) {
48        free_within(self, NATIVE_DEPTH);
49    }
50}
51
52/// A walk [`Nested::fold`] makes something of a tree of `N` with.
53pub trait Fold<N>: Sized {
54    /// What it makes of each node.
55    type Made;
56
57    /// What `node` makes without opening it, or `None` to open it.
58    fn open(&mut self, node: &N) -> Option<Self::Made>;
59
60    /// What the opened `node` makes, with `part` making what each of its
61    /// parts makes. It calls `part` once for each of [`Nested::parts`], in
62    /// order, unless it stops early.
63    fn join(&mut self, node: &N, part: impl FnMut(&mut Self, &N) -> Self::Made) -> Self::Made;
64}
65
66/// [`Nested::fold`], recursing natively for at most `room` more levels.
67fn fold_within<N: Nested, F: Fold<N>>(node: &N, fold: &mut F, room: usize) -> F::Made {
68    if let Some(made) = fold.open(node) {
69        return made;
70    }
71    match room.checked_sub(1) {
72        Some(room) => fold.join(node, |fold, part| fold_within(part, fold, room)),
73        None => fold_on_heap(node, fold),
74    }
75}
76
77/// [`Nested::fold`] of a node [`Fold::open`] has declined, over stacks on
78/// the heap: memory linear in the nodes waiting to be opened or joined.
79fn fold_on_heap<N: Nested, F: Fold<N>>(node: &N, fold: &mut F) -> F::Made {
80    enum Work<'t, N> {
81        Open(&'t N),
82        Join(&'t N, usize),
83    }
84    let mut work: Vec<Work<'_, N>> = node.parts().rev().map(Work::Open).collect();
85    let mut made = Vec::new();
86    while let Some(next) = work.pop() {
87        match next {
88            Work::Open(node) => {
89                if let Some(value) = fold.open(node) {
90                    made.push(value);
91                } else {
92                    work.push(Work::Join(node, node.parts().count()));
93                    work.extend(node.parts().rev().map(Work::Open));
94                }
95            }
96            Work::Join(node, count) => {
97                let value = join_made(fold, node, made.drain(made.len() - count..));
98                made.push(value);
99            }
100        }
101    }
102    join_made(fold, node, made.drain(..))
103}
104
105/// `fold`'s join of `node` from `made`, what its parts made, in order.
106fn join_made<N, F: Fold<N>>(
107    fold: &mut F,
108    node: &N,
109    mut made: impl Iterator<Item = F::Made>,
110) -> F::Made {
111    fold.join(node, |_, _| {
112        made.next()
113            .expect("a join takes each of its node's parts once")
114    })
115}
116
117/// Every node of `node` in pre-order, its parts in [`Nested::parts`] order.
118/// A node's first part is visited next and only its later parts wait on a
119/// stack on the heap, so a tree whose nodes have at most one part each is
120/// walked without allocating.
121fn walk<N: Nested>(node: &N) -> impl Iterator<Item = &N> {
122    let mut next = Some(node);
123    let mut later = Vec::new();
124    std::iter::from_fn(move || {
125        let node = next.take().or_else(|| later.pop())?;
126        let mut parts = node.parts();
127        next = parts.next();
128        later.extend(parts.rev());
129        Some(node)
130    })
131}
132
133/// [`Nested::same_tree`], comparing natively for at most `room` more levels
134/// and node by node in pre-order past them.
135fn same_within<N: Nested>(
136    node: &N,
137    other: &N,
138    same_node: &mut impl FnMut(&N, &N) -> bool,
139    room: usize,
140) -> bool {
141    if !same_node(node, other) {
142        return false;
143    }
144    let Some(room) = room.checked_sub(1) else {
145        let mut others = walk(other);
146        return walk(node).all(|node| others.next().is_some_and(|other| same_node(node, other)));
147    };
148    node.parts()
149        .zip(other.parts())
150        .all(|(part, other)| same_within(part, other, same_node, room))
151}
152
153/// [`Nested::free_parts`], recursing natively for at most `room` more
154/// levels and over a stack on the heap past them.
155fn free_within<N: Nested>(node: &mut N, room: usize) {
156    for part in node.parts_mut() {
157        if part.parts().next().is_none() {
158            continue;
159        }
160        let mut nested = std::mem::replace(part, N::LEAF);
161        if let Some(room) = room.checked_sub(1) {
162            free_within(&mut nested, room);
163        } else {
164            let mut held = vec![nested];
165            while let Some(mut node) = held.pop() {
166                for part in node.parts_mut() {
167                    if part.parts().next().is_some() {
168                        held.push(std::mem::replace(part, N::LEAF));
169                    }
170                }
171            }
172        }
173    }
174}