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
421fn 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#[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 const ARITY: usize;
437 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
476impl<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
494pub struct Tracer<'a> {
500 mark: &'a mut dyn FnMut(&dyn CallbackHandle),
501}
502
503impl<'a> Tracer<'a> {
504 #[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
517pub unsafe trait Trace {
540 fn trace(&self, tracer: &mut Tracer<'_>);
542}
543
544unsafe 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
555unsafe 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}