use alloc::vec::Vec;
use core::fmt;
use token_lang::Span;
use crate::context::Hygiene;
use crate::matcher::{Matcher, Outcome};
use crate::transcribe::{Expansion, Scratch, transcribe};
use crate::{Context, ExpandError, Macro, Origin, Tree};
pub struct Expander<K> {
hygiene: Hygiene,
matcher: Matcher<K>,
scratch: Scratch<K>,
limit: u32,
}
impl<K> Expander<K> {
pub const DEFAULT_LIMIT: u32 = 128;
#[must_use]
pub fn new() -> Self {
Self::with_limit(Self::DEFAULT_LIMIT)
}
#[must_use]
pub fn with_limit(limit: u32) -> Self {
Self {
hygiene: Hygiene::default(),
matcher: Matcher::default(),
scratch: Scratch::default(),
limit,
}
}
#[inline]
#[must_use]
pub const fn limit(&self) -> u32 {
self.limit
}
#[inline]
#[must_use]
pub fn origin(&self, ctx: Context) -> Option<Origin> {
self.hygiene.origin(ctx)
}
}
impl<K: Clone + PartialEq> Expander<K> {
pub fn expand(
&mut self,
mac: &Macro<K>,
input: &[Tree<K>],
call_site: Span,
call_context: Context,
) -> Result<Vec<Tree<K>>, ExpandError> {
let depth = self.hygiene.depth(call_context).saturating_add(1);
if depth > self.limit {
return Err(ExpandError::RecursionLimit { limit: self.limit });
}
self.matcher.load(input);
let mut furthest = 0;
for (index, rule) in mac.rules().iter().enumerate() {
match self.matcher.run(rule) {
Outcome::Match => {
let checkpoint = self.hygiene.checkpoint();
let expansion = self
.hygiene
.begin(mac.name(), call_site, call_context, depth);
let result = transcribe(
Expansion {
rule,
index,
matcher: &self.matcher,
hygiene: &mut self.hygiene,
expansion,
},
&mut self.scratch,
);
if result.is_err() {
self.hygiene.rollback(checkpoint);
}
return result;
}
Outcome::Ambiguous => return Err(ExpandError::Ambiguous { rule: index }),
Outcome::NoMatch { furthest: reached } => furthest = furthest.max(reached),
}
}
Err(ExpandError::NoMatch {
span: self.matcher.span_at(furthest, call_site),
})
}
}
impl<K> Default for Expander<K> {
fn default() -> Self {
Self::new()
}
}
impl<K> fmt::Debug for Expander<K> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (contexts, expansions) = self.hygiene.sizes();
f.debug_struct("Expander")
.field("limit", &self.limit)
.field("contexts", &contexts)
.field("expansions", &expansions)
.finish()
}
}