use std::{any::Any, collections::HashMap, error::Error, fmt, sync::Arc};
use crate::{
runtime::{NativeAbi, NativePassMode, NativeTypeKind, NativeTypeLayout},
semantic::{AccessPath, ModuleGraph, metadata::PrimitiveType},
};
#[derive(Default, Clone)]
pub struct RustLib {
pub scripts: HashMap<String, Script>,
}
#[derive(Default, Clone)]
pub struct Script {
pub content: String,
pub functions: HashMap<String, Function>,
pub traits: HashMap<String, Trait>,
pub types: HashMap<String, Type>,
pub native_types: HashMap<String, NativeTypeRegistration>,
}
#[derive(Clone)]
pub struct Function {
pub pub_visible: bool,
pub exported: bool,
pub self_argument: Option<SelfArgument>,
pub arguments: Vec<FunctionArgument>,
pub return_value_type: Option<RustTypeRef>,
pub body: FunctionBody,
}
#[derive(Debug, Clone)]
pub struct SelfArgument {
pub kind: SelfArgumentKind,
pub value_type: RustTypeRef,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SelfArgumentKind {
Owned {
mutable: bool,
},
Reference {
lifetime: Option<String>,
mutable: bool,
},
}
#[derive(Debug, Clone)]
pub struct FunctionArgument {
pub ident: String,
pub value_type: RustTypeRef,
}
#[derive(Clone)]
pub enum FunctionBody {
Script(String),
Ir(String),
External(ExternalFunction),
Native(NativeFunction),
}
pub struct NativeFunctionRegistrationBuilder<'a> {
functions: &'a mut HashMap<String, Function>,
name: String,
function: Function,
}
impl<'a> NativeFunctionRegistrationBuilder<'a> {
fn new(
functions: &'a mut HashMap<String, Function>,
name: impl Into<String>,
native: NativeFunction,
) -> Self {
Self {
functions,
name: name.into(),
function: Function {
pub_visible: false,
exported: false,
self_argument: None,
arguments: Vec::new(),
return_value_type: None,
body: FunctionBody::Native(native),
},
}
}
pub fn public(mut self) -> Self {
self.function.pub_visible = true;
self
}
pub fn exported(mut self) -> Self {
self.function.exported = true;
self
}
pub fn argument(mut self, ident: impl Into<String>, value_type: RustTypeRef) -> Self {
self.function.arguments.push(FunctionArgument {
ident: ident.into(),
value_type,
});
self
}
pub fn returns(mut self, value_type: RustTypeRef) -> Self {
self.function.return_value_type = Some(value_type);
self
}
pub fn owned_receiver(mut self, value_type: RustTypeRef, mutable: bool) -> Self {
self.function.self_argument = Some(SelfArgument {
kind: SelfArgumentKind::Owned { mutable },
value_type,
});
self
}
pub fn shared_receiver(mut self, value_type: RustTypeRef) -> Self {
self.function.self_argument = Some(SelfArgument {
kind: SelfArgumentKind::Reference {
lifetime: None,
mutable: false,
},
value_type,
});
self
}
pub fn mutable_receiver(mut self, value_type: RustTypeRef) -> Self {
self.function.self_argument = Some(SelfArgument {
kind: SelfArgumentKind::Reference {
lifetime: None,
mutable: true,
},
value_type,
});
self
}
pub fn finish(self) -> &'a mut Function {
self.functions.insert(self.name.clone(), self.function);
self.functions
.get_mut(&self.name)
.expect("native function was inserted above")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeEntrypointAbi {
Rust,
LehitIndirect,
}
#[derive(Debug, Clone)]
pub struct NativeFunction {
symbol: String,
address: usize,
abi: NativeEntrypointAbi,
signature: Option<NativeFunctionSignature>,
}
#[derive(Debug, Clone, Default)]
pub struct NativeFunctionSignature {
arguments: Vec<NativeFunctionArgumentLayout>,
argument_pass_modes: Vec<NativePassMode>,
return_type: Option<&'static NativeTypeLayout>,
return_pass_mode: Option<NativePassMode>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeFunctionArgumentLayout {
Owned(&'static NativeTypeLayout),
SharedBorrow(&'static NativeTypeLayout),
MutableBorrow(&'static NativeTypeLayout),
}
impl NativeFunctionArgumentLayout {
pub fn layout(self) -> &'static NativeTypeLayout {
match self {
Self::Owned(layout) | Self::SharedBorrow(layout) | Self::MutableBorrow(layout) => {
layout
}
}
}
}
impl NativeFunctionSignature {
pub fn new() -> Self {
Self::default()
}
pub fn argument<T: NativeAbi>(mut self) -> Self {
self.arguments
.push(NativeFunctionArgumentLayout::Owned(T::native_layout()));
self.argument_pass_modes.push(T::native_pass_mode());
self
}
pub fn shared_argument<T: NativeAbi>(mut self) -> Self {
self.arguments
.push(NativeFunctionArgumentLayout::SharedBorrow(
T::native_layout(),
));
self.argument_pass_modes.push(T::native_pass_mode());
self
}
pub fn mutable_argument<T: NativeAbi>(mut self) -> Self {
self.arguments
.push(NativeFunctionArgumentLayout::MutableBorrow(
T::native_layout(),
));
self.argument_pass_modes.push(T::native_pass_mode());
self
}
pub fn returns<T: NativeAbi>(mut self) -> Self {
self.return_type = Some(T::native_layout());
self.return_pass_mode = Some(T::native_pass_mode());
self
}
pub fn arguments(&self) -> &[NativeFunctionArgumentLayout] {
&self.arguments
}
pub fn argument_pass_modes(&self) -> &[NativePassMode] {
&self.argument_pass_modes
}
pub fn return_type(&self) -> Option<&'static NativeTypeLayout> {
self.return_type
}
pub fn return_pass_mode(&self) -> Option<&NativePassMode> {
self.return_pass_mode.as_ref()
}
}
impl NativeFunction {
pub unsafe fn new(symbol: impl Into<String>, address: *const ()) -> Self {
Self {
symbol: symbol.into(),
address: address as usize,
abi: NativeEntrypointAbi::Rust,
signature: None,
}
}
pub unsafe fn new_typed(
symbol: impl Into<String>,
address: *const (),
signature: NativeFunctionSignature,
) -> Self {
Self {
symbol: symbol.into(),
address: address as usize,
abi: NativeEntrypointAbi::Rust,
signature: Some(signature),
}
}
pub unsafe fn new_lehit_indirect(symbol: impl Into<String>, address: *const ()) -> Self {
Self {
symbol: symbol.into(),
address: address as usize,
abi: NativeEntrypointAbi::LehitIndirect,
signature: None,
}
}
pub unsafe fn from_rust_fn0<R: NativeAbi>(
symbol: impl Into<String>,
function: fn() -> R,
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new().returns::<R>(),
)
}
}
pub unsafe fn from_rust_fn0_void(symbol: impl Into<String>, function: fn()) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new(),
)
}
}
pub unsafe fn from_rust_fn1_ref<T: NativeAbi, R: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a T) -> R,
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new()
.shared_argument::<T>()
.returns::<R>(),
)
}
}
pub unsafe fn from_rust_fn1_mut<T: NativeAbi, R: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a mut T) -> R,
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new()
.mutable_argument::<T>()
.returns::<R>(),
)
}
}
pub unsafe fn from_rust_fn1_ref_void<T: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a T),
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new().shared_argument::<T>(),
)
}
}
pub unsafe fn from_rust_fn1_mut_void<T: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a mut T),
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new().mutable_argument::<T>(),
)
}
}
pub unsafe fn from_rust_fn2_ref_owned<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a T, U) -> R,
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new()
.shared_argument::<T>()
.argument::<U>()
.returns::<R>(),
)
}
}
pub unsafe fn from_rust_fn2_mut_owned<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a mut T, U) -> R,
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new()
.mutable_argument::<T>()
.argument::<U>()
.returns::<R>(),
)
}
}
pub unsafe fn from_rust_fn2_ref_owned_void<T: NativeAbi, U: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a T, U),
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new()
.shared_argument::<T>()
.argument::<U>(),
)
}
}
pub unsafe fn from_rust_fn2_mut_owned_void<T: NativeAbi, U: NativeAbi>(
symbol: impl Into<String>,
function: for<'a> fn(&'a mut T, U),
) -> Self {
unsafe {
Self::new_typed(
symbol,
function as *const (),
NativeFunctionSignature::new()
.mutable_argument::<T>()
.argument::<U>(),
)
}
}
pub unsafe fn from_rust_method_ref<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
symbol: impl Into<String>,
method: for<'a> fn(&'a T, U) -> R,
) -> Self {
unsafe { Self::from_rust_fn2_ref_owned(symbol, method) }
}
pub unsafe fn from_rust_method_mut<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
symbol: impl Into<String>,
method: for<'a> fn(&'a mut T, U) -> R,
) -> Self {
unsafe { Self::from_rust_fn2_mut_owned(symbol, method) }
}
pub unsafe fn from_rust_method_ref_void<T: NativeAbi, U: NativeAbi>(
symbol: impl Into<String>,
method: for<'a> fn(&'a T, U),
) -> Self {
unsafe { Self::from_rust_fn2_ref_owned_void(symbol, method) }
}
pub unsafe fn from_rust_method_mut_void<T: NativeAbi, U: NativeAbi>(
symbol: impl Into<String>,
method: for<'a> fn(&'a mut T, U),
) -> Self {
unsafe { Self::from_rust_fn2_mut_owned_void(symbol, method) }
}
pub fn abi(&self) -> NativeEntrypointAbi {
self.abi
}
pub fn symbol(&self) -> &str {
&self.symbol
}
pub fn signature(&self) -> Option<&NativeFunctionSignature> {
self.signature.as_ref()
}
pub fn address(&self) -> *const u8 {
self.address as *const u8
}
}
macro_rules! typed_native_function_helpers {
($returning:ident, $void:ident, $(($type:ident, $value:ident)),+ $(,)?) => {
impl NativeFunction {
pub unsafe fn $returning<$($type: NativeAbi,)+ R: NativeAbi>(
symbol: impl Into<String>,
function: fn($($type),+) -> R,
) -> Self {
let signature = NativeFunctionSignature::new()
$(.argument::<$type>())+
.returns::<R>();
unsafe { Self::new_typed(symbol, function as *const (), signature) }
}
pub unsafe fn $void<$($type: NativeAbi),+>(
symbol: impl Into<String>,
function: fn($($type),+),
) -> Self {
let signature = NativeFunctionSignature::new()
$(.argument::<$type>())+;
unsafe { Self::new_typed(symbol, function as *const (), signature) }
}
}
};
}
typed_native_function_helpers!(from_rust_fn1, from_rust_fn1_void, (A, a));
typed_native_function_helpers!(from_rust_fn2, from_rust_fn2_void, (A, a), (B, b));
typed_native_function_helpers!(from_rust_fn3, from_rust_fn3_void, (A, a), (B, b), (C, c));
typed_native_function_helpers!(
from_rust_fn4,
from_rust_fn4_void,
(A, a),
(B, b),
(C, c),
(D, d)
);
pub type ExternalFunction =
Arc<dyn Fn(&mut ExternalCallContext) -> ExternalFunctionResult + Send + Sync + 'static>;
pub fn external_function<F>(function: F) -> ExternalFunction
where
F: Fn(&mut ExternalCallContext) -> ExternalFunctionResult + Send + Sync + 'static,
{
Arc::new(move |context| {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| function(context))).unwrap_or_else(
|payload| {
let message = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str))
.unwrap_or("Rust callback panicked");
Err(ExternalFunctionError::new(message))
},
)
})
}
#[derive(Default)]
pub struct ExternalCallContext {
pub arguments: Vec<ExternalValue>,
pub return_value: Option<ExternalValue>,
}
impl ExternalCallContext {
pub fn new(arguments: Vec<ExternalValue>) -> Self {
Self {
arguments,
return_value: None,
}
}
pub fn argument<T: Any + Send + Sync>(&self, index: usize) -> Option<&T> {
self.arguments.get(index)?.downcast_ref()
}
pub fn argument_mut<T: Any + Send + Sync>(&mut self, index: usize) -> Option<&mut T> {
self.arguments.get_mut(index)?.downcast_mut()
}
pub fn set_return_value<T: Any + Send + Sync>(&mut self, value: T) {
self.return_value = Some(Box::new(value));
}
}
pub type ExternalValue = Box<dyn Any + Send + Sync>;
pub type ExternalFunctionResult = Result<(), ExternalFunctionError>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalFunctionError {
pub message: String,
}
impl ExternalFunctionError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ExternalFunctionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl Error for ExternalFunctionError {}
#[derive(Default, Clone)]
pub struct Trait {
pub pub_visible: bool,
pub supers: Vec<AccessPath>,
pub functions: HashMap<String, Function>,
}
#[derive(Debug, Clone)]
pub struct RustFieldRegistration {
pub index: u32,
pub ident: String,
pub value_type: RustTypeRef,
pub pub_visible: bool,
}
#[derive(Debug, Clone, Default)]
pub struct RustStructureFields {
fields: Vec<RustFieldRegistration>,
}
impl RustStructureFields {
pub fn new() -> Self {
Self::default()
}
pub fn field(
mut self,
index: u32,
ident: impl Into<String>,
value_type: RustTypeRef,
pub_visible: bool,
) -> Self {
self.fields.push(RustFieldRegistration {
index,
ident: ident.into(),
value_type,
pub_visible,
});
self
}
pub fn public_field(
self,
index: u32,
ident: impl Into<String>,
value_type: RustTypeRef,
) -> Self {
self.field(index, ident, value_type, true)
}
pub fn private_field(
self,
index: u32,
ident: impl Into<String>,
value_type: RustTypeRef,
) -> Self {
self.field(index, ident, value_type, false)
}
pub fn len(&self) -> usize {
self.fields.len()
}
pub fn is_empty(&self) -> bool {
self.fields.is_empty()
}
}
impl From<Vec<RustFieldRegistration>> for RustStructureFields {
fn from(fields: Vec<RustFieldRegistration>) -> Self {
Self { fields }
}
}
impl From<RustStructureFields> for Vec<RustFieldRegistration> {
fn from(fields: RustStructureFields) -> Self {
fields.fields
}
}
impl IntoIterator for RustStructureFields {
type Item = RustFieldRegistration;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.fields.into_iter()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustTypeRef {
Named(AccessPath),
Reference {
lifetime: Option<String>,
mutable: bool,
target: Box<RustTypeRef>,
},
Pointer {
mutable: bool,
target: Box<RustTypeRef>,
},
}
#[derive(Debug, Clone)]
pub struct NativeTypeRegistration {
pub layout: &'static NativeTypeLayout,
pub pass_mode: NativePassMode,
pub exported_fields: Vec<RustFieldRegistration>,
pub exported_variants: Vec<RustEnumVariantRegistration>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RustEnumVariantRegistration {
pub index: u32,
pub ident: String,
pub value_type: Option<RustTypeRef>,
}
impl RustEnumVariantRegistration {
pub fn unit(index: u32, ident: impl Into<String>) -> Self {
Self {
index,
ident: ident.into(),
value_type: None,
}
}
pub fn payload(index: u32, ident: impl Into<String>, value_type: RustTypeRef) -> Self {
Self {
index,
ident: ident.into(),
value_type: Some(value_type),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RustEnumVariants {
variants: Vec<RustEnumVariantRegistration>,
}
impl RustEnumVariants {
pub fn new() -> Self {
Self::default()
}
pub fn unit(mut self, index: u32, ident: impl Into<String>) -> Self {
self.variants
.push(RustEnumVariantRegistration::unit(index, ident));
self
}
pub fn payload(
mut self,
index: u32,
ident: impl Into<String>,
value_type: RustTypeRef,
) -> Self {
self.variants.push(RustEnumVariantRegistration::payload(
index, ident, value_type,
));
self
}
}
impl IntoIterator for RustEnumVariants {
type Item = RustEnumVariantRegistration;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.variants.into_iter()
}
}
#[derive(Debug, Clone)]
pub enum NativeLehitRegistration {
Structure {
name: String,
pub_visible: bool,
fields: RustStructureFields,
},
Enum {
name: String,
pub_visible: bool,
variants: RustEnumVariants,
},
}
pub trait NativeRegistration: NativeAbi {
fn lehit_registration() -> NativeLehitRegistration;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustTypeRegistrationError {
UnsupportedNativeKind,
DuplicateFieldIndex(u32),
UnknownNativeFieldIndex(u32),
UnknownLehitFieldType {
field: String,
module: String,
path: String,
},
MissingTypeContract {
type_: String,
},
MissingExportedField {
type_: String,
field: String,
},
UnregisteredContractField {
type_: String,
field: String,
},
FieldVisibilityMismatch {
type_: String,
field: String,
},
FieldTypeMismatch {
type_: String,
field: String,
},
MissingExportedVariant {
module: String,
type_: String,
variant: String,
type_span: crate::parsing::Span,
},
UnregisteredContractVariant {
module: String,
type_: String,
variant: String,
type_span: crate::parsing::Span,
variant_span: crate::parsing::Span,
},
VariantPayloadTypeMismatch {
module: String,
type_: String,
variant: String,
type_span: crate::parsing::Span,
variant_span: crate::parsing::Span,
},
}
impl fmt::Display for RustTypeRegistrationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnsupportedNativeKind => formatter.write_str(
"native layout kind does not match the requested Lehit registration kind",
),
Self::DuplicateFieldIndex(index) => write!(
formatter,
"native field index {index} is exported more than once"
),
Self::UnknownNativeFieldIndex(index) => {
write!(formatter, "native layout has no field index {index}")
}
Self::UnknownLehitFieldType {
field,
module,
path,
} => write!(
formatter,
"exported Rust field `{field}` references missing Lehit type `{module}::{path}`"
),
Self::MissingTypeContract { type_ } => {
write!(
formatter,
"native Rust type `{type_}` has no Lehit source contract"
)
}
Self::MissingExportedField { type_, field } => write!(
formatter,
"native type `{type_}` exports `{field}`, but its Lehit contract does not"
),
Self::UnregisteredContractField { type_, field } => write!(
formatter,
"Lehit contract for native type `{type_}` exposes unregistered field `{field}`"
),
Self::FieldVisibilityMismatch { type_, field } => write!(
formatter,
"visibility of `{type_}.{field}` differs between Rust metadata and Lehit contract"
),
Self::FieldTypeMismatch { type_, field } => write!(
formatter,
"type of `{type_}.{field}` differs between Rust metadata and Lehit contract"
),
Self::MissingExportedVariant { type_, variant, .. } => write!(
formatter,
"native enum `{type_}` exports variant `{variant}`, but its Lehit contract does not"
),
Self::UnregisteredContractVariant { type_, variant, .. } => write!(
formatter,
"Lehit contract for native enum `{type_}` exposes unregistered variant `{variant}`"
),
Self::VariantPayloadTypeMismatch { type_, variant, .. } => write!(
formatter,
"payload type of `{type_}::{variant}` differs between Rust metadata and Lehit contract"
),
}
}
}
impl Error for RustTypeRegistrationError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustFunctionRegistrationError {
MissingContract {
function: String,
},
VisibilityMismatch {
function: String,
},
ReceiverMismatch {
function: String,
},
ArgumentCountMismatch {
function: String,
rust: usize,
lehit: usize,
},
ArgumentNameMismatch {
function: String,
index: usize,
rust: String,
lehit: String,
},
ArgumentTypeMismatch {
function: String,
index: usize,
},
ReturnTypeMismatch {
function: String,
},
InvalidTypeMetadata {
function: String,
},
NativeSignatureCountMismatch {
function: String,
rust: usize,
lehit: usize,
},
NativeArgumentLayoutMismatch {
function: String,
index: usize,
},
NativeReturnLayoutMismatch {
function: String,
},
}
impl fmt::Display for RustFunctionRegistrationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingContract { function } => write!(
formatter,
"Rust function `{function}` has no Lehit contract"
),
Self::VisibilityMismatch { function } => write!(
formatter,
"visibility of Rust function `{function}` differs from its Lehit contract"
),
Self::ReceiverMismatch { function } => write!(
formatter,
"receiver of Rust function `{function}` differs from its Lehit contract"
),
Self::ArgumentCountMismatch {
function,
rust,
lehit,
} => write!(
formatter,
"Rust function `{function}` has {rust} arguments, Lehit contract has {lehit}"
),
Self::ArgumentNameMismatch {
function,
index,
rust,
lehit,
} => write!(
formatter,
"argument {index} of `{function}` is `{rust}` in Rust metadata and `{lehit}` in Lehit"
),
Self::ArgumentTypeMismatch { function, index } => write!(
formatter,
"argument {index} type of Rust function `{function}` differs from its Lehit contract"
),
Self::ReturnTypeMismatch { function } => write!(
formatter,
"return type of Rust function `{function}` differs from its Lehit contract"
),
Self::InvalidTypeMetadata { function } => write!(
formatter,
"Rust function `{function}` contains unresolved type metadata"
),
Self::NativeSignatureCountMismatch {
function,
rust,
lehit,
} => write!(
formatter,
"typed native function `{function}` describes {rust} arguments, Lehit contract has {lehit}"
),
Self::NativeArgumentLayoutMismatch { function, index } => write!(
formatter,
"physical layout of argument {index} of native function `{function}` differs from its Lehit contract"
),
Self::NativeReturnLayoutMismatch { function } => write!(
formatter,
"physical return layout of native function `{function}` differs from its Lehit contract"
),
}
}
}
impl Error for RustFunctionRegistrationError {}
impl Script {
pub fn native_function(
&mut self,
name: impl Into<String>,
native: NativeFunction,
) -> NativeFunctionRegistrationBuilder<'_> {
NativeFunctionRegistrationBuilder::new(&mut self.functions, name, native)
}
pub fn register_native<T: NativeRegistration>(
&mut self,
) -> Result<&mut Type, RustTypeRegistrationError> {
match T::lehit_registration() {
NativeLehitRegistration::Structure {
name,
pub_visible,
fields,
} => self.register_type::<T>(name, pub_visible, fields),
NativeLehitRegistration::Enum {
name,
pub_visible,
variants,
} => self.register_enum_type::<T>(name, pub_visible, variants),
}
}
pub fn register_type<T: NativeAbi>(
&mut self,
name: impl Into<String>,
pub_visible: bool,
exported_fields: impl IntoIterator<Item = RustFieldRegistration>,
) -> Result<&mut Type, RustTypeRegistrationError> {
let name = name.into();
let exported_fields = exported_fields.into_iter().collect::<Vec<_>>();
let layout = T::native_layout();
let NativeTypeKind::Structure {
fields: native_fields,
} = &layout.kind
else {
return Err(RustTypeRegistrationError::UnsupportedNativeKind);
};
let mut seen = std::collections::HashSet::new();
let mut fields = Vec::with_capacity(exported_fields.len());
for field in &exported_fields {
if !seen.insert(field.index) {
return Err(RustTypeRegistrationError::DuplicateFieldIndex(field.index));
}
let native = native_fields
.iter()
.find(|native| native.index == field.index)
.ok_or(RustTypeRegistrationError::UnknownNativeFieldIndex(
field.index,
))?;
fields.push(StructureField {
offset: native.offset,
ident: field.ident.clone(),
value_type: field.value_type.clone(),
pub_visible: field.pub_visible,
});
}
self.native_types.insert(
name.clone(),
NativeTypeRegistration {
layout,
pass_mode: T::native_pass_mode(),
exported_fields,
exported_variants: Vec::new(),
},
);
self.types.insert(
name.clone(),
Type {
pub_visible,
layout: TypeLayout::Structure(StructureType {
size: layout.size,
align: layout.align,
fields,
}),
functions: HashMap::new(),
trait_implementations: HashMap::new(),
},
);
Ok(self.types.get_mut(&name).expect("type was inserted above"))
}
pub fn register_enum_type<T: NativeAbi>(
&mut self,
name: impl Into<String>,
pub_visible: bool,
exported_variants: impl IntoIterator<Item = RustEnumVariantRegistration>,
) -> Result<&mut Type, RustTypeRegistrationError> {
let name = name.into();
let exported_variants = exported_variants.into_iter().collect::<Vec<_>>();
let layout = T::native_layout();
let NativeTypeKind::Enum(native_enum) = &layout.kind else {
return Err(RustTypeRegistrationError::UnsupportedNativeKind);
};
let mut seen = std::collections::HashSet::new();
let mut variants = Vec::with_capacity(exported_variants.len());
for variant in &exported_variants {
if !seen.insert(variant.index) {
return Err(RustTypeRegistrationError::DuplicateFieldIndex(
variant.index,
));
}
if !native_enum
.variants
.iter()
.any(|native| native.index == variant.index)
{
return Err(RustTypeRegistrationError::UnknownNativeFieldIndex(
variant.index,
));
}
variants.push(EnumVariant {
index: variant.index as usize,
ident: variant.ident.clone(),
value_type: variant.value_type.clone(),
});
}
self.native_types.insert(
name.clone(),
NativeTypeRegistration {
layout,
pass_mode: T::native_pass_mode(),
exported_fields: Vec::new(),
exported_variants,
},
);
self.types.insert(
name.clone(),
Type {
pub_visible,
layout: TypeLayout::Enum(EnumType {
size: layout.size,
align: layout.align,
variants,
}),
functions: HashMap::new(),
trait_implementations: HashMap::new(),
},
);
Ok(self.types.get_mut(&name).expect("type was inserted above"))
}
pub fn validate_registered_field_types(
&self,
graph: &ModuleGraph,
) -> Result<(), Vec<RustTypeRegistrationError>> {
let mut errors = Vec::new();
for registration in self.native_types.values() {
for (name, type_) in registration
.exported_fields
.iter()
.map(|field| (field.ident.as_str(), Some(&field.value_type)))
.chain(
registration
.exported_variants
.iter()
.map(|variant| (variant.ident.as_str(), variant.value_type.as_ref())),
)
{
let Some(type_) = type_ else {
continue;
};
let mut paths = Vec::new();
collect_registered_type_paths(type_, &mut paths);
for path in paths {
if graph.resolve(&path.file_path, &path.local_access).is_err() {
errors.push(RustTypeRegistrationError::UnknownLehitFieldType {
field: name.to_owned(),
module: path.file_path.clone(),
path: path.local_access.clone(),
});
}
}
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
fn collect_registered_type_paths<'a>(type_: &'a RustTypeRef, paths: &mut Vec<&'a AccessPath>) {
match type_ {
RustTypeRef::Named(path) => {
paths.push(path);
for generic in &path.generics {
collect_access_path_paths(generic, paths);
}
}
RustTypeRef::Reference { target, .. } | RustTypeRef::Pointer { target, .. } => {
collect_registered_type_paths(target, paths)
}
}
}
fn collect_access_path_paths<'a>(path: &'a AccessPath, paths: &mut Vec<&'a AccessPath>) {
paths.push(path);
for generic in &path.generics {
collect_access_path_paths(generic, paths);
}
}
#[derive(Clone)]
pub struct Type {
pub pub_visible: bool,
pub layout: TypeLayout,
pub functions: HashMap<String, Function>,
pub trait_implementations: HashMap<AccessPath, TraitImplementation>,
}
impl Type {
pub fn native_method(
&mut self,
name: impl Into<String>,
native: NativeFunction,
) -> NativeFunctionRegistrationBuilder<'_> {
NativeFunctionRegistrationBuilder::new(&mut self.functions, name, native)
}
}
#[derive(Default, Clone)]
pub struct TraitImplementation {
pub functions: HashMap<String, Function>,
}
#[derive(Debug, Clone)]
pub enum TypeLayout {
Primitive(PrimitiveType),
Structure(StructureType),
Enum(EnumType),
Tuple(TupleType),
Function(FunctionType),
}
#[derive(Debug, Clone)]
pub struct StructureType {
pub size: usize,
pub align: usize,
pub fields: Vec<StructureField>,
}
#[derive(Debug, Clone)]
pub struct StructureField {
pub offset: usize,
pub ident: String,
pub value_type: RustTypeRef,
pub pub_visible: bool,
}
#[derive(Debug, Clone)]
pub struct EnumType {
pub size: usize,
pub align: usize,
pub variants: Vec<EnumVariant>,
}
#[derive(Debug, Clone)]
pub struct EnumVariant {
pub index: usize,
pub ident: String,
pub value_type: Option<RustTypeRef>,
}
#[derive(Debug, Clone)]
pub struct TupleType {
pub items: Vec<RustTypeRef>,
}
#[derive(Debug, Clone)]
pub struct FunctionType {
pub arguments: Vec<RustTypeRef>,
pub return_value_type: Option<RustTypeRef>,
}
#[cfg(test)]
mod tests {
use std::sync::OnceLock;
use super::*;
use crate::{
core_lib,
parsing::{SourceFile, parse_file},
runtime::{NativeEnumLayout, NativeEnumVariant, NativeTypeLayout},
semantic::DeclarationIndex,
};
#[derive(crate::LehitRegistration)]
#[lehit(name = "NativePair", public)]
struct NativePair {
#[lehit(index = 0, public)]
exposed: i32,
private: i32,
}
#[derive(crate::LehitRegistration)]
#[lehit(name = "NativeChoice", public)]
#[repr(u8)]
enum NativeChoice {
#[lehit(index = 0)]
Empty,
#[lehit(index = 1)]
Value(i32),
}
unsafe impl NativeAbi for NativeChoice {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| {
NativeTypeLayout::enum_type::<NativeChoice>(NativeEnumLayout::direct(
vec![
NativeEnumVariant::unit(0),
NativeEnumVariant::payload(1, i32::native_layout(), 4),
],
0,
8,
false,
vec![0, 1],
))
})
}
}
fn i32_value_type() -> RustTypeRef {
RustTypeRef::Named(AccessPath {
file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local_access: "i32".into(),
generics: Vec::new(),
})
}
#[test]
fn registers_native_enum_variants_separately_from_physical_tags() {
let _empty = NativeChoice::Empty;
let NativeChoice::Value(payload) = NativeChoice::Value(7) else {
unreachable!()
};
assert_eq!(payload, 7);
let mut script = Script::default();
script.register_native::<NativeChoice>().unwrap();
let TypeLayout::Enum(enum_) = &script.types["NativeChoice"].layout else {
panic!("registered native enum expected")
};
assert_eq!(enum_.variants.len(), 2);
assert_eq!(enum_.variants[0].ident, "Empty");
assert_eq!(enum_.variants[1].ident, "Value");
assert_eq!(
script.native_types["NativeChoice"].exported_variants.len(),
2
);
}
#[test]
fn rust_function_pointer_helpers_derive_physical_signatures() {
fn combine(first: u32, second: u64) -> u64 {
u64::from(first) + second
}
fn consume(_: u8, _: u16, _: u32, _: u64) {}
fn read(value: &u32) -> u32 {
*value
}
fn clear(value: &mut u32) {
*value = 0;
}
fn read_add(value: &u32, extra: u16) -> u64 {
u64::from(*value) + u64::from(extra)
}
fn mutate_add(value: &mut u32, extra: u16) {
*value += u32::from(extra);
}
let returning = unsafe { NativeFunction::from_rust_fn2("combine", combine) };
let signature = returning.signature().unwrap();
assert_eq!(signature.arguments().len(), 2);
assert_eq!(
signature.arguments()[0].layout().rust_type_id,
std::any::TypeId::of::<u32>()
);
assert_eq!(
signature.arguments()[1].layout().rust_type_id,
std::any::TypeId::of::<u64>()
);
assert_eq!(
signature.return_type().unwrap().rust_type_id,
std::any::TypeId::of::<u64>()
);
let void = unsafe { NativeFunction::from_rust_fn4_void("consume", consume) };
assert_eq!(void.signature().unwrap().arguments().len(), 4);
assert!(void.signature().unwrap().return_type().is_none());
let shared = unsafe { NativeFunction::from_rust_fn1_ref("read", read) };
assert!(matches!(
shared.signature().unwrap().arguments(),
[NativeFunctionArgumentLayout::SharedBorrow(layout)]
if layout.rust_type_id == std::any::TypeId::of::<u32>()
));
let mutable = unsafe { NativeFunction::from_rust_fn1_mut_void("clear", clear) };
assert!(matches!(
mutable.signature().unwrap().arguments(),
[NativeFunctionArgumentLayout::MutableBorrow(layout)]
if layout.rust_type_id == std::any::TypeId::of::<u32>()
));
let mixed = unsafe { NativeFunction::from_rust_fn2_ref_owned("read_add", read_add) };
assert!(matches!(
mixed.signature().unwrap().arguments(),
[
NativeFunctionArgumentLayout::SharedBorrow(_),
NativeFunctionArgumentLayout::Owned(layout),
] if layout.rust_type_id == std::any::TypeId::of::<u16>()
));
let mixed_void =
unsafe { NativeFunction::from_rust_fn2_mut_owned_void("mutate_add", mutate_add) };
assert!(matches!(
mixed_void.signature().unwrap().arguments(),
[
NativeFunctionArgumentLayout::MutableBorrow(_),
NativeFunctionArgumentLayout::Owned(_),
]
));
assert!(mixed_void.signature().unwrap().return_type().is_none());
}
#[test]
fn native_registration_builder_assembles_functions_and_methods() {
fn identity(value: i32) -> i32 {
value
}
fn add(pair: &mut NativePair, amount: i32) -> i32 {
pair.exposed += amount;
pair.exposed
}
let i32_type = i32_value_type();
let pair_type = RustTypeRef::Named(AccessPath {
file_path: "native://builder.lt".into(),
local_access: "NativePair".into(),
generics: Vec::new(),
});
let mut script = Script::default();
let identity_native = unsafe { NativeFunction::from_rust_fn1("identity", identity) };
script
.native_function("identity", identity_native)
.public()
.exported()
.argument("value", i32_type.clone())
.returns(i32_type.clone())
.finish();
let identity = &script.functions["identity"];
assert!(identity.pub_visible);
assert!(identity.exported);
assert_eq!(identity.arguments[0].ident, "value");
assert!(matches!(identity.body, FunctionBody::Native(_)));
let type_ = script.register_native::<NativePair>().unwrap();
let add_native = unsafe { NativeFunction::from_rust_method_mut("add", add) };
type_
.native_method("add", add_native)
.mutable_receiver(pair_type.clone())
.argument("amount", i32_type.clone())
.returns(i32_type)
.finish();
let add = &script.types["NativePair"].functions["add"];
assert!(matches!(
add.self_argument,
Some(SelfArgument {
kind: SelfArgumentKind::Reference { mutable: true, .. },
..
})
));
assert_eq!(add.self_argument.as_ref().unwrap().value_type, pair_type);
assert_eq!(add.arguments[0].ident, "amount");
}
#[test]
fn safe_external_function_converts_panics_into_errors() {
let callback = external_function(|_| panic!("native callback failed"));
let mut context = ExternalCallContext::default();
let error = callback(&mut context).unwrap_err();
assert_eq!(error.message, "native callback failed");
}
#[test]
fn registers_only_explicitly_exported_native_fields() {
let mut script = Script::default();
script.register_native::<NativePair>().unwrap();
let TypeLayout::Structure(layout) = &script.types["NativePair"].layout else {
panic!("registered native structure expected")
};
assert_eq!(layout.size, std::mem::size_of::<NativePair>());
assert_eq!(layout.fields.len(), 1);
assert_eq!(layout.fields[0].ident, "exposed");
let parsed = parse_file(SourceFile {
path: core_lib::PRIMITIVE_MODULE_FILE_PATH,
text: core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
})
.unwrap();
let mut graph = ModuleGraph::default();
graph
.insert(
core_lib::PRIMITIVE_MODULE_FILE_PATH,
DeclarationIndex::collect(&parsed).unwrap(),
)
.unwrap();
script.validate_registered_field_types(&graph).unwrap();
}
#[test]
fn rejects_an_exported_field_whose_type_is_absent_from_lehit() {
let mut script = Script::default();
let RustTypeRef::Named(mut missing_path) = i32_value_type() else {
unreachable!()
};
missing_path.local_access = "Missing".into();
let missing = RustTypeRef::Named(missing_path);
script
.register_type::<NativePair>(
"NativePair",
true,
vec![RustFieldRegistration {
index: 0,
ident: "exposed".into(),
value_type: missing,
pub_visible: true,
}],
)
.unwrap();
let graph = ModuleGraph::default();
assert!(matches!(
script.validate_registered_field_types(&graph),
Err(errors) if matches!(errors.as_slice(), [RustTypeRegistrationError::UnknownLehitFieldType { .. }])
));
}
}