Skip to main content

inlean_runtime/
string.rs

1//! Lean's `String`: UTF-8 text, addressed by byte position.
2//!
3//! Positions are `Nat` byte offsets. A position is valid when it is at most the length in
4//! bytes and falls on a character boundary; the functions without `fast` in their name accept
5//! any position and behave as Lean's definitions say for invalid ones. As in `lean.h`,
6//! arguments are borrowed unless noted and results are owned.
7
8use crate::object::{box_, box_uint32, count_object, dec, dec_ref, is_exclusive, is_scalar, new_header, unbox, unbox_uint32};
9use crate::object::{alloc_ctor, ctor_get, ctor_set, Header, Obj, TAG_STRING};
10
11#[repr(C)]
12struct Str {
13    header: Header,
14    text: String,
15}
16
17pub(crate) unsafe fn free(o: Obj) {
18    count_object(-1);
19    drop(Box::from_raw(o.header().cast::<Str>()));
20}
21
22/// A new string object.
23pub fn mk_string(text: &str) -> Obj {
24    from_string(text.to_owned())
25}
26
27/// A new string object that takes over the buffer of `text`.
28pub fn from_string(text: String) -> Obj {
29    count_object(1);
30    let string = Box::new(Str { header: new_header(TAG_STRING, 0, 0), text });
31    Obj::from_header(Box::into_raw(string).cast())
32}
33
34/// The text of a string object, giving up one reference to it. Takes the buffer without
35/// copying when nothing else refers to the object.
36pub unsafe fn into_string(s: Obj) -> String {
37    if is_exclusive(s) {
38        count_object(-1);
39        return Box::from_raw(s.header().cast::<Str>()).text;
40    }
41    let copy = text(s).to_owned();
42    dec_ref(s);
43    copy
44}
45
46/// The text of a string object.
47pub unsafe fn text<'a>(s: Obj) -> &'a str {
48    &(*s.header().cast::<Str>()).text
49}
50
51/// The text of a string the caller owns, for changing in place: `s` itself if nothing else
52/// refers to it, and otherwise a copy, with the reference to `s` given up.
53unsafe fn exclusive<'a>(s: Obj) -> (Obj, &'a mut String) {
54    let s = if is_exclusive(s) {
55        s
56    } else {
57        let copy = mk_string(text(s));
58        dec_ref(s);
59        copy
60    };
61    (s, &mut (*s.header().cast::<Str>()).text)
62}
63
64/// A byte position as an index, if it is small enough to be one.
65unsafe fn index(position: Obj) -> Option<usize> {
66    is_scalar(position).then(|| unbox(position))
67}
68
69/// The character that starts at byte `i`, if `i` is a character boundary inside the text.
70fn char_at(text: &str, i: usize) -> Option<char> {
71    text.get(i..)?.chars().next()
72}
73
74/// What Lean returns for a character that is not there.
75const DEFAULT_CHAR: u32 = 'A' as u32;
76
77/// Consumes `s`.
78pub unsafe fn string_push(s: Obj, c: u32) -> Obj {
79    let (s, text) = exclusive(s);
80    text.push(crate::char_of_u32(c));
81    s
82}
83
84/// Consumes `s1`.
85pub unsafe fn string_append(s1: Obj, s2: Obj) -> Obj {
86    let addition = text(s2).to_owned();
87    let (s1, text) = exclusive(s1);
88    text.push_str(&addition);
89    s1
90}
91
92/// The number of characters.
93pub unsafe fn string_length(s: Obj) -> Obj {
94    box_(text(s).chars().count())
95}
96
97pub unsafe fn string_utf8_byte_size(s: Obj) -> Obj {
98    box_(text(s).len())
99}
100
101/// A string from a `List Char`, which it consumes.
102pub unsafe fn string_mk(chars: Obj) -> Obj {
103    let mut out = String::new();
104    let mut rest = chars;
105    while !is_scalar(rest) {
106        out.push(crate::char_of_u32(unbox_uint32(ctor_get(rest, 0))));
107        rest = ctor_get(rest, 1);
108    }
109    dec(chars);
110    mk_string(&out)
111}
112
113/// The characters as a `List Char`. Consumes `s`.
114pub unsafe fn string_data(s: Obj) -> Obj {
115    let mut list = box_(0);
116    for c in text(s).chars().rev() {
117        let cell = alloc_ctor(1, 2, 0, 0);
118        ctor_set(cell, 0, box_uint32(c as u32));
119        ctor_set(cell, 1, list);
120        list = cell;
121    }
122    dec(s);
123    list
124}
125
126pub unsafe fn string_utf8_get(s: Obj, i: Obj) -> u32 {
127    index(i).and_then(|i| char_at(text(s), i)).map_or(DEFAULT_CHAR, |c| c as u32)
128}
129
130/// For a valid position that is not the end.
131pub unsafe fn string_utf8_get_fast(s: Obj, i: Obj) -> u32 {
132    string_utf8_get(s, i)
133}
134
135pub unsafe fn string_get_byte_fast(s: Obj, i: Obj) -> u8 {
136    text(s).as_bytes()[unbox(i)]
137}
138
139pub unsafe fn string_uget_byte_fast(s: Obj, i: usize) -> u8 {
140    text(s).as_bytes()[i]
141}
142
143/// The position after the character at `i`; one byte further if there is no character.
144pub unsafe fn string_utf8_next(s: Obj, i: Obj) -> Obj {
145    let width = index(i).and_then(|i| char_at(text(s), i)).map_or(1, char::len_utf8);
146    crate::nat::nat_add(i, box_(width))
147}
148
149pub unsafe fn string_utf8_next_fast(s: Obj, i: Obj) -> Obj {
150    string_utf8_next(s, i)
151}
152
153/// The position of the character before `i`.
154pub unsafe fn string_utf8_prev(s: Obj, i: Obj) -> Obj {
155    let text = text(s);
156    match index(i) {
157        Some(0) => box_(0),
158        Some(i) if i <= text.len() => {
159            let mut start = i - 1;
160            while !text.is_char_boundary(start) {
161                start -= 1;
162            }
163            box_(start)
164        }
165        _ => crate::nat::nat_sub(i, box_(1)),
166    }
167}
168
169/// Replaces the character at `i`. Consumes `s`.
170pub unsafe fn string_utf8_set(s: Obj, i: Obj, c: u32) -> Obj {
171    let Some((i, old)) = index(i).and_then(|i| Some((i, char_at(text(s), i)?))) else {
172        return s;
173    };
174    let (s, text) = exclusive(s);
175    let mut buffer = [0u8; 4];
176    text.replace_range(i..i + old.len_utf8(), crate::char_of_u32(c).encode_utf8(&mut buffer));
177    s
178}
179
180pub unsafe fn string_utf8_at_end(s: Obj, i: Obj) -> u8 {
181    index(i).is_none_or(|i| i >= text(s).len()) as u8
182}
183
184/// The text from `begin` to `end`. Empty unless `begin` is a valid position before `end`;
185/// runs to the end of the string unless `end` is a valid position.
186pub unsafe fn string_utf8_extract(s: Obj, begin: Obj, end: Obj) -> Obj {
187    let text = text(s);
188    let Some(begin) = index(begin).filter(|&b| b < text.len() && text.is_char_boundary(b)) else {
189        return mk_string("");
190    };
191    let end = index(end).unwrap_or(usize::MAX);
192    if end <= begin {
193        return mk_string("");
194    }
195    let end = if end <= text.len() && text.is_char_boundary(end) { end } else { text.len() };
196    mk_string(&text[begin..end])
197}
198
199/// The text between two valid positions.
200pub unsafe fn string_utf8_extract_fast(s: Obj, begin: Obj, end: Obj) -> Obj {
201    let (begin, end) = (unbox(begin), unbox(end));
202    mk_string(text(s).get(begin..end).unwrap_or(""))
203}
204
205/// Appends `n` copies of a character. Consumes `s`.
206pub unsafe fn string_pushn(s: Obj, c: u32, n: Obj) -> Obj {
207    let Some(n) = index(n) else {
208        panic!("inlean: out of memory: the string is too large");
209    };
210    let (s, text) = exclusive(s);
211    text.extend(std::iter::repeat_n(crate::char_of_u32(c), n));
212    s
213}
214
215pub unsafe fn string_dec_eq(s1: Obj, s2: Obj) -> u8 {
216    (text(s1) == text(s2)) as u8
217}
218
219pub unsafe fn string_dec_lt(s1: Obj, s2: Obj) -> u8 {
220    (text(s1) < text(s2)) as u8
221}
222
223/// An `Ordering`: 0 for less, 1 for equal, 2 for greater.
224pub unsafe fn string_compare(s1: Obj, s2: Obj) -> u8 {
225    (text(s1).cmp(text(s2)) as i8 + 1) as u8
226}
227
228/// Whether `len` bytes of the two strings, from the given byte offsets, are equal.
229pub unsafe fn string_memcmp(s1: Obj, s2: Obj, start1: Obj, start2: Obj, len: Obj) -> u8 {
230    let (start1, start2, len) = (unbox(start1), unbox(start2), unbox(len));
231    (text(s1).as_bytes()[start1..start1 + len] == text(s2).as_bytes()[start2..start2 + len]) as u8
232}
233
234pub fn string_of_usize(n: usize) -> Obj {
235    mk_string(&n.to_string())
236}
237
238pub unsafe fn string_hash(s: Obj) -> u64 {
239    hash_bytes(text(s).as_bytes())
240}
241
242/// Lean's hash of a string or a byte array: MurmurHash64A with seed 11.
243pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 {
244    const M: u64 = 0xc6a4a7935bd1e995;
245    const R: u32 = 47;
246    let mut h: u64 = 11 ^ (bytes.len() as u64).wrapping_mul(M);
247    let mut chunks = bytes.chunks_exact(8);
248    for chunk in &mut chunks {
249        let mut k = u64::from_le_bytes(chunk.try_into().expect("eight bytes"));
250        k = k.wrapping_mul(M);
251        k ^= k >> R;
252        k = k.wrapping_mul(M);
253        h ^= k;
254        h = h.wrapping_mul(M);
255    }
256    let tail = chunks.remainder();
257    if !tail.is_empty() {
258        for (i, &byte) in tail.iter().enumerate() {
259            h ^= (byte as u64) << (8 * i);
260        }
261        h = h.wrapping_mul(M);
262    }
263    h ^= h >> R;
264    h = h.wrapping_mul(M);
265    h ^ (h >> R)
266}
267
268/// The functions of this module that generated code may call, named as in `lean.h` without
269/// the `lean_` prefix.
270pub(crate) const OPS: &[&str] = &[
271    "string_push", "string_append", "string_length", "string_utf8_byte_size", "string_mk", "string_data",
272    "string_utf8_get", "string_utf8_get_fast", "string_get_byte_fast", "string_uget_byte_fast",
273    "string_utf8_next", "string_utf8_next_fast", "string_utf8_prev", "string_utf8_set", "string_utf8_at_end",
274    "string_utf8_extract", "string_dec_eq", "string_dec_lt", "string_compare", "string_memcmp",
275    "string_of_usize", "string_hash", "string_utf8_extract_fast", "string_pushn",
276];