Skip to main content

unitype_runtime/
parametric.rs

1//! Free theorems: what a generic proposition promises before any proof runs.
2//!
3//! A proof of `reverse<T> : [T] -> [T]` cannot look at a `T`. It was given no
4//! way to — no comparison, no field, no method, nothing but the shape around
5//! it — so whatever it does, it does the same way whatever `T` turns out to be.
6//! That is a theorem about *every* proof of the proposition, and it follows
7//! from the signature alone (Reynolds's abstraction theorem; Wadler's
8//! "Theorems for free!"). Two consequences can be checked by running a proof:
9//!
10//! - **Conservation.** Every `T` in the result was one of the `T`s in the
11//!   arguments. A proof cannot make one up, because it does not know what one
12//!   looks like.
13//! - **Naturality.** Relabelling the `T`s commutes with the proof: for any
14//!   `g`, `f(map g xs) = map g (f xs)`. What the proof does is a function of
15//!   shape, not of content.
16//!
17//! Neither needs anyone to say what the right answer is, and neither needs a
18//! vector file. The harness fills each `T` position with a distinct token,
19//! runs the proof, and reads off which token landed where. That checks
20//! conservation outright, and it predicts what the proof *must* say at any
21//! other type — so it runs again with the tokens relabelled: once as distinct
22//! strings, once all onto a single boolean, and once onto two integers, and
23//! checks that each answer is the first one relabelled the same way. A proof
24//! that sorts when handed integers, or compares two elements and branches, or
25//! only works at the one type its author had in mind, is caught by one of
26//! those.
27//!
28//! One type is enough to test a parametric proof at, which is the practical
29//! face of the theorem: there is no second type at which it could behave
30//! differently, so there is no second type to try.
31//!
32//! # What this does not cover
33//!
34//! A bounded parameter — `T: Identified` — *can* be looked at, through the
35//! bound, so a proof may lawfully treat one `T` differently from another, and
36//! the theorem weakens to naturality over relabellings that respect the bound.
37//! That is a later addition; here a bounded proposition is reported as not
38//! checkable rather than held to a law it need not obey. The same goes for a
39//! `T` under an untagged union, where a value does not say whether it is the
40//! `T`, and for parameters whose types cannot be filled from nothing, such as
41//! functions and interfaces.
42
43use std::collections::{BTreeMap, BTreeSet};
44use std::fmt;
45
46use unitype_core::check::{CheckedWorkspace, bind, substitute};
47use unitype_core::ir::{Field, FunctionSig, LiteralValue, Type, TypeDef, TypeRef, Variant};
48use unitype_core::value::Value;
49use unitype_core::{Ident, QualifiedName};
50
51use crate::conform::{alike, unavailable};
52use crate::dispatch::{Dispatcher, Policy};
53use crate::implementation::ImplId;
54
55/// How many shapes each proposition is tried at.
56const TRIALS: usize = 5;
57/// How long a list or map is in each trial.
58const SIZES: [usize; TRIALS] = [0, 1, 2, 3, 5];
59/// Tokens for one parameter are numbered from `param * TOKEN_STRIDE`, so a
60/// token says which parameter it stands for as well as which occurrence.
61const TOKEN_STRIDE: i64 = 1000;
62
63/// One of the laws a parametric proof is held to.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum Law {
66    /// Every `T` in the result came from the arguments.
67    Conservation,
68    /// Relabelling the `T`s commutes with the proof.
69    Naturality,
70}
71
72impl fmt::Display for Law {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(match self {
75            Law::Conservation => "conservation",
76            Law::Naturality => "naturality",
77        })
78    }
79}
80
81/// What became of one proof on one trial.
82#[derive(Clone, Debug, PartialEq)]
83pub enum Verdict {
84    /// It obeyed both laws.
85    Held,
86    /// It broke one.
87    Broken {
88        /// Which.
89        law: Law,
90        /// How, concretely.
91        detail: String,
92    },
93    /// It ran and failed before anything could be checked.
94    Failed(String),
95    /// It could not be run here.
96    Skipped(String),
97}
98
99impl Verdict {
100    /// Whether this counts against the proof.
101    pub fn is_against(&self) -> bool {
102        matches!(self, Verdict::Broken { .. } | Verdict::Failed(_))
103    }
104
105    /// A short description, for a report.
106    pub fn summary(&self) -> String {
107        match self {
108            Verdict::Held => "held".into(),
109            Verdict::Broken { law, detail } => format!("{law} broken: {detail}"),
110            Verdict::Failed(why) => format!("failed: {why}"),
111            Verdict::Skipped(why) => format!("skipped: {why}"),
112        }
113    }
114}
115
116/// One shape the proposition was tried at.
117#[derive(Clone, Debug)]
118pub struct Trial {
119    /// The arguments, written out, so a failure can be talked about.
120    pub name: String,
121    /// The arguments as given, with tokens where the `T`s are.
122    pub args: Vec<Value>,
123    /// What each proof did with them.
124    pub verdicts: BTreeMap<ImplId, Verdict>,
125}
126
127impl Trial {
128    /// Whether no proof broke a law here.
129    pub fn held(&self) -> bool {
130        self.verdicts.values().all(|v| !v.is_against())
131    }
132}
133
134/// How a proposition's free theorem fared across every proof and trial.
135#[derive(Clone, Debug)]
136pub struct Theorems {
137    /// The proposition.
138    pub signature: QualifiedName,
139    /// Its type parameters, in order.
140    pub params: Vec<Ident>,
141    /// Every proof that took part.
142    pub proofs: Vec<ImplId>,
143    /// Each shape tried.
144    pub trials: Vec<Trial>,
145}
146
147impl Theorems {
148    /// Whether every proof obeyed both laws on every trial.
149    pub fn held(&self) -> bool {
150        self.trials.iter().all(Trial::held)
151    }
152
153    /// The trials where some proof broke a law.
154    pub fn broken(&self) -> Vec<&Trial> {
155        self.trials.iter().filter(|t| !t.held()).collect()
156    }
157
158    /// The proposition with its parameters, as it would be said: `reverse<T>`.
159    pub fn heading(&self) -> String {
160        let params: Vec<String> = self.params.iter().map(ToString::to_string).collect();
161        format!("{}<{}>", self.signature, params.join(", "))
162    }
163}
164
165/// Why a proposition's free theorem could not be checked.
166#[derive(thiserror::Error, Debug)]
167pub enum ParametricError {
168    /// The proposition is not in the workspace.
169    #[error("`{0}` is not a proposition in this workspace")]
170    UnknownSignature(QualifiedName),
171    /// It has no type parameters, so there is nothing to be parametric in.
172    #[error("`{0}` has no type parameters, so it has no free theorem")]
173    NotGeneric(QualifiedName),
174    /// A parameter is bounded, so a proof may lawfully look at one.
175    #[error(
176        "`{sig}` bounds `{param}` by `{bound}`, so a proof may look at one; \
177         the free theorem for a bounded parameter is a later addition"
178    )]
179    Bounded {
180        /// The proposition.
181        sig: QualifiedName,
182        /// The bounded parameter.
183        param: Ident,
184        /// What bounds it.
185        bound: String,
186    },
187    /// Some part of the signature cannot be filled or read without help.
188    #[error("`{sig}` cannot be checked this way: {what} {why}")]
189    Unfillable {
190        /// The proposition.
191        sig: QualifiedName,
192        /// The type in the way.
193        what: String,
194        /// Why it is in the way.
195        why: String,
196    },
197    /// Nothing proves it, so there is nothing to hold to the theorem.
198    #[error("nothing proves `{0}`, so there is nothing to check")]
199    NoProofs(QualifiedName),
200}
201
202/// Whether a proposition has a free theorem this harness can check, and if
203/// not, why not.
204///
205/// Answered without running anything, so a caller can decide what to try.
206pub fn applies(ws: &CheckedWorkspace, name: &QualifiedName) -> Result<(), ParametricError> {
207    let sig = ws
208        .sig(name)
209        .ok_or_else(|| ParametricError::UnknownSignature(name.clone()))?;
210    plan(ws, name, sig).map(|_| ())
211}
212
213/// Holds every proof of a generic proposition to its free theorem.
214pub async fn check(
215    dispatcher: &Dispatcher,
216    name: &QualifiedName,
217) -> Result<Theorems, ParametricError> {
218    let ws = dispatcher.workspace();
219    let sig = ws
220        .sig(name)
221        .ok_or_else(|| ParametricError::UnknownSignature(name.clone()))?;
222    let params = plan(ws, name, sig)?;
223
224    let proofs: Vec<ImplId> = dispatcher
225        .candidates(name, &Policy::Default)
226        .iter()
227        .map(|i| i.id.clone())
228        .collect();
229    if proofs.is_empty() {
230        return Err(ParametricError::NoProofs(name.clone()));
231    }
232
233    let shape = Shape {
234        ws,
235        params: &params,
236    };
237    let ret = eventual(&sig.ret);
238    let at_tokens = vec![Type::I64; params.len()];
239
240    let mut trials = Vec::with_capacity(TRIALS);
241    for trial in 0..TRIALS {
242        let mut filler = shape.filler(trial);
243        let mut args = Vec::with_capacity(sig.params.len());
244        for param in &sig.params {
245            args.push(filler.fill(&param.ty).map_err(|u| u.at(name))?);
246        }
247        let given = shape.tokens_given(&args, sig);
248
249        let mut verdicts = BTreeMap::new();
250        for id in &proofs {
251            let verdict = judge(
252                dispatcher, name, sig, &shape, &ret, &at_tokens, &args, &given, id,
253            )
254            .await;
255            verdicts.insert(id.clone(), verdict);
256        }
257
258        trials.push(Trial {
259            name: describe(sig, &args),
260            args,
261            verdicts,
262        });
263    }
264
265    Ok(Theorems {
266        signature: name.clone(),
267        params,
268        proofs,
269        trials,
270    })
271}
272
273/// The parameters a proposition is parametric in, or why it cannot be held to
274/// its theorem.
275fn plan(
276    ws: &CheckedWorkspace,
277    name: &QualifiedName,
278    sig: &FunctionSig,
279) -> Result<Vec<Ident>, ParametricError> {
280    if sig.params_decl.is_empty() {
281        return Err(ParametricError::NotGeneric(name.clone()));
282    }
283    for decl in &sig.params_decl {
284        if let Some(bound) = decl.bounds.first() {
285            return Err(ParametricError::Bounded {
286                sig: name.clone(),
287                param: decl.name.clone(),
288                bound: bound.to_string(),
289            });
290        }
291    }
292    let params: Vec<Ident> = sig.params_decl.iter().map(|d| d.name.clone()).collect();
293    let shape = Shape {
294        ws,
295        params: &params,
296    };
297
298    // Filling is deterministic in the type, so if the first trial can be
299    // filled they all can.
300    let mut filler = shape.filler(0);
301    for param in &sig.params {
302        filler.fill(&param.ty).map_err(|u| u.at(name))?;
303    }
304    shape
305        .readable(&eventual(&sig.ret))
306        .map_err(|u| u.at(name))?;
307    Ok(params)
308}
309
310/// Runs one proof against one trial and says what it did.
311#[allow(clippy::too_many_arguments)]
312async fn judge(
313    dispatcher: &Dispatcher,
314    name: &QualifiedName,
315    sig: &FunctionSig,
316    shape: &Shape<'_>,
317    ret: &Type,
318    at_tokens: &[Type],
319    args: &[Value],
320    given: &[BTreeSet<i64>],
321    id: &ImplId,
322) -> Verdict {
323    let pinned = Policy::Pinned(id.clone());
324
325    let result = match dispatcher
326        .call_at(name, at_tokens, args.to_vec(), &pinned)
327        .await
328    {
329        Ok(invocation) => invocation.value,
330        Err(error) if unavailable(&error) => return Verdict::Skipped(error.to_string()),
331        Err(error) => return Verdict::Failed(error.to_string()),
332    };
333
334    // Conservation: every token that came back is one that went in, standing
335    // for the same parameter.
336    let mut stray = None;
337    let read = shape.map_params(&result, ret, &mut |param, value| {
338        let token = Token::decode(value);
339        if !token.is_some_and(|t| t.param == param && given[param].contains(&t.ordinal))
340            && stray.is_none()
341        {
342            stray = Some(format!(
343                "a `{}` came back that was never passed in: {}",
344                shape.params[param],
345                json(value)
346            ));
347        }
348        value.clone()
349    });
350    if let Err(why) = read {
351        return Verdict::Failed(format!("could not read the result: {why}"));
352    }
353    if let Some(detail) = stray {
354        return Verdict::Broken {
355            law: Law::Conservation,
356            detail,
357        };
358    }
359
360    // Naturality: relabel the tokens, run again, and the proof must have
361    // relabelled its own answer the same way.
362    for relabel in [Relabel::Strings, Relabel::Collapse, Relabel::Parity] {
363        let mut g = |param: usize, value: &Value| match Token::decode(value) {
364            Some(token) => relabel.apply(&shape.params[param], token),
365            None => value.clone(),
366        };
367        let mut relabelled = Vec::with_capacity(args.len());
368        for (arg, param) in args.iter().zip(&sig.params) {
369            match shape.map_params(arg, &param.ty, &mut g) {
370                Ok(value) => relabelled.push(value),
371                Err(why) => {
372                    return Verdict::Failed(format!("could not relabel an argument: {why}"));
373                }
374            }
375        }
376        let expected = match shape.map_params(&result, ret, &mut g) {
377            Ok(value) => value,
378            Err(why) => return Verdict::Failed(format!("could not relabel the result: {why}")),
379        };
380
381        let at = vec![relabel.at(); shape.params.len()];
382        match dispatcher.call_at(name, &at, relabelled, &pinned).await {
383            Ok(invocation) if alike(&invocation.value, &expected, 0.0) => {}
384            Ok(invocation) => {
385                return Verdict::Broken {
386                    law: Law::Naturality,
387                    detail: format!(
388                        "{}, it gave {}, but relabelling what it gave at {} requires {}",
389                        relabel.describe(shape.params),
390                        json(&invocation.value),
391                        Relabel::tokens(shape.params),
392                        json(&expected)
393                    ),
394                };
395            }
396            Err(error) if unavailable(&error) => return Verdict::Skipped(error.to_string()),
397            Err(error) => {
398                return Verdict::Broken {
399                    law: Law::Naturality,
400                    detail: format!("{}, {error}", relabel.describe(shape.params)),
401                };
402            }
403        }
404    }
405
406    Verdict::Held
407}
408
409/// A proof's eventual answer: what a future resolves to, or the type itself.
410fn eventual(ret: &Type) -> Type {
411    match ret {
412        Type::Future { of } => (**of).clone(),
413        other => other.clone(),
414    }
415}
416
417/// A trial, named by what was passed: `xs = [0, 1, 2]`.
418fn describe(sig: &FunctionSig, args: &[Value]) -> String {
419    if args.is_empty() {
420        return "no arguments".into();
421    }
422    sig.params
423        .iter()
424        .zip(args)
425        .map(|(p, a)| format!("{} = {}", p.name, json(a)))
426        .collect::<Vec<_>>()
427        .join(", ")
428}
429
430fn json(value: &Value) -> String {
431    value
432        .to_json_string()
433        .unwrap_or_else(|_| "<unwritable>".into())
434}
435
436/// A stand-in for one `T`: distinct from every other, and saying which
437/// parameter it stands for.
438#[derive(Clone, Copy, Debug, PartialEq, Eq)]
439struct Token {
440    param: usize,
441    ordinal: i64,
442}
443
444impl Token {
445    fn value(self) -> Value {
446        Value::Int(self.param as i64 * TOKEN_STRIDE + self.ordinal)
447    }
448
449    fn decode(value: &Value) -> Option<Token> {
450        let n = value.as_int()?;
451        (n >= 0).then_some(Token {
452            param: (n / TOKEN_STRIDE) as usize,
453            ordinal: n % TOKEN_STRIDE,
454        })
455    }
456}
457
458/// A renaming of every token, into a type that is not the tokens' own.
459///
460/// Naturality holds for *every* renaming, so three are sampled that a proof
461/// could tell apart: one that keeps the tokens distinct, one that makes them
462/// all the same, and one in between.
463#[derive(Clone, Copy, Debug)]
464enum Relabel {
465    /// Each token to a distinct string: the same shape, at another type.
466    Strings,
467    /// Every token onto the one boolean `true`: a proof that compared two of
468    /// them for equality and branched now takes the other branch.
469    Collapse,
470    /// Tokens onto `0` and `1` by parity: some pairs equal, some not, for a
471    /// proof whose branch the other two happen to agree with.
472    Parity,
473}
474
475impl Relabel {
476    fn at(self) -> Type {
477        match self {
478            Relabel::Strings => Type::String,
479            Relabel::Collapse => Type::Bool,
480            Relabel::Parity => Type::I64,
481        }
482    }
483
484    fn apply(self, param: &Ident, token: Token) -> Value {
485        match self {
486            Relabel::Strings => Value::Str(format!("{param}{}", token.ordinal)),
487            Relabel::Collapse => Value::Bool(true),
488            Relabel::Parity => Value::Int(token.ordinal % 2),
489        }
490    }
491
492    /// `at T = str`, or `with every T made equal`.
493    fn describe(self, params: &[Ident]) -> String {
494        let names: Vec<String> = params.iter().map(ToString::to_string).collect();
495        match self {
496            Relabel::Strings => format!("at {} = str", names.join(" = ")),
497            Relabel::Collapse => format!("with every {} made equal", names.join(" and ")),
498            Relabel::Parity => format!("with {} collapsed onto two values", names.join(", ")),
499        }
500    }
501
502    /// Where the tokens were: `T = i64`.
503    fn tokens(params: &[Ident]) -> String {
504        let names: Vec<String> = params.iter().map(ToString::to_string).collect();
505        format!("{} = i64", names.join(" = "))
506    }
507}
508
509/// A type that cannot be filled from nothing, or read back, and why.
510#[derive(Debug)]
511struct Unfillable {
512    what: String,
513    why: &'static str,
514}
515
516impl Unfillable {
517    fn of(ty: &Type, why: &'static str) -> Self {
518        Self {
519            what: format!("`{ty}`"),
520            why,
521        }
522    }
523
524    fn at(self, sig: &QualifiedName) -> ParametricError {
525        ParametricError::Unfillable {
526            sig: sig.clone(),
527            what: self.what,
528            why: self.why.to_string(),
529        }
530    }
531}
532
533/// A declaration, seen through a reference to it with its arguments applied.
534enum Resolved {
535    Fields(Vec<Field>),
536    Interface,
537    Variants(Vec<Variant>),
538    Alias(Type),
539}
540
541/// The signature's parameters, and the means to walk a type looking for them.
542struct Shape<'a> {
543    ws: &'a CheckedWorkspace,
544    params: &'a [Ident],
545}
546
547impl<'a> Shape<'a> {
548    fn filler(&self, trial: usize) -> Filler<'a, '_> {
549        Filler {
550            shape: self,
551            trial,
552            next: vec![0; self.params.len()],
553        }
554    }
555
556    fn param(&self, name: &Ident) -> Option<usize> {
557        self.params.iter().position(|p| p == name)
558    }
559
560    fn mentions_param(&self, ty: &Type) -> bool {
561        match ty {
562            Type::Param { name } => self.param(name).is_some(),
563            other => other.children().into_iter().any(|c| self.mentions_param(c)),
564        }
565    }
566
567    fn resolve(&self, r: &TypeRef) -> Result<Resolved, String> {
568        let name = self
569            .ws
570            .ref_target_of(r)
571            .ok_or_else(|| format!("`{r}` is not a qualified reference"))?;
572        let def = self
573            .ws
574            .def(&name)
575            .ok_or_else(|| format!("`{name}` is not declared"))?;
576        let subst = bind(def.params(), &r.args);
577        let fields = || -> Vec<Field> {
578            self.ws
579                .flat_fields(&name)
580                .unwrap_or_default()
581                .iter()
582                .map(|f| Field {
583                    name: f.name.clone(),
584                    ty: substitute(&f.ty, &subst),
585                    doc: None,
586                })
587                .collect()
588        };
589        Ok(match def {
590            TypeDef::Alias(a) => Resolved::Alias(substitute(&a.target, &subst)),
591            TypeDef::Struct(_) => Resolved::Fields(fields()),
592            TypeDef::Interface(_) => Resolved::Interface,
593            TypeDef::Enum(e) => Resolved::Variants(
594                e.variants
595                    .iter()
596                    .map(|v| Variant {
597                        name: v.name.clone(),
598                        payload: substitute(&v.payload, &subst),
599                        doc: None,
600                    })
601                    .collect(),
602            ),
603        })
604    }
605
606    /// Whether every `T` position in a result can be found from its type.
607    fn readable(&self, ty: &Type) -> Result<(), Unfillable> {
608        match ty {
609            Type::Union { .. } if self.mentions_param(ty) => Err(Unfillable::of(
610                ty,
611                "puts a parameter under an untagged union, where a value does not \
612                 say whether it is the parameter",
613            )),
614            Type::Function { .. } if self.mentions_param(ty) => Err(Unfillable::of(
615                ty,
616                "is a runtime handle, so what it does with a parameter cannot be seen",
617            )),
618            Type::Ref(r) if self.mentions_param(ty) => match self.resolve(r) {
619                Ok(Resolved::Alias(target)) => self.readable(&target),
620                Ok(Resolved::Fields(fields)) => {
621                    fields.iter().try_for_each(|f| self.readable(&f.ty))
622                }
623                Ok(Resolved::Variants(variants)) => {
624                    variants.iter().try_for_each(|v| self.readable(&v.payload))
625                }
626                Ok(Resolved::Interface) => Err(Unfillable::of(
627                    ty,
628                    "is an interface, whose fields do not say where a parameter is",
629                )),
630                Err(_) => Err(Unfillable::of(ty, "does not resolve")),
631            },
632            other => other
633                .children()
634                .into_iter()
635                .try_for_each(|c| self.readable(c)),
636        }
637    }
638
639    /// The tokens standing in each argument, per parameter.
640    fn tokens_given(&self, args: &[Value], sig: &FunctionSig) -> Vec<BTreeSet<i64>> {
641        let mut given = vec![BTreeSet::new(); self.params.len()];
642        for (arg, param) in args.iter().zip(&sig.params) {
643            // The arguments were built here, so they read back.
644            let _ = self.map_params(arg, &param.ty, &mut |p, value| {
645                if let Some(token) = Token::decode(value) {
646                    given[p].insert(token.ordinal);
647                }
648                value.clone()
649            });
650        }
651        given
652    }
653
654    /// Rebuilds `value` with every `T` position passed through `f`, following
655    /// `ty` to know where those are.
656    fn map_params(
657        &self,
658        value: &Value,
659        ty: &Type,
660        f: &mut dyn FnMut(usize, &Value) -> Value,
661    ) -> Result<Value, String> {
662        let mismatch = || format!("a {} is not a `{ty}`", value.kind_name());
663        Ok(match ty {
664            Type::Param { name } => match self.param(name) {
665                Some(ix) => f(ix, value),
666                None => value.clone(),
667            },
668            _ if !self.mentions_param(ty) => value.clone(),
669
670            Type::Optional { of } => match value {
671                Value::Null => Value::Null,
672                present => self.map_params(present, of, f)?,
673            },
674            Type::Future { of } => self.map_params(value, of, f)?,
675            Type::List { of } => {
676                let Value::List(items) = value else {
677                    return Err(mismatch());
678                };
679                Value::List(
680                    items
681                        .iter()
682                        .map(|item| self.map_params(item, of, f))
683                        .collect::<Result<_, _>>()?,
684                )
685            }
686            Type::Map { value: of, .. } => {
687                let Value::Map(entries) = value else {
688                    return Err(mismatch());
689                };
690                Value::Map(
691                    entries
692                        .iter()
693                        .map(|(k, v)| Ok((k.clone(), self.map_params(v, of, f)?)))
694                        .collect::<Result<_, String>>()?,
695                )
696            }
697            Type::Tuple { items: types } => {
698                let Value::Tuple(items) = value else {
699                    return Err(mismatch());
700                };
701                if items.len() != types.len() {
702                    return Err(mismatch());
703                }
704                Value::Tuple(
705                    items
706                        .iter()
707                        .zip(types)
708                        .map(|(item, ty)| self.map_params(item, ty, f))
709                        .collect::<Result<_, _>>()?,
710                )
711            }
712            Type::Record { fields } => self.map_fields(value, fields, f)?,
713            Type::Ref(r) => match self.resolve(r)? {
714                Resolved::Alias(target) => self.map_params(value, &target, f)?,
715                Resolved::Fields(fields) => self.map_fields(value, &fields, f)?,
716                Resolved::Interface => {
717                    return Err(format!(
718                        "`{ty}` is an interface, which cannot be read through"
719                    ));
720                }
721                Resolved::Variants(variants) => {
722                    let Value::Variant { tag, value: inner } = value else {
723                        return Err(mismatch());
724                    };
725                    let Some(variant) = variants.iter().find(|v| v.name.as_str() == tag) else {
726                        return Err(format!("`{ty}` has no variant `{tag}`"));
727                    };
728                    Value::Variant {
729                        tag: tag.clone(),
730                        value: Box::new(self.map_params(inner, &variant.payload, f)?),
731                    }
732                }
733            },
734            Type::Union { .. } => {
735                return Err(format!("`{ty}` puts a parameter under an untagged union"));
736            }
737            _ => return Err(mismatch()),
738        })
739    }
740
741    fn map_fields(
742        &self,
743        value: &Value,
744        fields: &[Field],
745        f: &mut dyn FnMut(usize, &Value) -> Value,
746    ) -> Result<Value, String> {
747        let Value::Record(record) = value else {
748            return Err(format!("a {} is not a record", value.kind_name()));
749        };
750        let mut out = record.clone();
751        for (key, v) in record {
752            if let Some(field) = fields.iter().find(|f| f.name.as_str() == key) {
753                out.insert(key.clone(), self.map_params(v, &field.ty, f)?);
754            }
755        }
756        Ok(Value::Record(out))
757    }
758}
759
760/// Builds arguments for one trial: a fresh token at every `T`, and something
761/// small and deterministic everywhere else.
762struct Filler<'a, 's> {
763    shape: &'s Shape<'a>,
764    trial: usize,
765    next: Vec<i64>,
766}
767
768impl Filler<'_, '_> {
769    fn token(&mut self, param: usize) -> Value {
770        let ordinal = self.next[param];
771        self.next[param] += 1;
772        Token { param, ordinal }.value()
773    }
774
775    fn fill(&mut self, ty: &Type) -> Result<Value, Unfillable> {
776        let k = self.trial;
777        Ok(match ty {
778            Type::Param { name } => match self.shape.param(name) {
779                Some(ix) => self.token(ix),
780                None => return Err(Unfillable::of(ty, "is bound by nothing in scope")),
781            },
782            Type::Never => return Err(Unfillable::of(ty, "has no values")),
783            Type::Any => Value::Int(k as i64),
784            Type::Unit => Value::Null,
785            Type::Bool => Value::Bool(k % 2 == 0),
786            Type::I32 | Type::I64 => Value::Int(k as i64),
787            Type::F64 => Value::Float(k as f64 + 0.5),
788            Type::String => Value::Str(format!("s{k}")),
789            Type::Bytes => Value::Bytes(vec![k as u8; k]),
790            Type::Literal { value } => match value {
791                LiteralValue::Bool(b) => Value::Bool(*b),
792                LiteralValue::Int(i) => Value::Int(*i),
793                LiteralValue::Str(s) => Value::Str(s.clone()),
794            },
795            Type::Optional { of } => {
796                if k % 2 == 0 {
797                    Value::Null
798                } else {
799                    self.fill(of)?
800                }
801            }
802            Type::List { of } => Value::List(
803                (0..SIZES[k])
804                    .map(|_| self.fill(of))
805                    .collect::<Result<_, _>>()?,
806            ),
807            Type::Map { key, value } => {
808                // Keys have to be distinct, which only strings and integers
809                // can manage in quantity.
810                let entries = match key.as_ref() {
811                    Type::String | Type::I32 | Type::I64 => SIZES[k],
812                    _ => SIZES[k].min(1),
813                };
814                let mut out = Vec::with_capacity(entries);
815                for j in 0..entries {
816                    let k = match key.as_ref() {
817                        Type::String => Value::Str(format!("k{j}")),
818                        Type::I32 | Type::I64 => Value::Int(j as i64),
819                        other => self.fill(other)?,
820                    };
821                    out.push((k, self.fill(value)?));
822                }
823                Value::Map(out)
824            }
825            Type::Tuple { items } => Value::Tuple(
826                items
827                    .iter()
828                    .map(|t| self.fill(t))
829                    .collect::<Result<_, _>>()?,
830            ),
831            Type::Record { fields } => self.fill_fields(fields)?,
832            Type::Union { members } => {
833                if self.shape.mentions_param(ty) {
834                    return Err(Unfillable::of(
835                        ty,
836                        "puts a parameter under an untagged union, where a value does not \
837                         say whether it is the parameter",
838                    ));
839                }
840                match members.first() {
841                    Some(first) => self.fill(first)?,
842                    None => return Err(Unfillable::of(ty, "has no alternatives")),
843                }
844            }
845            Type::Function { .. } | Type::Future { .. } => {
846                return Err(Unfillable::of(ty, "is a runtime handle, not data"));
847            }
848            Type::Ref(r) => match self.shape.resolve(r) {
849                Ok(Resolved::Alias(target)) => self.fill(&target)?,
850                Ok(Resolved::Fields(fields)) => self.fill_fields(&fields)?,
851                Ok(Resolved::Interface) => {
852                    return Err(Unfillable::of(
853                        ty,
854                        "is an interface, which can be satisfied but not constructed",
855                    ));
856                }
857                Ok(Resolved::Variants(variants)) => {
858                    if variants.is_empty() {
859                        return Err(Unfillable::of(ty, "has no variants"));
860                    }
861                    let variant = &variants[k % variants.len()];
862                    Value::Variant {
863                        tag: variant.name.to_string(),
864                        value: Box::new(self.fill(&variant.payload)?),
865                    }
866                }
867                Err(_) => return Err(Unfillable::of(ty, "does not resolve")),
868            },
869        })
870    }
871
872    fn fill_fields(&mut self, fields: &[Field]) -> Result<Value, Unfillable> {
873        let mut out = Vec::with_capacity(fields.len());
874        for field in fields {
875            out.push((field.name.to_string(), self.fill(&field.ty)?));
876        }
877        Ok(Value::record(out))
878    }
879}
880
881#[cfg(test)]
882mod tests {
883    use super::*;
884    use std::sync::Arc;
885    use unitype_core::check::check_workspace;
886    use unitype_core::{BigO, ImplProfile, Workspace};
887
888    use crate::error::ExecError;
889    use crate::implementation::Implementation;
890    use crate::registry::Registry;
891
892    const WS: &str = r#"{"universes":[{"name":"demo",
893      "types":[
894        {"k":"struct","name":"Box","params":[{"name":"T"}],
895         "fields":[{"name":"label","ty":"str"},{"name":"inside","ty":{"k":"param","name":"T"}}]},
896        {"k":"interface","name":"Identified","fields":[{"name":"id","ty":"str"}]},
897        {"k":"enum","name":"Maybe","params":[{"name":"T"}],
898         "variants":[{"name":"nothing"},{"name":"just","payload":{"k":"param","name":"T"}}]}],
899      "functions":[
900        {"name":"reverse","params_decl":[{"name":"T"}],
901         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
902         "ret":{"k":"list","of":{"k":"param","name":"T"}}},
903        {"name":"first","params_decl":[{"name":"T"}],
904         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
905         "ret":{"k":"optional","of":{"k":"param","name":"T"}}},
906        {"name":"swap","params_decl":[{"name":"A"},{"name":"B"}],
907         "params":[{"name":"a","ty":{"k":"param","name":"A"}},{"name":"b","ty":{"k":"param","name":"B"}}],
908         "ret":{"k":"tuple","items":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
909        {"name":"unbox","params_decl":[{"name":"T"}],
910         "params":[{"name":"b","ty":{"k":"ref","name":"Box","args":[{"k":"param","name":"T"}]}}],
911         "ret":{"k":"ref","name":"Maybe","args":[{"k":"param","name":"T"}]}},
912        {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
913        {"name":"ids","params_decl":[{"name":"T","bounds":["Identified"]}],
914         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
915         "ret":"[str]"},
916        {"name":"either","params_decl":[{"name":"T"}],
917         "params":[{"name":"x","ty":{"k":"union","members":[{"k":"param","name":"T"},"str"]}}],
918         "ret":{"k":"param","name":"T"}}]}]}"#;
919
920    fn q(s: &str) -> QualifiedName {
921        s.parse().unwrap()
922    }
923
924    fn list(value: &Value) -> Vec<Value> {
925        match value {
926            Value::List(items) => items.clone(),
927            _ => Vec::new(),
928        }
929    }
930
931    /// Every proof this file talks about, under the name it is talked about by.
932    fn registry() -> Registry {
933        let mut registry = Registry::new();
934
935        registry.register_native_sync("reverses", |args| {
936            let mut items = list(&args[0]);
937            items.reverse();
938            Ok(Value::List(items))
939        });
940        // Sorts when it can tell the elements are integers, and reverses
941        // otherwise: right at every type the author tried, and not parametric.
942        registry.register_native_sync("sorts_integers", |args| {
943            let mut items = list(&args[0]);
944            if items.iter().all(|v| v.as_int().is_some()) {
945                items.sort_by_key(|v| v.as_int());
946            } else {
947                items.reverse();
948            }
949            Ok(Value::List(items))
950        });
951        // Reverses, unless the first two are equal, in which case it forgets
952        // the rest. Only a relabelling that makes two tokens equal finds this.
953        registry.register_native_sync("compares", |args| {
954            let mut items = list(&args[0]);
955            if items.len() >= 2 && items[0] == items[1] {
956                items.truncate(1);
957            } else {
958                items.reverse();
959            }
960            Ok(Value::List(items))
961        });
962        // Pads an empty list with something it made up.
963        registry.register_native_sync("pads", |args| {
964            let mut items = list(&args[0]);
965            if items.is_empty() {
966                items.push(Value::Int(0));
967            }
968            items.reverse();
969            Ok(Value::List(items))
970        });
971        // Only works at one type.
972        registry.register_native_sync("integers_only", |args| {
973            let items = list(&args[0]);
974            if items.iter().any(|v| v.as_int().is_none()) {
975                return Err(ExecError::Failed {
976                    id: "integers_only".into(),
977                    message: "expected integers".into(),
978                });
979            }
980            Ok(Value::List(items.into_iter().rev().collect()))
981        });
982        registry.register_native_sync("heads", |args| {
983            Ok(list(&args[0]).into_iter().next().unwrap_or(Value::Null))
984        });
985        registry.register_native_sync("swaps", |mut args| {
986            let b = args.remove(1);
987            let a = args.remove(0);
988            Ok(Value::Tuple(vec![b, a]))
989        });
990        // Returns the pair the way it came: an `A` where a `B` was promised.
991        registry.register_native_sync("keeps", |args| Ok(Value::Tuple(args)));
992        registry.register_native_sync("unboxes", |mut args| {
993            let Value::Record(mut fields) = args.remove(0) else {
994                return Err(ExecError::Untyped("expected a record".into()));
995            };
996            let inside = fields.swap_remove("inside").unwrap_or(Value::Null);
997            Ok(Value::Variant {
998                tag: "just".into(),
999                value: Box::new(inside),
1000            })
1001        });
1002        registry
1003    }
1004
1005    fn dispatcher(proves: &[(&str, &str)]) -> Dispatcher {
1006        let ws =
1007            Arc::new(check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks"));
1008        let mut registry = registry();
1009        for (entry, sig) in proves {
1010            registry
1011                .register(Implementation::new(
1012                    *entry,
1013                    q(sig),
1014                    Ident::new("here").unwrap(),
1015                    *entry,
1016                    ImplProfile::new(BigO::ON, BigO::ON),
1017                ))
1018                .expect("registers");
1019        }
1020        Dispatcher::new(ws, Arc::new(registry))
1021    }
1022
1023    /// The one verdict a proof got that was not `Held`, if any.
1024    fn against(theorems: &Theorems, id: &str) -> Option<Verdict> {
1025        theorems
1026            .trials
1027            .iter()
1028            .filter_map(|t| t.verdicts.get(&ImplId::new(id)))
1029            .find(|v| v.is_against())
1030            .cloned()
1031    }
1032
1033    #[tokio::test]
1034    async fn a_parametric_proof_holds_without_anyone_saying_what_it_should_return() {
1035        let theorems = check(
1036            &dispatcher(&[("reverses", "demo::reverse")]),
1037            &q("demo::reverse"),
1038        )
1039        .await
1040        .expect("checks");
1041
1042        assert!(theorems.held(), "{:?}", theorems.broken());
1043        assert_eq!(theorems.trials.len(), TRIALS);
1044        assert_eq!(theorems.heading(), "demo::reverse<T>");
1045    }
1046
1047    #[tokio::test]
1048    async fn a_proof_that_looks_at_the_elements_breaks_naturality() {
1049        // At `i64` it sorts, which is a permutation, so conservation holds.
1050        // At `str` it does something else, which is the whole complaint.
1051        let theorems = check(
1052            &dispatcher(&[("sorts_integers", "demo::reverse")]),
1053            &q("demo::reverse"),
1054        )
1055        .await
1056        .expect("checks");
1057
1058        let verdict = against(&theorems, "sorts_integers").expect("caught");
1059        assert!(
1060            matches!(
1061                &verdict,
1062                Verdict::Broken {
1063                    law: Law::Naturality,
1064                    ..
1065                }
1066            ),
1067            "{verdict:?}"
1068        );
1069        assert!(
1070            verdict.summary().contains("T = str"),
1071            "{}",
1072            verdict.summary()
1073        );
1074    }
1075
1076    #[tokio::test]
1077    async fn a_proof_that_compares_two_elements_is_found_by_collapsing_them() {
1078        // Distinct tokens never compare equal, and neither do distinct
1079        // strings, so only a relabelling that makes two equal can show this.
1080        let theorems = check(
1081            &dispatcher(&[("compares", "demo::reverse")]),
1082            &q("demo::reverse"),
1083        )
1084        .await
1085        .expect("checks");
1086
1087        let verdict = against(&theorems, "compares").expect("caught");
1088        assert!(
1089            verdict.summary().contains("made equal"),
1090            "{}",
1091            verdict.summary()
1092        );
1093    }
1094
1095    #[tokio::test]
1096    async fn a_proof_that_makes_up_an_element_breaks_conservation() {
1097        let theorems = check(
1098            &dispatcher(&[("pads", "demo::reverse")]),
1099            &q("demo::reverse"),
1100        )
1101        .await
1102        .expect("checks");
1103
1104        let verdict = against(&theorems, "pads").expect("caught");
1105        assert!(
1106            matches!(
1107                verdict,
1108                Verdict::Broken {
1109                    law: Law::Conservation,
1110                    ..
1111                }
1112            ),
1113            "{verdict:?}"
1114        );
1115        assert!(
1116            !theorems.trials[0].held(),
1117            "the empty list is where it pads"
1118        );
1119        assert!(theorems.trials[1].held(), "and nowhere else");
1120    }
1121
1122    #[tokio::test]
1123    async fn a_proof_that_only_works_at_one_type_has_not_proved_the_generic_claim() {
1124        let theorems = check(
1125            &dispatcher(&[("integers_only", "demo::reverse")]),
1126            &q("demo::reverse"),
1127        )
1128        .await
1129        .expect("checks");
1130
1131        let verdict = against(&theorems, "integers_only").expect("caught");
1132        assert!(
1133            matches!(
1134                verdict,
1135                Verdict::Broken {
1136                    law: Law::Naturality,
1137                    ..
1138                }
1139            ),
1140            "failing at another type breaks the law rather than excusing the proof: {verdict:?}"
1141        );
1142        assert!(
1143            theorems.trials[0].held(),
1144            "on the empty list there was nothing to be the wrong type"
1145        );
1146    }
1147
1148    #[tokio::test]
1149    async fn the_right_proof_and_the_wrong_one_are_told_apart_side_by_side() {
1150        let theorems = check(
1151            &dispatcher(&[
1152                ("reverses", "demo::reverse"),
1153                ("sorts_integers", "demo::reverse"),
1154            ]),
1155            &q("demo::reverse"),
1156        )
1157        .await
1158        .expect("checks");
1159
1160        assert!(against(&theorems, "reverses").is_none());
1161        assert!(against(&theorems, "sorts_integers").is_some());
1162        assert!(!theorems.held());
1163    }
1164
1165    #[tokio::test]
1166    async fn absence_in_the_result_is_a_position_with_nothing_in_it() {
1167        let theorems = check(&dispatcher(&[("heads", "demo::first")]), &q("demo::first"))
1168            .await
1169            .expect("checks");
1170        assert!(theorems.held(), "{:?}", theorems.broken());
1171    }
1172
1173    #[tokio::test]
1174    async fn two_parameters_are_told_apart() {
1175        let honest = check(&dispatcher(&[("swaps", "demo::swap")]), &q("demo::swap"))
1176            .await
1177            .expect("checks");
1178        assert!(honest.held(), "{:?}", honest.broken());
1179        assert_eq!(honest.heading(), "demo::swap<A, B>");
1180
1181        // Handing back an `A` where a `B` was promised is making up a `B`.
1182        let dishonest = check(&dispatcher(&[("keeps", "demo::swap")]), &q("demo::swap"))
1183            .await
1184            .expect("checks");
1185        let verdict = against(&dishonest, "keeps").expect("caught");
1186        assert!(
1187            matches!(
1188                verdict,
1189                Verdict::Broken {
1190                    law: Law::Conservation,
1191                    ..
1192                }
1193            ),
1194            "{verdict:?}"
1195        );
1196    }
1197
1198    #[tokio::test]
1199    async fn parameters_are_found_inside_declared_types() {
1200        // A `T` inside a struct field going in, and inside an enum payload
1201        // coming out: both reached through the declarations.
1202        let theorems = check(
1203            &dispatcher(&[("unboxes", "demo::unbox")]),
1204            &q("demo::unbox"),
1205        )
1206        .await
1207        .expect("checks");
1208        assert!(theorems.held(), "{:?}", theorems.broken());
1209        assert!(
1210            theorems.trials[0].name.contains("\"inside\":0"),
1211            "the token should have been put in the field: {}",
1212            theorems.trials[0].name
1213        );
1214    }
1215
1216    #[tokio::test]
1217    async fn a_proposition_with_nothing_generic_about_it_has_no_theorem() {
1218        let d = dispatcher(&[]);
1219        assert!(matches!(
1220            applies(d.workspace(), &q("demo::sort")),
1221            Err(ParametricError::NotGeneric(_))
1222        ));
1223    }
1224
1225    #[tokio::test]
1226    async fn a_bounded_parameter_is_declined_rather_than_held_to_a_law_it_need_not_obey() {
1227        let d = dispatcher(&[]);
1228        let err = applies(d.workspace(), &q("demo::ids")).unwrap_err();
1229        assert!(matches!(err, ParametricError::Bounded { .. }), "{err}");
1230        assert!(err.to_string().contains("Identified"), "{err}");
1231    }
1232
1233    #[tokio::test]
1234    async fn a_parameter_under_an_untagged_union_cannot_be_found() {
1235        let d = dispatcher(&[]);
1236        let err = applies(d.workspace(), &q("demo::either")).unwrap_err();
1237        assert!(matches!(err, ParametricError::Unfillable { .. }), "{err}");
1238        assert!(err.to_string().contains("untagged union"), "{err}");
1239    }
1240
1241    #[tokio::test]
1242    async fn nothing_to_check_is_said_rather_than_passed() {
1243        assert!(matches!(
1244            check(&dispatcher(&[]), &q("demo::reverse")).await,
1245            Err(ParametricError::NoProofs(_))
1246        ));
1247    }
1248
1249    #[test]
1250    fn tokens_say_which_parameter_they_stand_for() {
1251        let token = Token {
1252            param: 1,
1253            ordinal: 7,
1254        };
1255        assert_eq!(Token::decode(&token.value()), Some(token));
1256        assert_eq!(Token::decode(&Value::Str("T7".into())), None);
1257    }
1258}