Skip to main content

leanfran_runtime/
model.rs

1//! Rust values in the representation of Aeneas's Lean model of Rust.
2//!
3//! Aeneas models Rust's integers as `Std.U8` … `Std.I128` (a `BitVec` at run time, so a `Nat`
4//! holding the bits), `Vec<T>` and `&[T]` as `alloc.vec.Vec` and `Slice` (a length and a
5//! `ListN`), `[T; N]` as `Std.Array` (a `ListN`), `&str` as `Str` (a `Slice U8`) and `String`
6//! as Lean's `String`. [`Model`] converts a Rust value to and from that representation.
7//! `#[derive(leanfran::Model)]` implements it for the structs and enums of a crate, with the
8//! constructor layout Lean gives the structure or inductive type Aeneas generates.
9
10use crate::nat::{mk_nat, nat_value};
11use crate::object::*;
12use num_bigint::BigInt;
13use num_traits::ToPrimitive;
14
15/// A Rust value in the representation of its type in Aeneas's model.
16pub trait Model: Sized {
17    /// Size of the value as a scalar field of a constructor, or 0 when it is an object field.
18    const SCALAR_SIZE: u32 = 0;
19
20    /// The owned boxed object of `self`.
21    ///
22    /// # Safety
23    ///
24    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
25    unsafe fn to_model(self) -> Obj;
26
27    /// The Rust value of the borrowed boxed object `o`.
28    ///
29    /// # Safety
30    ///
31    /// `o` must be a valid Lean value of the model type of `Self`.
32    unsafe fn from_model(o: Obj) -> Self;
33
34    /// Writes `self` as a scalar field at byte offset `off` of the constructor `o`.
35    ///
36    /// # Safety
37    ///
38    /// `o` must be a constructor with a scalar area holding the field at `off`.
39    unsafe fn set_scalar(self, o: Obj, off: u32) {
40        let _ = (o, off);
41        unreachable!("not a scalar field")
42    }
43
44    /// Reads a scalar field at byte offset `off` of the constructor `o`.
45    ///
46    /// # Safety
47    ///
48    /// `o` must be a constructor with a scalar area holding the field at `off`.
49    unsafe fn get_scalar(o: Obj, off: u32) -> Self {
50        let _ = (o, off);
51        unreachable!("not a scalar field")
52    }
53}
54
55/// A `Nat` holding `bits`.
56pub unsafe fn bits_to_model(bits: u128) -> Obj {
57    match usize::try_from(bits) {
58        Ok(n) => crate::nat::lean_usize_to_nat(n),
59        Err(_) => mk_nat(BigInt::from(bits)),
60    }
61}
62
63/// The bits held by the borrowed `Nat` `o` (below `2^128`).
64pub unsafe fn bits_from_model(o: Obj) -> u128 {
65    if lean_is_scalar(o) {
66        lean_unbox(o) as u128
67    } else {
68        nat_value(o)
69            .to_u128()
70            .expect("a model integer has at most 128 bits")
71    }
72}
73
74macro_rules! model_int {
75    ($($t:ty => $u:ty),*) => {$(
76        impl Model for $t {
77            unsafe fn to_model(self) -> Obj {
78                bits_to_model(self as $u as u128)
79            }
80            unsafe fn from_model(o: Obj) -> Self {
81                bits_from_model(o) as $u as $t
82            }
83        }
84    )*};
85}
86
87model_int!(
88    u8 => u8, u16 => u16, u32 => u32, u64 => u64, u128 => u128, usize => usize,
89    i8 => u8, i16 => u16, i32 => u32, i64 => u64, i128 => u128, isize => usize
90);
91
92impl Model for bool {
93    const SCALAR_SIZE: u32 = 1;
94    unsafe fn to_model(self) -> Obj {
95        lean_box(self as usize)
96    }
97    unsafe fn from_model(o: Obj) -> Self {
98        lean_unbox(o) != 0
99    }
100    unsafe fn set_scalar(self, o: Obj, off: u32) {
101        lean_ctor_set_uint8(o, off, self as u8);
102    }
103    unsafe fn get_scalar(o: Obj, off: u32) -> Self {
104        lean_ctor_get_uint8(o, off) != 0
105    }
106}
107
108impl Model for char {
109    const SCALAR_SIZE: u32 = 4;
110    unsafe fn to_model(self) -> Obj {
111        crate::lean_box_uint32(self as u32)
112    }
113    unsafe fn from_model(o: Obj) -> Self {
114        crate::marshal::char_of_u32(crate::lean_unbox_uint32(o))
115    }
116    unsafe fn set_scalar(self, o: Obj, off: u32) {
117        lean_ctor_set_uint32(o, off, self as u32);
118    }
119    unsafe fn get_scalar(o: Obj, off: u32) -> Self {
120        crate::marshal::char_of_u32(lean_ctor_get_uint32(o, off))
121    }
122}
123
124impl Model for () {
125    unsafe fn to_model(self) -> Obj {
126        lean_box(0)
127    }
128    unsafe fn from_model(_o: Obj) -> Self {}
129}
130
131/// `ListN α n` of the elements.
132pub unsafe fn list_n_to_model<T>(v: Vec<T>, mut f: impl FnMut(T) -> Obj) -> Obj {
133    let elems: Vec<Obj> = v.into_iter().map(&mut f).collect();
134    let mut r = lean_box(0);
135    for (n, e) in elems.into_iter().rev().enumerate() {
136        let c = lean_alloc_ctor(1, 3, 0);
137        lean_ctor_set(c, 0, crate::nat::lean_usize_to_nat(n));
138        lean_ctor_set(c, 1, e);
139        lean_ctor_set(c, 2, r);
140        r = c;
141    }
142    r
143}
144
145/// The elements of the borrowed `ListN α n`.
146pub unsafe fn list_n_from_model<T>(mut o: Obj, mut f: impl FnMut(Obj) -> T) -> Vec<T> {
147    let mut out = Vec::new();
148    while !lean_is_scalar(o) {
149        out.push(f(lean_ctor_get(o, 1)));
150        o = lean_ctor_get(o, 2);
151    }
152    out
153}
154
155/// `Slice α` (and `alloc.vec.Vec α`, a structure around it) of the elements.
156pub unsafe fn slice_to_model<T>(v: Vec<T>, f: impl FnMut(T) -> Obj) -> Obj {
157    let n = v.len();
158    let s = lean_alloc_ctor(0, 2, 0);
159    lean_ctor_set(s, 0, crate::nat::lean_usize_to_nat(n));
160    lean_ctor_set(s, 1, list_n_to_model(v, f));
161    s
162}
163
164/// The elements of the borrowed `Slice α`.
165pub unsafe fn slice_from_model<T>(o: Obj, f: impl FnMut(Obj) -> T) -> Vec<T> {
166    list_n_from_model(lean_ctor_get(o, 1), f)
167}
168
169impl<T: Model> Model for Vec<T> {
170    unsafe fn to_model(self) -> Obj {
171        slice_to_model(self, |x| x.to_model())
172    }
173    unsafe fn from_model(o: Obj) -> Self {
174        slice_from_model(o, |x| T::from_model(x))
175    }
176}
177
178impl<T: Model, const N: usize> Model for [T; N] {
179    unsafe fn to_model(self) -> Obj {
180        list_n_to_model(Vec::from(self), |x| x.to_model())
181    }
182    unsafe fn from_model(o: Obj) -> Self {
183        array_n_from_model(o, |x| T::from_model(x))
184    }
185}
186
187impl Model for String {
188    unsafe fn to_model(self) -> Obj {
189        crate::string::lean_mk_string(&self)
190    }
191    unsafe fn from_model(o: Obj) -> Self {
192        crate::string::lean_string_to_str(o).to_string()
193    }
194}
195
196/// A `&'static str` read back from the model is leaked: tests compare the few values a model
197/// returns, and a field such as `Other(&'static str)` has no owner to borrow from.
198impl Model for &'static str {
199    unsafe fn to_model(self) -> Obj {
200        self.as_bytes().to_vec().to_model()
201    }
202    unsafe fn from_model(o: Obj) -> Self {
203        String::from_utf8(Vec::<u8>::from_model(o))
204            .expect("a Str of UTF-8")
205            .leak()
206    }
207}
208
209impl<T: Model> Model for Option<T> {
210    unsafe fn to_model(self) -> Obj {
211        match self {
212            None => lean_box(0),
213            Some(x) => {
214                let c = lean_alloc_ctor(1, 1, 0);
215                lean_ctor_set(c, 0, x.to_model());
216                c
217            }
218        }
219    }
220    unsafe fn from_model(o: Obj) -> Self {
221        if lean_is_scalar(o) {
222            None
223        } else {
224            Some(T::from_model(lean_ctor_get(o, 0)))
225        }
226    }
227}
228
229impl<T: Model> Model for Box<T> {
230    unsafe fn to_model(self) -> Obj {
231        (*self).to_model()
232    }
233    unsafe fn from_model(o: Obj) -> Self {
234        Box::new(T::from_model(o))
235    }
236}
237
238unsafe fn pair(a: Obj, b: Obj) -> Obj {
239    let c = lean_alloc_ctor(0, 2, 0);
240    lean_ctor_set(c, 0, a);
241    lean_ctor_set(c, 1, b);
242    c
243}
244
245impl<A: Model, B: Model> Model for (A, B) {
246    unsafe fn to_model(self) -> Obj {
247        pair(self.0.to_model(), self.1.to_model())
248    }
249    unsafe fn from_model(o: Obj) -> Self {
250        (
251            A::from_model(lean_ctor_get(o, 0)),
252            B::from_model(lean_ctor_get(o, 1)),
253        )
254    }
255}
256
257impl<A: Model, B: Model, C: Model> Model for (A, B, C) {
258    unsafe fn to_model(self) -> Obj {
259        pair(self.0.to_model(), (self.1, self.2).to_model())
260    }
261    unsafe fn from_model(o: Obj) -> Self {
262        let (b, c) = <(B, C)>::from_model(lean_ctor_get(o, 1));
263        (A::from_model(lean_ctor_get(o, 0)), b, c)
264    }
265}
266
267impl<A: Model, B: Model, C: Model, D: Model> Model for (A, B, C, D) {
268    unsafe fn to_model(self) -> Obj {
269        pair(self.0.to_model(), (self.1, self.2, self.3).to_model())
270    }
271    unsafe fn from_model(o: Obj) -> Self {
272        let (b, c, d) = <(B, C, D)>::from_model(lean_ctor_get(o, 1));
273        (A::from_model(lean_ctor_get(o, 0)), b, c, d)
274    }
275}
276
277/// The layout of a constructor whose fields have the [`Model::SCALAR_SIZE`]s `sizes`, as Lean
278/// lays it out: object fields first in their order, then the scalar fields by decreasing size.
279/// Per field: the object index or the byte offset in the scalar area; and the number of object
280/// fields and the size of the scalar area.
281pub fn ctor_layout(sizes: &[u32]) -> (Vec<u32>, u32, u32) {
282    let objs = sizes.iter().filter(|&&s| s == 0).count() as u32;
283    let mut slot = vec![0u32; sizes.len()];
284    let mut next_obj = 0;
285    for (i, &s) in sizes.iter().enumerate() {
286        if s == 0 {
287            slot[i] = next_obj;
288            next_obj += 1;
289        }
290    }
291    let mut off = 0;
292    for size in [8, 4, 2, 1] {
293        for (i, &s) in sizes.iter().enumerate() {
294            if s == size {
295                slot[i] = off;
296                off += size;
297            }
298        }
299    }
300    (slot, objs, off)
301}
302
303/// Offset of a scalar field of a constructor with `objs` object fields.
304pub const fn scalar_offset(objs: u32, off: u32) -> u32 {
305    objs * core::mem::size_of::<usize>() as u32 + off
306}
307
308/// `[T; N]` of the elements of the borrowed `ListN α N` (`Std.Array α N`).
309pub unsafe fn array_n_from_model<T, const N: usize>(o: Obj, f: impl FnMut(Obj) -> T) -> [T; N] {
310    match list_n_from_model(o, f).try_into() {
311        Ok(a) => a,
312        Err(_) => unreachable!("Std.Array of a different length"),
313    }
314}
315
316/// The constructors of Aeneas's `Error`, by tag.
317const AENEAS_ERRORS: [&str; 7] = [
318    "assertionFailure",
319    "integerOverflow",
320    "divisionByZero",
321    "arrayOutOfBounds",
322    "maximumSizeExceeded",
323    "panic",
324    "undef",
325];
326
327/// The value of the owned `MatchResult α` `m` (the result of `Result.match`): `ok` gives the
328/// value, `fail` and `div` are a Rust panic.
329pub unsafe fn result_value<T>(m: Obj, f: impl FnOnce(Obj) -> T) -> T {
330    match lean_obj_tag(m) {
331        0 => {
332            let v = f(lean_ctor_get(m, 0));
333            lean_dec(m);
334            v
335        }
336        1 => panic!("leanfran: the Lean function diverges"),
337        _ => {
338            let e = lean_ctor_get(m, 0);
339            let tag = if lean_is_scalar(e) {
340                lean_unbox(e)
341            } else {
342                lean_obj_tag(e) as usize
343            };
344            panic!(
345                "leanfran: the Lean function fails: {}",
346                AENEAS_ERRORS.get(tag).unwrap_or(&"error")
347            )
348        }
349    }
350}