inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! Lean's `String`: UTF-8 text, addressed by byte position.
//!
//! Positions are `Nat` byte offsets. A position is valid when it is at most the length in
//! bytes and falls on a character boundary; the functions without `fast` in their name accept
//! any position and behave as Lean's definitions say for invalid ones. As in `lean.h`,
//! arguments are borrowed unless noted and results are owned.

use crate::object::{alloc_ctor, ctor_get, ctor_set, Obj, TAG_STRING};
use crate::object::{box_, box_uint32, dec, is_scalar, unbox, unbox_uint32};
use crate::object::{held, held_mut, hold, into_held, take_held, Hold};

/// A string object holds a Rust `String`.
impl Hold for String {
    const TAG: u8 = TAG_STRING;

    unsafe fn copy(&self) -> String {
        self.clone()
    }
}

pub(crate) unsafe fn free(o: Obj) {
    drop(take_held::<String>(o));
}

/// A new string object.
pub fn mk_string(text: &str) -> Obj {
    from_string(text.to_owned())
}

/// A new string object that takes over the buffer of `text`.
pub fn from_string(text: String) -> Obj {
    hold(text)
}

/// The text of a string object, giving up one reference to it. Takes the buffer without
/// copying when nothing else refers to the object.
pub unsafe fn into_string(s: Obj) -> String {
    into_held(s)
}

/// The text of a string object.
pub unsafe fn text<'a>(s: Obj) -> &'a str {
    held::<String>(s)
}

/// The `String` a string object holds, for lending it as it is.
pub unsafe fn held_string<'a>(s: Obj) -> &'a String {
    held(s)
}

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

/// A byte position as an index, if it is small enough to be one.
unsafe fn index(position: Obj) -> Option<usize> {
    is_scalar(position).then(|| unbox(position))
}

/// The character that starts at byte `i`, if `i` is a character boundary inside the text.
fn char_at(text: &str, i: usize) -> Option<char> {
    text.get(i..)?.chars().next()
}

/// What Lean returns for a character that is not there.
const DEFAULT_CHAR: u32 = 'A' as u32;

/// Consumes `s`.
pub unsafe fn string_push(s: Obj, c: u32) -> Obj {
    let (s, text) = exclusive(s);
    text.push(crate::char_of_u32(c));
    s
}

/// Consumes `s1`.
pub unsafe fn string_append(s1: Obj, s2: Obj) -> Obj {
    let addition = text(s2).to_owned();
    let (s1, text) = exclusive(s1);
    text.push_str(&addition);
    s1
}

/// The number of characters.
pub unsafe fn string_length(s: Obj) -> Obj {
    box_(text(s).chars().count())
}

pub unsafe fn string_utf8_byte_size(s: Obj) -> Obj {
    box_(text(s).len())
}

/// A string from a `List Char`, which it consumes.
pub unsafe fn string_mk(chars: Obj) -> Obj {
    let mut out = String::new();
    let mut rest = chars;
    while !is_scalar(rest) {
        out.push(crate::char_of_u32(unbox_uint32(ctor_get(rest, 0))));
        rest = ctor_get(rest, 1);
    }
    dec(chars);
    mk_string(&out)
}

/// The characters as a `List Char`. Consumes `s`.
pub unsafe fn string_data(s: Obj) -> Obj {
    let mut list = box_(0);
    for c in text(s).chars().rev() {
        let cell = alloc_ctor(1, 2, 0, 0);
        ctor_set(cell, 0, box_uint32(c as u32));
        ctor_set(cell, 1, list);
        list = cell;
    }
    dec(s);
    list
}

pub unsafe fn string_utf8_get(s: Obj, i: Obj) -> u32 {
    index(i).and_then(|i| char_at(text(s), i)).map_or(DEFAULT_CHAR, |c| c as u32)
}

/// For a valid position that is not the end.
pub unsafe fn string_utf8_get_fast(s: Obj, i: Obj) -> u32 {
    string_utf8_get(s, i)
}

pub unsafe fn string_get_byte_fast(s: Obj, i: Obj) -> u8 {
    text(s).as_bytes()[unbox(i)]
}

pub unsafe fn string_uget_byte_fast(s: Obj, i: usize) -> u8 {
    text(s).as_bytes()[i]
}

/// The position after the character at `i`; one byte further if there is no character.
pub unsafe fn string_utf8_next(s: Obj, i: Obj) -> Obj {
    let width = index(i).and_then(|i| char_at(text(s), i)).map_or(1, char::len_utf8);
    crate::nat::nat_add(i, box_(width))
}

pub unsafe fn string_utf8_next_fast(s: Obj, i: Obj) -> Obj {
    string_utf8_next(s, i)
}

/// The position of the character before `i`.
pub unsafe fn string_utf8_prev(s: Obj, i: Obj) -> Obj {
    let text = text(s);
    match index(i) {
        Some(0) => box_(0),
        Some(i) if i <= text.len() => {
            let mut start = i - 1;
            while !text.is_char_boundary(start) {
                start -= 1;
            }
            box_(start)
        }
        _ => crate::nat::nat_sub(i, box_(1)),
    }
}

