use alloc::vec::Vec;
use core::fmt;
use intern_lang::Symbol;
use token_lang::Span;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Context(u32);
impl Context {
pub const ROOT: Self = Self(0);
#[inline]
#[must_use]
pub const fn is_root(self) -> bool {
self.0 == 0
}
#[inline]
#[must_use]
pub const fn as_u32(self) -> u32 {
self.0
}
}
impl fmt::Display for Context {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Origin {
pub parent: Context,
pub macro_name: Symbol,
pub call_site: Span,
pub call_context: Context,
}
#[derive(Clone, Copy, Debug)]
struct ContextData {
parent: Context,
expansion: usize,
}
#[derive(Clone, Copy, Debug)]
struct ExpansionData {
macro_name: Symbol,
call_site: Span,
call_context: Context,
depth: u32,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Hygiene {
contexts: Vec<ContextData>,
expansions: Vec<ExpansionData>,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Checkpoint {
contexts: usize,
expansions: usize,
}
impl Hygiene {
#[inline]
fn data(&self, ctx: Context) -> Option<&ContextData> {
let index = usize::try_from(ctx.0).ok()?.checked_sub(1)?;
self.contexts.get(index)
}
#[inline]
pub(crate) fn depth(&self, ctx: Context) -> u32 {
self.data(ctx)
.and_then(|data| self.expansions.get(data.expansion))
.map_or(0, |expansion| expansion.depth)
}
pub(crate) fn origin(&self, ctx: Context) -> Option<Origin> {
let data = self.data(ctx)?;
let expansion = self.expansions.get(data.expansion)?;
Some(Origin {
parent: data.parent,
macro_name: expansion.macro_name,
call_site: expansion.call_site,
call_context: expansion.call_context,
})
}
#[inline]
pub(crate) fn sizes(&self) -> (usize, usize) {
(self.contexts.len(), self.expansions.len())
}
#[inline]
pub(crate) fn checkpoint(&self) -> Checkpoint {
Checkpoint {
contexts: self.contexts.len(),
expansions: self.expansions.len(),
}
}
#[inline]
pub(crate) fn rollback(&mut self, checkpoint: Checkpoint) {
self.contexts.truncate(checkpoint.contexts);
self.expansions.truncate(checkpoint.expansions);
}
pub(crate) fn begin(
&mut self,
macro_name: Symbol,
call_site: Span,
call_context: Context,
depth: u32,
) -> usize {
let index = self.expansions.len();
self.expansions.push(ExpansionData {
macro_name,
call_site,
call_context,
depth,
});
index
}
pub(crate) fn mark(
&mut self,
parent: Context,
expansion: usize,
cache: &mut Vec<(Context, Context)>,
) -> Option<Context> {
if let Some(&(_, minted)) = cache.iter().find(|(from, _)| *from == parent) {
return Some(minted);
}
let raw = u32::try_from(self.contexts.len()).ok()?.checked_add(1)?;
self.contexts.push(ContextData { parent, expansion });
let minted = Context(raw);
cache.push((parent, minted));
Some(minted)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use alloc::string::ToString;
use super::*;
fn sym(n: u32) -> Symbol {
Symbol::from_u32(n).unwrap()
}
#[test]
fn test_root_is_zero_and_default() {
assert!(Context::ROOT.is_root());
assert_eq!(Context::default(), Context::ROOT);
assert_eq!(Context::ROOT.as_u32(), 0);
}
#[test]
fn test_display_uses_hash_notation() {
assert_eq!(Context(7).to_string(), "#7");
}
#[test]
fn test_mark_mints_one_context_per_parent() {
let mut table = Hygiene::default();
let e = table.begin(sym(1), Span::new(0, 1), Context::ROOT, 1);
let mut cache = Vec::new();
let a = table.mark(Context::ROOT, e, &mut cache).unwrap();
let b = table.mark(Context::ROOT, e, &mut cache).unwrap();
assert_eq!(a, b);
assert!(!a.is_root());
let c = table.mark(a, e, &mut cache).unwrap();
assert_ne!(a, c);
}
#[test]
fn test_separate_expansions_mint_distinct_contexts() {
let mut table = Hygiene::default();
let e1 = table.begin(sym(1), Span::new(0, 1), Context::ROOT, 1);
let a = table.mark(Context::ROOT, e1, &mut Vec::new()).unwrap();
let e2 = table.begin(sym(1), Span::new(5, 6), Context::ROOT, 1);
let b = table.mark(Context::ROOT, e2, &mut Vec::new()).unwrap();
assert_ne!(a, b);
}
#[test]
fn test_origin_reports_expansion_fields() {
let mut table = Hygiene::default();
let e = table.begin(sym(4), Span::new(3, 9), Context::ROOT, 1);
let ctx = table.mark(Context::ROOT, e, &mut Vec::new()).unwrap();
let origin = table.origin(ctx).unwrap();
assert_eq!(origin.macro_name, sym(4));
assert_eq!(origin.call_site, Span::new(3, 9));
assert_eq!(origin.parent, Context::ROOT);
assert_eq!(origin.call_context, Context::ROOT);
}
#[test]
fn test_origin_of_root_and_unknown_is_none() {
let table = Hygiene::default();
assert!(table.origin(Context::ROOT).is_none());
assert!(table.origin(Context(42)).is_none());
}
#[test]
fn test_depth_follows_expansion() {
let mut table = Hygiene::default();
assert_eq!(table.depth(Context::ROOT), 0);
let e = table.begin(sym(1), Span::new(0, 1), Context::ROOT, 3);
let ctx = table.mark(Context::ROOT, e, &mut Vec::new()).unwrap();
assert_eq!(table.depth(ctx), 3);
assert_eq!(table.depth(Context(99)), 0);
}
#[test]
fn test_rollback_discards_later_records() {
let mut table = Hygiene::default();
let saved = table.checkpoint();
let e = table.begin(sym(1), Span::new(0, 1), Context::ROOT, 1);
let ctx = table.mark(Context::ROOT, e, &mut Vec::new()).unwrap();
table.rollback(saved);
assert!(table.origin(ctx).is_none());
assert_eq!(table.checkpoint().contexts, 0);
assert_eq!(table.checkpoint().expansions, 0);
}
}