rils_builtins 0.4.0

Shared built-in API metadata for the Rils toolchain
Documentation
use crate::{BuiltinSignature, TypePattern};

pub use rils_stdlib::stdlib::comparison::comparison_contract;
pub use rils_stdlib::stdlib::ops::arithmetic::binary_contract as binary_operator_contract;
pub use rils_stdlib::stdlib::ops::unary::unary_contract as unary_operator_contract;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuiltinKind {
    Module,
    Primitive,
    Struct,
    Enum,
    Trait,
    Function,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuiltinBackend {
    /// Implemented by the Rils runtime.
    Runtime,
    /// Implemented as a compiler or VM intrinsic.
    Intrinsic,
    /// Supplied by an embedding host and protected by the named capability.
    Host(&'static str),
    /// A namespace or semantic declaration with no independently callable body.
    Metadata,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReceiverMode {
    Owned,
    Shared,
    Mutable,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuiltinMemberKind {
    Field,
    Variant,
    Method,
    AssociatedFunction,
    AssociatedType,
    Constant,
}

#[derive(Clone, Copy, Debug)]
pub struct BuiltinMember {
    pub name: &'static str,
    /// Trait identity for a method exported from a concrete trait implementation.
    pub trait_name: Option<&'static str>,
    pub kind: BuiltinMemberKind,
    pub signature: Option<BuiltinSignature>,
    pub value_type: Option<TypePattern>,
    pub receiver: Option<ReceiverMode>,
    /// Generated native implementation path, when this method has a direct bridge.
    pub native_symbol: Option<&'static str>,
    /// The declaration explicitly supplies a type-erased native adapter.
    pub native_bridge: bool,
    /// Whether a trait member must be supplied by user implementations.
    pub required: bool,
    pub type_parameters: &'static [&'static str],
    pub documentation: &'static str,
}

#[derive(Clone, Copy, Debug)]
pub enum BuiltinLayout {
    /// The outer layout requires these inline fields, including inactive variants.
    Inline(&'static [TypePattern]),
    /// The outer size and alignment do not require any type-argument layout.
    /// This promises neither child traversal nor lazy child layout resolution.
    Independent,
}

#[derive(Clone, Copy, Debug)]
pub struct BuiltinDeclaration {
    /// Explicit structural receiver identity; never an exported nominal type.
    pub structural_sequence: Option<rils_stdlib::storage::StructuralSequence>,
    /// Declaration-owned policy for a context entry point.
    pub entry: Option<crate::BuiltinEntry>,
    pub path: &'static str,
    pub kind: BuiltinKind,
    /// Rust-backed struct storage has fields Rils cannot initialize directly.
    pub opaque_native: bool,
    /// The single language type argument transmits locality for orphan checks.
    pub fundamental: bool,
    /// Layout dependencies generated from the same declaration as the backend.
    /// Non-type declarations have no layout contract.
    pub layout: Option<BuiltinLayout>,
    /// Finite supported concrete types, empty for unrestricted declarations.
    pub native_instances: &'static [TypePattern],
    /// Syntax role and declared constructor symbol.
    pub syntax_constructors: &'static [(&'static str, &'static str)],
    /// Generated Rils declaration source, including trait default bodies when present.
    pub source: Option<&'static str>,
    /// Rils trait bounds; empty for other declaration kinds.
    pub supertraits: &'static [&'static str],
    /// Native trait implementations generated from this type's declaration.
    pub trait_impls: &'static [BuiltinTraitImpl],
    pub type_parameters: &'static [&'static str],
    pub members: &'static [BuiltinMember],
    pub signature: Option<BuiltinSignature>,
    /// Native method target for an exported free-function alias.
    pub native_symbol: Option<&'static str>,
    pub backend: BuiltinBackend,
    pub documentation: &'static str,
}

#[derive(Clone, Copy, Debug)]
pub struct BuiltinModule {
    pub path: &'static str,
    pub members: &'static [&'static str],
    /// Explicit re-exports retain their target identity, including enum variants.
    pub imports: &'static [(&'static str, &'static str)],
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuiltinSourceKind {
    ModuleTree,
    Catalog,
    Type,
}

#[derive(Clone, Copy, Debug)]
pub struct BuiltinSource {
    pub path: &'static str,
    pub module: &'static str,
    pub kind: BuiltinSourceKind,
}

/// A native standard-library type checked against its Rust trait binding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BuiltinTraitImpl {
    pub type_name: &'static str,
    pub trait_name: &'static str,
    /// Explicit trait arguments; omitted arguments use the trait's defaults.
    pub trait_arguments: &'static [TypePattern],
    /// Associated type definitions supplied by the native declaration.
    pub associated_types: &'static [(&'static str, TypePattern)],
    /// Generic parameter and trait pairs required for this implementation.
    pub requirements: &'static [(&'static str, &'static str)],
}

