inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! The Rust functions behind the collections of inlean's Lean library: the standard
//! library's `Vec`, `VecDeque`, `HashMap` and `HashSet`.
//!
//! In a block such a collection is the Rust collection itself, held in a Lean object, and
//! each of its operations is a declaration that one of these functions runs for. The function
//! is trusted to compute what the operation's model in `Inlean.lean` says; the two are tested
//! against each other and against Lean's own collections.
//!
//! The functions are generic and name no element type. Generated code calls each with the
//! Rust values of the arguments, and rustc finds the types from the collection. A collection
//! or an index that Lean lends arrives as a reference. An element that Lean lends arrives as
//! `impl Borrow<T>`: a reference where the element is an object, and the value itself where
//! it is a number, which Lean never lends.
//!
//! What a Lean object holds for a collection is the collection, or an `Arc` of it where the
//! block says `instantiate ... as Arc`. Each function takes either, as a [`Slot`].
//!
//! A function that Lean passes arrives as a closure, which takes the elements by reference:
//! each call makes Lean values of them. A fold is generic in what it accumulates, as its Lean
//! declaration is, and only passes it between the calls.

use crate::Nat;
use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::sync::{Arc, OnceLock};

/// What holds a collection of type `T` in a Lean object: the collection itself, or an `Arc`
/// of it. An `Arc` is shared by a pointer, so that a collection kept in two places, or read
/// out of another collection, is not copied; one of two holders that changes it gets a copy
/// of its own first, which is what Lean does with a value it holds twice.
pub trait Slot<T>: Sized {
    fn of(collection: T) -> Self;
    fn inner(&self) -> &T;
    /// The collection for changing, which is this holder's alone afterwards.
    fn inner_mut(&mut self) -> &mut T;
    fn into_inner(self) -> T;
}

impl<T> Slot<T> for T {
    fn of(collection: T) -> T {
        collection
    }

    fn inner(&self) -> &T {
        self
    }

    fn inner_mut(&mut self) -> &mut T {
        self
    }

    fn into_inner(self) -> T {
        self
    }
}

impl<T: Clone> Slot<T> for Arc<T> {
    fn of(collection: T) -> Arc<T> {
        Arc::new(collection)
    }

    fn inner(&self) -> &T {
        self
    }

    fn inner_mut(&mut self) -> &mut T {
        Arc::make_mut(self)
    }

    fn into_inner(self) -> T {
        Arc::unwrap_or_clone(self)
    }
}

/// The place that `index` names in a collection, if a collection can have one.
fn place(index: &Nat) -> Option<usize> {
    u64::try_from(index).ok().and_then(|index| usize::try_from(index).ok())
}

/// A number of elements as Lean counts it.
fn count(elements: usize) -> Nat {
    Nat::from(elements as u64)
}

/// The hash keys of every map and set that is born in Lean.
///
/// Lean takes any two empty maps of one type for one value, so they have to behave as one:
/// after the same insertions, list the same entries in the same order. The standard library
/// gives every new map hash keys of its own, and the order of a listing depends on them, so
/// two maps it made would not. Every empty map and set is therefore made with these keys,
/// which are drawn once for the process. A map that comes in from Rust keeps the keys it has;
/// it is an argument, of which Lean assumes nothing.
fn hash_keys() -> RandomState {
    static KEYS: OnceLock<RandomState> = OnceLock::new();
    KEYS.get_or_init(RandomState::new).clone()
}

/// `Vec<T>`, whose model is the array of its elements.
pub mod vec {
    use super::{count, place, Borrow, Nat, Slot};

    pub fn empty<S: Slot<Vec<T>>, T>() -> S {
        S::of(Vec::new())
    }

    pub fn push<S: Slot<Vec<T>>, T>(mut vec: S, element: T) -> S {
        vec.inner_mut().push(element);
        vec
    }

    pub fn pop<S: Slot<Vec<T>>, T>(mut vec: S) -> S {
        if !vec.inner().is_empty() {
            vec.inner_mut().pop();
        }
        vec
    }

    pub fn back<S: Slot<Vec<T>>, T: Clone>(vec: &S) -> Option<T> {
        vec.inner().last().cloned()
    }

    pub fn size<S: Slot<Vec<T>>, T>(vec: &S) -> Nat {
        count(vec.inner().len())
    }

    pub fn get<S: Slot<Vec<T>>, T: Clone>(vec: &S, index: &Nat) -> Option<T> {
        vec.inner().get(place(index)?).cloned()
    }

