1use 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#[doc(hidden)]
26pub trait CallbackHandle: std::any::Any {
27 fn call_now(&self, call: JsCall);
33 fn post(&self, call: JsCall);
35 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
49#[non_exhaustive]
50pub struct Exception {
51 pub message: String,
53 pub stack: Option<String>,
55 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#[doc(hidden)]
82pub struct JsCall {
83 callback: Rc<dyn CallbackHandle>,
84 args: Option<ArgsFn>,
85 reply: Option<ReplyFn>,
86 settles: bool,
88 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 pub fn callback(&self) -> &Rc<dyn CallbackHandle> {
111 &self.callback
112 }
113
114 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 pub fn wants_reply(&self) -> bool {
124 self.reply.is_some()
125 }
126
127 pub fn settles(&self) -> bool {
130 self.settles
131 }
132
133 pub fn traced(&self) -> bool {
138 self.traced
139 }
140
141 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
167pub 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 pub(crate) fn handle(&self) -> &Rc<dyn CallbackHandle> {
201 &self.handle
202 }
203}
204
205impl<R: CallbackRet + 'static> Callback<(), R> {
206 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 pub fn call(&self, args: A) -> Result<R, String> {
238 self.call_now(args, false).map_err(|e| e.message)
239 }
240
241 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 pub fn post(&self, args: A) {
273 self.handle
274 .post(JsCall::new(self.handle.clone(), args, None, false, false));
275 }
276
277 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 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
315pub trait CallbackArgs {
317 const ARITY: usize;
319
320 fn ts_params(types: &mut TsTypes, names: &[&str]) -> String;
324 fn into_js_args<'a>(self, host: &'a dyn JsHost) -> Result<Vec<JsOwned<'a>>, PropError>;
326 #[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
392pub trait CallbackRet: Sized {
395 fn ts_type(types: &mut TsTypes) -> String;
397 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
421pub 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
436fn 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#[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 const ARITY: usize;
452 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
491impl<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
509pub struct Tracer<'a> {
515 mark: &'a mut dyn FnMut(&dyn CallbackHandle),
516}
517
518impl<'a> Tracer<'a> {
519 #[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
532pub unsafe trait Trace {
555 fn trace(&self, tracer: &mut Tracer<'_>);
557}
558
559unsafe 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
570unsafe 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}