2019-11-22 12:43:36 -06:00
|
|
|
//! Trace is a pretty niche data structure which is used when lowering a CST
|
|
|
|
//! into HIR.
|
|
|
|
//!
|
|
|
|
//! Lowering process calculates two bits of information:
|
|
|
|
//! * the lowered syntax itself
|
|
|
|
//! * a mapping between lowered syntax and original syntax
|
|
|
|
//!
|
|
|
|
//! Due to the way salsa works, the mapping is usually hot lava, as it contains
|
|
|
|
//! absolute offsets. The `Trace` structure (inspired, at least in name, by
|
|
|
|
//! Kotlin's `BindingTrace`) allows use the same code to compute both
|
|
|
|
//! projections.
|
2021-01-14 18:02:08 -06:00
|
|
|
use la_arena::{Arena, ArenaMap, Idx, RawIdx};
|
2019-11-22 12:43:36 -06:00
|
|
|
|
2020-03-19 10:00:11 -05:00
|
|
|
pub(crate) struct Trace<T, V> {
|
|
|
|
arena: Option<Arena<T>>,
|
|
|
|
map: Option<ArenaMap<Idx<T>, V>>,
|
2019-11-22 12:43:36 -06:00
|
|
|
len: u32,
|
|
|
|
}
|
|
|
|
|
2020-03-19 10:00:11 -05:00
|
|
|
impl<T, V> Trace<T, V> {
|
|
|
|
pub(crate) fn new_for_arena() -> Trace<T, V> {
|
2019-11-24 08:49:49 -06:00
|
|
|
Trace { arena: Some(Arena::default()), map: None, len: 0 }
|
2019-11-22 12:43:36 -06:00
|
|
|
}
|
|
|
|
|
2020-03-19 10:00:11 -05:00
|
|
|
pub(crate) fn new_for_map() -> Trace<T, V> {
|
2019-11-24 08:49:49 -06:00
|
|
|
Trace { arena: None, map: Some(ArenaMap::default()), len: 0 }
|
2019-11-22 12:43:36 -06:00
|
|
|
}
|
|
|
|
|
2020-03-19 10:00:11 -05:00
|
|
|
pub(crate) fn alloc(&mut self, value: impl FnOnce() -> V, data: impl FnOnce() -> T) -> Idx<T> {
|
2019-11-24 08:49:49 -06:00
|
|
|
let id = if let Some(arena) = &mut self.arena {
|
|
|
|
arena.alloc(data())
|
2019-11-22 12:43:36 -06:00
|
|
|
} else {
|
2021-01-14 18:02:08 -06:00
|
|
|
let id = Idx::<T>::from_raw(RawIdx::from(self.len));
|
2019-11-22 12:43:36 -06:00
|
|
|
self.len += 1;
|
2019-11-24 08:49:49 -06:00
|
|
|
id
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(map) = &mut self.map {
|
|
|
|
map.insert(id, value());
|
2019-11-22 12:43:36 -06:00
|
|
|
}
|
2019-11-24 08:49:49 -06:00
|
|
|
id
|
|
|
|
}
|
|
|
|
|
2020-03-19 10:00:11 -05:00
|
|
|
pub(crate) fn into_arena(mut self) -> Arena<T> {
|
2019-11-24 08:49:49 -06:00
|
|
|
self.arena.take().unwrap()
|
2019-11-22 12:43:36 -06:00
|
|
|
}
|
|
|
|
|
2020-03-19 10:00:11 -05:00
|
|
|
pub(crate) fn into_map(mut self) -> ArenaMap<Idx<T>, V> {
|
2019-11-24 08:49:49 -06:00
|
|
|
self.map.take().unwrap()
|
2019-11-22 12:43:36 -06:00
|
|
|
}
|
|
|
|
}
|