1use std::collections::HashSet;
37use std::sync::Arc;
38use std::time::{Duration, Instant};
39
40use unitype_core::check::CheckedWorkspace;
41use unitype_core::ir::Type;
42use unitype_core::value::Value;
43use unitype_core::{Ident, QualifiedName};
44
45use crate::environment::Reach;
46use crate::error::{DispatchError, ExecError};
47use crate::implementation::{ImplId, Implementation};
48use crate::interpret::{BoxFuture, Calls, eval_signature};
49use crate::registry::{INTRINSIC_ENTRY, Registry};
50
51#[derive(Clone, Debug, Default, PartialEq)]
53pub enum Policy {
54 #[default]
56 Default,
57 Fastest,
59 MinMemory,
61 Pinned(ImplId),
64 PreferEnvironment(Ident),
66}
67
68#[derive(Clone, Debug)]
70pub struct Options {
71 pub check_arguments: bool,
73 pub check_result: bool,
75 pub fall_back: bool,
81}
82
83impl Default for Options {
84 fn default() -> Self {
85 Self {
86 check_arguments: true,
87 check_result: true,
88 fall_back: false,
89 }
90 }
91}
92
93#[derive(Clone, Debug, PartialEq)]
95pub enum Outcome {
96 Answered,
98 Unavailable(String),
100 NotPreferred,
102 Failed(String),
104}
105
106#[derive(Clone, Debug, PartialEq)]
108pub struct Considered {
109 pub id: ImplId,
111 pub environment: Ident,
113 pub cost: String,
115 pub outcome: Outcome,
117}
118
119#[derive(Clone, Debug)]
121pub struct Invocation {
122 pub value: Value,
124 pub implementation: ImplId,
126 pub environment: Ident,
128 pub elapsed: Duration,
130 pub considered: Vec<Considered>,
132}
133
134pub struct Dispatcher {
136 ws: Arc<CheckedWorkspace>,
137 registry: Arc<Registry>,
138 options: Options,
139 workers: crate::worker::Workers,
141 #[cfg(feature = "wasm")]
148 wasm: std::sync::OnceLock<crate::wasm::WasmHost>,
149}
150
151impl Dispatcher {
152 pub fn new(ws: Arc<CheckedWorkspace>, registry: Arc<Registry>) -> Self {
154 Self {
155 ws,
156 registry,
157 options: Options::default(),
158 workers: crate::worker::Workers::new(),
159 #[cfg(feature = "wasm")]
160 wasm: std::sync::OnceLock::new(),
161 }
162 }
163
164 pub fn workers(&self) -> &crate::worker::Workers {
169 &self.workers
170 }
171
172 pub fn with_options(mut self, options: Options) -> Self {
174 self.options = options;
175 self
176 }
177
178 pub fn workspace(&self) -> &CheckedWorkspace {
180 &self.ws
181 }
182
183 pub fn registry(&self) -> &Registry {
185 &self.registry
186 }
187
188 pub fn candidates(&self, sig: &QualifiedName, policy: &Policy) -> Vec<&Implementation> {
194 self.routes(sig, policy)
195 .into_iter()
196 .map(|(implementation, _)| implementation)
197 .collect()
198 }
199
200 fn routes(&self, sig: &QualifiedName, policy: &Policy) -> Vec<(&Implementation, Vec<usize>)> {
204 let mut found: Vec<(&Implementation, Vec<usize>)> = Vec::new();
205 let mut seen = HashSet::new();
206 let arity = self.ws.sig(sig).map_or(0, |s| s.params.len());
207
208 let mut frontier = vec![(sig.clone(), (0..arity).collect::<Vec<usize>>())];
212 while let Some((name, order)) = frontier.pop() {
213 if !seen.insert(name.clone()) {
214 continue;
215 }
216 found.extend(
217 self.registry
218 .proofs_of(&name)
219 .into_iter()
220 .map(|i| (i, order.clone())),
221 );
222 frontier.extend(
223 self.ws
224 .refiners_of(&name)
225 .iter()
226 .map(|r| (r.clone(), order.clone())),
227 );
228 frontier.extend(
229 self.ws
230 .equivalents_of(&name)
231 .iter()
232 .map(|e| (e.sig.clone(), e.apply(&order))),
233 );
234 }
235
236 if let Policy::Pinned(id) = policy {
237 found.retain(|(i, _)| &i.id == id);
238 return found;
239 }
240
241 found.sort_by_key(|(i, _)| self.rank(i, policy));
242 found
243 }
244
245 fn rank(&self, implementation: &Implementation, policy: &Policy) -> (u8, u8, u8, u8, String) {
247 let overhead = self
248 .registry
249 .environment(&implementation.environment)
250 .map(|e| e.reach.overhead())
251 .unwrap_or(u8::MAX);
252 let (time, space, _) = implementation.cost_key();
253 let id = implementation.id.to_string();
254
255 match policy {
256 Policy::Default => (0, overhead, time, space, id),
262 Policy::Fastest => (0, time, space, overhead, id),
263 Policy::MinMemory => (0, space, time, overhead, id),
264 Policy::PreferEnvironment(wanted) => (
265 u8::from(&implementation.environment != wanted),
266 time,
267 space,
268 overhead,
269 id,
270 ),
271 Policy::Pinned(_) => (0, time, space, overhead, id),
272 }
273 }
274
275 pub fn call<'a>(
281 &'a self,
282 sig: &'a QualifiedName,
283 args: Vec<Value>,
284 policy: &'a Policy,
285 ) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
286 Box::pin(async move { self.dispatch(sig, &[], args, policy).await })
287 }
288
289 pub fn call_at<'a>(
298 &'a self,
299 sig: &'a QualifiedName,
300 type_args: &'a [Type],
301 args: Vec<Value>,
302 policy: &'a Policy,
303 ) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
304 Box::pin(async move { self.dispatch(sig, type_args, args, policy).await })
305 }
306
307 async fn dispatch(
308 &self,
309 name: &QualifiedName,
310 type_args: &[Type],
311 args: Vec<Value>,
312 policy: &Policy,
313 ) -> Result<Invocation, DispatchError> {
314 let Some(declared) = self.ws.sig(name) else {
315 return Err(DispatchError::UnknownSignature(name.clone()));
316 };
317
318 if declared.params_decl.len() != type_args.len() {
319 return Err(DispatchError::TypeArity {
320 sig: name.clone(),
321 expected: declared.params_decl.len(),
322 got: type_args.len(),
323 });
324 }
325 let subst = unitype_core::check::bind(&declared.params_decl, type_args);
328 for (param, arg) in declared.params_decl.iter().zip(type_args) {
329 for bound in ¶m.bounds {
330 let required = Type::Ref(unitype_core::check::substitute_ref(bound, &subst));
331 if !self.ws.is_subtype(arg, &required) {
332 return Err(DispatchError::BoundNotMet {
333 sig: name.clone(),
334 param: param.name.clone(),
335 arg: arg.to_string(),
336 bound: required.to_string(),
337 });
338 }
339 }
340 }
341 let instantiated;
344 let sig = if type_args.is_empty() {
345 declared
346 } else {
347 instantiated = declared.instantiate(type_args);
348 &instantiated
349 };
350
351 if sig.params.len() != args.len() {
352 return Err(DispatchError::Arity {
353 sig: name.clone(),
354 expected: sig.params.len(),
355 got: args.len(),
356 });
357 }
358 if self.options.check_arguments {
359 for (index, (param, arg)) in sig.params.iter().zip(&args).enumerate() {
360 if let Err(errors) = self.ws.validate(arg, ¶m.ty) {
361 return Err(DispatchError::BadArgument {
362 sig: name.clone(),
363 index,
364 errors,
365 });
366 }
367 }
368 }
369
370 let candidates = self.routes(name, policy);
371 if candidates.is_empty() {
372 return match policy {
373 Policy::Pinned(id) => Err(DispatchError::Unusable {
374 id: id.to_string(),
375 reason: format!("nothing registered under that name proves `{name}`"),
376 }),
377 _ => Err(DispatchError::NoImplementation(name.clone())),
378 };
379 }
380
381 let expected = match &sig.ret {
384 Type::Future { of } => (**of).clone(),
385 other => other.clone(),
386 };
387
388 let mut considered = Vec::with_capacity(candidates.len());
389 for (implementation, order) in candidates {
390 let cost = implementation.cost.to_string();
391 let environment = implementation.environment.clone();
392
393 if let Err(reason) = self.reachable(implementation) {
394 considered.push(Considered {
395 id: implementation.id.clone(),
396 environment,
397 cost,
398 outcome: Outcome::Unavailable(reason),
399 });
400 continue;
401 }
402
403 let started = Instant::now();
404 let handed: Vec<Value> = order.iter().map(|&i| args[i].clone()).collect();
407 let types: Vec<Type> = order.iter().map(|&i| sig.params[i].ty.clone()).collect();
410 let outcome = self
411 .invoke(implementation, handed, &types, &expected, policy)
412 .await;
413 let elapsed = started.elapsed();
414
415 match outcome {
416 Ok(value) => {
417 if self.options.check_result {
418 if let Err(errors) = self.ws.validate(&value, &expected) {
419 return Err(DispatchError::BadResult {
423 id: implementation.id.to_string(),
424 sig: name.clone(),
425 errors,
426 });
427 }
428 }
429 considered.push(Considered {
430 id: implementation.id.clone(),
431 environment: environment.clone(),
432 cost,
433 outcome: Outcome::Answered,
434 });
435 return Ok(Invocation {
436 value,
437 implementation: implementation.id.clone(),
438 environment,
439 elapsed,
440 considered,
441 });
442 }
443 Err(error) => {
444 let recoverable = self.options.fall_back && error.is_environmental();
445 considered.push(Considered {
446 id: implementation.id.clone(),
447 environment,
448 cost,
449 outcome: Outcome::Failed(error.to_string()),
450 });
451 if !recoverable {
452 return Err(DispatchError::Exec {
453 id: implementation.id.to_string(),
454 source: error,
455 });
456 }
457 }
458 }
459 }
460
461 Err(DispatchError::NoneAvailable {
462 sig: name.clone(),
463 skipped: considered
464 .iter()
465 .map(|c| match &c.outcome {
466 Outcome::Unavailable(why) | Outcome::Failed(why) => {
467 format!("{}: {why}", c.id)
468 }
469 other => format!("{}: {other:?}", c.id),
470 })
471 .collect(),
472 })
473 }
474
475 fn reachable(&self, implementation: &Implementation) -> Result<(), String> {
477 let Some(environment) = self.registry.environment(&implementation.environment) else {
478 return Err(format!(
479 "environment `{}` is not registered",
480 implementation.environment
481 ));
482 };
483 match &environment.reach {
484 Reach::Here => {
485 if implementation.entry == INTRINSIC_ENTRY
486 || self.registry.native(&implementation.entry).is_some()
487 {
488 Ok(())
489 } else {
490 Err(format!(
491 "nothing is registered in this process under `{}`",
492 implementation.entry
493 ))
494 }
495 }
496 Reach::Subprocess { .. } => Ok(()),
500 #[cfg(feature = "wasm")]
501 Reach::Wasm { .. } => Ok(()),
502 other => Err(format!(
503 "reaching a `{}` environment is not built into this binary",
504 other.kind()
505 )),
506 }
507 }
508
509 async fn invoke(
515 &self,
516 implementation: &Implementation,
517 args: Vec<Value>,
518 params: &[Type],
519 expected: &Type,
520 policy: &Policy,
521 ) -> Result<Value, ExecError> {
522 let Some(environment) = self.registry.environment(&implementation.environment) else {
523 return Err(ExecError::Unreachable {
524 environment: implementation.environment.to_string(),
525 detail: "not registered".into(),
526 });
527 };
528
529 match &environment.reach {
530 Reach::Here => {
531 if implementation.entry == INTRINSIC_ENTRY {
535 let calls = Through {
536 dispatcher: self,
537 policy,
538 };
539 return eval_signature(&self.ws, &implementation.proves, args, &calls).await;
540 }
541 let Some(native) = self.registry.native(&implementation.entry) else {
542 return Err(ExecError::NotRegistered(implementation.entry.clone()));
543 };
544 native(args).await
545 }
546 Reach::Subprocess {
549 persistent: true, ..
550 } => {
551 self.workers
552 .invoke(
553 &self.ws,
554 environment,
555 implementation,
556 args,
557 params,
558 expected,
559 )
560 .await
561 }
562 Reach::Subprocess { .. } => {
563 crate::subprocess::invoke(
564 &self.ws,
565 environment,
566 implementation,
567 args,
568 params,
569 expected,
570 )
571 .await
572 }
573 #[cfg(feature = "wasm")]
574 Reach::Wasm { .. } => {
575 self.wasm
576 .get_or_init(crate::wasm::WasmHost::new)
577 .invoke(
578 &self.ws,
579 environment,
580 implementation,
581 args,
582 params,
583 expected,
584 )
585 .await
586 }
587 other => Err(ExecError::Unreachable {
588 environment: environment.id.to_string(),
589 detail: format!(
590 "reaching a `{}` environment is not built into this binary",
591 other.kind()
592 ),
593 }),
594 }
595 }
596}
597
598struct Through<'a> {
600 dispatcher: &'a Dispatcher,
601 policy: &'a Policy,
602}
603
604impl Calls for Through<'_> {
605 fn call<'a>(
606 &'a self,
607 sig: &'a QualifiedName,
608 args: Vec<Value>,
609 ) -> BoxFuture<'a, Result<Value, ExecError>> {
610 Box::pin(async move {
611 let policy = match self.policy {
614 Policy::Pinned(_) => &Policy::Default,
615 other => other,
616 };
617 self.dispatcher
618 .call(sig, args, policy)
619 .await
620 .map(|i| i.value)
621 .map_err(|e| ExecError::Failed {
622 id: sig.to_string(),
623 message: e.to_string(),
624 })
625 })
626 }
627}
628
629#[cfg(test)]
630mod tests {
631 use super::*;
632 use unitype_core::check::check_workspace;
633 use unitype_core::{BigO, ImplProfile, Workspace};
634
635 use crate::environment::Environment;
636 use crate::implementation::Implementation;
637
638 fn q(s: &str) -> QualifiedName {
639 s.parse().unwrap()
640 }
641
642 fn here() -> Ident {
643 Ident::new("here").unwrap()
644 }
645
646 const SORT_WS: &str = r#"{"universes":[{"name":"demo","functions":[
647 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
648 {"name":"mergesort","refines":"demo::sort",
649 "params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#;
650
651 fn bubble(mut items: Vec<i64>) -> Vec<i64> {
653 for i in 0..items.len() {
654 for j in 0..items.len().saturating_sub(i + 1) {
655 if items[j] > items[j + 1] {
656 items.swap(j, j + 1);
657 }
658 }
659 }
660 items
661 }
662
663 fn ints(value: &Value) -> Vec<i64> {
664 let Value::List(items) = value else {
665 return Vec::new();
666 };
667 items.iter().filter_map(Value::as_int).collect()
668 }
669
670 fn sorting_dispatcher() -> Dispatcher {
672 let ws = Arc::new(
673 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
674 );
675 let mut registry = Registry::new();
676
677 registry.register_native_sync("merge_sort", |args| {
678 let mut items = ints(args.first().unwrap_or(&Value::Null));
679 items.sort_unstable();
680 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
681 });
682 registry.register_native_sync("bubble_sort", |args| {
683 let items = bubble(ints(args.first().unwrap_or(&Value::Null)));
684 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
685 });
686
687 registry
688 .register(Implementation::new(
689 "sort.merge",
690 q("demo::sort"),
691 here(),
692 "merge_sort",
693 ImplProfile::new(BigO::ONLogN, BigO::ON),
694 ))
695 .unwrap();
696 registry
697 .register(Implementation::new(
698 "sort.bubble",
699 q("demo::sort"),
700 here(),
701 "bubble_sort",
702 ImplProfile::new(BigO::ON2, BigO::O1),
703 ))
704 .unwrap();
705
706 Dispatcher::new(ws, Arc::new(registry))
707 }
708
709 async fn sort_with(policy: Policy) -> Invocation {
710 sorting_dispatcher()
711 .call(&q("demo::sort"), vec![list(&[3, 1, 2])], &policy)
712 .await
713 .expect("answers")
714 }
715
716 fn list(items: &[i64]) -> Value {
717 Value::List(items.iter().copied().map(Value::Int).collect())
718 }
719
720 fn request_dispatcher() -> Dispatcher {
723 let ws = Arc::new(
724 check_workspace(
725 Workspace::from_json(
726 r#"{"universes":[
727 {"name":"node","functions":[{"name":"fetch","ret":"str","params":[
728 {"name":"url","ty":"str"},{"name":"retries","ty":"i64"}]}]},
729 {"name":"browser","functions":[{"name":"get","ret":"str","params":[
730 {"name":"attempts","ty":"i64"},{"name":"getUrl","ty":"str"}]}]}],
731 "links":[{"name":"fetch_is_get","from":"node::fetch","to":"browser::get",
732 "kind":{"k":"equivalent"}}]}"#,
733 )
734 .expect("reads"),
735 )
736 .expect("checks"),
737 );
738 let mut registry = Registry::new();
739 registry.register_native_sync("node_fetch", |args| {
741 let url = args.first().and_then(Value::as_str).unwrap_or("?");
742 let retries = args.get(1).and_then(Value::as_int).unwrap_or(-1);
743 Ok(Value::Str(format!("{url} x{retries}")))
744 });
745 registry
746 .register(Implementation::new(
747 "fetch.node",
748 q("node::fetch"),
749 here(),
750 "node_fetch",
751 ImplProfile::new(BigO::O1, BigO::O1),
752 ))
753 .unwrap();
754 Dispatcher::new(ws, Arc::new(registry))
755 }
756
757 #[tokio::test]
758 async fn a_proof_of_an_equivalent_proposition_gets_the_arguments_its_own_way_round() {
759 let dispatcher = request_dispatcher();
760
761 let answered = dispatcher
762 .call(
763 &q("browser::get"),
764 vec![Value::Int(3), Value::Str("https://x".into())],
765 &Policy::Default,
766 )
767 .await
768 .expect("the node proof answers the browser's call");
769 assert_eq!(answered.implementation.as_str(), "fetch.node");
770 assert_eq!(
771 answered.value,
772 Value::Str("https://x x3".into()),
773 "the URL went where the proof reads it"
774 );
775
776 let direct = dispatcher
777 .call(
778 &q("node::fetch"),
779 vec![Value::Str("https://x".into()), Value::Int(3)],
780 &Policy::Default,
781 )
782 .await
783 .expect("answers its own proposition");
784 assert_eq!(direct.value, answered.value, "and the same call either way");
785 }
786
787 #[tokio::test]
788 async fn pinning_a_proof_of_an_equivalent_proposition_still_reorders() {
789 let answered = request_dispatcher()
790 .call(
791 &q("browser::get"),
792 vec![Value::Int(1), Value::Str("https://y".into())],
793 &Policy::Pinned(ImplId::new("fetch.node")),
794 )
795 .await
796 .expect("answers");
797 assert_eq!(answered.value, Value::Str("https://y x1".into()));
798 }
799
800 #[tokio::test]
801 async fn a_generic_proposition_is_answered_by_a_proof_of_its_equivalent() {
802 let ws = Arc::new(
805 check_workspace(
806 Workspace::from_json(
807 r#"{"universes":[
808 {"name":"py","functions":[{"name":"konst",
809 "params_decl":[{"name":"A"},{"name":"B"}],
810 "params":[{"name":"x","ty":{"k":"param","name":"A"}},
811 {"name":"y","ty":{"k":"param","name":"B"}}],
812 "ret":{"k":"param","name":"A"}}]},
813 {"name":"js","functions":[{"name":"always",
814 "params_decl":[{"name":"Y"},{"name":"X"}],
815 "params":[{"name":"ignored","ty":{"k":"param","name":"Y"}},
816 {"name":"kept","ty":{"k":"param","name":"X"}}],
817 "ret":{"k":"param","name":"X"}}]}],
818 "links":[{"name":"konst_is_always","from":"py::konst","to":"js::always",
819 "kind":{"k":"equivalent"}}]}"#,
820 )
821 .expect("reads"),
822 )
823 .expect("checks"),
824 );
825 let mut registry = Registry::new();
826 registry.register_native_sync("py_konst", |args| Ok(args[0].clone()));
828 registry
829 .register(Implementation::new(
830 "konst.py",
831 q("py::konst"),
832 here(),
833 "py_konst",
834 ImplProfile::new(BigO::O1, BigO::O1),
835 ))
836 .unwrap();
837 let dispatcher = Dispatcher::new(ws, Arc::new(registry));
838
839 let answered = dispatcher
841 .call_at(
842 &q("js::always"),
843 &[Type::String, Type::I64],
844 vec![Value::Str("dropped".into()), Value::Int(7)],
845 &Policy::Default,
846 )
847 .await
848 .expect("the proof of konst answers, checked against always<str, i64>");
849 assert_eq!(answered.implementation.as_str(), "konst.py");
850 assert_eq!(answered.value, Value::Int(7));
851 }
852
853 #[tokio::test]
854 async fn asking_for_speed_and_asking_for_memory_choose_differently() {
855 let fast = sort_with(Policy::Fastest).await;
856 let frugal = sort_with(Policy::MinMemory).await;
857
858 assert_eq!(fast.implementation.as_str(), "sort.merge");
859 assert_eq!(frugal.implementation.as_str(), "sort.bubble");
860 }
861
862 #[tokio::test]
863 async fn and_both_give_the_same_answer() {
864 let fast = sort_with(Policy::Fastest).await;
865 let frugal = sort_with(Policy::MinMemory).await;
866 assert_eq!(fast.value, list(&[1, 2, 3]));
867 assert_eq!(
868 fast.value, frugal.value,
869 "which proof ran should not change what is true"
870 );
871 }
872
873 #[tokio::test]
874 async fn a_caller_can_see_what_was_considered_and_why() {
875 let chosen = sort_with(Policy::Fastest).await;
876 assert_eq!(chosen.considered.len(), 1, "the first one worked");
877 assert_eq!(chosen.considered[0].outcome, Outcome::Answered);
878 assert_eq!(chosen.environment, here());
879
880 let ranked: Vec<String> = sorting_dispatcher()
881 .candidates(&q("demo::sort"), &Policy::MinMemory)
882 .iter()
883 .map(|i| i.id.to_string())
884 .collect();
885 assert_eq!(ranked, ["sort.bubble", "sort.merge"]);
886 }
887
888 #[tokio::test]
889 async fn the_default_stays_in_the_process_where_it_can() {
890 let ws = Arc::new(
891 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
892 );
893 let mut registry = Registry::new();
894 registry.register_native_sync("bubble_sort", |args| {
895 Ok(Value::List(
896 bubble(ints(&args[0])).into_iter().map(Value::Int).collect(),
897 ))
898 });
899 registry
900 .add_environment(Environment::subprocess("py", "python", "python3", &[]))
901 .unwrap();
902 registry
904 .register(Implementation::new(
905 "sort.py_merge",
906 q("demo::sort"),
907 Ident::new("py").unwrap(),
908 "merge_sort",
909 ImplProfile::new(BigO::ONLogN, BigO::ON),
910 ))
911 .unwrap();
912 registry
913 .register(Implementation::new(
914 "sort.here_bubble",
915 q("demo::sort"),
916 here(),
917 "bubble_sort",
918 ImplProfile::new(BigO::ON2, BigO::O1),
919 ))
920 .unwrap();
921
922 let dispatcher = Dispatcher::new(ws, Arc::new(registry));
923 let ranked: Vec<String> = dispatcher
924 .candidates(&q("demo::sort"), &Policy::Default)
925 .iter()
926 .map(|i| i.id.to_string())
927 .collect();
928 assert_eq!(
929 ranked[0], "sort.here_bubble",
930 "starting a process costs more than the difference in complexity, \
931 for the sizes most calls carry"
932 );
933
934 let ranked: Vec<String> = dispatcher
935 .candidates(&q("demo::sort"), &Policy::Fastest)
936 .iter()
937 .map(|i| i.id.to_string())
938 .collect();
939 assert_eq!(
940 ranked[0], "sort.py_merge",
941 "asked for speed, the better algorithm wins wherever it lives"
942 );
943 }
944
945 #[tokio::test]
946 async fn a_pinned_proof_is_the_one_that_runs() {
947 let pinned = sorting_dispatcher()
948 .call(
949 &q("demo::sort"),
950 vec![list(&[2, 1])],
951 &Policy::Pinned(ImplId::new("sort.bubble")),
952 )
953 .await
954 .expect("answers");
955 assert_eq!(pinned.implementation.as_str(), "sort.bubble");
956 }
957
958 #[tokio::test]
959 async fn pinning_something_that_proves_nothing_fails_rather_than_substituting() {
960 let err = sorting_dispatcher()
961 .call(
962 &q("demo::sort"),
963 vec![list(&[1])],
964 &Policy::Pinned(ImplId::new("sort.nonexistent")),
965 )
966 .await
967 .unwrap_err();
968 assert!(
969 matches!(err, DispatchError::Unusable { .. }),
970 "asking for one thing and getting another would be worse: {err}"
971 );
972 }
973
974 #[tokio::test]
975 async fn a_proposition_nobody_proves_says_so() {
976 let ws = Arc::new(
977 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
978 );
979 let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
980 assert!(matches!(
981 dispatcher
982 .call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
983 .await,
984 Err(DispatchError::NoImplementation(_))
985 ));
986 }
987
988 #[tokio::test]
989 async fn arguments_are_checked_before_anything_runs() {
990 let err = sorting_dispatcher()
991 .call(
992 &q("demo::sort"),
993 vec![Value::Str("not a list".into())],
994 &Policy::Default,
995 )
996 .await
997 .unwrap_err();
998 assert!(
999 matches!(err, DispatchError::BadArgument { index: 0, .. }),
1000 "{err}"
1001 );
1002 }
1003
1004 #[tokio::test]
1005 async fn the_wrong_number_of_arguments_is_caught() {
1006 let err = sorting_dispatcher()
1007 .call(&q("demo::sort"), vec![], &Policy::Default)
1008 .await
1009 .unwrap_err();
1010 assert!(matches!(
1011 err,
1012 DispatchError::Arity {
1013 expected: 1,
1014 got: 0,
1015 ..
1016 }
1017 ));
1018 }
1019
1020 #[tokio::test]
1021 async fn a_proof_that_returns_the_wrong_thing_is_caught_and_never_excused() {
1022 let ws = Arc::new(
1023 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1024 );
1025 let mut registry = Registry::new();
1026 registry.register_native_sync("liar", |_| Ok(Value::Str("not a list at all".into())));
1027 registry.register_native_sync("honest", |args| Ok(args[0].clone()));
1028 registry
1029 .register(Implementation::new(
1030 "sort.liar",
1031 q("demo::sort"),
1032 here(),
1033 "liar",
1034 ImplProfile::new(BigO::O1, BigO::O1),
1035 ))
1036 .unwrap();
1037 registry
1038 .register(Implementation::new(
1039 "sort.honest",
1040 q("demo::sort"),
1041 here(),
1042 "honest",
1043 ImplProfile::new(BigO::ON, BigO::ON),
1044 ))
1045 .unwrap();
1046
1047 let dispatcher = Dispatcher::new(ws, Arc::new(registry)).with_options(Options {
1048 fall_back: true,
1049 ..Options::default()
1050 });
1051
1052 let err = dispatcher
1053 .call(&q("demo::sort"), vec![list(&[1])], &Policy::Fastest)
1054 .await
1055 .unwrap_err();
1056
1057 assert!(
1058 matches!(err, DispatchError::BadResult { .. }),
1059 "even with fallback on, a broken proof must not be quietly replaced: {err}"
1060 );
1061 }
1062
1063 #[tokio::test]
1064 async fn a_proof_of_a_stronger_claim_answers_the_weaker_one() {
1065 let ws = Arc::new(
1066 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1067 );
1068 let mut registry = Registry::new();
1069 registry.register_native_sync("merge_sort", |args| {
1070 let mut items = ints(&args[0]);
1071 items.sort_unstable();
1072 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
1073 });
1074 registry
1077 .register(Implementation::new(
1078 "mergesort.rust",
1079 q("demo::mergesort"),
1080 here(),
1081 "merge_sort",
1082 ImplProfile::new(BigO::ONLogN, BigO::ON),
1083 ))
1084 .unwrap();
1085
1086 let answer = Dispatcher::new(ws, Arc::new(registry))
1087 .call(&q("demo::sort"), vec![list(&[3, 1, 2])], &Policy::Default)
1088 .await
1089 .expect("a proof of the stronger claim proves this one");
1090
1091 assert_eq!(answer.implementation.as_str(), "mergesort.rust");
1092 assert_eq!(answer.value, list(&[1, 2, 3]));
1093 }
1094
1095 #[tokio::test]
1096 async fn an_environment_that_cannot_be_reached_is_reported_with_the_reason() {
1097 let ws = Arc::new(
1098 check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
1099 );
1100 let mut registry = Registry::new();
1101 registry
1102 .add_environment(Environment::subprocess(
1103 "missing",
1104 "python",
1105 "unitype_no_such_interpreter",
1106 &[],
1107 ))
1108 .unwrap();
1109 registry
1110 .register(Implementation::new(
1111 "sort.elsewhere",
1112 q("demo::sort"),
1113 Ident::new("missing").unwrap(),
1114 "bubble_sort",
1115 ImplProfile::new(BigO::ON2, BigO::O1),
1116 ))
1117 .unwrap();
1118
1119 let err = Dispatcher::new(ws, Arc::new(registry))
1120 .call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
1121 .await
1122 .unwrap_err();
1123
1124 let message = err.to_string();
1125 assert!(message.contains("sort.elsewhere"), "{message}");
1126 assert!(
1127 message.contains("could not start"),
1128 "the reason should be the actual one: {message}"
1129 );
1130 }
1131
1132 #[tokio::test]
1133 async fn a_body_that_calls_out_is_answered_by_the_dispatcher() {
1134 let ws = Arc::new(
1135 check_workspace(
1136 Workspace::from_json(
1137 r#"{"universes":[{"name":"demo","functions":[
1138 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
1139 {"name":"sorted_twice","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
1140 "body":{"k":"call","sig":"demo::sort","args":[
1141 {"k":"call","sig":"demo::sort","args":[{"k":"var","name":"xs"}]}]}}]}]}"#,
1142 )
1143 .expect("reads"),
1144 )
1145 .expect("checks"),
1146 );
1147
1148 let mut registry = Registry::new();
1149 registry.register_bodies(&ws).unwrap();
1150 registry.register_native_sync("merge_sort", |args| {
1151 let mut items = ints(&args[0]);
1152 items.sort_unstable();
1153 Ok(Value::List(items.into_iter().map(Value::Int).collect()))
1154 });
1155 registry
1156 .register(Implementation::new(
1157 "sort.merge",
1158 q("demo::sort"),
1159 here(),
1160 "merge_sort",
1161 ImplProfile::new(BigO::ONLogN, BigO::ON),
1162 ))
1163 .unwrap();
1164
1165 let answer = Dispatcher::new(ws, Arc::new(registry))
1166 .call(
1167 &q("demo::sorted_twice"),
1168 vec![list(&[3, 1, 2])],
1169 &Policy::Default,
1170 )
1171 .await
1172 .expect("answers");
1173
1174 assert_eq!(answer.value, list(&[1, 2, 3]));
1175 assert!(
1176 answer.implementation.as_str().ends_with("#body"),
1177 "the body proved it, and the dispatcher answered what the body asked"
1178 );
1179 }
1180
1181 const GENERIC_WS: &str = r#"{"universes":[{"name":"demo","functions":[
1182 {"name":"reverse","params_decl":[{"name":"T"}],
1183 "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
1184 "ret":{"k":"list","of":{"k":"param","name":"T"}}}]}]}"#;
1185
1186 fn reversing_dispatcher() -> Dispatcher {
1188 let ws = Arc::new(
1189 check_workspace(Workspace::from_json(GENERIC_WS).expect("reads")).expect("checks"),
1190 );
1191 let mut registry = Registry::new();
1192 registry.register_native_sync("reverse", |mut args| {
1193 let Value::List(items) = args.remove(0) else {
1194 return Err(ExecError::Untyped("expected a list".into()));
1195 };
1196 Ok(Value::List(items.into_iter().rev().collect()))
1197 });
1198 registry
1199 .register(Implementation::new(
1200 "reverse.here",
1201 q("demo::reverse"),
1202 here(),
1203 "reverse",
1204 ImplProfile::new(BigO::ON, BigO::ON),
1205 ))
1206 .unwrap();
1207 Dispatcher::new(ws, Arc::new(registry))
1208 }
1209
1210 #[tokio::test]
1211 async fn a_generic_proposition_is_called_at_a_type() {
1212 let dispatcher = reversing_dispatcher();
1213 let words = Value::List(vec![Value::Str("a".into()), Value::Str("b".into())]);
1214
1215 let at_strings = dispatcher
1216 .call_at(
1217 &q("demo::reverse"),
1218 &[Type::String],
1219 vec![words],
1220 &Policy::Default,
1221 )
1222 .await
1223 .expect("answers");
1224 assert_eq!(
1225 at_strings.value,
1226 Value::List(vec![Value::Str("b".into()), Value::Str("a".into())])
1227 );
1228
1229 let at_ints = dispatcher
1230 .call_at(
1231 &q("demo::reverse"),
1232 &[Type::I64],
1233 vec![list(&[1, 2])],
1234 &Policy::Default,
1235 )
1236 .await
1237 .expect("answers");
1238 assert_eq!(at_ints.value, list(&[2, 1]));
1239 }
1240
1241 #[tokio::test]
1242 async fn a_generic_proposition_called_without_its_type_says_what_is_missing() {
1243 let err = reversing_dispatcher()
1246 .call(&q("demo::reverse"), vec![list(&[1, 2])], &Policy::Default)
1247 .await
1248 .unwrap_err();
1249 assert!(
1250 matches!(
1251 err,
1252 DispatchError::TypeArity {
1253 expected: 1,
1254 got: 0,
1255 ..
1256 }
1257 ),
1258 "{err}"
1259 );
1260 }
1261
1262 #[tokio::test]
1263 async fn a_generic_proposition_is_not_asked_at_a_type_its_bound_rules_out() {
1264 let ws = Arc::new(
1265 check_workspace(
1266 Workspace::from_json(
1267 r#"{"universes":[{"name":"demo",
1268 "types":[{"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
1269 {"k":"struct","name":"Person","implements":["Named"],
1270 "fields":[{"name":"name","ty":"str"}]}],
1271 "functions":[{"name":"first_named",
1272 "params_decl":[{"name":"T","bounds":["Named"]}],
1273 "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
1274 "ret":{"k":"optional","of":{"k":"param","name":"T"}}}]}]}"#,
1275 )
1276 .expect("reads"),
1277 )
1278 .expect("checks"),
1279 );
1280 let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
1281 let person = Type::Ref(unitype_core::ir::TypeRef::qualified(
1282 Ident::new("demo").unwrap(),
1283 Ident::new("Person").unwrap(),
1284 ));
1285
1286 let err = dispatcher
1287 .call_at(
1288 &q("demo::first_named"),
1289 &[Type::I64],
1290 vec![list(&[1])],
1291 &Policy::Default,
1292 )
1293 .await
1294 .unwrap_err();
1295 assert!(
1296 matches!(&err, DispatchError::BoundNotMet { param, .. } if param.as_str() == "T"),
1297 "an integer has no name: {err}"
1298 );
1299
1300 let err = dispatcher
1303 .call_at(
1304 &q("demo::first_named"),
1305 &[person],
1306 vec![Value::List(vec![])],
1307 &Policy::Default,
1308 )
1309 .await
1310 .unwrap_err();
1311 assert!(matches!(err, DispatchError::NoImplementation(_)), "{err}");
1312 }
1313
1314 #[tokio::test]
1315 async fn the_boundary_is_checked_at_the_type_the_call_named() {
1316 let err = reversing_dispatcher()
1319 .call_at(
1320 &q("demo::reverse"),
1321 &[Type::String],
1322 vec![list(&[1, 2])],
1323 &Policy::Default,
1324 )
1325 .await
1326 .unwrap_err();
1327 assert!(
1328 matches!(err, DispatchError::BadArgument { index: 0, .. }),
1329 "{err}"
1330 );
1331 }
1332}