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