yomi_core/registry/decl.rs
1//! Types of registry declarations (commands, variables, package entries, sugar).
2
3use super::*;
4
5/// The string type (`str` in scripts).
6pub type Str = String;
7
8/// The ID of a command (in registration order).
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub struct CommandId(pub u32);
11
12/// The kind of sugar.
13#[non_exhaustive]
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Sugar {
16 /// A plain line.
17 Plain,
18 /// A quote line.
19 Quote,
20 /// A choice.
21 Choice,
22}
23
24impl Sugar {
25 /// The name used in diagnostic arguments.
26 pub fn name(self) -> &'static str {
27 match self {
28 Sugar::Plain => "plain",
29 Sugar::Quote => "quote",
30 Sugar::Choice => "choice",
31 }
32 }
33}
34
35/// A sugar binding.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub(crate) enum Binding {
38 /// Bound to a stop command.
39 Command(CommandId),
40 /// Ignored (only checked).
41 Ignored,
42}
43
44/// The kind of a command (section 2.3 of `spec/host/02-registry.md`).
45#[non_exhaustive]
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum CommandKind {
48 /// Effect. The VM calls the function. Changes its own package's state. Does not stop.
49 Effect,
50 /// Query. The VM calls the function. Only reads state and returns a value.
51 Query,
52 /// Stop. The VM stops and the host does the work.
53 Stop,
54}
55
56impl CommandKind {
57 /// The name used in diagnostic arguments.
58 pub fn name(self) -> &'static str {
59 match self {
60 CommandKind::Effect => "effect",
61 CommandKind::Query => "query",
62 CommandKind::Stop => "stop",
63 }
64 }
65}
66
67/// The declaration of a stop command.
68#[derive(Debug, Clone, PartialEq)]
69pub struct StopDecl {
70 /// The command name (`package.command`).
71 pub name: String,
72 /// Parameter types.
73 pub args: Vec<Ty>,
74 /// The return type.
75 pub ret: Ty,
76 /// The package that provides the command (only when registered with `Registry::package`). Scripts cannot use this command
77 /// unless they `import` that package.
78 pub package: Option<String>,
79 /// Parameter names (only those given at registration; as many as the parameters).
80 pub params: Vec<Option<String>>,
81 /// Default values of parameters (as many as the parameters; parameters with defaults come last).
82 pub defaults: Vec<Option<Value>>,
83 /// A description (used for completion in tools).
84 pub doc: Option<String>,
85 /// The indices of parameters (`str`) that a text table can translate. Only when the script writes them as string literals
86 /// and the line has a stable ID, they are replaced with the translation under that line's key (`module.label#id`)
87 /// (section 5.2a of `spec/host/05-texts.md`).
88 pub text_param: Option<usize>,
89}
90
91/// The kind of a variable (section 2.7 of `spec/host/02-registry.md`).
92#[non_exhaustive]
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum Kind {
95 /// A variable in saves (same as `save var` in scripts).
96 Save,
97 /// A variable in persistent data (same as `persistent var` in scripts).
98 Persistent,
99}
100
101/// A variable declared by the host.
102#[derive(Debug, Clone, PartialEq)]
103pub struct VarDecl {
104 /// The name (`package.variable`).
105 pub name: String,
106 /// The type (`int`, `float`, `bool`, `str`).
107 pub ty: Ty,
108 /// Kind.
109 pub kind: Kind,
110 /// The initial value.
111 pub init: Value,
112 /// Whether scripts cannot assign to it.
113 pub read_only: bool,
114 /// A description (used for completion in tools).
115 pub doc: Option<String>,
116}
117
118/// The continuation of registering a variable (to add `.read_only()`).
119#[derive(Debug)]
120pub struct VarHandle<'r> {
121 pub(super) var: Option<&'r mut VarDecl>,
122}
123
124impl VarHandle<'_> {
125 /// Makes the variable one that scripts cannot assign to (a compile error; the host can still write it with `set_var`).
126 pub fn read_only(mut self) -> Self {
127 if let Some(v) = self.var.as_deref_mut() {
128 v.read_only = true;
129 }
130 self
131 }
132
133 /// Adds a description to the variable (written to declaration files).
134 pub fn doc(mut self, text: &str) -> Self {
135 if let Some(v) = self.var.as_deref_mut() {
136 v.doc = Some(text.to_string());
137 }
138 self
139 }
140}
141
142/// The kind of effect / query (internal).
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub(crate) enum NativeKind {
145 Effect,
146 Query,
147}
148
149/// A registered function (type-erased).
150pub(crate) type NativeFn =
151 Arc<dyn Fn(Env<'_>, &[Value]) -> Result<Value, CommandError> + Send + Sync>;
152
153/// An effect or query command.
154#[derive(Clone)]
155pub(crate) struct NativeDecl {
156 pub name: String,
157 pub kind: NativeKind,
158 pub args: Vec<Ty>,
159 pub ret: Ty,
160 /// An index into `Registry::packages`.
161 pub package: usize,
162 pub func: NativeFn,
163 pub params: Vec<Option<String>>,
164 pub defaults: Vec<Option<Value>>,
165 pub doc: Option<String>,
166}
167
168impl std::fmt::Debug for NativeDecl {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 f.debug_struct("NativeDecl")
171 .field("name", &self.name)
172 .field("kind", &self.kind)
173 .finish_non_exhaustive()
174 }
175}
176
177/// Validation of the arguments of a stop command (called before the VM returns the stop notification).
178#[derive(Clone)]
179pub(crate) struct StopCheck(Arc<StopCheckFn>);
180
181/// A function that validates the arguments of a stop command.
182type StopCheckFn = dyn Fn(&[Value]) -> Result<(), CommandError> + Send + Sync;
183
184impl StopCheck {
185 /// Makes one from a checking function.
186 pub(crate) fn new(
187 f: impl Fn(&[Value]) -> Result<(), CommandError> + Send + Sync + 'static,
188 ) -> Self {
189 Self(Arc::new(f))
190 }
191
192 /// Checks the arguments.
193 pub(crate) fn run(&self, args: &[Value]) -> Result<(), CommandError> {
194 (self.0)(args)
195 }
196}
197
198impl std::fmt::Debug for StopCheck {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 write!(f, "StopCheck(..)")
201 }
202}
203
204/// Validation of the return value of a stop command (called by `resume` before passing the value received from the host to
205/// the script).
206#[derive(Clone)]
207pub(crate) struct RetCheck(Arc<RetCheckFn>);
208
209/// A function that validates the return value of a stop command (the arguments at the stop, and the value returned).
210type RetCheckFn = dyn Fn(&[Value], &Value) -> Result<(), CommandError> + Send + Sync;
211
212impl RetCheck {
213 /// Makes one from a checking function.
214 pub(crate) fn new(
215 f: impl Fn(&[Value], &Value) -> Result<(), CommandError> + Send + Sync + 'static,
216 ) -> Self {
217 Self(Arc::new(f))
218 }
219
220 /// Checks the arguments and the return value given by the host.
221 pub(crate) fn run(&self, args: &[Value], ret: &Value) -> Result<(), CommandError> {
222 (self.0)(args, ret)
223 }
224}
225
226impl std::fmt::Debug for RetCheck {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 write!(f, "RetCheck(..)")
229 }
230}
231
232/// The result of looking up a command by name (internal).
233#[derive(Debug, Clone)]
234pub(crate) struct CommandInfo {
235 /// The official name (when looked up by an alias, the name the alias points to).
236 pub name: String,
237 /// Whether it was found by an alias (use of an old name; subject to a warning).
238 pub via_alias: bool,
239 pub kind: CommandKind,
240 pub args: Vec<Ty>,
241 pub ret: Ty,
242 /// The namespace that scripts must `import` (only for package commands; when looked up by an alias, the alias's
243 /// namespace).
244 pub package: Option<String>,
245 /// Parameter names (`None` if not given).
246 pub params: Vec<Option<String>>,
247 /// Default values of parameters.
248 pub defaults: Vec<Option<Value>>,
249}
250
251/// The declaration of a command (of any kind; for tools and declaration files; [`Registry::commands`]).
252#[derive(Debug, Clone, PartialEq)]
253pub struct CommandDecl {
254 /// The name (`package.command`).
255 pub name: String,
256 /// Kind.
257 pub kind: CommandKind,
258 /// Parameter types.
259 pub args: Vec<Ty>,
260 /// The return type (`()` if none).
261 pub ret: Ty,
262 /// Parameter names (only those given at registration).
263 pub params: Vec<Option<String>>,
264 /// Old names (aliases), in name order.
265 pub aliases: Vec<String>,
266 /// A description.
267 pub doc: Option<String>,
268 /// The package that provides the command.
269 pub package: Option<String>,
270 /// Default values of parameters (as many as the parameters).
271 pub defaults: Vec<Option<Value>>,
272}
273
274/// Information about a registered package (for declaration files and tools).
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct PackageDecl {
277 /// The name.
278 pub name: String,
279 /// The version of the state slice.
280 pub version: u32,
281 /// The version of the persistent slice.
282 pub persistent_version: u32,
283 /// The packages whose state this reads.
284 pub depends: Vec<String>,
285}
286
287/// A type-erased package entry passed to bulk registration ([`Registry::package_set`]). Made with
288/// [`packages!`](crate::packages).
289#[derive(Clone, Copy)]
290pub struct PackageItem {
291 pub(super) name: &'static str,
292 pub(super) depends: &'static [&'static str],
293 pub(super) stage: fn(&mut Registry) -> Result<(), RegistryError>,
294}
295
296impl PackageItem {
297 /// The entry for package `P`.
298 pub fn of<P: Package>() -> Self {
299 Self {
300 name: P::NAME,
301 depends: P::DEPENDS,
302 stage: |reg| {
303 reg.packages.push(PackageEntry::of::<P>());
304 let index = reg.packages.len() - 1;
305 let mut pr = PackageReg::<P>::new(reg, index);
306 P::register(&mut pr);
307 pr.finish()
308 },
309 }
310 }
311
312 /// The name of the package.
313 pub fn name(&self) -> &'static str {
314 self.name
315 }
316}
317
318impl std::fmt::Debug for PackageItem {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 write!(f, "PackageItem({})", self.name)
321 }
322}
323
324/// Turns multiple packages into a list passed to [`Registry::package_set`].
325///
326/// ```
327/// # use yomi_core::{packages, Registry, Package, PackageReg};
328/// # struct A; struct B;
329/// # impl Package for A { const NAME: &'static str = "a"; const DEPENDS: &'static [&'static str] = &["b"];
330/// # type State = (); type Persistent = (); fn register(_: &mut PackageReg<'_, Self>) {} }
331/// # impl Package for B { const NAME: &'static str = "b";
332/// # type State = (); type Persistent = (); fn register(_: &mut PackageReg<'_, Self>) {} }
333/// let mut reg = Registry::new();
334/// reg.package_set(&packages![A, B]).unwrap(); // A depends on B, but they are reordered
335/// ```
336#[macro_export]
337macro_rules! packages {
338 ($($p:ty),* $(,)?) => {
339 [$($crate::PackageItem::of::<$p>()),*]
340 };
341}