1#[cfg(test)]
4const FIXED_LOCATION: &Location = Location::caller();
5
6use crate::{
7 description,
8 prelude::DependencyMap,
9 send::{BoxFuture, MaybeSend, MaybeSync},
10 HandlerDescription,
11};
12
13use std::{
14 any::TypeId,
15 collections::{BTreeMap, BTreeSet},
16 fmt::Write,
17 future::Future,
18 hash::{Hash, Hasher},
19 ops::ControlFlow,
20 panic::Location,
21 sync::Arc,
22};
23
24use colored::Colorize;
25
26pub struct Handler<'a, Output, Descr = description::Unspecified> {
67 data: Arc<HandlerData<Descr, DynFn<'a, Output>>>,
68}
69
70struct HandlerData<Descr, F: ?Sized> {
71 description: Descr,
72 sig: HandlerSignature,
73 f: F,
74}
75
76#[derive(Clone, Debug, Eq, PartialEq)]
81pub enum HandlerSignature {
82 Entry,
84 Other {
86 obligations: BTreeMap<Type, &'static Location<'static>>,
89
90 guaranteed_outcomes: BTreeSet<Type>,
94
95 conditional_outcomes: BTreeSet<Type>,
99
100 continues: bool,
102 },
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
112pub struct Type {
113 pub name: &'static str,
115
116 pub id: TypeId,
118}
119
120impl Hash for Type {
121 fn hash<H: Hasher>(&self, state: &mut H) {
123 self.id.hash(state);
124 }
125}
126
127#[cfg(not(target_arch = "wasm32"))]
128type DynFn<'a, Output> =
129 dyn Fn(DependencyMap, Cont<'a, Output>) -> HandlerResult<'a, Output> + Send + Sync + 'a;
130#[cfg(target_arch = "wasm32")]
131type DynFn<'a, Output> = dyn Fn(DependencyMap, Cont<'a, Output>) -> HandlerResult<'a, Output> + 'a;
132
133pub type Cont<'a, Output> = ContInner<'a, Output>;
135#[cfg(not(target_arch = "wasm32"))]
136type ContInner<'a, Output> =
137 Box<dyn FnOnce(DependencyMap) -> HandlerResult<'a, Output> + Send + Sync + 'a>;
138#[cfg(target_arch = "wasm32")]
139type ContInner<'a, Output> = Box<dyn FnOnce(DependencyMap) -> HandlerResult<'a, Output> + 'a>;
140
141pub type HandlerResult<'a, Output> = BoxFuture<'a, ControlFlow<Output, DependencyMap>>;
143
144impl<Output, Descr> Clone for Handler<'_, Output, Descr> {
147 fn clone(&self) -> Self {
148 Handler { data: Arc::clone(&self.data) }
149 }
150}
151
152impl<'a, Output, Descr> Handler<'a, Output, Descr>
153where
154 Output: 'a,
155 Descr: HandlerDescription,
156{
157 #[must_use]
189 #[track_caller]
190 pub fn chain(self, next: Self) -> Self {
191 let required_update_kinds_set = self.description().merge_chain(next.description());
192
193 let new_sig = match (&self.data.sig, &next.data.sig) {
194 (_, HandlerSignature::Entry) => {
195 panic!("Ill-typed handler chain: the second handler cannot be an entry")
196 }
197 (HandlerSignature::Entry, other_sig @ HandlerSignature::Other { .. }) => {
198 other_sig.clone()
199 }
200 (
201 HandlerSignature::Other {
202 obligations: self_obligations,
203 guaranteed_outcomes: self_guaranteed_outcomes,
204 conditional_outcomes: self_conditional_outcomes,
205 continues: self_continues,
206 },
207 HandlerSignature::Other {
208 obligations: next_obligations,
209 guaranteed_outcomes: next_guaranteed_outcomes,
210 conditional_outcomes: next_conditional_outcomes,
211 continues: next_continues,
212 },
213 ) => {
214 if !self_continues {
215 panic!(
216 "Dead code detected: since the first handler aborts execution, the second \
217 handler will never be called."
218 );
219 }
220
221 Self::infer_chain(
222 self_obligations,
223 self_guaranteed_outcomes,
224 self_conditional_outcomes,
225 next_obligations,
226 next_guaranteed_outcomes,
227 next_conditional_outcomes,
228 *next_continues,
229 )
230 }
231 };
232
233 from_fn_with_description(
234 required_update_kinds_set,
235 move |event, cont| {
236 let this = self.clone();
237 let next = next.clone();
238
239 this.execute(event, |event| next.execute(event, cont))
240 },
241 new_sig,
242 )
243 }
244
245 fn infer_chain(
246 self_obligations: &BTreeMap<Type, &'static Location<'static>>,
247 self_guaranteed_outcomes: &BTreeSet<Type>,
248 self_conditional_outcomes: &BTreeSet<Type>,
249 next_obligations: &BTreeMap<Type, &'static Location<'static>>,
250 next_guaranteed_outcomes: &BTreeSet<Type>,
251 next_conditional_outcomes: &BTreeSet<Type>,
252 next_continues: bool,
253 ) -> HandlerSignature {
254 HandlerSignature::Other {
255 obligations: next_obligations
261 .clone()
262 .into_iter()
263 .filter(|(ty, _location)| {
264 !self_guaranteed_outcomes.contains(ty)
265 && !self_conditional_outcomes.contains(ty)
266 })
267 .chain(self_obligations.clone())
268 .collect(),
269
270 guaranteed_outcomes: self_guaranteed_outcomes
275 .union(next_guaranteed_outcomes)
276 .cloned()
277 .collect(),
278
279 conditional_outcomes: self_conditional_outcomes
283 .union(next_conditional_outcomes)
284 .cloned()
285 .collect(),
286
287 continues: next_continues,
288 }
289 }
290
291 #[must_use]
332 #[track_caller]
333 pub fn branch(self, next: Self) -> Self
334 where
335 Output: MaybeSend,
336 {
337 let required_update_kinds_set = self.description().merge_branch(next.description());
338
339 let new_sig = match (&self.data.sig, &next.data.sig) {
340 (_, HandlerSignature::Entry) => {
341 panic!("Ill-typed handler branch: the second handler cannot be an entry")
342 }
343 (HandlerSignature::Entry, other_sig @ HandlerSignature::Other { .. }) => {
344 other_sig.clone()
345 }
346 (
347 HandlerSignature::Other {
348 obligations: self_obligations,
349 guaranteed_outcomes: self_guaranteed_outcomes,
350 conditional_outcomes: self_conditional_outcomes,
351 continues: _self_continues,
352 },
353 HandlerSignature::Other {
354 obligations: next_obligations,
355 guaranteed_outcomes: _next_guaranteed_outcomes,
356 conditional_outcomes: next_conditional_outcomes,
357 continues: _next_continues,
358 },
359 ) => Self::infer_branch(
360 self_obligations,
361 self_guaranteed_outcomes,
362 self_conditional_outcomes,
363 next_obligations,
364 next_conditional_outcomes,
365 ),
366 };
367
368 from_fn_with_description(
369 required_update_kinds_set,
370 move |event, cont| {
371 let this = self.clone();
372 let next = next.clone();
373
374 this.execute(event, |event| async move {
375 match next.dispatch(event).await {
376 ControlFlow::Continue(event) => cont(event).await,
377 done => done,
378 }
379 })
380 },
381 new_sig,
382 )
383 }
384
385 fn infer_branch(
386 self_obligations: &BTreeMap<Type, &'static Location<'static>>,
387 self_guaranteed_outcomes: &BTreeSet<Type>,
388 self_conditional_outcomes: &BTreeSet<Type>,
389 next_obligations: &BTreeMap<Type, &'static Location<'static>>,
390 next_conditional_outcomes: &BTreeSet<Type>,
391 ) -> HandlerSignature {
392 HandlerSignature::Other {
393 obligations: next_obligations
397 .clone()
398 .into_iter()
399 .filter(|(ty, _location)| !self_guaranteed_outcomes.contains(ty))
400 .chain(self_obligations.clone())
401 .collect(),
402
403 guaranteed_outcomes: self_guaranteed_outcomes.clone(),
406
407 conditional_outcomes: self_conditional_outcomes
408 .union(next_conditional_outcomes)
409 .cloned()
410 .collect(),
411
412 continues: true,
413 }
414 }
415
416 pub async fn execute<Cont, ContFut>(
442 self,
443 input: DependencyMap,
444 cont: Cont,
445 ) -> ControlFlow<Output, DependencyMap>
446 where
447 Cont: FnOnce(DependencyMap) -> ContFut,
448 Cont: MaybeSend + MaybeSync + 'a,
449 ContFut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
450 {
451 (self.data.f)(input, Box::new(|event| Box::pin(cont(event)))).await
452 }
453
454 pub async fn dispatch(&self, input: DependencyMap) -> ControlFlow<Output, DependencyMap> {
464 self.clone().execute(input, |event| async move { ControlFlow::Continue(event) }).await
465 }
466
467 pub fn description(&self) -> &Descr {
469 &self.data.description
470 }
471
472 pub fn sig(&self) -> &HandlerSignature {
474 &self.data.sig
475 }
476}
477
478fn print_types<'a>(
479 types: impl IntoIterator<Item = &'a Type>,
480 f: impl Fn(&Type) -> String,
481) -> String {
482 let mut res = String::new();
483 let mut types = types.into_iter();
484
485 if let Some(ty) = types.next() {
486 write!(res, "{}", f(ty)).unwrap();
487 }
488 for ty in types {
489 write!(res, "\n {}", f(ty)).unwrap();
490 }
491
492 res
493}
494
495impl Type {
496 #[must_use]
498 pub fn of<T>() -> Self
499 where
500 T: 'static,
501 {
502 Self { id: TypeId::of::<T>(), name: std::any::type_name::<T>() }
503 }
504}
505
506#[must_use]
515pub fn from_fn<'a, F, Fut, Output, Descr>(f: F, sig: HandlerSignature) -> Handler<'a, Output, Descr>
516where
517 F: Fn(DependencyMap, Cont<'a, Output>) -> Fut,
518 F: MaybeSend + MaybeSync + 'a,
519 Fut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
520 Descr: HandlerDescription,
521{
522 from_fn_with_description(Descr::user_defined(), f, sig)
523}
524
525#[must_use]
527pub fn from_fn_with_description<'a, F, Fut, Output, Descr>(
528 description: Descr,
529 f: F,
530 sig: HandlerSignature,
531) -> Handler<'a, Output, Descr>
532where
533 F: Fn(DependencyMap, Cont<'a, Output>) -> Fut,
534 F: MaybeSend + MaybeSync + 'a,
535 Fut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
536{
537 Handler {
538 data: Arc::new(HandlerData {
539 f: move |event, cont| Box::pin(f(event, cont)) as HandlerResult<_>,
540 description,
541 sig,
542 }),
543 }
544}
545
546#[must_use]
555#[track_caller]
556pub fn entry<'a, Output, Descr>() -> Handler<'a, Output, Descr>
557where
558 Output: 'a,
559 Descr: HandlerDescription,
560{
561 from_fn_with_description(Descr::entry(), |event, cont| cont(event), HandlerSignature::Entry)
562}
563
564pub fn type_check(sig: &HandlerSignature, container: &DependencyMap, assumptions: &[Type]) {
600 match sig {
601 HandlerSignature::Entry => {}
602 HandlerSignature::Other {
603 obligations,
604 guaranteed_outcomes: _,
605 conditional_outcomes: _,
606 continues: _,
607 } => {
608 let container_types = container
609 .map
610 .iter()
611 .map(|(type_id, dep)| Type { id: *type_id, name: dep.type_name })
612 .chain(assumptions.iter().cloned())
613 .collect::<BTreeSet<_>>();
614
615 let handler_accepts_msg = "Your handler accepts the following types:".to_owned();
616 let provided_types_msg = "But only the following values were given to it:".to_owned();
617 let missing_types_msg = "The missing values are:".to_owned();
618 let note_msg = "Make sure all the required values are provided to the handler. For more information, visit <https://docs.rs/dptree/latest/dptree>.".to_owned();
619
620 if obligations.iter().any(|(ty, _location)| !container_types.contains(ty)) {
621 panic!(
622 "{}\n {}\n{}\n {}\n{}\n {}\n\n{}\n",
623 if cfg!(test) {
624 handler_accepts_msg
625 } else {
626 handler_accepts_msg.red().bold().to_string()
627 },
628 print_types(obligations.keys(), |ty| format!("`{}`", ty.name)),
629 if cfg!(test) {
630 provided_types_msg
631 } else {
632 provided_types_msg.red().bold().to_string()
633 },
634 print_types(&container_types, |ty| format!("`{}`", ty.name)),
635 if cfg!(test) {
636 missing_types_msg
637 } else {
638 missing_types_msg.red().bold().to_string()
639 },
640 print_types(
641 obligations.keys().filter(|ty| !container_types.contains(ty)),
642 |ty| { format!("`{}` from {}", ty.name, obligations[ty]) },
643 ),
644 note_msg,
645 );
646 }
647 }
648 }
649}
650
651#[cfg(test)]
652pub(crate) fn help_inference<Output>(h: Handler<Output>) -> Handler<Output> {
653 h
654}
655
656#[cfg(test)]
657mod tests {
658
659 use super::*;
660
661 use crate::{
662 deps, description, filter_map, filter_map_with_description,
663 handler::{endpoint, filter, filter_async},
664 };
665
666 use std::{any::Any, collections::HashSet, iter::FromIterator};
667
668 use maplit::{btreemap, btreeset, hashset};
669
670 crate::cross_test! {
671 async fn test_from_fn_break() {
672 let input = 123;
673 let output = "ABC";
674
675 let input_types = [Type::of::<i32>()];
676 let location = Location::caller();
677
678 let result = help_inference(from_fn(
679 |event, _cont: Cont<&'static str>| async move {
680 assert_eq!(event, deps![input]);
681 ControlFlow::Break(output)
682 },
683 HandlerSignature::Other {
684 obligations: BTreeMap::from_iter(
685 input_types.iter().cloned().map(|ty| (ty, location)),
686 ),
687 guaranteed_outcomes: btreeset! {},
688 conditional_outcomes: btreeset! {},
689 continues: false,
690 },
691 ))
692 .dispatch(deps![input])
693 .await;
694
695 assert!(result == ControlFlow::Break(output));
696 }
697
698 async fn test_from_fn_continue() {
699 let input = 123;
700 type Output = &'static str;
701
702 let input_types = [Type::of::<i32>()];
703 let location = Location::caller();
704
705 let result = help_inference(from_fn(
706 |event, _cont: Cont<&'static str>| async move {
707 assert_eq!(event, deps![input]);
708 ControlFlow::<Output, _>::Continue(event)
709 },
710 HandlerSignature::Other {
711 obligations: BTreeMap::from_iter(
712 input_types.iter().cloned().map(|ty| (ty, location)),
713 ),
714 guaranteed_outcomes: btreeset! {Type::of::<i32>()},
715 conditional_outcomes: btreeset! {},
716 continues: true,
717 },
718 ))
719 .dispatch(deps![input])
720 .await;
721
722 assert!(result == ControlFlow::Continue(deps![input]));
723 }
724
725 async fn test_entry() {
726 let input = 123;
727 type Output = &'static str;
728
729 let result = help_inference(entry::<Output, _>()).dispatch(deps![input]).await;
730
731 assert!(result == ControlFlow::Continue(deps![input]));
732 }
733
734 async fn test_execute() {
735 let input = 123;
736 let output = "ABC";
737
738 let input_types = [Type::of::<i32>()];
739 let location = Location::caller();
740
741 let result = help_inference(from_fn(
742 |event, cont| {
743 assert!(event == deps![input]);
744 cont(event)
745 },
746 HandlerSignature::Other {
747 obligations: BTreeMap::from_iter(
748 input_types.iter().cloned().map(|ty| (ty, location)),
749 ),
750 guaranteed_outcomes: btreeset! {Type::of::<i32>()},
751 conditional_outcomes: btreeset! {},
752 continues: true,
753 },
754 ))
755 .execute(deps![input], |event| async move {
756 assert!(event == deps![input]);
757 ControlFlow::Break(output)
758 })
759 .await;
760
761 assert!(result == ControlFlow::Break(output));
762 }
763
764 async fn test_deeply_nested_tree() {
765 #[derive(Debug, PartialEq)]
766 enum Output {
767 LT,
768 MinusOne,
769 Zero,
770 One,
771 GT,
772 }
773
774 let negative_handler = filter(|num: i32| num < 0)
775 .branch(
776 filter_async(|num: i32| async move { num == -1 })
777 .endpoint(|| async move { Output::MinusOne }),
778 )
779 .branch(endpoint(|| async move { Output::LT }));
780
781 let zero_handler = filter_async(|num: i32| async move { num == 0 })
782 .endpoint(|| async move { Output::Zero });
783
784 let positive_handler = filter_async(|num: i32| async move { num > 0 })
785 .branch(
786 filter_async(|num: i32| async move { num == 1 })
787 .endpoint(|| async move { Output::One }),
788 )
789 .branch(endpoint(|| async move { Output::GT }));
790
791 let dispatcher = help_inference(entry())
792 .branch(negative_handler)
793 .branch(zero_handler)
794 .branch(positive_handler);
795
796 assert_eq!(dispatcher.dispatch(deps![2]).await, ControlFlow::Break(Output::GT));
797 assert_eq!(dispatcher.dispatch(deps![1]).await, ControlFlow::Break(Output::One));
798 assert_eq!(dispatcher.dispatch(deps![0]).await, ControlFlow::Break(Output::Zero));
799 assert_eq!(dispatcher.dispatch(deps![-1]).await, ControlFlow::Break(Output::MinusOne));
800 assert_eq!(dispatcher.dispatch(deps![-2]).await, ControlFlow::Break(Output::LT));
801 }
802
803 async fn allowed_updates() {
804 use crate::description::{EventKind, InterestSet};
805 use UpdateKind::*;
806
807 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
808 enum UpdateKind {
809 A,
810 B,
811 C,
812 }
813
814 impl EventKind for UpdateKind {
815 fn full_set() -> HashSet<Self> {
816 hashset! { A, B, C }
817 }
818
819 fn empty_set() -> HashSet<Self> {
820 hashset! {}
821 }
822 }
823
824 #[derive(Clone)]
825 #[allow(dead_code)]
826 enum Update {
827 A(i32),
828 B(u8),
829 C(u64),
830 }
831
832 fn filter_a<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
833 where
834 Out: Send + Sync + 'static,
835 {
836 filter_map_with_description(
837 InterestSet::new_filter(hashset! { A }),
838 |update: Update| match update {
839 Update::A(x) => Some(x),
840 _ => None,
841 },
842 )
843 }
844
845 fn filter_b<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
846 where
847 Out: Send + Sync + 'static,
848 {
849 filter_map_with_description(
850 InterestSet::new_filter(hashset! { B }),
851 |update: Update| match update {
852 Update::B(x) => Some(x),
853 _ => None,
854 },
855 )
856 }
857
858 fn filter_c<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
859 where
860 Out: Send + Sync + 'static,
861 {
862 filter_map_with_description(
863 InterestSet::new_filter(hashset! { C }),
864 |update: Update| match update {
865 Update::B(x) => Some(x),
866 _ => None,
867 },
868 )
869 }
870
871 fn user_defined_filter<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
873 where
874 Out: Send + Sync + 'static,
875 {
876 filter_map(|update: Update| match update {
877 Update::B(x) => Some(x),
878 _ => None,
879 })
880 }
881
882 #[track_caller]
883 fn assert(
884 handler: Handler<'static, (), description::InterestSet<UpdateKind>>,
885 allowed: HashSet<UpdateKind>,
886 ) {
887 assert_eq!(handler.description().observed, allowed);
888 }
889
890 assert(filter_a(), hashset! {});
892 assert(entry().chain(filter_b()), hashset! {});
893 assert(filter_a().chain(filter_b()), hashset! {});
894 assert(filter_a().branch(filter_b()), hashset! {});
895 assert(filter_a().branch(filter_b()).branch(filter_c().chain(filter_c())), hashset! {});
896
897 assert(filter_a().chain(filter(|| true)), hashset! { A });
899 assert(user_defined_filter().chain(filter_a()), hashset! { A, B, C });
900 assert(filter_a().chain(user_defined_filter()), hashset! { A });
901 assert(
902 entry().branch(filter_a()).branch(filter_b()).chain(user_defined_filter()),
903 hashset! { A, B, C },
904 );
905 assert(
906 entry()
907 .branch(filter_a().endpoint(|| async {}))
908 .branch(filter_b().endpoint(|| async {})),
909 hashset! { A, B },
910 );
911 assert(user_defined_filter(), hashset! { A, B, C });
912 assert(user_defined_filter().branch(filter_a()), hashset! { A, B, C });
913
914 assert(entry(), hashset! {});
916 assert(entry().chain(filter_a().endpoint(|| async {})), hashset! { A });
917 assert(entry().branch(filter_a()), hashset! {});
918
919 assert(filter_a().chain(filter_b()).endpoint(|| async {}), hashset! {});
921 }
922
923 async fn type_check_success() {
924 #[derive(Clone)]
925 struct A;
926 #[derive(Clone)]
927 struct B;
928 #[derive(Clone)]
929 struct C;
930
931 macro_rules! test {
932 ($($key:ty),*) => {
933 type_check(
934 &HandlerSignature::Other {
935 obligations: btreemap! {
936 $(Type::of::<$key>() => Location::caller(),)*
937 },
938 guaranteed_outcomes: btreeset! {},
939 conditional_outcomes: btreeset! {},
940 continues: true,
941 },
942 &deps![A, B, C],
943 &[],
944 );
945 };
946 }
947
948 type_check(&HandlerSignature::Entry, &deps![], &[]);
950
951 test!(A, B, C);
953 test!(A, B);
954 test!(A, C);
955 test!(B, C);
956 test!(A);
957 test!(B);
958 test!(C);
959 }
960
961 #[should_panic(expected = "Your handler accepts the following types:
962 `dptree::handler::core::tests::type_check_panic::A`
963 `dptree::handler::core::tests::type_check_panic::B`
964 `dptree::handler::core::tests::type_check_panic::C`
965But only the following values were given to it:
966 `dptree::handler::core::tests::type_check_panic::A`
967 `dptree::handler::core::tests::type_check_panic::B`
968The missing values are:
969 `dptree::handler::core::tests::type_check_panic::C` from src/handler/core.rs:4:35
970
971Make sure all the required values are provided to the handler. For more information, visit <https://docs.rs/dptree/latest/dptree>.
972")]
973 fn type_check_panic() {
974 #[derive(Clone)]
975 struct A;
976 #[derive(Clone)]
977 struct B;
978 #[derive(Clone)]
979 struct C;
980
981 type_check(
982 &HandlerSignature::Other {
983 obligations: btreemap! {
984 Type::of::<A>() => Location::caller(),
985 Type::of::<B>() => Location::caller(),
986 Type::of::<C>() => FIXED_LOCATION,
987 },
988 guaranteed_outcomes: btreeset! {},
989 conditional_outcomes: btreeset! {},
990 continues: true,
991 },
992 &deps![A, B],
994 &[],
995 );
996 }
997
998 fn type_eq_ord_consistent() {
999 #[derive(Clone)]
1000 struct A;
1001
1002 let ta1 = Type { id: A.type_id(), name: "A1" };
1003 let ta2 = Type { id: A.type_id(), name: "A2" };
1004
1005 assert!(!(ta1 == ta2));
1006 assert!(ta1 < ta2);
1007 assert!(!(ta1 > ta2));
1008 }
1009
1010 fn type_btreeset_not_contains_duplicate_name() {
1011 #[derive(Clone)]
1012 struct A;
1013 #[derive(Clone)]
1014 struct B;
1015
1016 let ta = Type { id: A.type_id(), name: "DuplicateName" };
1017 let tb = Type { id: B.type_id(), name: "DuplicateName" };
1018 let set = btreeset! {ta};
1019
1020 assert!(ta != tb);
1021 assert!(!set.contains(&tb));
1022 }
1023
1024 async fn type_infer_check_chained_combinators() {
1025 #[derive(Clone)]
1026 struct A;
1027 #[derive(Clone)]
1028 struct B;
1029 #[derive(Clone)]
1030 struct C;
1031 #[derive(Clone)]
1032 struct D;
1033 #[derive(Clone)]
1034 struct E;
1035 #[derive(Clone)]
1036 struct F;
1037 #[derive(Clone)]
1038 struct G;
1039 #[derive(Clone, Debug, Eq, PartialEq)]
1040 struct H;
1041
1042 let h: Handler<H> = entry()
1043 .map(|_: A| B)
1044 .inspect(
1045 |_: B,
1048 _: E| (),
1050 )
1051 .filter_map(|_: C| Some(D))
1052 .filter(
1053 |_: D,
1054 _: F| true,
1055 )
1056 .endpoint(
1057 |_: B, _: D, _: G| async { H },
1059 );
1060
1061 let input_types =
1062 [Type::of::<A>(), Type::of::<C>(), Type::of::<E>(), Type::of::<F>(), Type::of::<G>()];
1063 let outcomes = btreeset! {Type::of::<B>(), Type::of::<D>()};
1064
1065 if let HandlerSignature::Other {
1066 obligations: actual_obligations,
1067 guaranteed_outcomes: actual_guaranteed_outcomes,
1068 conditional_outcomes: actual_conditional_outcomes,
1069 continues: _continues,
1070 } = h.sig()
1071 {
1072 assert_eq!(
1073 actual_obligations.keys().collect::<Vec<_>>(),
1074 input_types.iter().collect::<Vec<_>>()
1075 );
1076 let all_outcomes = actual_guaranteed_outcomes
1077 .union(actual_conditional_outcomes)
1078 .cloned()
1079 .collect::<BTreeSet<_>>();
1080 assert_eq!(all_outcomes, outcomes);
1081 } else {
1082 panic!("Expected `HandlerSignature::Other`");
1083 }
1084
1085 let deps = deps![A, C, E, F, G];
1086
1087 type_check(h.sig(), &deps, &[]);
1088
1089 assert_eq!(h.dispatch(deps).await, ControlFlow::Break(H));
1091 }
1092
1093 async fn type_infer_check_branched_combinators() {
1094 #[derive(Clone)]
1095 struct A;
1096 #[derive(Clone)]
1097 struct B;
1098 #[derive(Clone)]
1099 struct C;
1100 #[derive(Clone)]
1101 struct D;
1102 #[derive(Clone)]
1103 struct E;
1104 #[derive(Clone, Debug, Eq, PartialEq)]
1105 struct F;
1106
1107 let h: Handler<F> = entry()
1108 .branch(
1109 crate::inspect(|_: A| ()).map(|| B).map(|| C).map(|| D).endpoint(|| async { F }),
1110 )
1111 .branch(crate::inspect(|_: E| ()).map(|| B).map(|| D).endpoint(|| async { F }));
1112
1113 let input_types = btreeset! {Type::of::<A>(), Type::of::<E>()};
1115 let output_types = btreeset! {Type::of::<B>(), Type::of::<C>(), Type::of::<D>()};
1117
1118 if let HandlerSignature::Other {
1119 obligations: actual_obligations,
1120 guaranteed_outcomes: actual_guaranteed_outcomes,
1121 conditional_outcomes: actual_conditional_outcomes,
1122 continues: _continues,
1123 } = h.sig()
1124 {
1125 assert_eq!(
1126 actual_obligations.keys().collect::<Vec<_>>(),
1127 input_types.iter().collect::<Vec<_>>()
1128 );
1129 let all_outcomes = actual_guaranteed_outcomes
1130 .union(actual_conditional_outcomes)
1131 .cloned()
1132 .collect::<BTreeSet<_>>();
1133 assert_eq!(all_outcomes, output_types);
1134 } else {
1135 panic!("Expected `HandlerSignature::Other`");
1136 }
1137
1138 let deps = deps![A, E];
1139
1140 type_check(h.sig(), &deps, &[]);
1141
1142 assert_eq!(h.dispatch(deps).await, ControlFlow::Break(F));
1144 }
1145
1146 async fn obligations_priority() {
1147 #[derive(Clone)]
1148 struct A;
1149 #[derive(Clone)]
1150 struct B;
1151 #[derive(Clone, Debug, Eq, PartialEq)]
1152 struct C;
1153
1154 fn test<T: 'static>(h: Handler<C>, column: u32) {
1155 if let HandlerSignature::Other {
1156 obligations,
1157 guaranteed_outcomes: _,
1158 conditional_outcomes: _,
1159 continues: _,
1160 } = h.sig()
1161 {
1162 let (_ty, &location) = obligations
1163 .iter()
1164 .find(|(ty, _location)| ty.id == TypeId::of::<T>())
1165 .expect("Missing obligation");
1166 assert_eq!(location.column(), column);
1167 } else {
1168 panic!("Expected `HandlerSignature::Other`");
1169 }
1170 }
1171
1172 #[rustfmt::skip]
1173 let h: Handler<C> = entry().map(|_: A| ()).endpoint(|_: A, _: B| async { C });
1174 test::<A>(h, 41);
1175
1176 #[rustfmt::skip]
1177 let h: Handler<C> =
1178 entry().branch(crate::map(|_: A| { C })).branch(endpoint(|_: A, _: B| async { C }));
1179 test::<A>(h, 32);
1180 }
1181
1182 #[should_panic(expected = "Ill-typed handler chain: the second handler cannot be an entry")]
1183 fn chain_entry() {
1184 let _: Handler<()> = entry().chain(entry());
1185 }
1186
1187 #[should_panic(expected = "Ill-typed handler branch: the second handler cannot be an entry")]
1188 fn branch_entry() {
1189 let _: Handler<()> = entry().branch(entry());
1190 }
1191
1192 async fn chain_branch_type_check() {
1193 #[derive(Clone)]
1194 struct A;
1195
1196 let handler: Handler<()> =
1197 entry().chain(crate::map(|| A)).branch(endpoint(|_: A| async {}));
1198
1199 let _no_panic_here: ControlFlow<(), _> = handler.dispatch(deps![]).await;
1200
1201 type_check(handler.sig(), &deps![], &[]);
1202 }
1203
1204 async fn guaranteed_outcomes_chain_success() {
1205 #[derive(Clone)]
1206 struct A;
1207 #[derive(Clone)]
1208 struct B;
1209
1210 let handler: Handler<()> = entry().map(|| A).map(|_: A| B).endpoint(|_: B| async {});
1211
1212 let result = handler.dispatch(deps![]).await;
1213 assert_eq!(result, ControlFlow::Break(()));
1214
1215 type_check(handler.sig(), &deps![], &[]);
1216 }
1217
1218 async fn conditional_outcomes_chain_success() {
1219 #[derive(Clone)]
1220 struct A;
1221
1222 let handler: Handler<()> = entry().filter_map(|| Some(A)).endpoint(|_: A| async {});
1223
1224 let result = handler.dispatch(deps![]).await;
1225 assert_eq!(result, ControlFlow::Break(()));
1226
1227 type_check(handler.sig(), &deps![], &[]);
1228 }
1229
1230 async fn guaranteed_outcomes_branch_success() {
1231 #[derive(Clone)]
1232 struct A;
1233
1234 let producer = entry().map(|| A);
1235
1236 let handler: Handler<()> = producer.branch(endpoint(|_: A| async {}));
1238
1239 let result = handler.dispatch(deps![]).await;
1240 assert_eq!(result, ControlFlow::Break(()));
1241
1242 type_check(handler.sig(), &deps![], &[]);
1243 }
1244
1245 async fn mixed_outcomes_chain() {
1246 #[derive(Clone)]
1247 struct A;
1248 #[derive(Clone)]
1249 struct B;
1250 #[derive(Clone)]
1251 struct C;
1252
1253 let handler: Handler<()> = entry()
1254 .map(|| A) .filter_map(|_: A| Some(B)) .map(|_: B| C) .endpoint(|_: C| async {}); let result = handler.dispatch(deps![]).await;
1260 assert_eq!(result, ControlFlow::Break(()));
1261
1262 type_check(handler.sig(), &deps![], &[]);
1263 }
1264
1265 async fn branch_with_guaranteed_continuation() {
1266 #[derive(Clone)]
1267 struct A;
1268
1269 let first_branch = entry().map(|| A).inspect(|_: A| ()); let handler: Handler<()> = first_branch.branch(endpoint(|_: A| async {}));
1275
1276 let result = handler.dispatch(deps![]).await;
1277 assert_eq!(result, ControlFlow::Break(()));
1278
1279 type_check(handler.sig(), &deps![], &[]);
1280 }
1281
1282 #[should_panic(expected = "Your handler accepts the following types:")]
1283 async fn deeply_nested_conditional_failure() {
1284 #[derive(Clone)]
1285 struct A;
1286 #[derive(Clone)]
1287 struct B;
1288
1289 let handler: Handler<()> = entry()
1291 .branch(
1292 entry()
1293 .branch(crate::filter_map(|| Some(A)).endpoint(|| async {}))
1294 .branch(crate::filter_map(|_: A| Some(B)).endpoint(|| async {})),
1295 )
1296 .branch(endpoint(|_: B| async {})); type_check(handler.sig(), &deps![], &[]);
1299 }
1300
1301 #[should_panic(expected = "Dead code detected: since the first handler aborts execution, the \
1302 second handler will never be called.")]
1303 fn chain_endpoint_with_handler() {
1304 let _: Handler<()> = endpoint(|| async {}).endpoint(|| async {});
1305 }
1306
1307 #[should_panic(expected = "Dead code detected: since the first handler aborts execution, the \
1308 second handler will never be called.")]
1309 fn chain_endpoint_with_filter() {
1310 let _: Handler<()> = endpoint(|| async {}).filter(|_: i32| true);
1311 }
1312
1313 #[should_panic(expected = "Dead code detected: since the first handler aborts execution, the \
1314 second handler will never be called.")]
1315 fn chain_endpoint_with_map() {
1316 let _: Handler<()> = endpoint(|| async {}).map(|| 42);
1317 }
1318
1319 #[should_panic(expected = "Dead code detected: since the first handler aborts execution, the \
1320 second handler will never be called.")]
1321 fn chain_complex_endpoint_dead_code() {
1322 let _: Handler<()> = entry()
1323 .chain(filter(|x: i32| x > 0))
1324 .chain(endpoint(|| async {}))
1325 .chain(crate::map(|| "Unreachable"));
1326 }
1327 }
1328}