Skip to main content

inlean_runtime/
collections.rs

1//! The Rust functions behind the collections of inlean's Lean library: the standard
2//! library's `Vec`, `VecDeque`, `HashMap` and `HashSet`.
3//!
4//! In a block such a collection is the Rust collection itself, held in a Lean object, and
5//! each of its operations is a declaration that one of these functions runs for. The function
6//! is trusted to compute what the operation's model in `Inlean.lean` says; the two are tested
7//! against each other and against Lean's own collections.
8//!
9//! The functions are generic and name no element type. Generated code calls each with the
10//! Rust values of the arguments, and rustc finds the types from the collection. A collection
11//! or an index that Lean lends arrives as a reference. An element that Lean lends arrives as
12//! `impl Borrow<T>`: a reference where the element is an object, and the value itself where
13//! it is a number, which Lean never lends.
14//!
15//! What a Lean object holds for a collection is the collection, or an `Arc` of it where the
16//! block says `instantiate ... as Arc`. Each function takes either, as a [`Slot`].
17//!
18//! A function that Lean passes arrives as a closure, which takes the elements by reference:
19//! each call makes Lean values of them. A fold is generic in what it accumulates, as its Lean
20//! declaration is, and only passes it between the calls.
21
22use crate::Nat;
23use std::borrow::Borrow;
24use std::collections::hash_map::RandomState;
25use std::sync::{Arc, OnceLock};
26
27/// What holds a collection of type `T` in a Lean object: the collection itself, or an `Arc`
28/// of it. An `Arc` is shared by a pointer, so that a collection kept in two places, or read
29/// out of another collection, is not copied; one of two holders that changes it gets a copy
30/// of its own first, which is what Lean does with a value it holds twice.
31pub trait Slot<T>: Sized {
32    fn of(collection: T) -> Self;
33    fn inner(&self) -> &T;
34    /// The collection for changing, which is this holder's alone afterwards.
35    fn inner_mut(&mut self) -> &mut T;
36    fn into_inner(self) -> T;
37}
38
39impl<T> Slot<T> for T {
40    fn of(collection: T) -> T {
41        collection
42    }
43
44    fn inner(&self) -> &T {
45        self
46    }
47
48    fn inner_mut(&mut self) -> &mut T {
49        self
50    }
51
52    fn into_inner(self) -> T {
53        self
54    }
55}
56
57impl<T: Clone> Slot<T> for Arc<T> {
58    fn of(collection: T) -> Arc<T> {
59        Arc::new(collection)
60    }
61
62    fn inner(&self) -> &T {
63        self
64    }
65
66    fn inner_mut(&mut self) -> &mut T {
67        Arc::make_mut(self)
68    }
69
70    fn into_inner(self) -> T {
71        Arc::unwrap_or_clone(self)
72    }
73}
74
75/// The place that `index` names in a collection, if a collection can have one.
76fn place(index: &Nat) -> Option<usize> {
77    u64::try_from(index).ok().and_then(|index| usize::try_from(index).ok())
78}
79
80/// A number of elements as Lean counts it.
81fn count(elements: usize) -> Nat {
82    Nat::from(elements as u64)
83}
84
85/// The hash keys of every map and set that is born in Lean.
86///
87/// Lean takes any two empty maps of one type for one value, so they have to behave as one:
88/// after the same insertions, list the same entries in the same order. The standard library
89/// gives every new map hash keys of its own, and the order of a listing depends on them, so
90/// two maps it made would not. Every empty map and set is therefore made with these keys,
91/// which are drawn once for the process. A map that comes in from Rust keeps the keys it has;
92/// it is an argument, of which Lean assumes nothing.
93fn hash_keys() -> RandomState {
94    static KEYS: OnceLock<RandomState> = OnceLock::new();
95    KEYS.get_or_init(RandomState::new).clone()
96}
97
98/// `Vec<T>`, whose model is the array of its elements.
99pub mod vec {
100    use super::{count, place, Borrow, Nat, Slot};
101
102    pub fn empty<S: Slot<Vec<T>>, T>() -> S {
103        S::of(Vec::new())
104    }
105
106    pub fn push<S: Slot<Vec<T>>, T>(mut vec: S, element: T) -> S {
107        vec.inner_mut().push(element);
108        vec
109    }
110
111    pub fn pop<S: Slot<Vec<T>>, T>(mut vec: S) -> S {
112        if !vec.inner().is_empty() {
113            vec.inner_mut().pop();
114        }
115        vec
116    }
117
118    pub fn back<S: Slot<Vec<T>>, T: Clone>(vec: &S) -> Option<T> {
119        vec.inner().last().cloned()
120    }
121
122    pub fn size<S: Slot<Vec<T>>, T>(vec: &S) -> Nat {
123        count(vec.inner().len())
124    }
125
126    pub fn get<S: Slot<Vec<T>>, T: Clone>(vec: &S, index: &Nat) -> Option<T> {
127        vec.inner().get(place(index)?).cloned()
128    }
129
130    /// The element at `index`, or `fallback`, which is copied only if it is the answer.
131    pub fn get_or<S: Slot<Vec<T>>, T: Clone>(vec: &S, index: &Nat, fallback: impl Borrow<T>) -> T {
132        match place(index).and_then(|index| vec.inner().get(index)) {
133            Some(element) => element.clone(),
134            None => fallback.borrow().clone(),
135        }
136    }
137
138    /// The element at `index`, which Lean has a proof is there.
139    pub fn index<S: Slot<Vec<T>>, T: Clone>(vec: &S, index: &Nat) -> T {
140        let element = place(index).and_then(|index| vec.inner().get(index));
141        element.expect("inlean: an index Lean proved to be in range is not").clone()
142    }
143
144    pub fn set<S: Slot<Vec<T>>, T>(mut vec: S, index: &Nat, element: T) -> S {
145        // A place that is not there is found before the collection is made this holder's own.
146        if place(index).is_some_and(|index| index < vec.inner().len()) {
147            if let Some(slot) = place(index).and_then(|index| vec.inner_mut().get_mut(index)) {
148                *slot = element;
149            }
150        }
151        vec
152    }
153
154    pub fn truncate<S: Slot<Vec<T>>, T>(mut vec: S, length: &Nat) -> S {
155        // A length that is not a `usize` is more than any `Vec` holds.
156        if let Some(length) = place(length).filter(|&length| length < vec.inner().len()) {
157            vec.inner_mut().truncate(length);
158        }
159        vec
160    }
161
162    pub fn append<S: Slot<Vec<T>>, T: Clone>(mut vec: S, other: &S) -> S {
163        if !other.inner().is_empty() {
164            vec.inner_mut().extend_from_slice(other.inner());
165        }
166        vec
167    }
168
169    pub fn reverse<S: Slot<Vec<T>>, T>(mut vec: S) -> S {
170        vec.inner_mut().reverse();
171        vec
172    }
173
174    /// A Lean array crosses as a `Vec`, so both directions are the value itself: what
175    /// converts each element is the conversion of the array.
176    pub fn to_array<S: Slot<Vec<T>>, T>(vec: S) -> Vec<T> {
177        vec.into_inner()
178    }
179
180    pub fn of_array<S: Slot<Vec<T>>, T>(array: Vec<T>) -> S {
181        S::of(array)
182    }
183
184    pub fn foldl<S: Slot<Vec<T>>, T, B>(mut step: impl FnMut(B, &T) -> B, init: B, vec: &S) -> B {
185        vec.inner().iter().fold(init, |acc, element| step(acc, element))
186    }
187
188    pub fn any<S: Slot<Vec<T>>, T>(vec: &S, mut test: impl FnMut(&T) -> bool) -> bool {
189        vec.inner().iter().any(|element| test(element))
190    }
191
192    pub fn all<S: Slot<Vec<T>>, T>(vec: &S, mut test: impl FnMut(&T) -> bool) -> bool {
193        vec.inner().iter().all(|element| test(element))
194    }
195
196    pub fn filter<S: Slot<Vec<T>>, T>(mut vec: S, mut keep: impl FnMut(&T) -> bool) -> S {
197        vec.inner_mut().retain(|element| keep(element));
198        vec
199    }
200
201    pub fn map<S: Slot<Vec<T>>, T>(mut vec: S, mut change: impl FnMut(&T) -> T) -> S {
202        for element in vec.inner_mut() {
203            *element = change(element);
204        }
205        vec
206    }
207
208    pub fn find<S: Slot<Vec<T>>, T: Clone>(vec: &S, mut test: impl FnMut(&T) -> bool) -> Option<T> {
209        vec.inner().iter().find(|element| test(element)).cloned()
210    }
211}
212
213/// `VecDeque<T>`, whose model is the array of its elements from front to back.
214pub mod vec_deque {
215    use super::{count, place, Borrow, Nat, Slot};
216    use std::collections::VecDeque;
217
218    pub fn empty<S: Slot<VecDeque<T>>, T>() -> S {
219        S::of(VecDeque::new())
220    }
221
222    pub fn push_back<S: Slot<VecDeque<T>>, T>(mut deque: S, element: T) -> S {
223        deque.inner_mut().push_back(element);
224        deque
225    }
226
227    pub fn push_front<S: Slot<VecDeque<T>>, T>(mut deque: S, element: T) -> S {
228        deque.inner_mut().push_front(element);
229        deque
230    }
231
232    pub fn pop_back<S: Slot<VecDeque<T>>, T>(mut deque: S) -> S {
233        if !deque.inner().is_empty() {
234            deque.inner_mut().pop_back();
235        }
236        deque
237    }
238
239    pub fn pop_front<S: Slot<VecDeque<T>>, T>(mut deque: S) -> S {
240        if !deque.inner().is_empty() {
241            deque.inner_mut().pop_front();
242        }
243        deque
244    }
245
246    pub fn front<S: Slot<VecDeque<T>>, T: Clone>(deque: &S) -> Option<T> {
247        deque.inner().front().cloned()
248    }
249
250    pub fn back<S: Slot<VecDeque<T>>, T: Clone>(deque: &S) -> Option<T> {
251        deque.inner().back().cloned()
252    }
253
254    pub fn size<S: Slot<VecDeque<T>>, T>(deque: &S) -> Nat {
255        count(deque.inner().len())
256    }
257
258    pub fn get<S: Slot<VecDeque<T>>, T: Clone>(deque: &S, index: &Nat) -> Option<T> {
259        deque.inner().get(place(index)?).cloned()
260    }
261
262    pub fn get_or<S: Slot<VecDeque<T>>, T: Clone>(deque: &S, index: &Nat, fallback: impl Borrow<T>) -> T {
263        match place(index).and_then(|index| deque.inner().get(index)) {
264            Some(element) => element.clone(),
265            None => fallback.borrow().clone(),
266        }
267    }
268
269    pub fn to_array<S: Slot<VecDeque<T>>, T>(deque: S) -> Vec<T> {
270        deque.into_inner().into()
271    }
272
273    pub fn of_array<S: Slot<VecDeque<T>>, T>(array: Vec<T>) -> S {
274        S::of(array.into())
275    }
276
277    pub fn foldl<S: Slot<VecDeque<T>>, T, B>(mut step: impl FnMut(B, &T) -> B, init: B, deque: &S) -> B {
278        deque.inner().iter().fold(init, |acc, element| step(acc, element))
279    }
280
281    pub fn any<S: Slot<VecDeque<T>>, T>(deque: &S, mut test: impl FnMut(&T) -> bool) -> bool {
282        deque.inner().iter().any(|element| test(element))
283    }
284
285    pub fn all<S: Slot<VecDeque<T>>, T>(deque: &S, mut test: impl FnMut(&T) -> bool) -> bool {
286        deque.inner().iter().all(|element| test(element))
287    }
288
289    pub fn filter<S: Slot<VecDeque<T>>, T>(mut deque: S, mut keep: impl FnMut(&T) -> bool) -> S {
290        deque.inner_mut().retain(|element| keep(element));
291        deque
292    }
293
294    pub fn map<S: Slot<VecDeque<T>>, T>(mut deque: S, mut change: impl FnMut(&T) -> T) -> S {
295        for element in deque.inner_mut() {
296            *element = change(element);
297        }
298        deque
299    }
300
301    pub fn find<S: Slot<VecDeque<T>>, T: Clone>(deque: &S, mut test: impl FnMut(&T) -> bool) -> Option<T> {
302        deque.inner().iter().find(|element| test(element)).cloned()
303    }
304}
305
306/// `HashMap<K, V>`, whose model is what it holds and the shape its order depends on.
307///
308/// Nothing here may let two maps that Lean takes for one value behave differently. So every
309/// empty map has the same hash keys, and `to_array`, `keys` and `values` list in the one
310/// order the map has, which a clone keeps. An operation that changes nothing, such as
311/// erasing a key that is not there, is still done on a map of the holder's own: what the
312/// order of later listings depends on can change even then.
313pub mod hash_map {
314    use super::{count, hash_keys, Borrow, Nat, Slot};
315    use std::collections::HashMap;
316    use std::hash::Hash;
317
318    pub fn empty<S: Slot<HashMap<K, V>>, K, V>() -> S {
319        S::of(HashMap::with_hasher(hash_keys()))
320    }
321
322    pub fn insert<S: Slot<HashMap<K, V>>, K: Eq + Hash, V>(mut map: S, key: K, value: V) -> S {
323        map.inner_mut().insert(key, value);
324        map
325    }
326
327    pub fn erase<S: Slot<HashMap<K, V>>, K: Eq + Hash, V>(mut map: S, key: impl Borrow<K>) -> S {
328        let key: &K = key.borrow();
329        map.inner_mut().remove(key);
330        map
331    }
332
333    pub fn get<S: Slot<HashMap<K, V>>, K: Eq + Hash, V: Clone>(map: &S, key: impl Borrow<K>) -> Option<V> {
334        let key: &K = key.borrow();
335        map.inner().get(key).cloned()
336    }
337
338    /// What `key` is mapped to, or `fallback`, which is copied only if it is the answer.
339    pub fn get_or<S: Slot<HashMap<K, V>>, K: Eq + Hash, V: Clone>(
340        map: &S,
341        key: impl Borrow<K>,
342        fallback: impl Borrow<V>,
343    ) -> V {
344        let key: &K = key.borrow();
345        match map.inner().get(key) {
346            Some(value) => value.clone(),
347            None => fallback.borrow().clone(),
348        }
349    }
350
351    pub fn contains<S: Slot<HashMap<K, V>>, K: Eq + Hash, V>(map: &S, key: impl Borrow<K>) -> bool {
352        let key: &K = key.borrow();
353        map.inner().contains_key(key)
354    }
355
356    pub fn size<S: Slot<HashMap<K, V>>, K, V>(map: &S) -> Nat {
357        count(map.inner().len())
358    }
359
360    pub fn to_array<S: Slot<HashMap<K, V>>, K, V>(map: S) -> Vec<(K, V)> {
361        map.into_inner().into_iter().collect()
362    }
363
364    pub fn keys<S: Slot<HashMap<K, V>>, K: Clone, V>(map: &S) -> Vec<K> {
365        map.inner().keys().cloned().collect()
366    }
367
368    pub fn values<S: Slot<HashMap<K, V>>, K, V: Clone>(map: &S) -> Vec<V> {
369        map.inner().values().cloned().collect()
370    }
371
372    /// The entries come in the order `to_array` lists them, which is the order of the model.
373    pub fn fold<S: Slot<HashMap<K, V>>, K, V, B>(mut step: impl FnMut(B, &K, &V) -> B, init: B, map: &S) -> B {
374        map.inner().iter().fold(init, |acc, (key, value)| step(acc, key, value))
375    }
376
377    pub fn any<S: Slot<HashMap<K, V>>, K, V>(map: &S, mut test: impl FnMut(&K, &V) -> bool) -> bool {
378        map.inner().iter().any(|(key, value)| test(key, value))
379    }
380
381    pub fn all<S: Slot<HashMap<K, V>>, K, V>(map: &S, mut test: impl FnMut(&K, &V) -> bool) -> bool {
382        map.inner().iter().all(|(key, value)| test(key, value))
383    }
384
385    pub fn filter<S: Slot<HashMap<K, V>>, K, V>(mut map: S, mut keep: impl FnMut(&K, &V) -> bool) -> S {
386        map.inner_mut().retain(|key, value| keep(key, value));
387        map
388    }
389}
390
391/// `HashSet<K>`, whose model is what it holds and the shape its order depends on. What
392/// [`hash_map`] says of maps holds here.
393pub mod hash_set {
394    use super::{count, hash_keys, Borrow, Nat, Slot};
395    use std::collections::HashSet;
396    use std::hash::Hash;
397
398    pub fn empty<S: Slot<HashSet<K>>, K>() -> S {
399        S::of(HashSet::with_hasher(hash_keys()))
400    }
401
402    pub fn insert<S: Slot<HashSet<K>>, K: Eq + Hash>(mut set: S, key: K) -> S {
403        set.inner_mut().insert(key);
404        set
405    }
406
407    pub fn erase<S: Slot<HashSet<K>>, K: Eq + Hash>(mut set: S, key: impl Borrow<K>) -> S {
408        let key: &K = key.borrow();
409        set.inner_mut().remove(key);
410        set
411    }
412
413    pub fn contains<S: Slot<HashSet<K>>, K: Eq + Hash>(set: &S, key: impl Borrow<K>) -> bool {
414        let key: &K = key.borrow();
415        set.inner().contains(key)
416    }
417
418    pub fn size<S: Slot<HashSet<K>>, K>(set: &S) -> Nat {
419        count(set.inner().len())
420    }
421
422    pub fn to_array<S: Slot<HashSet<K>>, K>(set: S) -> Vec<K> {
423        set.into_inner().into_iter().collect()
424    }
425
426    pub fn fold<S: Slot<HashSet<K>>, K, B>(mut step: impl FnMut(B, &K) -> B, init: B, set: &S) -> B {
427        set.inner().iter().fold(init, |acc, key| step(acc, key))
428    }
429
430    pub fn any<S: Slot<HashSet<K>>, K>(set: &S, mut test: impl FnMut(&K) -> bool) -> bool {
431        set.inner().iter().any(|key| test(key))
432    }
433
434    pub fn all<S: Slot<HashSet<K>>, K>(set: &S, mut test: impl FnMut(&K) -> bool) -> bool {
435        set.inner().iter().all(|key| test(key))
436    }
437
438    pub fn filter<S: Slot<HashSet<K>>, K>(mut set: S, mut keep: impl FnMut(&K) -> bool) -> S {
439        set.inner_mut().retain(|key| keep(key));
440        set
441    }
442}