use std::{
collections::{BTreeMap, BTreeSet},
error::Error,
fmt,
sync::Arc,
};
use crate::{
core_lib,
parsing::{
ParseFailure, ParsedFile, SourceFile,
ast::{ContractDeclarationKind, ContractDefinitionContent, ContractSource},
parse_file,
},
runtime::{
ExecutionMode, JitError, LeasedJitCompilationUnit, OwnedJitCompilationUnit,
OwnedJitFunction, RuntimeAllocator, RuntimeErrorSink, ScriptCompilationError,
ScriptCompilationInput, ScriptCompilationSystem, TypeMetadataError, TypeMetadataRegistry,
},
rust_lib::{
Function as RustFunction, FunctionBody as RustFunctionBody, NativeFunction,
NativeTypeRegistration, RustFunctionRegistrationError, RustLib, RustTypeRef,
RustTypeRegistrationError, SelfArgumentKind,
},
semantic::{
BodyAnalysisError, CanonicalSymbolPath, CollectedAliasArgument, CollectedGenericParameter,
CollectedGenericParameterKind, CollectedSymbolKind, DeclarationCollectionError,
DeclarationIndex, FunctionRegistry, FunctionRegistryError, ModuleGraph, ModuleGraphError,
SemanticFunctionArgument, SemanticFunctionType, SemanticGenericArgument, SemanticLifetime,
SemanticNamedType, SemanticReceiver, SemanticType, TypeLowerer, TypeLoweringError,
},
};
#[derive(Debug)]
pub enum WorkspaceError {
Parse(ParseFailure),
UnknownCompilationUnit(crate::runtime::CompilationUnitId),
ModuleAlreadyLoaded {
module: String,
unit: crate::runtime::CompilationUnitId,
},
MissingScript {
requested_by: String,
path: String,
},
ConflictingScriptDependencies(String),
RustLibModuleConflict(String),
Declarations(Vec<DeclarationCollectionError>),
Module(ModuleGraphError),
Dependencies(Vec<ModuleGraphError>),
Functions(Vec<FunctionRegistryError>),
Body(Vec<BodyAnalysisError>),
RustTypes(Vec<RustTypeRegistrationError>),
RustFunctions(Vec<RustFunctionRegistrationError>),
TypeMetadata(Vec<TypeMetadataError>),
EntryType(TypeLoweringError),
MultipleFileFunctionContracts {
path: String,
},
DescriptorArity {
type_: String,
expected: usize,
actual: usize,
},
DescriptorArgumentKind {
type_: String,
parameter: String,
},
DescriptorExpectedType(CanonicalSymbolPath),
DescriptorAliasCycle(CanonicalSymbolPath),
Jit(JitError),
ScriptPlanning(String),
}
impl fmt::Display for WorkspaceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parse(error) => write!(f, "cannot parse `{}`", error.path),
Self::UnknownCompilationUnit(id) => write!(f, "unknown compilation unit `{id}`"),
Self::ModuleAlreadyLoaded { module, unit } => {
write!(
f,
"module `{module}` is already loaded in compilation unit `{unit}`"
)
}
Self::MissingScript { requested_by, path } => {
write!(
f,
"script `{requested_by}` requires missing script `{path}`"
)
}
Self::ConflictingScriptDependencies(path) => {
write!(
f,
"script `{path}` was discovered with conflicting dependencies"
)
}
Self::RustLibModuleConflict(path) => {
write!(f, "multiple Rust libraries define module `{path}`")
}
Self::Declarations(errors) => write!(f, "declaration errors: {errors:?}"),
Self::Module(error) => error.fmt(f),
Self::Dependencies(errors) => write!(f, "dependency errors: {errors:?}"),
Self::Functions(errors) => write!(f, "function registry errors: {errors:?}"),
Self::Body(errors) => write!(f, "body analysis errors: {errors:?}"),
Self::RustTypes(errors) => write!(f, "Rust type registration errors: {errors:?}"),
Self::RustFunctions(errors) => {
write!(f, "Rust function registration errors: {errors:?}")
}
Self::TypeMetadata(errors) => write!(f, "type metadata errors: {errors:?}"),
Self::EntryType(error) => write!(f, "file entry type error: {error}"),
Self::MultipleFileFunctionContracts { path } => {
write!(
f,
"script `{path}` declares more than one file function contract"
)
}
Self::DescriptorArity {
type_,
expected,
actual,
} => write!(
f,
"type descriptor `{type_}` expects {expected} generic arguments, got {actual}"
),
Self::DescriptorArgumentKind { type_, parameter } => write!(
f,
"generic argument for `{type_}` parameter `{parameter}` has the wrong kind"
),
Self::DescriptorExpectedType(path) => {
write!(f, "`{}::{}` does not name a type", path.module, path.local)
}
Self::DescriptorAliasCycle(path) => write!(
f,
"type descriptor alias cycle while resolving `{}::{}`",
path.module, path.local
),
Self::Jit(error) => error.fmt(f),
Self::ScriptPlanning(error) => write!(f, "script compilation planning failed: {error}"),
}
}
}
impl Error for WorkspaceError {}
fn validate_descriptor_arguments(
type_: &CanonicalSymbolPath,
parameters: &[CollectedGenericParameter],
arguments: &[SemanticGenericArgument],
) -> Result<(), WorkspaceError> {
if parameters.len() != arguments.len() {
return Err(WorkspaceError::DescriptorArity {
type_: format!("{}::{}", type_.module, type_.local),
expected: parameters.len(),
actual: arguments.len(),
});
}
for (parameter, argument) in parameters.iter().zip(arguments) {
let matches = matches!(
(¶meter.kind, argument),
(
CollectedGenericParameterKind::Type { .. },
SemanticGenericArgument::Type(_)
) | (
CollectedGenericParameterKind::Lifetime,
SemanticGenericArgument::Lifetime(_)
)
);
if !matches {
return Err(WorkspaceError::DescriptorArgumentKind {
type_: format!("{}::{}", type_.module, type_.local),
parameter: parameter.name.clone(),
});
}
}
Ok(())
}
pub(crate) const FILE_ENTRY_LOCAL_PATH: &str = "";
fn file_entry_signature(
graph: &ModuleGraph,
file: &ParsedFile,
path: &str,
) -> Result<Option<SemanticFunctionType>, WorkspaceError> {
let mut explicit = file
.ast
.file_contract_declarations
.iter()
.filter_map(|declaration| match &declaration.kind {
ContractDeclarationKind::FunctionOnly(function) => Some(function.as_ref()),
ContractDeclarationKind::FunctionAndLayout(declaration) => Some(&declaration.function),
_ => None,
});
let function = explicit.next();
if explicit.next().is_some() {
return Err(WorkspaceError::MultipleFileFunctionContracts {
path: path.to_owned(),
});
}
if let Some(function) = function {
return TypeLowerer::new(graph, file, path)
.lower_function(function)
.map(Some)
.map_err(WorkspaceError::EntryType);
}
if file.ast.contract_definition_content.statements.is_empty() {
Ok(None)
} else {
Ok(Some(SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(SemanticType::Void),
}))
}
}
#[derive(Clone)]
pub struct ScriptWorkspace {
graph: ModuleGraph,
files: BTreeMap<String, ParsedFile>,
native_types: BTreeMap<CanonicalSymbolPath, NativeTypeRegistration>,
native_functions: BTreeMap<CanonicalSymbolPath, NativeFunction>,
type_metadata: TypeMetadataRegistry,
rust_lib_unit: Option<Arc<LeasedJitCompilationUnit>>,
units: BTreeMap<crate::runtime::CompilationUnitId, Arc<LeasedJitCompilationUnit>>,
module_units: BTreeMap<String, crate::runtime::CompilationUnitId>,
next_unit_id: crate::runtime::CompilationUnitId,
allocator: RuntimeAllocator,
execution_mode: ExecutionMode,
error_sink: Option<RuntimeErrorSink>,
}
impl ScriptWorkspace {
pub fn with_core() -> Result<Self, WorkspaceError> {
Self::with_core_and_allocator(RuntimeAllocator::default())
}
pub fn with_core_and_allocator(allocator: RuntimeAllocator) -> Result<Self, WorkspaceError> {
Self::with_core_configuration(allocator, ExecutionMode::Direct, None)
}
pub(crate) fn with_core_configuration(
allocator: RuntimeAllocator,
execution_mode: ExecutionMode,
error_sink: Option<RuntimeErrorSink>,
) -> Result<Self, WorkspaceError> {
let mut graph = ModuleGraph::default();
let mut files = BTreeMap::new();
let core = core_lib::generate_core_lib();
for (path, script) in core.scripts {
let file = parse_file(SourceFile {
path: &path,
text: &script.content,
})
.map_err(WorkspaceError::Parse)?;
let declarations =
DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
graph
.insert(path.clone(), declarations)
.map_err(WorkspaceError::Module)?;
files.insert(path, file);
}
graph
.set_prelude(core_lib::PRELUDE_MODULE_FILE_PATH)
.map_err(WorkspaceError::Module)?;
let dependency_errors = graph.validate_dependencies();
if !dependency_errors.is_empty() {
return Err(WorkspaceError::Dependencies(dependency_errors));
}
let native_types = BTreeMap::new();
let type_metadata = TypeMetadataRegistry::build(&graph, &files, &native_types)
.map_err(WorkspaceError::TypeMetadata)?;
Ok(Self {
graph,
files,
native_types,
native_functions: BTreeMap::new(),
type_metadata,
rust_lib_unit: None,
units: BTreeMap::new(),
module_units: BTreeMap::new(),
next_unit_id: 0,
allocator,
execution_mode,
error_sink,
})
}
pub fn add_rust_libs(&mut self, libraries: &[&RustLib]) -> Result<(), WorkspaceError> {
let mut combined = RustLib::default();
for library in libraries {
for (path, script) in &library.scripts {
if combined
.scripts
.insert(path.clone(), script.clone())
.is_some()
{
return Err(WorkspaceError::RustLibModuleConflict(path.clone()));
}
}
}
self.add_rust_lib(&combined)
}
pub fn compile_rust_libs_unit(
&mut self,
libraries: &[&RustLib],
) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError> {
let mut candidate = self.clone();
candidate.add_rust_libs(libraries)?;
let modules = libraries
.iter()
.flat_map(|library| library.scripts.keys().cloned())
.collect::<Vec<_>>();
let executable = candidate.compile_registered_modules(&modules)?;
let unit = Arc::new(LeasedJitCompilationUnit::new(executable, Vec::new()));
candidate.rust_lib_unit = Some(Arc::clone(&unit));
*self = candidate;
Ok(unit)
}
pub fn add_rust_lib(&mut self, library: &RustLib) -> Result<(), WorkspaceError> {
let mut candidate_graph = self.graph.clone();
let mut candidate_files = self.files.clone();
let mut candidate_native_types = self.native_types.clone();
let mut candidate_native_functions = self.native_functions.clone();
for (path, script) in &library.scripts {
let file = parse_file(SourceFile {
path,
text: &script.content,
})
.map_err(WorkspaceError::Parse)?;
let declarations =
DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
candidate_graph
.insert(path.clone(), declarations)
.map_err(WorkspaceError::Module)?;
candidate_files.insert(path.clone(), file);
for (name, registration) in &script.native_types {
candidate_native_types.insert(
CanonicalSymbolPath {
module: path.clone(),
local: name.clone(),
},
registration.clone(),
);
}
}
let dependency_errors = candidate_graph.validate_dependencies();
if !dependency_errors.is_empty() {
return Err(WorkspaceError::Dependencies(dependency_errors));
}
let mut type_errors = Vec::new();
for (path, script) in &library.scripts {
if let Err(errors) = script.validate_registered_field_types(&candidate_graph) {
type_errors.extend(errors);
}
validate_native_contracts(
path,
script,
candidate_files
.get(path)
.expect("RustLib module was parsed above"),
&candidate_graph,
&mut type_errors,
);
}
if !type_errors.is_empty() {
return Err(WorkspaceError::RustTypes(type_errors));
}
let functions = FunctionRegistry::build(&candidate_graph, &candidate_files)
.map_err(WorkspaceError::Functions)?;
let candidate_type_metadata = build_type_metadata(
&candidate_graph,
&candidate_files,
&candidate_native_types,
&functions,
)
.map_err(WorkspaceError::TypeMetadata)?;
let mut function_errors = Vec::new();
for (module_path, script) in &library.scripts {
validate_rust_functions(
module_path,
script,
&candidate_graph,
&functions,
&candidate_type_metadata,
&mut function_errors,
);
}
if !function_errors.is_empty() {
return Err(WorkspaceError::RustFunctions(function_errors));
}
for (module_path, script) in &library.scripts {
collect_native_functions(module_path, script, &mut candidate_native_functions);
}
self.graph = candidate_graph;
self.files = candidate_files;
self.native_types = candidate_native_types;
self.native_functions = candidate_native_functions;
self.type_metadata = candidate_type_metadata;
Ok(())
}
pub fn allocator(&self) -> RuntimeAllocator {
self.allocator
}
pub fn execution_mode(&self) -> ExecutionMode {
self.execution_mode
}
pub fn graph(&self) -> &ModuleGraph {
&self.graph
}
pub fn files(&self) -> &BTreeMap<String, ParsedFile> {
&self.files
}
pub fn native_type(&self, path: &CanonicalSymbolPath) -> Option<&NativeTypeRegistration> {
self.native_types.get(path)
}
pub fn native_function(&self, path: &CanonicalSymbolPath) -> Option<&NativeFunction> {
self.native_functions.get(path)
}
pub fn type_metadata(&self) -> &TypeMetadataRegistry {
&self.type_metadata
}
pub fn unit_for_module(&self, module: &str) -> Option<crate::runtime::CompilationUnitId> {
self.module_units.get(module).copied()
}
pub fn loaded_unit(
&self,
id: crate::runtime::CompilationUnitId,
) -> Option<Arc<LeasedJitCompilationUnit>> {
self.units.get(&id).cloned()
}
pub fn compile_graph<F>(
&mut self,
root_path: &str,
root_source: &str,
mut provider: F,
) -> Result<crate::runtime::CompilationUnitId, WorkspaceError>
where
F: FnMut(&str) -> Result<Option<String>, WorkspaceError>,
{
let mut candidate = self.clone();
let root = candidate.compile_graph_ordered(root_path, root_source, &mut provider)?;
*self = candidate;
Ok(root)
}
pub fn reload_graph<F>(
&mut self,
root_path: &str,
root_source: &str,
mut provider: F,
) -> Result<crate::runtime::CompilationUnitId, WorkspaceError>
where
F: FnMut(&str) -> Result<Option<String>, WorkspaceError>,
{
let mut candidate = self.clone();
let old_unit = candidate.unit_for_module(root_path).ok_or_else(|| {
WorkspaceError::Module(ModuleGraphError::UnknownModule {
path: root_path.to_owned(),
})
})?;
let replaced_modules = candidate
.module_units
.iter()
.filter_map(|(module, unit)| (*unit == old_unit).then_some(module.clone()))
.collect::<Vec<_>>();
candidate.unload_unit(old_unit)?;
for module in replaced_modules {
candidate
.graph
.remove(&module)
.map_err(WorkspaceError::Module)?;
candidate.files.remove(&module);
}
let root = candidate.compile_graph_ordered(root_path, root_source, &mut provider)?;
*self = candidate;
Ok(root)
}
#[allow(dead_code)]
fn compile_graph_inner<F>(
&mut self,
root_path: &str,
root_source: &str,
provider: &mut F,
) -> Result<crate::runtime::CompilationUnitId, WorkspaceError>
where
F: FnMut(&str) -> Result<Option<String>, WorkspaceError>,
{
let existing_modules = self
.graph
.modules()
.map(|module| module.path.clone())
.collect::<std::collections::BTreeSet<_>>();
let mut sources = BTreeMap::from([(root_path.to_owned(), root_source.to_owned())]);
let mut dependencies = BTreeMap::new();
let root_dependencies = source_dependencies(root_path, root_source)?;
dependencies.insert(root_path.to_owned(), root_dependencies.clone());
let root = ScriptCompilationInput {
path: root_path.to_owned(),
dependencies: root_dependencies
.into_iter()
.filter(|dependency| !existing_modules.contains(dependency))
.collect(),
};
let plan = ScriptCompilationSystem
.plan([root], |path| {
let source = provider(path).map_err(|error| error)?;
let Some(source) = source else {
return Ok(None);
};
let discovered = source_dependencies(path, &source).map_err(|error| error)?;
dependencies.insert(path.to_owned(), discovered.clone());
sources.insert(path.to_owned(), source);
Ok(Some(ScriptCompilationInput {
path: path.to_owned(),
dependencies: discovered
.into_iter()
.filter(|dependency| !existing_modules.contains(dependency))
.collect(),
}))
})
.map_err(|error| match error {
ScriptCompilationError::Provider(error) => error,
ScriptCompilationError::MissingScript { requested_by, path } => {
WorkspaceError::MissingScript { requested_by, path }
}
ScriptCompilationError::ConflictingDependencies { path } => {
WorkspaceError::ConflictingScriptDependencies(path)
}
})?;
for unit in &plan.units {
let unit_sources = unit
.modules
.iter()
.map(|module| {
sources
.get(module)
.cloned()
.map(|source| (module.clone(), source))
.ok_or_else(|| WorkspaceError::MissingScript {
requested_by: "<planner>".into(),
path: module.clone(),
})
})
.collect::<Result<BTreeMap<_, _>, _>>()?;
let mut dependency_units = std::collections::BTreeSet::new();
for module in &unit.modules {
for dependency in dependencies.get(module).into_iter().flatten() {
if unit.modules.contains(dependency) {
continue;
}
if let Some(id) = self.unit_for_module(dependency) {
dependency_units.insert(id);
}
}
}
self.compile_and_register_scripts_unit(
unit_sources,
&dependency_units.into_iter().collect::<Vec<_>>(),
)?;
}
self.unit_for_module(root_path)
.ok_or_else(|| WorkspaceError::MissingScript {
requested_by: "<root>".into(),
path: root_path.to_owned(),
})
}
fn compile_graph_ordered<F>(
&mut self,
root_path: &str,
root_source: &str,
provider: &mut F,
) -> Result<crate::runtime::CompilationUnitId, WorkspaceError>
where
F: FnMut(&str) -> Result<Option<String>, WorkspaceError>,
{
let loaded_modules = self
.module_units
.keys()
.cloned()
.collect::<std::collections::BTreeSet<_>>();
let mut sources = BTreeMap::from([(root_path.to_owned(), root_source.to_owned())]);
let root_file = parse_file(SourceFile {
path: root_path,
text: root_source,
})
.map_err(WorkspaceError::Parse)?;
let root_declarations =
DeclarationIndex::collect(&root_file).map_err(WorkspaceError::Declarations)?;
let root = crate::runtime::ScriptCompilationInput {
path: root_path.to_owned(),
dependencies: root_declarations
.dependencies
.iter()
.filter(|dependency| !loaded_modules.contains(*dependency))
.cloned()
.collect(),
};
let mut inputs = BTreeMap::from([(root.path.clone(), root.clone())]);
let plan = crate::runtime::ScriptCompilationSystem
.plan([root], |path| {
let source = provider(path)?;
let Some(source) = source else {
return Ok::<_, WorkspaceError>(None);
};
let file = parse_file(SourceFile {
path,
text: &source,
})
.map_err(WorkspaceError::Parse)?;
let declarations =
DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
let input = crate::runtime::ScriptCompilationInput {
path: path.to_owned(),
dependencies: declarations
.dependencies
.iter()
.filter(|dependency| !loaded_modules.contains(*dependency))
.cloned()
.collect(),
};
sources.insert(path.to_owned(), source);
inputs.insert(path.to_owned(), input.clone());
Ok::<_, WorkspaceError>(Some(input))
})
.map_err(|error| WorkspaceError::ScriptPlanning(error.to_string()))?;
let mut compiled =
BTreeMap::<crate::runtime::CompilationUnitId, crate::runtime::CompilationUnitId>::new();
while compiled.len() < plan.units.len() {
let mut progress = false;
for unit in &plan.units {
if compiled.contains_key(&unit.id) {
continue;
}
let mut dependencies = std::collections::BTreeSet::new();
let mut ready = true;
for module in &unit.modules {
for dependency in &inputs[module].dependencies {
if unit.modules.contains(dependency) {
continue;
}
if let Some(id) = self.unit_for_module(dependency) {
dependencies.insert(id);
continue;
}
let Some(planned) = plan.unit_for(dependency) else {
return Err(WorkspaceError::ScriptPlanning(format!(
"module `{module}` depends on unplanned `{dependency}`"
)));
};
let Some(id) = compiled.get(&planned) else {
ready = false;
continue;
};
dependencies.insert(*id);
}
}
if !ready {
continue;
}
let unit_sources = unit
.modules
.iter()
.map(|module| (module.clone(), sources[module].clone()))
.collect();
let dependency_ids = dependencies.into_iter().collect::<Vec<_>>();
let runtime_id =
self.compile_and_register_scripts_unit(unit_sources, &dependency_ids)?;
compiled.insert(unit.id, runtime_id);
progress = true;
}
if !progress {
return Err(WorkspaceError::ScriptPlanning(
"SCC condensation graph could not be ordered".into(),
));
}
}
let root_plan_id = plan
.unit_for(root_path)
.ok_or_else(|| WorkspaceError::ScriptPlanning("root unit is absent".into()))?;
Ok(compiled[&root_plan_id])
}
pub fn compile_and_register_scripts_unit(
&mut self,
sources: BTreeMap<String, String>,
dependency_units: &[crate::runtime::CompilationUnitId],
) -> Result<crate::runtime::CompilationUnitId, WorkspaceError> {
for module in sources.keys() {
if let Some(unit) = self.module_units.get(module) {
return Err(WorkspaceError::ModuleAlreadyLoaded {
module: module.clone(),
unit: *unit,
});
}
}
let dependencies = dependency_units
.iter()
.map(|id| {
self.units
.get(id)
.cloned()
.ok_or(WorkspaceError::UnknownCompilationUnit(*id))
})
.collect::<Result<Vec<_>, _>>()?;
let modules = sources.keys().cloned().collect::<Vec<_>>();
let unit = self.compile_leased_scripts_unit(sources, dependencies)?;
let id = self.next_unit_id;
self.next_unit_id = self
.next_unit_id
.checked_add(1)
.expect("CompilationUnitId space exhausted");
for module in modules {
self.module_units.insert(module, id);
}
self.units.insert(id, unit);
Ok(id)
}
pub fn unload_unit(
&mut self,
id: crate::runtime::CompilationUnitId,
) -> Result<(), WorkspaceError> {
let unit = self
.units
.remove(&id)
.ok_or(WorkspaceError::UnknownCompilationUnit(id))?;
self.module_units.retain(|_, unit_id| *unit_id != id);
drop(unit);
Ok(())
}
pub fn unload_module(&mut self, module: &str) -> Result<(), WorkspaceError> {
let id = self.unit_for_module(module).ok_or_else(|| {
WorkspaceError::Module(ModuleGraphError::UnknownModule {
path: module.to_owned(),
})
})?;
self.unload_unit(id)
}
pub fn resolve_type(
&self,
requesting_module: &str,
path: &str,
) -> Result<SemanticType, WorkspaceError> {
self.resolve_named_type(requesting_module, path)
.map(SemanticType::Named)
}
pub fn resolve_named_type(
&self,
requesting_module: &str,
path: &str,
) -> Result<SemanticNamedType, WorkspaceError> {
let resolved = self
.graph
.resolve(requesting_module, path)
.map_err(WorkspaceError::Module)?;
Ok(SemanticNamedType::new(CanonicalSymbolPath {
module: resolved.module_path.to_owned(),
local: resolved.local_path.to_owned(),
}))
}
pub fn instantiate_named_type(
&self,
requesting_module: &str,
path: &str,
generic_arguments: impl IntoIterator<Item = SemanticGenericArgument>,
) -> Result<SemanticNamedType, WorkspaceError> {
self.resolve_named_descriptor(
requesting_module,
path,
generic_arguments.into_iter().collect(),
&mut BTreeSet::new(),
)
}
fn resolve_named_descriptor(
&self,
requesting_module: &str,
path: &str,
generic_arguments: Vec<SemanticGenericArgument>,
visited: &mut BTreeSet<CanonicalSymbolPath>,
) -> Result<SemanticNamedType, WorkspaceError> {
let declaration = self
.graph
.resolve_declaration(requesting_module, path)
.map_err(WorkspaceError::Module)?;
let canonical = CanonicalSymbolPath {
module: declaration.module_path.to_owned(),
local: declaration.local_path.to_owned(),
};
if !visited.insert(canonical.clone()) {
return Err(WorkspaceError::DescriptorAliasCycle(canonical));
}
validate_descriptor_arguments(
&canonical,
&declaration.symbol.generic_parameters,
&generic_arguments,
)?;
let result = match &declaration.symbol.kind {
CollectedSymbolKind::Alias { parameters, target } => {
let substitutions = parameters
.iter()
.zip(generic_arguments)
.map(|(parameter, argument)| (parameter.name.as_str(), argument))
.collect::<BTreeMap<_, _>>();
let mut target_arguments = Vec::with_capacity(target.arguments.len());
for argument in &target.arguments {
target_arguments.push(match argument {
CollectedAliasArgument::TypeParameter(name)
| CollectedAliasArgument::LifetimeParameter(name) => substitutions
.get(name.as_str())
.cloned()
.ok_or_else(|| WorkspaceError::DescriptorArgumentKind {
type_: canonical.local.clone(),
parameter: name.clone(),
})?,
CollectedAliasArgument::TypePath(path) => SemanticGenericArgument::Type(
SemanticType::Named(self.resolve_named_descriptor(
declaration.module_path,
path,
Vec::new(),
visited,
)?),
),
CollectedAliasArgument::Lifetime(name) => {
SemanticGenericArgument::Lifetime(SemanticLifetime::Named(name.clone()))
}
});
}
self.resolve_named_descriptor(
declaration.module_path,
&target.path,
target_arguments,
visited,
)
}
CollectedSymbolKind::Namespace => Ok(SemanticNamedType {
path: canonical,
generic_arguments,
}),
CollectedSymbolKind::Declaration(ids) if ids.type_.is_some() => Ok(SemanticNamedType {
path: canonical,
generic_arguments,
}),
_ => Err(WorkspaceError::DescriptorExpectedType(canonical)),
};
visited.remove(&CanonicalSymbolPath {
module: declaration.module_path.to_owned(),
local: declaration.local_path.to_owned(),
});
result
}
pub fn compile_leased_scripts_unit(
&mut self,
sources: BTreeMap<String, String>,
mut dependencies: Vec<Arc<LeasedJitCompilationUnit>>,
) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError> {
if let Some(rust_lib_unit) = &self.rust_lib_unit
&& !dependencies
.iter()
.any(|dependency| Arc::ptr_eq(dependency, rust_lib_unit))
{
dependencies.push(Arc::clone(rust_lib_unit));
}
let mut linked = BTreeMap::new();
for dependency in &dependencies {
linked.extend(dependency.exports());
}
let executable = self.compile_scripts_unit_with_linked(sources, &linked)?;
Ok(Arc::new(LeasedJitCompilationUnit::new(
executable,
dependencies,
)))
}
pub fn compile_scripts_unit(
&mut self,
sources: BTreeMap<String, String>,
) -> Result<OwnedJitCompilationUnit, WorkspaceError> {
self.compile_scripts_unit_with_linked(sources, &BTreeMap::new())
}
fn compile_registered_modules(
&self,
modules: &[String],
) -> Result<OwnedJitCompilationUnit, WorkspaceError> {
let functions =
FunctionRegistry::build(&self.graph, &self.files).map_err(WorkspaceError::Functions)?;
let mut bodies = BTreeMap::new();
let mut body_errors = Vec::new();
for path in modules {
let file = self
.files
.get(path)
.ok_or_else(|| WorkspaceError::MissingScript {
requested_by: "RustLib compilation unit".into(),
path: path.clone(),
})?;
let mut drafts = Vec::new();
collect_script_function_bodies(
file,
"",
&file.ast.contract_definition_content,
&mut drafts,
);
for (local, span, content) in drafts {
let canonical = CanonicalSymbolPath {
module: path.clone(),
local,
};
let Some(function) = functions.function_by_path(&canonical) else {
continue;
};
if !function.generic_parameters.is_empty() {
body_errors.push(BodyAnalysisError::Unsupported {
feature: "generic function monomorphization",
span,
});
continue;
}
match crate::semantic::BodyAnalyzer::new_with_metadata(
&self.graph,
&functions,
&self.type_metadata,
file,
path,
&function.signature,
) {
Ok(analyzer) => match analyzer.analyze(&content.statements) {
Ok(body) => {
bodies.insert(function.id, body);
}
Err(errors) => body_errors.extend(errors),
},
Err(error) => body_errors.push(error),
}
}
}
if !body_errors.is_empty() {
return Err(WorkspaceError::Body(body_errors));
}
OwnedJitCompilationUnit::compile_with_allocator_and_mode(
&bodies,
&functions,
&self.native_functions,
&self.type_metadata,
self.allocator,
self.execution_mode,
self.error_sink.clone(),
)
.map_err(WorkspaceError::Jit)
}
fn compile_scripts_unit_with_linked(
&mut self,
sources: BTreeMap<String, String>,
linked_functions: &BTreeMap<CanonicalSymbolPath, crate::runtime::LinkedFunction>,
) -> Result<OwnedJitCompilationUnit, WorkspaceError> {
let mut candidate_graph = self.graph.clone();
let mut candidate_files = self.files.clone();
for (path, source) in &sources {
let file =
parse_file(SourceFile { path, text: source }).map_err(WorkspaceError::Parse)?;
let declarations =
DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
candidate_graph
.insert(path.clone(), declarations)
.map_err(WorkspaceError::Module)?;
candidate_files.insert(path.clone(), file);
}
let dependency_errors = candidate_graph.validate_dependencies();
if !dependency_errors.is_empty() {
return Err(WorkspaceError::Dependencies(dependency_errors));
}
let mut functions = FunctionRegistry::build(&candidate_graph, &candidate_files)
.map_err(WorkspaceError::Functions)?;
let mut entry_ids = BTreeMap::new();
for path in sources.keys() {
let file = candidate_files
.get(path)
.expect("source module was inserted above");
if let Some(signature) = file_entry_signature(&candidate_graph, file, path)? {
let id = functions.insert_synthetic(
CanonicalSymbolPath {
module: path.clone(),
local: FILE_ENTRY_LOCAL_PATH.to_owned(),
},
signature,
);
entry_ids.insert(path.clone(), id);
}
}
let candidate_type_metadata = build_type_metadata(
&candidate_graph,
&candidate_files,
&self.native_types,
&functions,
)
.map_err(WorkspaceError::TypeMetadata)?;
let mut bodies = BTreeMap::new();
let mut body_errors = Vec::new();
for path in sources.keys() {
let file = candidate_files
.get(path)
.expect("source module was inserted above");
if let Some(entry_id) = entry_ids.get(path).copied() {
let entry = functions
.function(entry_id)
.expect("synthetic file entry was inserted above");
match crate::semantic::BodyAnalyzer::new_with_metadata(
&candidate_graph,
&functions,
&candidate_type_metadata,
file,
path,
&entry.signature,
) {
Ok(analyzer) => {
match analyzer.analyze(&file.ast.contract_definition_content.statements) {
Ok(body) => {
bodies.insert(entry_id, body);
}
Err(errors) => body_errors.extend(errors),
}
}
Err(error) => body_errors.push(error),
}
}
let mut drafts = Vec::new();
collect_script_function_bodies(
file,
"",
&file.ast.contract_definition_content,
&mut drafts,
);
for (local, span, content) in drafts {
let canonical = CanonicalSymbolPath {
module: path.clone(),
local,
};
let Some(function) = functions.function_by_path(&canonical) else {
continue;
};
if !function.generic_parameters.is_empty() {
body_errors.push(BodyAnalysisError::Unsupported {
feature: "generic function monomorphization",
span,
});
continue;
}
match crate::semantic::BodyAnalyzer::new_with_metadata(
&candidate_graph,
&functions,
&candidate_type_metadata,
file,
path,
&function.signature,
) {
Ok(analyzer) => match analyzer.analyze(&content.statements) {
Ok(body) => {
bodies.insert(function.id, body);
}
Err(errors) => body_errors.extend(errors),
},
Err(error) => body_errors.push(error),
}
}
}
if !body_errors.is_empty() {
return Err(WorkspaceError::Body(body_errors));
}
let compiled = OwnedJitCompilationUnit::compile_with_linked_and_allocator_and_mode(
&bodies,
&functions,
&self.native_functions,
linked_functions,
&candidate_type_metadata,
self.allocator,
self.execution_mode,
self.error_sink.clone(),
)
.map_err(WorkspaceError::Jit)?;
self.graph = candidate_graph;
self.files = candidate_files;
self.type_metadata = candidate_type_metadata;
Ok(compiled)
}
pub fn compile_script(
&mut self,
path: &str,
source: &str,
) -> Result<OwnedJitCompilationUnit, WorkspaceError> {
let file = parse_file(SourceFile { path, text: source }).map_err(WorkspaceError::Parse)?;
let declarations =
DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
let mut candidate_graph = self.graph.clone();
let mut candidate_files = self.files.clone();
candidate_graph
.insert(path.to_owned(), declarations)
.map_err(WorkspaceError::Module)?;
candidate_files.insert(path.to_owned(), file);
let dependency_errors = candidate_graph.validate_dependencies();
if !dependency_errors.is_empty() {
return Err(WorkspaceError::Dependencies(dependency_errors));
}
let mut functions = FunctionRegistry::build(&candidate_graph, &candidate_files)
.map_err(WorkspaceError::Functions)?;
let file = candidate_files
.get(path)
.expect("candidate file was inserted above");
let entry_id = file_entry_signature(&candidate_graph, file, path)?.map(|signature| {
functions.insert_synthetic(
CanonicalSymbolPath {
module: path.to_owned(),
local: FILE_ENTRY_LOCAL_PATH.to_owned(),
},
signature,
)
});
let candidate_type_metadata = build_type_metadata(
&candidate_graph,
&candidate_files,
&self.native_types,
&functions,
)
.map_err(WorkspaceError::TypeMetadata)?;
let mut drafts = Vec::new();
collect_script_function_bodies(
file,
"",
&file.ast.contract_definition_content,
&mut drafts,
);
let mut bodies = BTreeMap::new();
let mut body_errors = Vec::new();
if let Some(entry_id) = entry_id {
let entry = functions
.function(entry_id)
.expect("synthetic entry was inserted above");
match crate::semantic::BodyAnalyzer::new_with_metadata(
&candidate_graph,
&functions,
&candidate_type_metadata,
file,
path,
&entry.signature,
) {
Ok(analyzer) => {
match analyzer.analyze(&file.ast.contract_definition_content.statements) {
Ok(body) => {
bodies.insert(entry_id, body);
}
Err(errors) => body_errors.extend(errors),
}
}
Err(error) => body_errors.push(error),
}
}
for (local, span, content) in drafts {
let canonical = CanonicalSymbolPath {
module: path.to_owned(),
local,
};
let Some(function) = functions.function_by_path(&canonical) else {
continue;
};
if !function.generic_parameters.is_empty() {
body_errors.push(BodyAnalysisError::Unsupported {
feature: "generic function monomorphization",
span,
});
continue;
}
match crate::semantic::BodyAnalyzer::new_with_metadata(
&candidate_graph,
&functions,
&candidate_type_metadata,
file,
path,
&function.signature,
) {
Ok(analyzer) => match analyzer.analyze(&content.statements) {
Ok(body) => {
bodies.insert(function.id, body);
}
Err(errors) => body_errors.extend(errors),
},
Err(error) => body_errors.push(error),
}
}
if !body_errors.is_empty() {
return Err(WorkspaceError::Body(body_errors));
}
let compiled = OwnedJitCompilationUnit::compile_with_allocator_and_mode(
&bodies,
&functions,
&self.native_functions,
&candidate_type_metadata,
self.allocator,
self.execution_mode,
self.error_sink.clone(),
)
.map_err(WorkspaceError::Jit)?;
self.graph = candidate_graph;
self.files = candidate_files;
self.type_metadata = candidate_type_metadata;
Ok(compiled)
}
pub fn compile_body(
&mut self,
path: &str,
source: &str,
signature: SemanticFunctionType,
) -> Result<OwnedJitFunction, WorkspaceError> {
let file = parse_file(SourceFile { path, text: source }).map_err(WorkspaceError::Parse)?;
let declarations =
DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
let mut candidate_graph = self.graph.clone();
let mut candidate_files = self.files.clone();
candidate_graph
.insert(path.to_owned(), declarations)
.map_err(WorkspaceError::Module)?;
candidate_files.insert(path.to_owned(), file);
let dependency_errors = candidate_graph.validate_dependencies();
if !dependency_errors.is_empty() {
return Err(WorkspaceError::Dependencies(dependency_errors));
}
let functions = FunctionRegistry::build(&candidate_graph, &candidate_files)
.map_err(WorkspaceError::Functions)?;
let candidate_type_metadata = build_type_metadata(
&candidate_graph,
&candidate_files,
&self.native_types,
&functions,
)
.map_err(WorkspaceError::TypeMetadata)?;
let file = candidate_files
.get(path)
.expect("candidate file was inserted above");
let body = crate::semantic::BodyAnalyzer::new_with_metadata(
&candidate_graph,
&functions,
&candidate_type_metadata,
file,
path,
&signature,
)
.map_err(|error| WorkspaceError::Body(vec![error]))?
.analyze(&file.ast.contract_definition_content.statements)
.map_err(WorkspaceError::Body)?;
let compiled = OwnedJitFunction::compile_with_native_functions(
path,
&body,
&signature,
&functions,
&self.native_functions,
&candidate_type_metadata,
)
.map_err(WorkspaceError::Jit)?;
self.graph = candidate_graph;
self.files = candidate_files;
self.type_metadata = candidate_type_metadata;
Ok(compiled)
}
}
#[allow(dead_code)]
fn source_dependencies(path: &str, source: &str) -> Result<Vec<String>, WorkspaceError> {
let file = parse_file(SourceFile { path, text: source }).map_err(WorkspaceError::Parse)?;
let declarations = DeclarationIndex::collect(&file).map_err(WorkspaceError::Declarations)?;
Ok(declarations.dependencies.into_iter().collect())
}
fn collect_script_function_bodies<'a>(
file: &'a ParsedFile,
prefix: &str,
content: &'a ContractDefinitionContent,
output: &mut Vec<(String, crate::parsing::Span, &'a ContractDefinitionContent)>,
) {
for access in &content.contract_accesses {
let Some(name) = file.data.strings.get(access.ident.string.0 as usize) else {
continue;
};
let local = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}.{name}")
};
match &access.source {
ContractSource::Declaration(declaration) => {
let is_function = matches!(
declaration.kind,
ContractDeclarationKind::FunctionOnly(_)
| ContractDeclarationKind::FunctionAndLayout(_)
);
if is_function && let Some(definition) = &declaration.definition {
output.push((local.clone(), access.span, &definition.content));
}
if let Some(definition) = &declaration.definition {
collect_script_function_bodies(file, &local, &definition.content, output);
}
}
ContractSource::Definition(definition) => {
collect_script_function_bodies(file, &local, &definition.content, output);
}
ContractSource::Access(_) | ContractSource::File(_) => {}
}
}
for implementation in &content.trait_implementations {
let mut parts = Vec::with_capacity(implementation.trait_path.parts.1.len() + 1);
let Some(first) = file
.data
.strings
.get(implementation.trait_path.parts.0.ident.string.0 as usize)
else {
continue;
};
parts.push(first.clone());
let mut valid = true;
for part in &implementation.trait_path.parts.1 {
let Some(name) = file.data.strings.get(part.ident.string.0 as usize) else {
valid = false;
break;
};
parts.push(name.clone());
}
if !valid {
continue;
}
if let Some(definition) = &implementation.definition {
let trait_path = parts.join(".");
let owner = if prefix.is_empty() {
trait_path
} else {
format!("{prefix}.{trait_path}")
};
collect_script_function_bodies(file, &owner, &definition.content, output);
}
}
}
fn collect_native_functions(
module_path: &str,
script: &crate::rust_lib::Script,
output: &mut BTreeMap<CanonicalSymbolPath, NativeFunction>,
) {
let mut insert = |local: String, function: &RustFunction| {
if let RustFunctionBody::Native(native) = &function.body {
output.insert(
CanonicalSymbolPath {
module: module_path.to_owned(),
local,
},
native.clone(),
);
}
};
for (name, function) in &script.functions {
insert(name.clone(), function);
}
for (trait_name, trait_) in &script.traits {
for (name, function) in &trait_.functions {
insert(format!("{trait_name}.{name}"), function);
}
}
for (type_name, type_) in &script.types {
for (name, function) in &type_.functions {
insert(format!("{type_name}.{name}"), function);
}
for (trait_path, implementation) in &type_.trait_implementations {
for (name, function) in &implementation.functions {
insert(
format!("{type_name}.{}.{name}", trait_path.local_access),
function,
);
}
}
}
}
fn validate_rust_functions(
module_path: &str,
script: &crate::rust_lib::Script,
graph: &ModuleGraph,
registry: &FunctionRegistry,
type_metadata: &TypeMetadataRegistry,
errors: &mut Vec<RustFunctionRegistrationError>,
) {
for (name, function) in &script.functions {
validate_rust_function(
module_path,
name,
function,
graph,
registry,
type_metadata,
errors,
);
}
for (trait_name, trait_) in &script.traits {
for (name, function) in &trait_.functions {
validate_rust_function(
module_path,
&format!("{trait_name}.{name}"),
function,
graph,
registry,
type_metadata,
errors,
);
}
}
for (type_name, type_) in &script.types {
for (name, function) in &type_.functions {
validate_rust_function(
module_path,
&format!("{type_name}.{name}"),
function,
graph,
registry,
type_metadata,
errors,
);
}
for (trait_path, implementation) in &type_.trait_implementations {
for (name, function) in &implementation.functions {
validate_rust_function(
module_path,
&format!("{type_name}.{}.{name}", trait_path.local_access),
function,
graph,
registry,
type_metadata,
errors,
);
}
}
}
}
fn validate_rust_function(
module_path: &str,
local_path: &str,
rust: &RustFunction,
graph: &ModuleGraph,
registry: &FunctionRegistry,
type_metadata: &TypeMetadataRegistry,
errors: &mut Vec<RustFunctionRegistrationError>,
) {
let path = CanonicalSymbolPath {
module: module_path.to_owned(),
local: local_path.to_owned(),
};
let Some(lehit) = registry.function_by_path(&path) else {
errors.push(RustFunctionRegistrationError::MissingContract {
function: local_path.to_owned(),
});
return;
};
if rust.pub_visible != lehit.public {
errors.push(RustFunctionRegistrationError::VisibilityMismatch {
function: local_path.to_owned(),
});
}
let rust_signature = rust_function_signature(graph, rust);
let Ok(rust_signature) = rust_signature else {
errors.push(RustFunctionRegistrationError::InvalidTypeMetadata {
function: local_path.to_owned(),
});
return;
};
if rust_signature.receiver != lehit.signature.receiver {
errors.push(RustFunctionRegistrationError::ReceiverMismatch {
function: local_path.to_owned(),
});
}
if rust_signature.arguments.len() != lehit.signature.arguments.len() {
errors.push(RustFunctionRegistrationError::ArgumentCountMismatch {
function: local_path.to_owned(),
rust: rust_signature.arguments.len(),
lehit: lehit.signature.arguments.len(),
});
return;
}
for (index, (rust_argument, lehit_argument)) in rust_signature
.arguments
.iter()
.zip(&lehit.signature.arguments)
.enumerate()
{
if rust_argument.name != lehit_argument.name {
errors.push(RustFunctionRegistrationError::ArgumentNameMismatch {
function: local_path.to_owned(),
index,
rust: rust_argument.name.clone(),
lehit: lehit_argument.name.clone(),
});
}
if rust_argument.type_ != lehit_argument.type_ {
errors.push(RustFunctionRegistrationError::ArgumentTypeMismatch {
function: local_path.to_owned(),
index,
});
}
}
if rust_signature.return_type != lehit.signature.return_type {
errors.push(RustFunctionRegistrationError::ReturnTypeMismatch {
function: local_path.to_owned(),
});
}
let RustFunctionBody::Native(native) = &rust.body else {
return;
};
let Some(native_signature) = native.signature() else {
return;
};
let mut physical_arguments = Vec::new();
if let Some(receiver) = &rust.self_argument
&& let Ok(type_) = registered_field_type(graph, &receiver.value_type)
{
physical_arguments.push(match &receiver.kind {
SelfArgumentKind::Owned { .. } => type_,
SelfArgumentKind::Reference { lifetime, mutable } => SemanticType::Reference {
lifetime: lifetime
.as_ref()
.map(|lifetime| SemanticLifetime::Named(lifetime.clone())),
mutable: *mutable,
target: Box::new(type_),
},
});
}
physical_arguments.extend(
rust_signature
.arguments
.iter()
.map(|argument| argument.type_.clone()),
);
if native_signature.arguments().len() != physical_arguments.len() {
errors.push(
RustFunctionRegistrationError::NativeSignatureCountMismatch {
function: local_path.to_owned(),
rust: native_signature.arguments().len(),
lehit: physical_arguments.len(),
},
);
return;
}
for (index, (native_argument, semantic)) in native_signature
.arguments()
.iter()
.zip(&physical_arguments)
.enumerate()
{
if !native_argument_matches_semantic(*native_argument, semantic, type_metadata) {
errors.push(
RustFunctionRegistrationError::NativeArgumentLayoutMismatch {
function: local_path.to_owned(),
index,
},
);
}
}
let return_matches = match (
native_signature.return_type(),
rust_signature.return_type.as_ref(),
) {
(None, SemanticType::Void) => true,
(Some(layout), semantic) => native_layout_matches_semantic(layout, semantic, type_metadata),
(None, _) => false,
};
if !return_matches {
errors.push(RustFunctionRegistrationError::NativeReturnLayoutMismatch {
function: local_path.to_owned(),
});
}
}
fn native_argument_matches_semantic(
native: crate::rust_lib::NativeFunctionArgumentLayout,
semantic: &SemanticType,
registry: &TypeMetadataRegistry,
) -> bool {
match (native, semantic) {
(crate::rust_lib::NativeFunctionArgumentLayout::Owned(layout), semantic) => {
!matches!(semantic, SemanticType::Reference { .. })
&& native_layout_matches_semantic(layout, semantic, registry)
}
(
crate::rust_lib::NativeFunctionArgumentLayout::SharedBorrow(layout),
SemanticType::Reference {
mutable: false,
target,
..
},
) => native_layout_matches_semantic(layout, target, registry),
(
crate::rust_lib::NativeFunctionArgumentLayout::MutableBorrow(layout),
SemanticType::Reference {
mutable: true,
target,
..
},
) => native_layout_matches_semantic(layout, target, registry),
_ => false,
}
}
fn native_layout_matches_semantic(
native: &crate::runtime::NativeTypeLayout,
semantic: &SemanticType,
registry: &TypeMetadataRegistry,
) -> bool {
let Some((size, align)) = registry.layout_of(semantic) else {
return false;
};
if (native.size, native.align) != (size, align) {
return false;
}
let Some(metadata) = registry.metadata_of(semantic) else {
return true;
};
match (&native.kind, &metadata.kind) {
(
crate::runtime::NativeTypeKind::Scalar {
bits: native_bits,
signed: native_signed,
},
crate::runtime::TypeMetadataKind::Scalar { bits, signed },
) => native_bits == bits && native_signed == signed,
(
crate::runtime::NativeTypeKind::Structure { fields: native },
crate::runtime::TypeMetadataKind::Structure { fields },
) => fields.iter().all(|field| {
native
.iter()
.any(|native| native.index == field.index && native.offset == field.offset)
}),
(
crate::runtime::NativeTypeKind::Enum(native),
crate::runtime::TypeMetadataKind::Enum {
tag_offset,
tag_bits,
variants,
},
) => {
let tag_matches = match &native.tag {
crate::runtime::NativeEnumTag::Direct { offset, bits, .. } => {
offset == tag_offset && bits == tag_bits
}
crate::runtime::NativeEnumTag::Niche { offset, bits, .. } => {
offset == tag_offset && bits == tag_bits
}
crate::runtime::NativeEnumTag::SingleVariant => {
variants.len() == 1 && variants[0].fallback && !variants[0].writes_tag
}
};
tag_matches
&& native.variants.len() == variants.len()
&& native.variants.iter().all(|native_variant| {
variants.iter().any(|variant| {
variant.index == native_variant.index
&& variant.payload_offset == native_variant.payload_offset
})
})
}
(crate::runtime::NativeTypeKind::Opaque, crate::runtime::TypeMetadataKind::Native) => true,
_ => false,
}
}
fn rust_function_signature(
graph: &ModuleGraph,
function: &RustFunction,
) -> Result<SemanticFunctionType, ()> {
let receiver = function
.self_argument
.as_ref()
.map(|receiver| match &receiver.kind {
SelfArgumentKind::Owned { mutable } => SemanticReceiver {
borrow: false,
lifetime: None,
mutable: *mutable,
},
SelfArgumentKind::Reference { lifetime, mutable } => SemanticReceiver {
borrow: true,
lifetime: lifetime
.as_ref()
.map(|lifetime| SemanticLifetime::Named(lifetime.clone())),
mutable: *mutable,
},
});
let arguments = function
.arguments
.iter()
.map(|argument| {
Ok(SemanticFunctionArgument {
name: argument.ident.clone(),
mutable: false,
type_: registered_field_type(graph, &argument.value_type)?,
})
})
.collect::<Result<Vec<_>, ()>>()?;
let return_type = function
.return_value_type
.as_ref()
.map(|type_| registered_field_type(graph, type_))
.transpose()?
.unwrap_or(SemanticType::Void);
Ok(SemanticFunctionType {
receiver,
arguments,
return_type: Box::new(return_type),
})
}
fn validate_native_contracts(
module_path: &str,
script: &crate::rust_lib::Script,
file: &ParsedFile,
graph: &ModuleGraph,
errors: &mut Vec<RustTypeRegistrationError>,
) {
for (type_name, registration) in &script.native_types {
let Some(access) = file
.ast
.contract_definition_content
.contract_accesses
.iter()
.find(|access| {
file.data
.strings
.get(access.ident.string.0 as usize)
.map(String::as_str)
== Some(type_name.as_str())
})
else {
errors.push(RustTypeRegistrationError::MissingTypeContract {
type_: type_name.clone(),
});
continue;
};
let definition = match &access.source {
ContractSource::Declaration(declaration) => declaration.definition.as_ref(),
ContractSource::Definition(definition) => Some(definition.as_ref()),
_ => None,
};
let Some(definition) = definition else {
errors.push(RustTypeRegistrationError::MissingTypeContract {
type_: type_name.clone(),
});
continue;
};
let source_fields = definition
.content
.field_declarations
.iter()
.filter_map(|field| {
file.data
.strings
.get(field.ident.string.0 as usize)
.map(|name| (name.as_str(), field))
})
.collect::<BTreeMap<_, _>>();
let exported = registration
.exported_fields
.iter()
.map(|field| (field.ident.as_str(), field))
.collect::<BTreeMap<_, _>>();
for (name, field) in &source_fields {
let Some(registered) = exported.get(name) else {
errors.push(RustTypeRegistrationError::UnregisteredContractField {
type_: type_name.clone(),
field: (*name).to_owned(),
});
continue;
};
if field.pub_visible.is_some() != registered.pub_visible {
errors.push(RustTypeRegistrationError::FieldVisibilityMismatch {
type_: type_name.clone(),
field: (*name).to_owned(),
});
}
let actual = TypeLowerer::new(graph, file, module_path).lower(&field.value_type);
let expected = registered_field_type(graph, ®istered.value_type);
if !matches!((actual, expected), (Ok(actual), Ok(expected)) if actual == expected) {
errors.push(RustTypeRegistrationError::FieldTypeMismatch {
type_: type_name.clone(),
field: (*name).to_owned(),
});
}
}
for name in exported.keys() {
if !source_fields.contains_key(name) {
errors.push(RustTypeRegistrationError::MissingExportedField {
type_: type_name.clone(),
field: (*name).to_owned(),
});
}
}
let source_variants = definition
.content
.variant_declarations
.iter()
.filter_map(|variant| {
file.data
.strings
.get(variant.ident.string.0 as usize)
.map(|name| (name.as_str(), variant))
})
.collect::<BTreeMap<_, _>>();
let exported_variants = registration
.exported_variants
.iter()
.map(|variant| (variant.ident.as_str(), variant))
.collect::<BTreeMap<_, _>>();
for (name, variant) in &source_variants {
let Some(registered) = exported_variants.get(name) else {
errors.push(RustTypeRegistrationError::UnregisteredContractVariant {
module: module_path.to_owned(),
type_: type_name.clone(),
variant: (*name).to_owned(),
type_span: access.span,
variant_span: variant.span,
});
continue;
};
let actual = variant
.value_type
.as_ref()
.map(|type_| TypeLowerer::new(graph, file, module_path).lower(type_))
.transpose();
let expected = registered
.value_type
.as_ref()
.map(|type_| registered_field_type(graph, type_))
.transpose();
if !matches!((actual, expected), (Ok(actual), Ok(expected)) if actual == expected) {
errors.push(RustTypeRegistrationError::VariantPayloadTypeMismatch {
module: module_path.to_owned(),
type_: type_name.clone(),
variant: (*name).to_owned(),
type_span: access.span,
variant_span: variant.span,
});
}
}
for name in exported_variants.keys() {
if !source_variants.contains_key(name) {
errors.push(RustTypeRegistrationError::MissingExportedVariant {
module: module_path.to_owned(),
type_: type_name.clone(),
variant: (*name).to_owned(),
type_span: access.span,
});
}
}
}
}
fn build_type_metadata(
graph: &ModuleGraph,
files: &BTreeMap<String, ParsedFile>,
native_types: &BTreeMap<CanonicalSymbolPath, NativeTypeRegistration>,
functions: &FunctionRegistry,
) -> Result<TypeMetadataRegistry, Vec<crate::runtime::TypeMetadataError>> {
let mut specializations = Vec::<(SemanticNamedType, String)>::new();
for function in functions.iter() {
for argument in &function.signature.arguments {
collect_type_specializations(
&argument.type_,
&function.path.module,
&mut specializations,
);
}
collect_type_specializations(
&function.signature.return_type,
&function.path.module,
&mut specializations,
);
}
TypeMetadataRegistry::build_with_specializations(graph, files, native_types, &specializations)
}
fn collect_type_specializations(
type_: &SemanticType,
requesting_module: &str,
output: &mut Vec<(SemanticNamedType, String)>,
) {
match type_ {
SemanticType::Named(named) => {
for argument in &named.generic_arguments {
if let SemanticGenericArgument::Type(type_) = argument {
collect_type_specializations(type_, requesting_module, output);
}
}
if !named.generic_arguments.is_empty()
&& semantic_type_is_concrete(type_)
&& !output.iter().any(|(existing, _)| existing == named)
{
output.push((named.clone(), requesting_module.to_owned()));
}
}
SemanticType::Array { item, .. }
| SemanticType::Reference { target: item, .. }
| SemanticType::Pointer { target: item, .. } => {
collect_type_specializations(item, requesting_module, output)
}
SemanticType::Tuple(items) => {
for item in items {
collect_type_specializations(item, requesting_module, output);
}
}
SemanticType::Function(function) => {
for argument in &function.arguments {
collect_type_specializations(&argument.type_, requesting_module, output);
}
collect_type_specializations(&function.return_type, requesting_module, output);
}
SemanticType::Void
| SemanticType::SelfType
| SemanticType::Parameter(_)
| SemanticType::Associated { .. } => {}
}
}
fn semantic_type_is_concrete(type_: &SemanticType) -> bool {
match type_ {
SemanticType::Parameter(_) | SemanticType::Associated { .. } | SemanticType::SelfType => {
false
}
SemanticType::Named(named) => {
named
.generic_arguments
.iter()
.all(|argument| match argument {
SemanticGenericArgument::Type(type_) => semantic_type_is_concrete(type_),
SemanticGenericArgument::Lifetime(_) => true,
})
}
SemanticType::Array { item, .. }
| SemanticType::Reference { target: item, .. }
| SemanticType::Pointer { target: item, .. } => semantic_type_is_concrete(item),
SemanticType::Tuple(items) => items.iter().all(semantic_type_is_concrete),
SemanticType::Function(function) => {
function
.arguments
.iter()
.all(|argument| semantic_type_is_concrete(&argument.type_))
&& semantic_type_is_concrete(&function.return_type)
}
SemanticType::Void => true,
}
}
fn registered_field_type(graph: &ModuleGraph, type_: &RustTypeRef) -> Result<SemanticType, ()> {
match type_ {
RustTypeRef::Named(path) => registered_access_path_type(graph, path),
RustTypeRef::Reference {
lifetime,
mutable,
target,
} => Ok(SemanticType::Reference {
lifetime: lifetime
.as_ref()
.map(|lifetime| crate::semantic::SemanticLifetime::Named(lifetime.clone())),
mutable: *mutable,
target: Box::new(registered_field_type(graph, target)?),
}),
RustTypeRef::Pointer { mutable, target } => Ok(SemanticType::Pointer {
mutable: *mutable,
target: Box::new(registered_field_type(graph, target)?),
}),
}
}
fn registered_access_path_type(
graph: &ModuleGraph,
path: &crate::semantic::AccessPath,
) -> Result<SemanticType, ()> {
let resolved = graph
.resolve(&path.file_path, &path.local_access)
.map_err(|_| ())?;
let generic_arguments = path
.generics
.iter()
.map(|argument| {
registered_access_path_type(graph, argument).map(SemanticGenericArgument::Type)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: resolved.module_path.to_owned(),
local: resolved.local_path.to_owned(),
},
generic_arguments,
}))
}
#[cfg(test)]
mod tests {
use std::{
alloc::Layout,
any::TypeId,
collections::HashMap,
num::{NonZeroU8, NonZeroU32},
sync::OnceLock,
};
use super::*;
use crate::{
runtime::{
NativeAbi, NativeField, NativePassMode, NativeRegisterChunk, NativeRegisterClass,
NativeTypeKind, NativeTypeLayout,
},
rust_lib::{
FunctionArgument, FunctionBody, NativeFunctionSignature, RustEnumVariantRegistration,
RustFieldRegistration, RustTypeRef, Script,
},
semantic::AccessPath,
};
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct NativePair {
value: i32,
hidden: i32,
}
unsafe impl NativeAbi for NativePair {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<NativePair>(),
size: Layout::new::<NativePair>().size(),
align: Layout::new::<NativePair>().align(),
kind: NativeTypeKind::Structure {
fields: vec![
NativeField {
index: 0,
offset: 0,
layout: i32::native_layout(),
},
NativeField {
index: 1,
offset: Layout::new::<i32>().size(),
layout: i32::native_layout(),
},
],
},
})
}
fn native_pass_mode() -> NativePassMode {
NativePassMode::Registers(vec![NativeRegisterChunk {
offset: 0,
class: NativeRegisterClass::Integer { bits: 64 },
}])
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct NativeWide {
first: i64,
hidden: i64,
}
unsafe impl NativeAbi for NativeWide {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<NativeWide>(),
size: Layout::new::<NativeWide>().size(),
align: Layout::new::<NativeWide>().align(),
kind: NativeTypeKind::Structure {
fields: vec![
NativeField {
index: 0,
offset: 0,
layout: i64::native_layout(),
},
NativeField {
index: 1,
offset: Layout::new::<i64>().size(),
layout: i64::native_layout(),
},
],
},
})
}
fn native_pass_mode() -> NativePassMode {
NativePassMode::Registers(vec![
NativeRegisterChunk {
offset: 0,
class: NativeRegisterClass::Integer { bits: 64 },
},
NativeRegisterChunk {
offset: 8,
class: NativeRegisterClass::Integer { bits: 64 },
},
])
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
struct NativeMixed {
floating: f64,
hidden: i64,
}
unsafe impl NativeAbi for NativeMixed {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<NativeMixed>(),
size: Layout::new::<NativeMixed>().size(),
align: Layout::new::<NativeMixed>().align(),
kind: NativeTypeKind::Structure {
fields: vec![
NativeField {
index: 0,
offset: 0,
layout: f64::native_layout(),
},
NativeField {
index: 1,
offset: Layout::new::<f64>().size(),
layout: i64::native_layout(),
},
],
},
})
}
fn native_pass_mode() -> NativePassMode {
NativePassMode::Registers(vec![
NativeRegisterChunk {
offset: 0,
class: NativeRegisterClass::Float { bits: 64 },
},
NativeRegisterChunk {
offset: 8,
class: NativeRegisterClass::Integer { bits: 64 },
},
])
}
}
#[repr(u8)]
enum NativeDirectEnum {
Empty = 7,
Value(i32) = 9,
}
unsafe impl NativeAbi for NativeDirectEnum {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<NativeDirectEnum>(),
size: Layout::new::<NativeDirectEnum>().size(),
align: Layout::new::<NativeDirectEnum>().align(),
kind: NativeTypeKind::Enum(crate::runtime::NativeEnumLayout {
variants: vec![
crate::runtime::NativeEnumVariant {
index: 0,
payload: None,
payload_offset: None,
},
crate::runtime::NativeEnumVariant {
index: 1,
payload: Some(i32::native_layout()),
payload_offset: Some(4),
},
],
tag: crate::runtime::NativeEnumTag::Direct {
offset: 0,
bits: 8,
signed: false,
variant_tags: vec![7, 9],
},
}),
})
}
}
enum NativeNicheEnum {
Data(NonZeroU8),
Empty,
}
unsafe impl NativeAbi for NativeNicheEnum {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<NativeNicheEnum>(),
size: Layout::new::<NativeNicheEnum>().size(),
align: Layout::new::<NativeNicheEnum>().align(),
kind: NativeTypeKind::Enum(crate::runtime::NativeEnumLayout {
variants: vec![
crate::runtime::NativeEnumVariant {
index: 0,
payload: Some(u8::native_layout()),
payload_offset: Some(0),
},
crate::runtime::NativeEnumVariant {
index: 1,
payload: None,
payload_offset: None,
},
],
tag: crate::runtime::NativeEnumTag::Niche {
offset: 0,
bits: 8,
niche_start: 0,
niche_variants: 1..=1,
data_variant: 0,
},
}),
})
}
}
enum InvalidNativeEnum {
First,
Second,
}
unsafe impl NativeAbi for InvalidNativeEnum {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<InvalidNativeEnum>(),
size: Layout::new::<InvalidNativeEnum>().size(),
align: Layout::new::<InvalidNativeEnum>().align(),
kind: NativeTypeKind::Enum(crate::runtime::NativeEnumLayout {
variants: vec![
crate::runtime::NativeEnumVariant {
index: 0,
payload: None,
payload_offset: None,
},
crate::runtime::NativeEnumVariant {
index: 1,
payload: None,
payload_offset: None,
},
],
tag: crate::runtime::NativeEnumTag::Direct {
offset: 0,
bits: 8,
signed: false,
variant_tags: vec![0, 0],
},
}),
})
}
}
enum InvalidIndexedNativeEnum {
First,
Second(u8),
}
unsafe impl NativeAbi for InvalidIndexedNativeEnum {
fn native_layout() -> &'static NativeTypeLayout {
static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
LAYOUT.get_or_init(|| NativeTypeLayout {
rust_type_id: TypeId::of::<InvalidIndexedNativeEnum>(),
size: Layout::new::<InvalidIndexedNativeEnum>().size(),
align: Layout::new::<InvalidIndexedNativeEnum>().align(),
kind: NativeTypeKind::Enum(crate::runtime::NativeEnumLayout {
variants: vec![
crate::runtime::NativeEnumVariant {
index: 41,
payload: None,
payload_offset: None,
},
crate::runtime::NativeEnumVariant {
index: 7,
payload: Some(u8::native_layout()),
payload_offset: None,
},
],
tag: crate::runtime::NativeEnumTag::Direct {
offset: 0,
bits: 8,
signed: false,
variant_tags: vec![0, 1],
},
}),
})
}
}
fn named_core_type(name: &str) -> RustTypeRef {
RustTypeRef::Named(AccessPath {
file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local_access: name.into(),
generics: Vec::new(),
})
}
fn function_library(return_type: RustTypeRef) -> RustLib {
let script = Script {
content: "pub acs add: fn(left: i32, right: i32) -> i32".into(),
functions: HashMap::from([(
"add".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![
FunctionArgument {
ident: "left".into(),
value_type: named_core_type("i32"),
},
FunctionArgument {
ident: "right".into(),
value_type: named_core_type("i32"),
},
],
return_value_type: Some(return_type),
body: FunctionBody::Ir(String::new()),
},
)]),
..Script::default()
};
RustLib {
scripts: HashMap::from([("native://functions.lt".into(), script)]),
}
}
fn native_library(source: &str) -> RustLib {
let mut script = Script {
content: source.into(),
..Script::default()
};
script
.register_type::<NativePair>(
"NativePair",
true,
vec![RustFieldRegistration {
index: 0,
ident: "value".into(),
value_type: RustTypeRef::Named(AccessPath {
file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local_access: "i32".into(),
generics: Vec::new(),
}),
pub_visible: true,
}],
)
.unwrap();
RustLib {
scripts: HashMap::from([("native://types.lt".into(), script)]),
}
}
extern "C" fn direct_native_pair_identity(value: NativePair) -> NativePair {
value
}
extern "C" fn direct_native_wide_identity(value: NativeWide) -> NativeWide {
value
}
extern "C" fn direct_native_wide_add(left: NativeWide, right: NativeWide) -> NativeWide {
NativeWide {
first: left.first + right.first,
hidden: left.hidden + right.hidden,
}
}
extern "C" fn direct_native_wide_scale(value: NativeWide, factor: i64) -> NativeWide {
NativeWide {
first: value.first * factor,
hidden: value.hidden * factor,
}
}
extern "C" fn direct_native_wide_sum(value: NativeWide) -> i64 {
value.first + value.hidden
}
extern "C" fn direct_native_wide_from_borrow(value: &NativeWide) -> NativeWide {
NativeWide {
first: value.first + 1,
hidden: value.hidden + 2,
}
}
extern "C" fn direct_native_wide_mutate(value: &mut NativeWide, delta: i64) -> i64 {
value.first += delta;
value.hidden -= delta;
value.first + value.hidden
}
extern "C" fn direct_native_mixed_identity(value: NativeMixed) -> NativeMixed {
value
}
#[test]
fn installs_direct_native_enum_tags_and_payload_offsets_without_remapping() {
let module = "native://direct_enum.lt";
let mut script = Script {
content: "pub acs NativeDirectEnum: enum { var Empty var Value i32 }".into(),
..Script::default()
};
script
.register_enum_type::<NativeDirectEnum>(
"NativeDirectEnum",
true,
vec![
RustEnumVariantRegistration {
index: 0,
ident: "Empty".into(),
value_type: None,
},
RustEnumVariantRegistration {
index: 1,
ident: "Value".into(),
value_type: Some(named_core_type("i32")),
},
],
)
.unwrap();
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace.add_rust_lib(&library).unwrap();
let metadata = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: module.into(),
local: "NativeDirectEnum".into(),
})
.unwrap();
assert_eq!(metadata.origin, crate::runtime::TypeOrigin::Rust);
let crate::runtime::TypeMetadataKind::Enum {
tag_offset,
tag_bits,
variants,
} = &metadata.kind
else {
panic!("native enum metadata expected")
};
assert_eq!((*tag_offset, *tag_bits), (0, 8));
assert_eq!(
variants
.iter()
.map(|variant| (variant.index, variant.tag, variant.payload_offset))
.collect::<Vec<_>>(),
vec![(0, 7, None), (1, 9, Some(4))]
);
let script_module = "app://match_native_enum.lt";
let unit = workspace
.compile_script(
script_module,
"acs native: \"native://direct_enum.lt\"
pub acs classify: fn(value: native.NativeDirectEnum) -> i32 {
return match value {
native.NativeDirectEnum.Empty => 0
native.NativeDirectEnum.Value(payload) => payload
}
}",
)
.unwrap();
let function = CanonicalSymbolPath {
module: script_module.into(),
local: "classify".into(),
};
let pointer = unit.function_ptr(&function).unwrap();
let call: unsafe extern "C" fn(*const NativeDirectEnum) -> i32 =
unsafe { std::mem::transmute_copy(&pointer) };
let empty = NativeDirectEnum::Empty;
let value = NativeDirectEnum::Value(42);
assert!(matches!(&value, NativeDirectEnum::Value(42)));
assert_eq!(unsafe { call(&empty) }, 0);
assert_eq!(unsafe { call(&value) }, 42);
}
#[test]
fn matches_a_native_niche_enum_without_a_separate_discriminant() {
let module = "native://niche_enum.lt";
let mut script = Script {
content: "pub acs NativeNicheEnum: enum { var Data u8 var Empty }".into(),
..Script::default()
};
script
.register_enum_type::<NativeNicheEnum>(
"NativeNicheEnum",
true,
vec![
RustEnumVariantRegistration {
index: 0,
ident: "Data".into(),
value_type: Some(named_core_type("u8")),
},
RustEnumVariantRegistration {
index: 1,
ident: "Empty".into(),
value_type: None,
},
],
)
.unwrap();
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace.add_rust_lib(&library).unwrap();
let app_module = "app://match_niche_enum.lt";
let unit = workspace
.compile_script(
app_module,
"acs native: \"native://niche_enum.lt\"
pub acs read: fn(value: native.NativeNicheEnum) -> u8 {
return match value {
native.NativeNicheEnum.Data(payload) => payload
native.NativeNicheEnum.Empty => 0u8
}
}",
)
.unwrap();
let path = CanonicalSymbolPath {
module: app_module.into(),
local: "read".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*const NativeNicheEnum) -> u8 =
unsafe { std::mem::transmute_copy(&pointer) };
let data = NativeNicheEnum::Data(NonZeroU8::new(37).unwrap());
let empty = NativeNicheEnum::Empty;
assert!(matches!(&data, NativeNicheEnum::Data(value) if value.get() == 37));
assert_eq!(unsafe { call(&data) }, 37);
assert_eq!(unsafe { call(&empty) }, 0);
}
#[test]
fn rejects_invalid_native_enum_layout_transactionally() {
let _first = InvalidNativeEnum::First;
let _second = InvalidNativeEnum::Second;
let module = "native://invalid_enum.lt";
let mut script = Script {
content: "pub acs InvalidNativeEnum: enum { var First var Second }".into(),
..Script::default()
};
script
.register_enum_type::<InvalidNativeEnum>(
"InvalidNativeEnum",
true,
vec![
RustEnumVariantRegistration {
index: 0,
ident: "First".into(),
value_type: None,
},
RustEnumVariantRegistration {
index: 1,
ident: "Second".into(),
value_type: None,
},
],
)
.unwrap();
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let error = workspace.add_rust_lib(&library).unwrap_err();
assert!(matches!(
error,
WorkspaceError::TypeMetadata(errors)
if errors.iter().any(|error| matches!(
error,
crate::runtime::TypeMetadataError::InvalidNativeLayout { path, reason, .. }
if path.module == module
&& path.local == "InvalidNativeEnum"
&& reason
== &crate::runtime::NativeLayoutErrorKind::DuplicateTag { tag: 0 }
))
));
assert!(workspace.graph().module(module).is_none());
}
#[test]
fn maps_native_variant_error_spans_by_registered_name_not_index_position() {
let _first = InvalidIndexedNativeEnum::First;
let second = InvalidIndexedNativeEnum::Second(3);
assert!(matches!(second, InvalidIndexedNativeEnum::Second(3)));
let module = "native://invalid_indexed_enum.lt";
let source = "pub acs InvalidIndexedNativeEnum: enum { var First var Second u8 }";
let mut script = Script {
content: source.into(),
..Script::default()
};
script
.register_enum_type::<InvalidIndexedNativeEnum>(
"InvalidIndexedNativeEnum",
true,
vec![
RustEnumVariantRegistration {
index: 41,
ident: "First".into(),
value_type: None,
},
RustEnumVariantRegistration {
index: 7,
ident: "Second".into(),
value_type: Some(named_core_type("u8")),
},
],
)
.unwrap();
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let error = workspace.add_rust_lib(&library).unwrap_err();
let WorkspaceError::TypeMetadata(errors) = error else {
panic!("type metadata error expected")
};
let (_, variant_span) = errors
.iter()
.find_map(|error| match error {
crate::runtime::TypeMetadataError::InvalidNativeLayout {
reason:
crate::runtime::NativeLayoutErrorKind::InvalidPayload {
variant: Some(7), ..
},
variant_span,
..
} => Some((error, variant_span)),
_ => None,
})
.expect("invalid payload error for semantic index 7 expected");
let span = variant_span.expect("variant label expected");
assert_eq!(
&source[span.start as usize..span.end as usize],
"var Second u8"
);
}
#[test]
fn rejects_native_enum_contract_variant_and_payload_mismatches_transactionally() {
let module = "native://enum_contract_mismatch.lt";
let mut script = Script {
content: "pub acs NativeDirectEnum: enum { var Empty var Value u8 var Extra }".into(),
..Script::default()
};
script
.register_enum_type::<NativeDirectEnum>(
"NativeDirectEnum",
true,
vec![
RustEnumVariantRegistration {
index: 0,
ident: "Empty".into(),
value_type: None,
},
RustEnumVariantRegistration {
index: 1,
ident: "Value".into(),
value_type: Some(named_core_type("i32")),
},
],
)
.unwrap();
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let error = workspace.add_rust_lib(&library).unwrap_err();
let WorkspaceError::RustTypes(errors) = error else {
panic!("Rust type contract errors expected")
};
assert!(errors.iter().any(|error| matches!(
error,
RustTypeRegistrationError::VariantPayloadTypeMismatch { type_, variant, .. }
if type_ == "NativeDirectEnum" && variant == "Value"
)));
assert!(errors.iter().any(|error| matches!(
error,
RustTypeRegistrationError::UnregisteredContractVariant { type_, variant, .. }
if type_ == "NativeDirectEnum" && variant == "Extra"
)));
assert!(workspace.graph().module(module).is_none());
let missing_module = "native://enum_missing_variant.lt";
let mut missing_script = Script {
content: "pub acs NativeDirectEnum: enum { var Empty }".into(),
..Script::default()
};
missing_script
.register_enum_type::<NativeDirectEnum>(
"NativeDirectEnum",
true,
vec![
RustEnumVariantRegistration {
index: 0,
ident: "Empty".into(),
value_type: None,
},
RustEnumVariantRegistration {
index: 1,
ident: "Value".into(),
value_type: Some(named_core_type("i32")),
},
],
)
.unwrap();
let missing_library = RustLib {
scripts: HashMap::from([(missing_module.into(), missing_script)]),
};
let missing_error = workspace.add_rust_lib(&missing_library).unwrap_err();
assert!(matches!(
missing_error,
WorkspaceError::RustTypes(errors)
if errors.iter().any(|error| matches!(
error,
RustTypeRegistrationError::MissingExportedVariant { type_, variant, .. }
if type_ == "NativeDirectEnum" && variant == "Value"
))
));
assert!(workspace.graph().module(missing_module).is_none());
}
#[test]
fn computes_layout_metadata_for_a_lehit_structure() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let return_type = workspace
.resolve_type(core_lib::PRELUDE_MODULE_FILE_PATH, "i32")
.unwrap();
let _compiled = workspace
.compile_body(
"app://point.lt",
"pub acs Point: struct { pub fld x: i32 pub fld y: i32 } return 0",
SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(return_type),
},
)
.unwrap();
let metadata = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: "app://point.lt".into(),
local: "Point".into(),
})
.unwrap();
assert_eq!(metadata.origin, crate::runtime::TypeOrigin::Lehit);
assert_eq!((metadata.size, metadata.align), (8, 4));
let crate::runtime::TypeMetadataKind::Structure { fields } = &metadata.kind else {
panic!("structure metadata expected")
};
assert_eq!(
fields.iter().map(|field| field.offset).collect::<Vec<_>>(),
vec![0, 4]
);
}
#[test]
fn computes_tag_and_payload_layout_metadata_for_a_lehit_enum() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let return_type = workspace
.resolve_type(core_lib::PRELUDE_MODULE_FILE_PATH, "i32")
.unwrap();
workspace
.compile_body(
"app://state.lt",
"pub acs State: enum { var Empty var Byte u8 var Wide i64 }
pub acs Small: enum { var Empty var Value u8 }
pub acs SingleUnit: enum { var Only }
pub acs SingleValue: enum { var Only i64 }
return 0",
SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(return_type),
},
)
.unwrap();
let metadata = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: "app://state.lt".into(),
local: "State".into(),
})
.unwrap();
assert_eq!(metadata.origin, crate::runtime::TypeOrigin::Lehit);
assert_eq!((metadata.size, metadata.align), (16, 8));
let crate::runtime::TypeMetadataKind::Enum {
tag_offset,
tag_bits,
variants,
} = &metadata.kind
else {
panic!("enum metadata expected")
};
assert_eq!((*tag_offset, *tag_bits), (0, 8));
assert_eq!(
variants
.iter()
.map(|variant| (
variant.index,
variant.name.as_str(),
variant.tag,
variant.payload_offset,
))
.collect::<Vec<_>>(),
vec![
(0, "Empty", 0, None),
(1, "Byte", 1, Some(8)),
(2, "Wide", 2, Some(8)),
]
);
let small = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: "app://state.lt".into(),
local: "Small".into(),
})
.unwrap();
assert_eq!((small.size, small.align), (2, 1));
assert!(matches!(
&small.kind,
crate::runtime::TypeMetadataKind::Enum { tag_bits: 8, .. }
));
for (name, expected_layout, expected_payload) in [
("SingleUnit", (0, 1), None),
("SingleValue", (8, 8), Some(0)),
] {
let single = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: "app://state.lt".into(),
local: name.into(),
})
.unwrap();
assert_eq!((single.size, single.align), expected_layout);
let crate::runtime::TypeMetadataKind::Enum { variants, .. } = &single.kind else {
panic!("enum metadata expected")
};
assert_eq!(variants.len(), 1);
assert!(variants[0].fallback);
assert!(!variants[0].writes_tag);
assert!(variants[0].matching_tags.is_empty());
assert_eq!(variants[0].payload_offset, expected_payload);
}
}
#[test]
fn constructs_unit_and_payload_enum_variants_in_jit_code() {
let module = "app://enum_constructors.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs State: enum { var Empty var Byte u8 var Wide i64 }
pub acs make_empty: fn() -> State { return State.Empty }
pub acs make_wide: fn() -> State { return State.Wide(42) }",
)
.unwrap();
let empty_path = CanonicalSymbolPath {
module: module.into(),
local: "make_empty".into(),
};
let wide_path = CanonicalSymbolPath {
module: module.into(),
local: "make_wide".into(),
};
let empty_ptr = unit.function_ptr(&empty_path).unwrap();
let wide_ptr = unit.function_ptr(&wide_path).unwrap();
let empty_call: unsafe extern "C" fn(*mut [u8; 16]) =
unsafe { std::mem::transmute_copy(&empty_ptr) };
let wide_call: unsafe extern "C" fn(*mut [u8; 16]) =
unsafe { std::mem::transmute_copy(&wide_ptr) };
let mut empty = [0xAA; 16];
let mut wide = [0xAA; 16];
unsafe {
empty_call(&mut empty);
wide_call(&mut wide);
}
assert_eq!(empty[0], 0);
assert_eq!(wide[0], 2);
assert_eq!(i64::from_ne_bytes(wide[8..16].try_into().unwrap()), 42);
}
#[test]
fn exhaustively_matches_unit_enum_variants_in_jit_code() {
let module = "app://enum_match.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs State: enum { var Off var On }
pub acs classify: fn(value: State) -> i32 {
return match value { State.Off => 10 State.On => 20 }
}",
)
.unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "classify".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*const [u8; 1]) -> i32 =
unsafe { std::mem::transmute_copy(&pointer) };
assert_eq!(unsafe { call(&[0]) }, 10);
assert_eq!(unsafe { call(&[1]) }, 20);
let error = match workspace.compile_script(
"app://non_exhaustive_match.lt",
"pub acs State: enum { var Off var On }
pub acs classify: fn(value: State) -> i32 {
return match value { State.Off => 10 }
}",
) {
Ok(_) => panic!("non-exhaustive match must be rejected"),
Err(error) => error,
};
assert!(error.to_string().contains("non-exhaustive enum match"));
}
#[test]
fn binds_and_returns_an_owned_enum_payload_from_match() {
let module = "app://enum_payload_match.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs MaybeI64: enum { var Empty var Value i64 }
pub acs unwrap_or_zero: fn(value: MaybeI64) -> i64 {
return match value {
MaybeI64.Empty => 0
MaybeI64.Value(payload) => payload
}
}",
)
.unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "unwrap_or_zero".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*const [u8; 16]) -> i64 =
unsafe { std::mem::transmute_copy(&pointer) };
let empty = [0u8; 16];
let mut value = [0u8; 16];
value[0] = 1;
value[8..16].copy_from_slice(&123_456_i64.to_ne_bytes());
assert_eq!(unsafe { call(&empty) }, 0);
assert_eq!(unsafe { call(&value) }, 123_456);
}
#[test]
fn flattens_a_nested_enum_into_collision_free_zero_copy_tags() {
let module = "app://nested_enum.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs Inner: enum { var W var Q }
pub acs Outer: enum { var X Inner var Y }
pub acs make_w: fn() -> Outer { return Outer.X(Inner.W) }
pub acs make_q: fn() -> Outer { return Outer.X(Inner.Q) }
pub acs make_y: fn() -> Outer { return Outer.Y }
pub acs classify: fn(value: Outer) -> i32 {
return match value {
Outer.X(inner) => match inner {
Inner.W => 10
Inner.Q => 20
}
Outer.Y => 30
}
}",
)
.unwrap();
let outer = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: module.into(),
local: "Outer".into(),
})
.unwrap();
assert_eq!((outer.size, outer.align), (1, 1));
let crate::runtime::TypeMetadataKind::Enum {
tag_bits, variants, ..
} = &outer.kind
else {
panic!("outer enum metadata expected")
};
assert_eq!(*tag_bits, 8);
assert_eq!(variants[0].name, "X");
assert_eq!(variants[0].matching_tags, vec![0, 1]);
assert_eq!(variants[0].payload_offset, Some(0));
assert_eq!(variants[1].name, "Y");
assert_eq!(variants[1].matching_tags, vec![2]);
let function = |local: &str| CanonicalSymbolPath {
module: module.into(),
local: local.into(),
};
let make_w_ptr = unit.function_ptr(&function("make_w")).unwrap();
let make_q_ptr = unit.function_ptr(&function("make_q")).unwrap();
let make_y_ptr = unit.function_ptr(&function("make_y")).unwrap();
let classify_ptr = unit.function_ptr(&function("classify")).unwrap();
let make_w: unsafe extern "C" fn(*mut [u8; 1]) =
unsafe { std::mem::transmute_copy(&make_w_ptr) };
let make_q: unsafe extern "C" fn(*mut [u8; 1]) =
unsafe { std::mem::transmute_copy(&make_q_ptr) };
let make_y: unsafe extern "C" fn(*mut [u8; 1]) =
unsafe { std::mem::transmute_copy(&make_y_ptr) };
let classify: unsafe extern "C" fn(*const [u8; 1]) -> i32 =
unsafe { std::mem::transmute_copy(&classify_ptr) };
let mut w = [0xFF];
let mut q = [0xFF];
let mut y = [0xFF];
unsafe {
make_w(&mut w);
make_q(&mut q);
make_y(&mut y);
}
assert_eq!((w, q, y), ([0], [1], [2]));
assert_eq!(unsafe { classify(&w) }, 10);
assert_eq!(unsafe { classify(&q) }, 20);
assert_eq!(unsafe { classify(&y) }, 30);
}
#[test]
fn rebases_lehit_unit_enum_tags_to_flatten_multiple_nested_enums() {
let module = "app://nested_enum_collision.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs First: enum { var A var B }
pub acs Second: enum { var C var D }
pub acs Outer: enum { var FirstValue First var SecondValue Second var Empty }
pub acs make_first_a: fn() -> Outer { return Outer.FirstValue(First.A) }
pub acs make_second_c: fn() -> Outer { return Outer.SecondValue(Second.C) }
pub acs make_second_d: fn() -> Outer { return Outer.SecondValue(Second.D) }
pub acs make_empty: fn() -> Outer { return Outer.Empty }
pub acs classify: fn(value: Outer) -> i32 {
return match value {
Outer.FirstValue(first) => match first { First.A => 10 First.B => 20 }
Outer.SecondValue(second) => match second { Second.C => 30 Second.D => 40 }
Outer.Empty => 50
}
}",
)
.unwrap();
let outer = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: module.into(),
local: "Outer".into(),
})
.unwrap();
assert_eq!((outer.size, outer.align), (1, 1));
let crate::runtime::TypeMetadataKind::Enum { variants, .. } = &outer.kind else {
panic!("outer enum metadata expected")
};
assert_eq!(
variants
.iter()
.map(|variant| (variant.matching_tags.clone(), variant.payload_offset))
.collect::<Vec<_>>(),
vec![
(vec![0, 1], Some(0)),
(vec![2, 3], Some(0)),
(vec![4], None),
]
);
let second = workspace
.type_metadata()
.get(&CanonicalSymbolPath {
module: module.into(),
local: "Second".into(),
})
.unwrap();
let crate::runtime::TypeMetadataKind::Enum { variants, .. } = &second.kind else {
panic!("second enum metadata expected")
};
assert_eq!(
variants
.iter()
.map(|variant| variant.matching_tags.clone())
.collect::<Vec<_>>(),
vec![vec![2], vec![3]]
);
let function = |local: &str| CanonicalSymbolPath {
module: module.into(),
local: local.into(),
};
let make = |local: &str| {
let pointer = unit.function_ptr(&function(local)).unwrap();
unsafe { std::mem::transmute_copy::<_, unsafe extern "C" fn(*mut [u8; 1])>(&pointer) }
};
let classify_pointer = unit.function_ptr(&function("classify")).unwrap();
let classify: unsafe extern "C" fn(*const [u8; 1]) -> i32 =
unsafe { std::mem::transmute_copy(&classify_pointer) };
for (constructor, bytes, result) in [
("make_first_a", [0], 10),
("make_second_c", [2], 30),
("make_second_d", [3], 40),
("make_empty", [4], 50),
] {
let mut value = [0xFF];
unsafe { make(constructor)(&mut value) };
assert_eq!(value, bytes);
assert_eq!(unsafe { classify(&value) }, result);
}
}
#[test]
fn register_chunk_adapter_calls_direct_rust_aggregate_abi_without_marshalling() {
let module = "native://direct_aggregate.lt";
let mut library = native_library(
"pub acs NativePair: struct { pub fld value: i32 }
pub acs identity: fn(value: NativePair) -> NativePair",
);
let pair = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativePair".into(),
generics: Vec::new(),
});
let mut script = library.scripts.remove("native://types.lt").unwrap();
script.functions.insert(
"identity".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: pair.clone(),
}],
return_value_type: Some(pair),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_pair_identity",
direct_native_pair_identity as *const (),
)
}),
},
);
library.scripts.insert(module.into(), script);
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "identity".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativePair, *const NativePair) =
unsafe { std::mem::transmute_copy(&adapter) };
let input = NativePair {
value: 17,
hidden: 23,
};
let mut output = std::mem::MaybeUninit::<NativePair>::uninit();
unsafe { call(output.as_mut_ptr(), &input) };
assert_eq!(unsafe { output.assume_init() }, input);
}
#[test]
fn multiple_register_chunk_adapter_preserves_the_complete_rust_value() {
let module = "native://direct_wide.lt";
let mut script = Script {
content: "pub acs NativeWide: struct { pub fld first: i64 }
pub acs identity: fn(value: NativeWide) -> NativeWide"
.into(),
..Script::default()
};
script
.register_type::<NativeWide>(
"NativeWide",
true,
vec![RustFieldRegistration {
index: 0,
ident: "first".into(),
value_type: named_core_type("i64"),
pub_visible: true,
}],
)
.unwrap();
let wide = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeWide".into(),
generics: Vec::new(),
});
script.functions.insert(
"identity".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: wide.clone(),
}],
return_value_type: Some(wide),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_wide_identity",
direct_native_wide_identity as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "identity".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativeWide, *const NativeWide) =
unsafe { std::mem::transmute_copy(&adapter) };
let input = NativeWide {
first: 0x1122_3344_5566_7788,
hidden: -0x1020_3040_5060_708,
};
let mut output = std::mem::MaybeUninit::<NativeWide>::uninit();
unsafe { call(output.as_mut_ptr(), &input) };
assert_eq!(unsafe { output.assume_init() }, input);
}
#[test]
fn register_chunk_adapter_supports_multiple_aggregate_arguments() {
let module = "native://direct_wide_add.lt";
let mut script = Script {
content: "pub acs NativeWide: struct { pub fld first: i64 }
pub acs add: fn(left: NativeWide, right: NativeWide) -> NativeWide"
.into(),
..Script::default()
};
script
.register_type::<NativeWide>(
"NativeWide",
true,
vec![RustFieldRegistration {
index: 0,
ident: "first".into(),
value_type: named_core_type("i64"),
pub_visible: true,
}],
)
.unwrap();
let wide = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeWide".into(),
generics: Vec::new(),
});
script.functions.insert(
"add".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![
FunctionArgument {
ident: "left".into(),
value_type: wide.clone(),
},
FunctionArgument {
ident: "right".into(),
value_type: wide.clone(),
},
],
return_value_type: Some(wide),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_wide_add",
direct_native_wide_add as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "add".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativeWide, *const NativeWide, *const NativeWide) =
unsafe { std::mem::transmute_copy(&adapter) };
let left = NativeWide {
first: 11,
hidden: 101,
};
let right = NativeWide {
first: 23,
hidden: 307,
};
let mut output = std::mem::MaybeUninit::<NativeWide>::uninit();
unsafe { call(output.as_mut_ptr(), &left, &right) };
assert_eq!(
unsafe { output.assume_init() },
NativeWide {
first: 34,
hidden: 408,
}
);
}
#[test]
fn register_chunk_adapter_supports_mixed_aggregate_and_scalar_arguments() {
let module = "native://direct_wide_scale.lt";
let mut script = Script {
content: "pub acs NativeWide: struct { pub fld first: i64 }
pub acs scale: fn(value: NativeWide, factor: i64) -> NativeWide"
.into(),
..Script::default()
};
script
.register_type::<NativeWide>(
"NativeWide",
true,
vec![RustFieldRegistration {
index: 0,
ident: "first".into(),
value_type: named_core_type("i64"),
pub_visible: true,
}],
)
.unwrap();
let wide = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeWide".into(),
generics: Vec::new(),
});
script.functions.insert(
"scale".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![
FunctionArgument {
ident: "value".into(),
value_type: wide.clone(),
},
FunctionArgument {
ident: "factor".into(),
value_type: named_core_type("i64"),
},
],
return_value_type: Some(wide),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_wide_scale",
direct_native_wide_scale as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "scale".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativeWide, *const NativeWide, i64) =
unsafe { std::mem::transmute_copy(&adapter) };
let input = NativeWide {
first: 7,
hidden: -13,
};
let mut output = std::mem::MaybeUninit::<NativeWide>::uninit();
unsafe { call(output.as_mut_ptr(), &input, 5) };
assert_eq!(
unsafe { output.assume_init() },
NativeWide {
first: 35,
hidden: -65,
}
);
}
#[test]
fn register_chunk_adapter_returns_a_direct_scalar_without_an_output_pointer() {
let module = "native://direct_wide_sum.lt";
let mut script = Script {
content: "pub acs NativeWide: struct { pub fld first: i64 }
pub acs sum: fn(value: NativeWide) -> i64"
.into(),
..Script::default()
};
script
.register_type::<NativeWide>(
"NativeWide",
true,
vec![RustFieldRegistration {
index: 0,
ident: "first".into(),
value_type: named_core_type("i64"),
pub_visible: true,
}],
)
.unwrap();
let wide = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeWide".into(),
generics: Vec::new(),
});
script.functions.insert(
"sum".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: wide,
}],
return_value_type: Some(named_core_type("i64")),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_wide_sum",
direct_native_wide_sum as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "sum".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*const NativeWide) -> i64 =
unsafe { std::mem::transmute_copy(&adapter) };
let input = NativeWide {
first: 19,
hidden: 23,
};
assert_eq!(unsafe { call(&input) }, 42);
}
#[test]
fn register_chunk_adapter_passes_a_borrowed_aggregate_without_copying_it() {
let module = "native://direct_wide_borrow.lt";
let mut script = Script {
content: "pub acs NativeWide: struct { pub fld first: i64 }
pub acs from_borrow: fn(value: &NativeWide) -> NativeWide"
.into(),
..Script::default()
};
script
.register_type::<NativeWide>(
"NativeWide",
true,
vec![RustFieldRegistration {
index: 0,
ident: "first".into(),
value_type: named_core_type("i64"),
pub_visible: true,
}],
)
.unwrap();
let wide = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeWide".into(),
generics: Vec::new(),
});
script.functions.insert(
"from_borrow".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: RustTypeRef::Reference {
lifetime: None,
mutable: false,
target: Box::new(wide.clone()),
},
}],
return_value_type: Some(wide),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_wide_from_borrow",
direct_native_wide_from_borrow as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "from_borrow".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativeWide, *const NativeWide) =
unsafe { std::mem::transmute_copy(&adapter) };
let input = NativeWide {
first: 31,
hidden: 47,
};
let mut output = std::mem::MaybeUninit::<NativeWide>::uninit();
unsafe { call(output.as_mut_ptr(), &input) };
assert_eq!(
unsafe { output.assume_init() },
NativeWide {
first: 32,
hidden: 49,
}
);
assert_eq!(
input,
NativeWide {
first: 31,
hidden: 47,
}
);
}
#[test]
fn direct_native_function_mutates_a_borrowed_aggregate_in_place() {
let module = "native://direct_wide_mut.lt";
let mut script = Script {
content: "pub acs NativeWide: struct { pub fld first: i64 }
pub acs mutate: fn(value: &mut NativeWide, delta: i64) -> i64"
.into(),
..Script::default()
};
script
.register_type::<NativeWide>(
"NativeWide",
true,
vec![RustFieldRegistration {
index: 0,
ident: "first".into(),
value_type: named_core_type("i64"),
pub_visible: true,
}],
)
.unwrap();
let wide = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeWide".into(),
generics: Vec::new(),
});
script.functions.insert(
"mutate".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![
FunctionArgument {
ident: "value".into(),
value_type: RustTypeRef::Reference {
lifetime: None,
mutable: true,
target: Box::new(wide),
},
},
FunctionArgument {
ident: "delta".into(),
value_type: named_core_type("i64"),
},
],
return_value_type: Some(named_core_type("i64")),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_wide_mutate",
direct_native_wide_mutate as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "mutate".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativeWide, i64) -> i64 =
unsafe { std::mem::transmute_copy(&pointer) };
let mut value = NativeWide {
first: 20,
hidden: 30,
};
assert_eq!(unsafe { call(&mut value, 7) }, 50);
assert_eq!(
value,
NativeWide {
first: 27,
hidden: 23,
}
);
}
#[test]
fn register_chunk_adapter_supports_mixed_float_and_integer_classes() {
let module = "native://direct_mixed.lt";
let mut script = Script {
content: "pub acs NativeMixed: struct { pub fld floating: f64 }
pub acs identity: fn(value: NativeMixed) -> NativeMixed"
.into(),
..Script::default()
};
script
.register_type::<NativeMixed>(
"NativeMixed",
true,
vec![RustFieldRegistration {
index: 0,
ident: "floating".into(),
value_type: named_core_type("f64"),
pub_visible: true,
}],
)
.unwrap();
let mixed = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativeMixed".into(),
generics: Vec::new(),
});
script.functions.insert(
"identity".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: mixed.clone(),
}],
return_value_type: Some(mixed),
body: RustFunctionBody::Native(unsafe {
NativeFunction::new(
"direct_native_mixed_identity",
direct_native_mixed_identity as *const (),
)
}),
},
);
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "identity".into(),
};
let adapter = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativeMixed, *const NativeMixed) =
unsafe { std::mem::transmute_copy(&adapter) };
let input = NativeMixed {
floating: 1234.5,
hidden: -0x1234_5678_7654_321,
};
let mut output = std::mem::MaybeUninit::<NativeMixed>::uninit();
unsafe { call(output.as_mut_ptr(), &input) };
assert_eq!(unsafe { output.assume_init() }, input);
}
#[test]
fn function_signatures_request_concrete_generic_metadata_automatically() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace
.compile_scripts_unit(BTreeMap::from([(
"app://generic-signature.lt".into(),
"pub acs identity: fn(value: Option<NonZeroU32>) -> Option<NonZeroU32> {
return value
}"
.into(),
)]))
.unwrap();
let non_zero_u32 = SemanticType::Named(SemanticNamedType {
path: CanonicalSymbolPath {
module: core_lib::NON_ZERO_MODULE_FILE_PATH.into(),
local: "NonZero".into(),
},
generic_arguments: vec![SemanticGenericArgument::Type(SemanticType::Named(
SemanticNamedType {
path: CanonicalSymbolPath {
module: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local: "u32".into(),
},
generic_arguments: Vec::new(),
},
))],
});
let option = SemanticNamedType {
path: CanonicalSymbolPath {
module: core_lib::OPTION_MODULE_FILE_PATH.into(),
local: "Option".into(),
},
generic_arguments: vec![SemanticGenericArgument::Type(non_zero_u32)],
};
let metadata = workspace.type_metadata().get_named(&option).unwrap();
assert_eq!((metadata.size, metadata.align), (4, 4));
assert!(matches!(
&metadata.kind,
crate::runtime::TypeMetadataKind::Enum { variants, .. }
if variants.iter().any(|variant| variant.fallback && variant.name == "Some")
));
}
fn native_option_identity(value: Option<NonZeroU32>) -> Option<NonZeroU32> {
value
}
fn native_option_increment(value: Option<NonZeroU32>) -> Option<NonZeroU32> {
value.and_then(|value| NonZeroU32::new(value.get() + 1))
}
fn native_read_i32(value: &i32) -> i32 {
*value
}
fn native_read_i32_mut(value: &mut i32) -> i32 {
*value
}
fn native_pair_add(pair: &mut NativePair, amount: i32) -> i32 {
pair.value += amount;
pair.value
}
fn native_pair_read_add(pair: &NativePair, amount: i32) -> i32 {
pair.value + amount
}
#[test]
fn validates_typed_native_method_receivers_transactionally() {
let library = |shared_descriptor: bool| {
let module = "native://method.lt";
let mut library = native_library(
"pub acs NativePair: struct {
pub fld value: i32
pub acs add: fn(&mut self, amount: i32) -> i32
}",
);
let script = library.scripts.remove("native://types.lt").unwrap();
library.scripts.insert(module.into(), script);
let pair_type = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativePair".into(),
generics: Vec::new(),
});
let native = if shared_descriptor {
unsafe {
NativeFunction::from_rust_method_ref("NativePair.add", native_pair_read_add)
}
} else {
unsafe { NativeFunction::from_rust_method_mut("NativePair.add", native_pair_add) }
};
library
.scripts
.get_mut(module)
.unwrap()
.types
.get_mut("NativePair")
.unwrap()
.native_method("add", native)
.public()
.exported()
.mutable_receiver(pair_type)
.argument("amount", named_core_type("i32"))
.returns(named_core_type("i32"))
.finish();
library
};
let mut accepted = ScriptWorkspace::with_core().unwrap();
accepted.add_rust_lib(&library(false)).unwrap();
let mut rejected = ScriptWorkspace::with_core().unwrap();
assert!(matches!(
rejected.add_rust_lib(&library(true)),
Err(WorkspaceError::RustFunctions(errors))
if errors.iter().any(|error| matches!(
error,
RustFunctionRegistrationError::NativeArgumentLayoutMismatch {
function,
index: 0,
} if function == "NativePair.add"
))
));
assert!(rejected.graph().module("native://method.lt").is_none());
}
#[test]
fn executes_a_mutable_native_method_through_a_jit_wrapper() {
let module = "native://method-execution.lt";
let mut library = native_library(
"pub acs NativePair: struct {
pub fld value: i32
pub acs add: fn(&mut self, amount: i32) -> i32
}
pub acs through_jit: fn(pair: &mut NativePair, amount: i32) -> i32 {
return pair.add(amount)
}",
);
let script = library.scripts.remove("native://types.lt").unwrap();
library.scripts.insert(module.into(), script);
let pair_type = RustTypeRef::Named(AccessPath {
file_path: module.into(),
local_access: "NativePair".into(),
generics: Vec::new(),
});
let native =
unsafe { NativeFunction::from_rust_method_mut("NativePair.add", native_pair_add) };
library
.scripts
.get_mut(module)
.unwrap()
.types
.get_mut("NativePair")
.unwrap()
.native_method("add", native)
.public()
.mutable_receiver(pair_type)
.argument("amount", named_core_type("i32"))
.returns(named_core_type("i32"))
.finish();
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "through_jit".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut NativePair, i32) -> i32 =
unsafe { std::mem::transmute_copy(&pointer) };
let mut pair = NativePair {
value: 10,
hidden: 77,
};
let result = unsafe { call(&mut pair, 32) };
assert_eq!(result, 42);
assert_eq!(pair.value, 42);
assert_eq!(pair.hidden, 77);
}
#[test]
fn validates_typed_native_borrow_modes_transactionally() {
let library = |mutable_descriptor: bool| {
let i32_type = named_core_type("i32");
let native = if mutable_descriptor {
unsafe {
NativeFunction::from_rust_fn1_mut("native_read_i32_mut", native_read_i32_mut)
}
} else {
unsafe { NativeFunction::from_rust_fn1_ref("native_read_i32", native_read_i32) }
};
RustLib {
scripts: HashMap::from([(
"native://borrowed.lt".into(),
Script {
content: "pub acs read: fn(value: &i32) -> i32".into(),
functions: HashMap::from([(
"read".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: RustTypeRef::Reference {
lifetime: None,
mutable: false,
target: Box::new(i32_type.clone()),
},
}],
return_value_type: Some(i32_type),
body: RustFunctionBody::Native(native),
},
)]),
..Script::default()
},
)]),
}
};
let mut accepted = ScriptWorkspace::with_core().unwrap();
accepted.add_rust_lib(&library(false)).unwrap();
let mut rejected = ScriptWorkspace::with_core().unwrap();
assert!(matches!(
rejected.add_rust_lib(&library(true)),
Err(WorkspaceError::RustFunctions(errors))
if errors.iter().any(|error| matches!(
error,
RustFunctionRegistrationError::NativeArgumentLayoutMismatch {
function,
index: 0,
} if function == "read"
))
));
assert!(rejected.graph().module("native://borrowed.lt").is_none());
}
#[test]
fn validates_typed_native_generic_layouts_transactionally() {
let u32_path = AccessPath {
file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local_access: "u32".into(),
generics: Vec::new(),
};
let non_zero = AccessPath {
file_path: core_lib::NON_ZERO_MODULE_FILE_PATH.into(),
local_access: "NonZero".into(),
generics: vec![u32_path],
};
let option = RustTypeRef::Named(AccessPath {
file_path: core_lib::OPTION_MODULE_FILE_PATH.into(),
local_access: "Option".into(),
generics: vec![non_zero],
});
let library = |wrong_layout: bool| {
let signature = if wrong_layout {
NativeFunctionSignature::new()
.argument::<u64>()
.returns::<Option<NonZeroU32>>()
} else {
NativeFunctionSignature::new()
.argument::<Option<NonZeroU32>>()
.returns::<Option<NonZeroU32>>()
};
RustLib {
scripts: HashMap::from([(
"native://generic-option.lt".into(),
Script {
content:
"pub acs identity: fn(value: Option<NonZeroU32>) -> Option<NonZeroU32>"
.into(),
functions: HashMap::from([(
"identity".into(),
RustFunction {
pub_visible: true,
exported: true,
self_argument: None,
arguments: vec![FunctionArgument {
ident: "value".into(),
value_type: option.clone(),
}],
return_value_type: Some(option.clone()),
body: RustFunctionBody::Native(unsafe {
if wrong_layout {
NativeFunction::new_typed(
"native_option_identity",
native_option_identity as *const (),
signature,
)
} else {
NativeFunction::from_rust_fn1(
"native_option_identity",
native_option_identity,
)
}
}),
},
)]),
..Script::default()
},
)]),
}
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace.add_rust_lib(&library(false)).unwrap();
let mut rejected = ScriptWorkspace::with_core().unwrap();
assert!(matches!(
rejected.add_rust_lib(&library(true)),
Err(WorkspaceError::RustFunctions(errors))
if errors.iter().any(|error| matches!(
error,
RustFunctionRegistrationError::NativeArgumentLayoutMismatch {
function,
index: 0,
} if function == "identity"
))
));
assert!(
rejected
.graph()
.module("native://generic-option.lt")
.is_none()
);
}
#[test]
fn executes_native_option_non_zero_through_a_jit_wrapper_without_marshalling() {
let module = "native://option-execution.lt";
let u32_path = AccessPath {
file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local_access: "u32".into(),
generics: Vec::new(),
};
let non_zero = AccessPath {
file_path: core_lib::NON_ZERO_MODULE_FILE_PATH.into(),
local_access: "NonZero".into(),
generics: vec![u32_path],
};
let option = RustTypeRef::Named(AccessPath {
file_path: core_lib::OPTION_MODULE_FILE_PATH.into(),
local_access: "Option".into(),
generics: vec![non_zero],
});
let mut script = Script {
content: "pub acs increment: fn(value: Option<NonZeroU32>) -> Option<NonZeroU32>
pub acs through_jit: fn(value: Option<NonZeroU32>) -> Option<NonZeroU32> {
return increment(value)
}"
.into(),
..Script::default()
};
let native = unsafe {
NativeFunction::from_rust_fn1("native_option_increment", native_option_increment)
};
script
.native_function("increment", native)
.public()
.argument("value", option.clone())
.returns(option)
.finish();
let library = RustLib {
scripts: HashMap::from([(module.into(), script)]),
};
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace.compile_rust_libs_unit(&[&library]).unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "through_jit".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut Option<NonZeroU32>, *const Option<NonZeroU32>) =
unsafe { std::mem::transmute_copy(&pointer) };
for (input, expected) in [(None, None), (NonZeroU32::new(42), NonZeroU32::new(43))] {
let mut output = std::mem::MaybeUninit::<Option<NonZeroU32>>::uninit();
unsafe { call(output.as_mut_ptr(), &input) };
assert_eq!(unsafe { output.assume_init() }, expected);
}
}
#[test]
fn allocates_a_rust_compatible_box_in_jit_code() {
let module = "app://box-new.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs make: fn(value: u32) -> Box<u32> {
return Box.new(value)
}",
)
.unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "make".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut Box<u32>, u32) =
unsafe { std::mem::transmute_copy(&pointer) };
let mut output = std::mem::MaybeUninit::<Box<u32>>::uninit();
unsafe { call(output.as_mut_ptr(), 42) };
let boxed = unsafe { output.assume_init() };
assert_eq!(*boxed, 42);
}
#[test]
fn dereferences_a_rust_box_in_jit_code_without_copying_its_payload() {
let module = "app://box-deref.lt";
let mut workspace = ScriptWorkspace::with_core().unwrap();
let unit = workspace
.compile_script(
module,
"pub acs read: fn(value: Box<u32>) -> u32 {
return *value
}
pub acs read_mut: fn(mut value: Box<u32>) -> u32 {
*value = 43
return *value
}",
)
.unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "read".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*const Box<u32>) -> u32 =
unsafe { std::mem::transmute_copy(&pointer) };
let boxed = std::mem::ManuallyDrop::new(Box::new(42_u32));
assert_eq!(unsafe { call(&*boxed) }, 42);
let mutable_path = CanonicalSymbolPath {
module: module.into(),
local: "read_mut".into(),
};
let mutable_pointer = unit.function_ptr(&mutable_path).unwrap();
let mutable_call: unsafe extern "C" fn(*const Box<u32>) -> u32 =
unsafe { std::mem::transmute_copy(&mutable_pointer) };
let boxed = std::mem::ManuallyDrop::new(Box::new(42_u32));
assert_eq!(unsafe { mutable_call(&*boxed) }, 43);
}
#[test]
fn constructs_non_zero_through_the_core_intrinsic() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let module = "app://non-zero-new.lt";
let unit = workspace
.compile_script(
module,
"pub acs make: fn(value: u32) -> Option<NonZeroU32> {
return NonZeroU32.new(value)
}",
)
.unwrap();
let path = CanonicalSymbolPath {
module: module.into(),
local: "make".into(),
};
let pointer = unit.function_ptr(&path).unwrap();
let call: unsafe extern "C" fn(*mut Option<NonZeroU32>, u32) =
unsafe { std::mem::transmute_copy(&pointer) };
for (input, expected) in [(0, None), (42, NonZeroU32::new(42))] {
let mut output = std::mem::MaybeUninit::<Option<NonZeroU32>>::uninit();
unsafe { call(output.as_mut_ptr(), input) };
assert_eq!(unsafe { output.assume_init() }, expected);
}
}
#[test]
fn constructs_a_concrete_generic_option_from_expected_type() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace
.compile_script(
"app://generic-option-constructor.lt",
"pub acs some: fn(value: u32) -> Option<u32> {
return Option.Some(value)
}
pub acs none: fn() -> Option<u32> {
return Option.None()
}",
)
.unwrap();
}
#[test]
fn rejects_external_non_zero_structure_literals() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let result = workspace.compile_script(
"app://invalid-non-zero.lt",
"pub acs invalid: fn() -> NonZeroU32 {
return NonZeroU32 { value: 0 }
}",
);
match result {
Err(WorkspaceError::Body(errors))
if errors.iter().any(|error| {
matches!(
error,
BodyAnalysisError::PrivateField { field, .. } if field == "value"
)
}) => {}
Err(error) => panic!("unexpected non-zero privacy error: {error:?}"),
Ok(_) => panic!("private NonZero representation was exposed"),
}
assert!(
workspace
.graph()
.module("app://invalid-non-zero.lt")
.is_none()
);
}
#[test]
fn validates_exact_rust_function_contracts() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace
.add_rust_lib(&function_library(named_core_type("i32")))
.unwrap();
assert!(workspace.graph().module("native://functions.lt").is_some());
}
#[test]
fn rejects_rust_function_signature_mismatch_transactionally() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let result = workspace.add_rust_lib(&function_library(named_core_type("bool")));
assert!(matches!(
result,
Err(WorkspaceError::RustFunctions(errors))
if errors.iter().any(|error| matches!(
error,
RustFunctionRegistrationError::ReturnTypeMismatch { function }
if function == "add"
))
));
assert!(workspace.graph().module("native://functions.lt").is_none());
}
#[test]
fn structured_rust_field_types_preserve_lifetimes_and_pointer_mutability() {
let workspace = ScriptWorkspace::with_core().unwrap();
let named = RustTypeRef::Named(AccessPath {
file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
local_access: "i32".into(),
generics: Vec::new(),
});
let reference = RustTypeRef::Reference {
lifetime: Some("a".into()),
mutable: true,
target: Box::new(named.clone()),
};
let pointer = RustTypeRef::Pointer {
mutable: true,
target: Box::new(named),
};
assert!(matches!(
registered_field_type(workspace.graph(), &reference).unwrap(),
SemanticType::Reference {
lifetime: Some(crate::semantic::SemanticLifetime::Named(name)),
mutable: true,
..
} if name == "a"
));
assert!(matches!(
registered_field_type(workspace.graph(), &pointer).unwrap(),
SemanticType::Pointer { mutable: true, .. }
));
}
#[test]
fn installs_only_contract_fields_exported_by_native_metadata() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let library = native_library("pub acs NativePair: struct { pub fld value: i32 }");
workspace.add_rust_lib(&library).unwrap();
let path = CanonicalSymbolPath {
module: "native://types.lt".into(),
local: "NativePair".into(),
};
assert!(workspace.native_type(&path).is_some());
}
#[test]
fn rejects_unregistered_fields_in_a_native_type_contract_transactionally() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let library =
native_library("pub acs NativePair: struct { pub fld value: i32 pub fld hidden: i32 }");
assert!(matches!(
workspace.add_rust_lib(&library),
Err(WorkspaceError::RustTypes(errors))
if errors.iter().any(|error| matches!(
error,
RustTypeRegistrationError::UnregisteredContractField { field, .. }
if field == "hidden"
))
));
assert!(workspace.graph().module("native://types.lt").is_none());
}
#[test]
fn core_prelude_exports_copy_and_drop() {
let workspace = ScriptWorkspace::with_core().unwrap();
let copy = workspace
.graph()
.resolve(core_lib::PRELUDE_MODULE_FILE_PATH, "Copy")
.unwrap();
assert_eq!(copy.module_path, core_lib::CLONE_MODULE_FILE_PATH);
assert_eq!(copy.local_path, "Copy");
let clone = workspace
.graph()
.resolve(core_lib::PRELUDE_MODULE_FILE_PATH, "Clone")
.unwrap();
assert_eq!(clone.module_path, core_lib::CLONE_MODULE_FILE_PATH);
assert_eq!(clone.local_path, "Clone");
let resolved = workspace
.graph()
.resolve(core_lib::PRELUDE_MODULE_FILE_PATH, "Drop")
.unwrap();
assert_eq!(resolved.module_path, core_lib::DROP_MODULE_FILE_PATH);
assert_eq!(resolved.local_path, "Drop");
}
#[test]
fn rejects_cross_mode_script_dependency_linking() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let dependency = workspace
.compile_leased_scripts_unit(
BTreeMap::from([(
"app://direct-dependency.lt".into(),
"pub acs answer: fn() -> i32 { return 42 }".into(),
)]),
Vec::new(),
)
.unwrap();
workspace.execution_mode = ExecutionMode::Checked;
let error = match workspace.compile_leased_scripts_unit(
BTreeMap::from([(
"app://checked-caller.lt".into(),
"acs dependency: \"app://direct-dependency.lt\"
pub acs call: fn() -> i32 { return dependency.answer() }"
.into(),
)]),
vec![dependency],
) {
Ok(_) => panic!("cross-mode linking must be rejected"),
Err(error) => error,
};
assert!(
matches!(error, WorkspaceError::Jit(JitError::Module(message))
if message.contains("cannot link Direct function")
&& message.contains("Checked compilation unit"))
);
}
#[test]
fn compiles_an_internal_call_returning_a_lehit_aggregate() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
workspace
.compile_script(
"app://aggregate_call.lt",
"pub acs Item: struct { pub fld value: i32 } pub acs Pair: struct { pub fld first: Item pub fld second: Item } pub acs identity: fn(value: Pair) -> Pair { return value } pub acs read: fn(value: Pair) -> i32 { let returned: Pair = identity(value) return returned.first.value }",
)
.unwrap();
}
#[test]
fn compiles_source_with_a_small_public_workspace_api() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let return_type = workspace
.resolve_type(core_lib::PRELUDE_MODULE_FILE_PATH, "i32")
.unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(return_type),
};
let function = workspace
.compile_body("app://answer.lt", "return 20 + 22", signature)
.unwrap();
let callable: unsafe extern "C" fn() -> i32 =
unsafe { std::mem::transmute(function.as_ptr()) };
assert_eq!(unsafe { callable() }, 42);
}
#[test]
fn failed_compilation_is_not_committed() {
let mut workspace = ScriptWorkspace::with_core().unwrap();
let return_type = workspace
.resolve_type(core_lib::PRELUDE_MODULE_FILE_PATH, "i32")
.unwrap();
let signature = SemanticFunctionType {
receiver: None,
arguments: Vec::new(),
return_type: Box::new(return_type),
};
assert!(
workspace
.compile_body("app://broken.lt", "return false", signature)
.is_err()
);
assert!(workspace.graph().module("app://broken.lt").is_none());
assert!(!workspace.files().contains_key("app://broken.lt"));
}
}