Skip to main content

code_transpiler/
call_resolution.rs

1use crate::matrix::Matrix;
2use std::collections::BTreeSet;
3
4pub const EXACT_CALL_RESOLUTION_CAPABILITY: &str = "call.resolution.exact.v1";
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct CallCandidate {
8    pub name: String,
9    pub declaration: String,
10}
11#[derive(Debug, Clone, PartialEq)]
12pub struct CallResolution {
13    pub candidates: Vec<CallCandidate>,
14    pub obligations: Vec<String>,
15    pub selected: Option<usize>,
16    pub required: Matrix,
17    pub satisfied: Matrix,
18    pub conversion_cost: Matrix,
19    pub priority: Vec<f64>,
20}
21
22fn finite_nonnegative(v: f64) -> bool {
23    v.is_finite() && v >= 0.0
24}
25fn score_less(a: (f64, f64, f64), b: (f64, f64, f64)) -> bool {
26    a.0 < b.0 || (a.0 == b.0 && (a.1 < b.1 || (a.1 == b.1 && a.2 < b.2)))
27}
28
29pub fn validate_call_resolution(r: &CallResolution, arguments: usize) -> Result<usize, String> {
30    let n = r.candidates.len();
31    let obligations = r.obligations.len();
32    let selected = r
33        .selected
34        .ok_or_else(|| "call resolution has no valid selected candidate".to_string())?;
35    if n == 0 || selected >= n {
36        return Err("call resolution has no valid selected candidate".into());
37    }
38    if !r.required.valid()
39        || !r.satisfied.valid()
40        || !r.conversion_cost.valid()
41        || r.required.rows != n
42        || r.required.cols != obligations
43        || r.satisfied.rows != n
44        || r.satisfied.cols != obligations
45        || r.conversion_cost.rows != n
46        || r.conversion_cost.cols != arguments
47        || r.priority.len() != n
48    {
49        return Err(
50            "call resolution matrix dimensions do not match candidates, obligations, and arguments"
51                .into(),
52        );
53    }
54    let mut obs = BTreeSet::new();
55    for o in &r.obligations {
56        if o.is_empty() || !obs.insert(o.clone()) {
57            return Err("call resolution obligation names must be unique and nonempty".into());
58        }
59    }
60    let mut cand = BTreeSet::new();
61    for c in &r.candidates {
62        let key = format!("{}\0{}", c.name, c.declaration);
63        if c.name.is_empty() || !cand.insert(key) {
64            return Err("call resolution candidates must be unique and named".into());
65        }
66    }
67    let mut scores = Vec::with_capacity(n);
68    for row in 0..n {
69        if !finite_nonnegative(r.priority[row]) {
70            return Err("call resolution priority must be finite and nonnegative".into());
71        }
72        let mut missing = 0.0;
73        let mut cost = 0.0;
74        for col in 0..obligations {
75            let req = r.required.at(row, col);
76            let sat = r.satisfied.at(row, col);
77            if (req != 0.0 && req != 1.0) || (sat != 0.0 && sat != 1.0) || sat > req {
78                return Err("call resolution obligation planes must be binary and satisfied implies required".into());
79            }
80            missing += req * (1.0 - sat);
81        }
82        for col in 0..arguments {
83            let v = r.conversion_cost.at(row, col);
84            if !finite_nonnegative(v) {
85                return Err(
86                    "call resolution conversion costs must be finite and nonnegative".into(),
87                );
88            }
89            cost += v;
90        }
91        scores.push((missing, cost, r.priority[row]));
92    }
93    let mut best = 0usize;
94    for i in 1..n {
95        if score_less(scores[i], scores[best]) {
96            best = i;
97        }
98    }
99    let ties = scores.iter().filter(|&&s| s == scores[best]).count();
100    if ties != 1 {
101        return Err("call resolution is ambiguous at the minimum matrix score".into());
102    }
103    if selected != best {
104        return Err(format!(
105            "selected call candidate {selected} does not match matrix result {best}"
106        ));
107    }
108    Ok(best)
109}