    /// The element at `index`, or `fallback`, which is copied only if it is the answer.
    pub fn get_or<S: Slot<Vec<T>>, T: Clone>(vec: &S, index: &Nat, fallback: impl Borrow<T>) -> T {
        match place(index).and_then(|index| vec.inner().get(index)) {
            Some(element) => element.clone(),
            None => fallback.borrow().clone(),
        }
    }

    /// The element at `index`, which Lean has a proof is there.
    pub fn index<S: Slot<Vec<T>>, T: Clone>(vec: &S, index: &Nat) -> T {
        let element = place(index).and_then(|index| vec.inner().get(index));
        element.expect("inlean: an index Lean proved to be in range is not").clone()
    }

    pub fn set<S: Slot<Vec<T>>, T>(mut vec: S, index: &Nat, element: T) -> S {
        // A place that is not there is found before the collection is made this holder's own.
        if place(index).is_some_and(|index| index < vec.inner().len()) {
            if let Some(slot) = place(index).and_then(|index| vec.inner_mut().get_mut(index)) {
                *slot = element;
            }
        }
        vec
    }

    pub fn truncate<S: Slot<Vec<T>>, T>(mut vec: S, length: &Nat) -> S {
        // A length that is not a `usize` is more than any `Vec` holds.
        if let Some(length) = place(length).filter(|&length| length < vec.inner().len()) {
            vec.inner_mut().truncate(length);
        }
        vec
    }

    pub fn append<S: Slot<Vec<T>>, T: Clone>(mut vec: S, other: &S) -> S {
        if !other.inner().is_empty() {
            vec.inner_mut().extend_from_slice(other.inner());
        }
        vec
    }

    pub fn reverse<S: Slot<Vec<T>>, T>(mut vec: S) -> S {
        vec.inner_mut().reverse();
        vec
    }

    /// A Lean array crosses as a `Vec`, so both directions are the value itself: what
    /// converts each element is the conversion of the array.
    pub fn to_array<S: Slot<Vec<T>>, T>(vec: S) -> Vec<T> {
        vec.into_inner()
    }

    pub fn of_array<S: Slot<Vec<T>>, T>(array: Vec<T>) -> S {
        S::of(array)
    }

    pub fn foldl<S: Slot<Vec<T>>, T, B>(mut step: impl FnMut(B, &T) -> B, init: B, vec: &S) -> B {
        vec.inner().iter().fold(init, |acc, element| step(acc, element))
    }

    pub fn any<S: Slot<Vec<T>>, T>(vec: &S, mut test: impl FnMut(&T) -> bool) -> bool {
        vec.inner().iter().any(|element| test(element))
    }

    pub fn all<S: Slot<Vec<T>>, T>(vec: &S, mut test: impl FnMut(&T) -> bool) -> bool {
        vec.inner().iter().all(|element| test(element))
    }

    pub fn filter<S: Slot<Vec<T>>, T>(mut vec: S, mut keep: impl FnMut(&T) -> bool) -> S {
        vec.inner_mut().retain(|element| keep(element));
        vec
    }

    pub fn map<S: Slot<Vec<T>>, T>(mut vec: S, mut change: impl FnMut(&T) -> T) -> S {
        for element in vec.inner_mut() {
            *element = change(element);
        }
        vec
    }

    pub fn find<S: Slot<Vec<T>>, T: Clone>(vec: &S, mut test: impl FnMut(&T) -> bool) -> Option<T> {
        vec.inner().iter().find(|element| test(element)).cloned()
    }
}

/// `VecDeque<T>`, whose model is the array of its elements from front to back.
pub mod vec_deque {
    use super::{count, place, Borrow, Nat, Slot};
    use std::collections::VecDeque;

    pub fn empty<S: Slot<VecDeque<T>>, T>() -> S {
        S::of(VecDeque::new())
    }

    pub fn push_back<S: Slot<VecDeque<T>>, T>(mut deque: S, element: T) -> S {
        deque.inner_mut().push_back(element);
        deque
    }

    pub fn push_front<S: Slot<VecDeque<T>>, T>(mut deque: S, element: T) -> S {
        deque.inner_mut().push_front(element);
        deque
    }

    pub fn pop_back<S: Slot<VecDeque<T>>, T>(mut deque: S) -> S {
        if !deque.inner().is_empty() {
            deque.inner_mut().pop_back();
        }
        deque
    }

