Skip to main content

unitype_runtime/
interpret.rs

1//! Running a constructive proof.
2//!
3//! A signature carrying a body can be answered without anyone implementing it:
4//! the body *is* the implementation, and this walks it. That makes every
5//! derived bridge runnable the moment it is derived, with no code generated
6//! and no language involved.
7//!
8//! The language is total — no recursion, no unbounded loops, and a call graph
9//! the checker has already shown to be acyclic — so evaluation terminates. The
10//! depth limit here is a backstop for a body that reached this point without
11//! being checked, not something a well-formed body can hit.
12//!
13//! Calls out to other signatures go back through the dispatcher rather than
14//! being resolved here, so a body that calls `sort` gets whichever proof of
15//! `sort` the current policy prefers. A body says what to compute; it does not
16//! decide who computes it.
17
18use std::collections::HashMap;
19use std::future::Future;
20use std::pin::Pin;
21
22use std::cmp::Ordering;
23
24use unitype_core::check::CheckedWorkspace;
25use unitype_core::ir::{Expr, Functor, PrimOp};
26use unitype_core::value::Value;
27use unitype_core::{Ident, QualifiedName};
28
29use crate::conform::alike;
30use crate::error::ExecError;
31
32/// A future that can be held in a trait object.
33pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
34
35/// How a body reaches other signatures.
36///
37/// The interpreter does not choose implementations; it asks. That keeps policy
38/// in one place and means a body written once benefits from a faster proof
39/// appearing later.
40pub trait Calls: Send + Sync {
41    /// Invokes a signature and returns what it produced.
42    fn call<'a>(
43        &'a self,
44        sig: &'a QualifiedName,
45        args: Vec<Value>,
46    ) -> BoxFuture<'a, Result<Value, ExecError>>;
47}
48
49/// A world in which nothing can be called.
50///
51/// Enough for a body that only rearranges what it was given, which is most
52/// derived bridges.
53pub struct NoCalls;
54
55impl Calls for NoCalls {
56    fn call<'a>(
57        &'a self,
58        sig: &'a QualifiedName,
59        _args: Vec<Value>,
60    ) -> BoxFuture<'a, Result<Value, ExecError>> {
61        Box::pin(async move { Err(ExecError::UnknownSignature(sig.clone())) })
62    }
63}
64
65/// The names bound where an expression is being evaluated.
66pub type Scope = HashMap<Ident, Value>;
67
68/// How deep evaluation may go before giving up.
69const MAX_DEPTH: usize = 256;
70
71/// Runs a body with its parameters bound.
72pub async fn eval(
73    ws: &CheckedWorkspace,
74    expr: &Expr,
75    scope: Scope,
76    calls: &dyn Calls,
77) -> Result<Value, ExecError> {
78    run(ws, expr, &scope, calls, 0).await
79}
80
81/// Runs the body of a signature against positional arguments.
82pub async fn eval_signature(
83    ws: &CheckedWorkspace,
84    sig: &QualifiedName,
85    args: Vec<Value>,
86    calls: &dyn Calls,
87) -> Result<Value, ExecError> {
88    let Some(declared) = ws.sig(sig) else {
89        return Err(ExecError::UnknownSignature(sig.clone()));
90    };
91    let Some(body) = &declared.body else {
92        return Err(ExecError::NotRegistered(sig.to_string()));
93    };
94    let scope: Scope = declared
95        .params
96        .iter()
97        .map(|p| p.name.clone())
98        .zip(args)
99        .collect();
100    eval(ws, body, scope, calls).await
101}
102
103fn run<'a>(
104    ws: &'a CheckedWorkspace,
105    expr: &'a Expr,
106    scope: &'a Scope,
107    calls: &'a dyn Calls,
108    depth: usize,
109) -> BoxFuture<'a, Result<Value, ExecError>> {
110    Box::pin(async move {
111        if depth > MAX_DEPTH {
112            return Err(ExecError::TooDeep);
113        }
114
115        match expr {
116            Expr::Lit { value } => Ok(value.clone()),
117
118            Expr::Var { name } => scope
119                .get(name)
120                .cloned()
121                .ok_or_else(|| ExecError::Unbound(name.to_string())),
122
123            Expr::Field { of, name } => {
124                let subject = run(ws, of, scope, calls, depth + 1).await?;
125                match &subject {
126                    // A key that is not there means the field was absent, which
127                    // is the same state as null throughout this system. The
128                    // checker has already established that the field exists on
129                    // the type, so this cannot be a misspelling.
130                    Value::Record(fields) => {
131                        Ok(fields.get(name.as_str()).cloned().unwrap_or(Value::Null))
132                    }
133                    other => Err(ExecError::NoSuchField {
134                        value: other.kind_name().to_string(),
135                        field: name.to_string(),
136                    }),
137                }
138            }
139
140            Expr::MakeRecord { fields, .. } => {
141                let mut out = indexmap::IndexMap::with_capacity(fields.len());
142                for init in fields {
143                    out.insert(
144                        init.name.to_string(),
145                        run(ws, &init.value, scope, calls, depth + 1).await?,
146                    );
147                }
148                Ok(Value::Record(out))
149            }
150
151            Expr::MakeList { items } => {
152                let mut out = Vec::with_capacity(items.len());
153                for item in items {
154                    out.push(run(ws, item, scope, calls, depth + 1).await?);
155                }
156                Ok(Value::List(out))
157            }
158
159            Expr::MakeTuple { items } => {
160                let mut out = Vec::with_capacity(items.len());
161                for item in items {
162                    out.push(run(ws, item, scope, calls, depth + 1).await?);
163                }
164                Ok(Value::Tuple(out))
165            }
166
167            Expr::MakeVariant { tag, value, .. } => {
168                let payload = match value {
169                    Some(v) => run(ws, v, scope, calls, depth + 1).await?,
170                    None => Value::Null,
171                };
172                Ok(Value::variant(tag.to_string(), payload))
173            }
174
175            Expr::Call { sig, args } => {
176                let mut evaluated = Vec::with_capacity(args.len());
177                for arg in args {
178                    evaluated.push(run(ws, arg, scope, calls, depth + 1).await?);
179                }
180                calls.call(sig, evaluated).await
181            }
182
183            Expr::Let { name, value, body } => {
184                let bound = run(ws, value, scope, calls, depth + 1).await?;
185                let mut inner = scope.clone();
186                inner.insert(name.clone(), bound);
187                run(ws, body, &inner, calls, depth + 1).await
188            }
189
190            Expr::If {
191                cond,
192                then,
193                otherwise,
194            } => {
195                let taken = match run(ws, cond, scope, calls, depth + 1).await? {
196                    Value::Bool(b) => b,
197                    other => {
198                        return Err(ExecError::Untyped(format!(
199                            "a condition must be a boolean, but this is {}",
200                            other.kind_name()
201                        )));
202                    }
203                };
204                let branch = if taken { then } else { otherwise };
205                run(ws, branch, scope, calls, depth + 1).await
206            }
207
208            Expr::MapThrough {
209                functor,
210                value,
211                var,
212                body,
213            } => {
214                let subject = run(ws, value, scope, calls, depth + 1).await?;
215                map_through(ws, *functor, subject, var, body, scope, calls, depth).await
216            }
217
218            Expr::Prim { op, args } => {
219                if args.len() != op.arity() {
220                    return Err(ExecError::Untyped(format!(
221                        "`{}` takes {} operand(s), not {}",
222                        op.token(),
223                        op.arity(),
224                        args.len()
225                    )));
226                }
227                // The second operand of `and` and `or` is only worth evaluating
228                // if the first did not already decide.
229                if matches!(op, PrimOp::And | PrimOp::Or) {
230                    let first = boolean(*op, run(ws, &args[0], scope, calls, depth + 1).await?)?;
231                    if first == (*op == PrimOp::Or) {
232                        return Ok(Value::Bool(first));
233                    }
234                    let second = boolean(*op, run(ws, &args[1], scope, calls, depth + 1).await?)?;
235                    return Ok(Value::Bool(second));
236                }
237                let mut operands = Vec::with_capacity(args.len());
238                for arg in args {
239                    operands.push(run(ws, arg, scope, calls, depth + 1).await?);
240                }
241                prim(*op, &operands)
242            }
243
244            Expr::Fold {
245                list,
246                init,
247                acc,
248                item,
249                body,
250                ..
251            } => {
252                let items = match run(ws, list, scope, calls, depth + 1).await? {
253                    Value::List(items) => items,
254                    other => {
255                        return Err(ExecError::Untyped(format!(
256                            "a fold goes through a list, but this is {}",
257                            other.kind_name()
258                        )));
259                    }
260                };
261                let mut carried = run(ws, init, scope, calls, depth + 1).await?;
262                for element in items {
263                    let mut inner = scope.clone();
264                    inner.insert(acc.clone(), carried);
265                    inner.insert(item.clone(), element);
266                    carried = run(ws, body, &inner, calls, depth + 1).await?;
267                }
268                Ok(carried)
269            }
270
271            Expr::Case {
272                value,
273                var,
274                some,
275                none,
276            } => match run(ws, value, scope, calls, depth + 1).await? {
277                Value::Null => run(ws, none, scope, calls, depth + 1).await,
278                present => {
279                    let mut inner = scope.clone();
280                    inner.insert(var.clone(), present);
281                    run(ws, some, &inner, calls, depth + 1).await
282                }
283            },
284
285            Expr::Match { value, arms, .. } => {
286                let (tag, payload) = match run(ws, value, scope, calls, depth + 1).await? {
287                    Value::Variant { tag, value } => (tag, *value),
288                    other => {
289                        return Err(ExecError::Untyped(format!(
290                            "a match takes apart a variant, but this is {}",
291                            other.kind_name()
292                        )));
293                    }
294                };
295                let Some(arm) = arms.iter().find(|a| a.tag.as_str() == tag) else {
296                    return Err(ExecError::Untyped(format!(
297                        "this match has no arm for `{tag}`"
298                    )));
299                };
300                match &arm.var {
301                    Some(var) => {
302                        let mut inner = scope.clone();
303                        inner.insert(var.clone(), payload);
304                        run(ws, &arm.body, &inner, calls, depth + 1).await
305                    }
306                    None => run(ws, &arm.body, scope, calls, depth + 1).await,
307                }
308            }
309        }
310    })
311}
312
313/// The boolean an operand of `and`, `or`, or `not` must be.
314fn boolean(op: PrimOp, value: Value) -> Result<bool, ExecError> {
315    match value {
316        Value::Bool(b) => Ok(b),
317        other => Err(ExecError::Untyped(format!(
318            "`{}` takes booleans, but this is {}",
319            op.token(),
320            other.kind_name()
321        ))),
322    }
323}
324
325/// Applies an operation to operands that have already been evaluated.
326fn prim(op: PrimOp, operands: &[Value]) -> Result<Value, ExecError> {
327    let refuse = || {
328        ExecError::Untyped(format!(
329            "`{}` cannot be applied to {}",
330            op.token(),
331            operands
332                .iter()
333                .map(Value::kind_name)
334                .collect::<Vec<_>>()
335                .join(" and ")
336        ))
337    };
338    let overflow = || ExecError::Overflow {
339        op: op.token().to_string(),
340    };
341
342    Ok(match (op, operands) {
343        // The same notion of "the same" conformance uses: values, not their
344        // spelling, so `2` and `2.0` are one number.
345        (PrimOp::Eq, [a, b]) => Value::Bool(alike(a, b, 0.0)),
346        (PrimOp::Ne, [a, b]) => Value::Bool(!alike(a, b, 0.0)),
347        (op, [a, b]) if op.is_ordering() => {
348            let ordering = order(a, b).ok_or_else(refuse)?;
349            Value::Bool(match op {
350                PrimOp::Lt => ordering.is_lt(),
351                PrimOp::Le => ordering.is_le(),
352                PrimOp::Gt => ordering.is_gt(),
353                _ => ordering.is_ge(),
354            })
355        }
356        (PrimOp::Add | PrimOp::Sub | PrimOp::Mul, [Value::Int(a), Value::Int(b)]) => {
357            let result = match op {
358                PrimOp::Add => a.checked_add(*b),
359                PrimOp::Sub => a.checked_sub(*b),
360                _ => a.checked_mul(*b),
361            };
362            Value::Int(result.ok_or_else(overflow)?)
363        }
364        (PrimOp::Add | PrimOp::Sub | PrimOp::Mul, [a, b]) => {
365            let (Some(a), Some(b)) = (float(a), float(b)) else {
366                return Err(refuse());
367            };
368            let result = match op {
369                PrimOp::Add => a + b,
370                PrimOp::Sub => a - b,
371                _ => a * b,
372            };
373            // The wire has no infinity to carry, so producing one is as much
374            // an overflow as an integer that no longer fits.
375            if !result.is_finite() {
376                return Err(overflow());
377            }
378            Value::Float(result)
379        }
380        (PrimOp::Neg, [Value::Int(a)]) => Value::Int(a.checked_neg().ok_or_else(overflow)?),
381        (PrimOp::Neg, [Value::Float(a)]) => Value::Float(-a),
382        (PrimOp::Not, [value]) => Value::Bool(!boolean(op, value.clone())?),
383        (PrimOp::Len, [Value::List(items)]) => Value::Int(items.len() as i64),
384        _ => return Err(refuse()),
385    })
386}
387
388/// Which way round two values are, if they can be put in order at all.
389///
390/// Strings are ordered by code point, which is what ordering their UTF-8 bytes
391/// gives, and what every backend is made to agree with.
392fn order(a: &Value, b: &Value) -> Option<Ordering> {
393    match (a, b) {
394        (Value::Int(x), Value::Int(y)) => Some(x.cmp(y)),
395        (Value::Str(x), Value::Str(y)) => Some(x.cmp(y)),
396        _ => float(a)?.partial_cmp(&float(b)?),
397    }
398}
399
400/// A number, as a float.
401fn float(value: &Value) -> Option<f64> {
402    match value {
403        Value::Int(i) => Some(*i as f64),
404        Value::Float(f) => Some(*f),
405        _ => None,
406    }
407}
408
409/// Applies a transformation inside whatever constructor holds the value.
410///
411/// What "inside" means is the functor's business: every element of a list, the
412/// value of an optional if there is one, the eventual result of a future. A
413/// future has already been awaited by the time a value reaches here, so it is
414/// the same as a present optional.
415#[allow(clippy::too_many_arguments)]
416async fn map_through(
417    ws: &CheckedWorkspace,
418    functor: Functor,
419    subject: Value,
420    var: &Ident,
421    body: &Expr,
422    scope: &Scope,
423    calls: &dyn Calls,
424    depth: usize,
425) -> Result<Value, ExecError> {
426    let apply = async |element: Value| -> Result<Value, ExecError> {
427        let mut inner = scope.clone();
428        inner.insert(var.clone(), element);
429        run(ws, body, &inner, calls, depth + 1).await
430    };
431
432    match (functor, subject) {
433        (Functor::List, Value::List(items)) => {
434            let mut out = Vec::with_capacity(items.len());
435            for item in items {
436                out.push(apply(item).await?);
437            }
438            Ok(Value::List(out))
439        }
440        // Absent stays absent. This is the whole reason the form exists: it
441        // reaches inside optionality without letting a body ask whether
442        // something is there.
443        (Functor::Optional | Functor::Future, Value::Null) => Ok(Value::Null),
444        (Functor::Optional | Functor::Future, present) => apply(present).await,
445        (functor, other) => Err(ExecError::Untyped(format!(
446            "cannot map through {} over {}",
447            functor.describe(),
448            other.kind_name()
449        ))),
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use unitype_core::Workspace;
457    use unitype_core::check::check_workspace;
458    use unitype_core::ir::Type;
459    use unitype_core::value::Value;
460
461    fn ws(json: &str) -> CheckedWorkspace {
462        check_workspace(Workspace::from_json(json).expect("reads")).expect("checks")
463    }
464
465    fn q(s: &str) -> QualifiedName {
466        s.parse().unwrap()
467    }
468
469    fn v(json: &str) -> Value {
470        Value::parse_json(json).expect("reads")
471    }
472
473    const TYPES: &str = r#"
474        {"k":"struct","name":"User","fields":[
475            {"name":"first","ty":"str"},{"name":"last","ty":"str"},
476            {"name":"nickname","ty":"str?"}]},
477        {"k":"struct","name":"Badge","fields":[
478            {"name":"label","ty":"str"},{"name":"adult","ty":"bool"}]}"#;
479
480    fn universe(functions: &str) -> CheckedWorkspace {
481        ws(&format!(
482            r#"{{"universes":[{{"name":"demo","types":[{TYPES}],"functions":[{functions}]}}]}}"#
483        ))
484    }
485
486    #[tokio::test]
487    async fn a_body_builds_what_it_said_it_would() {
488        let ws = universe(
489            r#"{"name":"badge_of","params":[{"name":"u","ty":"User"}],"ret":"Badge",
490                "body":{"k":"make_record","ty":"Badge","fields":[
491                    {"name":"label","value":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}},
492                    {"name":"adult","value":{"k":"lit","value":true}}]}}"#,
493        );
494        let user = v(r#"{"first":"Ada","last":"Lovelace"}"#);
495        let badge = eval_signature(&ws, &q("demo::badge_of"), vec![user], &NoCalls)
496            .await
497            .expect("runs");
498
499        assert_eq!(badge.get("label"), Some(&Value::Str("Ada".into())));
500        assert_eq!(badge.get("adult"), Some(&Value::Bool(true)));
501    }
502
503    #[tokio::test]
504    async fn what_a_body_produces_is_what_its_signature_promised() {
505        let ws = universe(
506            r#"{"name":"badge_of","params":[{"name":"u","ty":"User"}],"ret":"Badge",
507                "body":{"k":"make_record","ty":"Badge","fields":[
508                    {"name":"label","value":{"k":"field","of":{"k":"var","name":"u"},"name":"last"}},
509                    {"name":"adult","value":{"k":"lit","value":false}}]}}"#,
510        );
511        let badge = eval_signature(
512            &ws,
513            &q("demo::badge_of"),
514            vec![v(r#"{"first":"Ada","last":"Lovelace"}"#)],
515            &NoCalls,
516        )
517        .await
518        .expect("runs");
519
520        let badge_ty = Type::Ref(unitype_core::ir::TypeRef::qualified(
521            Ident::new("demo").unwrap(),
522            Ident::new("Badge").unwrap(),
523        ));
524        assert!(
525            ws.validate(&badge, &badge_ty).is_ok(),
526            "the body should produce a real Badge: {badge:?}"
527        );
528    }
529
530    #[tokio::test]
531    async fn a_binding_is_visible_in_what_follows_it() {
532        let ws = universe(
533            r#"{"name":"f","params":[{"name":"u","ty":"User"}],"ret":"str",
534                "body":{"k":"let","name":"n",
535                        "value":{"k":"field","of":{"k":"var","name":"u"},"name":"first"},
536                        "body":{"k":"var","name":"n"}}}"#,
537        );
538        let out = eval_signature(
539            &ws,
540            &q("demo::f"),
541            vec![v(r#"{"first":"Ada","last":"L"}"#)],
542            &NoCalls,
543        )
544        .await
545        .expect("runs");
546        assert_eq!(out, Value::Str("Ada".into()));
547    }
548
549    #[tokio::test]
550    async fn only_the_branch_that_was_taken_runs() {
551        // The untaken arm calls a signature that nothing here can answer. If
552        // both arms ran, this would fail rather than returning the fallback.
553        let ws = universe(
554            r#"{"name":"shout","params":[{"name":"s","ty":"str"}],"ret":"str"},
555               {"name":"f","params":[{"name":"u","ty":"User"}],"ret":"str",
556                "body":{"k":"if","cond":{"k":"lit","value":false},
557                        "then":{"k":"call","sig":"demo::shout",
558                                "args":[{"k":"field","of":{"k":"var","name":"u"},"name":"first"}]},
559                        "else":{"k":"lit","value":"fallback"}}}"#,
560        );
561        let out = eval_signature(
562            &ws,
563            &q("demo::f"),
564            vec![v(r#"{"first":"A","last":"B"}"#)],
565            &NoCalls,
566        )
567        .await
568        .expect("runs");
569        assert_eq!(out, Value::Str("fallback".into()));
570    }
571
572    #[tokio::test]
573    async fn a_field_that_was_not_sent_reads_as_absent() {
574        // Missing, null, and none are one state here, so a body reading an
575        // optional field that nobody sent gets absence rather than an error.
576        let ws = universe(
577            r#"{"name":"nick_raw","params":[{"name":"u","ty":"User"}],"ret":"str?",
578                "body":{"k":"field","of":{"k":"var","name":"u"},"name":"nickname"}}"#,
579        );
580        let out = eval_signature(
581            &ws,
582            &q("demo::nick_raw"),
583            vec![v(r#"{"first":"A","last":"B"}"#)],
584            &NoCalls,
585        )
586        .await
587        .expect("runs");
588        assert_eq!(out, Value::Null);
589    }
590
591    #[tokio::test]
592    async fn mapping_through_a_list_visits_every_element() {
593        let ws = universe(
594            r#"{"name":"names","params":[{"name":"us","ty":"[User]"}],"ret":"[str]",
595                "body":{"k":"map_through","functor":"list","value":{"k":"var","name":"us"},
596                        "var":"u",
597                        "body":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}}}"#,
598        );
599        let out = eval_signature(
600            &ws,
601            &q("demo::names"),
602            vec![v(
603                r#"[{"first":"Ada","last":"L"},{"first":"Grace","last":"H"}]"#,
604            )],
605            &NoCalls,
606        )
607        .await
608        .expect("runs");
609
610        assert_eq!(
611            out,
612            Value::List(vec![Value::Str("Ada".into()), Value::Str("Grace".into())])
613        );
614    }
615
616    #[tokio::test]
617    async fn mapping_through_an_empty_list_produces_an_empty_list() {
618        let ws = universe(
619            r#"{"name":"names","params":[{"name":"us","ty":"[User]"}],"ret":"[str]",
620                "body":{"k":"map_through","functor":"list","value":{"k":"var","name":"us"},
621                        "var":"u",
622                        "body":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}}}"#,
623        );
624        let out = eval_signature(&ws, &q("demo::names"), vec![v("[]")], &NoCalls)
625            .await
626            .expect("runs");
627        assert_eq!(out, Value::List(vec![]));
628    }
629
630    #[tokio::test]
631    async fn what_was_absent_stays_absent() {
632        let ws = universe(
633            r#"{"name":"nick","params":[{"name":"u","ty":"User"}],"ret":"str?",
634                "body":{"k":"map_through","functor":"optional",
635                        "value":{"k":"field","of":{"k":"var","name":"u"},"name":"nickname"},
636                        "var":"n","body":{"k":"var","name":"n"}}}"#,
637        );
638
639        let present = eval_signature(
640            &ws,
641            &q("demo::nick"),
642            vec![v(r#"{"first":"A","last":"B","nickname":"Ace"}"#)],
643            &NoCalls,
644        )
645        .await
646        .expect("runs");
647        assert_eq!(present, Value::Str("Ace".into()));
648
649        let absent = eval_signature(
650            &ws,
651            &q("demo::nick"),
652            vec![v(r#"{"first":"A","last":"B"}"#)],
653            &NoCalls,
654        )
655        .await
656        .expect("runs");
657        assert_eq!(absent, Value::Null, "nothing was there to transform");
658    }
659
660    #[tokio::test]
661    async fn a_body_calling_another_signature_goes_back_out_to_ask() {
662        struct Shouts;
663        impl Calls for Shouts {
664            fn call<'a>(
665                &'a self,
666                _sig: &'a QualifiedName,
667                args: Vec<Value>,
668            ) -> BoxFuture<'a, Result<Value, ExecError>> {
669                Box::pin(async move {
670                    let Some(Value::Str(s)) = args.first() else {
671                        return Err(ExecError::Untyped("expected a string".into()));
672                    };
673                    Ok(Value::Str(s.to_uppercase()))
674                })
675            }
676        }
677
678        let ws = universe(
679            r#"{"name":"shout","params":[{"name":"s","ty":"str"}],"ret":"str"},
680               {"name":"loud_name","params":[{"name":"u","ty":"User"}],"ret":"str",
681                "body":{"k":"call","sig":"demo::shout",
682                        "args":[{"k":"field","of":{"k":"var","name":"u"},"name":"first"}]}}"#,
683        );
684        let out = eval_signature(
685            &ws,
686            &q("demo::loud_name"),
687            vec![v(r#"{"first":"Ada","last":"L"}"#)],
688            &Shouts,
689        )
690        .await
691        .expect("runs");
692        assert_eq!(out, Value::Str("ADA".into()));
693    }
694
695    #[tokio::test]
696    async fn a_signature_with_no_body_has_nothing_to_run() {
697        let ws = universe(r#"{"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}"#);
698        let err = eval_signature(&ws, &q("demo::sort"), vec![v("[3,1,2]")], &NoCalls)
699            .await
700            .unwrap_err();
701        assert!(
702            matches!(err, ExecError::NotRegistered(_)),
703            "sorting is a proposition someone has to prove: {err}"
704        );
705    }
706
707    /// The point of all of this: a bridge nobody wrote runs.
708    #[tokio::test]
709    async fn a_derived_bridge_runs_without_anyone_writing_it() {
710        let base = ws(r#"{"universes":[
711            {"name":"api","types":[{"k":"struct","name":"User","fields":[
712                {"name":"userId","ty":"str"},{"name":"age","ty":"i32"}]}]},
713            {"name":"db","types":[{"k":"struct","name":"UserRow","fields":[
714                {"name":"user_id","ty":"str"},{"name":"age","ty":"i64"}]}]}]}"#);
715
716        // Work out how one becomes the other...
717        let kind = base
718            .derive_link(&q("api::User"), &q("db::UserRow"), &[])
719            .expect("derives");
720
721        let mut workspace = base.workspace().clone();
722        workspace.links.push(unitype_core::link::Link {
723            name: Ident::new("user_row").unwrap(),
724            doc: None,
725            from: q("api::User"),
726            to: q("db::UserRow"),
727            kind,
728            derived: true,
729            meta: Default::default(),
730        });
731        let ws = check_workspace(workspace).expect("checks");
732
733        // ...turn that into a body, put it in the workspace, and run it.
734        let link = ws
735            .workspace()
736            .link(&Ident::new("user_row").unwrap())
737            .unwrap();
738        let bridge = ws.compile_link(link).expect("compiles").expect("succeeds");
739
740        let mut workspace = ws.workspace().clone();
741        workspace.universes[0].functions.push(bridge);
742        let ws = check_workspace(workspace).expect("the derived bridge checks");
743
744        let row = eval_signature(
745            &ws,
746            &q("api::user_row"),
747            vec![v(r#"{"userId":"u-1","age":37}"#)],
748            &NoCalls,
749        )
750        .await
751        .expect("runs");
752
753        assert_eq!(row.get("user_id"), Some(&Value::Str("u-1".into())));
754        assert_eq!(row.get("age"), Some(&Value::Int(37)));
755
756        let row_ty = Type::Ref(unitype_core::ir::TypeRef::qualified(
757            Ident::new("db").unwrap(),
758            Ident::new("UserRow").unwrap(),
759        ));
760        assert!(
761            ws.validate(&row, &row_ty).is_ok(),
762            "and what comes out really is a db::UserRow"
763        );
764    }
765
766    /// Bodies built from the forms that visit a list and take a value apart.
767    const FORMS: &str = r#"{"universes":[{"name":"demo","types":[
768        {"k":"struct","name":"Step","fields":[
769            {"name":"ok","ty":"bool"},{"name":"prev","ty":"i64"},{"name":"started","ty":"bool"}]},
770        {"k":"enum","name":"Size","variants":[{"name":"small"},{"name":"large","payload":"i64"}]}],
771      "functions":[
772        {"name":"total","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
773         "body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":0},
774                 "acc":"t","item":"x",
775                 "body":{"k":"prim","op":"add","args":[{"k":"var","name":"t"},{"k":"var","name":"x"}]}}},
776        {"name":"ordered","params":[{"name":"xs","ty":"[i64]"}],"ret":"bool",
777         "body":{"k":"field","name":"ok","of":
778           {"k":"fold","list":{"k":"var","name":"xs"},
779            "init":{"k":"make_record","ty":"Step","fields":[
780                {"name":"ok","value":{"k":"lit","value":true}},
781                {"name":"prev","value":{"k":"lit","value":0}},
782                {"name":"started","value":{"k":"lit","value":false}}]},
783            "acc":"s","item":"x",
784            "body":{"k":"make_record","ty":"Step","fields":[
785                {"name":"ok","value":{"k":"prim","op":"and","args":[
786                    {"k":"field","of":{"k":"var","name":"s"},"name":"ok"},
787                    {"k":"prim","op":"or","args":[
788                        {"k":"prim","op":"not","args":[{"k":"field","of":{"k":"var","name":"s"},"name":"started"}]},
789                        {"k":"prim","op":"le","args":[{"k":"field","of":{"k":"var","name":"s"},"name":"prev"},
790                                                      {"k":"var","name":"x"}]}]}]}},
791                {"name":"prev","value":{"k":"var","name":"x"}},
792                {"name":"started","value":{"k":"lit","value":true}}]}}}},
793        {"name":"note_or","params":[{"name":"n","ty":"str?"}],"ret":"str",
794         "body":{"k":"case","value":{"k":"var","name":"n"},"var":"it",
795                 "some":{"k":"var","name":"it"},"none":{"k":"lit","value":"none"}}},
796        {"name":"measure","params":[{"name":"s","ty":"Size"}],"ret":"i64",
797         "body":{"k":"match","ty":"Size","value":{"k":"var","name":"s"},"arms":[
798            {"tag":"small","body":{"k":"lit","value":0}},
799            {"tag":"large","var":"n","body":{"k":"prim","op":"mul","args":[
800                {"k":"var","name":"n"},{"k":"lit","value":2}]}}]}},
801        {"name":"boom","params":[],"ret":"bool"},
802        {"name":"careful","params":[],"ret":"bool",
803         "body":{"k":"prim","op":"and","args":[{"k":"lit","value":false},
804                                               {"k":"call","sig":"demo::boom","args":[]}]}},
805        {"name":"bigger","params":[{"name":"a","ty":"i64"}],"ret":"i64",
806         "body":{"k":"prim","op":"add","args":[{"k":"var","name":"a"},{"k":"lit","value":1}]}},
807        {"name":"before","params":[{"name":"a","ty":"str"},{"name":"b","ty":"str"}],"ret":"bool",
808         "body":{"k":"prim","op":"lt","args":[{"k":"var","name":"a"},{"k":"var","name":"b"}]}}]}]}"#;
809
810    async fn answer(sig: &str, args: &[&str]) -> Result<Value, ExecError> {
811        let ws = ws(FORMS);
812        eval_signature(&ws, &q(sig), args.iter().map(|a| v(a)).collect(), &NoCalls).await
813    }
814
815    #[tokio::test]
816    async fn a_fold_carries_a_value_through_a_list() {
817        assert_eq!(
818            answer("demo::total", &["[1,2,3,4]"]).await.unwrap(),
819            v("10")
820        );
821        assert_eq!(
822            answer("demo::total", &["[]"]).await.unwrap(),
823            v("0"),
824            "an empty list leaves the starting value as it was"
825        );
826    }
827
828    #[tokio::test]
829    async fn whether_a_list_is_in_order_can_be_said_with_a_fold() {
830        assert_eq!(
831            answer("demo::ordered", &["[1,2,2,5]"]).await.unwrap(),
832            v("true")
833        );
834        assert_eq!(
835            answer("demo::ordered", &["[3,1]"]).await.unwrap(),
836            v("false")
837        );
838        assert_eq!(answer("demo::ordered", &["[]"]).await.unwrap(), v("true"));
839    }
840
841    #[tokio::test]
842    async fn a_case_runs_the_arm_for_what_is_there() {
843        assert_eq!(
844            answer("demo::note_or", &["\"hi\""]).await.unwrap(),
845            v("\"hi\"")
846        );
847        assert_eq!(
848            answer("demo::note_or", &["null"]).await.unwrap(),
849            v("\"none\"")
850        );
851    }
852
853    #[tokio::test]
854    async fn a_match_runs_the_arm_for_the_variant_it_was_given() {
855        assert_eq!(
856            answer("demo::measure", &[r#"{"$tag":"large","value":21}"#])
857                .await
858                .unwrap(),
859            v("42")
860        );
861        assert_eq!(
862            answer("demo::measure", &[r#"{"$tag":"small"}"#])
863                .await
864                .unwrap(),
865            v("0")
866        );
867    }
868
869    #[tokio::test]
870    async fn the_second_half_of_an_and_runs_only_when_it_could_matter() {
871        // `boom` has no proof anywhere, so evaluating it would fail.
872        assert_eq!(answer("demo::careful", &[]).await.unwrap(), v("false"));
873    }
874
875    #[tokio::test]
876    async fn an_integer_that_no_longer_fits_is_a_failure_rather_than_a_wrap() {
877        let err = answer("demo::bigger", &[&i64::MAX.to_string()])
878            .await
879            .unwrap_err();
880        assert!(matches!(err, ExecError::Overflow { .. }), "{err}");
881    }
882
883    #[tokio::test]
884    async fn strings_are_ordered_by_code_point() {
885        // U+FF5E sorts before U+1F600 by code point. Comparing UTF-16 units,
886        // as JavaScript's `<` does, would put them the other way round.
887        assert_eq!(
888            answer("demo::before", &["\"\u{FF5E}\"", "\"\u{1F600}\""])
889                .await
890                .unwrap(),
891            v("true")
892        );
893    }
894}