rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Invocation effects are value metadata, independent of a function signature.
use crate::{ExprId, Span};
pub use rils_builtins::CallableTraitKind as CallableKind;
use std::collections::HashMap;

pub fn callable_contract_signature(bound: &crate::Type) -> Option<crate::Type> {
    use crate::Type;
    let Type::Named { name, arguments } = bound else {
        return None;
    };
    rils_builtins::callable_trait_kind(name)?;
    let [parameters, output] = arguments.as_slice() else {
        return None;
    };
    let parameters = match parameters {
        Type::Unit => Vec::new(),
        Type::Tuple(parameters) => parameters.clone(),
        _ => return None,
    };
    Some(Type::function(parameters, output.clone()))
}

/// Infer other type parameters from a callable's declared argument/result
/// contract, e.g. F: FnMut<(T,), U> with F = fn(i32) -> string.
pub fn infer_callable_generics(
    parameters: &[crate::ast::GenericParameter],
    bindings: &mut HashMap<String, crate::Type>,
    resolve: impl Fn(&crate::Type, &HashMap<String, crate::Type>) -> crate::Type,
) -> Result<(), String> {
    for _ in 0..parameters.len().max(1) {
        let before = bindings.clone();
        for parameter in parameters {
            let Some(actual @ crate::Type::Function { .. }) =
                bindings.get(&parameter.name).cloned()
            else {
                continue;
            };
            for bound in &parameter.bounds {
                let known = bindings
                    .iter()
                    .filter(|(_, ty)| ty.is_concrete_type())
                    .map(|(name, ty)| (name.clone(), ty.clone()))
                    .collect();
                if let Some(signature) = callable_contract_signature(&resolve(bound, &known)) {
                    crate::types::infer_generic_arguments(&signature, &actual, bindings)?;
                }
            }
        }
        if *bindings == before {
            break;
        }
    }
    Ok(())
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CallableCapabilities {
    pub(crate) bodies: HashMap<Span, CallableKind>,
    pub(crate) parameters: HashMap<Span, Vec<Option<CallableKind>>>,
    pub(crate) expressions: HashMap<ExprId, CallableKind>,
}

impl CallableCapabilities {
    /// The exact immutable source body, including its source file identity.
    pub fn body(&self, span: Span) -> Option<CallableKind> {
        self.bodies.get(&span).copied()
    }
    pub fn expression(&self, id: ExprId) -> Option<CallableKind> {
        self.expressions.get(&id).copied()
    }
    pub fn parameters(&self, body: Span) -> Option<&[Option<CallableKind>]> {
        self.parameters.get(&body).map(Vec::as_slice)
    }
    pub(super) fn extend(&mut self, other: Self) {
        self.bodies.extend(other.bodies);
        self.parameters.extend(other.parameters);
        self.expressions.extend(other.expressions);
    }
}