flow-types 0.1.0-rc.5

The Flow declaration model with no values: types, declarations and their identities, record and enum shapes, and which types decoding may build.
Documentation
//! Trees nested however deep, walked on a native stack of bounded size.
//!
//! A type's depth is not bounded, and neither is that of anything written
//! after one, such as its description or its schema. [`Nested`] walks any
//! such tree the same way: the first few levels by native recursion, so a
//! shallow tree, the common one, is walked with no allocation of the walk's
//! own, and anything deeper over stacks on the heap.

/// How many levels of a tree a walk over it recurses natively before it goes
/// on over a stack on the heap: few enough that their frames, a few KiB each
/// in an unoptimized build, fit a small thread's stack, and as deep as most
/// types written in source nest.
const NATIVE_DEPTH: usize = 8;

/// A tree whose nodes each hold their parts, nested to no bound.
pub trait Nested: Sized {
    /// A node with no parts, left in a part's place when it is moved out.
    const LEAF: Self;

    /// The nodes `self` is made of, in order.
    fn parts(&self) -> impl DoubleEndedIterator<Item = &Self>;

    /// The parts only `self` holds, in [`Nested::parts`] order, for moving
    /// out: none of those it shares with another tree.
    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Self>;

    /// What `fold` makes of `self`, built bottom-up.
    ///
    /// Each node is offered to [`Fold::open`] once, in pre-order, its parts
    /// in [`Nested::parts`] order, and a node it opens is joined from what
    /// its parts make. It takes time linear in the nodes opened, and the
    /// native stack stays bounded however deep `self` is.
    fn fold<F: Fold<Self>>(&self, fold: &mut F) -> F::Made {
        fold_within(self, fold, NATIVE_DEPTH)
    }

    /// Whether `self` and `other` are alike node by node, by `same_node`,
    /// which says whether two nodes are alike on their own, with as many
    /// parts: with each node's count of parts, pre-order spells the tree.
    fn same_tree(&self, other: &Self, mut same_node: impl FnMut(&Self, &Self) -> bool) -> bool {
        same_within(self, other, &mut same_node, NATIVE_DEPTH)
    }

    /// Frees each part only `self` holds that has parts of its own, leaving
    /// [`Nested::LEAF`] in its place: what dropping `self` does first, so a
    /// tree nested however deep drops on a native stack of fixed size.
    fn free_parts(&mut self) {
        free_within(self, NATIVE_DEPTH);
    }
}

/// A walk [`Nested::fold`] makes something of a tree of `N` with.
pub trait Fold<N>: Sized {
    /// What it makes of each node.
    type Made;

    /// What `node` makes without opening it, or `None` to open it.
    fn open(&mut self, node: &N) -> Option<Self::Made>;

    /// What the opened `node` makes, with `part` making what each of its
    /// parts makes. It calls `part` once for each of [`Nested::parts`], in
    /// order, unless it stops early.
    fn join(&mut self, node: &N, part: impl FnMut(&mut Self, &N) -> Self::Made) -> Self::Made;
}

/// [`Nested::fold`], recursing natively for at most `room` more levels.
fn fold_within<N: Nested, F: Fold<N>>(node: &N, fold: &mut F, room: usize) -> F::Made {
    if let Some(made) = fold.open(node) {
        return made;
    }
    match room.checked_sub(1) {
        Some(room) => fold.join(node, |fold, part| fold_within(part, fold, room)),
        None => fold_on_heap(node, fold),
    }
}

/// [`Nested::fold`] of a node [`Fold::open`] has declined, over stacks on
/// the heap: memory linear in the nodes waiting to be opened or joined.
fn fold_on_heap<N: Nested, F: Fold<N>>(node: &N, fold: &mut F) -> F::Made {
    enum Work<'t, N> {
        Open(&'t N),
        Join(&'t N, usize),
    }
    let mut work: Vec<Work<'_, N>> = node.parts().rev().map(Work::Open).collect();
    let mut made = Vec::new();
    while let Some(next) = work.pop() {
        match next {
            Work::Open(node) => {
                if let Some(value) = fold.open(node) {
                    made.push(value);
                } else {
                    work.push(Work::Join(node, node.parts().count()));
                    work.extend(node.parts().rev().map(Work::Open));
                }
            }
            Work::Join(node, count) => {
                let value = join_made(fold, node, made.drain(made.len() - count..));
                made.push(value);
            }
        }
    }
    join_made(fold, node, made.drain(..))
}

/// `fold`'s join of `node` from `made`, what its parts made, in order.
fn join_made<N, F: Fold<N>>(
    fold: &mut F,
    node: &N,
    mut made: impl Iterator<Item = F::Made>,
) -> F::Made {
    fold.join(node, |_, _| {
        made.next()
            .expect("a join takes each of its node's parts once")
    })
}

/// Every node of `node` in pre-order, its parts in [`Nested::parts`] order.
/// A node's first part is visited next and only its later parts wait on a
/// stack on the heap, so a tree whose nodes have at most one part each is
/// walked without allocating.
fn walk<N: Nested>(node: &N) -> impl Iterator<Item = &N> {
    let mut next = Some(node);
    let mut later = Vec::new();
    std::iter::from_fn(move || {
        let node = next.take().or_else(|| later.pop())?;
        let mut parts = node.parts();
        next = parts.next();
        later.extend(parts.rev());
        Some(node)
    })
}

/// [`Nested::same_tree`], comparing natively for at most `room` more levels
/// and node by node in pre-order past them.
fn same_within<N: Nested>(
    node: &N,
    other: &N,
    same_node: &mut impl FnMut(&N, &N) -> bool,
    room: usize,
) -> bool {
    if !same_node(node, other) {
        return false;
    }
    let Some(room) = room.checked_sub(1) else {
        let mut others = walk(other);
        return walk(node).all(|node| others.next().is_some_and(|other| same_node(node, other)));
    };
    node.parts()
        .zip(other.parts())
        .all(|(part, other)| same_within(part, other, same_node, room))
}

/// [`Nested::free_parts`], recursing natively for at most `room` more
/// levels and over a stack on the heap past them.
fn free_within<N: Nested>(node: &mut N, room: usize) {
    for part in node.parts_mut() {
        if part.parts().next().is_none() {
            continue;
        }
        let mut nested = std::mem::replace(part, N::LEAF);
        if let Some(room) = room.checked_sub(1) {
            free_within(&mut nested, room);
        } else {
            let mut held = vec![nested];
            while let Some(mut node) = held.pop() {
                for part in node.parts_mut() {
                    if part.parts().next().is_some() {
                        held.push(std::mem::replace(part, N::LEAF));
                    }
                }
            }
        }
    }
}