xur-runtime 0.1.10

Values, native-function registry and facet conversions for the Xur language
Documentation
//! Parsing a registered attribute's arguments into its `#[derive(Facet)]` type.
//!
//! A registered attribute names a Rust type authored to match its syntax: an
//! enum for single-word attributes (`#[jit(always)]` → a variant) or a struct
//! with scalar / `Option` fields for `name = value` attributes (`#[field(offset
//! = 100)]` → fields). The [`AttrInput`] (built in resolution, facet-free) is
//! driven straight into a `facet::Partial`, so absent optional fields default
//! to `None` without needing any language context.

use std::any::Any;
use std::sync::Arc;

use facet::{Def, Facet, Partial, ScalarType, Type, UserType};
use xur_resolve::{AttrError, AttrInput, AttrLit, AttributeKind};

/// A move-based facet builder, as `convert.rs` uses it.
type Builder = Partial<'static, false>;

/// A registered attribute: where it may appear, and how to parse its args into
/// the type it was registered with (type-erased).
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>,
}

/// Builds the spec for an attribute whose arguments parse into `T`.
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 {
        // Enum: a single bare word selects the variant (case-insensitive).
        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)
        }
        // Struct: `name = value` fills a field; a bare word sets a bool flag;
        // plain literals fill the remaining fields in order (skipping any that
        // can't hold the literal, and a list field takes all that are left);
        // anything else defaults (so `Option` fields become `None`).
        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")),
    }
}

/// Whether a field of `shape` can hold `lit` (after unwrapping an `Option`):
/// strings take strings, bools bools, integers integers, floats any number.
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),
    }
}

/// Sets one scalar leaf (unwrapping an `Option` first) from an attribute lit.
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),
        // A whole number for a float field: `#[range(0, 100)]` on f64 bounds.
        (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())
}