Skip to main content

xur_runtime/registry/
raw_sig.rs

1//! Signatures for raw functions, which work on Xur values directly and so
2//! have no Rust types to describe them: what they take and return, for
3//! hovers, inlay hints and generated docs.
4
5use facet::Facet;
6
7use super::builder::{BuiltinBuilder, ModuleBuilder, ReturnHint, TypeBuilder, XurType};
8use super::{Context, Registry};
9use crate::marshal::TypeDesc;
10use crate::{RunResult, Value};
11use xur_resolve::NativeFnId;
12
13/// A raw function's parameters and return type, as documented.
14#[derive(Clone, Default)]
15pub struct RawSig {
16    pub params: Vec<RawParam>,
17    /// `None` for `()`.
18    pub ret: Option<TypeDesc>,
19    /// What the LSP infers the result to be, when `ret` isn't a shape it can
20    /// read (`list<T>` from a list: [`XurType::List`] of `Param(0)`).
21    pub lsp: Option<XurType>,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct RawParam {
26    pub name: &'static str,
27    pub ty: TypeDesc,
28    /// May be left out (trailing parameters only).
29    pub optional: bool,
30    /// Takes any number of further arguments (the last parameter only).
31    pub rest: bool,
32}
33
34impl RawSig {
35    /// No parameters, returning `()`.
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    /// A required parameter.
41    pub fn param(self, name: &'static str, ty: impl Into<TypeDesc>) -> Self {
42        self.push(name, ty.into(), false, false)
43    }
44
45    /// A trailing parameter that may be left out.
46    pub fn optional(self, name: &'static str, ty: impl Into<TypeDesc>) -> Self {
47        self.push(name, ty.into(), true, false)
48    }
49
50    /// Any number of further arguments, each of type `ty`.
51    pub fn rest(self, name: &'static str, ty: impl Into<TypeDesc>) -> Self {
52        self.push(name, ty.into(), true, true)
53    }
54
55    /// The return type.
56    pub fn returns(mut self, ty: impl Into<TypeDesc>) -> Self {
57        self.ret = Some(ty.into());
58        self
59    }
60
61    /// The return type as the LSP should infer it.
62    pub fn lsp(mut self, ty: XurType) -> Self {
63        self.lsp = Some(ty);
64        self
65    }
66
67    fn push(mut self, name: &'static str, ty: TypeDesc, optional: bool, rest: bool) -> Self {
68        self.params.push(RawParam {
69            name,
70            ty,
71            optional,
72            rest,
73        });
74        self
75    }
76
77    fn names(&self) -> Vec<String> {
78        self.params.iter().map(|p| p.name.to_string()).collect()
79    }
80}
81
82impl From<&'static str> for TypeDesc {
83    /// A type by name: `"str"`, `"T"`, `"fn(T) -> bool"`.
84    fn from(name: &'static str) -> Self {
85        TypeDesc::Name(name)
86    }
87}
88
89impl TypeDesc {
90    /// The type `T`, named as the registry names it.
91    pub fn of<T: Facet<'static>>() -> Self {
92        TypeDesc::Shape(T::SHAPE)
93    }
94}
95
96impl Registry {
97    pub(super) fn set_raw_sig(&self, id: NativeFnId, sig: RawSig) {
98        // Keep the LSP's inference: an explicit hint, or the shape returned.
99        let hint = match (sig.lsp, &sig.ret) {
100            (Some(xur), _) => Some(ReturnHint::Xur(xur)),
101            (None, Some(TypeDesc::Shape(shape))) => Some(ReturnHint::Shape(shape)),
102            (None, None) => Some(ReturnHint::Xur(XurType::UNIT)),
103            _ => None,
104        };
105        self.with_fn_mut(id, |f| {
106            f.return_hint = hint;
107            f.raw_sig = Some(sig);
108        });
109    }
110}
111
112impl ModuleBuilder<'_> {
113    /// A raw function (see [`raw_function`](Self::raw_function)) with its
114    /// signature, for hovers and docs.
115    pub fn raw_function_sig(
116        &mut self,
117        name: &str,
118        sig: RawSig,
119        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
120    ) -> &mut Self {
121        let id = self.add_raw(name, sig.names(), Box::new(f));
122        self.registry().set_raw_sig(id, sig);
123        self
124    }
125}
126
127impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
128    /// A raw method, the object first in `args`, with its signature (not
129    /// counting the object).
130    pub fn raw_method_sig(
131        &mut self,
132        name: &str,
133        sig: RawSig,
134        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
135    ) -> &mut Self {
136        let names = std::iter::once("self".to_string())
137            .chain(sig.names())
138            .collect();
139        let id = self.add_raw(name, names, Box::new(f));
140        self.registry().set_raw_sig(id, sig);
141        self
142    }
143
144    /// A raw associated function, `Type::name(..)`, with its signature.
145    pub fn raw_function_sig(
146        &mut self,
147        name: &str,
148        sig: RawSig,
149        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
150    ) -> &mut Self {
151        let id = self.add_raw(name, sig.names(), Box::new(f));
152        self.registry().set_raw_sig(id, sig);
153        self
154    }
155}
156
157impl BuiltinBuilder<'_> {
158    /// A raw method, the receiver first in `args`, with its signature (not
159    /// counting the receiver).
160    pub fn raw_method_sig(
161        &mut self,
162        name: &str,
163        sig: RawSig,
164        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
165    ) -> &mut Self {
166        let id = self.add_raw(name, sig.names(), Box::new(f));
167        self.registry().set_raw_sig(id, sig);
168        self
169    }
170}