← alloc

alloc/collections/list.kur

//! Singly linked lists stored in a caller-owned arena.
// Arena-backed singly linked list. Nodes live until the arena is
// destroyed; list handles are Copy when their fields are Copy.
//
// A list is persistent: `cons` shares the tail it is given, so extending a
// list never changes it, and a scope that adds bindings for a while and
// then goes back to the list it started from needs nothing undone. Nothing
// outside this module changes a cell once a list holds it: `List` and
// `Cons` are restricted, so no code elsewhere reaches a cell's `Ref`, and the
// one function here that writes a cell after making it, `ListBuilder!::push`,
// writes only cells of the list being built, which no one else holds until
// `finish` hands it out and consumes the builder.
//
// Every method that reads cells takes the context that lends the domain's
// capability by place (`&cx`, `core::cap::Access`), and one that makes
// cells takes one that lends the arena too (`alloc::arena::Allocate`).

use package as alloc;

use core::cap::{Access, Exclusive!};
use core::mem::Ref;
use alloc::arena::{Allocate, ref_in};
use core::option::{Option, Result};
use core::iter::Iterator;

/// A persistent singly linked list in an arena: a cell holding the first
/// element and the rest, or the empty list. Restricted: a list is made by
/// `empty`, `cons` and the functions that build one, and read through its
/// methods.
forall T, 'k.
enum List {
    Cell(Ref[Cons[T, 'k], 'k]),
    Empty,
}

/// One cell of a `List`: an element and the list after it.
forall T, 'k.
struct Cons {
    head: T,
    tail: List[T, 'k],
}

forall T, 'k.
impl List[T, 'k] {
    /// The list with no elements.
    fn empty() -> List[T, 'k] {
        List::Empty
    }

    /// Prepends `head`. The cell is arena-allocated, so it needs no free
    /// of its own; the whole arena is freed as a unit. `T` is `Copy`, as
    /// everything in an arena is.
    forall C, R where Copy[T], Allocate[C -> 'k, R].
    fn cons(self, &cx: C, head: T) -> List[T, 'k] {
        List::Cell.(ref_in(&cx, Cons.{ head, tail: self }))
    }

    /// Whether the list has no elements.
    fn is_empty(self) -> bool {
        match self {
            Empty => true,
            Cell(_) => false,
        }
    }
}

// Reading a cell at all needs `T` Copy: `Ref::copy` hands the whole
// `Cons[T, 'k]` out, head included, even to look only at its tail.
forall T, 'k where Copy[T].
impl List[T, 'k] {
    /// The first element, leaving the rest in `self`: a loop over a list
    /// whose body needs the context.
    forall C, R where Access[C -> 'k, R].
    fn pop(&self, &cx: C) -> Option[T] {
        match self {
            Empty => Option::None,
            Cell(r) => {
                let cell = r.copy(&cx);
                self = cell.tail;
                Option::Some.(cell.head)
            },
        }
    }

    /// How many elements the list has, counted cell by cell.
    forall C, R where Access[C -> 'k, R].
    fn len(self, &cx: C) -> usize {
        var rest = self;
        var count = 0usize;
        while !rest.is_empty() {
            rest = rest.tail(&cx);
            count = count + 1usize;
        }
        count
    }

    /// The elements of `self`, copied into new cells, followed by `other`.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn append(self, &cx: C, other: List[T, 'k]) -> List[T, 'k] {
        var out = ListBuilder!::new();
        var rest = self;
        var going = true;
        while going {
            match &rest.pop(&cx) {
                Some(x) => &out.push(&cx, x),
                None => {
                    going = false;
                },
            }
        }
        out.finish(&cx, other)
    }

    /// Reverses `self` onto the front of `acc`; a nonempty `acc` merges
    /// the list onto a running result.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn reverse(self, &cx: C, acc: List[T, 'k]) -> List[T, 'k] {
        var rest = self;
        var out = acc;
        var going = true;
        while going {
            let next = &rest.pop(&cx);
            match next {
                Some(x) => {
                    out = out.cons(&cx, x);
                },
                None => {
                    going = false;
                },
            }
        }
        out
    }

    /// The element at `index`, counting from 0, if the list is that long.
    forall C, R where Access[C -> 'k, R].
    fn nth(self, &cx: C, index: usize) -> Option[T] {
        self.skip(&cx, index).first(&cx)
    }

    /// The first element, or `None` when the list is empty.
    forall C, R where Access[C -> 'k, R].
    fn first(self, &cx: C) -> Option[T] {
        match self {
            Empty => Option::None,
            Cell(r) => Option::Some.(r.copy(&cx).head),
        }
    }

    /// The list without its first element (empty when it is empty).
    forall C, R where Access[C -> 'k, R].
    fn tail(self, &cx: C) -> List[T, 'k] {
        match self {
            Empty => List::Empty,
            Cell(r) => r.copy(&cx).tail,
        }
    }

    /// The list without its first `count` elements.
    forall C, R where Access[C -> 'k, R].
    fn skip(self, &cx: C, count: usize) -> List[T, 'k] {
        var rest = self;
        var left = count;
        while left > 0usize && !rest.is_empty() {
            rest = rest.tail(&cx);
            left = left - 1usize;
        }
        rest
    }

    /// The last element, or `None` when the list is empty.
    forall C, R where Access[C -> 'k, R].
    fn last(self, &cx: C) -> Option[T] {
        var rest = self;
        var found = Option::None;
        var going = true;
        while going {
            let next = &rest.pop(&cx);
            match next {
                Some(x) => {
                    found = Option::Some.(x);
                },
                None => {
                    going = false;
                },
            }
        }
        found
    }

    /// Whether both lists have the same length and `eq` holds pairwise, in
    /// order.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn eq_with(self, &cx: C, other: List[T, 'k], eq: closure[Env](&_: C, T, T) -> bool) -> bool {
        var a = self;
        var b = other;
        var same = true;
        var going = true;
        while same && going {
            let x = &a.pop(&cx);
            let y = &b.pop(&cx);
            match x {
                Some(u) => {
                    match y {
                        Some(v) => {
                            same = eq(&cx, u, v);
                        },
                        None => {
                            same = false;
                        },
                    }
                },
                None => {
                    same = y.is_none();
                    going = false;
                },
            }
        }
        same
    }

    // ------------------------------------------------------ combinators --
    // The computation goes to the list: each combinator lends its closure
    // the context, so the closure reads other data of the domain and
    // captures only `Copy` values. Searches stop at the first element that
    // decides them; results keep the list's order.

    /// The first element `f` returns a value for, and that value.
    forall U, Env, C, R where Access[C -> 'k, R], Copy[U], Copy[Env].
    fn find_map(self, &cx: C, f: closure[Env](&_: C, T) -> Option[U]) -> Option[U] {
        var rest = self;
        var found = Option::None;
        var going = true;
        while going {
            let next = &rest.pop(&cx);
            match next {
                Some(x) => {
                    found = f(&cx, x);
                    going = found.is_none();
                },
                None => {
                    going = false;
                },
            }
        }
        found
    }

    /// The first element `f` holds for.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn find(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> Option[T] {
        self.find_map(&cx, |&c, x| if f(&c, x) { Option::Some.(x) } else { Option::None })
    }

    /// Whether `f` holds for some element.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn any(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> bool {
        self.find(&cx, f).is_some()
    }

    /// Whether `f` holds for every element.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn all(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> bool {
        !self.any(&cx, |&c, x| !f(&c, x))
    }

    /// `f` on each element, for what it does through the context.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn each(self, &cx: C, f: closure[Env](&_: C, T) -> ()) {
        var rest = self;
        var going = true;
        while going {
            let next = &rest.pop(&cx);
            match next {
                Some(x) => f(&cx, x),
                None => {
                    going = false;
                },
            }
        }
    }

    /// How many elements `f` holds for.
    forall Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn count(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> usize {
        self.fold(&cx, 0usize, |&c, n, x| if f(&c, x) { n + 1usize } else { n })
    }

    /// `acc` through `f` with each element, head first.
    forall A, Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn fold(self, &cx: C, acc: A, f: closure[Env](&_: C, A, T) -> A) -> A {
        var rest = self;
        var acc = acc;
        var going = true;
        while going {
            let next = &rest.pop(&cx);
            match next {
                Some(x) => {
                    acc = f(&cx, acc, x);
                },
                None => {
                    going = false;
                },
            }
        }
        acc
    }

    /// `f` on each element, stopping at the first error.
    forall E, Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn try_each(self, &cx: C, f: closure[Env](&_: C, T) -> Result[(), E]) -> Result[(), E] {
        var rest = self;
        while true {
            match &rest.pop(&cx) {
                Some(x) => {
                    f(&cx, x)?;
                },
                None => {
                    return Result::Ok.(());
                },
            }
        }
        Result::Ok.(())
    }

    /// `acc` through `f` with each element, stopping at the first error.
    forall A, E, Env, C, R where Access[C -> 'k, R], Copy[Env].
    fn try_fold(self, &cx: C, acc: A, f: closure[Env](&_: C, A, T) -> Result[A, E]) -> Result[A, E] {
        var rest = self;
        var acc = acc;
        while !rest.is_empty() {
            match &rest.pop(&cx) {
                Some(x) => {
                    acc = f(&cx, acc, x)?;
                },
                None => (),
            }
        }
        Result::Ok.(acc)
    }

    /// Each element through `f`.
    forall U, Env, C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], Copy[U], Copy[Env].
    fn map(self, &cx: C, f: closure[Env](&_: C, T) -> U) -> List[U, 'k] {
        var out = ListBuilder!::new();
        var rest = self;
        var going = true;
        while going {
            match &rest.pop(&cx) {
                Some(x) => {
                    let u = f(&cx, x);
                    &out.push(&cx, u);
                },
                None => {
                    going = false;
                },
            }
        }
        out.finish(&cx, List::Empty)
    }

    /// The values `f` returns, skipping the elements it returns none for.
    forall U, Env, C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], Copy[U], Copy[Env].
    fn filter_map(self, &cx: C, f: closure[Env](&_: C, T) -> Option[U]) -> List[U, 'k] {
        var out = ListBuilder!::new();
        var rest = self;
        var going = true;
        while going {
            match &rest.pop(&cx) {
                Some(x) => {
                    match f(&cx, x) {
                        Some(u) => &out.push(&cx, u),
                        None => (),
                    }
                },
                None => {
                    going = false;
                },
            }
        }
        out.finish(&cx, List::Empty)
    }

    /// The elements `f` holds for.
    forall Env, C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], Copy[Env].
    fn filter(self, &cx: C, f: closure[Env](&_: C, T) -> bool) -> List[T, 'k] {
        self.filter_map(&cx, |&c, x| if f(&c, x) { Option::Some.(x) } else { Option::None })
    }

    /// Each element through `f`, stopping at the first error.
    forall U, E, Env, C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q], Copy[U], Copy[Env].
    fn try_map(self, &cx: C, f: closure[Env](&_: C, T) -> Result[U, E]) -> Result[List[U, 'k], E] {
        var out = ListBuilder!::new();
        var rest = self;
        while !rest.is_empty() {
            match &rest.pop(&cx) {
                Some(x) => match f(&cx, x) {
                    Ok(u) => &out.push(&cx, u),
                    Err(e) => {
                        let unfinished = out.finish(&cx, List::Empty);
                        return Result::Err.(e);
                    },
                },
                None => (),
            }
        }
        Result::Ok.(out.finish(&cx, List::Empty))
    }
}

/// A list built front to back in one pass: `push` links a new last cell
/// after the previous one, so the list comes out in push order with one
/// cell per element and no recursion. `finish` ends it with a given tail.
///
/// Linear and restricted: `finish` consumes the builder, so no copy of it
/// is left to link cells onto a list that has been handed out.
forall T, 'k.
struct ListBuilder! {
    first: List[T, 'k],
    last: Option[Ref[Cons[T, 'k], 'k]],
}

forall T, 'k where Copy[T].
impl ListBuilder![T, 'k] {
    /// A builder with no elements yet.
    fn new() -> ListBuilder![T, 'k] {
        ListBuilder!.{ first: List::Empty, last: Option::None }
    }

    /// Adds `value` at the end, in a new cell linked after the last one.
    forall C, R, Q where Access[C -> 'k, R], Allocate[C -> 'k, Q].
    fn push(&self, &cx: C, value: T) {
        let { first, last } = self;
        let cell = ref_in(&cx, Cons.{ head: value, tail: List::Empty });
        let first = match last {
            None => List::Cell.(cell),
            Some(r) => {
                let previous = r.copy(&cx);
                r.set(&cx, Cons.{ head: previous.head, tail: List::Cell.(cell) });
                first
            },
        };
        self = ListBuilder!.{ first, last: Option::Some.(cell) };
    }

    /// The list pushed so far, followed by `tail`.
    forall C, R where Access[C -> 'k, R].
    fn finish(self, &cx: C, tail: List[T, 'k]) -> List[T, 'k] {
        let { first, last } = self;
        match last {
            None => tail,
            Some(r) => {
                let previous = r.copy(&cx);
                r.set(&cx, Cons.{ head: previous.head, tail });
                first
            },
        }
    }
}

// ------------------------------------------------------------ iteration --
/// A list's items, read under the capability a context lends (`Access`).
/// `iter` opens the context and the iterator holds what it opened while it
/// runs; `finish` closes it and hands the context back:
/// `var it = xs.iter(cx); for x in &it { .. } let cx = it.finish();`.
forall T, 'k, C, R.
exposed struct ListIter! {
    tag: Exclusive!['k],
    held: R,
    rest: List[T, 'k],
}

forall T, 'k where Copy[T].
impl List[T, 'k] {
    /// An iterator over the list's elements, holding the context `cx` opens
    /// until `ListIter!::finish` hands it back.
    forall C, R where Access[C -> 'k, R].
    fn iter(self, cx: C) -> ListIter![T, 'k, C, R] {
        let (tag, held) = Access[C -> 'k, R]::open(cx);
        ListIter!.{ tag, held, rest: self }
    }
}

forall T, 'k, C, R where Access[C -> 'k, R].
impl ListIter![T, 'k, C, R] {
    /// Ends the iteration, handing back the context.
    fn finish(self) -> C {
        let { tag, held, rest: _rest } = self;
        Access[C -> 'k, R]::close(tag, held)
    }
}

/// The list's elements in order, read under the capability the iterator holds.
forall T, 'k, C, R where Copy[T].
instance Iterator[ListIter![T, 'k, C, R] -> T] {
    fn next(&it: ListIter![T, 'k, C, R]) -> Option[T] {
        var { tag, held, rest } = it;
        var rest = rest;
        let item = &rest.pop(&tag);
        it = ListIter!.{ tag, held, rest };
        item
    }
}