rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
use super::*;

impl Checker<'_> {
    pub(super) fn check_contracts(
        &mut self,
        call: &Expr,
        callee: &Expr,
        arguments: &[Expr],
        facts: &[Facts],
    ) {
        self.check_signature_contracts(call, callee, arguments, facts);
        self.check_native_contracts(call, callee, facts);
        let definition = self
            .id(call)
            .and_then(|id| self.types.resolved_call(id))
            .and_then(|call| match call {
                ResolvedCall::Definition(id) => Some(*id),
                _ => None,
            })
            .or_else(|| self.definition(callee));
        let Some(function) = definition
            .and_then(|id| self.registry.names.get(&id))
            .and_then(|body| self.registry.functions.get(body))
            .cloned()
        else {
            return;
        };
        if !function.generics.iter().any(|p| {
            p.bounds.iter().any(|bound| {
                let required = self.declarations.resolve(bound, &function.module);
                self.bound_kind(&required).is_some()
            })
        }) {
            return;
        }
        let mut inputs = arguments
            .iter()
            .map(|argument| self.ty(argument))
            .collect::<Vec<_>>();
        let mut values = facts.to_vec();
        if let Expr::Member { object, .. } = callee {
            inputs.insert(0, self.ty(object));
            values.insert(0, Facts::default());
        }
        let mut bindings = HashMap::new();
        if let Expr::GenericPath { arguments, .. } = callee {
            for (parameter, actual) in function.generics.iter().rev().zip(arguments.iter().rev()) {
                bindings.insert(
                    parameter.name.clone(),
                    self.declarations.resolve(actual, &self.module),
                );
            }
        }
        for (parameter, actual) in function.parameters.iter().zip(&inputs) {
            if let Some(expected) = &parameter.type_annotation {
                let _ = crate::types::infer_generic_arguments(
                    &self.declarations.resolve(expected, &function.module),
                    actual,
                    &mut bindings,
                );
            }
        }
        if let Some(expected) = function.return_type {
            let _ = crate::types::infer_generic_arguments(
                &self.declarations.resolve(expected, &function.module),
                &self.ty(call),
                &mut bindings,
            );
        }
        let _ = crate::semantic::infer_callable_generics(
            &function.generics,
            &mut bindings,
            |bound, known| {
                self.declarations
                    .resolve(&bound.substitute(known), &function.module)
            },
        );
        for generic in &function.generics {
            for bound in &generic.bounds {
                let required = self
                    .declarations
                    .resolve(bound, &function.module)
                    .substitute(&bindings);
                let Some(kind) = self.bound_kind(&required) else {
                    continue;
                };
                let input = function.parameters.iter().enumerate().find(|(_, parameter)| matches!(&parameter.type_annotation,
                    Some(Type::Variable(name) | Type::BoundVariable { name, .. }) if name == &generic.name));
                let Some((index, _)) = input else {
                    continue;
                };
                let Some(actual) = inputs.get(index) else {
                    continue;
                };
                let actual_signature = self.callable_signature(actual);
                let expected_signature = callable_signature(&required);
                let capability = values
                    .get(index)
                    .and_then(|value| value.kind)
                    .unwrap_or(CallableKind::Once);
                if actual_signature.is_none()
                    || actual_signature != expected_signature
                    || !capability.satisfies(kind)
                {
                    self.diagnostic(format!("type `{actual}` does not implement required trait `{required}`: incompatible callable signature or capture capability"), call.span());
                }
            }
        }
    }

    fn check_native_contracts(&mut self, call: &Expr, callee: &Expr, facts: &[Facts]) {
        let contract = match self.id(call).and_then(|id| self.types.resolved_call(id)) {
            Some(ResolvedCall::Native { symbol, .. }) => rils_builtins::native_signature(symbol)
                .map(|(signature, receiver)| (*symbol, signature, receiver)),
            Some(ResolvedCall::Import { name, .. }) => rils_builtins::builtin_function(name)
                .and_then(|declaration| {
                    declaration
                        .signature
                        .map(|signature| (declaration.path, signature, 0))
                }),
            _ => None,
        };
        let Some((symbol, signature, receiver)) = contract else {
            return;
        };
        // Member calls keep the receiver outside the explicit arguments; UFCS
        // calls pass it as the first argument.
        let offset = if matches!(callee, Expr::Member { .. }) {
            0
        } else {
            receiver
        };
        for &(index, required) in signature.parameter_capabilities {
            let Some(actual) = facts.get(index + offset) else {
                continue;
            };
            if !actual
                .kind
                .unwrap_or(CallableKind::Once)
                .satisfies(required)
            {
                self.diagnostic(format!("native callback argument {} of `{symbol}` has incompatible capture capability: requires {}", index + 1, required.trait_name()), call.span());
            }
        }
    }

    // Native declarations and source-default methods carry their generic
    // contracts in the resolved signature, without a source function DefId.
    fn check_signature_contracts(
        &mut self,
        call: &Expr,
        callee: &Expr,
        arguments: &[Expr],
        facts: &[Facts],
    ) {
        let Type::Function {
            parameters: Some(parameters),
            ..
        } = self.ty(callee)
        else {
            return;
        };
        if parameters.len() != arguments.len() {
            return;
        }
        let mut bindings = HashMap::new();
        for (expected, actual) in parameters.iter().zip(arguments) {
            let _ =
                crate::types::infer_generic_arguments(expected, &self.ty(actual), &mut bindings);
            if let Type::BoundVariable { bounds, .. } = expected {
                for bound in bounds {
                    if let Some(signature) = crate::semantic::callable_contract_signature(
                        &self.declarations.resolve(bound, &self.module),
                    ) {
                        let _ = crate::types::infer_generic_arguments(
                            &signature,
                            &self.ty(actual),
                            &mut bindings,
                        );
                    }
                }
            }
        }
        for ((expected, actual), facts) in parameters.iter().zip(arguments).zip(facts) {
            let Type::BoundVariable { bounds, .. } = expected else {
                continue;
            };
            for bound in bounds {
                let required = self.declarations.resolve_canonical(
                    &self
                        .declarations
                        .resolve(bound, &self.module)
                        .substitute(&bindings),
                );
                let Some(kind) = self.bound_kind(&required) else {
                    continue;
                };
                let actual = self.ty(actual);
                let signature = self.callable_signature(&actual);
                if signature.is_none()
                    || signature != callable_signature(&required)
                    || !facts.kind.unwrap_or(CallableKind::Once).satisfies(kind)
                {
                    self.diagnostic(format!("type `{actual}` does not implement required trait `{required}`: incompatible callable signature or capture capability"), call.span());
                }
            }
        }
    }
    fn callable_signature(&self, ty: &Type) -> Option<Type> {
        match ty {
            Type::Function {
                parameters: Some(_),
                ..
            } => Some(ty.clone()),
            Type::BoundVariable { bounds, .. } => bounds.iter().find_map(|bound| {
                self.bound_kind(bound)
                    .and_then(|_| callable_signature(bound))
            }),
            Type::Variable(name) => self
                .current
                .and_then(|body| self.registry.functions.get(&body))
                .and_then(|function| {
                    function
                        .generics
                        .iter()
                        .find(|parameter| parameter.name == *name)
                })
                .and_then(|parameter| {
                    parameter.bounds.iter().find_map(|bound| {
                        self.bound_kind(bound)
                            .and_then(|_| callable_signature(bound))
                    })
                }),
            _ => None,
        }
    }
}

fn callable_signature(bound: &Type) -> Option<Type> {
    let Type::Named { arguments, .. } = bound else {
        return None;
    };
    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()))
}