inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! Lean's `Array`: a growable sequence of objects, updated in place when nothing else
//! refers to it.
//!
//! As in `lean.h`: an argument named `a` that a function changes is consumed, indexes and
//! arrays that are only read are borrowed, stored values are consumed, and results are owned
//! unless the function's name ends in `borrowed`.

use crate::object::{alloc_ctor, ctor_get, ctor_set, Obj, TAG_ARRAY};
use crate::object::{box_, dec, inc, is_scalar, unbox};
use crate::object::{held, held_mut, hold, take_held, Hold};

/// An array object holds a `Vec` of its elements, with a reference to each.
impl Hold for Vec<Obj> {
    const TAG: u8 = TAG_ARRAY;

    unsafe fn copy(&self) -> Vec<Obj> {
        for &item in self {
            inc(item);
        }
        self.clone()
    }
}

/// Frees the array itself, not its elements.
pub(crate) unsafe fn free(o: Obj) {
    drop(take_held::<Vec<Obj>>(o));
}

/// A new array that owns `items`.
pub fn from_vec(items: Vec<Obj>) -> Obj {
    hold(items)
}

/// The elements of an array nothing else refers to, with the references it held. Gives up
/// the array.
pub unsafe fn into_vec(a: Obj) -> Vec<Obj> {
    take_held(a)
}

/// The elements of an array.
pub unsafe fn elements<'a>(a: Obj) -> &'a [Obj] {
    held::<Vec<Obj>>(a)
}

/// The elements of an array the caller owns, for changing in place: `a` itself if nothing
/// else refers to it, and otherwise a copy, with the reference to `a` given up.
unsafe fn exclusive<'a>(a: Obj) -> (Obj, &'a mut Vec<Obj>) {
    held_mut(a)
}

/// An index given as a `Nat`, if it is inside an array of `len` elements.
unsafe fn index(i: Obj, len: usize) -> Option<usize> {
    (is_scalar(i) && unbox(i) < len).then(|| unbox(i))
}

#[cold]
fn out_of_bounds() -> ! {
    panic!("inlean: index out of bounds")
}

pub unsafe fn array_size(a: Obj) -> usize {
    elements(a).len()
}

pub unsafe fn array_get_size(a: Obj) -> Obj {
    box_(elements(a).len())
}

pub unsafe fn mk_empty_array_with_capacity(capacity: Obj) -> Obj {
    from_vec(Vec::with_capacity(if is_scalar(capacity) { unbox(capacity).min(1 << 20) } else { 0 }))
}

/// An array from a `List`, which it consumes.
pub unsafe fn array_mk(list: Obj) -> Obj {
    let mut items = Vec::new();
    let mut rest = list;
    while !is_scalar(rest) {
        let head = ctor_get(rest, 0);
        inc(head);
        items.push(head);
        rest = ctor_get(rest, 1);
    }
    dec(list);
    from_vec(items)
}

/// The elements as a `List`. Consumes `a`.
pub unsafe fn array_to_list(a: Obj) -> Obj {
    let mut list = box_(0);
    for &item in elements(a).iter().rev() {
        inc(item);
        let cell = alloc_ctor(1, 2, 0, 0);
        ctor_set(cell, 0, item);
        ctor_set(cell, 1, list);
        list = cell;
    }
    dec(a);
    list
}

pub unsafe fn array_uget_borrowed(a: Obj, i: usize) -> Obj {
    elements(a)[i]
}

pub unsafe fn array_uget(a: Obj, i: usize) -> Obj {
    let item = elements(a)[i];
    inc(item);
    item
}

pub unsafe fn array_fget_borrowed(a: Obj, i: Obj) -> Obj {
    elements(a)[unbox(i)]
}

pub unsafe fn array_fget(a: Obj, i: Obj) -> Obj {
    array_uget(a, unbox(i))
}

/// The element at `i`. Lean's `arr[i]!`: an index outside the array is a panic.
pub unsafe fn array_get_borrowed(_default: Obj, a: Obj, i: Obj) -> Obj {
    match index(i, elements(a).len()) {
        Some(i) => elements(a)[i],
        None => out_of_bounds(),
    }
}

pub unsafe fn array_get(default: Obj, a: Obj, i: Obj) -> Obj {
    let item = array_get_borrowed(default, a, i);
    inc(item);
    item
}

pub unsafe fn array_uset(a: Obj, i: usize, value: Obj) -> Obj {
    let (a, items) = exclusive(a);
    dec(std::mem::replace(&mut items[i], value));
    a
}

pub unsafe fn array_fset(a: Obj, i: Obj, value: Obj) -> Obj {
    array_uset(a, unbox(i), value)
}

/// Lean's `arr.set! i v`: an index outside the array is a panic.
pub unsafe fn array_set(a: Obj, i: Obj, value: Obj) -> Obj {
    match index(i, elements(a).len()) {
        Some(i) => array_uset(a, i, value),
        None => out_of_bounds(),
    }
}

pub unsafe fn array_push(a: Obj, value: Obj) -> Obj {
    let (a, items) = exclusive(a);
    items.push(value);
    a
}

/// Removes the last element, if there is one.
pub unsafe fn array_pop(a: Obj) -> Obj {
    let (a, items) = exclusive(a);
    if let Some(last) = items.pop() {
        dec(last);
    }
    a
}

pub unsafe fn array_uswap(a: Obj, i: usize, j: usize) -> Obj {
    let (a, items) = exclusive(a);
    items.swap(i, j);
    a
}

pub unsafe fn array_fswap(a: Obj, i: Obj, j: Obj) -> Obj {
    array_uswap(a, unbox(i), unbox(j))
}

/// Swaps two elements; does nothing if an index is outside the array.
pub unsafe fn array_swap(a: Obj, i: Obj, j: Obj) -> Obj {
    let len = elements(a).len();
    match (index(i, len), index(j, len)) {
        (Some(i), Some(j)) => array_uswap(a, i, j),
        _ => a,
    }
}

/// An array of `n` references to `value`. Consumes both.
pub unsafe fn mk_array(n: Obj, value: Obj) -> Obj {
    if !is_scalar(n) {
        panic!("inlean: out of memory: the array is too large");
    }
    let n = unbox(n);
    match n {
        0 => dec(value),
        _ => crate::object::inc_n(value, n as u32 - 1),
    }
    dec(box_(n));
    from_vec(vec![value; n])
}

/// Lean's debugging aid for finding accidental copies of an array. The mark has no effect on
/// values, and this runtime does not track it.
pub unsafe fn array_mark_linear(a: Obj) -> Obj {
    a
}

/// See [`array_mark_linear`]. Returns `target`.
pub unsafe fn array_propagate_mark(_source: Obj, target: Obj) -> Obj {
    target
}

/// The functions of this module that generated code may call, named as in `lean.h` without
/// the `lean_` prefix.
pub(crate) const OPS: &[&str] = &[
    "array_size", "array_get_size", "mk_empty_array_with_capacity", "array_mk", "array_to_list",
    "array_uget", "array_uget_borrowed", "array_fget", "array_fget_borrowed", "array_get", "array_get_borrowed",
    "array_uset", "array_fset", "array_set", "array_push", "array_pop", "array_uswap", "array_fswap",
    "array_swap", "mk_array", "array_mark_linear", "array_propagate_mark",
];