rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Symmetric header unification; call coercions never establish impl overlap.
use crate::Type;
use std::collections::HashMap;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Variable(bool, String);

#[derive(Clone, PartialEq, Eq)]
enum Term {
    Variable(Variable),
    Apply(Type, Vec<Term>),
}

fn term(ty: &Type, side: bool) -> Term {
    let nested = |ty: &Type| term(ty, side);
    let (shape, children) = match ty {
        Type::Variable(name) | Type::BoundVariable { name, .. } => {
            return Term::Variable(Variable(side, name.clone()));
        }
        Type::Tuple(items) => (Type::Tuple(vec![]), items.iter().map(nested).collect()),
        Type::Named { name, arguments } => {
            (Type::named(name), arguments.iter().map(nested).collect())
        }
        Type::Option(item) => (Type::Option(Box::new(Type::Unknown)), vec![nested(item)]),
        Type::Result(ok, error) => (
            Type::Result(Box::new(Type::Unknown), Box::new(Type::Unknown)),
            vec![nested(ok), nested(error)],
        ),
        Type::Slice(item) => (Type::Slice(Box::new(Type::Unknown)), vec![nested(item)]),
        Type::Reference { mutable, inner } => (
            Type::Reference {
                mutable: *mutable,
                inner: Box::new(Type::Unknown),
            },
            vec![nested(inner)],
        ),
        Type::Array { element, length } => (
            Type::Array {
                element: Box::new(Type::Unknown),
                length: 0,
            },
            vec![nested(element), nested(&Type::ConstUsize(*length))],
        ),
        Type::ArrayParameter { element, length } => (
            Type::Array {
                element: Box::new(Type::Unknown),
                length: 0,
            },
            vec![
                nested(element),
                Term::Variable(Variable(side, length.clone())),
            ],
        ),
        Type::Function {
            parameters,
            return_type,
        } => {
            let mut children = parameters.iter().flatten().map(nested).collect::<Vec<_>>();
            children.push(nested(return_type));
            (
                Type::Function {
                    parameters: parameters.as_ref().map(|_| vec![]),
                    return_type: Box::new(Type::Unknown),
                },
                children,
            )
        }
        Type::Associated {
            base,
            trait_name,
            trait_arguments,
            name,
            arguments,
        } => {
            let mut children = vec![nested(base), nested(&Type::Tuple(trait_arguments.clone()))];
            children.extend(arguments.iter().map(nested));
            (
                Type::Associated {
                    base: Box::new(Type::Unknown),
                    trait_name: trait_name.clone(),
                    trait_arguments: vec![],
                    name: name.clone(),
                    arguments: vec![],
                },
                children,
            )
        }
        leaf => (leaf.clone(), vec![]),
    };
    Term::Apply(shape, children)
}

#[derive(Default)]
struct Unifier {
    bindings: HashMap<Variable, Term>,
}
impl Unifier {
    fn resolve(&self, term: &Term) -> Term {
        match term {
            Term::Variable(variable) if self.bindings.contains_key(variable) => {
                self.resolve(&self.bindings[variable])
            }
            _ => term.clone(),
        }
    }
    fn occurs(&self, variable: &Variable, term: &Term) -> bool {
        match self.resolve(term) {
            Term::Variable(other) => variable == &other,
            Term::Apply(_, children) => children.iter().any(|child| self.occurs(variable, child)),
        }
    }
    fn unify(&mut self, left: &Term, right: &Term) -> bool {
        let (left, right) = (self.resolve(left), self.resolve(right));
        if left == right {
            return true;
        }
        match (left, right) {
            (Term::Variable(variable), term) | (term, Term::Variable(variable)) => {
                if self.occurs(&variable, &term) {
                    return false;
                }
                self.bindings.insert(variable, term);
                true
            }
            (Term::Apply(left, a), Term::Apply(right, b)) => {
                left == right
                    && a.len() == b.len()
                    && a.iter()
                        .zip(&b)
                        .all(|(left, right)| self.unify(left, right))
            }
        }
    }
}

pub(super) fn headers(left: (&Type, &[Type]), right: (&Type, &[Type])) -> bool {
    let mut unifier = Unifier::default();
    left.1.len() == right.1.len()
        && std::iter::once(left.0)
            .chain(left.1)
            .zip(std::iter::once(right.0).chain(right.1))
            .all(|(left, right)| unifier.unify(&term(left, false), &term(right, true)))
}