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),
136}
137
138impl MemberCall {
139 pub fn is_async(&self) -> bool {
141 matches!(self, MemberCall::Async(_) | MemberCall::Start(_))
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Thrown {
148 Type(String),
150 Range(String),
152 Error(String),
154 Fields(Box<super::ErrorFields>),
156}
157
158impl Thrown {
159 pub fn message(&self) -> &str {
161 match self {
162 Thrown::Type(m) | Thrown::Range(m) | Thrown::Error(m) => m,
163 Thrown::Fields(f) => &f.message,
164 }
165 }
166}
167
168impl From<PropError> for Thrown {
169 fn from(e: PropError) -> Self {
170 Thrown::Type(e.0)
171 }
172}
173
174impl From<String> for Thrown {
175 fn from(message: String) -> Self {
176 Thrown::Error(message)
177 }
178}
179
180impl From<&str> for Thrown {
181 fn from(message: &str) -> Self {
182 Thrown::Error(message.to_owned())
183 }
184}
185
186impl fmt::Display for Thrown {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.write_str(self.message())
189 }
190}
191
192pub struct Instance<C: 'static> {
207 cell: Rc<InstanceCell<C>>,
208}
209
210impl<C> Clone for Instance<C> {
211 fn clone(&self) -> Self {
212 Self {
213 cell: self.cell.clone(),
214 }
215 }
216}
217
218impl<C> fmt::Debug for Instance<C> {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 write!(f, "Instance<{}>", std::any::type_name::<C>())
221 }
222}
223
224struct InstanceCell<C> {
226 value: RefCell<Option<C>>,
228}
229
230impl<C: Class> Instance<C> {
231 pub fn new(value: C) -> Self {
234 Self {
235 cell: Rc::new(InstanceCell {
236 value: RefCell::new(Some(value)),
237 }),
238 }
239 }
240
241 #[track_caller]
248 pub fn with<R>(&self, f: impl FnOnce(&C) -> R) -> R {
249 match self.borrow() {
250 Ok(value) => f(&value),
251 Err(e) => panic!("{e}"),
252 }
253 }
254
255 #[track_caller]
262 pub fn with_mut<R>(&self, f: impl FnOnce(&mut C) -> R) -> R {
263 match self.borrow_mut() {
264 Ok(mut value) => f(&mut value),
265 Err(e) => panic!("{e}"),
266 }
267 }
268
269 pub fn is_disposed(&self) -> bool {
272 matches!(self.cell.value.try_borrow().as_deref(), Ok(None))
273 }
274
275 #[track_caller]
282 pub fn dispose(&self) {
283 if let Err(e) = self.cell.dispose() {
284 panic!("{e}");
285 }
286 }
287
288 pub fn ptr_eq(&self, other: &Self) -> bool {
290 Rc::ptr_eq(&self.cell, &other.cell)
291 }
292
293 fn borrow(&self) -> Result<Ref<'_, C>, Thrown> {
294 let value = self
295 .cell
296 .value
297 .try_borrow()
298 .map_err(|_| Thrown::Type(format!("{} used re-entrantly", C::DEF.name)))?;
299 Ref::filter_map(value, Option::as_ref)
300 .map_err(|_| Thrown::Type(format!("{} is 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(format!("{} used re-entrantly", C::DEF.name)))?;
309 RefMut::filter_map(value, Option::as_mut)
310 .map_err(|_| Thrown::Type(format!("{} is disposed", C::DEF.name)))
311 }
312
313 pub(super) fn only_handle(&self) -> bool {
316 Rc::strong_count(&self.cell) == 1
317 }
318
319 pub(super) fn trace_value(&self, tracer: &mut Tracer<'_>) {
321 self.cell.trace(tracer);
322 }
323
324 fn erased(&self) -> Rc<dyn ClassInstance> {
326 self.cell.clone()
327 }
328
329 fn of(any: Rc<dyn ClassInstance>) -> Option<Self> {
331 let any: Rc<dyn Any> = any;
332 any.downcast::<InstanceCell<C>>()
333 .ok()
334 .map(|cell| Self { cell })
335 }
336}
337
338#[doc(hidden)]
340pub trait ClassInstance: Any {
341 fn def(&self) -> &'static ClassDef;
343 fn dispose(&self) -> Result<(), String>;
345 fn disposed(&self) -> bool;
347 fn trace(&self, tracer: &mut Tracer<'_>);
350}
351
352impl<C: Class> ClassInstance for InstanceCell<C> {
353 fn def(&self) -> &'static ClassDef {
354 C::DEF
355 }
356
357 fn dispose(&self) -> Result<(), String> {
358 let value = self
359 .value
360 .try_borrow_mut()
361 .map_err(|_| format!("{} used re-entrantly", C::DEF.name))?
362 .take();
363 drop(value);
365 Ok(())
366 }
367
368 fn disposed(&self) -> bool {
369 matches!(self.value.try_borrow().as_deref(), Ok(None))
370 }
371
372 fn trace(&self, tracer: &mut Tracer<'_>) {
373 if let Ok(value) = self.value.try_borrow()
374 && let Some(value) = &*value
375 {
376 value.trace(tracer);
377 }
378 }
379}
380
381pub trait Arg: Sized {
387 fn ts_type(types: &mut TsTypes) -> String;
389 fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
391 #[doc(hidden)]
394 fn classes(_out: &mut Vec<&'static ClassDef>) {}
395}
396
397impl<T: JsValue> Arg for T {
398 fn ts_type(types: &mut TsTypes) -> String {
399 T::ts_type(types)
400 }
401
402 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
403 T::from_js(value)
404 }
405}
406
407impl<C: Class> Arg for Instance<C> {
410 fn ts_type(types: &mut TsTypes) -> String {
411 types.class(C::DEF)
412 }
413
414 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
415 value
416 .host()
417 .instance(value.raw())
418 .and_then(Instance::of)
419 .ok_or_else(|| value.expected(&format!("a {}", C::DEF.name)))
420 }
421
422 fn classes(out: &mut Vec<&'static ClassDef>) {
423 out.push(C::DEF);
424 }
425}
426
427impl<C: Class> Arg for Option<Instance<C>> {
429 fn ts_type(types: &mut TsTypes) -> String {
430 format!("{} | null", <Instance<C> as Arg>::ts_type(types))
431 }
432
433 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
434 if value.is_nullish() {
435 return Ok(None);
436 }
437 Instance::from_js(value).map(Some)
438 }
439
440 fn classes(out: &mut Vec<&'static ClassDef>) {
441 out.push(C::DEF);
442 }
443}
444
445pub trait Ret: Sized {
449 const UNIT: bool = false;
451 fn ts_type(types: &mut TsTypes) -> String;
453 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
455 #[doc(hidden)]
457 fn classes(_out: &mut Vec<&'static ClassDef>) {}
458}
459
460impl<T: JsValue> Ret for T {
461 fn ts_type(types: &mut TsTypes) -> String {
462 T::ts_type(types)
463 }
464
465 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
466 self.to_js(host)
467 }
468}
469
470impl Ret for () {
471 const UNIT: bool = true;
472
473 fn ts_type(_types: &mut TsTypes) -> String {
474 "void".into()
475 }
476
477 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
478 Ok(JsOwned::new(host, host.undefined()))
479 }
480}
481
482impl<C: Class> Ret for Instance<C> {
483 fn ts_type(types: &mut TsTypes) -> String {
484 types.class(C::DEF)
485 }
486
487 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
488 Ok(JsOwned::new(host, host.wrap(self.erased())?))
489 }
490
491 fn classes(out: &mut Vec<&'static ClassDef>) {
492 out.push(C::DEF);
493 }
494}
495
496impl<C: Class> Ret for Vec<Instance<C>> {
498 fn ts_type(types: &mut TsTypes) -> String {
499 format!("{}[]", types.class(C::DEF))
500 }
501
502 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
503 let mut items = Vec::with_capacity(self.len());
505 for instance in self {
506 items.push(instance.into_js(host)?);
507 }
508 let raws = items.into_iter().map(JsOwned::into_raw).collect();
509 Ok(JsOwned::new(host, host.new_array(raws)?))
510 }
511
512 fn classes(out: &mut Vec<&'static ClassDef>) {
513 out.push(C::DEF);
514 }
515}
516
517impl<C: Class> Ret for Option<Instance<C>> {
518 fn ts_type(types: &mut TsTypes) -> String {
519 format!("{} | null", <Instance<C> as Ret>::ts_type(types))
520 }
521
522 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
523 match self {
524 Some(i) => i.into_js(host),
525 None => Ok(JsOwned::new(host, host.null())),
526 }
527 }
528
529 fn classes(out: &mut Vec<&'static ClassDef>) {
530 out.push(C::DEF);
531 }
532}
533
534#[derive(Debug, Clone)]
538pub struct MemberSpec {
539 pub name: &'static str,
541 pub doc: &'static str,
543 pub kind: MemberKind,
545 pub params: Vec<(&'static str, String, bool)>,
547 pub returns: Option<String>,
549 pub is_async: bool,
551 pub overloads: Vec<super::OverloadSpec>,
553}
554
555#[derive(Debug, Clone)]
557pub struct ClassSpec {
558 pub name: &'static str,
560 pub doc: &'static str,
562 pub members: Vec<MemberSpec>,
564 pub types: TsTypes,
566 pub def: &'static ClassDef,
568}
569
570impl ClassSpec {
571 pub(crate) fn of(def: &'static ClassDef) -> Self {
572 let mut types = TsTypes::default();
573 let members = def
574 .members
575 .iter()
576 .map(|m| MemberSpec {
577 name: m.name,
578 doc: m.doc,
579 kind: m.kind,
580 params: m
581 .params
582 .iter()
583 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
584 .collect(),
585 returns: m.returns.map(|ts| ts(&mut types)),
586 is_async: m.call.is_async(),
587 overloads: m
588 .overloads
589 .iter()
590 .map(|o| {
591 let params = o
592 .params
593 .iter()
594 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
595 .collect();
596 (params, o.returns.map(|ts| ts(&mut types)))
597 })
598 .collect(),
599 })
600 .collect();
601 Self {
602 name: def.name,
603 doc: def.doc,
604 members,
605 types,
606 def,
607 }
608 }
609}
610
611#[doc(hidden)]
615pub(crate) mod __private {
616 use super::*;
617
618 pub const fn arg_ts<T: Arg>() -> TsType {
621 if crate::element::DECLARATIONS {
622 T::ts_type
623 } else {
624 |_| String::new()
625 }
626 }
627
628 pub fn named_arg_ts<T: crate::element::callback::NamedArgs>(
632 types: &mut TsTypes,
633 names: &[&str],
634 ) -> String {
635 if crate::element::DECLARATIONS {
636 T::ts_named(types, names)
637 } else {
638 String::new()
639 }
640 }
641
642 pub const fn ret_ts<T: Ret>() -> TsType {
644 if crate::element::DECLARATIONS {
645 T::ts_type
646 } else {
647 |_| String::new()
648 }
649 }
650
651 pub fn class_into_js<C: Class>(value: C, host: &dyn JsHost) -> Result<JsOwned<'_>, PropError> {
653 Instance::new(value).into_js(host)
654 }
655
656 pub fn class_ts<C: Class>(types: &mut TsTypes) -> String {
658 types.class(C::DEF)
659 }
660
661 pub fn arg_classes<T: Arg>(out: &mut Vec<&'static ClassDef>) {
663 T::classes(out);
664 }
665
666 pub fn ret_classes<T: Ret>(out: &mut Vec<&'static ClassDef>) {
668 T::classes(out);
669 }
670
671 pub fn class_refs<C: Class>(out: &mut Vec<&'static ClassDef>) {
673 out.push(C::DEF);
674 }
675
676 pub fn arg<T: Arg>(host: &dyn JsHost, i: usize, what: &str, name: &str) -> Result<T, Thrown> {
679 T::from_js(JsIn::new(host, host.arg(i)))
680 .map_err(|e| Thrown::Type(format!("{what}: `{name}`: {e}")))
681 }
682
683 pub fn this<C: Class>(host: &dyn JsHost, what: &str) -> Result<Instance<C>, Thrown> {
685 host.instance(host.this())
686 .and_then(Instance::of)
687 .ok_or_else(|| {
688 Thrown::Type(format!("{what}: Illegal invocation: not a {}", C::DEF.name))
689 })
690 }
691
692 pub fn borrow<C: Class>(instance: &Instance<C>) -> Result<Ref<'_, C>, Thrown> {
694 instance.borrow()
695 }
696
697 pub fn borrow_mut<C: Class>(instance: &Instance<C>) -> Result<RefMut<'_, C>, Thrown> {
699 instance.borrow_mut()
700 }
701
702 pub fn borrow_arg<'a, C: Class>(
706 instance: &'a Instance<C>,
707 what: &str,
708 name: &str,
709 ) -> Result<Ref<'a, C>, Thrown> {
710 instance.borrow().map_err(|e| arg_error(e, what, name))
711 }
712
713 pub fn borrow_arg_mut<'a, C: Class>(
715 instance: &'a Instance<C>,
716 what: &str,
717 name: &str,
718 ) -> Result<RefMut<'a, C>, Thrown> {
719 instance.borrow_mut().map_err(|e| arg_error(e, what, name))
720 }
721
722 fn arg_error(e: Thrown, what: &str, name: &str) -> Thrown {
724 match e {
725 Thrown::Type(m) => Thrown::Type(format!("{what}: `{name}`: {m}")),
726 Thrown::Range(m) => Thrown::Range(format!("{what}: `{name}`: {m}")),
727 Thrown::Error(m) => Thrown::Error(format!("{what}: `{name}`: {m}")),
728 Thrown::Fields(mut f) => {
729 f.message = format!("{what}: `{name}`: {}", f.message);
730 Thrown::Fields(f)
731 }
732 }
733 }
734
735 pub fn ret<T: Ret>(host: &dyn JsHost, value: T) -> Result<JsRaw, Thrown> {
737 value
738 .into_js(host)
739 .map(JsOwned::into_raw)
740 .map_err(|e| Thrown::Error(e.0))
741 }
742
743 pub fn ret_result<T: Ret, E: crate::element::IntoThrown>(
746 host: &dyn JsHost,
747 value: Result<T, E>,
748 ) -> Result<JsRaw, Thrown> {
749 match value {
750 Ok(v) => ret(host, v),
751 Err(e) => Err(e.into_thrown()),
752 }
753 }
754
755 pub fn start<T: Ret + 'static>(value: crate::element::Later<T>) -> Result<TaskStart, Thrown> {
757 Ok(Box::new(move || value.into_future()))
758 }
759
760 pub fn start_result<T: Ret + 'static, E: crate::element::IntoThrown>(
762 value: Result<crate::element::Later<T>, E>,
763 ) -> Result<TaskStart, Thrown> {
764 value.map_err(E::into_thrown).and_then(start)
765 }
766
767 pub fn call_cx(host: &dyn JsHost) -> crate::element::CallCx<'_> {
769 crate::element::CallCx::new(host)
770 }
771
772 pub fn system(host: &dyn JsHost) -> crate::element::System {
774 host.system()
775 }
776
777 pub fn construct<C: Class>(host: &dyn JsHost, value: C) -> Result<JsRaw, Thrown> {
779 host.construct(Instance::new(value).erased())
780 .map_err(|e| Thrown::Error(e.0))
781 }
782
783 pub fn construct_result<C: Class, E: crate::element::IntoThrown>(
785 host: &dyn JsHost,
786 value: Result<C, E>,
787 ) -> Result<JsRaw, Thrown> {
788 match value {
789 Ok(v) => construct(host, v),
790 Err(e) => Err(e.into_thrown()),
791 }
792 }
793
794 pub fn boxed<T: Ret + 'static>(value: T) -> JsResult {
796 Ok(Box::new(value))
797 }
798
799 pub fn boxed_result<T: Ret + 'static, E: crate::element::IntoThrown>(
802 value: Result<T, E>,
803 ) -> JsResult {
804 match value {
805 Ok(v) => Ok(Box::new(v)),
806 Err(e) => Err(e.into_thrown()),
807 }
808 }
809
810 #[diagnostic::on_unimplemented(
812 message = "`{Self}` needs `#[class]` on its struct too",
813 label = "a class's struct and its `impl` block both have `#[class]`"
814 )]
815 pub trait ClassDoc {
816 const DOC: &'static str;
818 const INTERFACE: bool;
820 }
821
822 #[diagnostic::on_unimplemented(
825 message = "`{Self}` needs `#[module]` on its struct too",
826 label = "a module's struct and its `impl` block both have `#[module]` (the struct's doc comment documents it)"
827 )]
828 pub trait ModuleDoc {
829 const DOC: &'static str;
831 }
832
833 pub struct Field<'a, T>(pub &'a T);
838
839 pub trait TraceField {
841 fn trace_field(&self, tracer: &mut Tracer<'_>);
843 }
844
845 impl<T: Trace> TraceField for &Field<'_, T> {
846 fn trace_field(&self, tracer: &mut Tracer<'_>) {
847 self.0.trace(tracer);
848 }
849 }
850
851 pub trait SkipField {
853 fn trace_field(&self, tracer: &mut Tracer<'_>);
855 }
856
857 impl<T> SkipField for Field<'_, T> {
858 fn trace_field(&self, _tracer: &mut Tracer<'_>) {}
859 }
860
861 pub fn type_id<T: 'static>() -> TypeId {
863 TypeId::of::<T>()
864 }
865
866 pub fn type_name<T: 'static>() -> &'static str {
868 std::any::type_name::<T>()
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use crate::{
875 element::{Registry, declarations},
876 prelude::*,
877 };
878
879 #[allow(dead_code)]
881 fn drop() {}
882
883 #[class]
885 struct Configured {
886 #[cfg(any())]
887 gone: NoSuchType,
888 kept: Option<Callback>,
889 }
890
891 #[class]
892 impl Configured {}
893
894 #[allow(dead_code)]
895 fn configured() -> Configured {
896 Configured { kept: None }
897 }
898
899 #[class]
901 struct Tally {
902 count: i64,
903 label: Option<String>,
904 }
905
906 #[class]
907 impl Tally {
908 pub(crate) fn new(start: Option<i64>) -> Self {
910 Tally {
911 count: start.unwrap_or(0),
912 label: None,
913 }
914 }
915
916 pub(crate) fn add(&mut self, by: i64, label: Option<String>) -> i64 {
918 let _ = label;
919 self.count += by;
920 self.count
921 }
922
923 #[getter]
925 pub(crate) fn count(&self) -> i64 {
926 self.count
927 }
928
929 #[setter]
930 pub(crate) fn set_count(&mut self, count: i64) {
931 self.count = count;
932 }
933
934 #[getter]
935 pub(crate) fn label(&self) -> Option<String> {
936 self.label.clone()
937 }
938
939 #[setter]
941 pub(crate) fn set_label(&mut self, label: Option<String>) {
942 self.label = label;
943 }
944
945 #[cfg(any())]
947 pub(crate) fn nowhere(&self) -> i64 {
948 0
949 }
950
951 pub(crate) fn parse(text: String) -> Result<Tally, String> {
953 text.parse()
954 .map(|count| Tally { count, label: None })
955 .map_err(|_| text)
956 }
957
958 pub(crate) fn reset(&mut self, to: Option<i64>, by: i64) {
959 self.count = to.unwrap_or(0) + by;
960 }
961
962 pub(crate) fn absorb(
963 &mut self,
964 other: &Tally,
965 token: Option<Instance<Token>>,
966 ) -> Instance<Token> {
967 self.count += other.count;
968 token.unwrap_or_else(|| Instance::new(Token))
969 }
970
971 pub(crate) async fn save(this: Instance<Self>, path: String) -> Result<(), String> {
973 let _ = (this, path);
974 Ok(())
975 }
976
977 pub(crate) async fn later(start: i64) -> Tally {
978 Tally {
979 count: start,
980 label: None,
981 }
982 }
983
984 pub(crate) fn sort_by(&mut self, compare: Callback<(String, String), f64>) {
986 let _ = compare;
987 }
988
989 pub(crate) fn on(
990 &mut self,
991 #[args(count)] listener: Option<Callback<i64>>,
992 done: Option<Callback>,
993 ) {
994 let _ = (listener, done);
995 }
996
997 #[allow(dead_code)]
999 fn bump(&mut self) {
1000 self.count += 1;
1001 }
1002
1003 #[allow(dead_code)]
1005 async fn private_later() -> i64 {
1006 0
1007 }
1008 }
1009
1010 #[class]
1012 struct Token;
1013
1014 #[class]
1015 impl Token {
1016 pub(crate) fn mint() -> Token {
1017 Token
1018 }
1019 }
1020
1021 #[test]
1022 fn classes_are_declared_from_their_definitions() {
1023 let mut registry = Registry::ui_set("test/ui");
1024 registry.class::<Tally>().class::<Token>();
1025 assert!(
1027 !<Tally as crate::element::Class>::DEF
1028 .members
1029 .iter()
1030 .any(|m| m.name == "bump" || m.name == "privateLater")
1031 );
1032 assert_eq!(
1033 declarations(®istry, &[]),
1034 r#"/** A tally kept in Rust. */
1035export declare class Tally {
1036 /** Starts at `start` (0 when left out). */
1037 constructor(start?: number | null);
1038 /** Adds `by`; the new count. */
1039 add(by: number, label?: string | null): number;
1040 /** The count. */
1041 get count(): number;
1042 set count(count: number);
1043 get label(): string | null;
1044 /** A setter's value is required, even an `Option`. */
1045 set label(label: string | null);
1046 /** A tally from `"12"`; throws on anything else. */
1047 static parse(text: string): Tally;
1048 reset(to: number | null, by: number): void;
1049 absorb(other: Tally, token?: Token | null): Token;
1050 /** Saves the count; resolves when it is written. */
1051 save(path: string): Promise<void>;
1052 static later(start: number): Promise<Tally>;
1053 /** Sorts with the app's comparison. */
1054 sortBy(compare: (a: string, b: string) => number): void;
1055 on(listener?: ((count: number) => void) | null, done?: (() => void) | null): void;
1056 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1057 dispose(): void;
1058 [Symbol.dispose](): void;
1059}
1060
1061/** Made by its members only. */
1062export declare class Token {
1063 /** Made by the class's members only. */
1064 private constructor();
1065 static mint(): Token;
1066 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1067 dispose(): void;
1068 [Symbol.dispose](): void;
1069}
1070
1071"#
1072 );
1073 }
1074
1075 #[module]
1077 struct Tools;
1078
1079 #[module]
1080 impl Tools {
1081 pub(crate) fn sum(values: Vec<f64>) -> f64 {
1083 values.iter().sum()
1084 }
1085
1086 pub(crate) fn shout(text: String) {
1087 let _ = text;
1088 }
1089
1090 pub(crate) fn measure(text: String, cx: &mut ModuleCx) -> usize {
1092 let _ = cx;
1093 text.len()
1094 }
1095
1096 pub(crate) fn pick(#[args(old_value, new_value)] choose: Callback<(f64, f64), f64>) -> f64 {
1098 choose.call((0.0, 1.0)).unwrap_or(0.0)
1099 }
1100
1101 pub(crate) fn beep(cx: &mut ModuleCx) {
1103 let _ = cx;
1104 }
1105
1106 pub(crate) fn check(cx: &mut ModuleCx) -> Result<(), String> {
1108 let _ = cx;
1109 Ok(())
1110 }
1111
1112 #[allow(clippy::unused_unit)]
1114 pub(crate) fn hum(cx: &mut ModuleCx) -> () {
1115 let _ = cx;
1116 }
1117
1118 pub(crate) async fn settle() {}
1120
1121 pub(crate) async fn later(listener: Callback<i64, String>) -> Result<String, String> {
1122 listener.call_async(1).await
1123 }
1124
1125 #[cfg(any())]
1127 pub(crate) fn nowhere() {}
1128
1129 #[allow(dead_code)]
1131 fn helper(text: String) -> String {
1132 text
1133 }
1134 }
1135
1136 #[test]
1137 fn functions_without_a_context_return_their_values() {
1138 let mut registry = Registry::ui_set("test/ui");
1139 registry.module::<Tools>();
1140 assert!(
1141 !<Tools as crate::element::Module>::FUNCTIONS
1142 .iter()
1143 .any(|f| f.name == "helper")
1144 );
1145 assert_eq!(
1146 declarations(®istry, &[]),
1147 r#"/** Functions of the three kinds. */
1148export interface ToolsModule {
1149 /** The sum, at once. */
1150 sum(values: (number)[]): number;
1151 shout(text: string): void;
1152 /** A promise of the length. */
1153 measure(text: string): Promise<number>;
1154 /** Picks with the app's choice, its arguments named. */
1155 pick(choose: (oldValue: number, newValue: number) => number): number;
1156 /** An op returning nothing: a plain call. */
1157 beep(): void;
1158 /** An op that may fail: a promise, rejected with an `Err`. */
1159 check(): Promise<void>;
1160 /** `-> ()` written out: the same as no return type. */
1161 hum(): void;
1162 /** A task returning nothing. */
1163 settle(): Promise<void>;
1164 later(listener: (value: number) => string): Promise<string>;
1165}
1166
1167/** Functions of the three kinds. */
1168export declare const Tools: ToolsModule;
1169
1170"#
1171 );
1172 }
1173
1174 #[test]
1177 fn registering_a_class_again_does_nothing() {
1178 let mut r = Registry::ui_set("test/ui");
1179 r.class::<Tally>().class::<Tally>();
1180 let tallies = r.class_specs().iter().filter(|c| c.name == "Tally").count();
1181 assert_eq!(tallies, 1);
1182 }
1183
1184 mod view {
1186 use crate::prelude::*;
1187
1188 pub(super) struct Tally;
1189
1190 impl Component for Tally {
1191 type Props = ();
1192 type Event = NoEvent;
1193
1194 fn view(_: (), _: Scope<NoEvent>) -> impl IntoElement {
1195 view()
1196 }
1197 }
1198 }
1199
1200 #[test]
1202 fn a_class_and_a_component_share_no_name() {
1203 let class_first = std::panic::catch_unwind(|| {
1204 Registry::ui_set("test/ui")
1205 .class::<Tally>()
1206 .register::<view::Tally>();
1207 });
1208 assert!(class_first.is_err(), "a component after a class");
1209 let component_first = std::panic::catch_unwind(|| {
1210 Registry::ui_set("test/ui")
1211 .register::<view::Tally>()
1212 .class::<Tally>();
1213 });
1214 assert!(component_first.is_err(), "a class after a component");
1215 }
1216}