1
//! Trial typing: the parameters no use pins take the numeric dimensions under
2
//! which the body evaluates, when every fitting assignment agrees on them.
3

            
4
use crate::ast::{Expr, LambdaParams, WasmType};
5
use crate::compiler::expr::eval_value;
6
use crate::error::Error;
7
use crate::runtime::SymbolTable;
8

            
9
use super::PLACEHOLDER;
10

            
11
const DIMENSIONS: [WasmType; 3] = [PLACEHOLDER, WasmType::Ratio, WasmType::Commodity];
12

            
13
/// `3^MAX_FREE` probes per lambda; more unpinned parameters get no trial pin.
14
const MAX_FREE: usize = 4;
15

            
16
/// The joint assignments of the unpinned parameters under which the body
17
/// evaluates: one dimension per unpinned parameter, in order.
18
struct Fits {
19
    free: Vec<usize>,
20
    assignments: Vec<Vec<WasmType>>,
21
}
22

            
23
impl Fits {
24
    /// `None` when no verdict can stand: nothing to try, too many unpinned
25
    /// parameters, or a probe out of its resource budget.
26
253098
    fn of(
27
253098
        symbols: &SymbolTable,
28
253098
        (params, body): (&LambdaParams, &Expr),
29
253098
        pins: &[Option<WasmType>],
30
253098
    ) -> Option<Self> {
31
253098
        let free: Vec<usize> = (0..pins.len()).filter(|&i| pins[i].is_none()).collect();
32
253098
        if free.is_empty() || free.len() > MAX_FREE {
33
131947
            return None;
34
121151
        }
35
121151
        let callee = Expr::Lambda(params.clone(), Box::new(body.clone()));
36
121151
        let mut assignments = Vec::new();
37
121151
        for assignment in assignments_of(free.len()) {
38
292979
            if fits(symbols, &callee, arguments(pins, &free, &assignment))? {
39
201064
                assignments.push(assignment);
40
43031
            }
41
        }
42
72267
        Some(Self { free, assignments })
43
253098
    }
44

            
45
76766
    fn dimensions(&self, slot: usize) -> Vec<WasmType> {
46
76766
        let mut seen = Vec::new();
47
76766
        for assignment in &self.assignments {
48
220094
            if !seen.contains(&assignment[slot]) {
49
206738
                seen.push(assignment[slot]);
50
13356
            }
51
        }
52
76766
        seen
53
76766
    }
54
}
55

            
56
/// For each parameter no use pins, the dimensions some fitting joint assignment
57
/// gives it, empty for a pinned parameter; `None` for every parameter when no
58
/// verdict stands.
59
253098
pub(super) fn fitting_dimensions(
60
253098
    symbols: &SymbolTable,
61
253098
    lambda: (&LambdaParams, &Expr),
62
253098
    pins: &[Option<WasmType>],
63
253098
) -> Option<Vec<Vec<WasmType>>> {
64
253098
    let fits = Fits::of(symbols, lambda, pins)?;
65
72267
    let mut dimensions = vec![Vec::new(); pins.len()];
66
72267
    for (slot, &index) in fits.free.iter().enumerate() {
67
76766
        dimensions[index] = fits.dimensions(slot);
68
    }
69
72267
    Some(dimensions)
70
253098
}
71

            
72
121151
fn assignments_of(count: usize) -> Vec<Vec<WasmType>> {
73
125650
    (0..count).fold(vec![Vec::new()], |prefixes, _| {
74
125650
        prefixes
75
125650
            .iter()
76
134798
            .flat_map(|prefix| {
77
404394
                DIMENSIONS.map(|ty| {
78
404394
                    let mut next = prefix.clone();
79
404394
                    next.push(ty);
80
404394
                    next
81
404394
                })
82
134798
            })
83
            .collect()
84
125650
    })
85
121151
}
86

            
87
292979
fn arguments(pins: &[Option<WasmType>], free: &[usize], assignment: &[WasmType]) -> Vec<Expr> {
88
292979
    let mut tried = pins.to_vec();
89
292979
    for (&slot, &ty) in free.iter().zip(assignment) {
90
334550
        tried[slot] = Some(ty);
91
    }
92
292979
    tried.into_iter().flatten().map(Expr::WasmRuntime).collect()
93
292979
}
94

            
95
/// `None` when the probe ran out of its resource budget: no verdict to stand on.
96
292979
fn fits(symbols: &SymbolTable, callee: &Expr, arguments: Vec<Expr>) -> Option<bool> {
97
292979
    let call = Expr::List(
98
292979
        [Expr::symbol("FUNCALL"), callee.clone()]
99
292979
            .into_iter()
100
292979
            .chain(arguments)
101
292979
            .collect(),
102
292979
    );
103
292979
    match symbols
104
292979
        .speculative_clone()
105
290881
        .within_shared_recursion(|scratch| eval_value(scratch, &call))
106
    {
107
48884
        Err(Error::Resource(_)) => None,
108
244095
        verdict => Some(verdict.is_ok()),
109
    }
110
292979
}