Skip to main content

fic/base/
id.rs

1//! Ids: a node another node refers to lives in an arena, an [`IdVec`], and
2//! is referred to by its index there, a `u32` newtype per kind. A kind's
3//! id indexes only its own arena, so a `ChanId` can never look up a
4//! process.
5//!
6//! System items and every mapping are indexed in the environment's arenas,
7//! a program's locals in its PD's `locals` there, its events and processes
8//! in its body's, and a body's variables in its own `body_vars`:
9//! an id is meaningful only beside the arena it came from.
10
11use std::fmt;
12use std::marker::PhantomData;
13use std::ops::{Index, IndexMut};
14
15use serde::{Serialize, Serializer};
16
17impl PdId {
18    /// The highest id a protection domain can have: a system holds at most
19    /// 63 protection domains, Microkit's limit. The 64th declaration gets
20    /// no id.
21    pub const MAX: PdId = PdId(62);
22}
23
24/// An arena index.
25pub trait Idx: Copy {
26    /// The id of the `index`-th node.
27    fn new(index: usize) -> Self;
28    /// The position this id stands for.
29    fn index(self) -> usize;
30}
31
32macro_rules! id {
33    ($($(#[$doc:meta])* $name:ident),* $(,)?) => {
34        $(
35            $(#[$doc])*
36            #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
37            #[serde(transparent)]
38            pub struct $name(u32);
39
40            impl Idx for $name {
41                fn new(index: usize) -> Self {
42                    Self(u32::try_from(index).expect("fewer than 2^32 nodes of one kind"))
43                }
44                fn index(self) -> usize {
45                    self.0 as usize
46                }
47            }
48        )*
49    };
50}
51
52id! {
53    /// A memory region, in the environment's `mrs`.
54    MrId,
55    /// A protection domain, in the environment's `pds`; at most
56    /// [`PdId::MAX`].
57    PdId,
58    /// A channel, in the environment's `chans`.
59    ChanId,
60    /// A system struct, in the environment's `structs`.
61    StructId,
62    /// A system const, in the environment's `consts`.
63    ConstId,
64    /// An imported file, in the foreign store's `modules`.
65    ModuleId,
66    /// A called foreign function, in the environment's `ffis`.
67    FfnId,
68    /// A mapping, in the environment's `mappings`, project-wide.
69    MappingId,
70    /// A local variable, in its program's `locals` in the environment.
71    LocalVarId,
72    /// An event, in its program's body's `events`.
73    EventId,
74    /// A process, in its program's body's `processes`.
75    ProcId,
76    /// A variable of one process or event body, in that body's `body_vars`.
77    BodyVarId,
78}
79
80/// A `Vec<T>` indexed by `I`.
81pub struct IdVec<I, T> {
82    items: Vec<T>,
83    id: PhantomData<fn(I) -> I>,
84}
85
86impl<I: Idx, T> IdVec<I, T> {
87    /// An empty arena.
88    pub fn new() -> Self {
89        Self {
90            items: Vec::new(),
91            id: PhantomData,
92        }
93    }
94
95    /// Add `item`; returns its id.
96    pub fn push(&mut self, item: T) -> I {
97        let id = I::new(self.items.len());
98        self.items.push(item);
99        id
100    }
101
102    /// The node `id` names, if it is in this arena.
103    pub fn get(&self, id: I) -> Option<&T> {
104        self.items.get(id.index())
105    }
106
107    /// Every node, in id order.
108    pub fn iter(&self) -> impl Iterator<Item = &T> {
109        self.items.iter()
110    }
111
112    /// Every node, mutably, in id order.
113    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
114        self.items.iter_mut()
115    }
116
117    /// Every node with its id, in id order.
118    pub fn iter_enumerated(&self) -> impl Iterator<Item = (I, &T)> {
119        self.items.iter().enumerate().map(|(i, t)| (I::new(i), t))
120    }
121
122    /// Every node with its id, mutably, in id order.
123    pub fn iter_enumerated_mut(&mut self) -> impl Iterator<Item = (I, &mut T)> {
124        self.items
125            .iter_mut()
126            .enumerate()
127            .map(|(i, t)| (I::new(i), t))
128    }
129
130    /// Every node with its id, taken out of the arena, in id order.
131    pub fn into_iter_enumerated(self) -> impl Iterator<Item = (I, T)> {
132        self.items
133            .into_iter()
134            .enumerate()
135            .map(|(i, t)| (I::new(i), t))
136    }
137
138    /// Number of nodes.
139    pub fn len(&self) -> usize {
140        self.items.len()
141    }
142
143    /// Whether the arena is empty.
144    pub fn is_empty(&self) -> bool {
145        self.items.is_empty()
146    }
147}
148
149impl<I: Idx, T> Default for IdVec<I, T> {
150    fn default() -> Self {
151        Self::new()
152    }
153}
154
155impl<I: Idx, T> FromIterator<T> for IdVec<I, T> {
156    fn from_iter<It: IntoIterator<Item = T>>(items: It) -> Self {
157        Self {
158            items: items.into_iter().collect(),
159            id: PhantomData,
160        }
161    }
162}
163
164impl<I: Idx, T> Index<I> for IdVec<I, T> {
165    type Output = T;
166    fn index(&self, id: I) -> &T {
167        &self.items[id.index()]
168    }
169}
170
171impl<I: Idx, T> IndexMut<I> for IdVec<I, T> {
172    fn index_mut(&mut self, id: I) -> &mut T {
173        &mut self.items[id.index()]
174    }
175}
176
177impl<I, T: Clone> Clone for IdVec<I, T> {
178    fn clone(&self) -> Self {
179        Self {
180            items: self.items.clone(),
181            id: PhantomData,
182        }
183    }
184}
185
186impl<I, T: fmt::Debug> fmt::Debug for IdVec<I, T> {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_list().entries(&self.items).finish()
189    }
190}
191
192/// Serialised as the list itself: an id is a position in it.
193impl<I, T: Serialize> Serialize for IdVec<I, T> {
194    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
195        self.items.serialize(serializer)
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn push_returns_the_index_it_is_looked_up_by() {
205        let mut arena: IdVec<PdId, &str> = IdVec::new();
206        let a = arena.push("a");
207        let b = arena.push("b");
208        assert_eq!((a.index(), b.index()), (0, 1));
209        assert_eq!(arena[b], "b");
210        assert_eq!(
211            arena.iter_enumerated().collect::<Vec<_>>(),
212            vec![(a, &"a"), (b, &"b")]
213        );
214        assert!(arena.get(PdId::new(2)).is_none());
215    }
216
217    #[test]
218    fn serialises_as_its_list() {
219        let mut arena: IdVec<BodyVarId, u8> = IdVec::new();
220        arena.push(7);
221        assert_eq!(serde_json::to_string(&arena).unwrap(), "[7]");
222        assert_eq!(serde_json::to_string(&BodyVarId::new(3)).unwrap(), "3");
223    }
224}