Skip to main content

inlean_runtime/
array.rs

1//! Lean's `Array`: a growable sequence of objects, updated in place when nothing else
2//! refers to it.
3//!
4//! As in `lean.h`: an argument named `a` that a function changes is consumed, indexes and
5//! arrays that are only read are borrowed, stored values are consumed, and results are owned
6//! unless the function's name ends in `borrowed`.
7
8use crate::object::{box_, count_object, dec, dec_ref, inc, is_exclusive, is_scalar, new_header, unbox};
9use crate::object::{alloc_ctor, ctor_get, ctor_set, Header, Obj, TAG_ARRAY};
10
11#[repr(C)]
12struct Array {
13    header: Header,
14    items: Vec<Obj>,
15}
16
17/// Frees the array itself, not its elements.
18pub(crate) unsafe fn free(o: Obj) {
19    count_object(-1);
20    drop(Box::from_raw(o.header().cast::<Array>()));
21}
22
23/// A new array that owns `items`.
24pub fn from_vec(items: Vec<Obj>) -> Obj {
25    count_object(1);
26    let array = Box::new(Array { header: new_header(TAG_ARRAY, 0, 0), items });
27    Obj::from_header(Box::into_raw(array).cast())
28}
29
30/// The elements of an array.
31pub unsafe fn elements<'a>(a: Obj) -> &'a [Obj] {
32    &(*a.header().cast::<Array>()).items
33}
34
35/// The elements of an array the caller owns, for changing in place: `a` itself if nothing
36/// else refers to it, and otherwise a copy, with the reference to `a` given up.
37unsafe fn exclusive<'a>(a: Obj) -> (Obj, &'a mut Vec<Obj>) {
38    let a = if is_exclusive(a) {
39        a
40    } else {
41        let items = elements(a).to_vec();
42        for &item in &items {
43            inc(item);
44        }
45        dec_ref(a);
46        from_vec(items)
47    };
48    (a, &mut (*a.header().cast::<Array>()).items)
49}
50
51/// An index given as a `Nat`, if it is inside an array of `len` elements.
52unsafe fn index(i: Obj, len: usize) -> Option<usize> {
53    (is_scalar(i) && unbox(i) < len).then(|| unbox(i))
54}
55
56#[cold]
57fn out_of_bounds() -> ! {
58    panic!("inlean: index out of bounds")
59}
60
61pub unsafe fn array_size(a: Obj) -> usize {
62    elements(a).len()
63}
64
65pub unsafe fn array_get_size(a: Obj) -> Obj {
66    box_(elements(a).len())
67}
68
69pub unsafe fn mk_empty_array_with_capacity(capacity: Obj) -> Obj {
70    from_vec(Vec::with_capacity(if is_scalar(capacity) { unbox(capacity).min(1 << 20) } else { 0 }))
71}
72
73/// An array from a `List`, which it consumes.
74pub unsafe fn array_mk(list: Obj) -> Obj {
75    let mut items = Vec::new();
76    let mut rest = list;
77    while !is_scalar(rest) {
78        let head = ctor_get(rest, 0);
79        inc(head);
80        items.push(head);
81        rest = ctor_get(rest, 1);
82    }
83    dec(list);
84    from_vec(items)
85}
86
87/// The elements as a `List`. Consumes `a`.
88pub unsafe fn array_to_list(a: Obj) -> Obj {
89    let mut list = box_(0);
90    for &item in elements(a).iter().rev() {
91        inc(item);
92        let cell = alloc_ctor(1, 2, 0, 0);
93        ctor_set(cell, 0, item);
94        ctor_set(cell, 1, list);
95        list = cell;
96    }
97    dec(a);
98    list
99}
100
101pub unsafe fn array_uget_borrowed(a: Obj, i: usize) -> Obj {
102    elements(a)[i]
103}
104
105pub unsafe fn array_uget(a: Obj, i: usize) -> Obj {
106    let item = elements(a)[i];
107    inc(item);
108    item
109}
110
111pub unsafe fn array_fget_borrowed(a: Obj, i: Obj) -> Obj {
112    elements(a)[unbox(i)]
113}
114
115pub unsafe fn array_fget(a: Obj, i: Obj) -> Obj {
116    array_uget(a, unbox(i))
117}
118
119/// The element at `i`. Lean's `arr[i]!`: an index outside the array is a panic.
120pub unsafe fn array_get_borrowed(_default: Obj, a: Obj, i: Obj) -> Obj {
121    match index(i, elements(a).len()) {
122        Some(i) => elements(a)[i],
123        None => out_of_bounds(),
124    }
125}
126
127pub unsafe fn array_get(default: Obj, a: Obj, i: Obj) -> Obj {
128    let item = array_get_borrowed(default, a, i);
129    inc(item);
130    item
131}
132
133pub unsafe fn array_uset(a: Obj, i: usize, value: Obj) -> Obj {
134    let (a, items) = exclusive(a);
135    dec(std::mem::replace(&mut items[i], value));
136    a
137}
138
139pub unsafe fn array_fset(a: Obj, i: Obj, value: Obj) -> Obj {
140    array_uset(a, unbox(i), value)
141}
142
143/// Lean's `arr.set! i v`: an index outside the array is a panic.
144pub unsafe fn array_set(a: Obj, i: Obj, value: Obj) -> Obj {
145    match index(i, elements(a).len()) {
146        Some(i) => array_uset(a, i, value),
147        None => out_of_bounds(),
148    }
149}
150
151pub unsafe fn array_push(a: Obj, value: Obj) -> Obj {
152    let (a, items) = exclusive(a);
153    items.push(value);
154    a
155}
156
157/// Removes the last element, if there is one.
158pub unsafe fn array_pop(a: Obj) -> Obj {
159    let (a, items) = exclusive(a);
160    if let Some(last) = items.pop() {
161        dec(last);
162    }
163    a
164}
165
166pub unsafe fn array_uswap(a: Obj, i: usize, j: usize) -> Obj {
167    let (a, items) = exclusive(a);
168    items.swap(i, j);
169    a
170}
171
172pub unsafe fn array_fswap(a: Obj, i: Obj, j: Obj) -> Obj {
173    array_uswap(a, unbox(i), unbox(j))
174}
175
176/// Swaps two elements; does nothing if an index is outside the array.
177pub unsafe fn array_swap(a: Obj, i: Obj, j: Obj) -> Obj {
178    let len = elements(a).len();
179    match (index(i, len), index(j, len)) {
180        (Some(i), Some(j)) => array_uswap(a, i, j),
181        _ => a,
182    }
183}
184
185/// An array of `n` references to `value`. Consumes both.
186pub unsafe fn mk_array(n: Obj, value: Obj) -> Obj {
187    if !is_scalar(n) {
188        panic!("inlean: out of memory: the array is too large");
189    }
190    let n = unbox(n);
191    match n {
192        0 => dec(value),
193        _ => crate::object::inc_n(value, n as u32 - 1),
194    }
195    dec(box_(n));
196    from_vec(vec![value; n])
197}
198
199/// Lean's debugging aid for finding accidental copies of an array. The mark has no effect on
200/// values, and this runtime does not track it.
201pub unsafe fn array_mark_linear(a: Obj) -> Obj {
202    a
203}
204
205/// See [`array_mark_linear`]. Returns `target`.
206pub unsafe fn array_propagate_mark(_source: Obj, target: Obj) -> Obj {
207    target
208}
209
210/// The functions of this module that generated code may call, named as in `lean.h` without
211/// the `lean_` prefix.
212pub(crate) const OPS: &[&str] = &[
213    "array_size", "array_get_size", "mk_empty_array_with_capacity", "array_mk", "array_to_list",
214    "array_uget", "array_uget_borrowed", "array_fget", "array_fget_borrowed", "array_get", "array_get_borrowed",
215    "array_uset", "array_fset", "array_set", "array_push", "array_pop", "array_uswap", "array_fswap",
216    "array_swap", "mk_array", "array_mark_linear", "array_propagate_mark",
217];