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    // A parameter standing for a type constructor is not filled with a type: a
284    // free theorem over one needs the harness to choose constructors, which it
285    // does not do yet.
286    for decl in &sig.params_decl {
287        if decl.is_higher_order() {
288            return Err(ParametricError::Unfillable {
289                sig: name.clone(),
290                what: format!("`{}`", decl.name),
291                why:
292                    "stands for a type constructor, and a free theorem over one is a later addition"
293                        .into(),
294            });
295        }
296    }
297    for decl in &sig.params_decl {
298        if let Some(bound) = decl.bounds.first() {
299            return Err(ParametricError::Bounded {
300                sig: name.clone(),
301                param: decl.name.clone(),
302                bound: bound.to_string(),
303            });
304        }
305    }
306    let params: Vec<Ident> = sig.params_decl.iter().map(|d| d.name.clone()).collect();
307    let shape = Shape {
308        ws,
309        params: &params,
310    };
311
312    // Filling is deterministic in the type, so if the first trial can be
313    // filled they all can.
314    let mut filler = shape.filler(0);
315    for param in &sig.params {
316        filler.fill(&param.ty).map_err(|u| u.at(name))?;
317    }
318    shape
319        .readable(&eventual(&sig.ret))
320        .map_err(|u| u.at(name))?;
321    Ok(params)
322}
323
324/// Runs one proof against one trial and says what it did.
325#[allow(clippy::too_many_arguments)]
326async fn judge(
327    dispatcher: &Dispatcher,
328    name: &QualifiedName,
329    sig: &FunctionSig,
330    shape: &Shape<'_>,
331    ret: &Type,
332    at_tokens: &[Type],
333    args: &[Value],
334    given: &[BTreeSet<i64>],
335    id: &ImplId,
336) -> Verdict {
337    let pinned = Policy::Pinned(id.clone());
338
339    let result = match dispatcher
340        .call_at(name, at_tokens, args.to_vec(), &pinned)
341        .await
342    {
343        Ok(invocation) => invocation.value,
344        Err(error) if unavailable(&error) => return Verdict::Skipped(error.to_string()),
345        Err(error) => return Verdict::Failed(error.to_string()),
346    };
347
348    // Conservation: every token that came back is one that went in, standing
349    // for the same parameter.
350    let mut stray = None;
351    let read = shape.map_params(&result, ret, &mut |param, value| {
352        let token = Token::decode(value);
353        if !token.is_some_and(|t| t.param == param && given[param].contains(&t.ordinal))
354            && stray.is_none()
355        {
356            stray = Some(format!(
357                "a `{}` came back that was never passed in: {}",
358                shape.params[param],
359                json(value)
360            ));
361        }
362        value.clone()
363    });
364    if let Err(why) = read {
365        return Verdict::Failed(format!("could not read the result: {why}"));
366    }
367    if let Some(detail) = stray {
368        return Verdict::Broken {
369            law: Law::Conservation,
370            detail,
371        };
372    }
373
374    // Naturality: relabel the tokens, run again, and the proof must have
375    // relabelled its own answer the same way.
376    for relabel in [Relabel::Strings, Relabel::Collapse, Relabel::Parity] {
377        let mut g = |param: usize, value: &Value| match Token::decode(value) {
378            Some(token) => relabel.apply(&shape.params[param], token),
379            None => value.clone(),
380        };
381        let mut relabelled = Vec::with_capacity(args.len());
382        for (arg, param) in args.iter().zip(&sig.params) {
383            match shape.map_params(arg, &param.ty, &mut g) {
384                Ok(value) => relabelled.push(value),
385                Err(why) => {
386                    return Verdict::Failed(format!("could not relabel an argument: {why}"));
387                }
388            }
389        }
390        let expected = match shape.map_params(&result, ret, &mut g) {
391            Ok(value) => value,
392            Err(why) => return Verdict::Failed(format!("could not relabel the result: {why}")),
393        };
394
395        let at = vec![relabel.at(); shape.params.len()];
396        match dispatcher.call_at(name, &at, relabelled, &pinned).await {
397            Ok(invocation) if alike(&invocation.value, &expected, 0.0) => {}
398            Ok(invocation) => {
399                return Verdict::Broken {
400                    law: Law::Naturality,
401                    detail: format!(
402                        "{}, it gave {}, but relabelling what it gave at {} requires {}",
403                        relabel.describe(shape.params),
404                        json(&invocation.value),
405                        Relabel::tokens(shape.params),
406                        json(&expected)
407                    ),
408                };
409            }
410            Err(error) if unavailable(&error) => return Verdict::Skipped(error.to_string()),
411            Err(error) => {
412                return Verdict::Broken {
413                    law: Law::Naturality,
414                    detail: format!("{}, {error}", relabel.describe(shape.params)),
415                };
416            }
417        }
418    }
419
420    Verdict::Held
421}
422
423/// A proof's eventual answer: what a future resolves to, or the type itself.
424fn eventual(ret: &Type) -> Type {
425    ret.future_of().cloned().unwrap_or_else(|| ret.clone())
426}
427
428/// A trial, named by what was passed: `xs = [0, 1, 2]`.
429fn describe(sig: &FunctionSig, args: &[Value]) -> String {
430    if args.is_empty() {
431        return "no arguments".into();
432    }
433    sig.params
434        .iter()
435        .zip(args)
436        .map(|(p, a)| format!("{} = {}", p.name, json(a)))
437        .collect::<Vec<_>>()
438        .join(", ")
439}
440
441fn json(value: &Value) -> String {
442    value
443        .to_json_string()
444        .unwrap_or_else(|_| "<unwritable>".into())
445}
446
447/// A stand-in for one `T`: distinct from every other, and saying which
448/// parameter it stands for.
449#[derive(Clone, Copy, Debug, PartialEq, Eq)]
450struct Token {
451    param: usize,
452    ordinal: i64,
453}
454
455impl Token {
456    fn value(self) -> Value {
457        Value::Int(self.param as i64 * TOKEN_STRIDE + self.ordinal)
458    }
459
460    fn decode(value: &Value) -> Option<Token> {
461        let n = value.as_int()?;
462        (n >= 0).then_some(Token {
463            param: (n / TOKEN_STRIDE) as usize,
464            ordinal: n % TOKEN_STRIDE,
465        })
466    }
467}
468
469/// A renaming of every token, into a type that is not the tokens' own.
470///
471/// Naturality holds for *every* renaming, so three are sampled that a proof
472/// could tell apart: one that keeps the tokens distinct, one that makes them
473/// all the same, and one in between.
474#[derive(Clone, Copy, Debug)]
475enum Relabel {
476    /// Each token to a distinct string: the same shape, at another type.
477    Strings,
478    /// Every token onto the one boolean `true`: a proof that compared two of
479    /// them for equality and branched now takes the other branch.
480    Collapse,
481    /// Tokens onto `0` and `1` by parity: some pairs equal, some not, for a
482    /// proof whose branch the other two happen to agree with.
483    Parity,
484}
485
486impl Relabel {
487    fn at(self) -> Type {
488        match self {
489            Relabel::Strings => Type::String,
490            Relabel::Collapse => Type::Bool,
491            Relabel::Parity => Type::I64,
492        }
493    }
494
495    fn apply(self, param: &Ident, token: Token) -> Value {
496        match self {
497            Relabel::Strings => Value::Str(format!("{param}{}", token.ordinal)),
498            Relabel::Collapse => Value::Bool(true),
499            Relabel::Parity => Value::Int(token.ordinal % 2),
500        }
501    }
502
503    /// `at T = str`, or `with every T made equal`.
504    fn describe(self, params: &[Ident]) -> String {
505        let names: Vec<String> = params.iter().map(ToString::to_string).collect();
506        match self {
507            Relabel::Strings => format!("at {} = str", names.join(" = ")),
508            Relabel::Collapse => format!("with every {} made equal", names.join(" and ")),
509            Relabel::Parity => format!("with {} collapsed onto two values", names.join(", ")),
510        }
511    }
512
513    /// Where the tokens were: `T = i64`.
514    fn tokens(params: &[Ident]) -> String {
515        let names: Vec<String> = params.iter().map(ToString::to_string).collect();
516        format!("{} = i64", names.join(" = "))
517    }
518}
519
520/// A type that cannot be filled from nothing, or read back, and why.
521#[derive(Debug)]
522struct Unfillable {
523    what: String,
524    why: &'static str,
525}
526
527impl Unfillable {
528    fn of(ty: &Type, why: &'static str) -> Self {
529        Self {
530            what: format!("`{ty}`"),
531            why,
532        }
533    }
534
535    fn at(self, sig: &QualifiedName) -> ParametricError {
536        ParametricError::Unfillable {
537            sig: sig.clone(),
538            what: self.what,
539            why: self.why.to_string(),
540        }
541    }
542}
543
544/// A declaration, seen through a reference to it with its arguments applied.
545enum Resolved {
546    Fields(Vec<Field>),
547    Interface,
548    Variants(Vec<Variant>),
549    Alias(Type),
550}
551
552/// The signature's parameters, and the means to walk a type looking for them.
553struct Shape<'a> {
554    ws: &'a CheckedWorkspace,
555    params: &'a [Ident],
556}
557
558impl<'a> Shape<'a> {
559    fn filler(&self, trial: usize) -> Filler<'a, '_> {
560        Filler {
561            shape: self,
562            trial,
563            next: vec![0; self.params.len()],
564        }
565    }
566
567    fn param(&self, name: &Ident) -> Option<usize> {
568        self.params.iter().position(|p| p == name)
569    }
570
571    fn mentions_param(&self, ty: &Type) -> bool {
572        match ty {
573            Type::Param { name } => self.param(name).is_some(),
574            other => other.children().into_iter().any(|c| self.mentions_param(c)),
575        }
576    }
577
578    fn resolve(&self, r: &TypeRef) -> Result<Resolved, String> {
579        let name = self
580            .ws
581            .ref_target_of(r)
582            .ok_or_else(|| format!("`{r}` is not a qualified reference"))?;
583        let def = self
584            .ws
585            .def(&name)
586            .ok_or_else(|| format!("`{name}` is not declared"))?;
587        let subst = bind(def.params(), &r.args);
588        let fields = || -> Vec<Field> {
589            self.ws
590                .flat_fields(&name)
591                .unwrap_or_default()
592                .iter()
593                .map(|f| Field {
594                    name: f.name.clone(),
595                    ty: substitute(&f.ty, &subst),
596                    doc: None,
597                })
598                .collect()
599        };
600        Ok(match def {
601            TypeDef::Alias(a) => Resolved::Alias(substitute(&a.target, &subst)),
602            TypeDef::Struct(_) => Resolved::Fields(fields()),
603            TypeDef::Interface(_) => Resolved::Interface,
604            TypeDef::Enum(e) => Resolved::Variants(
605                e.variants
606                    .iter()
607                    .map(|v| Variant {
608                        name: v.name.clone(),
609                        payload: substitute(&v.payload, &subst),
610                        doc: None,
611                    })
612                    .collect(),
613            ),
614        })
615    }
616
617    /// Whether every `T` position in a result can be found from its type.
618    fn readable(&self, ty: &Type) -> Result<(), Unfillable> {
619        match ty {
620            Type::Bounded { of, .. } => self.readable(of),
621            Type::Union { .. } if self.mentions_param(ty) => Err(Unfillable::of(
622                ty,
623                "puts a parameter under an untagged union, where a value does not \
624                 say whether it is the parameter",
625            )),
626            Type::Function { .. } if self.mentions_param(ty) => Err(Unfillable::of(
627                ty,
628                "is a runtime handle, so what it does with a parameter cannot be seen",
629            )),
630            Type::Ref(r) if self.mentions_param(ty) => match self.resolve(r) {
631                Ok(Resolved::Alias(target)) => self.readable(&target),
632                Ok(Resolved::Fields(fields)) => {
633                    fields.iter().try_for_each(|f| self.readable(&f.ty))
634                }
635                Ok(Resolved::Variants(variants)) => {
636                    variants.iter().try_for_each(|v| self.readable(&v.payload))
637                }
638                Ok(Resolved::Interface) => Err(Unfillable::of(
639                    ty,
640                    "is an interface, whose fields do not say where a parameter is",
641                )),
642                Err(_) => Err(Unfillable::of(ty, "does not resolve")),
643            },
644            other => other
645                .children()
646                .into_iter()
647                .try_for_each(|c| self.readable(c)),
648        }
649    }
650
651    /// The tokens standing in each argument, per parameter.
652    fn tokens_given(&self, args: &[Value], sig: &FunctionSig) -> Vec<BTreeSet<i64>> {
653        let mut given = vec![BTreeSet::new(); self.params.len()];
654        for (arg, param) in args.iter().zip(&sig.params) {
655            // The arguments were built here, so they read back.
656            let _ = self.map_params(arg, &param.ty, &mut |p, value| {
657                if let Some(token) = Token::decode(value) {
658                    given[p].insert(token.ordinal);
659                }
660                value.clone()
661            });
662        }
663        given
664    }
665
666    /// Rebuilds `value` with every `T` position passed through `f`, following
667    /// `ty` to know where those are.
668    fn map_params(
669        &self,
670        value: &Value,
671        ty: &Type,
672        f: &mut dyn FnMut(usize, &Value) -> Value,
673    ) -> Result<Value, String> {
674        let mismatch = || format!("a {} is not a `{ty}`", value.kind_name());
675        Ok(match ty {
676            Type::Param { name } => match self.param(name) {
677                Some(ix) => f(ix, value),
678                None => value.clone(),
679            },
680            _ if !self.mentions_param(ty) => value.clone(),
681            Type::Apply { .. } | Type::Constructor { .. } => {
682                return Err(format!(
683                    "`{ty}` applies a type constructor, which this harness cannot read"
684                ));
685            }
686
687            Type::Optional { of } => match value {
688                Value::Null => Value::Null,
689                present => self.map_params(present, of, f)?,
690            },
691            Type::Future { of } => self.map_params(value, of, f)?,
692            Type::Bounded { of, .. } => self.map_params(value, of, f)?,
693            Type::List { of } => {
694                let Value::List(items) = value else {
695                    return Err(mismatch());
696                };
697                Value::List(
698                    items
699                        .iter()
700                        .map(|item| self.map_params(item, of, f))
701                        .collect::<Result<_, _>>()?,
702                )
703            }
704            Type::Map { value: of, .. } => {
705                let Value::Map(entries) = value else {
706                    return Err(mismatch());
707                };
708                Value::Map(
709                    entries
710                        .iter()
711                        .map(|(k, v)| Ok((k.clone(), self.map_params(v, of, f)?)))
712                        .collect::<Result<_, String>>()?,
713                )
714            }
715            Type::Tuple { items: types } => {
716                let Value::Tuple(items) = value else {
717                    return Err(mismatch());
718                };
719                if items.len() != types.len() {
720                    return Err(mismatch());
721                }
722                Value::Tuple(
723                    items
724                        .iter()
725                        .zip(types)
726                        .map(|(item, ty)| self.map_params(item, ty, f))
727                        .collect::<Result<_, _>>()?,
728                )
729            }
730            Type::Record { fields } => self.map_fields(value, fields, f)?,
731            Type::Ref(r) => match self.resolve(r)? {
732                Resolved::Alias(target) => self.map_params(value, &target, f)?,
733                Resolved::Fields(fields) => self.map_fields(value, &fields, f)?,
734                Resolved::Interface => {
735                    return Err(format!(
736                        "`{ty}` is an interface, which cannot be read through"
737                    ));
738                }
739                Resolved::Variants(variants) => {
740                    let Value::Variant { tag, value: inner } = value else {
741                        return Err(mismatch());
742                    };
743                    let Some(variant) = variants.iter().find(|v| v.name.as_str() == tag) else {
744                        return Err(format!("`{ty}` has no variant `{tag}`"));
745                    };
746                    Value::Variant {
747                        tag: tag.clone(),
748                        value: Box::new(self.map_params(inner, &variant.payload, f)?),
749                    }
750                }
751            },
752            Type::Union { .. } => {
753                return Err(format!("`{ty}` puts a parameter under an untagged union"));
754            }
755            _ => return Err(mismatch()),
756        })
757    }
758
759    fn map_fields(
760        &self,
761        value: &Value,
762        fields: &[Field],
763        f: &mut dyn FnMut(usize, &Value) -> Value,
764    ) -> Result<Value, String> {
765        let Value::Record(record) = value else {
766            return Err(format!("a {} is not a record", value.kind_name()));
767        };
768        let mut out = record.clone();
769        for (key, v) in record {
770            if let Some(field) = fields.iter().find(|f| f.name.as_str() == key) {
771                out.insert(key.clone(), self.map_params(v, &field.ty, f)?);
772            }
773        }
774        Ok(Value::Record(out))
775    }
776}
777
778/// Builds arguments for one trial: a fresh token at every `T`, and something
779/// small and deterministic everywhere else.
780struct Filler<'a, 's> {
781    shape: &'s Shape<'a>,
782    trial: usize,
783    next: Vec<i64>,
784}
785
786impl Filler<'_, '_> {
787    fn token(&mut self, param: usize) -> Value {
788        let ordinal = self.next[param];
789        self.next[param] += 1;
790        Token { param, ordinal }.value()
791    }
792
793    fn fill(&mut self, ty: &Type) -> Result<Value, Unfillable> {
794        let k = self.trial;
795        Ok(match ty {
796            Type::Param { name } => match self.shape.param(name) {
797                Some(ix) => self.token(ix),
798                None => return Err(Unfillable::of(ty, "is bound by nothing in scope")),
799            },
800            Type::Never => return Err(Unfillable::of(ty, "has no values")),
801            Type::Apply { .. } => {
802                return Err(Unfillable::of(
803                    ty,
804                    "applies a type constructor, and no constructor is chosen to fill it with",
805                ));
806            }
807            Type::Constructor { .. } => {
808                return Err(Unfillable::of(ty, "is a type constructor, not a type"));
809            }
810            Type::Any => Value::Int(k as i64),
811            Type::Unit => Value::Null,
812            Type::Bool => Value::Bool(k % 2 == 0),
813            Type::I32 | Type::I64 => Value::Int(k as i64),
814            Type::F64 => Value::Float(k as f64 + 0.5),
815            Type::String => Value::Str(format!("s{k}")),
816            Type::Bytes => Value::Bytes(vec![k as u8; k]),
817            Type::Literal { value } => match value {
818                LiteralValue::Bool(b) => Value::Bool(*b),
819                LiteralValue::Int(i) => Value::Int(*i),
820                LiteralValue::Str(s) => Value::Str(s.clone()),
821            },
822            Type::Optional { of } => {
823                if k % 2 == 0 {
824                    Value::Null
825                } else {
826                    self.fill(of)?
827                }
828            }
829            Type::List { of } => Value::List(
830                (0..SIZES[k])
831                    .map(|_| self.fill(of))
832                    .collect::<Result<_, _>>()?,
833            ),
834            // Within the bounds: an integer brought into its range, a list or
835            // bytes cut or grown to a length the bounds allow.
836            Type::Bounded { of, value, len, .. } => {
837                let within = |n: i64, bounds: &Option<unitype_core::Bounds>| match bounds {
838                    Some(b) => n.max(b.min.unwrap_or(n)).min(b.max.unwrap_or(n)),
839                    None => n,
840                };
841                match (self.fill(of)?, of.as_ref()) {
842                    (Value::Int(i), _) => Value::Int(within(i, value)),
843                    (Value::List(mut items), Type::List { of: item }) => {
844                        let want = within(items.len() as i64, len).max(0) as usize;
845                        items.truncate(want);
846                        while items.len() < want {
847                            items.push(self.fill(item)?);
848                        }
849                        Value::List(items)
850                    }
851                    (Value::Bytes(mut bytes), _) => {
852                        let want = within(bytes.len() as i64, len).max(0) as usize;
853                        bytes.resize(want, k as u8);
854                        Value::Bytes(bytes)
855                    }
856                    (other, _) => other,
857                }
858            }
859            Type::Map { key, value } => {
860                // Keys have to be distinct, which only strings and integers
861                // can manage in quantity.
862                let entries = match key.as_ref() {
863                    Type::String | Type::I32 | Type::I64 => SIZES[k],
864                    _ => SIZES[k].min(1),
865                };
866                let mut out = Vec::with_capacity(entries);
867                for j in 0..entries {
868                    let k = match key.as_ref() {
869                        Type::String => Value::Str(format!("k{j}")),
870                        Type::I32 | Type::I64 => Value::Int(j as i64),
871                        other => self.fill(other)?,
872                    };
873                    out.push((k, self.fill(value)?));
874                }
875                Value::Map(out)
876            }
877            Type::Tuple { items } => Value::Tuple(
878                items
879                    .iter()
880                    .map(|t| self.fill(t))
881                    .collect::<Result<_, _>>()?,
882            ),
883            Type::Record { fields } => self.fill_fields(fields)?,
884            Type::Union { members } => {
885                if self.shape.mentions_param(ty) {
886                    return Err(Unfillable::of(
887                        ty,
888                        "puts a parameter under an untagged union, where a value does not \
889                         say whether it is the parameter",
890                    ));
891                }
892                match members.first() {
893                    Some(first) => self.fill(first)?,
894                    None => return Err(Unfillable::of(ty, "has no alternatives")),
895                }
896            }
897            Type::Function { .. } | Type::Future { .. } => {
898                return Err(Unfillable::of(ty, "is a runtime handle, not data"));
899            }
900            Type::Ref(r) => match self.shape.resolve(r) {
901                Ok(Resolved::Alias(target)) => self.fill(&target)?,
902                Ok(Resolved::Fields(fields)) => self.fill_fields(&fields)?,
903                Ok(Resolved::Interface) => {
904                    return Err(Unfillable::of(
905                        ty,
906                        "is an interface, which can be satisfied but not constructed",
907                    ));
908                }
909                Ok(Resolved::Variants(variants)) => {
910                    if variants.is_empty() {
911                        return Err(Unfillable::of(ty, "has no variants"));
912                    }
913                    let variant = &variants[k % variants.len()];
914                    Value::Variant {
915                        tag: variant.name.to_string(),
916                        value: Box::new(self.fill(&variant.payload)?),
917                    }
918                }
919                Err(_) => return Err(Unfillable::of(ty, "does not resolve")),
920            },
921        })
922    }
923
924    fn fill_fields(&mut self, fields: &[Field]) -> Result<Value, Unfillable> {
925        let mut out = Vec::with_capacity(fields.len());
926        for field in fields {
927            out.push((field.name.to_string(), self.fill(&field.ty)?));
928        }
929        Ok(Value::record(out))
930    }
931}
932
933#[cfg(test)]
934mod tests {
935    use super::*;
936    use std::sync::Arc;
937    use unitype_core::check::check_workspace;
938    use unitype_core::{BigO, ImplProfile, Workspace};
939
940    use crate::error::ExecError;
941    use crate::implementation::Implementation;
942    use crate::registry::Registry;
943
944    const WS: &str = r#"{"universes":[{"name":"demo",
945      "types":[
946        {"k":"struct","name":"Box","params":[{"name":"T"}],
947         "fields":[{"name":"label","ty":"str"},{"name":"inside","ty":{"k":"param","name":"T"}}]},
948        {"k":"interface","name":"Identified","fields":[{"name":"id","ty":"str"}]},
949        {"k":"enum","name":"Maybe","params":[{"name":"T"}],
950         "variants":[{"name":"nothing"},{"name":"just","payload":{"k":"param","name":"T"}}]}],
951      "functions":[
952        {"name":"reverse","params_decl":[{"name":"T"}],
953         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
954         "ret":{"k":"list","of":{"k":"param","name":"T"}}},
955        {"name":"first","params_decl":[{"name":"T"}],
956         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
957         "ret":{"k":"optional","of":{"k":"param","name":"T"}}},
958        {"name":"swap","params_decl":[{"name":"A"},{"name":"B"}],
959         "params":[{"name":"a","ty":{"k":"param","name":"A"}},{"name":"b","ty":{"k":"param","name":"B"}}],
960         "ret":{"k":"tuple","items":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
961        {"name":"unbox","params_decl":[{"name":"T"}],
962         "params":[{"name":"b","ty":{"k":"ref","name":"Box","args":[{"k":"param","name":"T"}]}}],
963         "ret":{"k":"ref","name":"Maybe","args":[{"k":"param","name":"T"}]}},
964        {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"},
965        {"name":"ids","params_decl":[{"name":"T","bounds":["Identified"]}],
966         "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
967         "ret":"[str]"},
968        {"name":"either","params_decl":[{"name":"T"}],
969         "params":[{"name":"x","ty":{"k":"union","members":[{"k":"param","name":"T"},"str"]}}],
970         "ret":{"k":"param","name":"T"}}]}]}"#;
971
972    fn q(s: &str) -> QualifiedName {
973        s.parse().unwrap()
974    }
975
976    fn list(value: &Value) -> Vec<Value> {
977        match value {
978            Value::List(items) => items.clone(),
979            _ => Vec::new(),
980        }
981    }
982
983    /// Every proof this file talks about, under the name it is talked about by.
984    fn registry() -> Registry {
985        let mut registry = Registry::new();
986
987        registry.register_native_sync("reverses", |args| {
988            let mut items = list(&args[0]);
989            items.reverse();
990            Ok(Value::List(items))
991        });
992        // Sorts when it can tell the elements are integers, and reverses
993        // otherwise: right at every type the author tried, and not parametric.
994        registry.register_native_sync("sorts_integers", |args| {
995            let mut items = list(&args[0]);
996            if items.iter().all(|v| v.as_int().is_some()) {
997                items.sort_by_key(|v| v.as_int());
998            } else {
999                items.reverse();
1000            }
1001            Ok(Value::List(items))
1002        });
1003        // Reverses, unless the first two are equal, in which case it forgets
1004        // the rest. Only a relabelling that makes two tokens equal finds this.
1005        registry.register_native_sync("compares", |args| {
1006            let mut items = list(&args[0]);
1007            if items.len() >= 2 && items[0] == items[1] {
1008                items.truncate(1);
1009            } else {
1010                items.reverse();
1011            }
1012            Ok(Value::List(items))
1013        });
1014        // Pads an empty list with something it made up.
1015        registry.register_native_sync("pads", |args| {
1016            let mut items = list(&args[0]);
1017            if items.is_empty() {
1018                items.push(Value::Int(0));
1019            }
1020            items.reverse();
1021            Ok(Value::List(items))
1022        });
1023        // Only works at one type.
1024        registry.register_native_sync("integers_only", |args| {
1025            let items = list(&args[0]);
1026            if items.iter().any(|v| v.as_int().is_none()) {
1027                return Err(ExecError::Failed {
1028                    id: "integers_only".into(),
1029                    message: "expected integers".into(),
1030                });
1031            }
1032            Ok(Value::List(items.into_iter().rev().collect()))
1033        });
1034        registry.register_native_sync("heads", |args| {
1035            Ok(list(&args[0]).into_iter().next().unwrap_or(Value::Null))
1036        });
1037        registry.register_native_sync("swaps", |mut args| {
1038            let b = args.remove(1);
1039            let a = args.remove(0);
1040            Ok(Value::Tuple(vec![b, a]))
1041        });
1042        // Returns the pair the way it came: an `A` where a `B` was promised.
1043        registry.register_native_sync("keeps", |args| Ok(Value::Tuple(args)));
1044        registry.register_native_sync("unboxes", |mut args| {
1045            let Value::Record(mut fields) = args.remove(0) else {
1046                return Err(ExecError::Untyped("expected a record".into()));
1047            };
1048            let inside = fields.swap_remove("inside").unwrap_or(Value::Null);
1049            Ok(Value::Variant {
1050                tag: "just".into(),
1051                value: Box::new(inside),
1052            })
1053        });
1054        registry
1055    }
1056
1057    fn dispatcher(proves: &[(&str, &str)]) -> Dispatcher {
1058        let ws =
1059            Arc::new(check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks"));
1060        let mut registry = registry();
1061        for (entry, sig) in proves {
1062            registry
1063                .register(Implementation::new(
1064                    *entry,
1065                    q(sig),
1066                    Ident::new("here").unwrap(),
1067                    *entry,
1068                    ImplProfile::new(BigO::ON, BigO::ON),
1069                ))
1070                .expect("registers");
1071        }
1072        Dispatcher::new(ws, Arc::new(registry))
1073    }
1074
1075    /// The one verdict a proof got that was not `Held`, if any.
1076    fn against(theorems: &Theorems, id: &str) -> Option<Verdict> {
1077        theorems
1078            .trials
1079            .iter()
1080            .filter_map(|t| t.verdicts.get(&ImplId::new(id)))
1081            .find(|v| v.is_against())
1082            .cloned()
1083    }
1084
1085    #[tokio::test]
1086    async fn a_parametric_proof_holds_without_anyone_saying_what_it_should_return() {
1087        let theorems = check(
1088            &dispatcher(&[("reverses", "demo::reverse")]),
1089            &q("demo::reverse"),
1090        )
1091        .await
1092        .expect("checks");
1093
1094        assert!(theorems.held(), "{:?}", theorems.broken());
1095        assert_eq!(theorems.trials.len(), TRIALS);
1096        assert_eq!(theorems.heading(), "demo::reverse<T>");
1097    }
1098
1099    #[tokio::test]
1100    async fn a_proof_that_looks_at_the_elements_breaks_naturality() {
1101        // At `i64` it sorts, which is a permutation, so conservation holds.
1102        // At `str` it does something else, which is the whole complaint.
1103        let theorems = check(
1104            &dispatcher(&[("sorts_integers", "demo::reverse")]),
1105            &q("demo::reverse"),
1106        )
1107        .await
1108        .expect("checks");
1109
1110        let verdict = against(&theorems, "sorts_integers").expect("caught");
1111        assert!(
1112            matches!(
1113                &verdict,
1114                Verdict::Broken {
1115                    law: Law::Naturality,
1116                    ..
1117                }
1118            ),
1119            "{verdict:?}"
1120        );
1121        assert!(
1122            verdict.summary().contains("T = str"),
1123            "{}",
1124            verdict.summary()
1125        );
1126    }
1127
1128    #[tokio::test]
1129    async fn a_proof_that_compares_two_elements_is_found_by_collapsing_them() {
1130        // Distinct tokens never compare equal, and neither do distinct
1131        // strings, so only a relabelling that makes two equal can show this.
1132        let theorems = check(
1133            &dispatcher(&[("compares", "demo::reverse")]),
1134            &q("demo::reverse"),
1135        )
1136        .await
1137        .expect("checks");
1138
1139        let verdict = against(&theorems, "compares").expect("caught");
1140        assert!(
1141            verdict.summary().contains("made equal"),
1142            "{}",
1143            verdict.summary()
1144        );
1145    }
1146
1147    #[tokio::test]
1148    async fn a_proof_that_makes_up_an_element_breaks_conservation() {
1149        let theorems = check(
1150            &dispatcher(&[("pads", "demo::reverse")]),
1151            &q("demo::reverse"),
1152        )
1153        .await
1154        .expect("checks");
1155
1156        let verdict = against(&theorems, "pads").expect("caught");
1157        assert!(
1158            matches!(
1159                verdict,
1160                Verdict::Broken {
1161                    law: Law::Conservation,
1162                    ..
1163                }
1164            ),
1165            "{verdict:?}"
1166        );
1167        assert!(
1168            !theorems.trials[0].held(),
1169            "the empty list is where it pads"
1170        );
1171        assert!(theorems.trials[1].held(), "and nowhere else");
1172    }
1173
1174    #[tokio::test]
1175    async fn a_proof_that_only_works_at_one_type_has_not_proved_the_generic_claim() {
1176        let theorems = check(
1177            &dispatcher(&[("integers_only", "demo::reverse")]),
1178            &q("demo::reverse"),
1179        )
1180        .await
1181        .expect("checks");
1182
1183        let verdict = against(&theorems, "integers_only").expect("caught");
1184        assert!(
1185            matches!(
1186                verdict,
1187                Verdict::Broken {
1188                    law: Law::Naturality,
1189                    ..
1190                }
1191            ),
1192            "failing at another type breaks the law rather than excusing the proof: {verdict:?}"
1193        );
1194        assert!(
1195            theorems.trials[0].held(),
1196            "on the empty list there was nothing to be the wrong type"
1197        );
1198    }
1199
1200    #[tokio::test]
1201    async fn the_right_proof_and_the_wrong_one_are_told_apart_side_by_side() {
1202        let theorems = check(
1203            &dispatcher(&[
1204                ("reverses", "demo::reverse"),
1205                ("sorts_integers", "demo::reverse"),
1206            ]),
1207            &q("demo::reverse"),
1208        )
1209        .await
1210        .expect("checks");
1211
1212        assert!(against(&theorems, "reverses").is_none());
1213        assert!(against(&theorems, "sorts_integers").is_some());
1214        assert!(!theorems.held());
1215    }
1216
1217    #[tokio::test]
1218    async fn absence_in_the_result_is_a_position_with_nothing_in_it() {
1219        let theorems = check(&dispatcher(&[("heads", "demo::first")]), &q("demo::first"))
1220            .await
1221            .expect("checks");
1222        assert!(theorems.held(), "{:?}", theorems.broken());
1223    }
1224
1225    #[tokio::test]
1226    async fn two_parameters_are_told_apart() {
1227        let honest = check(&dispatcher(&[("swaps", "demo::swap")]), &q("demo::swap"))
1228            .await
1229            .expect("checks");
1230        assert!(honest.held(), "{:?}", honest.broken());
1231        assert_eq!(honest.heading(), "demo::swap<A, B>");
1232
1233        // Handing back an `A` where a `B` was promised is making up a `B`.
1234        let dishonest = check(&dispatcher(&[("keeps", "demo::swap")]), &q("demo::swap"))
1235            .await
1236            .expect("checks");
1237        let verdict = against(&dishonest, "keeps").expect("caught");
1238        assert!(
1239            matches!(
1240                verdict,
1241                Verdict::Broken {
1242                    law: Law::Conservation,
1243                    ..
1244                }
1245            ),
1246            "{verdict:?}"
1247        );
1248    }
1249
1250    #[tokio::test]
1251    async fn parameters_are_found_inside_declared_types() {
1252        // A `T` inside a struct field going in, and inside an enum payload
1253        // coming out: both reached through the declarations.
1254        let theorems = check(
1255            &dispatcher(&[("unboxes", "demo::unbox")]),
1256            &q("demo::unbox"),
1257        )
1258        .await
1259        .expect("checks");
1260        assert!(theorems.held(), "{:?}", theorems.broken());
1261        assert!(
1262            theorems.trials[0].name.contains("\"inside\":0"),
1263            "the token should have been put in the field: {}",
1264            theorems.trials[0].name
1265        );
1266    }
1267
1268    #[tokio::test]
1269    async fn a_proposition_with_nothing_generic_about_it_has_no_theorem() {
1270        let d = dispatcher(&[]);
1271        assert!(matches!(
1272            applies(d.workspace(), &q("demo::sort")),
1273            Err(ParametricError::NotGeneric(_))
1274        ));
1275    }
1276
1277    #[tokio::test]
1278    async fn a_bounded_parameter_is_declined_rather_than_held_to_a_law_it_need_not_obey() {
1279        let d = dispatcher(&[]);
1280        let err = applies(d.workspace(), &q("demo::ids")).unwrap_err();
1281        assert!(matches!(err, ParametricError::Bounded { .. }), "{err}");
1282        assert!(err.to_string().contains("Identified"), "{err}");
1283    }
1284
1285    #[tokio::test]
1286    async fn a_parameter_under_an_untagged_union_cannot_be_found() {
1287        let d = dispatcher(&[]);
1288        let err = applies(d.workspace(), &q("demo::either")).unwrap_err();
1289        assert!(matches!(err, ParametricError::Unfillable { .. }), "{err}");
1290        assert!(err.to_string().contains("untagged union"), "{err}");
1291    }
1292
1293    #[tokio::test]
1294    async fn nothing_to_check_is_said_rather_than_passed() {
1295        assert!(matches!(
1296            check(&dispatcher(&[]), &q("demo::reverse")).await,
1297            Err(ParametricError::NoProofs(_))
1298        ));
1299    }
1300
1301    #[test]
1302    fn tokens_say_which_parameter_they_stand_for() {
1303        let token = Token {
1304            param: 1,
1305            ordinal: 7,
1306        };
1307        assert_eq!(Token::decode(&token.value()), Some(token));
1308        assert_eq!(Token::decode(&Value::Str("T7".into())), None);
1309    }
1310}