Skip to main content

inlean_runtime/
map.rs

1//! `Inlean.Map`: a hash map for Lean code, kept in a Rust `HashMap`.
2//!
3//! In Lean the map is defined by a model: a list of entries in insertion order, searched
4//! with the key type's `==`. This module is the implementation the compiled code runs
5//! instead, and it must agree with the model on every operation. Two things make that
6//! possible. Entries are kept in insertion order, so listing the map has one defined
7//! result. And the index is keyed by Lean's hash of a key and searched with Lean's `==`,
8//! both called through the instances the Lean code passes in, so "the same key" means here
9//! what it means in the model. A lawful hash (`a == b → hash a = hash b`, which the Lean
10//! side requires) guarantees that a key is always found in its own bucket.
11
12use crate::object::{apply, box_, count_object, dec, dec_ref, inc, is_exclusive, new_header, unbox, unbox_uint64};
13use crate::object::{alloc_ctor, ctor_set, Header, Obj, TAG_MAP};
14use std::collections::HashMap;
15
16#[repr(C)]
17struct Map {
18    header: Header,
19    /// Keys and values by slot, in insertion order. An erased slot holds `box_(0)` twice.
20    keys: Vec<Obj>,
21    values: Vec<Obj>,
22    occupied: Vec<bool>,
23    /// Lean's hash of the key in each slot.
24    hashes: Vec<u64>,
25    /// The number of occupied slots.
26    len: usize,
27    /// The occupied slots whose key has a given hash, in insertion order.
28    index: HashMap<u64, Vec<u32>>,
29}
30
31/// Frees the map itself, not its keys and values.
32pub(crate) unsafe fn free(o: Obj) {
33    count_object(-1);
34    drop(Box::from_raw(o.header().cast::<Map>()));
35}
36
37/// The objects a map refers to. Erased slots contribute scalars, which are not counted.
38pub(crate) unsafe fn children<'a>(o: Obj) -> [&'a [Obj]; 2] {
39    let map = &*o.header().cast::<Map>();
40    [&map.keys, &map.values]
41}
42
43fn new() -> Obj {
44    count_object(1);
45    let map = Box::new(Map {
46        header: new_header(TAG_MAP, 0, 0),
47        keys: Vec::new(),
48        values: Vec::new(),
49        occupied: Vec::new(),
50        hashes: Vec::new(),
51        len: 0,
52        index: HashMap::new(),
53    });
54    Obj::from_header(Box::into_raw(map).cast())
55}
56
57unsafe fn get<'a>(m: Obj) -> &'a Map {
58    &*m.header().cast::<Map>()
59}
60
61/// The map the caller owns, for changing in place: `m` itself if nothing else refers to
62/// it, and otherwise a copy, with the reference to `m` given up.
63unsafe fn exclusive<'a>(m: Obj) -> (Obj, &'a mut Map) {
64    let m = if is_exclusive(m) {
65        m
66    } else {
67        let old = get(m);
68        let copy = new();
69        let new = &mut *copy.header().cast::<Map>();
70        for slot in 0..old.keys.len() {
71            inc(old.keys[slot]);
72            inc(old.values[slot]);
73        }
74        new.keys = old.keys.clone();
75        new.values = old.values.clone();
76        new.occupied = old.occupied.clone();
77        new.hashes = old.hashes.clone();
78        new.len = old.len;
79        new.index = old.index.clone();
80        dec_ref(m);
81        copy
82    };
83    (m, &mut *m.header().cast::<Map>())
84}
85
86/// Lean's hash of a key: the `Hashable` instance applied to it.
87unsafe fn hash_of(hash: Obj, key: Obj) -> u64 {
88    inc(hash);
89    inc(key);
90    let boxed = apply(hash, &[key]);
91    let value = unbox_uint64(boxed);
92    dec(boxed);
93    value
94}
95
96/// Lean's `stored == key`: the `BEq` instance applied to the two.
97unsafe fn equal(beq: Obj, stored: Obj, key: Obj) -> bool {
98    inc(beq);
99    inc(stored);
100    inc(key);
101    unbox(apply(beq, &[stored, key])) != 0
102}
103
104/// The first slot whose key equals `key`, which is the entry the model finds.
105unsafe fn find(map: &Map, beq: Obj, hash: u64, key: Obj) -> Option<usize> {
106    let slots = map.index.get(&hash)?;
107    slots.iter().map(|&slot| slot as usize).find(|&slot| equal(beq, map.keys[slot], key))
108}
109
110/// Drops erased slots once they outnumber the live ones, keeping the order.
111fn compact(map: &mut Map) {
112    if map.keys.len() < 16 || map.len * 2 >= map.keys.len() {
113        return;
114    }
115    let mut renumbered = vec![u32::MAX; map.keys.len()];
116    let mut next = 0;
117    for slot in 0..map.keys.len() {
118        if map.occupied[slot] {
119            map.keys[next] = map.keys[slot];
120            map.values[next] = map.values[slot];
121            map.hashes[next] = map.hashes[slot];
122            renumbered[slot] = next as u32;
123            next += 1;
124        }
125    }
126    map.keys.truncate(next);
127    map.values.truncate(next);
128    map.hashes.truncate(next);
129    map.occupied.clear();
130    map.occupied.resize(next, true);
131    for slots in map.index.values_mut() {
132        for slot in slots.iter_mut() {
133            *slot = renumbered[*slot as usize];
134        }
135    }
136}
137
138/// The empty map.
139pub fn empty() -> Obj {
140    new()
141}
142
143/// `m` with `key` bound to `value`. An entry whose key equals `key` is replaced where it
144/// is, key included; otherwise the entry is added at the end. Consumes `m`, `key` and
145/// `value`; borrows the instances.
146pub unsafe fn insert(beq: Obj, hash: Obj, m: Obj, key: Obj, value: Obj) -> Obj {
147    let hashed = hash_of(hash, key);
148    let (m, map) = exclusive(m);
149    match find(map, beq, hashed, key) {
150        Some(slot) => {
151            dec(std::mem::replace(&mut map.keys[slot], key));
152            dec(std::mem::replace(&mut map.values[slot], value));
153        }
154        None => {
155            map.index.entry(hashed).or_default().push(map.keys.len() as u32);
156            map.keys.push(key);
157            map.values.push(value);
158            map.hashes.push(hashed);
159            map.occupied.push(true);
160            map.len += 1;
161        }
162    }
163    m
164}
165
166/// The value bound to a key equal to `key`, as an `Option`. Borrows everything.
167pub unsafe fn get_opt(beq: Obj, hash: Obj, m: Obj, key: Obj) -> Obj {
168    let map = get(m);
169    match find(map, beq, hash_of(hash, key), key) {
170        Some(slot) => {
171            let value = map.values[slot];
172            inc(value);
173            let some = alloc_ctor(1, 1, 0, 0);
174            ctor_set(some, 0, value);
175            some
176        }
177        None => box_(0),
178    }
179}
180
181/// `m` without the entries whose key equals `key`. Consumes `m`; borrows the rest.
182pub unsafe fn erase(beq: Obj, hash: Obj, m: Obj, key: Obj) -> Obj {
183    let hashed = hash_of(hash, key);
184    if find(get(m), beq, hashed, key).is_none() {
185        return m;
186    }
187    let (m, map) = exclusive(m);
188    let slots = map.index.remove(&hashed).unwrap_or_default();
189    let mut kept = Vec::new();
190    for slot in slots {
191        let at = slot as usize;
192        if equal(beq, map.keys[at], key) {
193            dec(std::mem::replace(&mut map.keys[at], box_(0)));
194            dec(std::mem::replace(&mut map.values[at], box_(0)));
195            map.occupied[at] = false;
196            map.len -= 1;
197        } else {
198            kept.push(slot);
199        }
200    }
201    if !kept.is_empty() {
202        map.index.insert(hashed, kept);
203    }
204    compact(map);
205    m
206}
207
208/// Empties a slot and takes it out of the index.
209unsafe fn vacate(map: &mut Map, slot: usize) {
210    dec(std::mem::replace(&mut map.keys[slot], box_(0)));
211    dec(std::mem::replace(&mut map.values[slot], box_(0)));
212    map.occupied[slot] = false;
213    map.len -= 1;
214    let hash = map.hashes[slot];
215    if let Some(slots) = map.index.get_mut(&hash) {
216        slots.retain(|&s| s as usize != slot);
217        if slots.is_empty() {
218            map.index.remove(&hash);
219        }
220    }
221}
222
223/// `m` with only the entries for which `keep key value` is true. Consumes `m`; borrows
224/// the function.
225pub unsafe fn filter(keep: Obj, m: Obj) -> Obj {
226    let (m, map) = exclusive(m);
227    for slot in 0..map.keys.len() {
228        if !map.occupied[slot] {
229            continue;
230        }
231        inc(keep);
232        inc(map.keys[slot]);
233        inc(map.values[slot]);
234        if unbox(apply(keep, &[map.keys[slot], map.values[slot]])) == 0 {
235            vacate(map, slot);
236        }
237    }
238    compact(map);
239    m
240}
241
242/// A map with the keys of `m`, in the same order, each bound to `f key value`. Borrows
243/// both arguments.
244pub unsafe fn map_values(f: Obj, m: Obj) -> Obj {
245    let old = get(m);
246    let copy = new();
247    let new = &mut *copy.header().cast::<Map>();
248    new.values = Vec::with_capacity(old.values.len());
249    for slot in 0..old.keys.len() {
250        if !old.occupied[slot] {
251            new.values.push(box_(0));
252            continue;
253        }
254        inc(f);
255        inc(old.keys[slot]);
256        inc(old.keys[slot]);
257        inc(old.values[slot]);
258        new.values.push(apply(f, &[old.keys[slot], old.values[slot]]));
259    }
260    new.keys = old.keys.clone();
261    new.occupied = old.occupied.clone();
262    new.hashes = old.hashes.clone();
263    new.len = old.len;
264    new.index = old.index.clone();
265    copy
266}
267
268/// The number of entries, as a `Nat`.
269pub unsafe fn size(m: Obj) -> Obj {
270    box_(get(m).len)
271}
272
273/// The entries in insertion order, as a `List (κ × α)`. Borrows `m`.
274pub unsafe fn to_list(m: Obj) -> Obj {
275    let map = get(m);
276    let mut list = box_(0);
277    for slot in (0..map.keys.len()).rev().filter(|&slot| map.occupied[slot]) {
278        inc(map.keys[slot]);
279        inc(map.values[slot]);
280        let pair = alloc_ctor(0, 2, 0, 0);
281        ctor_set(pair, 0, map.keys[slot]);
282        ctor_set(pair, 1, map.values[slot]);
283        let cell = alloc_ctor(1, 2, 0, 0);
284        ctor_set(cell, 0, pair);
285        ctor_set(cell, 1, list);
286        list = cell;
287    }
288    list
289}
290
291/// The entries of a map, for a caller that owns nothing: each key and value is borrowed.
292pub unsafe fn entries<'a>(m: Obj) -> impl Iterator<Item = (Obj, Obj)> + 'a {
293    let map = get(m);
294    (0..map.keys.len()).filter(|&slot| map.occupied[slot]).map(|slot| (map.keys[slot], map.values[slot]))
295}
296
297/// The functions of this module that generated code may call. Their names in Lean's
298/// `@[extern]` attributes are `inlean_map_` followed by the name here.
299pub(crate) const OPS: &[&str] = &["empty", "insert", "get_opt", "erase", "size", "to_list", "filter", "map_values"];