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}
479
480impl<T: JsValue> Ret for T {
481    fn ts_type(types: &mut TsTypes) -> String {
482        T::ts_type(types)
483    }
484
485    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
486        self.to_js(host)
487    }
488}
489
490impl Ret for () {
491    const UNIT: bool = true;
492
493    fn ts_type(_types: &mut TsTypes) -> String {
494        "void".into()
495    }
496
497    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
498        Ok(JsOwned::new(host, host.undefined()))
499    }
500}
501
502impl<C: Class> Ret for Instance<C> {
503    fn ts_type(types: &mut TsTypes) -> String {
504        types.class(C::DEF)
505    }
506
507    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
508        Ok(JsOwned::new(host, host.wrap(self.erased())?))
509    }
510
511    fn classes(out: &mut Vec<&'static ClassDef>) {
512        out.push(C::DEF);
513    }
514}
515
516/// An array of instances' objects.
517impl<C: Class> Ret for Vec<Instance<C>> {
518    fn ts_type(types: &mut TsTypes) -> String {
519        format!("{}[]", types.class(C::DEF))
520    }
521
522    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
523        // Owned until the array takes them, as `Vec<T>`'s items are.
524        let mut items = Vec::with_capacity(self.len());
525        for instance in self {
526            items.push(instance.into_js(host)?);
527        }
528        let raws = items.into_iter().map(JsOwned::into_raw).collect();
529        Ok(JsOwned::new(host, host.new_array(raws)?))
530    }
531
532    fn classes(out: &mut Vec<&'static ClassDef>) {
533        out.push(C::DEF);
534    }
535}
536
537impl<C: Class> Ret for Option<Instance<C>> {
538    fn ts_type(types: &mut TsTypes) -> String {
539        format!("{} | null", <Instance<C> as Ret>::ts_type(types))
540    }
541
542    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
543        match self {
544            Some(i) => i.into_js(host),
545            None => Ok(JsOwned::new(host, host.null())),
546        }
547    }
548
549    fn classes(out: &mut Vec<&'static ClassDef>) {
550        out.push(C::DEF);
551    }
552}
553
554// --- Specs ------------------------------------------------------------------------
555
556/// One member, for the JS face and the declarations.
557#[derive(Debug, Clone)]
558pub struct MemberSpec {
559    /// Its JS name.
560    pub name: &'static str,
561    /// Documentation.
562    pub doc: &'static str,
563    /// What it is.
564    pub kind: MemberKind,
565    /// Its parameters: JS name, TypeScript type, optional.
566    pub params: Vec<(&'static str, String, bool)>,
567    /// The TypeScript type of its result (`None`: nothing).
568    pub returns: Option<String>,
569    /// JS gets a promise.
570    pub is_async: bool,
571    /// The signatures TypeScript sees instead ([`Member::overloads`]).
572    pub overloads: Vec<super::OverloadSpec>,
573}
574
575/// What a class is to JS and its declarations.
576#[derive(Debug, Clone)]
577pub struct ClassSpec {
578    /// Its JS name.
579    pub name: &'static str,
580    /// Documentation.
581    pub doc: &'static str,
582    /// Its members.
583    pub members: Vec<MemberSpec>,
584    /// The named TypeScript types they use.
585    pub types: TsTypes,
586    /// The class itself.
587    pub def: &'static ClassDef,
588}
589
590impl ClassSpec {
591    pub(crate) fn of(def: &'static ClassDef) -> Self {
592        let mut types = TsTypes::default();
593        let members = def
594            .members
595            .iter()
596            .map(|m| MemberSpec {
597                name: m.name,
598                doc: m.doc,
599                kind: m.kind,
600                params: m
601                    .params
602                    .iter()
603                    .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
604                    .collect(),
605                returns: m.returns.map(|ts| ts(&mut types)),
606                is_async: m.call.is_async(),
607                overloads: m
608                    .overloads
609                    .iter()
610                    .map(|o| {
611                        let params = o
612                            .params
613                            .iter()
614                            .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
615                            .collect();
616                        (params, o.returns.map(|ts| ts(&mut types)))
617                    })
618                    .collect(),
619            })
620            .collect();
621        Self {
622            name: def.name,
623            doc: def.doc,
624            members,
625            types,
626            def,
627        }
628    }
629}
630
631// --- What `#[class]` and `#[module]` call -----------------------------------------
632
633/// The generated code's helpers.
634#[doc(hidden)]
635pub(crate) mod __private {
636    use super::*;
637
638    /// `T`'s TypeScript type as a parameter, or nothing in builds without
639    /// declarations.
640    pub const fn arg_ts<T: Arg>() -> TsType {
641        if crate::element::DECLARATIONS {
642            T::ts_type
643        } else {
644            |_| String::new()
645        }
646    }
647
648    /// The TypeScript type of `T`, a callback parameter whose function's
649    /// arguments `#[args(..)]` names `names`; nothing in builds without
650    /// declarations.
651    pub fn named_arg_ts<T: crate::element::callback::NamedArgs>(
652        types: &mut TsTypes,
653        names: &[&str],
654    ) -> String {
655        if crate::element::DECLARATIONS {
656            T::ts_named(types, names)
657        } else {
658            String::new()
659        }
660    }
661
662    /// `T`'s TypeScript type as a result.
663    pub const fn ret_ts<T: Ret>() -> TsType {
664        if crate::element::DECLARATIONS {
665            T::ts_type
666        } else {
667            |_| String::new()
668        }
669    }
670
671    /// The class a struct's value makes a new instance of.
672    pub fn class_into_js<C: Class>(value: C, host: &dyn JsHost) -> Result<JsOwned<'_>, PropError> {
673        Instance::new(value).into_js(host)
674    }
675
676    /// `C`'s TypeScript type.
677    pub fn class_ts<C: Class>(types: &mut TsTypes) -> String {
678        types.class(C::DEF)
679    }
680
681    /// The classes parameter type `T` names.
682    pub fn arg_classes<T: Arg>(out: &mut Vec<&'static ClassDef>) {
683        T::classes(out);
684    }
685
686    /// The classes result type `T` names.
687    pub fn ret_classes<T: Ret>(out: &mut Vec<&'static ClassDef>) {
688        T::classes(out);
689    }
690
691    /// Class `C` itself (a struct's value as a result).
692    pub fn class_refs<C: Class>(out: &mut Vec<&'static ClassDef>) {
693        out.push(C::DEF);
694    }
695
696    /// Argument `i` of the call (`what`: `Tally.add`, `name`: `by`, for
697    /// the error).
698    pub fn arg<T: Arg>(host: &dyn JsHost, i: usize, what: &str, name: &str) -> Result<T, Thrown> {
699        T::from_js(JsIn::new(host, host.arg(i))).map_err(|e| bad_arg(e, what, name))
700    }
701
702    /// The instance `this` of the call is.
703    pub fn this<C: Class>(host: &dyn JsHost, what: &str) -> Result<Instance<C>, Thrown> {
704        host.instance(host.this())
705            .and_then(Instance::of)
706            .ok_or_else(|| illegal_invocation(what, C::DEF.name))
707    }
708
709    /// The value of `instance`, borrowed for a call.
710    pub fn borrow<C: Class>(instance: &Instance<C>) -> Result<Ref<'_, C>, Thrown> {
711        instance.borrow()
712    }
713
714    /// The value of `instance`, borrowed mutably for a call.
715    pub fn borrow_mut<C: Class>(instance: &Instance<C>) -> Result<RefMut<'_, C>, Thrown> {
716        instance.borrow_mut()
717    }
718
719    /// The value of `instance`, argument `name` of `what` (`Account.transfer`,
720    /// `to`), borrowed for the call: its error names them, as a wrong
721    /// argument's does (``Account.transfer: `to`: Account is disposed``).
722    pub fn borrow_arg<'a, C: Class>(
723        instance: &'a Instance<C>,
724        what: &str,
725        name: &str,
726    ) -> Result<Ref<'a, C>, Thrown> {
727        instance.borrow().map_err(|e| arg_error(e, what, name))
728    }
729
730    /// [`borrow_arg`], mutably.
731    pub fn borrow_arg_mut<'a, C: Class>(
732        instance: &'a Instance<C>,
733        what: &str,
734        name: &str,
735    ) -> Result<RefMut<'a, C>, Thrown> {
736        instance.borrow_mut().map_err(|e| arg_error(e, what, name))
737    }
738
739    /// The error of argument `name` of `what` JS passed a wrong value for.
740    #[cold]
741    #[inline(never)]
742    fn bad_arg(e: PropError, what: &str, name: &str) -> Thrown {
743        Thrown::Type(format!("{what}: `{name}`: {e}"))
744    }
745
746    /// The error of a call whose `this` is no `class`.
747    #[cold]
748    #[inline(never)]
749    fn illegal_invocation(what: &str, class: &str) -> Thrown {
750        Thrown::Type(format!("{what}: Illegal invocation: not a {class}"))
751    }
752
753    /// `e`, an argument's error, after `what` and the argument's `name`.
754    #[cold]
755    #[inline(never)]
756    fn arg_error(e: Thrown, what: &str, name: &str) -> Thrown {
757        match e {
758            Thrown::Type(m) => Thrown::Type(format!("{what}: `{name}`: {m}")),
759            Thrown::Range(m) => Thrown::Range(format!("{what}: `{name}`: {m}")),
760            Thrown::Error(m) => Thrown::Error(format!("{what}: `{name}`: {m}")),
761            Thrown::Fields(mut f) => {
762                f.message = format!("{what}: `{name}`: {}", f.message);
763                Thrown::Fields(f)
764            }
765        }
766    }
767
768    /// The result of a synchronous call as a JS value.
769    pub fn ret<T: Ret>(host: &dyn JsHost, value: T) -> Result<JsRaw, Thrown> {
770        value
771            .into_js(host)
772            .map(JsOwned::into_raw)
773            .map_err(|e| Thrown::Error(e.0))
774    }
775
776    /// [`ret`] of a `Result`: an `Err` throws an `Error` with its message
777    /// (a [`crate::element::JsError`] its class).
778    pub fn ret_result<T: Ret, E: crate::element::IntoThrown>(
779        host: &dyn JsHost,
780        value: Result<T, E>,
781    ) -> Result<JsRaw, Thrown> {
782        match value {
783            Ok(v) => ret(host, v),
784            Err(e) => Err(e.into_thrown()),
785        }
786    }
787
788    /// The task a synchronous call returned ([`crate::element::Later`]).
789    pub fn start<T: Ret + 'static>(value: crate::element::Later<T>) -> Result<TaskStart, Thrown> {
790        Ok(Box::new(move || value.into_future()))
791    }
792
793    /// [`start`] of a `Result`: an `Err` rejects the call's promise.
794    pub fn start_result<T: Ret + 'static, E: crate::element::IntoThrown>(
795        value: Result<crate::element::Later<T>, E>,
796    ) -> Result<TaskStart, Thrown> {
797        value.map_err(E::into_thrown).and_then(start)
798    }
799
800    /// What the call can do beyond computing (a `cx: CallCx` parameter).
801    pub fn call_cx(host: &dyn JsHost) -> crate::element::CallCx<'_> {
802        crate::element::CallCx::new(host)
803    }
804
805    /// The VM the call comes from (a `sys: System` parameter).
806    pub fn system(host: &dyn JsHost) -> crate::element::System {
807        host.system()
808    }
809
810    /// The object a constructor makes for `value`.
811    pub fn construct<C: Class>(host: &dyn JsHost, value: C) -> Result<JsRaw, Thrown> {
812        host.construct(Instance::new(value).erased())
813            .map_err(|e| Thrown::Error(e.0))
814    }
815
816    /// [`construct`] of a `Result`.
817    pub fn construct_result<C: Class, E: crate::element::IntoThrown>(
818        host: &dyn JsHost,
819        value: Result<C, E>,
820    ) -> Result<JsRaw, Thrown> {
821        match value {
822            Ok(v) => construct(host, v),
823            Err(e) => Err(e.into_thrown()),
824        }
825    }
826
827    /// The result of a call JS waits for, boxed for its reply.
828    pub fn boxed<T: Ret + 'static>(value: T) -> JsResult {
829        Ok(Box::new(value))
830    }
831
832    /// [`boxed`] of a `Result`: an `Err` rejects (a [`crate::element::JsError`]
833    /// with its class and properties, any other error with its message).
834    pub fn boxed_result<T: Ret + 'static, E: crate::element::IntoThrown>(
835        value: Result<T, E>,
836    ) -> JsResult {
837        match value {
838            Ok(v) => Ok(Box::new(v)),
839            Err(e) => Err(e.into_thrown()),
840        }
841    }
842
843    /// The documentation of a class (`#[class]` on its struct).
844    #[diagnostic::on_unimplemented(
845        message = "`{Self}` needs `#[class]` on its struct too",
846        label = "a class's struct and its `impl` block both have `#[class]`"
847    )]
848    pub trait ClassDoc {
849        /// The struct's doc comment.
850        const DOC: &'static str;
851        /// `#[class(interface)]`: [`super::ClassDef::interface`].
852        const INTERFACE: bool;
853    }
854
855    /// The documentation of a module (`#[module]` on its struct, or the
856    /// `#[component]` of its name).
857    #[diagnostic::on_unimplemented(
858        message = "`{Self}` needs `#[module]` on its struct too",
859        label = "a module's struct and its `impl` block both have `#[module]` (the struct's doc comment documents it)"
860    )]
861    pub trait ModuleDoc {
862        /// The struct's (or component function's) doc comment.
863        const DOC: &'static str;
864    }
865
866    /// A field of a class's struct, traced when its type implements
867    /// [`Trace`] (`#[class]` calls `(&&Field(&self.x)).trace_field(t)`: the
868    /// method of `TraceField` applies to types that implement it, the one
869    /// of `SkipField` to the others).
870    pub struct Field<'a, T>(pub &'a T);
871
872    /// Traces a field whose type implements [`Trace`].
873    pub trait TraceField {
874        /// Reports the field's callbacks.
875        fn trace_field(&self, tracer: &mut Tracer<'_>);
876    }
877
878    impl<T: Trace> TraceField for &Field<'_, T> {
879        fn trace_field(&self, tracer: &mut Tracer<'_>) {
880            self.0.trace(tracer);
881        }
882    }
883
884    /// Skips a field whose type does not implement [`Trace`].
885    pub trait SkipField {
886        /// Nothing.
887        fn trace_field(&self, tracer: &mut Tracer<'_>);
888    }
889
890    impl<T> SkipField for Field<'_, T> {
891        fn trace_field(&self, _tracer: &mut Tracer<'_>) {}
892    }
893
894    /// The `TypeId` of `T` (what a [`ClassDef`] tells types apart by).
895    pub fn type_id<T: 'static>() -> TypeId {
896        TypeId::of::<T>()
897    }
898
899    /// `T`'s Rust path.
900    pub fn type_name<T: 'static>() -> &'static str {
901        std::any::type_name::<T>()
902    }
903}
904
905#[cfg(test)]
906mod tests {
907    use crate::{
908        element::{Registry, declarations},
909        prelude::*,
910    };
911
912    /// A function the generated code must not call for `core::mem::drop`.
913    #[allow(dead_code)]
914    fn drop() {}
915
916    /// A field configured out is not traced: its type need not exist.
917    #[class]
918    struct Configured {
919        #[cfg(any())]
920        gone: NoSuchType,
921        kept: Option<Callback>,
922    }
923
924    #[class]
925    impl Configured {}
926
927    #[allow(dead_code)]
928    fn configured() -> Configured {
929        Configured { kept: None }
930    }
931
932    /// A tally kept in Rust.
933    #[class]
934    struct Tally {
935        count: i64,
936        label: Option<String>,
937    }
938
939    #[class]
940    impl Tally {
941        /// Starts at `start` (0 when left out).
942        pub(crate) fn new(start: Option<i64>) -> Self {
943            Tally {
944                count: start.unwrap_or(0),
945                label: None,
946            }
947        }
948
949        /// Adds `by`; the new count.
950        pub(crate) fn add(&mut self, by: i64, label: Option<String>) -> i64 {
951            let _ = label;
952            self.count += by;
953            self.count
954        }
955
956        /// The count.
957        #[getter]
958        pub(crate) fn count(&self) -> i64 {
959            self.count
960        }
961
962        #[setter]
963        pub(crate) fn set_count(&mut self, count: i64) {
964            self.count = count;
965        }
966
967        #[getter]
968        pub(crate) fn label(&self) -> Option<String> {
969            self.label.clone()
970        }
971
972        /// A setter's value is required, even an `Option`.
973        #[setter]
974        pub(crate) fn set_label(&mut self, label: Option<String>) {
975            self.label = label;
976        }
977
978        /// Only where it is compiled.
979        #[cfg(any())]
980        pub(crate) fn nowhere(&self) -> i64 {
981            0
982        }
983
984        /// A tally from `"12"`; throws on anything else.
985        pub(crate) fn parse(text: String) -> Result<Tally, String> {
986            text.parse()
987                .map(|count| Tally { count, label: None })
988                .map_err(|_| text)
989        }
990
991        pub(crate) fn reset(&mut self, to: Option<i64>, by: i64) {
992            self.count = to.unwrap_or(0) + by;
993        }
994
995        pub(crate) fn absorb(
996            &mut self,
997            other: &Tally,
998            token: Option<Instance<Token>>,
999        ) -> Instance<Token> {
1000            self.count += other.count;
1001            token.unwrap_or_else(|| Instance::new(Token))
1002        }
1003
1004        /// Saves the count; resolves when it is written.
1005        pub(crate) async fn save(this: Instance<Self>, path: String) -> Result<(), String> {
1006            let _ = (this, path);
1007            Ok(())
1008        }
1009
1010        pub(crate) async fn later(start: i64) -> Tally {
1011            Tally {
1012                count: start,
1013                label: None,
1014            }
1015        }
1016
1017        /// Sorts with the app's comparison.
1018        pub(crate) fn sort_by(&mut self, compare: Callback<(String, String), f64>) {
1019            let _ = compare;
1020        }
1021
1022        pub(crate) fn on(
1023            &mut self,
1024            #[args(count)] listener: Option<Callback<i64>>,
1025            done: Option<Callback>,
1026        ) {
1027            let _ = (listener, done);
1028        }
1029
1030        /// A helper without `pub`: Rust's only, not in TS.
1031        #[allow(dead_code)]
1032        fn bump(&mut self) {
1033            self.count += 1;
1034        }
1035
1036        /// A private associated function: not a static in TS either.
1037        #[allow(dead_code)]
1038        async fn private_later() -> i64 {
1039            0
1040        }
1041    }
1042
1043    /// Made by its members only.
1044    #[class]
1045    struct Token;
1046
1047    #[class]
1048    impl Token {
1049        pub(crate) fn mint() -> Token {
1050            Token
1051        }
1052    }
1053
1054    #[test]
1055    fn classes_are_declared_from_their_definitions() {
1056        let mut registry = Registry::ui_set("test/ui");
1057        registry.class::<Tally>().class::<Token>();
1058        // Helpers without `pub` stay Rust's: neither declared nor members.
1059        assert!(
1060            !<Tally as crate::element::Class>::DEF
1061                .members
1062                .iter()
1063                .any(|m| m.name == "bump" || m.name == "privateLater")
1064        );
1065        assert_eq!(
1066            declarations(&registry, &[]),
1067            r#"/** A tally kept in Rust. */
1068export declare class Tally {
1069  /** Starts at `start` (0 when left out). */
1070  constructor(start?: number | null);
1071  /** Adds `by`; the new count. */
1072  add(by: number, label?: string | null): number;
1073  /** The count. */
1074  get count(): number;
1075  set count(count: number);
1076  get label(): string | null;
1077  /** A setter's value is required, even an `Option`. */
1078  set label(label: string | null);
1079  /** A tally from `"12"`; throws on anything else. */
1080  static parse(text: string): Tally;
1081  reset(to: number | null, by: number): void;
1082  absorb(other: Tally, token?: Token | null): Token;
1083  /** Saves the count; resolves when it is written. */
1084  save(path: string): Promise<void>;
1085  static later(start: number): Promise<Tally>;
1086  /** Sorts with the app's comparison. */
1087  sortBy(compare: (a: string, b: string) => number): void;
1088  on(listener?: ((count: number) => void) | null, done?: (() => void) | null): void;
1089  /** Frees the Rust value now (else when the object is collected); the object throws after. */
1090  dispose(): void;
1091  [Symbol.dispose](): void;
1092}
1093
1094/** Made by its members only. */
1095export declare class Token {
1096  /** Made by the class's members only. */
1097  private constructor();
1098  static mint(): Token;
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"#
1105        );
1106    }
1107
1108    /// Functions of the three kinds.
1109    #[module]
1110    struct Tools;
1111
1112    #[module]
1113    impl Tools {
1114        /// The sum, at once.
1115        pub(crate) fn sum(values: Vec<f64>) -> f64 {
1116            values.iter().sum()
1117        }
1118
1119        pub(crate) fn shout(text: String) {
1120            let _ = text;
1121        }
1122
1123        /// A promise of the length.
1124        pub(crate) fn measure(text: String, cx: &mut ModuleCx) -> usize {
1125            let _ = cx;
1126            text.len()
1127        }
1128
1129        /// Picks with the app's choice, its arguments named.
1130        pub(crate) fn pick(#[args(old_value, new_value)] choose: Callback<(f64, f64), f64>) -> f64 {
1131            choose.call((0.0, 1.0)).unwrap_or(0.0)
1132        }
1133
1134        /// An op returning nothing: a plain call.
1135        pub(crate) fn beep(cx: &mut ModuleCx) {
1136            let _ = cx;
1137        }
1138
1139        /// An op that may fail: a promise, rejected with an `Err`.
1140        pub(crate) fn check(cx: &mut ModuleCx) -> Result<(), String> {
1141            let _ = cx;
1142            Ok(())
1143        }
1144
1145        /// `-> ()` written out: the same as no return type.
1146        #[allow(clippy::unused_unit)]
1147        pub(crate) fn hum(cx: &mut ModuleCx) -> () {
1148            let _ = cx;
1149        }
1150
1151        /// A task returning nothing.
1152        pub(crate) async fn settle() {}
1153
1154        pub(crate) async fn later(listener: Callback<i64, String>) -> Result<String, String> {
1155            listener.call_async(1).await
1156        }
1157
1158        /// Only where it is compiled.
1159        #[cfg(any())]
1160        pub(crate) fn nowhere() {}
1161
1162        /// A helper without `pub`: not exported.
1163        #[allow(dead_code)]
1164        fn helper(text: String) -> String {
1165            text
1166        }
1167    }
1168
1169    #[test]
1170    fn functions_without_a_context_return_their_values() {
1171        let mut registry = Registry::ui_set("test/ui");
1172        registry.module::<Tools>();
1173        assert!(
1174            !<Tools as crate::element::Module>::FUNCTIONS
1175                .iter()
1176                .any(|f| f.name == "helper")
1177        );
1178        assert_eq!(
1179            declarations(&registry, &[]),
1180            r#"/** Functions of the three kinds. */
1181export interface ToolsModule {
1182  /** The sum, at once. */
1183  sum(values: (number)[]): number;
1184  shout(text: string): void;
1185  /** A promise of the length. */
1186  measure(text: string): Promise<number>;
1187  /** Picks with the app's choice, its arguments named. */
1188  pick(choose: (oldValue: number, newValue: number) => number): number;
1189  /** An op returning nothing: a plain call. */
1190  beep(): void;
1191  /** An op that may fail: a promise, rejected with an `Err`. */
1192  check(): Promise<void>;
1193  /** `-> ()` written out: the same as no return type. */
1194  hum(): void;
1195  /** A task returning nothing. */
1196  settle(): Promise<void>;
1197  later(listener: (value: number) => string): Promise<string>;
1198}
1199
1200/** Functions of the three kinds. */
1201export declare const Tools: ToolsModule;
1202
1203"#
1204        );
1205    }
1206
1207    /// A signature naming a class registers it too: registering it again
1208    /// does nothing.
1209    #[test]
1210    fn registering_a_class_again_does_nothing() {
1211        let mut r = Registry::ui_set("test/ui");
1212        r.class::<Tally>().class::<Tally>();
1213        let tallies = r.class_specs().iter().filter(|c| c.name == "Tally").count();
1214        assert_eq!(tallies, 1);
1215    }
1216
1217    /// A component exported as `Tally`.
1218    mod view {
1219        use crate::prelude::*;
1220
1221        pub(super) struct Tally;
1222
1223        impl Component for Tally {
1224            type Props = ();
1225            type Event = NoEvent;
1226
1227            fn view(_: (), _: Scope<NoEvent>) -> impl IntoElement {
1228                view()
1229            }
1230        }
1231    }
1232
1233    /// A class and a component of one name clash, whichever comes first.
1234    #[test]
1235    fn a_class_and_a_component_share_no_name() {
1236        let class_first = std::panic::catch_unwind(|| {
1237            Registry::ui_set("test/ui")
1238                .class::<Tally>()
1239                .register::<view::Tally>();
1240        });
1241        assert!(class_first.is_err(), "a component after a class");
1242        let component_first = std::panic::catch_unwind(|| {
1243            Registry::ui_set("test/ui")
1244                .register::<view::Tally>()
1245                .class::<Tally>();
1246        });
1247        assert!(component_first.is_err(), "a class after a component");
1248    }
1249}