Skip to main content

nsh_core/ui/
class.rs

1//! Classes: Rust types TypeScript uses as classes (`new Tally(3)`), written
2//! with `#[class]` on a struct and its `impl` block and registered with
3//! [`super::Registry::class`].
4//!
5//! An instance lives in Rust ([`Instance`]: the value in an `Rc<RefCell>`)
6//! and is owned by its JS object: the object being collected drops it, and
7//! `dispose()` (or `[Symbol.dispose]`) drops it at once; using the object
8//! after that throws. Members that are not `async` (the constructor
9//! `new`, `&self` / `&mut self` methods, getters and setters, statics) run
10//! inside the JS call, outside the core, converting JS values directly
11//! ([`JsValue::from_js`]); a method borrows its instance for the call, so
12//! a re-entrant use of it throws instead of aliasing. `async` members
13//! (`this: Instance<Self>`) are ops like `async` module functions: their
14//! arguments are converted in the JS call, the op carries the task's start
15//! (with the instance), and JS gets a promise the core's result settles
16//! (`super::call`). JS functions cross as callbacks (`super::callback`).
17
18use std::{
19    any::{Any, TypeId},
20    cell::{Ref, RefCell, RefMut},
21    fmt,
22    rc::Rc,
23};
24
25use super::{
26    JsValue, PropError, TsType, TsTypes,
27    call::{JsResult, TaskStart},
28    callback::{Trace, Tracer},
29    js::{JsHost, JsIn, JsOwned, JsRaw},
30    module::ModuleParam,
31};
32
33// --- The class -----------------------------------------------------------------------
34
35/// A Rust type JS uses as a class. `#[class]` on the struct (its
36/// [`Trace`]) and on its `impl` block (this) implements it.
37pub trait Class: Trace + Sized + 'static {
38    /// The class: its JS name (the type's), documentation and members.
39    const DEF: &'static ClassDef;
40}
41
42/// What a class is: its name and members (`#[class]` writes it).
43pub struct ClassDef {
44    /// Its JS name: the type's own (`Tally`).
45    pub name: &'static str,
46    /// Documentation (the struct's doc comment).
47    pub doc: &'static str,
48    /// The type, telling two classes of the same name apart.
49    pub type_id: fn() -> TypeId,
50    /// The type's Rust path, for messages (`app::ledger::Ledger`).
51    pub type_name: fn() -> &'static str,
52    /// Its members: the constructor, methods, accessors and statics.
53    pub members: &'static [Member],
54    /// Its objects come from members only and its module exports no value
55    /// of it: declared as an `interface` (`#[class(interface)]`: `fs`'s
56    /// `Stats`).
57    pub interface: bool,
58}
59
60impl ClassDef {
61    /// Its constructor (`new`), if JS can make one.
62    pub fn constructor(&self) -> Option<&'static Member> {
63        self.members
64            .iter()
65            .find(|m| m.kind == MemberKind::Constructor)
66    }
67}
68
69impl fmt::Debug for ClassDef {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        f.debug_struct("ClassDef")
72            .field("name", &self.name)
73            .finish_non_exhaustive()
74    }
75}
76
77/// What a member of a class is to JS.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum MemberKind {
80    /// `new Tally(...)`.
81    Constructor,
82    /// `tally.add(...)`.
83    Method,
84    /// `tally.count`.
85    Getter,
86    /// `tally.count = ...`.
87    Setter,
88    /// `Tally.parse(...)`.
89    Static,
90}
91
92/// A member of a class (`#[class]` makes them).
93pub struct Member {
94    /// Its JS name (`add`; a getter's and its setter's are the property's).
95    pub name: &'static str,
96    /// Documentation.
97    pub doc: &'static str,
98    /// What it is.
99    pub kind: MemberKind,
100    /// Its parameters.
101    pub params: &'static [ModuleParam],
102    /// The TypeScript type of its result (`None`: nothing).
103    pub returns: Option<TsType>,
104    /// The classes its parameters and result name.
105    pub refs: ClassRefs,
106    /// How it runs.
107    pub call: MemberCall,
108    /// The signatures TypeScript sees instead of the one its types give
109    /// (`#[overload(fn(..) -> ..)]`), as a module function's: what an
110    /// argument selects (`on("exit", ..)`).
111    pub overloads: &'static [super::Overload],
112}
113
114/// Adds the classes a signature names (its parameters' and result's
115/// types: [`Arg::classes`], [`Ret::classes`]) to the list: registering it
116/// registers them ([`super::Registry::class`]). Not stripped from builds
117/// without declarations: JS needs the classes there too.
118pub type ClassRefs = fn(&mut Vec<&'static ClassDef>);
119
120/// An `async` member's or function's call, its arguments (and instance)
121/// converted in the JS call: the start of its task.
122pub type AsyncCall = fn(&dyn JsHost) -> Result<TaskStart, Thrown>;
123
124/// How a member (or a synchronous module function) runs.
125#[derive(Clone, Copy)]
126pub enum MemberCall {
127    /// In the JS call, converting the call's values directly; the result
128    /// is an owned JS value.
129    Sync(fn(&dyn JsHost) -> Result<JsRaw, Thrown>),
130    /// As a task of the core, started in order with the UI's ops; JS gets
131    /// a promise.
132    Async(AsyncCall),
133    /// In the JS call, returning a task's start ([`super::Later`]): what
134    /// the call throws throws there; JS gets a promise of the task.
135    Start(AsyncCall),
136}
137
138impl MemberCall {
139    /// Whether JS gets a promise.
140    pub fn is_async(&self) -> bool {
141        matches!(self, MemberCall::Async(_) | MemberCall::Start(_))
142    }
143}
144
145/// What a synchronous call throws in JS.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Thrown {
148    /// A `TypeError`: a wrong argument, a disposed or busy instance.
149    Type(String),
150    /// A `RangeError`: a value past a limit ([`super::JsError::Range`]).
151    Range(String),
152    /// An `Error`: the member's `Err`, or its panic.
153    Error(String),
154    /// One of those with properties (`code`, ...: [`super::JsError::with`]).
155    Fields(Box<super::ErrorFields>),
156}
157
158impl Thrown {
159    /// Its message.
160    pub fn message(&self) -> &str {
161        match self {
162            Thrown::Type(m) | Thrown::Range(m) | Thrown::Error(m) => m,
163            Thrown::Fields(f) => &f.message,
164        }
165    }
166}
167
168impl From<PropError> for Thrown {
169    fn from(e: PropError) -> Self {
170        Thrown::Type(e.0)
171    }
172}
173
174impl From<String> for Thrown {
175    fn from(message: String) -> Self {
176        Thrown::Error(message)
177    }
178}
179
180impl From<&str> for Thrown {
181    fn from(message: &str) -> Self {
182        Thrown::Error(message.to_owned())
183    }
184}
185
186impl fmt::Display for Thrown {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.write_str(self.message())
189    }
190}
191
192// --- Instances ----------------------------------------------------------------
193
194/// An instance of class `C`: a handle of the value its JS object owns
195/// (cheap to clone). [`Instance::with`] / [`Instance::with_mut`] borrow
196/// the value: in an `async` member, between awaits.
197///
198/// A value whose JS object goes drops inside QuickJS's finalizer, in a
199/// collection or when the object's last reference goes, where no JS runs:
200/// a callback's `call` fails there, and `post` queues the call at the end
201/// for the next turn (not parked in program order). Before it drops, the callbacks the value alone keeps
202/// (its traced fields, and the instances it alone holds) are released. So
203/// a `Drop` that moves out an instance it held as the only handle (into a
204/// static, a task) keeps that instance, but with dead callbacks: calling
205/// them fails and posting them does nothing.
206pub struct Instance<C: 'static> {
207    cell: Rc<InstanceCell<C>>,
208}
209
210impl<C> Clone for Instance<C> {
211    fn clone(&self) -> Self {
212        Self {
213            cell: self.cell.clone(),
214        }
215    }
216}
217
218impl<C> fmt::Debug for Instance<C> {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        write!(f, "Instance<{}>", std::any::type_name::<C>())
221    }
222}
223
224/// What an [`Instance`] points to.
225struct InstanceCell<C> {
226    /// `None` once disposed.
227    value: RefCell<Option<C>>,
228}
229
230impl<C: Class> Instance<C> {
231    /// A new instance holding `value` (its JS object is made when it
232    /// reaches JS).
233    pub fn new(value: C) -> Self {
234        Self {
235            cell: Rc::new(InstanceCell {
236                value: RefCell::new(Some(value)),
237            }),
238        }
239    }
240
241    /// Runs `f` with the value borrowed.
242    ///
243    /// # Panics
244    ///
245    /// When the instance was disposed, or `f` runs while the value is
246    /// borrowed mutably (a re-entrant use).
247    #[track_caller]
248    pub fn with<R>(&self, f: impl FnOnce(&C) -> R) -> R {
249        match self.borrow() {
250            Ok(value) => f(&value),
251            Err(e) => panic!("{e}"),
252        }
253    }
254
255    /// Runs `f` with the value borrowed mutably.
256    ///
257    /// # Panics
258    ///
259    /// When the instance was disposed, or the value is borrowed (a
260    /// re-entrant use).
261    #[track_caller]
262    pub fn with_mut<R>(&self, f: impl FnOnce(&mut C) -> R) -> R {
263        match self.borrow_mut() {
264            Ok(mut value) => f(&mut value),
265            Err(e) => panic!("{e}"),
266        }
267    }
268
269    /// Whether the value was dropped ([`Instance::dispose`], JS's
270    /// `dispose()`).
271    pub fn is_disposed(&self) -> bool {
272        matches!(self.cell.value.try_borrow().as_deref(), Ok(None))
273    }
274
275    /// Drops the value now (JS's `dispose()`): its JS object throws when
276    /// used after. Nothing when it was dropped already.
277    ///
278    /// # Panics
279    ///
280    /// When the value is borrowed.
281    #[track_caller]
282    pub fn dispose(&self) {
283        if let Err(e) = self.cell.dispose() {
284            panic!("{e}");
285        }
286    }
287
288    /// Whether `self` and `other` are the same instance.
289    pub fn ptr_eq(&self, other: &Self) -> bool {
290        Rc::ptr_eq(&self.cell, &other.cell)
291    }
292
293    fn borrow(&self) -> Result<Ref<'_, C>, Thrown> {
294        let value = self
295            .cell
296            .value
297            .try_borrow()
298            .map_err(|_| Thrown::Type(format!("{} used re-entrantly", C::DEF.name)))?;
299        Ref::filter_map(value, Option::as_ref)
300            .map_err(|_| Thrown::Type(format!("{} is disposed", C::DEF.name)))
301    }
302
303    fn borrow_mut(&self) -> Result<RefMut<'_, C>, Thrown> {
304        let value = self
305            .cell
306            .value
307            .try_borrow_mut()
308            .map_err(|_| Thrown::Type(format!("{} used re-entrantly", C::DEF.name)))?;
309        RefMut::filter_map(value, Option::as_mut)
310            .map_err(|_| Thrown::Type(format!("{} is disposed", C::DEF.name)))
311    }
312
313    /// Whether this is the only handle of the instance (no JS object, task
314    /// or other value holds it).
315    pub(super) fn only_handle(&self) -> bool {
316        Rc::strong_count(&self.cell) == 1
317    }
318
319    /// Reports the callbacks the value keeps.
320    pub(super) fn trace_value(&self, tracer: &mut Tracer<'_>) {
321        self.cell.trace(tracer);
322    }
323
324    /// The instance, type-erased (what JS objects and the table hold).
325    fn erased(&self) -> Rc<dyn ClassInstance> {
326        self.cell.clone()
327    }
328
329    /// `any` as an instance of `C` (`None`: another class's).
330    fn of(any: Rc<dyn ClassInstance>) -> Option<Self> {
331        let any: Rc<dyn Any> = any;
332        any.downcast::<InstanceCell<C>>()
333            .ok()
334            .map(|cell| Self { cell })
335    }
336}
337
338/// An instance of some class, as its JS object and the table hold it.
339#[doc(hidden)]
340pub trait ClassInstance: Any {
341    /// Its class.
342    fn def(&self) -> &'static ClassDef;
343    /// Drops the value (`Err` when it is borrowed).
344    fn dispose(&self) -> Result<(), String>;
345    /// Whether it was disposed.
346    fn disposed(&self) -> bool;
347    /// Reports the callbacks the value keeps (nothing while it is
348    /// borrowed).
349    fn trace(&self, tracer: &mut Tracer<'_>);
350}
351
352impl<C: Class> ClassInstance for InstanceCell<C> {
353    fn def(&self) -> &'static ClassDef {
354        C::DEF
355    }
356
357    fn dispose(&self) -> Result<(), String> {
358        let value = self
359            .value
360            .try_borrow_mut()
361            .map_err(|_| format!("{} used re-entrantly", C::DEF.name))?
362            .take();
363        // Dropped after the borrow: its drop may reach JS (callbacks).
364        drop(value);
365        Ok(())
366    }
367
368    fn disposed(&self) -> bool {
369        matches!(self.value.try_borrow().as_deref(), Ok(None))
370    }
371
372    fn trace(&self, tracer: &mut Tracer<'_>) {
373        if let Ok(value) = self.value.try_borrow()
374            && let Some(value) = &*value
375        {
376            value.trace(tracer);
377        }
378    }
379}
380
381// --- What crosses -----------------------------------------------------------------
382
383/// A parameter of a class's member or a function: a [`JsValue`] type, an
384/// instance ([`Instance`]; `&Other` / `&mut Other` borrow one for the
385/// call) or a [`super::Callback`], converted from JS in the JS call.
386pub trait Arg: Sized {
387    /// Its TypeScript type.
388    fn ts_type(types: &mut TsTypes) -> String;
389    /// The value of a JS argument.
390    fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
391    /// Adds the classes the type names (an instance's, a callback's
392    /// arguments').
393    #[doc(hidden)]
394    fn classes(_out: &mut Vec<&'static ClassDef>) {}
395}
396
397impl<T: JsValue> Arg for T {
398    fn ts_type(types: &mut TsTypes) -> String {
399        T::ts_type(types)
400    }
401
402    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
403        T::from_js(value)
404    }
405}
406
407/// The instance a JS object of `C` holds (another class's, or another
408/// value, is refused).
409impl<C: Class> Arg for Instance<C> {
410    fn ts_type(types: &mut TsTypes) -> String {
411        types.class(C::DEF)
412    }
413
414    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
415        value
416            .host()
417            .instance(value.raw())
418            .and_then(Instance::of)
419            .ok_or_else(|| value.expected(&format!("a {}", C::DEF.name)))
420    }
421
422    fn classes(out: &mut Vec<&'static ClassDef>) {
423        out.push(C::DEF);
424    }
425}
426
427/// `null` or `undefined` is `None`.
428impl<C: Class> Arg for Option<Instance<C>> {
429    fn ts_type(types: &mut TsTypes) -> String {
430        format!("{} | null", <Instance<C> as Arg>::ts_type(types))
431    }
432
433    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
434        if value.is_nullish() {
435            return Ok(None);
436        }
437        Instance::from_js(value).map(Some)
438    }
439
440    fn classes(out: &mut Vec<&'static ClassDef>) {
441        out.push(C::DEF);
442    }
443}
444
445/// A result of a class's member: a [`JsValue`] type, `()`, an instance
446/// (the JS object it has, or a new one), or a class's value (`#[class]`
447/// implements it for the struct: a new instance).
448pub trait Ret: Sized {
449    /// `()`: nothing (a callback taking it has no parameters).
450    const UNIT: bool = false;
451    /// Its TypeScript type.
452    fn ts_type(types: &mut TsTypes) -> String;
453    /// The value for JS.
454    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
455    /// Adds the classes the type names (an instance's).
456    #[doc(hidden)]
457    fn classes(_out: &mut Vec<&'static ClassDef>) {}
458}
459
460impl<T: JsValue> Ret for T {
461    fn ts_type(types: &mut TsTypes) -> String {
462        T::ts_type(types)
463    }
464
465    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
466        self.to_js(host)
467    }
468}
469
470impl Ret for () {
471    const UNIT: bool = true;
472
473    fn ts_type(_types: &mut TsTypes) -> String {
474        "void".into()
475    }
476
477    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
478        Ok(JsOwned::new(host, host.undefined()))
479    }
480}
481
482impl<C: Class> Ret for Instance<C> {
483    fn ts_type(types: &mut TsTypes) -> String {
484        types.class(C::DEF)
485    }
486
487    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
488        Ok(JsOwned::new(host, host.wrap(self.erased())?))
489    }
490
491    fn classes(out: &mut Vec<&'static ClassDef>) {
492        out.push(C::DEF);
493    }
494}
495
496/// An array of instances' objects.
497impl<C: Class> Ret for Vec<Instance<C>> {
498    fn ts_type(types: &mut TsTypes) -> String {
499        format!("{}[]", types.class(C::DEF))
500    }
501
502    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
503        // Owned until the array takes them, as `Vec<T>`'s items are.
504        let mut items = Vec::with_capacity(self.len());
505        for instance in self {
506            items.push(instance.into_js(host)?);
507        }
508        let raws = items.into_iter().map(JsOwned::into_raw).collect();
509        Ok(JsOwned::new(host, host.new_array(raws)?))
510    }
511
512    fn classes(out: &mut Vec<&'static ClassDef>) {
513        out.push(C::DEF);
514    }
515}
516
517impl<C: Class> Ret for Option<Instance<C>> {
518    fn ts_type(types: &mut TsTypes) -> String {
519        format!("{} | null", <Instance<C> as Ret>::ts_type(types))
520    }
521
522    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
523        match self {
524            Some(i) => i.into_js(host),
525            None => Ok(JsOwned::new(host, host.null())),
526        }
527    }
528
529    fn classes(out: &mut Vec<&'static ClassDef>) {
530        out.push(C::DEF);
531    }
532}
533
534// --- Specs ------------------------------------------------------------------------
535
536/// One member, for the JS face and the declarations.
537#[derive(Debug, Clone)]
538pub struct MemberSpec {
539    /// Its JS name.
540    pub name: &'static str,
541    /// Documentation.
542    pub doc: &'static str,
543    /// What it is.
544    pub kind: MemberKind,
545    /// Its parameters: JS name, TypeScript type, optional.
546    pub params: Vec<(&'static str, String, bool)>,
547    /// The TypeScript type of its result (`None`: nothing).
548    pub returns: Option<String>,
549    /// JS gets a promise.
550    pub is_async: bool,
551    /// The signatures TypeScript sees instead ([`Member::overloads`]).
552    pub overloads: Vec<super::OverloadSpec>,
553}
554
555/// What a class is to JS and its declarations.
556#[derive(Debug, Clone)]
557pub struct ClassSpec {
558    /// Its JS name.
559    pub name: &'static str,
560    /// Documentation.
561    pub doc: &'static str,
562    /// Its members.
563    pub members: Vec<MemberSpec>,
564    /// The named TypeScript types they use.
565    pub types: TsTypes,
566    /// The class itself.
567    pub def: &'static ClassDef,
568}
569
570impl ClassSpec {
571    pub(crate) fn of(def: &'static ClassDef) -> Self {
572        let mut types = TsTypes::default();
573        let members = def
574            .members
575            .iter()
576            .map(|m| MemberSpec {
577                name: m.name,
578                doc: m.doc,
579                kind: m.kind,
580                params: m
581                    .params
582                    .iter()
583                    .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
584                    .collect(),
585                returns: m.returns.map(|ts| ts(&mut types)),
586                is_async: m.call.is_async(),
587                overloads: m
588                    .overloads
589                    .iter()
590                    .map(|o| {
591                        let params = o
592                            .params
593                            .iter()
594                            .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
595                            .collect();
596                        (params, o.returns.map(|ts| ts(&mut types)))
597                    })
598                    .collect(),
599            })
600            .collect();
601        Self {
602            name: def.name,
603            doc: def.doc,
604            members,
605            types,
606            def,
607        }
608    }
609}
610
611// --- What `#[class]` and `#[module]` call -----------------------------------------
612
613/// The generated code's helpers.
614#[doc(hidden)]
615pub(crate) mod __private {
616    use super::*;
617
618    /// `T`'s TypeScript type as a parameter, or nothing in builds without
619    /// declarations.
620    pub const fn arg_ts<T: Arg>() -> TsType {
621        if crate::ui::DECLARATIONS {
622            T::ts_type
623        } else {
624            |_| String::new()
625        }
626    }
627
628    /// The TypeScript type of `T`, a callback parameter whose function's
629    /// arguments `#[args(..)]` names `names`; nothing in builds without
630    /// declarations.
631    pub fn named_arg_ts<T: crate::ui::callback::NamedArgs>(
632        types: &mut TsTypes,
633        names: &[&str],
634    ) -> String {
635        if crate::ui::DECLARATIONS {
636            T::ts_named(types, names)
637        } else {
638            String::new()
639        }
640    }
641
642    /// `T`'s TypeScript type as a result.
643    pub const fn ret_ts<T: Ret>() -> TsType {
644        if crate::ui::DECLARATIONS {
645            T::ts_type
646        } else {
647            |_| String::new()
648        }
649    }
650
651    /// The class a struct's value makes a new instance of.
652    pub fn class_into_js<C: Class>(value: C, host: &dyn JsHost) -> Result<JsOwned<'_>, PropError> {
653        Instance::new(value).into_js(host)
654    }
655
656    /// `C`'s TypeScript type.
657    pub fn class_ts<C: Class>(types: &mut TsTypes) -> String {
658        types.class(C::DEF)
659    }
660
661    /// The classes parameter type `T` names.
662    pub fn arg_classes<T: Arg>(out: &mut Vec<&'static ClassDef>) {
663        T::classes(out);
664    }
665
666    /// The classes result type `T` names.
667    pub fn ret_classes<T: Ret>(out: &mut Vec<&'static ClassDef>) {
668        T::classes(out);
669    }
670
671    /// Class `C` itself (a struct's value as a result).
672    pub fn class_refs<C: Class>(out: &mut Vec<&'static ClassDef>) {
673        out.push(C::DEF);
674    }
675
676    /// Argument `i` of the call (`what`: `Tally.add`, `name`: `by`, for
677    /// the error).
678    pub fn arg<T: Arg>(host: &dyn JsHost, i: usize, what: &str, name: &str) -> Result<T, Thrown> {
679        T::from_js(JsIn::new(host, host.arg(i)))
680            .map_err(|e| Thrown::Type(format!("{what}: `{name}`: {e}")))
681    }
682
683    /// The instance `this` of the call is.
684    pub fn this<C: Class>(host: &dyn JsHost, what: &str) -> Result<Instance<C>, Thrown> {
685        host.instance(host.this())
686            .and_then(Instance::of)
687            .ok_or_else(|| {
688                Thrown::Type(format!("{what}: Illegal invocation: not a {}", C::DEF.name))
689            })
690    }
691
692    /// The value of `instance`, borrowed for a call.
693    pub fn borrow<C: Class>(instance: &Instance<C>) -> Result<Ref<'_, C>, Thrown> {
694        instance.borrow()
695    }
696
697    /// The value of `instance`, borrowed mutably for a call.
698    pub fn borrow_mut<C: Class>(instance: &Instance<C>) -> Result<RefMut<'_, C>, Thrown> {
699        instance.borrow_mut()
700    }
701
702    /// The value of `instance`, argument `name` of `what` (`Account.transfer`,
703    /// `to`), borrowed for the call: its error names them, as a wrong
704    /// argument's does (``Account.transfer: `to`: Account is disposed``).
705    pub fn borrow_arg<'a, C: Class>(
706        instance: &'a Instance<C>,
707        what: &str,
708        name: &str,
709    ) -> Result<Ref<'a, C>, Thrown> {
710        instance.borrow().map_err(|e| arg_error(e, what, name))
711    }
712
713    /// [`borrow_arg`], mutably.
714    pub fn borrow_arg_mut<'a, C: Class>(
715        instance: &'a Instance<C>,
716        what: &str,
717        name: &str,
718    ) -> Result<RefMut<'a, C>, Thrown> {
719        instance.borrow_mut().map_err(|e| arg_error(e, what, name))
720    }
721
722    /// `e`, an argument's error, after `what` and the argument's `name`.
723    fn arg_error(e: Thrown, what: &str, name: &str) -> Thrown {
724        match e {
725            Thrown::Type(m) => Thrown::Type(format!("{what}: `{name}`: {m}")),
726            Thrown::Range(m) => Thrown::Range(format!("{what}: `{name}`: {m}")),
727            Thrown::Error(m) => Thrown::Error(format!("{what}: `{name}`: {m}")),
728            Thrown::Fields(mut f) => {
729                f.message = format!("{what}: `{name}`: {}", f.message);
730                Thrown::Fields(f)
731            }
732        }
733    }
734
735    /// The result of a synchronous call as a JS value.
736    pub fn ret<T: Ret>(host: &dyn JsHost, value: T) -> Result<JsRaw, Thrown> {
737        value
738            .into_js(host)
739            .map(JsOwned::into_raw)
740            .map_err(|e| Thrown::Error(e.0))
741    }
742
743    /// [`ret`] of a `Result`: an `Err` throws an `Error` with its message
744    /// (a [`crate::ui::JsError`] its class).
745    pub fn ret_result<T: Ret, E: crate::ui::IntoThrown>(
746        host: &dyn JsHost,
747        value: Result<T, E>,
748    ) -> Result<JsRaw, Thrown> {
749        match value {
750            Ok(v) => ret(host, v),
751            Err(e) => Err(e.into_thrown()),
752        }
753    }
754
755    /// The task a synchronous call returned ([`crate::ui::Later`]).
756    pub fn start<T: Ret + 'static>(value: crate::ui::Later<T>) -> Result<TaskStart, Thrown> {
757        Ok(Box::new(move || value.into_future()))
758    }
759
760    /// [`start`] of a `Result`: an `Err` throws in the call.
761    pub fn start_result<T: Ret + 'static, E: crate::ui::IntoThrown>(
762        value: Result<crate::ui::Later<T>, E>,
763    ) -> Result<TaskStart, Thrown> {
764        value.map_err(E::into_thrown).and_then(start)
765    }
766
767    /// What the call can do beyond computing (a `cx: CallCx` parameter).
768    pub fn call_cx(host: &dyn JsHost) -> crate::ui::CallCx<'_> {
769        crate::ui::CallCx::new(host)
770    }
771
772    /// The VM the call comes from (a `sys: System` parameter).
773    pub fn system(host: &dyn JsHost) -> crate::ui::System {
774        host.system()
775    }
776
777    /// The object a constructor makes for `value`.
778    pub fn construct<C: Class>(host: &dyn JsHost, value: C) -> Result<JsRaw, Thrown> {
779        host.construct(Instance::new(value).erased())
780            .map_err(|e| Thrown::Error(e.0))
781    }
782
783    /// [`construct`] of a `Result`.
784    pub fn construct_result<C: Class, E: crate::ui::IntoThrown>(
785        host: &dyn JsHost,
786        value: Result<C, E>,
787    ) -> Result<JsRaw, Thrown> {
788        match value {
789            Ok(v) => construct(host, v),
790            Err(e) => Err(e.into_thrown()),
791        }
792    }
793
794    /// The result of a call JS waits for, boxed for its reply.
795    pub fn boxed<T: Ret + 'static>(value: T) -> JsResult {
796        Ok(Box::new(value))
797    }
798
799    /// [`boxed`] of a `Result`: an `Err` rejects (a [`crate::ui::JsError`]
800    /// with its class and properties, any other error with its message).
801    pub fn boxed_result<T: Ret + 'static, E: crate::ui::IntoThrown>(
802        value: Result<T, E>,
803    ) -> JsResult {
804        match value {
805            Ok(v) => Ok(Box::new(v)),
806            Err(e) => Err(e.into_thrown()),
807        }
808    }
809
810    /// The documentation of a class (`#[class]` on its struct).
811    #[diagnostic::on_unimplemented(
812        message = "`{Self}` needs `#[class]` on its struct too",
813        label = "a class's struct and its `impl` block both have `#[class]`"
814    )]
815    pub trait ClassDoc {
816        /// The struct's doc comment.
817        const DOC: &'static str;
818        /// `#[class(interface)]`: [`super::ClassDef::interface`].
819        const INTERFACE: bool;
820    }
821
822    /// The documentation of a module (`#[module]` on its struct, or the
823    /// `#[component]` of its name).
824    #[diagnostic::on_unimplemented(
825        message = "`{Self}` needs `#[module]` on its struct too",
826        label = "a module's struct and its `impl` block both have `#[module]` (the struct's doc comment documents it)"
827    )]
828    pub trait ModuleDoc {
829        /// The struct's (or component function's) doc comment.
830        const DOC: &'static str;
831    }
832
833    /// A field of a class's struct, traced when its type implements
834    /// [`Trace`] (`#[class]` calls `(&&Field(&self.x)).trace_field(t)`: the
835    /// method of `TraceField` applies to types that implement it, the one
836    /// of `SkipField` to the others).
837    pub struct Field<'a, T>(pub &'a T);
838
839    /// Traces a field whose type implements [`Trace`].
840    pub trait TraceField {
841        /// Reports the field's callbacks.
842        fn trace_field(&self, tracer: &mut Tracer<'_>);
843    }
844
845    impl<T: Trace> TraceField for &Field<'_, T> {
846        fn trace_field(&self, tracer: &mut Tracer<'_>) {
847            self.0.trace(tracer);
848        }
849    }
850
851    /// Skips a field whose type does not implement [`Trace`].
852    pub trait SkipField {
853        /// Nothing.
854        fn trace_field(&self, tracer: &mut Tracer<'_>);
855    }
856
857    impl<T> SkipField for Field<'_, T> {
858        fn trace_field(&self, _tracer: &mut Tracer<'_>) {}
859    }
860
861    /// The `TypeId` of `T` (what a [`ClassDef`] tells types apart by).
862    pub fn type_id<T: 'static>() -> TypeId {
863        TypeId::of::<T>()
864    }
865
866    /// `T`'s Rust path.
867    pub fn type_name<T: 'static>() -> &'static str {
868        std::any::type_name::<T>()
869    }
870}
871
872#[cfg(test)]
873mod tests {
874    use crate::ui::{Registry, declarations, prelude::*};
875
876    /// A function the generated code must not call for `core::mem::drop`.
877    #[allow(dead_code)]
878    fn drop() {}
879
880    /// A field configured out is not traced: its type need not exist.
881    #[class]
882    struct Configured {
883        #[cfg(any())]
884        gone: NoSuchType,
885        kept: Option<Callback>,
886    }
887
888    #[class]
889    impl Configured {}
890
891    #[allow(dead_code)]
892    fn configured() -> Configured {
893        Configured { kept: None }
894    }
895
896    /// A tally kept in Rust.
897    #[class]
898    struct Tally {
899        count: i64,
900        label: Option<String>,
901    }
902
903    #[class]
904    impl Tally {
905        /// Starts at `start` (0 when left out).
906        pub(crate) fn new(start: Option<i64>) -> Self {
907            Tally {
908                count: start.unwrap_or(0),
909                label: None,
910            }
911        }
912
913        /// Adds `by`; the new count.
914        pub(crate) fn add(&mut self, by: i64, label: Option<String>) -> i64 {
915            let _ = label;
916            self.count += by;
917            self.count
918        }
919
920        /// The count.
921        #[getter]
922        pub(crate) fn count(&self) -> i64 {
923            self.count
924        }
925
926        #[setter]
927        pub(crate) fn set_count(&mut self, count: i64) {
928            self.count = count;
929        }
930
931        #[getter]
932        pub(crate) fn label(&self) -> Option<String> {
933            self.label.clone()
934        }
935
936        /// A setter's value is required, even an `Option`.
937        #[setter]
938        pub(crate) fn set_label(&mut self, label: Option<String>) {
939            self.label = label;
940        }
941
942        /// Only where it is compiled.
943        #[cfg(any())]
944        pub(crate) fn nowhere(&self) -> i64 {
945            0
946        }
947
948        /// A tally from `"12"`; throws on anything else.
949        pub(crate) fn parse(text: String) -> Result<Tally, String> {
950            text.parse()
951                .map(|count| Tally { count, label: None })
952                .map_err(|_| text)
953        }
954
955        pub(crate) fn reset(&mut self, to: Option<i64>, by: i64) {
956            self.count = to.unwrap_or(0) + by;
957        }
958
959        pub(crate) fn absorb(
960            &mut self,
961            other: &Tally,
962            token: Option<Instance<Token>>,
963        ) -> Instance<Token> {
964            self.count += other.count;
965            token.unwrap_or_else(|| Instance::new(Token))
966        }
967
968        /// Saves the count; resolves when it is written.
969        pub(crate) async fn save(this: Instance<Self>, path: String) -> Result<(), String> {
970            let _ = (this, path);
971            Ok(())
972        }
973
974        pub(crate) async fn later(start: i64) -> Tally {
975            Tally {
976                count: start,
977                label: None,
978            }
979        }
980
981        /// Sorts with the app's comparison.
982        pub(crate) fn sort_by(&mut self, compare: Callback<(String, String), f64>) {
983            let _ = compare;
984        }
985
986        pub(crate) fn on(
987            &mut self,
988            #[args(count)] listener: Option<Callback<i64>>,
989            done: Option<Callback>,
990        ) {
991            let _ = (listener, done);
992        }
993
994        /// A helper without `pub`: Rust's only, not in TS.
995        #[allow(dead_code)]
996        fn bump(&mut self) {
997            self.count += 1;
998        }
999
1000        /// A private associated function: not a static in TS either.
1001        #[allow(dead_code)]
1002        async fn private_later() -> i64 {
1003            0
1004        }
1005    }
1006
1007    /// Made by its members only.
1008    #[class]
1009    struct Token;
1010
1011    #[class]
1012    impl Token {
1013        pub(crate) fn mint() -> Token {
1014            Token
1015        }
1016    }
1017
1018    #[test]
1019    fn classes_are_declared_from_their_definitions() {
1020        let mut registry = Registry::ui_set("test/ui");
1021        registry.class::<Tally>().class::<Token>();
1022        // Helpers without `pub` stay Rust's: neither declared nor members.
1023        assert!(
1024            !<Tally as crate::ui::Class>::DEF
1025                .members
1026                .iter()
1027                .any(|m| m.name == "bump" || m.name == "privateLater")
1028        );
1029        assert_eq!(
1030            declarations(&registry, &[]),
1031            r#"/** A tally kept in Rust. */
1032export declare class Tally {
1033  /** Starts at `start` (0 when left out). */
1034  constructor(start?: number | null);
1035  /** Adds `by`; the new count. */
1036  add(by: number, label?: string | null): number;
1037  /** The count. */
1038  get count(): number;
1039  set count(count: number);
1040  get label(): string | null;
1041  /** A setter's value is required, even an `Option`. */
1042  set label(label: string | null);
1043  /** A tally from `"12"`; throws on anything else. */
1044  static parse(text: string): Tally;
1045  reset(to: number | null, by: number): void;
1046  absorb(other: Tally, token?: Token | null): Token;
1047  /** Saves the count; resolves when it is written. */
1048  save(path: string): Promise<void>;
1049  static later(start: number): Promise<Tally>;
1050  /** Sorts with the app's comparison. */
1051  sortBy(compare: (a: string, b: string) => number): void;
1052  on(listener?: ((count: number) => void) | null, done?: (() => void) | null): void;
1053  /** Frees the Rust value now (else when the object is collected); the object throws after. */
1054  dispose(): void;
1055  [Symbol.dispose](): void;
1056}
1057
1058/** Made by its members only. */
1059export declare class Token {
1060  /** Made by the class's members only. */
1061  private constructor();
1062  static mint(): Token;
1063  /** Frees the Rust value now (else when the object is collected); the object throws after. */
1064  dispose(): void;
1065  [Symbol.dispose](): void;
1066}
1067
1068"#
1069        );
1070    }
1071
1072    /// Functions of the three kinds.
1073    #[module]
1074    struct Tools;
1075
1076    #[module]
1077    impl Tools {
1078        /// The sum, at once.
1079        pub(crate) fn sum(values: Vec<f64>) -> f64 {
1080            values.iter().sum()
1081        }
1082
1083        pub(crate) fn shout(text: String) {
1084            let _ = text;
1085        }
1086
1087        /// A promise of the length.
1088        pub(crate) fn measure(text: String, cx: &mut ModuleCx) -> usize {
1089            let _ = cx;
1090            text.len()
1091        }
1092
1093        /// Picks with the app's choice, its arguments named.
1094        pub(crate) fn pick(#[args(old_value, new_value)] choose: Callback<(f64, f64), f64>) -> f64 {
1095            choose.call((0.0, 1.0)).unwrap_or(0.0)
1096        }
1097
1098        /// An op returning nothing: a plain call.
1099        pub(crate) fn beep(cx: &mut ModuleCx) {
1100            let _ = cx;
1101        }
1102
1103        /// An op that may fail: a promise, rejected with an `Err`.
1104        pub(crate) fn check(cx: &mut ModuleCx) -> Result<(), String> {
1105            let _ = cx;
1106            Ok(())
1107        }
1108
1109        /// `-> ()` written out: the same as no return type.
1110        #[allow(clippy::unused_unit)]
1111        pub(crate) fn hum(cx: &mut ModuleCx) -> () {
1112            let _ = cx;
1113        }
1114
1115        /// A task returning nothing.
1116        pub(crate) async fn settle() {}
1117
1118        pub(crate) async fn later(listener: Callback<i64, String>) -> Result<String, String> {
1119            listener.call_async(1).await
1120        }
1121
1122        /// Only where it is compiled.
1123        #[cfg(any())]
1124        pub(crate) fn nowhere() {}
1125
1126        /// A helper without `pub`: not exported.
1127        #[allow(dead_code)]
1128        fn helper(text: String) -> String {
1129            text
1130        }
1131    }
1132
1133    #[test]
1134    fn functions_without_a_context_return_their_values() {
1135        let mut registry = Registry::ui_set("test/ui");
1136        registry.module::<Tools>();
1137        assert!(
1138            !<Tools as crate::ui::Module>::FUNCTIONS
1139                .iter()
1140                .any(|f| f.name == "helper")
1141        );
1142        assert_eq!(
1143            declarations(&registry, &[]),
1144            r#"/** Functions of the three kinds. */
1145export interface ToolsModule {
1146  /** The sum, at once. */
1147  sum(values: (number)[]): number;
1148  shout(text: string): void;
1149  /** A promise of the length. */
1150  measure(text: string): Promise<number>;
1151  /** Picks with the app's choice, its arguments named. */
1152  pick(choose: (oldValue: number, newValue: number) => number): number;
1153  /** An op returning nothing: a plain call. */
1154  beep(): void;
1155  /** An op that may fail: a promise, rejected with an `Err`. */
1156  check(): Promise<void>;
1157  /** `-> ()` written out: the same as no return type. */
1158  hum(): void;
1159  /** A task returning nothing. */
1160  settle(): Promise<void>;
1161  later(listener: (value: number) => string): Promise<string>;
1162}
1163
1164/** Functions of the three kinds. */
1165export declare const Tools: ToolsModule;
1166
1167"#
1168        );
1169    }
1170
1171    /// A signature naming a class registers it too: registering it again
1172    /// does nothing.
1173    #[test]
1174    fn registering_a_class_again_does_nothing() {
1175        let mut r = Registry::ui_set("test/ui");
1176        r.class::<Tally>().class::<Tally>();
1177        let tallies = r.class_specs().iter().filter(|c| c.name == "Tally").count();
1178        assert_eq!(tallies, 1);
1179    }
1180
1181    /// A component exported as `Tally`.
1182    mod view {
1183        use crate::ui::prelude::*;
1184
1185        pub(super) struct Tally;
1186
1187        impl Component for Tally {
1188            type Props = ();
1189            type Event = NoEvent;
1190
1191            fn view(_: (), _: Scope<NoEvent>) -> impl IntoElement {
1192                view()
1193            }
1194        }
1195    }
1196
1197    /// A class and a component of one name clash, whichever comes first.
1198    #[test]
1199    fn a_class_and_a_component_share_no_name() {
1200        let class_first = std::panic::catch_unwind(|| {
1201            Registry::ui_set("test/ui")
1202                .class::<Tally>()
1203                .register::<view::Tally>();
1204        });
1205        assert!(class_first.is_err(), "a component after a class");
1206        let component_first = std::panic::catch_unwind(|| {
1207            Registry::ui_set("test/ui")
1208                .register::<view::Tally>()
1209                .class::<Tally>();
1210        });
1211        assert!(component_first.is_err(), "a class after a component");
1212    }
1213}