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 #[doc(hidden)]
482 fn boxed(self) -> Box<dyn super::ToJs>
483 where
484 Self: 'static,
485 {
486 Box::new(self)
487 }
488}
489
490impl<T: JsValue> Ret for T {
491 fn ts_type(types: &mut TsTypes) -> String {
492 T::ts_type(types)
493 }
494
495 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
496 self.to_js(host)
497 }
498}
499
500impl Ret for () {
501 const UNIT: bool = true;
502
503 fn ts_type(_types: &mut TsTypes) -> String {
504 "void".into()
505 }
506
507 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
508 Ok(JsOwned::new(host, host.undefined()))
509 }
510}
511
512impl<C: Class> Ret for Instance<C> {
513 fn ts_type(types: &mut TsTypes) -> String {
514 types.class(C::DEF)
515 }
516
517 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
518 Ok(JsOwned::new(host, host.wrap(self.erased())?))
519 }
520
521 fn classes(out: &mut Vec<&'static ClassDef>) {
522 out.push(C::DEF);
523 }
524}
525
526impl<C: Class> Ret for Vec<Instance<C>> {
528 fn ts_type(types: &mut TsTypes) -> String {
529 format!("{}[]", types.class(C::DEF))
530 }
531
532 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
533 let mut items = Vec::with_capacity(self.len());
535 for instance in self {
536 items.push(instance.into_js(host)?);
537 }
538 let raws = items.into_iter().map(JsOwned::into_raw).collect();
539 Ok(JsOwned::new(host, host.new_array(raws)?))
540 }
541
542 fn classes(out: &mut Vec<&'static ClassDef>) {
543 out.push(C::DEF);
544 }
545}
546
547impl<C: Class> Ret for Option<Instance<C>> {
548 fn ts_type(types: &mut TsTypes) -> String {
549 format!("{} | null", <Instance<C> as Ret>::ts_type(types))
550 }
551
552 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
553 match self {
554 Some(i) => i.into_js(host),
555 None => Ok(JsOwned::new(host, host.null())),
556 }
557 }
558
559 fn classes(out: &mut Vec<&'static ClassDef>) {
560 out.push(C::DEF);
561 }
562}
563
564#[derive(Debug, Clone)]
568pub struct MemberSpec {
569 pub name: &'static str,
571 pub doc: &'static str,
573 pub kind: MemberKind,
575 pub params: Vec<(&'static str, String, bool)>,
577 pub returns: Option<String>,
579 pub is_async: bool,
581 pub overloads: Vec<super::OverloadSpec>,
583}
584
585#[derive(Debug, Clone)]
587pub struct ClassSpec {
588 pub name: &'static str,
590 pub doc: &'static str,
592 pub members: Vec<MemberSpec>,
594 pub types: TsTypes,
596 pub def: &'static ClassDef,
598}
599
600impl ClassSpec {
601 pub(crate) fn of(def: &'static ClassDef) -> Self {
602 let mut types = TsTypes::default();
603 let members = def
604 .members
605 .iter()
606 .map(|m| MemberSpec {
607 name: m.name,
608 doc: m.doc,
609 kind: m.kind,
610 params: m
611 .params
612 .iter()
613 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
614 .collect(),
615 returns: m.returns.map(|ts| ts(&mut types)),
616 is_async: m.call.is_async(),
617 overloads: m
618 .overloads
619 .iter()
620 .map(|o| {
621 let params = o
622 .params
623 .iter()
624 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
625 .collect();
626 (params, o.returns.map(|ts| ts(&mut types)))
627 })
628 .collect(),
629 })
630 .collect();
631 Self {
632 name: def.name,
633 doc: def.doc,
634 members,
635 types,
636 def,
637 }
638 }
639}
640
641#[doc(hidden)]
645pub(crate) mod __private {
646 use super::*;
647
648 pub const fn arg_ts<T: Arg>() -> TsType {
651 if crate::element::DECLARATIONS {
652 T::ts_type
653 } else {
654 |_| String::new()
655 }
656 }
657
658 pub fn named_arg_ts<T: crate::element::callback::NamedArgs>(
662 types: &mut TsTypes,
663 names: &[&str],
664 ) -> String {
665 if crate::element::DECLARATIONS {
666 T::ts_named(types, names)
667 } else {
668 String::new()
669 }
670 }
671
672 pub const fn ret_ts<T: Ret>() -> TsType {
674 if crate::element::DECLARATIONS {
675 T::ts_type
676 } else {
677 |_| String::new()
678 }
679 }
680
681 pub fn class_into_js<C: Class>(value: C, host: &dyn JsHost) -> Result<JsOwned<'_>, PropError> {
683 Instance::new(value).into_js(host)
684 }
685
686 pub fn class_ts<C: Class>(types: &mut TsTypes) -> String {
688 types.class(C::DEF)
689 }
690
691 pub fn arg_classes<T: Arg>(out: &mut Vec<&'static ClassDef>) {
693 T::classes(out);
694 }
695
696 pub fn ret_classes<T: Ret>(out: &mut Vec<&'static ClassDef>) {
698 T::classes(out);
699 }
700
701 pub fn class_refs<C: Class>(out: &mut Vec<&'static ClassDef>) {
703 out.push(C::DEF);
704 }
705
706 pub fn arg<T: Arg>(host: &dyn JsHost, i: usize, what: &str, name: &str) -> Result<T, Thrown> {
709 T::from_js(JsIn::new(host, host.arg(i))).map_err(|e| bad_arg(e, what, name))
710 }
711
712 pub fn this<C: Class>(host: &dyn JsHost, what: &str) -> Result<Instance<C>, Thrown> {
714 host.instance(host.this())
715 .and_then(Instance::of)
716 .ok_or_else(|| illegal_invocation(what, C::DEF.name))
717 }
718
719 pub fn borrow<C: Class>(instance: &Instance<C>) -> Result<Ref<'_, C>, Thrown> {
721 instance.borrow()
722 }
723
724 pub fn borrow_mut<C: Class>(instance: &Instance<C>) -> Result<RefMut<'_, C>, Thrown> {
726 instance.borrow_mut()
727 }
728
729 pub fn borrow_arg<'a, C: Class>(
733 instance: &'a Instance<C>,
734 what: &str,
735 name: &str,
736 ) -> Result<Ref<'a, C>, Thrown> {
737 instance.borrow().map_err(|e| arg_error(e, what, name))
738 }
739
740 pub fn borrow_arg_mut<'a, C: Class>(
742 instance: &'a Instance<C>,
743 what: &str,
744 name: &str,
745 ) -> Result<RefMut<'a, C>, Thrown> {
746 instance.borrow_mut().map_err(|e| arg_error(e, what, name))
747 }
748
749 #[cold]
751 #[inline(never)]
752 fn bad_arg(e: PropError, what: &str, name: &str) -> Thrown {
753 Thrown::Type(format!("{what}: `{name}`: {e}"))
754 }
755
756 #[cold]
758 #[inline(never)]
759 fn illegal_invocation(what: &str, class: &str) -> Thrown {
760 Thrown::Type(format!("{what}: Illegal invocation: not a {class}"))
761 }
762
763 #[cold]
765 #[inline(never)]
766 fn arg_error(e: Thrown, what: &str, name: &str) -> Thrown {
767 match e {
768 Thrown::Type(m) => Thrown::Type(format!("{what}: `{name}`: {m}")),
769 Thrown::Range(m) => Thrown::Range(format!("{what}: `{name}`: {m}")),
770 Thrown::Error(m) => Thrown::Error(format!("{what}: `{name}`: {m}")),
771 Thrown::Fields(mut f) => {
772 f.message = format!("{what}: `{name}`: {}", f.message);
773 Thrown::Fields(f)
774 }
775 }
776 }
777
778 pub fn ret<T: Ret>(host: &dyn JsHost, value: T) -> Result<JsRaw, Thrown> {
780 value
781 .into_js(host)
782 .map(JsOwned::into_raw)
783 .map_err(|e| Thrown::Error(e.0))
784 }
785
786 pub fn ret_result<T: Ret, E: crate::element::IntoThrown>(
789 host: &dyn JsHost,
790 value: Result<T, E>,
791 ) -> Result<JsRaw, Thrown> {
792 match value {
793 Ok(v) => ret(host, v),
794 Err(e) => Err(e.into_thrown()),
795 }
796 }
797
798 pub fn start<T: Ret + 'static>(value: crate::element::Later<T>) -> Result<TaskStart, Thrown> {
800 Ok(Box::new(move || value.into_future()))
801 }
802
803 pub fn start_result<T: Ret + 'static, E: crate::element::IntoThrown>(
805 value: Result<crate::element::Later<T>, E>,
806 ) -> Result<TaskStart, Thrown> {
807 value.map_err(E::into_thrown).and_then(start)
808 }
809
810 pub fn call_cx(host: &dyn JsHost) -> crate::element::CallCx<'_> {
812 crate::element::CallCx::new(host)
813 }
814
815 pub fn system(host: &dyn JsHost) -> crate::element::System {
817 host.system()
818 }
819
820 pub fn construct<C: Class>(host: &dyn JsHost, value: C) -> Result<JsRaw, Thrown> {
822 host.construct(Instance::new(value).erased())
823 .map_err(|e| Thrown::Error(e.0))
824 }
825
826 pub fn construct_result<C: Class, E: crate::element::IntoThrown>(
828 host: &dyn JsHost,
829 value: Result<C, E>,
830 ) -> Result<JsRaw, Thrown> {
831 match value {
832 Ok(v) => construct(host, v),
833 Err(e) => Err(e.into_thrown()),
834 }
835 }
836
837 pub fn boxed<T: Ret + 'static>(value: T) -> JsResult {
839 Ok(value.boxed())
840 }
841
842 pub fn boxed_result<T: Ret + 'static, E: crate::element::IntoThrown>(
845 value: Result<T, E>,
846 ) -> JsResult {
847 match value {
848 Ok(v) => Ok(v.boxed()),
849 Err(e) => Err(e.into_thrown()),
850 }
851 }
852
853 #[diagnostic::on_unimplemented(
855 message = "`{Self}` needs `#[class]` on its struct too",
856 label = "a class's struct and its `impl` block both have `#[class]`"
857 )]
858 pub trait ClassDoc {
859 const DOC: &'static str;
861 const INTERFACE: bool;
863 }
864
865 #[diagnostic::on_unimplemented(
868 message = "`{Self}` needs `#[module]` on its struct too",
869 label = "a module's struct and its `impl` block both have `#[module]` (the struct's doc comment documents it)"
870 )]
871 pub trait ModuleDoc {
872 const DOC: &'static str;
874 }
875
876 pub struct Field<'a, T>(pub &'a T);
881
882 pub trait TraceField {
884 fn trace_field(&self, tracer: &mut Tracer<'_>);
886 }
887
888 impl<T: Trace> TraceField for &Field<'_, T> {
889 fn trace_field(&self, tracer: &mut Tracer<'_>) {
890 self.0.trace(tracer);
891 }
892 }
893
894 pub trait SkipField {
896 fn trace_field(&self, tracer: &mut Tracer<'_>);
898 }
899
900 impl<T> SkipField for Field<'_, T> {
901 fn trace_field(&self, _tracer: &mut Tracer<'_>) {}
902 }
903
904 pub fn type_id<T: 'static>() -> TypeId {
906 TypeId::of::<T>()
907 }
908
909 pub fn type_name<T: 'static>() -> &'static str {
911 std::any::type_name::<T>()
912 }
913}
914
915#[cfg(test)]
916mod tests {
917 use crate::{
918 element::{Registry, declarations},
919 prelude::*,
920 };
921
922 #[allow(dead_code)]
924 fn drop() {}
925
926 #[class]
928 struct Configured {
929 #[cfg(any())]
930 gone: NoSuchType,
931 kept: Option<Callback>,
932 }
933
934 #[class]
935 impl Configured {}
936
937 #[allow(dead_code)]
938 fn configured() -> Configured {
939 Configured { kept: None }
940 }
941
942 #[class]
944 struct Tally {
945 count: i64,
946 label: Option<String>,
947 }
948
949 #[class]
950 impl Tally {
951 pub(crate) fn new(start: Option<i64>) -> Self {
953 Tally {
954 count: start.unwrap_or(0),
955 label: None,
956 }
957 }
958
959 pub(crate) fn add(&mut self, by: i64, label: Option<String>) -> i64 {
961 let _ = label;
962 self.count += by;
963 self.count
964 }
965
966 #[getter]
968 pub(crate) fn count(&self) -> i64 {
969 self.count
970 }
971
972 #[setter]
973 pub(crate) fn set_count(&mut self, count: i64) {
974 self.count = count;
975 }
976
977 #[getter]
978 pub(crate) fn label(&self) -> Option<String> {
979 self.label.clone()
980 }
981
982 #[setter]
984 pub(crate) fn set_label(&mut self, label: Option<String>) {
985 self.label = label;
986 }
987
988 #[cfg(any())]
990 pub(crate) fn nowhere(&self) -> i64 {
991 0
992 }
993
994 pub(crate) fn parse(text: String) -> Result<Tally, String> {
996 text.parse()
997 .map(|count| Tally { count, label: None })
998 .map_err(|_| text)
999 }
1000
1001 pub(crate) fn reset(&mut self, to: Option<i64>, by: i64) {
1002 self.count = to.unwrap_or(0) + by;
1003 }
1004
1005 pub(crate) fn absorb(
1006 &mut self,
1007 other: &Tally,
1008 token: Option<Instance<Token>>,
1009 ) -> Instance<Token> {
1010 self.count += other.count;
1011 token.unwrap_or_else(|| Instance::new(Token))
1012 }
1013
1014 pub(crate) async fn save(this: Instance<Self>, path: String) -> Result<(), String> {
1016 let _ = (this, path);
1017 Ok(())
1018 }
1019
1020 pub(crate) async fn later(start: i64) -> Tally {
1021 Tally {
1022 count: start,
1023 label: None,
1024 }
1025 }
1026
1027 pub(crate) fn sort_by(&mut self, compare: Callback<(String, String), f64>) {
1029 let _ = compare;
1030 }
1031
1032 pub(crate) fn on(
1033 &mut self,
1034 #[args(count)] listener: Option<Callback<i64>>,
1035 done: Option<Callback>,
1036 ) {
1037 let _ = (listener, done);
1038 }
1039
1040 #[allow(dead_code)]
1042 fn bump(&mut self) {
1043 self.count += 1;
1044 }
1045
1046 #[allow(dead_code)]
1048 async fn private_later() -> i64 {
1049 0
1050 }
1051 }
1052
1053 #[class]
1055 struct Token;
1056
1057 #[class]
1058 impl Token {
1059 pub(crate) fn mint() -> Token {
1060 Token
1061 }
1062 }
1063
1064 #[test]
1065 fn classes_are_declared_from_their_definitions() {
1066 let mut registry = Registry::ui_set("test/ui");
1067 registry.class::<Tally>().class::<Token>();
1068 assert!(
1070 !<Tally as crate::element::Class>::DEF
1071 .members
1072 .iter()
1073 .any(|m| m.name == "bump" || m.name == "privateLater")
1074 );
1075 assert_eq!(
1076 declarations(®istry, &[]),
1077 r#"/** A tally kept in Rust. */
1078export declare class Tally {
1079 /** Starts at `start` (0 when left out). */
1080 constructor(start?: number | null);
1081 /** Adds `by`; the new count. */
1082 add(by: number, label?: string | null): number;
1083 /** The count. */
1084 get count(): number;
1085 set count(count: number);
1086 get label(): string | null;
1087 /** A setter's value is required, even an `Option`. */
1088 set label(label: string | null);
1089 /** A tally from `"12"`; throws on anything else. */
1090 static parse(text: string): Tally;
1091 reset(to: number | null, by: number): void;
1092 absorb(other: Tally, token?: Token | null): Token;
1093 /** Saves the count; resolves when it is written. */
1094 save(path: string): Promise<void>;
1095 static later(start: number): Promise<Tally>;
1096 /** Sorts with the app's comparison. */
1097 sortBy(compare: (a: string, b: string) => number): void;
1098 on(listener?: ((count: number) => void) | null, done?: (() => void) | null): void;
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/** Made by its members only. */
1105export declare class Token {
1106 /** Made by the class's members only. */
1107 private constructor();
1108 static mint(): Token;
1109 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1110 dispose(): void;
1111 [Symbol.dispose](): void;
1112}
1113
1114"#
1115 );
1116 }
1117
1118 #[module]
1120 struct Tools;
1121
1122 #[module]
1123 impl Tools {
1124 pub(crate) fn sum(values: Vec<f64>) -> f64 {
1126 values.iter().sum()
1127 }
1128
1129 pub(crate) fn shout(text: String) {
1130 let _ = text;
1131 }
1132
1133 pub(crate) fn measure(text: String, cx: &mut ModuleCx) -> usize {
1135 let _ = cx;
1136 text.len()
1137 }
1138
1139 pub(crate) fn pick(#[args(old_value, new_value)] choose: Callback<(f64, f64), f64>) -> f64 {
1141 choose.call((0.0, 1.0)).unwrap_or(0.0)
1142 }
1143
1144 pub(crate) fn beep(cx: &mut ModuleCx) {
1146 let _ = cx;
1147 }
1148
1149 pub(crate) fn check(cx: &mut ModuleCx) -> Result<(), String> {
1151 let _ = cx;
1152 Ok(())
1153 }
1154
1155 #[allow(clippy::unused_unit)]
1157 pub(crate) fn hum(cx: &mut ModuleCx) -> () {
1158 let _ = cx;
1159 }
1160
1161 pub(crate) async fn settle() {}
1163
1164 pub(crate) async fn later(listener: Callback<i64, String>) -> Result<String, String> {
1165 listener.call_async(1).await
1166 }
1167
1168 #[cfg(any())]
1170 pub(crate) fn nowhere() {}
1171
1172 #[allow(dead_code)]
1174 fn helper(text: String) -> String {
1175 text
1176 }
1177 }
1178
1179 #[test]
1180 fn functions_without_a_context_return_their_values() {
1181 let mut registry = Registry::ui_set("test/ui");
1182 registry.module::<Tools>();
1183 assert!(
1184 !<Tools as crate::element::Module>::FUNCTIONS
1185 .iter()
1186 .any(|f| f.name == "helper")
1187 );
1188 assert_eq!(
1189 declarations(®istry, &[]),
1190 r#"/** Functions of the three kinds. */
1191export interface ToolsModule {
1192 /** The sum, at once. */
1193 sum(values: (number)[]): number;
1194 shout(text: string): void;
1195 /** A promise of the length. */
1196 measure(text: string): Promise<number>;
1197 /** Picks with the app's choice, its arguments named. */
1198 pick(choose: (oldValue: number, newValue: number) => number): number;
1199 /** An op returning nothing: a plain call. */
1200 beep(): void;
1201 /** An op that may fail: a promise, rejected with an `Err`. */
1202 check(): Promise<void>;
1203 /** `-> ()` written out: the same as no return type. */
1204 hum(): void;
1205 /** A task returning nothing. */
1206 settle(): Promise<void>;
1207 later(listener: (value: number) => string): Promise<string>;
1208}
1209
1210/** Functions of the three kinds. */
1211export declare const Tools: ToolsModule;
1212
1213"#
1214 );
1215 }
1216
1217 #[test]
1220 fn registering_a_class_again_does_nothing() {
1221 let mut r = Registry::ui_set("test/ui");
1222 r.class::<Tally>().class::<Tally>();
1223 let tallies = r.class_specs().iter().filter(|c| c.name == "Tally").count();
1224 assert_eq!(tallies, 1);
1225 }
1226
1227 mod view {
1229 use crate::prelude::*;
1230
1231 pub(super) struct Tally;
1232
1233 impl Component for Tally {
1234 type Props = ();
1235 type Event = NoEvent;
1236
1237 fn view(_: (), _: Scope<NoEvent>) -> impl IntoElement {
1238 view()
1239 }
1240 }
1241 }
1242
1243 #[test]
1245 fn a_class_and_a_component_share_no_name() {
1246 let class_first = std::panic::catch_unwind(|| {
1247 Registry::ui_set("test/ui")
1248 .class::<Tally>()
1249 .register::<view::Tally>();
1250 });
1251 assert!(class_first.is_err(), "a component after a class");
1252 let component_first = std::panic::catch_unwind(|| {
1253 Registry::ui_set("test/ui")
1254 .register::<view::Tally>()
1255 .class::<Tally>();
1256 });
1257 assert!(component_first.is_err(), "a class after a component");
1258 }
1259}