    pub fn pop_front<S: Slot<VecDeque<T>>, T>(mut deque: S) -> S {
        if !deque.inner().is_empty() {
            deque.inner_mut().pop_front();
        }
        deque
    }

    pub fn front<S: Slot<VecDeque<T>>, T: Clone>(deque: &S) -> Option<T> {
        deque.inner().front().cloned()
    }

    pub fn back<S: Slot<VecDeque<T>>, T: Clone>(deque: &S) -> Option<T> {
        deque.inner().back().cloned()
    }

    pub fn size<S: Slot<VecDeque<T>>, T>(deque: &S) -> Nat {
        count(deque.inner().len())
    }

    pub fn get<S: Slot<VecDeque<T>>, T: Clone>(deque: &S, index: &Nat) -> Option<T> {
        deque.inner().get(place(index)?).cloned()
    }

    pub fn get_or<S: Slot<VecDeque<T>>, T: Clone>(deque: &S, index: &Nat, fallback: impl Borrow<T>) -> T {
        match place(index).and_then(|index| deque.inner().get(index)) {
            Some(element) => element.clone(),
            None => fallback.borrow().clone(),
        }
    }

    pub fn to_array<S: Slot<VecDeque<T>>, T>(deque: S) -> Vec<T> {
        deque.into_inner().into()
    }

    pub fn of_array<S: Slot<VecDeque<T>>, T>(array: Vec<T>) -> S {
        S::of(array.into())
    }

    pub fn foldl<S: Slot<VecDeque<T>>, T, B>(mut step: impl FnMut(B, &T) -> B, init: B, deque: &S) -> B {
        deque.inner().iter().fold(init, |acc, element| step(acc, element))
    }

    pub fn any<S: Slot<VecDeque<T>>, T>(deque: &S, mut test: impl FnMut(&T) -> bool) -> bool {
        deque.inner().iter().any(|element| test(element))
    }

    pub fn all<S: Slot<VecDeque<T>>, T>(deque: &S, mut test: impl FnMut(&T) -> bool) -> bool {
        deque.inner().iter().all(|element| test(element))
    }

    pub fn filter<S: Slot<VecDeque<T>>, T>(mut deque: S, mut keep: impl FnMut(&T) -> bool) -> S {
        deque.inner_mut().retain(|element| keep(element));
        deque
    }

    pub fn map<S: Slot<VecDeque<T>>, T>(mut deque: S, mut change: impl FnMut(&T) -> T) -> S {
        for element in deque.inner_mut() {
            *element = change(element);
        }
        deque
    }

    pub fn find<S: Slot<VecDeque<T>>, T: Clone>(deque: &S, mut test: impl FnMut(&T) -> bool) -> Option<T> {
        deque.inner().iter().find(|element| test(element)).cloned()
    }
}

/// `HashMap<K, V>`, whose model is what it holds and the shape its order depends on.
///
/// Nothing here may let two maps that Lean takes for one value behave differently. So every
/// empty map has the same hash keys, and `to_array`, `keys` and `values` list in the one
/// order the map has, which a clone keeps. An operation that changes nothing, such as
/// erasing a key that is not there, is still done on a map of the holder's own: what the
/// order of later listings depends on can change even then.
pub mod hash_map {
    use super::{count, hash_keys, Borrow, Nat, Slot};
    use std::collections::HashMap;
    use std::hash::Hash;

    pub fn empty<S: Slot<HashMap<K, V>>, K, V>() -> S {
        S::of(HashMap::with_hasher(hash_keys()))
    }

    pub fn insert<S: Slot<HashMap<K, V>>, K: Eq + Hash, V>(mut map: S, key: K, value: V) -> S {
        map.inner_mut().insert(key, value);
        map
    }

    pub fn erase<S: Slot<HashMap<K, V>>, K: Eq + Hash, V>(mut map: S, key: impl Borrow<K>) -> S {
        let key: &K = key.borrow();
        map.inner_mut().remove(key);
        map
    }

    pub fn get<S: Slot<HashMap<K, V>>, K: Eq + Hash, V: Clone>(map: &S, key: impl Borrow<K>) -> Option<V> {
        let key: &K = key.borrow();
        map.inner().get(key).cloned()
    }

