inlean-runtime 0.1.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! `Inlean.Map`: a hash map for Lean code, kept in a Rust `HashMap`.
//!
//! In Lean the map is defined by a model: a list of entries in insertion order, searched
//! with the key type's `==`. This module is the implementation the compiled code runs
//! instead, and it must agree with the model on every operation. Two things make that
//! possible. Entries are kept in insertion order, so listing the map has one defined
//! result. And the index is keyed by Lean's hash of a key and searched with Lean's `==`,
//! both called through the instances the Lean code passes in, so "the same key" means here
//! what it means in the model. A lawful hash (`a == b → hash a = hash b`, which the Lean
//! side requires) guarantees that a key is always found in its own bucket.

use crate::object::{apply, box_, count_object, dec, dec_ref, inc, is_exclusive, new_header, unbox, unbox_uint64};
use crate::object::{alloc_ctor, ctor_set, Header, Obj, TAG_MAP};
use std::collections::HashMap;

#[repr(C)]
struct Map {
    header: Header,
    /// Keys and values by slot, in insertion order. An erased slot holds `box_(0)` twice.
    keys: Vec<Obj>,
    values: Vec<Obj>,
    occupied: Vec<bool>,
    /// Lean's hash of the key in each slot.
    hashes: Vec<u64>,
    /// The number of occupied slots.
    len: usize,
    /// The occupied slots whose key has a given hash, in insertion order.
    index: HashMap<u64, Vec<u32>>,
}

/// Frees the map itself, not its keys and values.
pub(crate) unsafe fn free(o: Obj) {
    count_object(-1);
    drop(Box::from_raw(o.header().cast::<Map>()));
}

/// The objects a map refers to. Erased slots contribute scalars, which are not counted.
pub(crate) unsafe fn children<'a>(o: Obj) -> [&'a [Obj]; 2] {
    let map = &*o.header().cast::<Map>();
    [&map.keys, &map.values]
}

fn new() -> Obj {
    count_object(1);
    let map = Box::new(Map {
        header: new_header(TAG_MAP, 0, 0),
        keys: Vec::new(),
        values: Vec::new(),
        occupied: Vec::new(),
        hashes: Vec::new(),
        len: 0,
        index: HashMap::new(),
    });
    Obj::from_header(Box::into_raw(map).cast())
}

unsafe fn get<'a>(m: Obj) -> &'a Map {
    &*m.header().cast::<Map>()
}

/// The map the caller owns, for changing in place: `m` itself if nothing else refers to
/// it, and otherwise a copy, with the reference to `m` given up.
unsafe fn exclusive<'a>(m: Obj) -> (Obj, &'a mut Map) {
    let m = if is_exclusive(m) {
        m
    } else {
        let old = get(m);
        let copy = new();
        let new = &mut *copy.header().cast::<Map>();
        for slot in 0..old.keys.len() {
            inc(old.keys[slot]);
            inc(old.values[slot]);
        }
        new.keys = old.keys.clone();
        new.values = old.values.clone();
        new.occupied = old.occupied.clone();
        new.hashes = old.hashes.clone();
        new.len = old.len;
        new.index = old.index.clone();
        dec_ref(m);
        copy
    };
    (m, &mut *m.header().cast::<Map>())
}

/// Lean's hash of a key: the `Hashable` instance applied to it.
unsafe fn hash_of(hash: Obj, key: Obj) -> u64 {
    inc(hash);
    inc(key);
    let boxed = apply(hash, &[key]);
    let value = unbox_uint64(boxed);
    dec(boxed);
    value
}

/// Lean's `stored == key`: the `BEq` instance applied to the two.
unsafe fn equal(beq: Obj, stored: Obj, key: Obj) -> bool {
    inc(beq);
    inc(stored);
    inc(key);
    unbox(apply(beq, &[stored, key])) != 0
}

/// The first slot whose key equals `key`, which is the entry the model finds.
unsafe fn find(map: &Map, beq: Obj, hash: u64, key: Obj) -> Option<usize> {
    let slots = map.index.get(&hash)?;
    slots.iter().map(|&slot| slot as usize).find(|&slot| equal(beq, map.keys[slot], key))
}

/// Drops erased slots once they outnumber the live ones, keeping the order.
fn compact(map: &mut Map) {
    if map.keys.len() < 16 || map.len * 2 >= map.keys.len() {
        return;
    }
    let mut renumbered = vec![u32::MAX; map.keys.len()];
    let mut next = 0;
    for slot in 0..map.keys.len() {
        if map.occupied[slot] {
            map.keys[next] = map.keys[slot];
            map.values[next] = map.values[slot];
            map.hashes[next] = map.hashes[slot];
            renumbered[slot] = next as u32;
            next += 1;
        }
    }
    map.keys.truncate(next);
    map.values.truncate(next);
    map.hashes.truncate(next);
    map.occupied.clear();
    map.occupied.resize(next, true);
    for slots in map.index.values_mut() {
        for slot in slots.iter_mut() {
            *slot = renumbered[*slot as usize];
        }
    }
}

/// The empty map.
pub fn empty() -> Obj {
    new()
}

