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