rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Declaration-owned generic implementations shared by analysis and execution.

use std::{collections::HashMap, sync::OnceLock};

use crate::{
    Type,
    ast::{AssociatedType, GenericParameter, ImplMethod, Program, Stmt},
};

mod bytecode;
mod qualification;
mod validation;
pub use bytecode::append_bytecode_builtin_impls;

#[derive(Clone, Debug)]
pub struct BuiltinImpl {
    pub id: &'static str,
    pub module: Vec<String>,
    pub target: Type,
    pub trait_type: Type,
    pub generic_parameters: Vec<GenericParameter>,
    pub associated_types: Vec<AssociatedType>,
    pub methods: Vec<ImplMethod>,
}

pub fn builtin_impls() -> &'static [BuiltinImpl] {
    static IMPLEMENTATIONS: OnceLock<Vec<BuiltinImpl>> = OnceLock::new();
    IMPLEMENTATIONS.get_or_init(|| {
        rils_builtins::BUILTIN_IMPLS
            .iter()
            .enumerate()
            .map(|(index, declaration)| {
                let source = crate::SourceId::new(
                    crate::SourceId::GENERATED_BIT
                        | 0x4000_0000
                        | u32::try_from(index + 1).expect("too many built-in implementations"),
                );
                parse_impl(
                    declaration.id,
                    declaration.module,
                    declaration.source,
                    source,
                )
            })
            .collect()
    })
}

fn parse_impl(
    id: &'static str,
    module: &str,
    source: &str,
    source_id: crate::SourceId,
) -> BuiltinImpl {
    let tokens =
        crate::lex_with_source_id(source, source_id).expect("declared implementation must lex");
    let program = rils_syntax::parser::parse_builtin_declarations(tokens)
        .expect("declared implementation must parse");
    let mut implementations = program.statements.into_iter().filter_map(|statement| {
        if let Stmt::Impl {
            target,
            trait_name: Some(name),
            trait_arguments,
            generic_parameters,
            associated_types,
            methods,
            ..
        } = statement
        {
            Some(BuiltinImpl {
                id,
                module: module
                    .split("::")
                    .filter(|part| !part.is_empty())
                    .map(str::to_owned)
                    .collect(),
                target,
                trait_type: Type::Named {
                    name,
                    arguments: trait_arguments,
                },
                generic_parameters,
                associated_types,
                methods,
            })
        } else {
            None
        }
    });
    let mut result = implementations
        .next()
        .expect("declaration must contain a trait implementation");
    assert!(
        implementations.next().is_none(),
        "declaration must contain one implementation"
    );
    qualification::qualify(&mut result);
    validation::validate(&result).unwrap_or_else(|message| {
        panic!("invalid standard-library implementation `{id}`: {message}")
    });
    result
}

pub fn builtin_impl_function_name(id: &str, method: &str) -> String {
    let encoded = id
        .as_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<String>();
    format!("@impl_{encoded}_{method}")
}

fn bindings(implementation: &BuiltinImpl, target: &Type) -> Option<HashMap<String, Type>> {
    let mut bindings = HashMap::new();
    crate::types::infer_generic_arguments(&implementation.target, target, &mut bindings).ok()?;
    bindings.insert("Self".into(), target.clone());
    Some(bindings)
}

pub fn builtin_impl_trait(id: &str, target: &Type) -> Option<Type> {
    let implementation = builtin_impls()
        .iter()
        .find(|implementation| implementation.id == id)?;
    Some(
        implementation
            .trait_type
            .substitute(&bindings(implementation, target)?),
    )
}

/// Match declaration patterns using a caller's trait evidence, preserving reference Self.
/// Callers retain their ordinary inherent-method and ambiguity checks.
pub fn builtin_impl_method_with(
    target: &Type,
    required: Option<&Type>,
    name: &str,
    mut satisfies: impl FnMut(&Type, &Type) -> bool,
) -> Option<(&'static str, rils_builtins::ReceiverMode)> {
    let resolver = crate::semantic::DeclarationTypeResolver::default();
    let required = required.map(|ty| resolver.resolve_canonical(ty));
    let mut selected = None;
    for implementation in builtin_impls() {
        let Some(method) = implementation
            .methods
            .iter()
            .find(|method| method.name == name)
        else {
            continue;
        };
        let Some(bindings) = bindings(implementation, target) else {
            continue;
        };
        let provided = resolver
            .resolve(&implementation.trait_type, &implementation.module)
            .substitute(&bindings);
        if required
            .as_ref()
            .is_some_and(|required| required != &provided)
        {
            continue;
        }
        if !implementation.generic_parameters.iter().all(|parameter| {
            bindings.get(&parameter.name).is_some_and(|actual| {
                parameter.bounds.iter().all(|bound| {
                    satisfies(
                        actual,
                        &resolver
                            .resolve(bound, &implementation.module)
                            .substitute(&bindings),
                    )
                })
            })
        }) {
            continue;
        }
        let candidate = (implementation.id, receiver_mode(method)?);
        if selected.is_some() {
            return None;
        }
        selected = Some(candidate);
    }
    selected
}

pub(crate) fn receiver_mode(method: &ImplMethod) -> Option<rils_builtins::ReceiverMode> {
    let receiver = method
        .parameters
        .first()
        .filter(|parameter| parameter.name == "self")?;
    Some(match receiver.type_annotation.as_ref() {
        Some(Type::Reference { mutable: true, .. }) => rils_builtins::ReceiverMode::Mutable,
        Some(Type::Reference { mutable: false, .. }) => rils_builtins::ReceiverMode::Shared,
        _ => rils_builtins::ReceiverMode::Owned,
    })
}

/// Substitute only declaration parameters; applicability is checked by the caller.
pub fn specialize_builtin_impl(id: &str, target: &Type, name: &str) -> Option<ImplMethod> {
    let implementation = builtin_impls()
        .iter()
        .find(|implementation| implementation.id == id)?;
    let bindings = bindings(implementation, target)?;
    specialize_method(implementation, target, name, &bindings)
}

fn specialize_method(
    implementation: &BuiltinImpl,
    target: &Type,
    name: &str,
    bindings: &HashMap<String, Type>,
) -> Option<ImplMethod> {
    let mut method = implementation
        .methods
        .iter()
        .find(|method| method.name == name)?
        .clone();
    let trait_name = match &implementation.trait_type {
        Type::Named { name, .. } => name.as_str(),
        _ => return None,
    };
    let resolve = |ty| {
        crate::trait_defaults::resolve_associated_type(
            ty,
            target,
            trait_name,
            &implementation.associated_types,
        )
        .substitute(bindings)
    };
    for parameter in &mut method.parameters {
        parameter.type_annotation = parameter.type_annotation.take().map(resolve);
        if parameter.name == "self" && parameter.type_annotation.is_none() {
            parameter.type_annotation = Some(target.clone());
        }
    }
    method.return_type = method.return_type.take().map(resolve);
    for parameter in &mut method.generic_parameters {
        parameter.bounds = std::mem::take(&mut parameter.bounds)
            .into_iter()
            .map(resolve)
            .collect();
        parameter.default = parameter.default.take().map(resolve);
    }
    crate::trait_defaults::resolve_block_types(
        &mut method.body,
        target,
        trait_name,
        &implementation.associated_types,
    );
    crate::trait_defaults::substitution::block(&mut method.body, bindings);
    method.definition_module = Some(implementation.module.clone());
    Some(method)
}