/// `m` with `key` bound to `value`. An entry whose key equals `key` is replaced where it
/// is, key included; otherwise the entry is added at the end. Consumes `m`, `key` and
/// `value`; borrows the instances.
pub unsafe fn insert(beq: Obj, hash: Obj, m: Obj, key: Obj, value: Obj) -> Obj {
    let hashed = hash_of(hash, key);
    let (m, map) = exclusive(m);
    match find(map, beq, hashed, key) {
        Some(slot) => {
            dec(std::mem::replace(&mut map.keys[slot], key));
            dec(std::mem::replace(&mut map.values[slot], value));
        }
        None => {
            map.index.entry(hashed).or_default().push(map.keys.len() as u32);
            map.keys.push(key);
            map.values.push(value);
            map.hashes.push(hashed);
            map.occupied.push(true);
            map.len += 1;
        }
    }
    m
}

/// The value bound to a key equal to `key`, as an `Option`. Borrows everything.
pub unsafe fn get_opt(beq: Obj, hash: Obj, m: Obj, key: Obj) -> Obj {
    let map = get(m);
    match find(map, beq, hash_of(hash, key), key) {
        Some(slot) => {
            let value = map.values[slot];
            inc(value);
            let some = alloc_ctor(1, 1, 0, 0);
            ctor_set(some, 0, value);
            some
        }
        None => box_(0),
    }
}

/// `m` without the entries whose key equals `key`. Consumes `m`; borrows the rest.
pub unsafe fn erase(beq: Obj, hash: Obj, m: Obj, key: Obj) -> Obj {
    let hashed = hash_of(hash, key);
    if find(get(m), beq, hashed, key).is_none() {
        return m;
    }
    let (m, map) = exclusive(m);
    let slots = map.index.remove(&hashed).unwrap_or_default();
    let mut kept = Vec::new();
    for slot in slots {
        let at = slot as usize;
        if equal(beq, map.keys[at], key) {
            dec(std::mem::replace(&mut map.keys[at], box_(0)));
            dec(std::mem::replace(&mut map.values[at], box_(0)));
            map.occupied[at] = false;
            map.len -= 1;
        } else {
            kept.push(slot);
        }
    }
    if !kept.is_empty() {
        map.index.insert(hashed, kept);
    }
    compact(map);
    m
}

/// Empties a slot and takes it out of the index.
unsafe fn vacate(map: &mut Map, slot: usize) {
    dec(std::mem::replace(&mut map.keys[slot], box_(0)));
    dec(std::mem::replace(&mut map.values[slot], box_(0)));
    map.occupied[slot] = false;
    map.len -= 1;
    let hash = map.hashes[slot];
    if let Some(slots) = map.index.get_mut(&hash) {
        slots.retain(|&s| s as usize != slot);
        if slots.is_empty() {
            map.index.remove(&hash);
        }
    }
}

/// `m` with only the entries for which `keep key value` is true. Consumes `m`; borrows
/// the function.
pub unsafe fn filter(keep: Obj, m: Obj) -> Obj {
    let (m, map) = exclusive(m);
    for slot in 0..map.keys.len() {
        if !map.occupied[slot] {
            continue;
        }
        inc(keep);
        inc(map.keys[slot]);
        inc(map.values[slot]);
        if unbox(apply(keep, &[map.keys[slot], map.values[slot]])) == 0 {
            vacate(map, slot);
        }
    }
    compact(map);
    m
}

/// A map with the keys of `m`, in the same order, each bound to `f key value`. Borrows
/// both arguments.
pub unsafe fn map_values(f: Obj, m: Obj) -> Obj {
    let old = get(m);
    let copy = new();
    let new = &mut *copy.header().cast::<Map>();
    new.values = Vec::with_capacity(old.values.len());
    for slot in 0..old.keys.len() {
        if !old.occupied[slot] {
            new.values.push(box_(0));
            continue;
        }
        inc(f);
        inc(old.keys[slot]);
        inc(old.keys[slot]);
        inc(old.values[slot]);
        new.values.push(apply(f, &[old.keys[slot], old.values[slot]]));
    }
    new.keys = old.keys.clone();
    new.occupied = old.occupied.clone();
    new.hashes = old.hashes.clone();
    new.len = old.len;
    new.index = old.index.clone();
    copy
}

/// The number of entries, as a `Nat`.
pub unsafe fn size(m: Obj) -> Obj {
    box_(get(m).len)
}

/// The entries in insertion order, as a `List (κ × α)`. Borrows `m`.
pub unsafe fn to_list(m: Obj) -> Obj {
    let map = get(m);
    let mut list = box_(0);
    for slot in (0..map.keys.len()).rev().filter(|&slot| map.occupied[slot]) {
        inc(map.keys[slot]);
        inc(map.values[slot]);
        let pair = alloc_ctor(0, 2, 0, 0);
        ctor_set(pair, 0, map.keys[slot]);
        ctor_set(pair, 1, map.values[slot]);
        let cell = alloc_ctor(1, 2, 0, 0);
        ctor_set(cell, 0, pair);
        ctor_set(cell, 1, list);
        list = cell;
    }
    list
}

/// The entries of a map, for a caller that owns nothing: each key and value is borrowed.
pub unsafe fn entries<'a>(m: Obj) -> impl Iterator<Item = (Obj, Obj)> + 'a {
    let map = get(m);
    (0..map.keys.len()).filter(|&slot| map.occupied[slot]).map(|slot| (map.keys[slot], map.values[slot]))
}

/// The functions of this module that generated code may call. Their names in Lean's
/// `@[extern]` attributes are `inlean_map_` followed by the name here.
pub(crate) const OPS: &[&str] = &["empty", "insert", "get_opt", "erase", "size", "to_list", "filter", "map_values"];