Skip to main content

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