1use std::{
19 any::{Any, TypeId},
20 cell::{Ref, RefCell, RefMut},
21 fmt,
22 rc::Rc,
23};
24
25use super::{
26 JsValue, PropError, TsType, TsTypes,
27 call::{JsResult, TaskStart},
28 callback::{Trace, Tracer},
29 js::{JsHost, JsIn, JsOwned, JsRaw},
30 module::ModuleParam,
31};
32
33pub trait Class: Trace + Sized + 'static {
38 const DEF: &'static ClassDef;
40}
41
42pub struct ClassDef {
44 pub name: &'static str,
46 pub doc: &'static str,
48 pub type_id: fn() -> TypeId,
50 pub type_name: fn() -> &'static str,
52 pub members: &'static [Member],
54 pub interface: bool,
58}
59
60impl ClassDef {
61 pub fn constructor(&self) -> Option<&'static Member> {
63 self.members
64 .iter()
65 .find(|m| m.kind == MemberKind::Constructor)
66 }
67}
68
69impl fmt::Debug for ClassDef {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.debug_struct("ClassDef")
72 .field("name", &self.name)
73 .finish_non_exhaustive()
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum MemberKind {
80 Constructor,
82 Method,
84 Getter,
86 Setter,
88 Static,
90}
91
92pub struct Member {
94 pub name: &'static str,
96 pub doc: &'static str,
98 pub kind: MemberKind,
100 pub params: &'static [ModuleParam],
102 pub returns: Option<TsType>,
104 pub refs: ClassRefs,
106 pub call: MemberCall,
108 pub overloads: &'static [super::Overload],
112}
113
114pub type ClassRefs = fn(&mut Vec<&'static ClassDef>);
119
120pub type AsyncCall = fn(&dyn JsHost) -> Result<TaskStart, Thrown>;
123
124#[derive(Clone, Copy)]
126pub enum MemberCall {
127 Sync(fn(&dyn JsHost) -> Result<JsRaw, Thrown>),
130 Async(AsyncCall),
133 Start(AsyncCall),
137}
138
139impl MemberCall {
140 pub fn is_async(&self) -> bool {
142 matches!(self, MemberCall::Async(_) | MemberCall::Start(_))
143 }
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum Thrown {
149 Type(String),
151 Range(String),
153 Error(String),
155 Fields(Box<super::ErrorFields>),
157}
158
159impl Thrown {
160 pub fn message(&self) -> &str {
162 match self {
163 Thrown::Type(m) | Thrown::Range(m) | Thrown::Error(m) => m,
164 Thrown::Fields(f) => &f.message,
165 }
166 }
167}
168
169impl From<PropError> for Thrown {
170 fn from(e: PropError) -> Self {
171 Thrown::Type(e.0)
172 }
173}
174
175impl From<String> for Thrown {
176 fn from(message: String) -> Self {
177 Thrown::Error(message)
178 }
179}
180
181impl From<&str> for Thrown {
182 fn from(message: &str) -> Self {
183 Thrown::Error(message.to_owned())
184 }
185}
186
187impl fmt::Display for Thrown {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 f.write_str(self.message())
190 }
191}
192
193pub struct Instance<C: 'static> {
208 cell: Rc<InstanceCell<C>>,
209}
210
211impl<C> Clone for Instance<C> {
212 fn clone(&self) -> Self {
213 Self {
214 cell: self.cell.clone(),
215 }
216 }
217}
218
219impl<C> fmt::Debug for Instance<C> {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(f, "Instance<{}>", std::any::type_name::<C>())
222 }
223}
224
225struct InstanceCell<C> {
227 value: RefCell<Option<C>>,
229}
230
231impl<C: Class> Instance<C> {
232 pub fn new(value: C) -> Self {
235 Self {
236 cell: Rc::new(InstanceCell {
237 value: RefCell::new(Some(value)),
238 }),
239 }
240 }
241
242 #[track_caller]
249 pub fn with<R>(&self, f: impl FnOnce(&C) -> R) -> R {
250 match self.borrow() {
251 Ok(value) => f(&value),
252 Err(e) => panic!("{e}"),
253 }
254 }
255
256 #[track_caller]
263 pub fn with_mut<R>(&self, f: impl FnOnce(&mut C) -> R) -> R {
264 match self.borrow_mut() {
265 Ok(mut value) => f(&mut value),
266 Err(e) => panic!("{e}"),
267 }
268 }
269
270 pub fn is_disposed(&self) -> bool {
273 matches!(self.cell.value.try_borrow().as_deref(), Ok(None))
274 }
275
276 #[track_caller]
283 pub fn dispose(&self) {
284 if let Err(e) = self.cell.dispose() {
285 panic!("{e}");
286 }
287 }
288
289 pub fn ptr_eq(&self, other: &Self) -> bool {
291 Rc::ptr_eq(&self.cell, &other.cell)
292 }
293
294 fn borrow(&self) -> Result<Ref<'_, C>, Thrown> {
295 let value = self
296 .cell
297 .value
298 .try_borrow()
299 .map_err(|_| Thrown::Type(reentrant(C::DEF.name)))?;
300 Ref::filter_map(value, Option::as_ref).map_err(|_| disposed(C::DEF.name))
301 }
302
303 fn borrow_mut(&self) -> Result<RefMut<'_, C>, Thrown> {
304 let value = self
305 .cell
306 .value
307 .try_borrow_mut()
308 .map_err(|_| Thrown::Type(reentrant(C::DEF.name)))?;
309 RefMut::filter_map(value, Option::as_mut).map_err(|_| disposed(C::DEF.name))
310 }
311
312 pub(super) fn only_handle(&self) -> bool {
315 Rc::strong_count(&self.cell) == 1
316 }
317
318 pub(super) fn trace_value(&self, tracer: &mut Tracer<'_>) {
320 self.cell.trace(tracer);
321 }
322
323 fn erased(&self) -> Rc<dyn ClassInstance> {
325 self.cell.clone()
326 }
327
328 fn of(any: Rc<dyn ClassInstance>) -> Option<Self> {
330 let any: Rc<dyn Any> = any;
331 any.downcast::<InstanceCell<C>>()
332 .ok()
333 .map(|cell| Self { cell })
334 }
335}
336
337#[cold]
341#[inline(never)]
342fn reentrant(class: &str) -> String {
343 format!("{class} used re-entrantly")
344}
345
346#[cold]
347#[inline(never)]
348fn disposed(class: &str) -> Thrown {
349 Thrown::Type(format!("{class} is disposed"))
350}
351
352#[cold]
353#[inline(never)]
354fn not_an_instance(value: JsIn<'_>, class: &str) -> PropError {
355 value.expected(&format!("a {class}"))
356}
357
358#[doc(hidden)]
360pub trait ClassInstance: Any {
361 fn def(&self) -> &'static ClassDef;
363 fn dispose(&self) -> Result<(), String>;
365 fn disposed(&self) -> bool;
367 fn trace(&self, tracer: &mut Tracer<'_>);
370}
371
372impl<C: Class> ClassInstance for InstanceCell<C> {
373 fn def(&self) -> &'static ClassDef {
374 C::DEF
375 }
376
377 fn dispose(&self) -> Result<(), String> {
378 let value = self
379 .value
380 .try_borrow_mut()
381 .map_err(|_| reentrant(C::DEF.name))?
382 .take();
383 drop(value);
385 Ok(())
386 }
387
388 fn disposed(&self) -> bool {
389 matches!(self.value.try_borrow().as_deref(), Ok(None))
390 }
391
392 fn trace(&self, tracer: &mut Tracer<'_>) {
393 if let Ok(value) = self.value.try_borrow()
394 && let Some(value) = &*value
395 {
396 value.trace(tracer);
397 }
398 }
399}
400
401pub trait Arg: Sized {
407 fn ts_type(types: &mut TsTypes) -> String;
409 fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
411 #[doc(hidden)]
414 fn classes(_out: &mut Vec<&'static ClassDef>) {}
415}
416
417impl<T: JsValue> Arg for T {
418 fn ts_type(types: &mut TsTypes) -> String {
419 T::ts_type(types)
420 }
421
422 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
423 T::from_js(value)
424 }
425}
426
427impl<C: Class> Arg for Instance<C> {
430 fn ts_type(types: &mut TsTypes) -> String {
431 types.class(C::DEF)
432 }
433
434 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
435 value
436 .host()
437 .instance(value.raw())
438 .and_then(Instance::of)
439 .ok_or_else(|| not_an_instance(value, C::DEF.name))
440 }
441
442 fn classes(out: &mut Vec<&'static ClassDef>) {
443 out.push(C::DEF);
444 }
445}
446
447impl<C: Class> Arg for Option<Instance<C>> {
449 fn ts_type(types: &mut TsTypes) -> String {
450 format!("{} | null", <Instance<C> as Arg>::ts_type(types))
451 }
452
453 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
454 if value.is_nullish() {
455 return Ok(None);
456 }
457 Instance::from_js(value).map(Some)
458 }
459
460 fn classes(out: &mut Vec<&'static ClassDef>) {
461 out.push(C::DEF);
462 }
463}
464
465pub trait Ret: Sized {
469 const UNIT: bool = false;
471 fn ts_type(types: &mut TsTypes) -> String;
473 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
475 #[doc(hidden)]
477 fn classes(_out: &mut Vec<&'static ClassDef>) {}
478}
479
480impl<T: JsValue> Ret for T {
481 fn ts_type(types: &mut TsTypes) -> String {
482 T::ts_type(types)
483 }
484
485 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
486 self.to_js(host)
487 }
488}
489
490impl Ret for () {
491 const UNIT: bool = true;
492
493 fn ts_type(_types: &mut TsTypes) -> String {
494 "void".into()
495 }
496
497 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
498 Ok(JsOwned::new(host, host.undefined()))
499 }
500}
501
502impl<C: Class> Ret for Instance<C> {
503 fn ts_type(types: &mut TsTypes) -> String {
504 types.class(C::DEF)
505 }
506
507 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
508 Ok(JsOwned::new(host, host.wrap(self.erased())?))
509 }
510
511 fn classes(out: &mut Vec<&'static ClassDef>) {
512 out.push(C::DEF);
513 }
514}
515
516impl<C: Class> Ret for Vec<Instance<C>> {
518 fn ts_type(types: &mut TsTypes) -> String {
519 format!("{}[]", types.class(C::DEF))
520 }
521
522 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
523 let mut items = Vec::with_capacity(self.len());
525 for instance in self {
526 items.push(instance.into_js(host)?);
527 }
528 let raws = items.into_iter().map(JsOwned::into_raw).collect();
529 Ok(JsOwned::new(host, host.new_array(raws)?))
530 }
531
532 fn classes(out: &mut Vec<&'static ClassDef>) {
533 out.push(C::DEF);
534 }
535}
536
537impl<C: Class> Ret for Option<Instance<C>> {
538 fn ts_type(types: &mut TsTypes) -> String {
539 format!("{} | null", <Instance<C> as Ret>::ts_type(types))
540 }
541
542 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
543 match self {
544 Some(i) => i.into_js(host),
545 None => Ok(JsOwned::new(host, host.null())),
546 }
547 }
548
549 fn classes(out: &mut Vec<&'static ClassDef>) {
550 out.push(C::DEF);
551 }
552}
553
554#[derive(Debug, Clone)]
558pub struct MemberSpec {
559 pub name: &'static str,
561 pub doc: &'static str,
563 pub kind: MemberKind,
565 pub params: Vec<(&'static str, String, bool)>,
567 pub returns: Option<String>,
569 pub is_async: bool,
571 pub overloads: Vec<super::OverloadSpec>,
573}
574
575#[derive(Debug, Clone)]
577pub struct ClassSpec {
578 pub name: &'static str,
580 pub doc: &'static str,
582 pub members: Vec<MemberSpec>,
584 pub types: TsTypes,
586 pub def: &'static ClassDef,
588}
589
590impl ClassSpec {
591 pub(crate) fn of(def: &'static ClassDef) -> Self {
592 let mut types = TsTypes::default();
593 let members = def
594 .members
595 .iter()
596 .map(|m| MemberSpec {
597 name: m.name,
598 doc: m.doc,
599 kind: m.kind,
600 params: m
601 .params
602 .iter()
603 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
604 .collect(),
605 returns: m.returns.map(|ts| ts(&mut types)),
606 is_async: m.call.is_async(),
607 overloads: m
608 .overloads
609 .iter()
610 .map(|o| {
611 let params = o
612 .params
613 .iter()
614 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
615 .collect();
616 (params, o.returns.map(|ts| ts(&mut types)))
617 })
618 .collect(),
619 })
620 .collect();
621 Self {
622 name: def.name,
623 doc: def.doc,
624 members,
625 types,
626 def,
627 }
628 }
629}
630
631#[doc(hidden)]
635pub(crate) mod __private {
636 use super::*;
637
638 pub const fn arg_ts<T: Arg>() -> TsType {
641 if crate::element::DECLARATIONS {
642 T::ts_type
643 } else {
644 |_| String::new()
645 }
646 }
647
648 pub fn named_arg_ts<T: crate::element::callback::NamedArgs>(
652 types: &mut TsTypes,
653 names: &[&str],
654 ) -> String {
655 if crate::element::DECLARATIONS {
656 T::ts_named(types, names)
657 } else {
658 String::new()
659 }
660 }
661
662 pub const fn ret_ts<T: Ret>() -> TsType {
664 if crate::element::DECLARATIONS {
665 T::ts_type
666 } else {
667 |_| String::new()
668 }
669 }
670
671 pub fn class_into_js<C: Class>(value: C, host: &dyn JsHost) -> Result<JsOwned<'_>, PropError> {
673 Instance::new(value).into_js(host)
674 }
675
676 pub fn class_ts<C: Class>(types: &mut TsTypes) -> String {
678 types.class(C::DEF)
679 }
680
681 pub fn arg_classes<T: Arg>(out: &mut Vec<&'static ClassDef>) {
683 T::classes(out);
684 }
685
686 pub fn ret_classes<T: Ret>(out: &mut Vec<&'static ClassDef>) {
688 T::classes(out);
689 }
690
691 pub fn class_refs<C: Class>(out: &mut Vec<&'static ClassDef>) {
693 out.push(C::DEF);
694 }
695
696 pub fn arg<T: Arg>(host: &dyn JsHost, i: usize, what: &str, name: &str) -> Result<T, Thrown> {
699 T::from_js(JsIn::new(host, host.arg(i))).map_err(|e| bad_arg(e, what, name))
700 }
701
702 pub fn this<C: Class>(host: &dyn JsHost, what: &str) -> Result<Instance<C>, Thrown> {
704 host.instance(host.this())
705 .and_then(Instance::of)
706 .ok_or_else(|| illegal_invocation(what, C::DEF.name))
707 }
708
709 pub fn borrow<C: Class>(instance: &Instance<C>) -> Result<Ref<'_, C>, Thrown> {
711 instance.borrow()
712 }
713
714 pub fn borrow_mut<C: Class>(instance: &Instance<C>) -> Result<RefMut<'_, C>, Thrown> {
716 instance.borrow_mut()
717 }
718
719 pub fn borrow_arg<'a, C: Class>(
723 instance: &'a Instance<C>,
724 what: &str,
725 name: &str,
726 ) -> Result<Ref<'a, C>, Thrown> {
727 instance.borrow().map_err(|e| arg_error(e, what, name))
728 }
729
730 pub fn borrow_arg_mut<'a, C: Class>(
732 instance: &'a Instance<C>,
733 what: &str,
734 name: &str,
735 ) -> Result<RefMut<'a, C>, Thrown> {
736 instance.borrow_mut().map_err(|e| arg_error(e, what, name))
737 }
738
739 #[cold]
741 #[inline(never)]
742 fn bad_arg(e: PropError, what: &str, name: &str) -> Thrown {
743 Thrown::Type(format!("{what}: `{name}`: {e}"))
744 }
745
746 #[cold]
748 #[inline(never)]
749 fn illegal_invocation(what: &str, class: &str) -> Thrown {
750 Thrown::Type(format!("{what}: Illegal invocation: not a {class}"))
751 }
752
753 #[cold]
755 #[inline(never)]
756 fn arg_error(e: Thrown, what: &str, name: &str) -> Thrown {
757 match e {
758 Thrown::Type(m) => Thrown::Type(format!("{what}: `{name}`: {m}")),
759 Thrown::Range(m) => Thrown::Range(format!("{what}: `{name}`: {m}")),
760 Thrown::Error(m) => Thrown::Error(format!("{what}: `{name}`: {m}")),
761 Thrown::Fields(mut f) => {
762 f.message = format!("{what}: `{name}`: {}", f.message);
763 Thrown::Fields(f)
764 }
765 }
766 }
767
768 pub fn ret<T: Ret>(host: &dyn JsHost, value: T) -> Result<JsRaw, Thrown> {
770 value
771 .into_js(host)
772 .map(JsOwned::into_raw)
773 .map_err(|e| Thrown::Error(e.0))
774 }
775
776 pub fn ret_result<T: Ret, E: crate::element::IntoThrown>(
779 host: &dyn JsHost,
780 value: Result<T, E>,
781 ) -> Result<JsRaw, Thrown> {
782 match value {
783 Ok(v) => ret(host, v),
784 Err(e) => Err(e.into_thrown()),
785 }
786 }
787
788 pub fn start<T: Ret + 'static>(value: crate::element::Later<T>) -> Result<TaskStart, Thrown> {
790 Ok(Box::new(move || value.into_future()))
791 }
792
793 pub fn start_result<T: Ret + 'static, E: crate::element::IntoThrown>(
795 value: Result<crate::element::Later<T>, E>,
796 ) -> Result<TaskStart, Thrown> {
797 value.map_err(E::into_thrown).and_then(start)
798 }
799
800 pub fn call_cx(host: &dyn JsHost) -> crate::element::CallCx<'_> {
802 crate::element::CallCx::new(host)
803 }
804
805 pub fn system(host: &dyn JsHost) -> crate::element::System {
807 host.system()
808 }
809
810 pub fn construct<C: Class>(host: &dyn JsHost, value: C) -> Result<JsRaw, Thrown> {
812 host.construct(Instance::new(value).erased())
813 .map_err(|e| Thrown::Error(e.0))
814 }
815
816 pub fn construct_result<C: Class, E: crate::element::IntoThrown>(
818 host: &dyn JsHost,
819 value: Result<C, E>,
820 ) -> Result<JsRaw, Thrown> {
821 match value {
822 Ok(v) => construct(host, v),
823 Err(e) => Err(e.into_thrown()),
824 }
825 }
826
827 pub fn boxed<T: Ret + 'static>(value: T) -> JsResult {
829 Ok(Box::new(value))
830 }
831
832 pub fn boxed_result<T: Ret + 'static, E: crate::element::IntoThrown>(
835 value: Result<T, E>,
836 ) -> JsResult {
837 match value {
838 Ok(v) => Ok(Box::new(v)),
839 Err(e) => Err(e.into_thrown()),
840 }
841 }
842
843 #[diagnostic::on_unimplemented(
845 message = "`{Self}` needs `#[class]` on its struct too",
846 label = "a class's struct and its `impl` block both have `#[class]`"
847 )]
848 pub trait ClassDoc {
849 const DOC: &'static str;
851 const INTERFACE: bool;
853 }
854
855 #[diagnostic::on_unimplemented(
858 message = "`{Self}` needs `#[module]` on its struct too",
859 label = "a module's struct and its `impl` block both have `#[module]` (the struct's doc comment documents it)"
860 )]
861 pub trait ModuleDoc {
862 const DOC: &'static str;
864 }
865
866 pub struct Field<'a, T>(pub &'a T);
871
872 pub trait TraceField {
874 fn trace_field(&self, tracer: &mut Tracer<'_>);
876 }
877
878 impl<T: Trace> TraceField for &Field<'_, T> {
879 fn trace_field(&self, tracer: &mut Tracer<'_>) {
880 self.0.trace(tracer);
881 }
882 }
883
884 pub trait SkipField {
886 fn trace_field(&self, tracer: &mut Tracer<'_>);
888 }
889
890 impl<T> SkipField for Field<'_, T> {
891 fn trace_field(&self, _tracer: &mut Tracer<'_>) {}
892 }
893
894 pub fn type_id<T: 'static>() -> TypeId {
896 TypeId::of::<T>()
897 }
898
899 pub fn type_name<T: 'static>() -> &'static str {
901 std::any::type_name::<T>()
902 }
903}
904
905#[cfg(test)]
906mod tests {
907 use crate::{
908 element::{Registry, declarations},
909 prelude::*,
910 };
911
912 #[allow(dead_code)]
914 fn drop() {}
915
916 #[class]
918 struct Configured {
919 #[cfg(any())]
920 gone: NoSuchType,
921 kept: Option<Callback>,
922 }
923
924 #[class]
925 impl Configured {}
926
927 #[allow(dead_code)]
928 fn configured() -> Configured {
929 Configured { kept: None }
930 }
931
932 #[class]
934 struct Tally {
935 count: i64,
936 label: Option<String>,
937 }
938
939 #[class]
940 impl Tally {
941 pub(crate) fn new(start: Option<i64>) -> Self {
943 Tally {
944 count: start.unwrap_or(0),
945 label: None,
946 }
947 }
948
949 pub(crate) fn add(&mut self, by: i64, label: Option<String>) -> i64 {
951 let _ = label;
952 self.count += by;
953 self.count
954 }
955
956 #[getter]
958 pub(crate) fn count(&self) -> i64 {
959 self.count
960 }
961
962 #[setter]
963 pub(crate) fn set_count(&mut self, count: i64) {
964 self.count = count;
965 }
966
967 #[getter]
968 pub(crate) fn label(&self) -> Option<String> {
969 self.label.clone()
970 }
971
972 #[setter]
974 pub(crate) fn set_label(&mut self, label: Option<String>) {
975 self.label = label;
976 }
977
978 #[cfg(any())]
980 pub(crate) fn nowhere(&self) -> i64 {
981 0
982 }
983
984 pub(crate) fn parse(text: String) -> Result<Tally, String> {
986 text.parse()
987 .map(|count| Tally { count, label: None })
988 .map_err(|_| text)
989 }
990
991 pub(crate) fn reset(&mut self, to: Option<i64>, by: i64) {
992 self.count = to.unwrap_or(0) + by;
993 }
994
995 pub(crate) fn absorb(
996 &mut self,
997 other: &Tally,
998 token: Option<Instance<Token>>,
999 ) -> Instance<Token> {
1000 self.count += other.count;
1001 token.unwrap_or_else(|| Instance::new(Token))
1002 }
1003
1004 pub(crate) async fn save(this: Instance<Self>, path: String) -> Result<(), String> {
1006 let _ = (this, path);
1007 Ok(())
1008 }
1009
1010 pub(crate) async fn later(start: i64) -> Tally {
1011 Tally {
1012 count: start,
1013 label: None,
1014 }
1015 }
1016
1017 pub(crate) fn sort_by(&mut self, compare: Callback<(String, String), f64>) {
1019 let _ = compare;
1020 }
1021
1022 pub(crate) fn on(
1023 &mut self,
1024 #[args(count)] listener: Option<Callback<i64>>,
1025 done: Option<Callback>,
1026 ) {
1027 let _ = (listener, done);
1028 }
1029
1030 #[allow(dead_code)]
1032 fn bump(&mut self) {
1033 self.count += 1;
1034 }
1035
1036 #[allow(dead_code)]
1038 async fn private_later() -> i64 {
1039 0
1040 }
1041 }
1042
1043 #[class]
1045 struct Token;
1046
1047 #[class]
1048 impl Token {
1049 pub(crate) fn mint() -> Token {
1050 Token
1051 }
1052 }
1053
1054 #[test]
1055 fn classes_are_declared_from_their_definitions() {
1056 let mut registry = Registry::ui_set("test/ui");
1057 registry.class::<Tally>().class::<Token>();
1058 assert!(
1060 !<Tally as crate::element::Class>::DEF
1061 .members
1062 .iter()
1063 .any(|m| m.name == "bump" || m.name == "privateLater")
1064 );
1065 assert_eq!(
1066 declarations(®istry, &[]),
1067 r#"/** A tally kept in Rust. */
1068export declare class Tally {
1069 /** Starts at `start` (0 when left out). */
1070 constructor(start?: number | null);
1071 /** Adds `by`; the new count. */
1072 add(by: number, label?: string | null): number;
1073 /** The count. */
1074 get count(): number;
1075 set count(count: number);
1076 get label(): string | null;
1077 /** A setter's value is required, even an `Option`. */
1078 set label(label: string | null);
1079 /** A tally from `"12"`; throws on anything else. */
1080 static parse(text: string): Tally;
1081 reset(to: number | null, by: number): void;
1082 absorb(other: Tally, token?: Token | null): Token;
1083 /** Saves the count; resolves when it is written. */
1084 save(path: string): Promise<void>;
1085 static later(start: number): Promise<Tally>;
1086 /** Sorts with the app's comparison. */
1087 sortBy(compare: (a: string, b: string) => number): void;
1088 on(listener?: ((count: number) => void) | null, done?: (() => void) | null): void;
1089 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1090 dispose(): void;
1091 [Symbol.dispose](): void;
1092}
1093
1094/** Made by its members only. */
1095export declare class Token {
1096 /** Made by the class's members only. */
1097 private constructor();
1098 static mint(): Token;
1099 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1100 dispose(): void;
1101 [Symbol.dispose](): void;
1102}
1103
1104"#
1105 );
1106 }
1107
1108 #[module]
1110 struct Tools;
1111
1112 #[module]
1113 impl Tools {
1114 pub(crate) fn sum(values: Vec<f64>) -> f64 {
1116 values.iter().sum()
1117 }
1118
1119 pub(crate) fn shout(text: String) {
1120 let _ = text;
1121 }
1122
1123 pub(crate) fn measure(text: String, cx: &mut ModuleCx) -> usize {
1125 let _ = cx;
1126 text.len()
1127 }
1128
1129 pub(crate) fn pick(#[args(old_value, new_value)] choose: Callback<(f64, f64), f64>) -> f64 {
1131 choose.call((0.0, 1.0)).unwrap_or(0.0)
1132 }
1133
1134 pub(crate) fn beep(cx: &mut ModuleCx) {
1136 let _ = cx;
1137 }
1138
1139 pub(crate) fn check(cx: &mut ModuleCx) -> Result<(), String> {
1141 let _ = cx;
1142 Ok(())
1143 }
1144
1145 #[allow(clippy::unused_unit)]
1147 pub(crate) fn hum(cx: &mut ModuleCx) -> () {
1148 let _ = cx;
1149 }
1150
1151 pub(crate) async fn settle() {}
1153
1154 pub(crate) async fn later(listener: Callback<i64, String>) -> Result<String, String> {
1155 listener.call_async(1).await
1156 }
1157
1158 #[cfg(any())]
1160 pub(crate) fn nowhere() {}
1161
1162 #[allow(dead_code)]
1164 fn helper(text: String) -> String {
1165 text
1166 }
1167 }
1168
1169 #[test]
1170 fn functions_without_a_context_return_their_values() {
1171 let mut registry = Registry::ui_set("test/ui");
1172 registry.module::<Tools>();
1173 assert!(
1174 !<Tools as crate::element::Module>::FUNCTIONS
1175 .iter()
1176 .any(|f| f.name == "helper")
1177 );
1178 assert_eq!(
1179 declarations(®istry, &[]),
1180 r#"/** Functions of the three kinds. */
1181export interface ToolsModule {
1182 /** The sum, at once. */
1183 sum(values: (number)[]): number;
1184 shout(text: string): void;
1185 /** A promise of the length. */
1186 measure(text: string): Promise<number>;
1187 /** Picks with the app's choice, its arguments named. */
1188 pick(choose: (oldValue: number, newValue: number) => number): number;
1189 /** An op returning nothing: a plain call. */
1190 beep(): void;
1191 /** An op that may fail: a promise, rejected with an `Err`. */
1192 check(): Promise<void>;
1193 /** `-> ()` written out: the same as no return type. */
1194 hum(): void;
1195 /** A task returning nothing. */
1196 settle(): Promise<void>;
1197 later(listener: (value: number) => string): Promise<string>;
1198}
1199
1200/** Functions of the three kinds. */
1201export declare const Tools: ToolsModule;
1202
1203"#
1204 );
1205 }
1206
1207 #[test]
1210 fn registering_a_class_again_does_nothing() {
1211 let mut r = Registry::ui_set("test/ui");
1212 r.class::<Tally>().class::<Tally>();
1213 let tallies = r.class_specs().iter().filter(|c| c.name == "Tally").count();
1214 assert_eq!(tallies, 1);
1215 }
1216
1217 mod view {
1219 use crate::prelude::*;
1220
1221 pub(super) struct Tally;
1222
1223 impl Component for Tally {
1224 type Props = ();
1225 type Event = NoEvent;
1226
1227 fn view(_: (), _: Scope<NoEvent>) -> impl IntoElement {
1228 view()
1229 }
1230 }
1231 }
1232
1233 #[test]
1235 fn a_class_and_a_component_share_no_name() {
1236 let class_first = std::panic::catch_unwind(|| {
1237 Registry::ui_set("test/ui")
1238 .class::<Tally>()
1239 .register::<view::Tally>();
1240 });
1241 assert!(class_first.is_err(), "a component after a class");
1242 let component_first = std::panic::catch_unwind(|| {
1243 Registry::ui_set("test/ui")
1244 .register::<view::Tally>()
1245 .class::<Tally>();
1246 });
1247 assert!(component_first.is_err(), "a class after a component");
1248 }
1249}