Skip to main content

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