1
//! The first return-type guess of a self-recursive function, shared by the
2
//! codegen monomorph pass and the eval-path stand-in so both start alike.
3

            
4
use crate::ast::{Expr, Number, WasmType};
5

            
6
use crate::runtime::MAX_SHARED_RECURSION_DEPTH;
7

            
8
use crate::compiler::native::chain_pair_element;
9
use crate::compiler::special::binding::spec_name;
10

            
11
use super::stack::classify_stack_type;
12

            
13
/// The type of the first non-recursive exit of `body` when it is statically
14
/// known, else the first argument's type when numeric, else `Ratio`. An
15
/// integer literal exit is an Index unless the recursion accumulates a scalar:
16
/// a fractional literal beside a self call, or a scalar numeric argument.
17
#[must_use]
18
67421
pub(in crate::compiler) fn recursive_ret_guess(
19
67421
    name: &str,
20
67421
    params: &[String],
21
67421
    body: &Expr,
22
67421
    arg_types: impl IntoIterator<Item = Option<WasmType>>,
23
67421
) -> WasmType {
24
67421
    let args: Vec<Option<WasmType>> = arg_types.into_iter().collect();
25
67421
    let first_numeric = args.first().copied().flatten().filter(is_numeric);
26
67421
    exit_type(name, body, 0, &[], &|exit, bound| {
27
62826
        leaf_type(exit, params, bound, &args)
28
62826
    })
29
24458
    .map(|exit| match exit {
30
12164
        WasmType::I32 if scalar_beside_call(name, body, 0) || scalar_numeric_arg(&args) => {
31
2
            WasmType::Ratio
32
        }
33
24456
        other => other,
34
24458
    })
35
67421
    .or(first_numeric)
36
67421
    .unwrap_or(WasmType::Ratio)
37
67421
}
38

            
39
86040
fn is_numeric(ty: &WasmType) -> bool {
40
86040
    matches!(ty, WasmType::I32 | WasmType::Ratio | WasmType::Commodity)
41
86040
}
42

            
43
12163
fn scalar_numeric_arg(args: &[Option<WasmType>]) -> bool {
44
12163
    args.iter()
45
12163
        .flatten()
46
18622
        .find(|ty| is_numeric(ty))
47
12160
        .is_some_and(|ty| *ty != WasmType::I32)
48
12163
}
49

            
50
3
fn is_call_of(name: &str, form: &Expr) -> bool {
51
3
    matches!(form, Expr::List(elems)
52
1
        if matches!(elems.first(), Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case(name)))
53
3
}
54

            
55
236290
fn scalar_beside_call(name: &str, form: &Expr, depth: usize) -> bool {
56
236290
    let Expr::List(elems) = form else {
57
160224
        return false;
58
    };
59
76066
    if depth > MAX_SHARED_RECURSION_DEPTH {
60
        return false;
61
76066
    }
62
76066
    let fractional = elems
63
76066
        .iter()
64
224128
        .any(|elem| matches!(elem, Expr::Number(Number::Scalar(_))));
65
76066
    (fractional && elems.iter().any(|elem| is_call_of(name, elem)))
66
76065
        || elems
67
76065
            .iter()
68
224126
            .any(|elem| scalar_beside_call(name, elem, depth + 1))
69
236290
}
70

            
71
/// The type of an exit that does not call the function: a bare parameter that
72
/// no `LET` on the way rebound has its argument's type, a `(list …)` of
73
/// literals and such parameters is a pair.
74
62826
fn leaf_type(
75
62826
    form: &Expr,
76
62826
    params: &[String],
77
62826
    bound: &[String],
78
62826
    args: &[Option<WasmType>],
79
62826
) -> Option<WasmType> {
80
15953
    let param_type = |symbol: &str| {
81
15953
        let hidden = bound.iter().any(|name| name.eq_ignore_ascii_case(symbol));
82
15953
        params
83
15953
            .iter()
84
21154
            .position(|param| param.eq_ignore_ascii_case(symbol))
85
11460
            .filter(|_| !hidden)
86
9794
            .and_then(|at| args.get(at).copied().flatten())
87
15953
    };
88
62826
    match form {
89
14080
        Expr::Symbol(symbol) => param_type(symbol),
90
34068
        Expr::List(elems) => match elems.as_slice() {
91
            [Expr::Symbol(head), cars @ ..]
92
34068
                if head.eq_ignore_ascii_case("LIST") && !cars.is_empty() =>
93
            {
94
                let cars: Option<Vec<Expr>> =
95
2498
                    cars.iter().map(|car| list_car(car, &param_type)).collect();
96
1874
                chain_pair_element(&cars?).ok().map(WasmType::PairRef)
97
            }
98
32194
            _ => classify_stack_type(form),
99
        },
100
14678
        _ => classify_stack_type(form),
101
    }
102
62826
}
103

            
104
/// A `LIST` element the guess can type: a literal, or a parameter standing
105
/// for a runtime value of its argument's type.
106
2498
fn list_car(car: &Expr, param_type: &dyn Fn(&str) -> Option<WasmType>) -> Option<Expr> {
107
2498
    match car {
108
625
        Expr::Number(_) | Expr::String(_) | Expr::T | Expr::Nil => Some(car.clone()),
109
1873
        Expr::Symbol(symbol) => param_type(symbol).map(Expr::WasmRuntime),
110
        _ => None,
111
    }
112
2498
}
113

            
114
2541
fn let_bound_names(bindings: Option<&Expr>) -> impl Iterator<Item = &str> {
115
2541
    let bindings: &[Expr] = match bindings {
116
2541
        Some(Expr::List(bindings)) => bindings,
117
        _ => &[],
118
    };
119
2541
    bindings.iter().filter_map(spec_name)
120
2541
}
121

            
122
151884
fn exit_type(
123
151884
    name: &str,
124
151884
    form: &Expr,
125
151884
    depth: usize,
126
151884
    bound: &[String],
127
151884
    leaf: &dyn Fn(&Expr, &[String]) -> Option<WasmType>,
128
151884
) -> Option<WasmType> {
129
151884
    if depth > MAX_SHARED_RECURSION_DEPTH {
130
        return None;
131
151884
    }
132
151884
    if !calls(name, form, depth) {
133
62826
        return leaf(form, bound);
134
89058
    }
135
89058
    let Expr::List(elems) = form else {
136
        return None;
137
    };
138
89058
    let Some(Expr::Symbol(head)) = elems.first() else {
139
        return None;
140
    };
141
51099
    let arms = |arms: &[Expr]| {
142
51099
        arms.iter()
143
80239
            .find_map(|arm| exit_type(name, arm, depth + 1, bound, leaf))
144
51099
    };
145
89058
    match head.to_ascii_uppercase().as_str() {
146
51099
        "IF" => arms(elems.get(2..)?),
147
18
        "PROGN" => elems
148
18
            .last()
149
18
            .and_then(|last| exit_type(name, last, depth + 1, bound, leaf)),
150
        "LET" | "LET*" => {
151
2541
            let inner: Vec<String> = bound
152
2541
                .iter()
153
2541
                .cloned()
154
2541
                .chain(let_bound_names(elems.get(1)).map(String::from))
155
2541
                .collect();
156
2541
            elems
157
2541
                .last()
158
2541
                .and_then(|last| exit_type(name, last, depth + 1, &inner, leaf))
159
        }
160
833
        "COND" => elems[1..]
161
833
            .iter()
162
1665
            .filter_map(|clause| match clause {
163
1665
                Expr::List(parts) => parts.last(),
164
                _ => None,
165
1665
            })
166
1665
            .find_map(|arm| exit_type(name, arm, depth + 1, bound, leaf)),
167
34567
        _ => None,
168
    }
169
151884
}
170

            
171
1034405
fn calls(name: &str, form: &Expr, depth: usize) -> bool {
172
1034405
    match form {
173
447446
        Expr::Symbol(symbol) => symbol.eq_ignore_ascii_case(name),
174
        Expr::List(elems) => {
175
349613
            depth > MAX_SHARED_RECURSION_DEPTH
176
882521
                || elems.iter().any(|elem| calls(name, elem, depth + 1))
177
        }
178
237346
        _ => false,
179
    }
180
1034405
}
181

            
182
#[cfg(test)]
183
#[path = "ret_guess_tests.rs"]
184
mod tests;