Skip to main content

nsh_core/element/
callback.rs

1//! JS functions Rust takes ([`Callback`]): called on the spot inside a
2//! synchronous call from JS, or queued for the next JS turn from anywhere
3//! on the engine thread ([`Callback::post`], [`Callback::call_async`]: the
4//! engine hands the queue, [`super::Posts`], to the script after the
5//! core's work). A callback an instance keeps is reported to QuickJS's
6//! collector through the class's [`Trace`], so a cycle through the
7//! instance's JS object is collected.
8
9use std::{
10    cell::RefCell,
11    collections::{BTreeMap, HashMap, VecDeque},
12    fmt,
13    marker::PhantomData,
14    rc::Rc,
15};
16
17use super::{
18    JsValue, PropError, TsTypes,
19    class::{Arg, Class, ClassDef, Instance, Ret},
20    js::{JsHost, JsIn, JsOwned},
21    task::Answer,
22};
23
24/// A JS function as Rust keeps it (`nsh-js` implements it).
25#[doc(hidden)]
26pub trait CallbackHandle: std::any::Any {
27    /// Runs `call` now: inside a synchronous call from JS.
28    ///
29    /// # Panics
30    ///
31    /// Outside one (in a task): JS is not running there.
32    fn call_now(&self, call: JsCall);
33    /// Queues `call` for the next JS turn.
34    fn post(&self, call: JsCall);
35    /// The value it keeps, as an owned value of `host` (a new reference the
36    /// caller frees); `None` once the VM is gone.
37    fn value(&self, _host: &dyn JsHost) -> Option<super::JsRaw> {
38        None
39    }
40}
41
42type ArgsFn = Box<dyn for<'a> FnOnce(&'a dyn JsHost) -> Result<Vec<JsOwned<'a>>, PropError>>;
43pub(crate) type ReplyFn = Box<dyn for<'a> FnOnce(Result<JsIn<'a>, Exception>)>;
44
45/// What a JS function threw ([`Callback::call_async_traced`]): its message
46/// and, for an `Error`, the stack where it was made (`    at f
47/// (bundle.js:12:5)` lines, the bundle's positions).
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49#[non_exhaustive]
50pub struct Exception {
51    /// The message (an `Error`'s `message`, else the value as a string).
52    pub message: String,
53    /// The stack, for an `Error`.
54    pub stack: Option<String>,
55    /// What was thrown, as JSON, for checks of it (`nsh/test`'s `toThrow`,
56    /// `toMatchObject`): an object's own enumerable properties (an
57    /// `Error`'s `code`, ...) with its `name` and `message`, any other
58    /// value as itself; `None` when Rust made the error (a conversion's),
59    /// and for a call that is not traced ([`JsCall::traced`]).
60    pub thrown: Option<crate::JsonValue>,
61}
62
63impl From<String> for Exception {
64    fn from(message: String) -> Self {
65        Self {
66            message,
67            stack: None,
68            thrown: None,
69        }
70    }
71}
72
73impl fmt::Display for Exception {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.write_str(&self.message)
76    }
77}
78
79/// A call of a JS function: its arguments, made when it runs, and what
80/// receives its result.
81#[doc(hidden)]
82pub struct JsCall {
83    callback: Rc<dyn CallbackHandle>,
84    args: Option<ArgsFn>,
85    reply: Option<ReplyFn>,
86    /// The reply waits for a promise the function returns.
87    settles: bool,
88    /// The reply wants what was thrown whole ([`Exception::thrown`]).
89    traced: bool,
90}
91
92impl JsCall {
93    pub(crate) fn new<A: CallbackArgs + 'static>(
94        callback: Rc<dyn CallbackHandle>,
95        args: A,
96        reply: Option<ReplyFn>,
97        settles: bool,
98        traced: bool,
99    ) -> Self {
100        Self {
101            callback,
102            args: Some(Box::new(move |host| args.into_js_args(host))),
103            reply,
104            settles,
105            traced,
106        }
107    }
108
109    /// The function to call.
110    pub fn callback(&self) -> &Rc<dyn CallbackHandle> {
111        &self.callback
112    }
113
114    /// The arguments, as values of `host`.
115    pub fn args<'a>(&mut self, host: &'a dyn JsHost) -> Result<Vec<JsOwned<'a>>, PropError> {
116        match self.args.take() {
117            Some(args) => args(host),
118            None => Ok(Vec::new()),
119        }
120    }
121
122    /// Whether the result is wanted (`call`, `call_async`).
123    pub fn wants_reply(&self) -> bool {
124        self.reply.is_some()
125    }
126
127    /// Whether the reply waits for a promise the function returns
128    /// (`call_async`).
129    pub fn settles(&self) -> bool {
130        self.settles
131    }
132
133    /// Whether the reply wants the value thrown as JSON
134    /// ([`Exception::thrown`]: `call_traced`, `call_async_traced`); other
135    /// calls' exceptions carry their message and stack only, so an
136    /// exception costs no conversion where nothing checks it.
137    pub fn traced(&self) -> bool {
138        self.traced
139    }
140
141    /// Delivers the result (or what the function threw).
142    pub fn reply(mut self, result: Result<JsIn<'_>, Exception>) {
143        if let Some(reply) = self.reply.take() {
144            reply(result);
145        }
146    }
147}
148
149impl Drop for JsCall {
150    fn drop(&mut self) {
151        if let Some(reply) = self.reply.take() {
152            reply(Err("the JS function was not called (JS stopped)"
153                .to_owned()
154                .into()));
155        }
156    }
157}
158
159impl fmt::Debug for JsCall {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.debug_struct("JsCall")
162            .field("reply", &self.reply.is_some())
163            .finish_non_exhaustive()
164    }
165}
166
167/// A JS function a class's member or a function takes (TS:
168/// `Callback<f64>` is `(value: number) => void`, `Callback<(String, f64),
169/// bool>` is `(a: string, b: number) => boolean`; `#[args(name, amount)]`
170/// on the parameter names them, `(name: string, amount: number) =>
171/// boolean`):
172/// `A` is its argument (a [`JsValue`] type, an instance, a tuple of them
173/// for several, `()` for none), `R` what it returns. Cheap to clone; the JS
174/// function is released when the last clone goes. Kept in an instance's
175/// field, it is reported to QuickJS's collector, so a cycle through the
176/// instance's JS object is collected; kept elsewhere, it keeps the
177/// function alive until dropped.
178pub struct Callback<A = (), R = ()> {
179    handle: Rc<dyn CallbackHandle>,
180    _types: PhantomData<fn(A) -> R>,
181}
182
183impl<A, R> Clone for Callback<A, R> {
184    fn clone(&self) -> Self {
185        Self {
186            handle: self.handle.clone(),
187            _types: PhantomData,
188        }
189    }
190}
191
192impl<A, R> fmt::Debug for Callback<A, R> {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        f.write_str("Callback")
195    }
196}
197
198impl<A, R> Callback<A, R> {
199    /// The JS function it keeps (two callbacks of one function share it).
200    pub(crate) fn handle(&self) -> &Rc<dyn CallbackHandle> {
201        &self.handle
202    }
203}
204
205impl<R: CallbackRet + 'static> Callback<(), R> {
206    /// A stand-in for a function that returns `value`: called with
207    /// [`Callback::call_async`] (or `call_async_traced`), it answers
208    /// `value`, a promise what it settles to (`nsh/test`'s
209    /// `expect(promise).rejects`). Called on the spot ([`Callback::call`])
210    /// it throws, as calling what is no function does. A promise is
211    /// handled from then on: its rejection comes here, not reported as
212    /// unhandled. `None` where the host keeps no values
213    /// ([`JsHost::retain`]).
214    pub fn settling(value: JsIn<'_>) -> Option<Self> {
215        value.host().retain(value.raw()).map(Callback::of)
216    }
217}
218
219impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> Callback<A, R> {
220    fn of(handle: Rc<dyn CallbackHandle>) -> Self {
221        Self {
222            handle,
223            _types: PhantomData,
224        }
225    }
226
227    /// Calls the function now, inside a synchronous call from JS (a
228    /// method, a function, the constructor), as `Array.prototype.sort`
229    /// calls its comparison: its result, or what it threw (its message).
230    /// The instance the call is on stays borrowed meanwhile: the function
231    /// using it again throws.
232    ///
233    /// # Panics
234    ///
235    /// Outside a synchronous call from JS (in a task): use
236    /// [`Callback::post`] or [`Callback::call_async`] there.
237    pub fn call(&self, args: A) -> Result<R, String> {
238        self.call_now(args, false).map_err(|e| e.message)
239    }
240
241    /// [`Callback::call`], with what the function threw whole: the
242    /// message, the stack and the value thrown ([`Exception::thrown`]).
243    ///
244    /// # Panics
245    ///
246    /// As [`Callback::call`].
247    pub fn call_traced(&self, args: A) -> Result<R, Exception> {
248        self.call_now(args, true)
249    }
250
251    fn call_now(&self, args: A, traced: bool) -> Result<R, Exception> {
252        let out: Rc<RefCell<Option<Result<R, Exception>>>> = Rc::default();
253        let slot = out.clone();
254        let call = JsCall::new(
255            self.handle.clone(),
256            args,
257            Some(Box::new(move |result| {
258                *slot.borrow_mut() =
259                    Some(result.and_then(|v| R::from_js(v).map_err(|e| e.0.into())));
260            })),
261            false,
262            traced,
263        );
264        self.handle.call_now(call);
265        let result = out.borrow_mut().take();
266        result.unwrap_or_else(|| Err("the JS function was not called".to_owned().into()))
267    }
268
269    /// Calls the function in the next JS turn, in order with the other
270    /// posts, forgetting its result (what it throws is reported as
271    /// uncaught). From anywhere on the engine thread.
272    pub fn post(&self, args: A) {
273        self.handle
274            .post(JsCall::new(self.handle.clone(), args, None, false, false));
275    }
276
277    /// Calls the function in the next JS turn: its result (a promise it
278    /// returns, settled), or the message of what it threw.
279    pub fn call_async(&self, args: A) -> Answer<Result<R, String>> {
280        let (answer, slot) = Answer::new();
281        self.handle.post(JsCall::new(
282            self.handle.clone(),
283            args,
284            Some(Box::new(move |result| {
285                let value = result
286                    .map_err(|e| e.message)
287                    .and_then(|v| R::from_js(v).map_err(|e| e.0));
288                slot.borrow_mut().deliver(value);
289            })),
290            true,
291            false,
292        ));
293        answer
294    }
295
296    /// [`Callback::call_async`], with what the function threw (or its
297    /// promise rejected with) whole: the message and the stack, which says
298    /// where it was thrown (a test's failing line).
299    pub fn call_async_traced(&self, args: A) -> Answer<Result<R, Exception>> {
300        let (answer, slot) = Answer::new();
301        self.handle.post(JsCall::new(
302            self.handle.clone(),
303            args,
304            Some(Box::new(move |result| {
305                let value = result.and_then(|v| R::from_js(v).map_err(|e| e.0.into()));
306                slot.borrow_mut().deliver(value);
307            })),
308            true,
309            true,
310        ));
311        answer
312    }
313}
314
315/// The arguments of a [`Callback`]: one value, `()` for none, or a tuple.
316pub trait CallbackArgs {
317    /// How many there are.
318    const ARITY: usize;
319
320    /// Its TypeScript parameters, named `names` (`name: string, amount:
321    /// number`), or without names `value` for one and `a`, `b`, ... for
322    /// several.
323    fn ts_params(types: &mut TsTypes, names: &[&str]) -> String;
324    /// The arguments as JS values.
325    fn into_js_args<'a>(self, host: &'a dyn JsHost) -> Result<Vec<JsOwned<'a>>, PropError>;
326    /// Adds the classes the arguments name.
327    #[doc(hidden)]
328    fn classes(out: &mut Vec<&'static ClassDef>);
329}
330
331impl<T: Ret> CallbackArgs for T {
332    const ARITY: usize = if T::UNIT { 0 } else { 1 };
333
334    fn ts_params(types: &mut TsTypes, names: &[&str]) -> String {
335        if T::UNIT {
336            String::new()
337        } else {
338            format!(
339                "{}: {}",
340                names.first().copied().unwrap_or("value"),
341                T::ts_type(types)
342            )
343        }
344    }
345
346    fn into_js_args<'a>(self, host: &'a dyn JsHost) -> Result<Vec<JsOwned<'a>>, PropError> {
347        if T::UNIT {
348            Ok(Vec::new())
349        } else {
350            Ok(vec![Ret::into_js(self, host)?])
351        }
352    }
353
354    fn classes(out: &mut Vec<&'static ClassDef>) {
355        T::classes(out);
356    }
357}
358
359macro_rules! callback_tuple {
360    ($(($($t:ident $v:ident $n:literal $i:literal),*)),*) => {$(
361        impl<$($t: Ret),*> CallbackArgs for ($($t,)*) {
362            const ARITY: usize = [$($n),*].len();
363
364            fn ts_params(types: &mut TsTypes, names: &[&str]) -> String {
365                let defaults = [$($n),*];
366                [$($t::ts_type(types)),*]
367                    .iter()
368                    .enumerate()
369                    .map(|(i, ts)| format!("{}: {ts}", names.get(i).copied().unwrap_or(defaults[i])))
370                    .collect::<Vec<_>>()
371                    .join(", ")
372            }
373
374            fn into_js_args<'a>(self, host: &'a dyn JsHost) -> Result<Vec<JsOwned<'a>>, PropError> {
375                let ($($v,)*) = self;
376                Ok(vec![$(Ret::into_js($v, host)?),*])
377            }
378
379            fn classes(out: &mut Vec<&'static ClassDef>) {
380                $($t::classes(out);)*
381            }
382        }
383    )*};
384}
385
386callback_tuple!(
387    (A a "a" 0, B b "b" 1),
388    (A a "a" 0, B b "b" 1, C c "c" 2),
389    (A a "a" 0, B b "b" 1, C c "c" 2, D d "d" 3)
390);
391
392/// What a [`Callback`] returns: a [`JsValue`] type, or `()` (its result
393/// ignored).
394pub trait CallbackRet: Sized {
395    /// Its TypeScript type.
396    fn ts_type(types: &mut TsTypes) -> String;
397    /// The value the function returned.
398    fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
399}
400
401impl<T: JsValue> CallbackRet for T {
402    fn ts_type(types: &mut TsTypes) -> String {
403        T::ts_type(types)
404    }
405
406    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
407        T::from_js(value)
408    }
409}
410
411impl CallbackRet for () {
412    fn ts_type(_types: &mut TsTypes) -> String {
413        "void".into()
414    }
415
416    fn from_js(_value: JsIn<'_>) -> Result<Self, PropError> {
417        Ok(())
418    }
419}
420
421/// A listener whose promise the caller awaits (`Application.on("quit")`):
422/// `(…) => void | Promise<void>`. What the function returns is not read
423/// here; the callback's caller awaits the promise the call made.
424pub struct Settles;
425
426impl CallbackRet for Settles {
427    fn ts_type(_types: &mut TsTypes) -> String {
428        "void | Promise<void>".into()
429    }
430
431    fn from_js(_value: JsIn<'_>) -> Result<Self, PropError> {
432        Ok(Settles)
433    }
434}
435
436/// The TypeScript type of a callback whose arguments are named `names`
437/// (none: the defaults): `(value: string) => void`.
438fn callback_ts<A: CallbackArgs, R: CallbackRet>(types: &mut TsTypes, names: &[&str]) -> String {
439    format!("({}) => {}", A::ts_params(types, names), R::ts_type(types))
440}
441
442/// A parameter whose JS function's arguments `#[args(..)]` names: a
443/// [`Callback`], or an `Option` of one.
444#[doc(hidden)]
445#[diagnostic::on_unimplemented(
446    message = "`#[args(..)]` names the arguments of a `Callback`: `{Self}` is not one",
447    label = "`#[args(..)]` is for a `Callback<A, R>` parameter (or an `Option` of one)"
448)]
449pub trait NamedArgs {
450    /// How many arguments the function takes.
451    const ARITY: usize;
452    /// The parameter's TypeScript type, its function's arguments named
453    /// `names`.
454    fn ts_named(types: &mut TsTypes, names: &[&str]) -> String;
455}
456
457impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> NamedArgs for Callback<A, R> {
458    const ARITY: usize = A::ARITY;
459
460    fn ts_named(types: &mut TsTypes, names: &[&str]) -> String {
461        callback_ts::<A, R>(types, names)
462    }
463}
464
465impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> NamedArgs for Option<Callback<A, R>> {
466    const ARITY: usize = A::ARITY;
467
468    fn ts_named(types: &mut TsTypes, names: &[&str]) -> String {
469        format!("({}) | null", callback_ts::<A, R>(types, names))
470    }
471}
472
473impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> Arg for Callback<A, R> {
474    fn ts_type(types: &mut TsTypes) -> String {
475        callback_ts::<A, R>(types, &[])
476    }
477
478    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
479        value
480            .host()
481            .callback(value.raw())
482            .map(Callback::of)
483            .ok_or_else(|| value.expected("a function"))
484    }
485
486    fn classes(out: &mut Vec<&'static ClassDef>) {
487        A::classes(out);
488    }
489}
490
491/// `null` or `undefined` is `None`.
492impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> Arg for Option<Callback<A, R>> {
493    fn ts_type(types: &mut TsTypes) -> String {
494        format!("({}) | null", callback_ts::<A, R>(types, &[]))
495    }
496
497    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
498        if value.is_nullish() {
499            return Ok(None);
500        }
501        Callback::from_js(value).map(Some)
502    }
503
504    fn classes(out: &mut Vec<&'static ClassDef>) {
505        A::classes(out);
506    }
507}
508
509// --- Tracing ----------------------------------------------------------------------
510
511/// Where a class reports the callbacks its value keeps, for QuickJS's
512/// collector: a callback whose function reaches the instance's own JS
513/// object would keep both alive forever otherwise.
514pub struct Tracer<'a> {
515    mark: &'a mut dyn FnMut(&dyn CallbackHandle),
516}
517
518impl<'a> Tracer<'a> {
519    /// Reports callbacks to `mark`.
520    #[doc(hidden)]
521    pub fn new(mark: &'a mut dyn FnMut(&dyn CallbackHandle)) -> Self {
522        Self { mark }
523    }
524}
525
526impl fmt::Debug for Tracer<'_> {
527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528        f.write_str("Tracer")
529    }
530}
531
532/// What reports the callbacks a value keeps, for QuickJS's collector.
533/// `#[class]` on a struct implements it from the fields whose types
534/// implement it (`Callback`, `Instance`, and `Option`, `Box`, `RefCell`,
535/// `Vec`, `VecDeque`, `HashMap` / `BTreeMap` values and pairs of them);
536/// other fields are not reported, which is always safe: what they keep
537/// stays alive while they do.
538///
539/// # Safety
540///
541/// The collector counts each reported function as one reference held by
542/// the instance's JS object. An implementation reports, on each call, a
543/// callback at most once, and only one held through this value alone (no
544/// other value or clone keeps it, as the impls of `Callback` and
545/// `Instance` check with their strong counts): reporting one twice, or one
546/// shared (an `Rc` reached from two instances), lets the collector free a
547/// function still in use. It never panics, allocates JS values or runs
548/// JS: it is called from the collector's mark phase, which a panic would
549/// leave half done (the runtime catches one and logs it, and what was not
550/// reported stays alive, but a panic midway may already have reported part
551/// of a value). It reads only, without borrowing what the app may hold
552/// borrowed (`RefCell::try_borrow`: a value borrowed elsewhere is
553/// skipped).
554pub unsafe trait Trace {
555    /// Reports the callbacks to `tracer`.
556    fn trace(&self, tracer: &mut Tracer<'_>);
557}
558
559/// A callback held only here: shared ones are kept alive by whoever else
560/// holds them (reporting those would let the collector free a function
561/// still in use).
562unsafe impl<A, R> Trace for Callback<A, R> {
563    fn trace(&self, tracer: &mut Tracer<'_>) {
564        if Rc::strong_count(&self.handle) == 1 {
565            (tracer.mark)(&*self.handle);
566        }
567    }
568}
569
570/// An instance held only here: the callbacks its value keeps.
571unsafe impl<C: Class> Trace for Instance<C> {
572    fn trace(&self, tracer: &mut Tracer<'_>) {
573        if self.only_handle() {
574            self.trace_value(tracer);
575        }
576    }
577}
578
579unsafe impl<T: Trace> Trace for Option<T> {
580    fn trace(&self, tracer: &mut Tracer<'_>) {
581        if let Some(v) = self {
582            v.trace(tracer);
583        }
584    }
585}
586
587unsafe impl<T: Trace> Trace for Box<T> {
588    fn trace(&self, tracer: &mut Tracer<'_>) {
589        (**self).trace(tracer);
590    }
591}
592
593unsafe impl<T: Trace> Trace for RefCell<T> {
594    fn trace(&self, tracer: &mut Tracer<'_>) {
595        if let Ok(v) = self.try_borrow() {
596            v.trace(tracer);
597        }
598    }
599}
600
601unsafe impl<T: Trace> Trace for Vec<T> {
602    fn trace(&self, tracer: &mut Tracer<'_>) {
603        for v in self {
604            v.trace(tracer);
605        }
606    }
607}
608
609unsafe impl<T: Trace> Trace for VecDeque<T> {
610    fn trace(&self, tracer: &mut Tracer<'_>) {
611        for v in self {
612            v.trace(tracer);
613        }
614    }
615}
616
617unsafe impl<K, T: Trace, S> Trace for HashMap<K, T, S> {
618    fn trace(&self, tracer: &mut Tracer<'_>) {
619        for v in self.values() {
620            v.trace(tracer);
621        }
622    }
623}
624
625unsafe impl<K, T: Trace> Trace for BTreeMap<K, T> {
626    fn trace(&self, tracer: &mut Tracer<'_>) {
627        for v in self.values() {
628            v.trace(tracer);
629        }
630    }
631}
632
633unsafe impl<A: Trace, B: Trace> Trace for (A, B) {
634    fn trace(&self, tracer: &mut Tracer<'_>) {
635        self.0.trace(tracer);
636        self.1.trace(tracer);
637    }
638}