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>>;
43type 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    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/// The TypeScript type of a callback whose arguments are named `names`
422/// (none: the defaults): `(value: string) => void`.
423fn callback_ts<A: CallbackArgs, R: CallbackRet>(types: &mut TsTypes, names: &[&str]) -> String {
424    format!("({}) => {}", A::ts_params(types, names), R::ts_type(types))
425}
426
427/// A parameter whose JS function's arguments `#[args(..)]` names: a
428/// [`Callback`], or an `Option` of one.
429#[doc(hidden)]
430#[diagnostic::on_unimplemented(
431    message = "`#[args(..)]` names the arguments of a `Callback`: `{Self}` is not one",
432    label = "`#[args(..)]` is for a `Callback<A, R>` parameter (or an `Option` of one)"
433)]
434pub trait NamedArgs {
435    /// How many arguments the function takes.
436    const ARITY: usize;
437    /// The parameter's TypeScript type, its function's arguments named
438    /// `names`.
439    fn ts_named(types: &mut TsTypes, names: &[&str]) -> String;
440}
441
442impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> NamedArgs for Callback<A, R> {
443    const ARITY: usize = A::ARITY;
444
445    fn ts_named(types: &mut TsTypes, names: &[&str]) -> String {
446        callback_ts::<A, R>(types, names)
447    }
448}
449
450impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> NamedArgs for Option<Callback<A, R>> {
451    const ARITY: usize = A::ARITY;
452
453    fn ts_named(types: &mut TsTypes, names: &[&str]) -> String {
454        format!("({}) | null", callback_ts::<A, R>(types, names))
455    }
456}
457
458impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> Arg for Callback<A, R> {
459    fn ts_type(types: &mut TsTypes) -> String {
460        callback_ts::<A, R>(types, &[])
461    }
462
463    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
464        value
465            .host()
466            .callback(value.raw())
467            .map(Callback::of)
468            .ok_or_else(|| value.expected("a function"))
469    }
470
471    fn classes(out: &mut Vec<&'static ClassDef>) {
472        A::classes(out);
473    }
474}
475
476/// `null` or `undefined` is `None`.
477impl<A: CallbackArgs + 'static, R: CallbackRet + 'static> Arg for Option<Callback<A, R>> {
478    fn ts_type(types: &mut TsTypes) -> String {
479        format!("({}) | null", callback_ts::<A, R>(types, &[]))
480    }
481
482    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
483        if value.is_nullish() {
484            return Ok(None);
485        }
486        Callback::from_js(value).map(Some)
487    }
488
489    fn classes(out: &mut Vec<&'static ClassDef>) {
490        A::classes(out);
491    }
492}
493
494// --- Tracing ----------------------------------------------------------------------
495
496/// Where a class reports the callbacks its value keeps, for QuickJS's
497/// collector: a callback whose function reaches the instance's own JS
498/// object would keep both alive forever otherwise.
499pub struct Tracer<'a> {
500    mark: &'a mut dyn FnMut(&dyn CallbackHandle),
501}
502
503impl<'a> Tracer<'a> {
504    /// Reports callbacks to `mark`.
505    #[doc(hidden)]
506    pub fn new(mark: &'a mut dyn FnMut(&dyn CallbackHandle)) -> Self {
507        Self { mark }
508    }
509}
510
511impl fmt::Debug for Tracer<'_> {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.write_str("Tracer")
514    }
515}
516
517/// What reports the callbacks a value keeps, for QuickJS's collector.
518/// `#[class]` on a struct implements it from the fields whose types
519/// implement it (`Callback`, `Instance`, and `Option`, `Box`, `RefCell`,
520/// `Vec`, `VecDeque`, `HashMap` / `BTreeMap` values and pairs of them);
521/// other fields are not reported, which is always safe: what they keep
522/// stays alive while they do.
523///
524/// # Safety
525///
526/// The collector counts each reported function as one reference held by
527/// the instance's JS object. An implementation reports, on each call, a
528/// callback at most once, and only one held through this value alone (no
529/// other value or clone keeps it, as the impls of `Callback` and
530/// `Instance` check with their strong counts): reporting one twice, or one
531/// shared (an `Rc` reached from two instances), lets the collector free a
532/// function still in use. It never panics, allocates JS values or runs
533/// JS: it is called from the collector's mark phase, which a panic would
534/// leave half done (the runtime catches one and logs it, and what was not
535/// reported stays alive, but a panic midway may already have reported part
536/// of a value). It reads only, without borrowing what the app may hold
537/// borrowed (`RefCell::try_borrow`: a value borrowed elsewhere is
538/// skipped).
539pub unsafe trait Trace {
540    /// Reports the callbacks to `tracer`.
541    fn trace(&self, tracer: &mut Tracer<'_>);
542}
543
544/// A callback held only here: shared ones are kept alive by whoever else
545/// holds them (reporting those would let the collector free a function
546/// still in use).
547unsafe impl<A, R> Trace for Callback<A, R> {
548    fn trace(&self, tracer: &mut Tracer<'_>) {
549        if Rc::strong_count(&self.handle) == 1 {
550            (tracer.mark)(&*self.handle);
551        }
552    }
553}
554
555/// An instance held only here: the callbacks its value keeps.
556unsafe impl<C: Class> Trace for Instance<C> {
557    fn trace(&self, tracer: &mut Tracer<'_>) {
558        if self.only_handle() {
559            self.trace_value(tracer);
560        }
561    }
562}
563
564unsafe impl<T: Trace> Trace for Option<T> {
565    fn trace(&self, tracer: &mut Tracer<'_>) {
566        if let Some(v) = self {
567            v.trace(tracer);
568        }
569    }
570}
571
572unsafe impl<T: Trace> Trace for Box<T> {
573    fn trace(&self, tracer: &mut Tracer<'_>) {
574        (**self).trace(tracer);
575    }
576}
577
578unsafe impl<T: Trace> Trace for RefCell<T> {
579    fn trace(&self, tracer: &mut Tracer<'_>) {
580        if let Ok(v) = self.try_borrow() {
581            v.trace(tracer);
582        }
583    }
584}
585
586unsafe impl<T: Trace> Trace for Vec<T> {
587    fn trace(&self, tracer: &mut Tracer<'_>) {
588        for v in self {
589            v.trace(tracer);
590        }
591    }
592}
593
594unsafe impl<T: Trace> Trace for VecDeque<T> {
595    fn trace(&self, tracer: &mut Tracer<'_>) {
596        for v in self {
597            v.trace(tracer);
598        }
599    }
600}
601
602unsafe impl<K, T: Trace, S> Trace for HashMap<K, T, S> {
603    fn trace(&self, tracer: &mut Tracer<'_>) {
604        for v in self.values() {
605            v.trace(tracer);
606        }
607    }
608}
609
610unsafe impl<K, T: Trace> Trace for BTreeMap<K, T> {
611    fn trace(&self, tracer: &mut Tracer<'_>) {
612        for v in self.values() {
613            v.trace(tracer);
614        }
615    }
616}
617
618unsafe impl<A: Trace, B: Trace> Trace for (A, B) {
619    fn trace(&self, tracer: &mut Tracer<'_>) {
620        self.0.trace(tracer);
621        self.1.trace(tracer);
622    }
623}