use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, Instant};
use unitype_core::check::CheckedWorkspace;
use unitype_core::ir::{FunctionSig, Type};
use unitype_core::meta::ImplProfile;
use unitype_core::value::Value;
use unitype_core::{Ident, QualifiedName};
use crate::environment::Reach;
use crate::error::{DispatchError, ExecError};
use crate::implementation::{ImplId, Implementation};
use crate::interpret::{BoxFuture, Calls, eval_signature};
use crate::registry::{INTRINSIC_ENTRY, Registry};
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Policy {
#[default]
Default,
Fastest,
MinMemory,
Pinned(ImplId),
PreferEnvironment(Ident),
}
#[derive(Clone, Debug)]
pub struct Options {
pub check_arguments: bool,
pub check_result: bool,
pub fall_back: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
check_arguments: true,
check_result: true,
fall_back: false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Outcome {
Answered,
Unavailable(String),
NotPreferred,
Failed(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Considered {
pub id: ImplId,
pub environment: Ident,
pub cost: String,
pub outcome: Outcome,
}
#[derive(Clone, Debug)]
pub struct Invocation {
pub value: Value,
pub implementation: ImplId,
pub environment: Ident,
pub elapsed: Duration,
pub considered: Vec<Considered>,
}
fn over_budget(sig: &FunctionSig, claimed: &ImplProfile) -> Option<String> {
for (axis, allowed, claim) in [
("time", &sig.time, &claimed.time),
("space", &sig.space, &claimed.space),
] {
let Some(allowed) = allowed else {
continue;
};
let fits = match (claim.rank(), allowed.rank()) {
(Some(claim), Some(allowed)) => claim <= allowed,
_ => false,
};
if !fits {
return Some(format!(
"claims {claim} for {axis}, but the proposition allows at most {allowed}"
));
}
}
None
}
fn millis(n: i64) -> Duration {
Duration::from_millis(u64::try_from(n).unwrap_or(0))
}
pub struct Dispatcher {
ws: Arc<CheckedWorkspace>,
registry: Arc<Registry>,
options: Options,
workers: crate::worker::Workers,
#[cfg(feature = "wasm")]
wasm: std::sync::OnceLock<crate::wasm::WasmHost>,
}
impl Dispatcher {
pub fn new(ws: Arc<CheckedWorkspace>, registry: Arc<Registry>) -> Self {
Self {
ws,
registry,
options: Options::default(),
workers: crate::worker::Workers::new(),
#[cfg(feature = "wasm")]
wasm: std::sync::OnceLock::new(),
}
}
pub fn workers(&self) -> &crate::worker::Workers {
&self.workers
}
pub fn with_options(mut self, options: Options) -> Self {
self.options = options;
self
}
pub fn workspace(&self) -> &CheckedWorkspace {
&self.ws
}
pub fn registry(&self) -> &Registry {
&self.registry
}
pub fn candidates(&self, sig: &QualifiedName, policy: &Policy) -> Vec<&Implementation> {
self.routes(sig, policy)
.into_iter()
.map(|(implementation, _)| implementation)
.collect()
}
fn routes(&self, sig: &QualifiedName, policy: &Policy) -> Vec<(&Implementation, Vec<usize>)> {
let mut found: Vec<(&Implementation, Vec<usize>)> = Vec::new();
let mut seen = HashSet::new();
let arity = self.ws.sig(sig).map_or(0, |s| s.params.len());
let mut frontier = vec![(sig.clone(), (0..arity).collect::<Vec<usize>>())];
while let Some((name, order)) = frontier.pop() {
if !seen.insert(name.clone()) {
continue;
}
found.extend(
self.registry
.proofs_of(&name)
.into_iter()
.map(|i| (i, order.clone())),
);
frontier.extend(
self.ws
.refiners_of(&name)
.iter()
.map(|r| (r.clone(), order.clone())),
);
frontier.extend(
self.ws
.equivalents_of(&name)
.iter()
.map(|e| (e.sig.clone(), e.apply(&order))),
);
}
if let Policy::Pinned(id) = policy {
found.retain(|(i, _)| &i.id == id);
return found;
}
found.sort_by_key(|(i, _)| self.rank(i, policy));
found
}
fn rank(&self, implementation: &Implementation, policy: &Policy) -> (u8, u8, u8, u8, String) {
let overhead = self
.registry
.environment(&implementation.environment)
.map(|e| e.reach.overhead())
.unwrap_or(u8::MAX);
let (time, space, _) = implementation.cost_key();
let id = implementation.id.to_string();
match policy {
Policy::Default => (0, overhead, time, space, id),
Policy::Fastest => (0, time, space, overhead, id),
Policy::MinMemory => (0, space, time, overhead, id),
Policy::PreferEnvironment(wanted) => (
u8::from(&implementation.environment != wanted),
time,
space,
overhead,
id,
),
Policy::Pinned(_) => (0, time, space, overhead, id),
}
}
pub fn call<'a>(
&'a self,
sig: &'a QualifiedName,
args: Vec<Value>,
policy: &'a Policy,
) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
Box::pin(async move { self.dispatch(sig, &[], args, policy).await })
}
pub fn call_at<'a>(
&'a self,
sig: &'a QualifiedName,
type_args: &'a [Type],
args: Vec<Value>,
policy: &'a Policy,
) -> BoxFuture<'a, Result<Invocation, DispatchError>> {
Box::pin(async move { self.dispatch(sig, type_args, args, policy).await })
}
async fn dispatch(
&self,
name: &QualifiedName,
type_args: &[Type],
args: Vec<Value>,
policy: &Policy,
) -> Result<Invocation, DispatchError> {
let Some(declared) = self.ws.sig(name) else {
return Err(DispatchError::UnknownSignature(name.clone()));
};
if declared.params_decl.len() != type_args.len() {
return Err(DispatchError::TypeArity {
sig: name.clone(),
expected: declared.params_decl.len(),
got: type_args.len(),
});
}
let subst = unitype_core::check::bind(&declared.params_decl, type_args);
for (param, arg) in declared.params_decl.iter().zip(type_args) {
for bound in ¶m.bounds {
let required = Type::Ref(unitype_core::check::substitute_ref(bound, &subst));
if !self.ws.is_subtype(arg, &required) {
return Err(DispatchError::BoundNotMet {
sig: name.clone(),
param: param.name.clone(),
arg: arg.to_string(),
bound: required.to_string(),
});
}
}
}
let instantiated;
let sig = if type_args.is_empty() {
declared
} else {
instantiated = declared.instantiate(type_args);
&instantiated
};
if sig.params.len() != args.len() {
return Err(DispatchError::Arity {
sig: name.clone(),
expected: sig.params.len(),
got: args.len(),
});
}
if self.options.check_arguments {
for (index, (param, arg)) in sig.params.iter().zip(&args).enumerate() {
if let Err(errors) = self.ws.validate(arg, ¶m.ty) {
return Err(DispatchError::BadArgument {
sig: name.clone(),
index,
errors,
});
}
}
}
let candidates = self.routes(name, policy);
if candidates.is_empty() {
return match policy {
Policy::Pinned(id) => Err(DispatchError::Unusable {
id: id.to_string(),
reason: format!("nothing registered under that name proves `{name}`"),
}),
_ => Err(DispatchError::NoImplementation(name.clone())),
};
}
let expected = sig
.ret
.future_of()
.cloned()
.unwrap_or_else(|| sig.ret.clone());
let window = match &sig.ret {
Type::Bounded { wait, .. } => *wait,
_ => None,
};
let mut considered = Vec::with_capacity(candidates.len());
for (implementation, order) in candidates {
let cost = implementation.cost.to_string();
let environment = implementation.environment.clone();
if let Err(reason) = self.reachable(implementation) {
considered.push(Considered {
id: implementation.id.clone(),
environment,
cost,
outcome: Outcome::Unavailable(reason),
});
continue;
}
if let Some(reason) = over_budget(sig, &implementation.cost) {
considered.push(Considered {
id: implementation.id.clone(),
environment,
cost,
outcome: Outcome::Unavailable(reason),
});
continue;
}
let started = Instant::now();
let handed: Vec<Value> = order.iter().map(|&i| args[i].clone()).collect();
let types: Vec<Type> = order.iter().map(|&i| sig.params[i].ty.clone()).collect();
let call = self.invoke(implementation, handed, &types, &expected, policy);
let outcome = match window.and_then(|w| w.max) {
Some(max) => {
match tokio::time::timeout(millis(max.saturating_add(1)), call).await {
Ok(outcome) => outcome,
Err(_) => {
considered.push(Considered {
id: implementation.id.clone(),
environment: environment.clone(),
cost: cost.clone(),
outcome: Outcome::Failed(format!(
"did not answer within {max} ms, the window's end"
)),
});
continue;
}
}
}
None => call.await,
};
let elapsed = started.elapsed();
if let Some(w) = window {
let ms = i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX);
let early = w.min.is_some_and(|min| ms < min);
let late = w.max.is_some_and(|max| ms > max);
if early || late {
let why = if early {
format!(
"answered after {} ms, before the window opens at {} ms",
elapsed.as_millis(),
w.min.unwrap_or_default()
)
} else {
format!(
"answered after {} ms, after the window closes at {} ms",
elapsed.as_millis(),
w.max.unwrap_or_default()
)
};
considered.push(Considered {
id: implementation.id.clone(),
environment: environment.clone(),
cost: cost.clone(),
outcome: Outcome::Failed(why),
});
continue;
}
}
match outcome {
Ok(value) => {
if self.options.check_result {
if let Err(errors) = self.ws.validate(&value, &expected) {
return Err(DispatchError::BadResult {
id: implementation.id.to_string(),
sig: name.clone(),
errors,
});
}
}
considered.push(Considered {
id: implementation.id.clone(),
environment: environment.clone(),
cost,
outcome: Outcome::Answered,
});
return Ok(Invocation {
value,
implementation: implementation.id.clone(),
environment,
elapsed,
considered,
});
}
Err(error) => {
let recoverable = self.options.fall_back && error.is_environmental();
considered.push(Considered {
id: implementation.id.clone(),
environment,
cost,
outcome: Outcome::Failed(error.to_string()),
});
if !recoverable {
return Err(DispatchError::Exec {
id: implementation.id.to_string(),
source: error,
});
}
}
}
}
Err(DispatchError::NoneAvailable {
sig: name.clone(),
skipped: considered
.iter()
.map(|c| match &c.outcome {
Outcome::Unavailable(why) | Outcome::Failed(why) => {
format!("{}: {why}", c.id)
}
other => format!("{}: {other:?}", c.id),
})
.collect(),
})
}
fn reachable(&self, implementation: &Implementation) -> Result<(), String> {
let Some(environment) = self.registry.environment(&implementation.environment) else {
return Err(format!(
"environment `{}` is not registered",
implementation.environment
));
};
match &environment.reach {
Reach::Here => {
if implementation.entry == INTRINSIC_ENTRY
|| self.registry.native(&implementation.entry).is_some()
{
Ok(())
} else {
Err(format!(
"nothing is registered in this process under `{}`",
implementation.entry
))
}
}
Reach::Subprocess { .. } => Ok(()),
#[cfg(feature = "wasm")]
Reach::Wasm { .. } => Ok(()),
other => Err(format!(
"reaching a `{}` environment is not built into this binary",
other.kind()
)),
}
}
async fn invoke(
&self,
implementation: &Implementation,
args: Vec<Value>,
params: &[Type],
expected: &Type,
policy: &Policy,
) -> Result<Value, ExecError> {
let Some(environment) = self.registry.environment(&implementation.environment) else {
return Err(ExecError::Unreachable {
environment: implementation.environment.to_string(),
detail: "not registered".into(),
});
};
match &environment.reach {
Reach::Here => {
if implementation.entry == INTRINSIC_ENTRY {
let calls = Through {
dispatcher: self,
policy,
};
return eval_signature(&self.ws, &implementation.proves, args, &calls).await;
}
let Some(native) = self.registry.native(&implementation.entry) else {
return Err(ExecError::NotRegistered(implementation.entry.clone()));
};
native(args).await
}
Reach::Subprocess {
persistent: true, ..
} => {
self.workers
.invoke(
&self.ws,
environment,
implementation,
args,
params,
expected,
)
.await
}
Reach::Subprocess { .. } => {
crate::subprocess::invoke(
&self.ws,
environment,
implementation,
args,
params,
expected,
)
.await
}
#[cfg(feature = "wasm")]
Reach::Wasm { .. } => {
self.wasm
.get_or_init(crate::wasm::WasmHost::new)
.invoke(
&self.ws,
environment,
implementation,
args,
params,
expected,
)
.await
}
other => Err(ExecError::Unreachable {
environment: environment.id.to_string(),
detail: format!(
"reaching a `{}` environment is not built into this binary",
other.kind()
),
}),
}
}
}
struct Through<'a> {
dispatcher: &'a Dispatcher,
policy: &'a Policy,
}
impl Calls for Through<'_> {
fn call<'a>(
&'a self,
sig: &'a QualifiedName,
args: Vec<Value>,
) -> BoxFuture<'a, Result<Value, ExecError>> {
Box::pin(async move {
let policy = match self.policy {
Policy::Pinned(_) => &Policy::Default,
other => other,
};
self.dispatcher
.call(sig, args, policy)
.await
.map(|i| i.value)
.map_err(|e| ExecError::Failed {
id: sig.to_string(),
message: e.to_string(),
})
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use unitype_core::check::check_workspace;
use unitype_core::{BigO, ImplProfile, Workspace};
use crate::environment::Environment;
use crate::implementation::Implementation;
fn q(s: &str) -> QualifiedName {
s.parse().unwrap()
}
fn here() -> Ident {
Ident::new("here").unwrap()
}
const SORT_WS: &str = r#"{"universes":[{"name":"demo","functions":[
{"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
{"name":"mergesort","refines":"demo::sort",
"params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#;
fn bubble(mut items: Vec<i64>) -> Vec<i64> {
for i in 0..items.len() {
for j in 0..items.len().saturating_sub(i + 1) {
if items[j] > items[j + 1] {
items.swap(j, j + 1);
}
}
}
items
}
fn ints(value: &Value) -> Vec<i64> {
let Value::List(items) = value else {
return Vec::new();
};
items.iter().filter_map(Value::as_int).collect()
}
fn sorting_dispatcher() -> Dispatcher {
let ws = Arc::new(
check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("merge_sort", |args| {
let mut items = ints(args.first().unwrap_or(&Value::Null));
items.sort_unstable();
Ok(Value::List(items.into_iter().map(Value::Int).collect()))
});
registry.register_native_sync("bubble_sort", |args| {
let items = bubble(ints(args.first().unwrap_or(&Value::Null)));
Ok(Value::List(items.into_iter().map(Value::Int).collect()))
});
registry
.register(Implementation::new(
"sort.merge",
q("demo::sort"),
here(),
"merge_sort",
ImplProfile::new(BigO::ONLogN, BigO::ON),
))
.unwrap();
registry
.register(Implementation::new(
"sort.bubble",
q("demo::sort"),
here(),
"bubble_sort",
ImplProfile::new(BigO::ON2, BigO::O1),
))
.unwrap();
Dispatcher::new(ws, Arc::new(registry))
}
async fn sort_with(policy: Policy) -> Invocation {
sorting_dispatcher()
.call(&q("demo::sort"), vec![list(&[3, 1, 2])], &policy)
.await
.expect("answers")
}
fn list(items: &[i64]) -> Value {
Value::List(items.iter().copied().map(Value::Int).collect())
}
fn request_dispatcher() -> Dispatcher {
let ws = Arc::new(
check_workspace(
Workspace::from_json(
r#"{"universes":[
{"name":"node","functions":[{"name":"fetch","ret":"str","params":[
{"name":"url","ty":"str"},{"name":"retries","ty":"i64"}]}]},
{"name":"browser","functions":[{"name":"get","ret":"str","params":[
{"name":"attempts","ty":"i64"},{"name":"getUrl","ty":"str"}]}]}],
"links":[{"name":"fetch_is_get","from":"node::fetch","to":"browser::get",
"kind":{"k":"equivalent"}}]}"#,
)
.expect("reads"),
)
.expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("node_fetch", |args| {
let url = args.first().and_then(Value::as_str).unwrap_or("?");
let retries = args.get(1).and_then(Value::as_int).unwrap_or(-1);
Ok(Value::Str(format!("{url} x{retries}")))
});
registry
.register(Implementation::new(
"fetch.node",
q("node::fetch"),
here(),
"node_fetch",
ImplProfile::new(BigO::O1, BigO::O1),
))
.unwrap();
Dispatcher::new(ws, Arc::new(registry))
}
#[tokio::test]
async fn a_proof_of_an_equivalent_proposition_gets_the_arguments_its_own_way_round() {
let dispatcher = request_dispatcher();
let answered = dispatcher
.call(
&q("browser::get"),
vec![Value::Int(3), Value::Str("https://x".into())],
&Policy::Default,
)
.await
.expect("the node proof answers the browser's call");
assert_eq!(answered.implementation.as_str(), "fetch.node");
assert_eq!(
answered.value,
Value::Str("https://x x3".into()),
"the URL went where the proof reads it"
);
let direct = dispatcher
.call(
&q("node::fetch"),
vec![Value::Str("https://x".into()), Value::Int(3)],
&Policy::Default,
)
.await
.expect("answers its own proposition");
assert_eq!(direct.value, answered.value, "and the same call either way");
}
#[tokio::test]
async fn pinning_a_proof_of_an_equivalent_proposition_still_reorders() {
let answered = request_dispatcher()
.call(
&q("browser::get"),
vec![Value::Int(1), Value::Str("https://y".into())],
&Policy::Pinned(ImplId::new("fetch.node")),
)
.await
.expect("answers");
assert_eq!(answered.value, Value::Str("https://y x1".into()));
}
#[tokio::test]
async fn a_generic_proposition_is_answered_by_a_proof_of_its_equivalent() {
let ws = Arc::new(
check_workspace(
Workspace::from_json(
r#"{"universes":[
{"name":"py","functions":[{"name":"konst",
"params_decl":[{"name":"A"},{"name":"B"}],
"params":[{"name":"x","ty":{"k":"param","name":"A"}},
{"name":"y","ty":{"k":"param","name":"B"}}],
"ret":{"k":"param","name":"A"}}]},
{"name":"js","functions":[{"name":"always",
"params_decl":[{"name":"Y"},{"name":"X"}],
"params":[{"name":"ignored","ty":{"k":"param","name":"Y"}},
{"name":"kept","ty":{"k":"param","name":"X"}}],
"ret":{"k":"param","name":"X"}}]}],
"links":[{"name":"konst_is_always","from":"py::konst","to":"js::always",
"kind":{"k":"equivalent"}}]}"#,
)
.expect("reads"),
)
.expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("py_konst", |args| Ok(args[0].clone()));
registry
.register(Implementation::new(
"konst.py",
q("py::konst"),
here(),
"py_konst",
ImplProfile::new(BigO::O1, BigO::O1),
))
.unwrap();
let dispatcher = Dispatcher::new(ws, Arc::new(registry));
let answered = dispatcher
.call_at(
&q("js::always"),
&[Type::String, Type::I64],
vec![Value::Str("dropped".into()), Value::Int(7)],
&Policy::Default,
)
.await
.expect("the proof of konst answers, checked against always<str, i64>");
assert_eq!(answered.implementation.as_str(), "konst.py");
assert_eq!(answered.value, Value::Int(7));
}
#[tokio::test]
async fn asking_for_speed_and_asking_for_memory_choose_differently() {
let fast = sort_with(Policy::Fastest).await;
let frugal = sort_with(Policy::MinMemory).await;
assert_eq!(fast.implementation.as_str(), "sort.merge");
assert_eq!(frugal.implementation.as_str(), "sort.bubble");
}
#[tokio::test]
async fn and_both_give_the_same_answer() {
let fast = sort_with(Policy::Fastest).await;
let frugal = sort_with(Policy::MinMemory).await;
assert_eq!(fast.value, list(&[1, 2, 3]));
assert_eq!(
fast.value, frugal.value,
"which proof ran should not change what is true"
);
}
#[tokio::test]
async fn a_caller_can_see_what_was_considered_and_why() {
let chosen = sort_with(Policy::Fastest).await;
assert_eq!(chosen.considered.len(), 1, "the first one worked");
assert_eq!(chosen.considered[0].outcome, Outcome::Answered);
assert_eq!(chosen.environment, here());
let ranked: Vec<String> = sorting_dispatcher()
.candidates(&q("demo::sort"), &Policy::MinMemory)
.iter()
.map(|i| i.id.to_string())
.collect();
assert_eq!(ranked, ["sort.bubble", "sort.merge"]);
}
#[tokio::test]
async fn the_default_stays_in_the_process_where_it_can() {
let ws = Arc::new(
check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("bubble_sort", |args| {
Ok(Value::List(
bubble(ints(&args[0])).into_iter().map(Value::Int).collect(),
))
});
registry
.add_environment(Environment::subprocess("py", "python", "python3", &[]))
.unwrap();
registry
.register(Implementation::new(
"sort.py_merge",
q("demo::sort"),
Ident::new("py").unwrap(),
"merge_sort",
ImplProfile::new(BigO::ONLogN, BigO::ON),
))
.unwrap();
registry
.register(Implementation::new(
"sort.here_bubble",
q("demo::sort"),
here(),
"bubble_sort",
ImplProfile::new(BigO::ON2, BigO::O1),
))
.unwrap();
let dispatcher = Dispatcher::new(ws, Arc::new(registry));
let ranked: Vec<String> = dispatcher
.candidates(&q("demo::sort"), &Policy::Default)
.iter()
.map(|i| i.id.to_string())
.collect();
assert_eq!(
ranked[0], "sort.here_bubble",
"starting a process costs more than the difference in complexity, \
for the sizes most calls carry"
);
let ranked: Vec<String> = dispatcher
.candidates(&q("demo::sort"), &Policy::Fastest)
.iter()
.map(|i| i.id.to_string())
.collect();
assert_eq!(
ranked[0], "sort.py_merge",
"asked for speed, the better algorithm wins wherever it lives"
);
}
#[tokio::test]
async fn a_pinned_proof_is_the_one_that_runs() {
let pinned = sorting_dispatcher()
.call(
&q("demo::sort"),
vec![list(&[2, 1])],
&Policy::Pinned(ImplId::new("sort.bubble")),
)
.await
.expect("answers");
assert_eq!(pinned.implementation.as_str(), "sort.bubble");
}
#[tokio::test]
async fn pinning_something_that_proves_nothing_fails_rather_than_substituting() {
let err = sorting_dispatcher()
.call(
&q("demo::sort"),
vec![list(&[1])],
&Policy::Pinned(ImplId::new("sort.nonexistent")),
)
.await
.unwrap_err();
assert!(
matches!(err, DispatchError::Unusable { .. }),
"asking for one thing and getting another would be worse: {err}"
);
}
#[tokio::test]
async fn a_proposition_nobody_proves_says_so() {
let ws = Arc::new(
check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
);
let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
assert!(matches!(
dispatcher
.call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
.await,
Err(DispatchError::NoImplementation(_))
));
}
#[tokio::test]
async fn arguments_are_checked_before_anything_runs() {
let err = sorting_dispatcher()
.call(
&q("demo::sort"),
vec![Value::Str("not a list".into())],
&Policy::Default,
)
.await
.unwrap_err();
assert!(
matches!(err, DispatchError::BadArgument { index: 0, .. }),
"{err}"
);
}
#[tokio::test]
async fn the_wrong_number_of_arguments_is_caught() {
let err = sorting_dispatcher()
.call(&q("demo::sort"), vec![], &Policy::Default)
.await
.unwrap_err();
assert!(matches!(
err,
DispatchError::Arity {
expected: 1,
got: 0,
..
}
));
}
const BUDGET_WS: &str = r#"{"universes":[{"name":"demo","functions":[
{"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
"time":"o_n_log_n","space":"o1"}]}]}"#;
fn budget_dispatcher(registry: Registry) -> Dispatcher {
let ws = Arc::new(
check_workspace(Workspace::from_json(BUDGET_WS).expect("reads")).expect("checks"),
);
Dispatcher::new(ws, Arc::new(registry))
}
fn sorting_proof(registry: &mut Registry, id: &str, profile: ImplProfile) {
registry.register_native_sync(id, |args| Ok(args[0].clone()));
registry
.register(Implementation::new(
format!("sort.{id}").as_str(),
q("demo::sort"),
here(),
id,
profile,
))
.unwrap();
}
#[tokio::test]
async fn a_proof_that_claims_more_than_the_proposition_allows_is_not_asked() {
let mut registry = Registry::new();
sorting_proof(
&mut registry,
"bubble",
ImplProfile::new(BigO::ON2, BigO::O1),
);
let err = budget_dispatcher(registry)
.call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
.await
.unwrap_err();
let DispatchError::NoneAvailable { skipped, .. } = err else {
panic!("expected the claim to be ruled out");
};
assert!(
skipped
.iter()
.any(|s| s.contains("allows at most O(n log n)")),
"{skipped:?}"
);
}
#[tokio::test]
async fn a_proof_within_the_budget_answers_and_an_unnamed_claim_does_not() {
let mut registry = Registry::new();
sorting_proof(
&mut registry,
"merge",
ImplProfile::new(BigO::ONLogN, BigO::O1),
);
let done = budget_dispatcher(registry)
.call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
.await
.expect("the claim fits the budget");
assert_eq!(done.implementation.to_string(), "sort.merge");
let mut registry = Registry::new();
sorting_proof(
&mut registry,
"vague",
ImplProfile::new(BigO::Custom("usually fast".into()), BigO::O1),
);
assert!(
budget_dispatcher(registry)
.call(&q("demo::sort"), vec![list(&[2, 1])], &Policy::Default)
.await
.is_err(),
"a claim with no rank cannot be shown to fit a bound"
);
}
const WINDOW_WS: &str = r#"{"universes":[{"name":"demo","functions":[
{"name":"fetch","params":[{"name":"url","ty":"str"}],
"ret":{"k":"bounded","of":{"k":"future","of":"str"},"wait":{"min":20,"max":200}}}]}]}"#;
fn window_dispatcher(registry: Registry) -> Dispatcher {
let ws = Arc::new(
check_workspace(Workspace::from_json(WINDOW_WS).expect("reads")).expect("checks"),
);
Dispatcher::new(ws, Arc::new(registry))
}
#[tokio::test]
async fn a_proof_that_delivers_inside_its_window_answers() {
let mut registry = Registry::new();
registry.register_native_sync("steady", |_| {
std::thread::sleep(Duration::from_millis(60));
Ok(Value::Str("page".into()))
});
registry
.register(Implementation::new(
"fetch.steady",
q("demo::fetch"),
here(),
"steady",
ImplProfile::new(BigO::O1, BigO::O1),
))
.unwrap();
let done = window_dispatcher(registry)
.call(
&q("demo::fetch"),
vec![Value::Str("https://example.com".into())],
&Policy::Default,
)
.await
.expect("it delivers inside the window");
assert!(matches!(done.value, Value::Str(ref s) if s == "page"));
}
#[tokio::test]
async fn a_proof_that_misses_the_window_is_passed_over_for_one_that_meets_it() {
let mut registry = Registry::new();
registry.register_native_sync("late", |_| {
std::thread::sleep(Duration::from_millis(300));
Ok(Value::Str("late".into()))
});
registry.register_native_sync("prompt", |_| {
std::thread::sleep(Duration::from_millis(50));
Ok(Value::Str("prompt".into()))
});
registry
.register(Implementation::new(
"fetch.late",
q("demo::fetch"),
here(),
"late",
ImplProfile::new(BigO::O1, BigO::O1),
))
.unwrap();
registry
.register(Implementation::new(
"fetch.prompt",
q("demo::fetch"),
here(),
"prompt",
ImplProfile::new(BigO::ON, BigO::ON),
))
.unwrap();
let done = window_dispatcher(registry)
.call(
&q("demo::fetch"),
vec![Value::Str("https://example.com".into())],
&Policy::Fastest,
)
.await
.expect("the prompt one meets the window");
assert_eq!(done.implementation.to_string(), "fetch.prompt");
assert!(
done.considered.iter().any(|c| matches!(
&c.outcome,
Outcome::Failed(why) if why.contains("after the window closes")
)),
"the late answer is recorded, not hidden"
);
}
#[tokio::test]
async fn a_window_nothing_meets_says_which_end_it_missed() {
let mut registry = Registry::new();
registry.register_native_sync("instant", |_| Ok(Value::Str("too soon".into())));
registry
.register(Implementation::new(
"fetch.instant",
q("demo::fetch"),
here(),
"instant",
ImplProfile::new(BigO::O1, BigO::O1),
))
.unwrap();
let err = window_dispatcher(registry)
.call(
&q("demo::fetch"),
vec![Value::Str("https://example.com".into())],
&Policy::Default,
)
.await
.unwrap_err();
let DispatchError::NoneAvailable { skipped, .. } = err else {
panic!("expected no proof to meet the window, got {err}");
};
assert!(
skipped
.iter()
.any(|s| s.contains("before the window opens")),
"{skipped:?}"
);
}
#[tokio::test]
async fn a_proof_that_returns_the_wrong_thing_is_caught_and_never_excused() {
let ws = Arc::new(
check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("liar", |_| Ok(Value::Str("not a list at all".into())));
registry.register_native_sync("honest", |args| Ok(args[0].clone()));
registry
.register(Implementation::new(
"sort.liar",
q("demo::sort"),
here(),
"liar",
ImplProfile::new(BigO::O1, BigO::O1),
))
.unwrap();
registry
.register(Implementation::new(
"sort.honest",
q("demo::sort"),
here(),
"honest",
ImplProfile::new(BigO::ON, BigO::ON),
))
.unwrap();
let dispatcher = Dispatcher::new(ws, Arc::new(registry)).with_options(Options {
fall_back: true,
..Options::default()
});
let err = dispatcher
.call(&q("demo::sort"), vec![list(&[1])], &Policy::Fastest)
.await
.unwrap_err();
assert!(
matches!(err, DispatchError::BadResult { .. }),
"even with fallback on, a broken proof must not be quietly replaced: {err}"
);
}
#[tokio::test]
async fn a_proof_of_a_stronger_claim_answers_the_weaker_one() {
let ws = Arc::new(
check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("merge_sort", |args| {
let mut items = ints(&args[0]);
items.sort_unstable();
Ok(Value::List(items.into_iter().map(Value::Int).collect()))
});
registry
.register(Implementation::new(
"mergesort.rust",
q("demo::mergesort"),
here(),
"merge_sort",
ImplProfile::new(BigO::ONLogN, BigO::ON),
))
.unwrap();
let answer = Dispatcher::new(ws, Arc::new(registry))
.call(&q("demo::sort"), vec![list(&[3, 1, 2])], &Policy::Default)
.await
.expect("a proof of the stronger claim proves this one");
assert_eq!(answer.implementation.as_str(), "mergesort.rust");
assert_eq!(answer.value, list(&[1, 2, 3]));
}
#[tokio::test]
async fn an_environment_that_cannot_be_reached_is_reported_with_the_reason() {
let ws = Arc::new(
check_workspace(Workspace::from_json(SORT_WS).expect("reads")).expect("checks"),
);
let mut registry = Registry::new();
registry
.add_environment(Environment::subprocess(
"missing",
"python",
"unitype_no_such_interpreter",
&[],
))
.unwrap();
registry
.register(Implementation::new(
"sort.elsewhere",
q("demo::sort"),
Ident::new("missing").unwrap(),
"bubble_sort",
ImplProfile::new(BigO::ON2, BigO::O1),
))
.unwrap();
let err = Dispatcher::new(ws, Arc::new(registry))
.call(&q("demo::sort"), vec![list(&[1])], &Policy::Default)
.await
.unwrap_err();
let message = err.to_string();
assert!(message.contains("sort.elsewhere"), "{message}");
assert!(
message.contains("could not start"),
"the reason should be the actual one: {message}"
);
}
#[tokio::test]
async fn a_body_that_calls_out_is_answered_by_the_dispatcher() {
let ws = Arc::new(
check_workspace(
Workspace::from_json(
r#"{"universes":[{"name":"demo","functions":[
{"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
{"name":"sorted_twice","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]",
"body":{"k":"call","sig":"demo::sort","args":[
{"k":"call","sig":"demo::sort","args":[{"k":"var","name":"xs"}]}]}}]}]}"#,
)
.expect("reads"),
)
.expect("checks"),
);
let mut registry = Registry::new();
registry.register_bodies(&ws).unwrap();
registry.register_native_sync("merge_sort", |args| {
let mut items = ints(&args[0]);
items.sort_unstable();
Ok(Value::List(items.into_iter().map(Value::Int).collect()))
});
registry
.register(Implementation::new(
"sort.merge",
q("demo::sort"),
here(),
"merge_sort",
ImplProfile::new(BigO::ONLogN, BigO::ON),
))
.unwrap();
let answer = Dispatcher::new(ws, Arc::new(registry))
.call(
&q("demo::sorted_twice"),
vec![list(&[3, 1, 2])],
&Policy::Default,
)
.await
.expect("answers");
assert_eq!(answer.value, list(&[1, 2, 3]));
assert!(
answer.implementation.as_str().ends_with("#body"),
"the body proved it, and the dispatcher answered what the body asked"
);
}
const GENERIC_WS: &str = r#"{"universes":[{"name":"demo","functions":[
{"name":"reverse","params_decl":[{"name":"T"}],
"params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
"ret":{"k":"list","of":{"k":"param","name":"T"}}}]}]}"#;
fn reversing_dispatcher() -> Dispatcher {
let ws = Arc::new(
check_workspace(Workspace::from_json(GENERIC_WS).expect("reads")).expect("checks"),
);
let mut registry = Registry::new();
registry.register_native_sync("reverse", |mut args| {
let Value::List(items) = args.remove(0) else {
return Err(ExecError::Untyped("expected a list".into()));
};
Ok(Value::List(items.into_iter().rev().collect()))
});
registry
.register(Implementation::new(
"reverse.here",
q("demo::reverse"),
here(),
"reverse",
ImplProfile::new(BigO::ON, BigO::ON),
))
.unwrap();
Dispatcher::new(ws, Arc::new(registry))
}
#[tokio::test]
async fn a_generic_proposition_is_called_at_a_type() {
let dispatcher = reversing_dispatcher();
let words = Value::List(vec![Value::Str("a".into()), Value::Str("b".into())]);
let at_strings = dispatcher
.call_at(
&q("demo::reverse"),
&[Type::String],
vec![words],
&Policy::Default,
)
.await
.expect("answers");
assert_eq!(
at_strings.value,
Value::List(vec![Value::Str("b".into()), Value::Str("a".into())])
);
let at_ints = dispatcher
.call_at(
&q("demo::reverse"),
&[Type::I64],
vec![list(&[1, 2])],
&Policy::Default,
)
.await
.expect("answers");
assert_eq!(at_ints.value, list(&[2, 1]));
}
#[tokio::test]
async fn a_generic_proposition_called_without_its_type_says_what_is_missing() {
let err = reversing_dispatcher()
.call(&q("demo::reverse"), vec![list(&[1, 2])], &Policy::Default)
.await
.unwrap_err();
assert!(
matches!(
err,
DispatchError::TypeArity {
expected: 1,
got: 0,
..
}
),
"{err}"
);
}
#[tokio::test]
async fn a_generic_proposition_is_not_asked_at_a_type_its_bound_rules_out() {
let ws = Arc::new(
check_workspace(
Workspace::from_json(
r#"{"universes":[{"name":"demo",
"types":[{"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
{"k":"struct","name":"Person","implements":["Named"],
"fields":[{"name":"name","ty":"str"}]}],
"functions":[{"name":"first_named",
"params_decl":[{"name":"T","bounds":["Named"]}],
"params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
"ret":{"k":"optional","of":{"k":"param","name":"T"}}}]}]}"#,
)
.expect("reads"),
)
.expect("checks"),
);
let dispatcher = Dispatcher::new(ws, Arc::new(Registry::new()));
let person = Type::Ref(unitype_core::ir::TypeRef::qualified(
Ident::new("demo").unwrap(),
Ident::new("Person").unwrap(),
));
let err = dispatcher
.call_at(
&q("demo::first_named"),
&[Type::I64],
vec![list(&[1])],
&Policy::Default,
)
.await
.unwrap_err();
assert!(
matches!(&err, DispatchError::BoundNotMet { param, .. } if param.as_str() == "T"),
"an integer has no name: {err}"
);
let err = dispatcher
.call_at(
&q("demo::first_named"),
&[person],
vec![Value::List(vec![])],
&Policy::Default,
)
.await
.unwrap_err();
assert!(matches!(err, DispatchError::NoImplementation(_)), "{err}");
}
#[tokio::test]
async fn the_boundary_is_checked_at_the_type_the_call_named() {
let err = reversing_dispatcher()
.call_at(
&q("demo::reverse"),
&[Type::String],
vec![list(&[1, 2])],
&Policy::Default,
)
.await
.unwrap_err();
assert!(
matches!(err, DispatchError::BadArgument { index: 0, .. }),
"{err}"
);
}
}