xur-runtime 0.1.8

Values, native-function registry and facet conversions for the Xur language
Documentation
//! Signatures for raw functions, which work on Xur values directly and so
//! have no Rust types to describe them: what they take and return, for
//! hovers, inlay hints and generated docs.

use facet::Facet;

use super::builder::{BuiltinBuilder, ModuleBuilder, ReturnHint, TypeBuilder, XurType};
use super::{Context, Registry};
use crate::marshal::TypeDesc;
use crate::{RunResult, Value};
use xur_resolve::NativeFnId;

/// A raw function's parameters and return type, as documented.
#[derive(Clone, Default)]
pub struct RawSig {
    pub params: Vec<RawParam>,
    /// `None` for `()`.
    pub ret: Option<TypeDesc>,
    /// What the LSP infers the result to be, when `ret` isn't a shape it can
    /// read (`list<T>` from a list: [`XurType::List`] of `Param(0)`).
    pub lsp: Option<XurType>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawParam {
    pub name: &'static str,
    pub ty: TypeDesc,
    /// May be left out (trailing parameters only).
    pub optional: bool,
    /// Takes any number of further arguments (the last parameter only).
    pub rest: bool,
}

impl RawSig {
    /// No parameters, returning `()`.
    pub fn new() -> Self {
        Self::default()
    }

    /// A required parameter.
    pub fn param(self, name: &'static str, ty: impl Into<TypeDesc>) -> Self {
        self.push(name, ty.into(), false, false)
    }

    /// A trailing parameter that may be left out.
    pub fn optional(self, name: &'static str, ty: impl Into<TypeDesc>) -> Self {
        self.push(name, ty.into(), true, false)
    }

    /// Any number of further arguments, each of type `ty`.
    pub fn rest(self, name: &'static str, ty: impl Into<TypeDesc>) -> Self {
        self.push(name, ty.into(), true, true)
    }

    /// The return type.
    pub fn returns(mut self, ty: impl Into<TypeDesc>) -> Self {
        self.ret = Some(ty.into());
        self
    }

    /// The return type as the LSP should infer it.
    pub fn lsp(mut self, ty: XurType) -> Self {
        self.lsp = Some(ty);
        self
    }

    fn push(mut self, name: &'static str, ty: TypeDesc, optional: bool, rest: bool) -> Self {
        self.params.push(RawParam {
            name,
            ty,
            optional,
            rest,
        });
        self
    }

    fn names(&self) -> Vec<String> {
        self.params.iter().map(|p| p.name.to_string()).collect()
    }
}

impl From<&'static str> for TypeDesc {
    /// A type by name: `"str"`, `"T"`, `"fn(T) -> bool"`.
    fn from(name: &'static str) -> Self {
        TypeDesc::Name(name)
    }
}

impl TypeDesc {
    /// The type `T`, named as the registry names it.
    pub fn of<T: Facet<'static>>() -> Self {
        TypeDesc::Shape(T::SHAPE)
    }
}

impl Registry {
    pub(super) fn set_raw_sig(&self, id: NativeFnId, sig: RawSig) {
        // Keep the LSP's inference: an explicit hint, or the shape returned.
        let hint = match (sig.lsp, &sig.ret) {
            (Some(xur), _) => Some(ReturnHint::Xur(xur)),
            (None, Some(TypeDesc::Shape(shape))) => Some(ReturnHint::Shape(shape)),
            (None, None) => Some(ReturnHint::Xur(XurType::UNIT)),
            _ => None,
        };
        self.with_fn_mut(id, |f| {
            f.return_hint = hint;
            f.raw_sig = Some(sig);
        });
    }
}

impl ModuleBuilder<'_> {
    /// A raw function (see [`raw_function`](Self::raw_function)) with its
    /// signature, for hovers and docs.
    pub fn raw_function_sig(
        &mut self,
        name: &str,
        sig: RawSig,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let id = self.add_raw(name, sig.names(), Box::new(f));
        self.registry().set_raw_sig(id, sig);
        self
    }
}

impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
    /// A raw method, the object first in `args`, with its signature (not
    /// counting the object).
    pub fn raw_method_sig(
        &mut self,
        name: &str,
        sig: RawSig,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let names = std::iter::once("self".to_string())
            .chain(sig.names())
            .collect();
        let id = self.add_raw(name, names, Box::new(f));
        self.registry().set_raw_sig(id, sig);
        self
    }

    /// A raw associated function, `Type::name(..)`, with its signature.
    pub fn raw_function_sig(
        &mut self,
        name: &str,
        sig: RawSig,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let id = self.add_raw(name, sig.names(), Box::new(f));
        self.registry().set_raw_sig(id, sig);
        self
    }
}

impl BuiltinBuilder<'_> {
    /// A raw method, the receiver first in `args`, with its signature (not
    /// counting the receiver).
    pub fn raw_method_sig(
        &mut self,
        name: &str,
        sig: RawSig,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let id = self.add_raw(name, sig.names(), Box::new(f));
        self.registry().set_raw_sig(id, sig);
        self
    }
}