/// Replaces the character at `i`. Consumes `s`.
pub unsafe fn string_utf8_set(s: Obj, i: Obj, c: u32) -> Obj {
    let Some((i, old)) = index(i).and_then(|i| Some((i, char_at(text(s), i)?))) else {
        return s;
    };
    let (s, text) = exclusive(s);
    let mut buffer = [0u8; 4];
    text.replace_range(i..i + old.len_utf8(), crate::char_of_u32(c).encode_utf8(&mut buffer));
    s
}

pub unsafe fn string_utf8_at_end(s: Obj, i: Obj) -> u8 {
    index(i).is_none_or(|i| i >= text(s).len()) as u8
}

/// The text from `begin` to `end`. Empty unless `begin` is a valid position before `end`;
/// runs to the end of the string unless `end` is a valid position.
pub unsafe fn string_utf8_extract(s: Obj, begin: Obj, end: Obj) -> Obj {
    let text = text(s);
    let Some(begin) = index(begin).filter(|&b| b < text.len() && text.is_char_boundary(b)) else {
        return mk_string("");
    };
    let end = index(end).unwrap_or(usize::MAX);
    if end <= begin {
        return mk_string("");
    }
    let end = if end <= text.len() && text.is_char_boundary(end) { end } else { text.len() };
    mk_string(&text[begin..end])
}

/// The text between two valid positions.
pub unsafe fn string_utf8_extract_fast(s: Obj, begin: Obj, end: Obj) -> Obj {
    let (begin, end) = (unbox(begin), unbox(end));
    mk_string(text(s).get(begin..end).unwrap_or(""))
}

/// Appends `n` copies of a character. Consumes `s`.
pub unsafe fn string_pushn(s: Obj, c: u32, n: Obj) -> Obj {
    let Some(n) = index(n) else {
        panic!("inlean: out of memory: the string is too large");
    };
    let (s, text) = exclusive(s);
    text.extend(std::iter::repeat_n(crate::char_of_u32(c), n));
    s
}

pub unsafe fn string_dec_eq(s1: Obj, s2: Obj) -> u8 {
    (text(s1) == text(s2)) as u8
}

pub unsafe fn string_dec_lt(s1: Obj, s2: Obj) -> u8 {
    (text(s1) < text(s2)) as u8
}

/// An `Ordering`: 0 for less, 1 for equal, 2 for greater.
pub unsafe fn string_compare(s1: Obj, s2: Obj) -> u8 {
    (text(s1).cmp(text(s2)) as i8 + 1) as u8
}

/// Whether `len` bytes of the two strings, from the given byte offsets, are equal.
pub unsafe fn string_memcmp(s1: Obj, s2: Obj, start1: Obj, start2: Obj, len: Obj) -> u8 {
    let (start1, start2, len) = (unbox(start1), unbox(start2), unbox(len));
    (text(s1).as_bytes()[start1..start1 + len] == text(s2).as_bytes()[start2..start2 + len]) as u8
}

pub fn string_of_usize(n: usize) -> Obj {
    mk_string(&n.to_string())
}

pub unsafe fn string_hash(s: Obj) -> u64 {
    hash_bytes(text(s).as_bytes())
}

/// Lean's hash of a string or a byte array: MurmurHash64A with seed 11.
pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 {
    const M: u64 = 0xc6a4a7935bd1e995;
    const R: u32 = 47;
    let mut h: u64 = 11 ^ (bytes.len() as u64).wrapping_mul(M);
    let mut chunks = bytes.chunks_exact(8);
    for chunk in &mut chunks {
        let mut k = u64::from_le_bytes(chunk.try_into().expect("eight bytes"));
        k = k.wrapping_mul(M);
        k ^= k >> R;
        k = k.wrapping_mul(M);
        h ^= k;
        h = h.wrapping_mul(M);
    }
    let tail = chunks.remainder();
    if !tail.is_empty() {
        for (i, &byte) in tail.iter().enumerate() {
            h ^= (byte as u64) << (8 * i);
        }
        h = h.wrapping_mul(M);
    }
    h ^= h >> R;
    h = h.wrapping_mul(M);
    h ^ (h >> R)
}

/// The functions of this module that generated code may call, named as in `lean.h` without
/// the `lean_` prefix.
pub(crate) const OPS: &[&str] = &[
    "string_push", "string_append", "string_length", "string_utf8_byte_size", "string_mk", "string_data",
    "string_utf8_get", "string_utf8_get_fast", "string_get_byte_fast", "string_uget_byte_fast",
    "string_utf8_next", "string_utf8_next_fast", "string_utf8_prev", "string_utf8_set", "string_utf8_at_end",
    "string_utf8_extract", "string_dec_eq", "string_dec_lt", "string_compare", "string_memcmp",
    "string_of_usize", "string_hash", "string_utf8_extract_fast", "string_pushn",
];