use std::any::Any;
use std::sync::Arc;
use facet::{Def, Facet, Partial, ScalarType, Type, UserType};
use xur_resolve::{AttrError, AttrInput, AttrLit, AttributeKind};
type Builder = Partial<'static, false>;
pub(crate) struct AttributeSpec {
pub kind: AttributeKind,
#[allow(clippy::type_complexity)]
pub parse:
Arc<dyn Fn(&AttrInput) -> Result<Arc<dyn Any + Send + Sync>, AttrError> + Send + Sync>,
}
pub(crate) fn spec<T>(kind: AttributeKind) -> AttributeSpec
where
T: Facet<'static> + Send + Sync,
{
AttributeSpec {
kind,
parse: Arc::new(|input: &AttrInput| {
let value = parse::<T>(input)?;
Ok(Arc::new(value) as Arc<dyn Any + Send + Sync>)
}),
}
}
fn parse<T: Facet<'static>>(input: &AttrInput) -> Result<T, AttrError> {
let partial = Partial::alloc_owned::<T>().map_err(reflect)?;
let partial = drive(partial, input)?;
let heap = partial.build().map_err(reflect)?;
heap.materialize::<T>().map_err(reflect)
}
fn drive(mut partial: Builder, input: &AttrInput) -> Result<Builder, AttrError> {
let shape = partial.shape();
match shape.ty {
Type::User(UserType::Enum(e)) => {
let Some(word) = input.words.first() else {
return Err(AttrError::new(
"this attribute takes a word, e.g. `#[name(value)]`",
));
};
let idx = e
.variants
.iter()
.position(|v| v.name.eq_ignore_ascii_case(word))
.ok_or_else(|| AttrError::new(format!("unknown option `{word}`")))?;
partial = partial.select_nth_variant(idx).map_err(reflect)?;
Ok(partial)
}
Type::User(UserType::Struct(st)) => {
let mut args = input.args.iter().peekable();
for (i, field) in st.fields.iter().enumerate() {
if let Some((_, lit)) = input.pairs.iter().find(|(k, _)| k == field.name) {
partial = partial.begin_nth_field(i).map_err(reflect)?;
partial = set_leaf(partial, lit)?;
partial = partial.end().map_err(reflect)?;
} else if input.words.iter().any(|w| w == field.name) {
partial = partial.set_nth_field::<bool>(i, true).map_err(reflect)?;
} else if let Def::List(list) = field.shape().def {
partial = partial.begin_nth_field(i).map_err(reflect)?;
partial = partial.init_list().map_err(reflect)?;
while let Some(lit) = args.next_if(|lit| accepts(list.t(), lit)) {
partial = partial.begin_list_item().map_err(reflect)?;
partial = set_leaf(partial, lit)?;
partial = partial.end().map_err(reflect)?;
}
partial = partial.end().map_err(reflect)?;
} else if let Some(lit) = args.next_if(|lit| accepts(field.shape(), lit)) {
partial = partial.begin_nth_field(i).map_err(reflect)?;
partial = set_leaf(partial, lit)?;
partial = partial.end().map_err(reflect)?;
} else {
partial = partial.set_nth_field_to_default(i).map_err(|_| {
AttrError::new(format!("attribute is missing `{}`", field.name))
})?;
}
}
if args.peek().is_some() {
return Err(AttrError::new("too many arguments"));
}
Ok(partial)
}
_ => Err(AttrError::new("an attribute type must be a struct or enum")),
}
}
fn accepts(shape: &facet::Shape, lit: &AttrLit) -> bool {
if let Def::Option(option) = shape.def {
return accepts(option.t(), lit);
}
let Some(scalar) = ScalarType::try_from_shape(shape) else {
return false;
};
match lit {
AttrLit::Str(_) => scalar == ScalarType::String,
AttrLit::Bool(_) => scalar == ScalarType::Bool,
AttrLit::Float(_) => matches!(scalar, ScalarType::F32 | ScalarType::F64),
AttrLit::Int(_) => !matches!(scalar, ScalarType::String | ScalarType::Bool),
}
}
fn set_leaf(mut partial: Builder, lit: &AttrLit) -> Result<Builder, AttrError> {
let shape = partial.shape();
if matches!(shape.def, Def::Option(_)) {
partial = partial.begin_some().map_err(reflect)?;
partial = set_leaf(partial, lit)?;
return partial.end().map_err(reflect);
}
let scalar = ScalarType::try_from_shape(shape)
.ok_or_else(|| AttrError::new("unsupported attribute field type"))?;
macro_rules! int {
($ty:ty) => {{
let AttrLit::Int(n) = lit else {
return Err(AttrError::new("expected an integer"));
};
let v = <$ty>::try_from(*n as i128)
.map_err(|_| AttrError::new(format!("{n} does not fit the field type")))?;
partial.set(v)
}};
}
let result = match (scalar, lit) {
(ScalarType::Bool, AttrLit::Bool(b)) => partial.set(*b),
(ScalarType::String, AttrLit::Str(s)) => partial.set(s.clone()),
(ScalarType::F64, AttrLit::Float(f)) => partial.set(*f),
(ScalarType::F32, AttrLit::Float(f)) => partial.set(*f as f32),
(ScalarType::F64, AttrLit::Int(n)) => partial.set(*n as f64),
(ScalarType::F32, AttrLit::Int(n)) => partial.set(*n as f32),
(ScalarType::U8, _) => int!(u8),
(ScalarType::U16, _) => int!(u16),
(ScalarType::U32, _) => int!(u32),
(ScalarType::U64, _) => int!(u64),
(ScalarType::USize, _) => int!(usize),
(ScalarType::I8, _) => int!(i8),
(ScalarType::I16, _) => int!(i16),
(ScalarType::I32, _) => int!(i32),
(ScalarType::I64, _) => int!(i64),
(ScalarType::ISize, _) => int!(isize),
_ => return Err(AttrError::new("attribute value has the wrong type")),
};
result.map_err(reflect)
}
fn reflect(error: impl std::fmt::Display) -> AttrError {
AttrError::new(error.to_string())
}