    /// What `key` is mapped to, or `fallback`, which is copied only if it is the answer.
    pub fn get_or<S: Slot<HashMap<K, V>>, K: Eq + Hash, V: Clone>(
        map: &S,
        key: impl Borrow<K>,
        fallback: impl Borrow<V>,
    ) -> V {
        let key: &K = key.borrow();
        match map.inner().get(key) {
            Some(value) => value.clone(),
            None => fallback.borrow().clone(),
        }
    }

    pub fn contains<S: Slot<HashMap<K, V>>, K: Eq + Hash, V>(map: &S, key: impl Borrow<K>) -> bool {
        let key: &K = key.borrow();
        map.inner().contains_key(key)
    }

    pub fn size<S: Slot<HashMap<K, V>>, K, V>(map: &S) -> Nat {
        count(map.inner().len())
    }

    pub fn to_array<S: Slot<HashMap<K, V>>, K, V>(map: S) -> Vec<(K, V)> {
        map.into_inner().into_iter().collect()
    }

    pub fn keys<S: Slot<HashMap<K, V>>, K: Clone, V>(map: &S) -> Vec<K> {
        map.inner().keys().cloned().collect()
    }

    pub fn values<S: Slot<HashMap<K, V>>, K, V: Clone>(map: &S) -> Vec<V> {
        map.inner().values().cloned().collect()
    }

    /// The entries come in the order `to_array` lists them, which is the order of the model.
    pub fn fold<S: Slot<HashMap<K, V>>, K, V, B>(mut step: impl FnMut(B, &K, &V) -> B, init: B, map: &S) -> B {
        map.inner().iter().fold(init, |acc, (key, value)| step(acc, key, value))
    }

    pub fn any<S: Slot<HashMap<K, V>>, K, V>(map: &S, mut test: impl FnMut(&K, &V) -> bool) -> bool {
        map.inner().iter().any(|(key, value)| test(key, value))
    }

    pub fn all<S: Slot<HashMap<K, V>>, K, V>(map: &S, mut test: impl FnMut(&K, &V) -> bool) -> bool {
        map.inner().iter().all(|(key, value)| test(key, value))
    }

    pub fn filter<S: Slot<HashMap<K, V>>, K, V>(mut map: S, mut keep: impl FnMut(&K, &V) -> bool) -> S {
        map.inner_mut().retain(|key, value| keep(key, value));
        map
    }
}

/// `HashSet<K>`, whose model is what it holds and the shape its order depends on. What
/// [`hash_map`] says of maps holds here.
pub mod hash_set {
    use super::{count, hash_keys, Borrow, Nat, Slot};
    use std::collections::HashSet;
    use std::hash::Hash;

    pub fn empty<S: Slot<HashSet<K>>, K>() -> S {
        S::of(HashSet::with_hasher(hash_keys()))
    }

    pub fn insert<S: Slot<HashSet<K>>, K: Eq + Hash>(mut set: S, key: K) -> S {
        set.inner_mut().insert(key);
        set
    }

    pub fn erase<S: Slot<HashSet<K>>, K: Eq + Hash>(mut set: S, key: impl Borrow<K>) -> S {
        let key: &K = key.borrow();
        set.inner_mut().remove(key);
        set
    }

    pub fn contains<S: Slot<HashSet<K>>, K: Eq + Hash>(set: &S, key: impl Borrow<K>) -> bool {
        let key: &K = key.borrow();
        set.inner().contains(key)
    }

    pub fn size<S: Slot<HashSet<K>>, K>(set: &S) -> Nat {
        count(set.inner().len())
    }

    pub fn to_array<S: Slot<HashSet<K>>, K>(set: S) -> Vec<K> {
        set.into_inner().into_iter().collect()
    }

    pub fn fold<S: Slot<HashSet<K>>, K, B>(mut step: impl FnMut(B, &K) -> B, init: B, set: &S) -> B {
        set.inner().iter().fold(init, |acc, key| step(acc, key))
    }

    pub fn any<S: Slot<HashSet<K>>, K>(set: &S, mut test: impl FnMut(&K) -> bool) -> bool {
        set.inner().iter().any(|key| test(key))
    }

    pub fn all<S: Slot<HashSet<K>>, K>(set: &S, mut test: impl FnMut(&K) -> bool) -> bool {
        set.inner().iter().all(|key| test(key))
    }

    pub fn filter<S: Slot<HashSet<K>>, K>(mut set: S, mut keep: impl FnMut(&K) -> bool) -> S {
        set.inner_mut().retain(|key| keep(key));
        set
    }
}