| 1 |
/*! The [`Arena`], [`UniqueArena`], and [`Handle`] types. |
| 2 |
|
| 3 |
To improve translator performance and reduce memory usage, most structures are |
| 4 |
stored in an [`Arena`]. An `Arena<T>` stores a series of `T` values, indexed by |
| 5 |
[`Handle<T>`] values, which are just wrappers around integer indexes. |
| 6 |
For example, a `Function`'s expressions are stored in an `Arena<Expression>`, |
| 7 |
and compound expressions refer to their sub-expressions via `Handle<Expression>` |
| 8 |
values. |
| 9 |
|
| 10 |
A [`UniqueArena`] is just like an `Arena`, except that it stores only a single |
| 11 |
instance of each value. The value type must implement `Eq` and `Hash`. Like an |
| 12 |
`Arena`, inserting a value into a `UniqueArena` returns a `Handle` which can be |
| 13 |
used to efficiently access the value, without a hash lookup. Inserting a value |
| 14 |
multiple times returns the same `Handle`. |
| 15 |
|
| 16 |
If the `span` feature is enabled, both `Arena` and `UniqueArena` can associate a |
| 17 |
source code span with each element. |
| 18 |
|
| 19 |
[`Handle<T>`]: Handle |
| 20 |
*/ |
| 21 |
|
| 22 |
mod handle; |
| 23 |
mod handle_set; |
| 24 |
mod handlevec; |
| 25 |
mod range; |
| 26 |
mod unique_arena; |
| 27 |
|
| 28 |
pub use handle::{BadHandle, Handle}; |
| 29 |
pub(crate) use handle_set::HandleSet; |
| 30 |
pub(crate) use handlevec::HandleVec; |
| 31 |
pub use range::{BadRangeError, Range}; |
| 32 |
pub use unique_arena::UniqueArena; |
| 33 |
|
| 34 |
use alloc::vec::Vec; |
| 35 |
use core::{fmt, ops}; |
| 36 |
|
| 37 |
use crate::Span; |
| 38 |
|
| 39 |
use handle::Index; |
| 40 |
|
| 41 |
/// An arena holding some kind of component (e.g., type, constant, |
| 42 |
/// instruction, etc.) that can be referenced. |
| 43 |
/// |
| 44 |
/// Adding new items to the arena produces a strongly-typed [`Handle`]. |
| 45 |
/// The arena can be indexed using the given handle to obtain |
| 46 |
/// a reference to the stored item. |
| 47 |
#[derive(Clone)] |
| 48 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 49 |
#[cfg_attr(feature = "serialize", serde(transparent))] |
| 50 |
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] |
| 51 |
#[cfg_attr(test, derive(PartialEq))] |
| 52 |
pub struct Arena<T> { |
| 53 |
/// Values of this arena. |
| 54 |
data: Vec<T>, |
| 55 |
#[cfg_attr(feature = "serialize", serde(skip))] |
| 56 |
span_info: Vec<Span>, |
| 57 |
} |
| 58 |
|
| 59 |
impl<T> Default for Arena<T> { |
| 60 |
fn default() -> Self { |
| 61 |
Self::new() |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
impl<T: fmt::Debug> fmt::Debug for Arena<T> { |
| 66 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 67 |
f.debug_map().entries(self.iter()).finish() |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
impl<T> Arena<T> { |
| 72 |
/// Create a new arena with no initial capacity allocated. |
| 73 |
pub const fn new() -> Self { |
| 74 |
Arena { |
| 75 |
data: Vec::new(), |
| 76 |
span_info: Vec::new(), |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
/// Extracts the inner vector. |
| 81 |
#[allow(clippy::missing_const_for_fn)] // ignore due to requirement of #![feature(const_precise_live_drops)] |
| 82 |
pub fn into_inner(self) -> Vec<T> { |
| 83 |
self.data |
| 84 |
} |
| 85 |
|
| 86 |
/// Returns the current number of items stored in this arena. |
| 87 |
pub fn len(&self) -> usize { |
| 88 |
self.data.len() |
| 89 |
} |
| 90 |
|
| 91 |
/// Returns `true` if the arena contains no elements. |
| 92 |
pub fn is_empty(&self) -> bool { |
| 93 |
self.data.is_empty() |
| 94 |
} |
| 95 |
|
| 96 |
/// Returns an iterator over the items stored in this arena, returning both |
| 97 |
/// the item's handle and a reference to it. |
| 98 |
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Handle<T>, &T)> + ExactSizeIterator { |
| 99 |
self.data |
| 100 |
.iter() |
| 101 |
.enumerate() |
| 102 |
.map(|(i, v)| unsafe { (Handle::from_usize_unchecked(i), v) }) |
| 103 |
} |
| 104 |
|
| 105 |
/// Returns an iterator over the items stored in this arena, returning both |
| 106 |
/// the item's handle and a reference to it. |
| 107 |
pub fn iter_mut_span( |
| 108 |
&mut self, |
| 109 |
) -> impl DoubleEndedIterator<Item = (Handle<T>, &mut T, &Span)> + ExactSizeIterator { |
| 110 |
self.data |
| 111 |
.iter_mut() |
| 112 |
.zip(self.span_info.iter()) |
| 113 |
.enumerate() |
| 114 |
.map(|(i, (v, span))| unsafe { (Handle::from_usize_unchecked(i), v, span) }) |
| 115 |
} |
| 116 |
|
| 117 |
/// Drains the arena, returning an iterator over the items stored. |
| 118 |
pub fn drain(&mut self) -> impl DoubleEndedIterator<Item = (Handle<T>, T, Span)> { |
| 119 |
let arena = core::mem::take(self); |
| 120 |
arena |
| 121 |
.data |
| 122 |
.into_iter() |
| 123 |
.zip(arena.span_info) |
| 124 |
.enumerate() |
| 125 |
.map(|(i, (v, span))| unsafe { (Handle::from_usize_unchecked(i), v, span) }) |
| 126 |
} |
| 127 |
|
| 128 |
/// Returns a iterator over the items stored in this arena, |
| 129 |
/// returning both the item's handle and a mutable reference to it. |
| 130 |
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = (Handle<T>, &mut T)> { |
| 131 |
self.data |
| 132 |
.iter_mut() |
| 133 |
.enumerate() |
| 134 |
.map(|(i, v)| unsafe { (Handle::from_usize_unchecked(i), v) }) |
| 135 |
} |
| 136 |
|
| 137 |
/// Adds a new value to the arena, returning a typed handle. |
| 138 |
pub fn append(&mut self, value: T, span: Span) -> Handle<T> { |
| 139 |
let index = self.data.len(); |
| 140 |
self.data.push(value); |
| 141 |
self.span_info.push(span); |
| 142 |
Handle::from_usize(index) |
| 143 |
} |
| 144 |
|
| 145 |
/// Fetch a handle to an existing type. |
| 146 |
pub fn fetch_if<F: Fn(&T) -> bool>(&self, fun: F) -> Option<Handle<T>> { |
| 147 |
self.data |
| 148 |
.iter() |
| 149 |
.position(fun) |
| 150 |
.map(|index| unsafe { Handle::from_usize_unchecked(index) }) |
| 151 |
} |
| 152 |
|
| 153 |
/// Adds a value with a custom check for uniqueness: |
| 154 |
/// returns a handle pointing to |
| 155 |
/// an existing element if the check succeeds, or adds a new |
| 156 |
/// element otherwise. |
| 157 |
pub fn fetch_if_or_append<F: Fn(&T, &T) -> bool>( |
| 158 |
&mut self, |
| 159 |
value: T, |
| 160 |
span: Span, |
| 161 |
fun: F, |
| 162 |
) -> Handle<T> { |
| 163 |
if let Some(index) = self.data.iter().position(|d| fun(d, &value)) { |
| 164 |
unsafe { Handle::from_usize_unchecked(index) } |
| 165 |
} else { |
| 166 |
self.append(value, span) |
| 167 |
} |
| 168 |
} |
| 169 |
|
| 170 |
/// Adds a value with a check for uniqueness, where the check is plain comparison. |
| 171 |
pub fn fetch_or_append(&mut self, value: T, span: Span) -> Handle<T> |
| 172 |
where |
| 173 |
T: PartialEq, |
| 174 |
{ |
| 175 |
self.fetch_if_or_append(value, span, T::eq) |
| 176 |
} |
| 177 |
|
| 178 |
pub fn try_get(&self, handle: Handle<T>) -> Result<&T, BadHandle> { |
| 179 |
self.data |
| 180 |
.get(handle.index()) |
| 181 |
.ok_or_else(|| BadHandle::new(handle)) |
| 182 |
} |
| 183 |
|
| 184 |
/// Get a mutable reference to an element in the arena. |
| 185 |
pub fn get_mut(&mut self, handle: Handle<T>) -> &mut T { |
| 186 |
self.data.get_mut(handle.index()).unwrap() |
| 187 |
} |
| 188 |
|
| 189 |
/// Get the range of handles from a particular number of elements to the end. |
| 190 |
pub fn range_from(&self, old_length: usize) -> Range<T> { |
| 191 |
let range = old_length as u32..self.data.len() as u32; |
| 192 |
Range::from_index_range(range, self) |
| 193 |
} |
| 194 |
|
| 195 |
/// Clears the arena keeping all allocations |
| 196 |
pub fn clear(&mut self) { |
| 197 |
self.data.clear() |
| 198 |
} |
| 199 |
|
| 200 |
pub fn get_span(&self, handle: Handle<T>) -> Span { |
| 201 |
*self |
| 202 |
.span_info |
| 203 |
.get(handle.index()) |
| 204 |
.unwrap_or(&Span::default()) |
| 205 |
} |
| 206 |
|
| 207 |
/// Assert that `handle` is valid for this arena. |
| 208 |
pub fn check_contains_handle(&self, handle: Handle<T>) -> Result<(), BadHandle> { |
| 209 |
if handle.index() < self.data.len() { |
| 210 |
Ok(()) |
| 211 |
} else { |
| 212 |
Err(BadHandle::new(handle)) |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
/// Assert that `range` is valid for this arena. |
| 217 |
pub fn check_contains_range(&self, range: &Range<T>) -> Result<(), BadRangeError> { |
| 218 |
// Since `range.inner` is a `Range<u32>`, we only need to check that the |
| 219 |
// start precedes the end, and that the end is in range. |
| 220 |
if range.inner.start > range.inner.end { |
| 221 |
return Err(BadRangeError::new(range.clone())); |
| 222 |
} |
| 223 |
|
| 224 |
// Empty ranges are tolerated: they can be produced by compaction. |
| 225 |
if range.inner.start == range.inner.end { |
| 226 |
return Ok(()); |
| 227 |
} |
| 228 |
|
| 229 |
let last_handle = Handle::new(Index::new(range.inner.end - 1).unwrap()); |
| 230 |
if self.check_contains_handle(last_handle).is_err() { |
| 231 |
return Err(BadRangeError::new(range.clone())); |
| 232 |
} |
| 233 |
|
| 234 |
Ok(()) |
| 235 |
} |
| 236 |
|
| 237 |
#[cfg(feature = "compact")] |
| 238 |
pub(crate) fn retain_mut<P>(&mut self, mut predicate: P) |
| 239 |
where |
| 240 |
P: FnMut(Handle<T>, &mut T) -> bool, |
| 241 |
{ |
| 242 |
let mut index = 0; |
| 243 |
let mut retained = 0; |
| 244 |
self.data.retain_mut(|elt| { |
| 245 |
let handle = Handle::from_usize(index); |
| 246 |
let keep = predicate(handle, elt); |
| 247 |
|
| 248 |
// Since `predicate` needs mutable access to each element, |
| 249 |
// we can't feasibly call it twice, so we have to compact |
| 250 |
// spans by hand in parallel as part of this iteration. |
| 251 |
if keep { |
| 252 |
self.span_info[retained] = self.span_info[index]; |
| 253 |
retained += 1; |
| 254 |
} |
| 255 |
|
| 256 |
index += 1; |
| 257 |
keep |
| 258 |
}); |
| 259 |
|
| 260 |
self.span_info.truncate(retained); |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
#[cfg(feature = "deserialize")] |
| 265 |
impl<'de, T> serde::Deserialize<'de> for Arena<T> |
| 266 |
where |
| 267 |
T: serde::Deserialize<'de>, |
| 268 |
{ |
| 269 |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 270 |
where |
| 271 |
D: serde::Deserializer<'de>, |
| 272 |
{ |
| 273 |
let data = Vec::deserialize(deserializer)?; |
| 274 |
let span_info = core::iter::repeat_n(Span::default(), data.len()).collect(); |
| 275 |
|
| 276 |
Ok(Self { data, span_info }) |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
impl<T> ops::Index<Handle<T>> for Arena<T> { |
| 281 |
type Output = T; |
| 282 |
fn index(&self, handle: Handle<T>) -> &T { |
| 283 |
&self.data[handle.index()] |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
impl<T> ops::IndexMut<Handle<T>> for Arena<T> { |
| 288 |
fn index_mut(&mut self, handle: Handle<T>) -> &mut T { |
| 289 |
&mut self.data[handle.index()] |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
impl<T> ops::Index<Range<T>> for Arena<T> { |
| 294 |
type Output = [T]; |
| 295 |
fn index(&self, range: Range<T>) -> &[T] { |
| 296 |
&self.data[range.inner.start as usize..range.inner.end as usize] |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
#[cfg(test)] |
| 301 |
mod tests { |
| 302 |
use super::*; |
| 303 |
|
| 304 |
#[test] |
| 305 |
fn append_non_unique() { |
| 306 |
let mut arena: Arena<u8> = Arena::new(); |
| 307 |
let t1 = arena.append(0, Default::default()); |
| 308 |
let t2 = arena.append(0, Default::default()); |
| 309 |
assert!(t1 != t2); |
| 310 |
assert!(arena[t1] == arena[t2]); |
| 311 |
} |
| 312 |
|
| 313 |
#[test] |
| 314 |
fn append_unique() { |
| 315 |
let mut arena: Arena<u8> = Arena::new(); |
| 316 |
let t1 = arena.append(0, Default::default()); |
| 317 |
let t2 = arena.append(1, Default::default()); |
| 318 |
assert!(t1 != t2); |
| 319 |
assert!(arena[t1] != arena[t2]); |
| 320 |
} |
| 321 |
|
| 322 |
#[test] |
| 323 |
fn fetch_or_append_non_unique() { |
| 324 |
let mut arena: Arena<u8> = Arena::new(); |
| 325 |
let t1 = arena.fetch_or_append(0, Default::default()); |
| 326 |
let t2 = arena.fetch_or_append(0, Default::default()); |
| 327 |
assert!(t1 == t2); |
| 328 |
assert!(arena[t1] == arena[t2]) |
| 329 |
} |
| 330 |
|
| 331 |
#[test] |
| 332 |
fn fetch_or_append_unique() { |
| 333 |
let mut arena: Arena<u8> = Arena::new(); |
| 334 |
let t1 = arena.fetch_or_append(0, Default::default()); |
| 335 |
let t2 = arena.fetch_or_append(1, Default::default()); |
| 336 |
assert!(t1 != t2); |
| 337 |
assert!(arena[t1] != arena[t2]); |
| 338 |
} |
| 339 |
} |