Lines
94.66 %
Functions
95.65 %
Branches
100 %
//! The first return-type guess of a self-recursive function, shared by the
//! codegen monomorph pass and the eval-path stand-in so both start alike.
use crate::ast::{Expr, Number, WasmType};
use crate::runtime::MAX_SHARED_RECURSION_DEPTH;
use crate::compiler::native::chain_pair_element;
use crate::compiler::special::binding::spec_name;
use super::stack::classify_stack_type;
/// The type of the first non-recursive exit of `body` when it is statically
/// known, else the first argument's type when numeric, else `Ratio`. An
/// integer literal exit is an Index unless the recursion accumulates a scalar:
/// a fractional literal beside a self call, or a scalar numeric argument.
#[must_use]
pub(in crate::compiler) fn recursive_ret_guess(
name: &str,
params: &[String],
body: &Expr,
arg_types: impl IntoIterator<Item = Option<WasmType>>,
) -> WasmType {
let args: Vec<Option<WasmType>> = arg_types.into_iter().collect();
let first_numeric = args.first().copied().flatten().filter(is_numeric);
exit_type(name, body, 0, &[], &|exit, bound| {
leaf_type(exit, params, bound, &args)
})
.map(|exit| match exit {
WasmType::I32 if scalar_beside_call(name, body, 0) || scalar_numeric_arg(&args) => {
WasmType::Ratio
}
other => other,
.or(first_numeric)
.unwrap_or(WasmType::Ratio)
fn is_numeric(ty: &WasmType) -> bool {
matches!(ty, WasmType::I32 | WasmType::Ratio | WasmType::Commodity)
fn scalar_numeric_arg(args: &[Option<WasmType>]) -> bool {
args.iter()
.flatten()
.find(|ty| is_numeric(ty))
.is_some_and(|ty| *ty != WasmType::I32)
fn is_call_of(name: &str, form: &Expr) -> bool {
matches!(form, Expr::List(elems)
if matches!(elems.first(), Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case(name)))
fn scalar_beside_call(name: &str, form: &Expr, depth: usize) -> bool {
let Expr::List(elems) = form else {
return false;
};
if depth > MAX_SHARED_RECURSION_DEPTH {
let fractional = elems
.iter()
.any(|elem| matches!(elem, Expr::Number(Number::Scalar(_))));
(fractional && elems.iter().any(|elem| is_call_of(name, elem)))
|| elems
.any(|elem| scalar_beside_call(name, elem, depth + 1))
/// The type of an exit that does not call the function: a bare parameter that
/// no `LET` on the way rebound has its argument's type, a `(list …)` of
/// literals and such parameters is a pair.
fn leaf_type(
form: &Expr,
bound: &[String],
args: &[Option<WasmType>],
) -> Option<WasmType> {
let param_type = |symbol: &str| {
let hidden = bound.iter().any(|name| name.eq_ignore_ascii_case(symbol));
params
.position(|param| param.eq_ignore_ascii_case(symbol))
.filter(|_| !hidden)
.and_then(|at| args.get(at).copied().flatten())
match form {
Expr::Symbol(symbol) => param_type(symbol),
Expr::List(elems) => match elems.as_slice() {
[Expr::Symbol(head), cars @ ..]
if head.eq_ignore_ascii_case("LIST") && !cars.is_empty() =>
{
let cars: Option<Vec<Expr>> =
cars.iter().map(|car| list_car(car, ¶m_type)).collect();
chain_pair_element(&cars?).ok().map(WasmType::PairRef)
_ => classify_stack_type(form),
},
/// A `LIST` element the guess can type: a literal, or a parameter standing
/// for a runtime value of its argument's type.
fn list_car(car: &Expr, param_type: &dyn Fn(&str) -> Option<WasmType>) -> Option<Expr> {
match car {
Expr::Number(_) | Expr::String(_) | Expr::T | Expr::Nil => Some(car.clone()),
Expr::Symbol(symbol) => param_type(symbol).map(Expr::WasmRuntime),
_ => None,
fn let_bound_names(bindings: Option<&Expr>) -> impl Iterator<Item = &str> {
let bindings: &[Expr] = match bindings {
Some(Expr::List(bindings)) => bindings,
_ => &[],
bindings.iter().filter_map(spec_name)
fn exit_type(
depth: usize,
leaf: &dyn Fn(&Expr, &[String]) -> Option<WasmType>,
return None;
if !calls(name, form, depth) {
return leaf(form, bound);
let Some(Expr::Symbol(head)) = elems.first() else {
let arms = |arms: &[Expr]| {
arms.iter()
.find_map(|arm| exit_type(name, arm, depth + 1, bound, leaf))
match head.to_ascii_uppercase().as_str() {
"IF" => arms(elems.get(2..)?),
"PROGN" => elems
.last()
.and_then(|last| exit_type(name, last, depth + 1, bound, leaf)),
"LET" | "LET*" => {
let inner: Vec<String> = bound
.cloned()
.chain(let_bound_names(elems.get(1)).map(String::from))
.collect();
elems
.and_then(|last| exit_type(name, last, depth + 1, &inner, leaf))
"COND" => elems[1..]
.filter_map(|clause| match clause {
Expr::List(parts) => parts.last(),
.find_map(|arm| exit_type(name, arm, depth + 1, bound, leaf)),
fn calls(name: &str, form: &Expr, depth: usize) -> bool {
Expr::Symbol(symbol) => symbol.eq_ignore_ascii_case(name),
Expr::List(elems) => {
depth > MAX_SHARED_RECURSION_DEPTH
|| elems.iter().any(|elem| calls(name, elem, depth + 1))
_ => false,
#[cfg(test)]
#[path = "ret_guess_tests.rs"]
mod tests;