/// A standard-library implementation with an ordinary language method body.
/// Its complete source owns generic bounds, associated types and method signatures.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BuiltinImplDeclaration {
    /// Stable declaration identity derived from the module and implementation header.
    pub id: &'static str,
    /// Namespace used when resolving names in the declaration.
    pub module: &'static str,
    pub source: &'static str,
}

pub use crate::native_definitions::IMPL_DECLARATIONS as BUILTIN_IMPLS;

#[inline]
pub fn native_implements(type_name: &str, trait_name: &str) -> bool {
    native_implements_with(type_name, trait_name, |_, _| false)
}

#[inline]
pub fn native_implements_with(
    type_name: &str,
    trait_name: &str,
    mut satisfies: impl FnMut(&str, &str) -> bool,
) -> bool {
    builtin(type_name).is_some_and(|declaration| {
        declaration.trait_impls.iter().any(|implementation| {
            implementation.trait_name == trait_name
                && implementation
                    .requirements
                    .iter()
                    .all(|(parameter, required_trait)| satisfies(parameter, required_trait))
        })
    })
}

impl BuiltinDeclaration {
    /// Module that declares this name, independently of its prelude re-exports.
    pub fn declaring_module(&self) -> Option<&'static str> {
        if self.kind == BuiltinKind::Primitive {
            return None;
        }
        if self.kind == BuiltinKind::Trait {
            return crate::native_definitions::TRAIT_EXPORTS
                .iter()
                .find_map(|&(module, name)| (name == self.path).then_some(module));
        }
        self.path
            .rsplit_once("::")
            .map(|(module, _)| module)
            .or_else(|| {
                self.members
                    .iter()
                    .filter_map(|member| member.native_symbol)
                    .find_map(|symbol| {
                        symbol
                            .rsplit_once("::")?
                            .0
                            .rsplit_once("::")
                            .map(|(module, _)| module)
                    })
            })
    }

    pub fn member(&self, name: &str) -> Option<&BuiltinMember> {
        self.members.iter().find(|member| member.name == name)
    }

    pub fn contains_member(&self, name: &str) -> bool {
        self.member(name).is_some()
    }
}

rils_builtins_macros::builtin_stdlib! {
    "stdlib";
    pub static BUILTINS;
    pub const BUILTIN_MODULES, BUILTIN_SOURCES;
}

pub use crate::native_definitions::float::INTRINSICS as FLOAT_INTRINSICS;
pub use crate::native_definitions::integer::INTRINSICS as INTEGER_INTRINSICS;

pub fn builtin(path: &str) -> Option<&'static BuiltinDeclaration> {
    BUILTINS.iter().find(|item| item.path == path)
}
pub fn builtin_function(path: &str) -> Option<&'static BuiltinDeclaration> {
    builtin(path)
        .or_else(|| {
            let (module, member) = path.rsplit_once("::")?;
            builtin_module_members(module)
                .contains(&member)
                .then(|| builtin(member))
                .flatten()
        })
        .filter(|item| item.kind == BuiltinKind::Function)
}

