Skip to main content

yomi_core/package/
reg.rs

1//! Registering a package's commands and variables.
2
3use super::*;
4
5/// A typed registration entry passed to [`Package::register`].
6///
7/// Registration failures (the first half of a name is not `P::NAME`, double registration of the same name, and so on) are
8/// remembered (the first one), and [`Registry::package`] returns it as `Err` (the registry is then unchanged).
9pub struct PackageReg<'r, P: Package> {
10    pub(super) reg: &'r mut Registry,
11    pub(super) package: usize,
12    pub(super) error: Option<RegistryError>,
13    /// The name of the command, variable or type registered just before (what `alias`, `doc` and `param_names` attach to).
14    pub(super) last: Option<String>,
15    /// Whether what was registered just before is a command.
16    pub(super) last_is_command: bool,
17    pub(super) _package: PhantomData<fn() -> P>,
18}
19
20impl<'r, P: Package> PackageReg<'r, P> {
21    /// Makes the registration entry of a package. `package` is the position of the package.
22    pub(crate) fn new(reg: &'r mut Registry, package: usize) -> Self {
23        Self {
24            reg,
25            package,
26            error: None,
27            last: None,
28            last_is_command: false,
29            _package: PhantomData,
30        }
31    }
32
33    /// Finishes registration. If there was an error along the way, returns the first error.
34    pub(crate) fn finish(self) -> Result<(), RegistryError> {
35        match self.error {
36            Some(e) => Err(e),
37            None => Ok(()),
38        }
39    }
40
41    /// Records an error (keeps only the first one).
42    fn fail(&mut self, e: RegistryError) {
43        if self.error.is_none() {
44            self.error = Some(e);
45        }
46    }
47
48    /// Calls `f` for the command registered just before. `NoCommand` if the previous one is not a command.
49    fn with_last_command(
50        &mut self,
51        f: impl FnOnce(&mut Registry, &str) -> Result<(), RegistryError>,
52    ) -> &mut Self {
53        let result = match self.last.clone() {
54            Some(name) if self.last_is_command => f(self.reg, &name),
55            _ => Err(RegistryError::NoCommand),
56        };
57        if let Err(e) = result {
58            self.fail(e);
59        }
60        self
61    }
62
63    /// Receives the result of registering a command (on success, it becomes what `alias` and `doc` attach to).
64    fn done_command<T>(&mut self, name: &str, result: Result<T, RegistryError>) -> &mut Self {
65        match result {
66            Ok(_) => {
67                self.last = Some(name.to_string());
68                self.last_is_command = true;
69            }
70            Err(e) => self.fail(e),
71        }
72        self
73    }
74
75    /// Registers an old name (alias) of the command registered just before (section 2.2 of `spec/host/02-registry.md`). The
76    /// old name is `namespace.name`, and may be in another package's namespace.
77    pub fn alias(&mut self, old: &str) -> &mut Self {
78        self.with_last_command(|reg, name| reg.alias(old, name))
79    }
80
81    /// Adds a description to the command, variable or type registered just before.
82    pub fn doc(&mut self, text: &str) -> &mut Self {
83        match self.last.clone() {
84            Some(name) => {
85                if let Err(e) = self.reg.doc(&name, text) {
86                    self.fail(e);
87                }
88            }
89            None => self.fail(RegistryError::NoCommand),
90        }
91        self
92    }
93
94    /// Names the parameters of the command registered just before. The count must be the same as the parameters.
95    pub fn param_names(&mut self, names: &[&str]) -> &mut Self {
96        self.with_last_command(|reg, name| reg.param_names(name, names))
97    }
98
99    /// Adds default values to the parameters of the command registered just before (names are those given with
100    /// `param_names`; [`Registry::param_defaults`]).
101    pub fn defaults(&mut self, defaults: &[(&str, Value)]) -> &mut Self {
102        self.with_last_command(|reg, name| reg.param_defaults(name, defaults))
103    }
104
105    /// Makes parameter `index` (`str`) of the stop command registered just before a body that text tables can translate (such
106    /// as input prompts). It is replaced with that line's key only when the script writes it as a string literal and the line
107    /// has a stable ID.
108    pub fn text_param(&mut self, index: usize) -> &mut Self {
109        self.with_last_command(|reg, name| reg.text_param(name, index))
110    }
111
112    /// Registers a `struct` or `enum` (a type with `#[derive(YomiType)]`). The namespace must be the package's name
113    /// (`InvalidName` otherwise). Register the types it uses first.
114    pub fn ty<T: crate::registry::YomiDecl>(&mut self) -> &mut Self {
115        let decl = T::decl();
116        let name = decl.name.clone();
117        match self.reg.add_type(Some(P::NAME), decl) {
118            Ok(()) => {
119                self.last = Some(name);
120                self.last_is_command = false;
121            }
122            Err(e) => self.fail(e),
123        }
124        self
125    }
126
127    /// Registers an effect command. The function is `Fn(&mut Ctx<P>, args...) -> R` (`R` is `()`, a type usable in scripts,
128    /// or `Result<that, CommandError>`). Parameter and return types are derived from the function. The function is
129    /// `Send + Sync` (so the VM can run on other threads).
130    pub fn effect<Args, R, F: EffectFn<P, Args, R> + Send + Sync + 'static>(
131        &mut self,
132        name: &str,
133        f: F,
134    ) -> &mut Self {
135        let result = self.reg.add_native(
136            self.package,
137            name,
138            crate::registry::NativeKind::Effect,
139            F::arg_types(),
140            F::ret_ty(),
141            std::sync::Arc::new(move |env: Env<'_>, args: &[Value]| {
142                let mut ctx = Ctx::<P>::new(env)?;
143                f.call(&mut ctx, args)
144            }),
145        );
146        self.done_command(name, result)
147    }
148
149    /// Registers a query command. The function is `Fn(&Ctx<P>, args...) -> R`. It does not change state and returns the same
150    /// value for the same state. The return value cannot be `()`. The function is `Send + Sync`.
151    pub fn query<Args, R, F: QueryFn<P, Args, R> + Send + Sync + 'static>(
152        &mut self,
153        name: &str,
154        f: F,
155    ) -> &mut Self {
156        let result = self.reg.add_native(
157            self.package,
158            name,
159            crate::registry::NativeKind::Query,
160            F::arg_types(),
161            F::ret_ty(),
162            std::sync::Arc::new(move |env: Env<'_>, args: &[Value]| {
163                let ctx = Ctx::<P>::new(env)?;
164                f.call(&ctx, args)
165            }),
166        );
167        self.done_command(name, result)
168    }
169
170    /// Registers a stop command by declaring only its types (the host does the work).
171    pub fn stop<A: YomiArgs, R: YomiType>(&mut self, name: &str) -> &mut Self {
172        let result = self
173            .reg
174            .add_stop(name, A::types(), R::ty(), Some(P::NAME), None, None);
175        self.done_command(name, result)
176    }
177
178    /// Registers a stop command with validation. `check` is called with the evaluated arguments before the VM returns the stop
179    /// notification. If it is `Err`, it does not stop and becomes a runtime error (the VM adds the position). `check` is
180    /// `Send + Sync`.
181    pub fn stop_checked<A, R, F>(&mut self, name: &str, check: F) -> &mut Self
182    where
183        A: FromArgs + 'static,
184        R: YomiType,
185        F: Fn(A) -> Result<(), CommandError> + Send + Sync + 'static,
186    {
187        let verify =
188            crate::registry::StopCheck::new(move |args: &[Value]| match A::from_values(args) {
189                Some(a) => check(a),
190                None => Err(bad_args("stop")),
191            });
192        let result =
193            self.reg
194                .add_stop(name, A::types(), R::ty(), Some(P::NAME), Some(verify), None);
195        self.done_command(name, result)
196    }
197
198    /// Registers a stop command with checks of arguments and return values.
199    ///
200    /// - `check_args` is the same as `check` of `stop_checked` (called with the evaluated arguments before stopping; if `Err`,
201    ///   it does not stop and becomes a runtime error).
202    /// - `check_return` is called with the arguments at the stop and the returned value, after the type of the value the host
203    ///   returned with `Input::Return` has matched and before the value is passed to the script. If `Err`, `resume` returns a
204    ///   runtime error (the VM adds the position; the VM is left in the state after a runtime error and can be restored from a
205    ///   snapshot with `restore`).
206    /// - Both functions are `Send + Sync`.
207    pub fn stop_validated<A, R, F, G>(
208        &mut self,
209        name: &str,
210        check_args: F,
211        check_return: G,
212    ) -> &mut Self
213    where
214        A: FromArgs + 'static,
215        R: FromValue + 'static,
216        F: Fn(&A) -> Result<(), CommandError> + Send + Sync + 'static,
217        G: Fn(&A, &R) -> Result<(), CommandError> + Send + Sync + 'static,
218    {
219        let verify =
220            crate::registry::StopCheck::new(move |args: &[Value]| match A::from_values(args) {
221                Some(a) => check_args(&a),
222                None => Err(bad_args("stop")),
223            });
224        let verify_return =
225            crate::registry::RetCheck::new(move |args: &[Value], ret: &Value| {
226                match (A::from_values(args), R::from_value(ret)) {
227                    (Some(a), Some(r)) => check_return(&a, &r),
228                    _ => Err(bad_args("stop")),
229                }
230            });
231        let result = self.reg.add_stop(
232            name,
233            A::types(),
234            R::ty(),
235            Some(P::NAME),
236            Some(verify),
237            Some(verify_return),
238        );
239        self.done_command(name, result)
240    }
241
242    /// Registers a variable declared by the host. The name is `P::NAME.variable`. `.read_only()` makes it impossible for
243    /// scripts to assign to it. The type is one of `int`, `float`, `bool`, `str`.
244    pub fn var<T: YomiType + IntoValue>(
245        &mut self,
246        name: &str,
247        kind: Kind,
248        initial: T,
249    ) -> VarHandle<'_> {
250        match self
251            .reg
252            .add_var(Some(P::NAME), name, T::ty(), kind, initial.into_value())
253        {
254            Ok(index) => {
255                self.last = Some(name.to_string());
256                self.last_is_command = false;
257                self.reg.var_handle(Some(index))
258            }
259            Err(e) => {
260                self.fail(e);
261                self.reg.var_handle(None)
262            }
263        }
264    }
265}