/// Resolve a native function symbol through its language declaration.
pub fn native_function(symbol: &str) -> Option<&'static BuiltinDeclaration> {
    BUILTINS
        .iter()
        .find(|item| item.kind == BuiltinKind::Function && item.native_symbol == Some(symbol))
}

pub fn standard_host_capabilities() -> Vec<&'static str> {
    let mut capabilities = BUILTINS
        .iter()
        .filter_map(|item| match item.backend {
            BuiltinBackend::Host(capability) if capability.starts_with("std::") => Some(capability),
            _ => None,
        })
        .collect::<Vec<_>>();
    capabilities.sort_unstable();
    capabilities.dedup();
    capabilities
}

pub fn builtin_member(owner: &str, name: &str) -> Option<&'static BuiltinMember> {
    builtin(owner)?.member(name)
}

pub fn builtin_module_members(path: &str) -> &'static [&'static str] {
    static MEMBERS: std::sync::OnceLock<
        std::collections::HashMap<&'static str, Vec<&'static str>>,
    > = std::sync::OnceLock::new();
    MEMBERS
        .get_or_init(|| {
            let mut members = BUILTIN_MODULES
                .iter()
                .map(|module| (module.path, module.members.to_vec()))
                .collect::<std::collections::HashMap<_, _>>();
            for &(module, name) in crate::native_definitions::TRAIT_EXPORTS {
                members.entry(module).or_default().push(name);
            }
            for declaration in BUILTINS {
                if declaration.structural_sequence.is_some() {
                    continue;
                }
                if (declaration.kind == BuiltinKind::Function
                    || matches!(declaration.backend, BuiltinBackend::Host(_)))
                    && let Some((module, name)) = declaration.path.rsplit_once("::")
                {
                    members.entry(module).or_default().push(name);
                } else if matches!(declaration.kind, BuiltinKind::Struct | BuiltinKind::Enum)
                    && let Some(module) = declaration.declaring_module()
                {
                    members.entry(module).or_default().push(
                        declaration
                            .path
                            .rsplit("::")
                            .next()
                            .unwrap_or(declaration.path),
                    );
                }
            }
            // A declared module can be introduced entirely by Rust exports.
            // Retain the source module tree, and connect those generated leaves
            // to their parents without requiring a second module catalogue.
            for mut path in members.keys().copied().collect::<Vec<_>>() {
                while let Some((parent, child)) = path.rsplit_once("::") {
                    members.entry(parent).or_default().push(child);
                    path = parent;
                }
            }
            for names in members.values_mut() {
                names.sort_unstable();
                names.dedup();
            }
            members
        })
        .get(path)
        .map_or(&[], Vec::as_slice)
}

pub fn native_member_owner(
    symbol: &str,
) -> Option<(&'static BuiltinDeclaration, &'static BuiltinMember)> {
    BUILTINS.iter().find_map(|owner| {
        owner
            .members
            .iter()
            .find(|member| member.native_symbol == Some(symbol))
            .map(|member| (owner, member))
    })
}

pub fn native_member(symbol: &str) -> Option<&'static BuiltinMember> {
    native_member_owner(symbol).map(|(_, member)| member)
}

/// Signature and leading receiver count at a native invocation boundary.
pub fn native_signature(symbol: &str) -> Option<(BuiltinSignature, usize)> {
    if let Some(member) = native_member(symbol) {
        Some((member.signature?, usize::from(member.receiver.is_some())))
    } else {
        Some((native_function(symbol)?.signature?, 0))
    }
}

/// Whether an exported signature requires the runtime's callable bridge.
pub fn requires_native_callback(symbol: &str) -> bool {
    native_member(symbol)
        .and_then(|member| member.signature)
        .or_else(|| native_function(symbol).and_then(|function| function.signature))
        .is_some_and(|signature| {
            signature
                .parameters
                .iter()
                .any(|parameter| matches!(parameter, TypePattern::Function { .. }))
        })
}