diff --git a/.gitignore b/.gitignore index 0df76f45..5b7a4172 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,8 @@ Examples/**/build Examples/**/build-* Examples/**/bin Examples/**/obj +Examples/**/target +Cargo.lock # Visual Studio Code debug diff --git a/Build/Dockerfile b/Build/Dockerfile index b2868d0b..0707714e 100644 --- a/Build/Dockerfile +++ b/Build/Dockerfile @@ -29,13 +29,18 @@ RUN dnf -y module enable python39 && \ # RUN dnf -y install libicu libicu-devel # Free Pascal 3.0.4 -RUN (cd /opt && curl -O -L 'http://downloads.sourceforge.net/project/freepascal/Linux/3.0.4/fpc-3.0.4-1.x86_64.rpm' \ +RUN (cd /opt && curl -f -O -L --retry 5 --retry-delay 5 -C - 'https://downloads.freepascal.org/fpc/dist/3.0.4/x86_64-linux/fpc-3.0.4-1.x86_64.rpm' \ && rpm -i fpc-3.0.4-1.x86_64.rpm) # Go RUN (cd /opt && curl -O -L https://golang.org/dl/go1.17.2.linux-amd64.tar.gz && tar zxvf go1.17.2.linux-amd64.tar.gz) ENV PATH="${PATH}:/opt/go/bin" +# Rust +ENV RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo +RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --no-modify-path +ENV PATH="${PATH}:/opt/cargo/bin" + # Java & Mono RUN dnf -y install java-11-openjdk-devel RUN rpm --import https://download.mono-project.com/repo/xamarin.gpg \ diff --git a/Build/build.bat b/Build/build.bat index 91fce019..a102db3a 100644 --- a/Build/build.bat +++ b/Build/build.bat @@ -3,7 +3,7 @@ set startingDir="%CD%" set basepath="%~dp0" cd %basepath%\..\Source -set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go +set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingrust.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go set GOOS=windows set GOARCH=amd64 diff --git a/Build/build.sh b/Build/build.sh index 6a9b3065..9510e7fd 100755 --- a/Build/build.sh +++ b/Build/build.sh @@ -6,7 +6,7 @@ startingpath="$(pwd)" basepath="$(cd "$(dirname "$0")" && pwd)" cd "$basepath/../Source" -Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go" +Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingrust.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go" echo "Build act.win64.exe" export GOARCH="amd64" diff --git a/Documentation/Rust.md b/Documentation/Rust.md new file mode 100644 index 00000000..26bd67d0 --- /dev/null +++ b/Documentation/Rust.md @@ -0,0 +1,123 @@ +# Rust bindings + +ACT generates a Rust crate that loads a component at run time (`dlopen`/`LoadLibrary`), like the other dynamic bindings. Rust is a binding language only; ACT does not generate implementation stubs in Rust. + +## Generating + +Add a binding to the component description: + +```xml + + + +``` + +ACT writes `Bindings/Rust/Cargo.toml` and `Bindings/Rust/src/lib.rs`. The crate has no dependencies besides other generated crates of imported components. Add it to your project as a path dependency: + +```toml +[dependencies] +libprimes = { path = "LibPrimes_component/Bindings/Rust" } +``` + +Unless ACT is called with `-suppressexamples`, ACT also writes a small application to `Examples/Rust`. + +## Requirements + +Rust 1.65 or newer. Older compilers down to 1.57 build the crates but warn about nested `unsafe` blocks. + +## Using a component + +```rust +use libprimes::Wrapper; + +fn main() -> libprimes::Result<()> { + let wrapper = Wrapper::new("path/to/libprimes")?; // the platform's file extension is not added + let (major, minor, micro) = wrapper.get_version()?; + println!("version {major}.{minor}.{micro}"); + let calculator = wrapper.create_factorization_calculator()?; + calculator.set_value(735)?; + calculator.calculate()?; + for factor in calculator.get_prime_factors()? { + let (prime, multiplicity) = (factor.prime, factor.multiplicity); + println!("{prime}^{multiplicity}"); + } + Ok(()) +} +``` + +* Function names are snake case (`GetPrimeFactors` becomes `get_prime_factors`). Names that are keywords in Rust get a trailing underscore. +* `return` and `out` parameters are returned: a single value as is, several as a tuple. Every call returns `Result`. +* Instances are released when they are dropped. They keep the library loaded for as long as any of them is alive. +* Strings are `&str` in and `String` out; arrays are slices in and `Vec` out. + +### Errors + +`Error` has the public fields `code` and `message`. Its `Display` output reads `Error NAME (code): message`. The codes are available as constants in the `error_code` module. + +### Types + +| IDL | Rust | +| --- | --- | +| `uint8`...`int64`, `single`, `double`, `bool` | `u8`...`i64`, `f32`, `f64`, `bool` | +| `pointer` | `*mut c_void` | +| `enum` | a Rust `enum` with explicit values | +| `struct` | `#[repr(C)]` struct, or `#[repr(C, packed)]` where C would add padding | +| `rows`/`columns` members | `[T; rows]` or `[[T; rows]; columns]`, indexed `[column][row]` like the other bindings | + +Structs of the C ABI are packed without padding. A packed struct cannot be borrowed field by field: copy the field into a local first, as in the example above. + +Enumerations written by the library are checked before they reach your code. A value that the binding does not know yields an error with the code for an invalid cast. + +## Classes + +Classes are structs that dereference to their parent class, so the methods of the parent are available on the child. Every class implements `Class`, which carries the type identifiers used for run-time type checks: + +* `instance.is::()` tells whether an instance is, or derives from, a class. +* `instance.cast::()` returns a new reference as `Option`. +* `instance.downcast::()` consumes the instance and returns `Result`. +* `animal.into_kind()` returns an enum with a variant per derived class, to be used in a `match`. + +These need a `classtypeidmethod` in the IDL. + +## Threads + +Instances are `Send`. They are `Sync` only if the class is declared with `threadsafetyoption="strict"`; the library protects such instances for every call. For `soft` and `none`, share an instance between threads only if you serialise the calls yourself. + +## Callbacks + +A function type with a user data pointer, used by a method that takes the callback and the pointer, is offered with closures: + +```rust +let calls = Arc::new(AtomicUsize::new(0)); +let counter = calls.clone(); +writer.set_progress_callback(move |progress, _identifier| { + counter.fetch_add(1, Ordering::SeqCst); + progress > 0.5 // the value returned for an `out` or `return` parameter is written back +})?; +``` + +* Parameters of the function type become closure arguments (strings as `&str`, arrays as slices, enumerations checked, classes as borrowed references). `out` and `return` parameters become the return value of the closure, a tuple if there are several. +* The closure has to be `Send + 'static`. Several callbacks of one method share state through an `Arc>`. +* The closure is kept until the same callback is set again on the same instance, or until the wrapper is dropped. Do not capture the `Wrapper` or class instances in the closure, as that would create a reference cycle keeping the library loaded. +* The library may call the closure from any thread. Calls of one callback are serialised, so the closure must not cause the same callback to be called again while it runs. Do not replace a callback while the library may concurrently invoke the previously registered one. +* A panic in the closure aborts the process, because it cannot unwind through the library. + +The same method exists with the callbacks of the C ABI as `_raw`. It is `unsafe` and takes the function pointer and the user data. Function types that cannot be mapped (no user data pointer, arrays or structs that the callback has to fill) are only available this way, under their normal name. Callback functions have to be `unsafe extern "C" fn`, must not panic, and anything they are given has to outlive the registration. + +## Injection + +If a component imports another one, the binding of the importing component depends on the binding of the imported one. Load both and pass the imported wrapper: + +```rust +let numbers = numbers::Wrapper::new(numbers_path)?; +let wrapper = calculation::Wrapper::new(calculation_path)?; +wrapper.inject_numbers(&numbers)?; +``` + +`inject_` keeps the imported wrapper alive. The injection function of the IDL (named by `injectionmethod`, `inject_component` in the example) takes the raw symbol lookup method and is `unsafe`. + +## Platforms and status + +The binding is tested on macOS (arm64) and in the Linux image of the CI, and its Windows code path is checked with `cargo check --target x86_64-pc-windows-gnu`. Generated crates build without warnings with `cargo clippy`. + +The `enumarray` parameter type is accepted by the IDL but no binding of ACT generates it, so the Rust binding does not either. diff --git a/Examples/Calculator/Calculator.xml b/Examples/Calculator/Calculator.xml index 28f4485d..e370c72c 100644 --- a/Examples/Calculator/Calculator.xml +++ b/Examples/Calculator/Calculator.xml @@ -10,6 +10,7 @@ + diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..1bd4b391 --- /dev/null +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "calculator" +version = "1.0.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of Calculator library" diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..8cc7bb19 --- /dev/null +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,816 @@ +/*++ + +Copyright (C) 2019 Calculator developers + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of Calculator library + +Interface version: 1.0.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; +} + +/// Error returned by the Calculator library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "CalculatorError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + calculator_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + calculator_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + calculator_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + calculator_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + calculator_createvariable: unsafe extern "C" fn(f64, *mut Handle) -> i32, + calculator_createcalculator: unsafe extern "C" fn(*mut Handle) -> i32, + calculator_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + calculator_variable_getvalue: unsafe extern "C" fn(Handle, *mut f64) -> i32, + calculator_variable_setvalue: unsafe extern "C" fn(Handle, f64) -> i32, + calculator_calculator_enlistvariable: unsafe extern "C" fn(Handle, Handle) -> i32, + calculator_calculator_getenlistedvariable: unsafe extern "C" fn(Handle, u32, *mut Handle) -> i32, + calculator_calculator_clearvariables: unsafe extern "C" fn(Handle) -> i32, + calculator_calculator_multiply: unsafe extern "C" fn(Handle, *mut Handle) -> i32, + calculator_calculator_add: unsafe extern "C" fn(Handle, *mut Handle) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + calculator_getversion: mem::transmute(load_symbol("calculator_getversion")?), + calculator_getlasterror: mem::transmute(load_symbol("calculator_getlasterror")?), + calculator_releaseinstance: mem::transmute(load_symbol("calculator_releaseinstance")?), + calculator_acquireinstance: mem::transmute(load_symbol("calculator_acquireinstance")?), + calculator_createvariable: mem::transmute(load_symbol("calculator_createvariable")?), + calculator_createcalculator: mem::transmute(load_symbol("calculator_createcalculator")?), + calculator_base_classtypeid: mem::transmute(load_symbol("calculator_base_classtypeid")?), + calculator_variable_getvalue: mem::transmute(load_symbol("calculator_variable_getvalue")?), + calculator_variable_setvalue: mem::transmute(load_symbol("calculator_variable_setvalue")?), + calculator_calculator_enlistvariable: mem::transmute(load_symbol("calculator_calculator_enlistvariable")?), + calculator_calculator_getenlistedvariable: mem::transmute(load_symbol("calculator_calculator_getenlistedvariable")?), + calculator_calculator_clearvariables: mem::transmute(load_symbol("calculator_calculator_clearvariables")?), + calculator_calculator_multiply: mem::transmute(load_symbol("calculator_calculator_multiply")?), + calculator_calculator_add: mem::transmute(load_symbol("calculator_calculator_add")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.calculator_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.calculator_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the Calculator library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.calculator_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.calculator_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == Variable::TYPE_ID { + return BaseKind::Variable(Variable::from_base(self.into_base())); + } + if id == Calculator::TYPE_ID { + return BaseKind::Calculator(Calculator::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.calculator_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + Variable(Variable), + Calculator(Calculator), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0xDDEA9DC03BDC9EC4, 0xC228BBEB32E22A34, 0x5FA5D809D8A728B0]; + const TYPE_ID: u64 = 0xDDEA9DC03BDC9EC4; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.calculator_releaseinstance)(self.handle) }; + } + } +} + +/// A variable number +pub struct Variable { + parent: Base, +} + +impl std::ops::Deref for Variable { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Variable { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.calculator_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns the current value of this Variable + /// + /// # Returns + /// * `value` - The current value of this Variable + pub fn get_value(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_value: f64 = 0.0; + let __act_code = unsafe { (__act_inner.api.calculator_variable_getvalue)(__act_handle, &mut __act_out_value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_value) + } + + /// Set the numerical value of this Variable + /// + /// # Arguments + /// * `value` - The new value of this Variable + pub fn set_value(&self, value: f64) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.calculator_variable_setvalue)(__act_handle, value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +impl fmt::Debug for Variable { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Variable").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Variable {} + +impl Class for Variable { + const TYPE_IDS: &'static [u64] = &[0xC228BBEB32E22A34]; + const TYPE_ID: u64 = 0xC228BBEB32E22A34; + + fn from_base(base: Base) -> Self { + Variable { parent: base } + } +} + +/// Sums up or multiplies a list of variables +pub struct Calculator { + parent: Base, +} + +impl std::ops::Deref for Calculator { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Calculator { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.calculator_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Adds a Variable to the list of Variables this calculator works on + /// + /// # Arguments + /// * `variable` - The new variable in this calculator + pub fn enlist_variable(&self, variable: &Variable) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.calculator_calculator_enlistvariable)(__act_handle, variable.handle()) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Returns an instance of a enlisted variable + /// + /// # Arguments + /// * `index` - The index of the variable to query + /// + /// # Returns + /// * `variable` - The Index-th variable in this calculator + pub fn get_enlisted_variable(&self, index: u32) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_variable: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculator_calculator_getenlistedvariable)(__act_handle, index, &mut __act_out_variable) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(Variable::from_handle(__act_inner.clone(), __act_out_variable)) + } + + /// Clears all variables in enlisted in this calculator + pub fn clear_variables(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.calculator_calculator_clearvariables)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Multiplies all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the product of all enlisted Variables + pub fn multiply(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculator_calculator_multiply)(__act_handle, &mut __act_out_instance) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// Sums all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the sum of all enlisted Variables + #[allow(clippy::should_implement_trait)] + pub fn add(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculator_calculator_add)(__act_handle, &mut __act_out_instance) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance)) + } +} + +impl fmt::Debug for Calculator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Calculator").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Calculator {} + +impl Class for Calculator { + const TYPE_IDS: &'static [u64] = &[0x5FA5D809D8A728B0]; + const TYPE_ID: u64 = 0x5FA5D809D8A728B0; + + fn from_base(base: Base) -> Self { + Calculator { parent: base } + } +} + +/// Entry point to the Calculator library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 0; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.calculator_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.calculator_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.calculator_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.calculator_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.calculator_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Creates a new Variable instance + /// + /// # Arguments + /// * `initial_value` - Initial value of the new Variable + /// + /// # Returns + /// * `instance` - New Variable instance + pub fn create_variable(&self, initial_value: f64) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculator_createvariable)(initial_value, &mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// Creates a new Calculator instance + /// + /// # Returns + /// * `instance` - New Calculator instance + pub fn create_calculator(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculator_createcalculator)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(Calculator::from_handle(__act_inner.clone(), __act_out_instance)) + } +} diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs new file mode 100644 index 00000000..6795053e --- /dev/null +++ b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs @@ -0,0 +1,31 @@ +/*++ + +Copyright (C) 2019 Calculator developers + +All rights reserved. + +Abstract: Rust example that exercises the Rust bindings of Calculator library. + It only needs the example library of this component. + +Interface version: 1.0.0 + +*/ + +use calculator::*; +fn main() -> Result<()> { + let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?; + let (major, minor, micro) = wrapper.get_version()?; + println!("Calculator version: {}.{}.{}", major, minor, micro); + let calc = wrapper.create_calculator()?; + calc.enlist_variable(&wrapper.create_variable(2.0)?)?; + calc.enlist_variable(&wrapper.create_variable(3.0)?)?; + let sum = calc.add()?.get_value()?; + println!(" sum = {}", sum); + assert_eq!(sum, 5.0); + println!("Changing the value of the first summand"); + calc.get_enlisted_variable(0)?.set_value(10.0)?; + let new_sum = calc.add()?.get_value()?; + println!("newSum = {}", new_sum); + assert_eq!(new_sum, 13.0); + Ok(()) +} diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml b/Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml new file mode 100644 index 00000000..26d1aeb2 --- /dev/null +++ b/Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "calculator_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +calculator = { path = "../../Bindings/Rust" } + +[[bin]] +name = "calculator_example" +path = "Calculator_example.rs" diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/build.sh b/Examples/Calculator/Calculator_component/Examples/Rust/build.sh new file mode 100755 index 00000000..5fa71717 --- /dev/null +++ b/Examples/Calculator/Calculator_component/Examples/Rust/build.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -euxo pipefail + +cd "$(dirname "$0")" +source ../../../../../Build/build.inc + +echo "Build Rust example" +export CARGO_TARGET_DIR=build +cargo build + +echo "Test C++ library" +./build/debug/calculator_example $PWD/../../Implementations/Cpp/build/calculator$OSLIBEXT + +echo "Test Pascal library" +./build/debug/calculator_example $PWD/../../Implementations/Pascal/build/calculator$OSLIBEXT diff --git a/Examples/Calculator/build.sh b/Examples/Calculator/build.sh index e5f61e7e..2764b0f4 100755 --- a/Examples/Calculator/build.sh +++ b/Examples/Calculator/build.sh @@ -39,4 +39,10 @@ if command -v python3 >/dev/null 2>&1; then else echo "Skipping Python example (python3 not found)" fi + +if command -v cargo >/dev/null 2>&1; then + ./Calculator_component/Examples/Rust/build.sh +else + echo "Skipping Rust example (cargo not found)" +fi echo "Build and test are done and successful" diff --git a/Examples/Injection/Calculation.xml b/Examples/Injection/Calculation.xml index b75f88b9..df31e7a5 100644 --- a/Examples/Injection/Calculation.xml +++ b/Examples/Injection/Calculation.xml @@ -15,6 +15,7 @@ + diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..5872e8d6 --- /dev/null +++ b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "calculation" +version = "1.0.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of Calculation library" + +[dependencies] +numbers = { path = "../../../Numbers_component/Bindings/Rust" } diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..08d069e7 --- /dev/null +++ b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,798 @@ +/*++ + +Copyright (C) 2019 Calculation developers + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of Calculation library + +Interface version: 1.0.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +use std::sync::Mutex; + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; +} + +/// Error returned by the Calculation library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "CalculationError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: numbers::Error) -> Self { + Error::new(e.code, e.message) + } +} + +pub type Result = std::result::Result; + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + calculation_createcalculator: unsafe extern "C" fn(*mut Handle) -> i32, + calculation_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + calculation_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + calculation_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + calculation_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + calculation_injectcomponent: unsafe extern "C" fn(*const c_char, *mut c_void) -> i32, + calculation_getsymbollookupmethod: unsafe extern "C" fn(*mut *mut c_void) -> i32, + calculation_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + calculation_calculator_enlistvariable: unsafe extern "C" fn(Handle, Handle) -> i32, + calculation_calculator_getenlistedvariable: unsafe extern "C" fn(Handle, u32, *mut Handle) -> i32, + calculation_calculator_clearvariables: unsafe extern "C" fn(Handle) -> i32, + calculation_calculator_multiply: unsafe extern "C" fn(Handle, *mut Handle) -> i32, + calculation_calculator_add: unsafe extern "C" fn(Handle, *mut Handle) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + calculation_createcalculator: mem::transmute(load_symbol("calculation_createcalculator")?), + calculation_getversion: mem::transmute(load_symbol("calculation_getversion")?), + calculation_getlasterror: mem::transmute(load_symbol("calculation_getlasterror")?), + calculation_releaseinstance: mem::transmute(load_symbol("calculation_releaseinstance")?), + calculation_acquireinstance: mem::transmute(load_symbol("calculation_acquireinstance")?), + calculation_injectcomponent: mem::transmute(load_symbol("calculation_injectcomponent")?), + calculation_getsymbollookupmethod: mem::transmute(load_symbol("calculation_getsymbollookupmethod")?), + calculation_base_classtypeid: mem::transmute(load_symbol("calculation_base_classtypeid")?), + calculation_calculator_enlistvariable: mem::transmute(load_symbol("calculation_calculator_enlistvariable")?), + calculation_calculator_getenlistedvariable: mem::transmute(load_symbol("calculation_calculator_getenlistedvariable")?), + calculation_calculator_clearvariables: mem::transmute(load_symbol("calculation_calculator_clearvariables")?), + calculation_calculator_multiply: mem::transmute(load_symbol("calculation_calculator_multiply")?), + calculation_calculator_add: mem::transmute(load_symbol("calculation_calculator_add")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, + imported_numbers: Mutex>, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + imported_numbers: Mutex::new(None), + }) + } + + /// Wrapper of the imported component Numbers, available after it was injected. + #[allow(dead_code)] + fn imported_numbers(&self) -> Result { + let guard = self.imported_numbers.lock().unwrap_or_else(|e| e.into_inner()); + guard.clone().ok_or_else(|| { + Error::new( + error_code::COULDNOTLOADLIBRARY, + "the component Numbers has not been injected", + ) + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.calculation_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.calculation_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the Calculation library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.calculation_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.calculation_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == Calculator::TYPE_ID { + return BaseKind::Calculator(Calculator::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.calculation_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + Calculator(Calculator), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0x3BA5271BAB410E5D, 0xB23F514353D0C606]; + const TYPE_ID: u64 = 0x3BA5271BAB410E5D; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.calculation_releaseinstance)(self.handle) }; + } + } +} + +/// Sums up or multiplies a list of variables +pub struct Calculator { + parent: Base, +} + +impl std::ops::Deref for Calculator { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Calculator { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.calculation_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Adds a Variable to the list of Variables this calculator works on + /// + /// # Arguments + /// * `variable` - The new variable in this calculator + pub fn enlist_variable(&self, variable: &numbers::Variable) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.calculation_calculator_enlistvariable)(__act_handle, variable.handle()) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Returns an instance of a enlisted variable + /// + /// # Arguments + /// * `index` - The index of the variable to query + /// + /// # Returns + /// * `variable` - The Index-th variable in this calculator + pub fn get_enlisted_variable(&self, index: u32) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_variable: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculation_calculator_getenlistedvariable)(__act_handle, index, &mut __act_out_variable) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(unsafe { numbers::Variable::from_raw(&__act_inner.imported_numbers()?, __act_out_variable) }) + } + + /// Clears all variables in enlisted in this calculator + pub fn clear_variables(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.calculation_calculator_clearvariables)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Multiplies all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the product of all enlisted Variables + pub fn multiply(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculation_calculator_multiply)(__act_handle, &mut __act_out_instance) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(unsafe { numbers::Variable::from_raw(&__act_inner.imported_numbers()?, __act_out_instance) }) + } + + /// Sums all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the sum of all enlisted Variables + #[allow(clippy::should_implement_trait)] + pub fn add(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculation_calculator_add)(__act_handle, &mut __act_out_instance) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(unsafe { numbers::Variable::from_raw(&__act_inner.imported_numbers()?, __act_out_instance) }) + } +} + +impl fmt::Debug for Calculator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Calculator").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Calculator {} + +impl Class for Calculator { + const TYPE_IDS: &'static [u64] = &[0xB23F514353D0C606]; + const TYPE_ID: u64 = 0xB23F514353D0C606; + + fn from_base(base: Base) -> Self { + Calculator { parent: base } + } +} + +/// Entry point to the Calculation library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Creates a wrapper that resolves the functions of the library through the address of its symbol lookup + /// method, as returned by `get_symbol_lookup_method`. This is used to inject a component into another one. + /// The library that provides the symbol lookup method has to stay loaded for as long as the wrapper is used. + /// + /// # Safety + /// `symbol_lookup_method` must be the address of a valid symbol lookup method of a compatible library + /// (`int32 fn(const char*, void**)`), and that library must outlive the wrapper and all objects created from it. + pub unsafe fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + if symbol_lookup_method.is_null() { + return Err(Error::new(error_code::INVALIDPARAM, "the symbol lookup method is null")); + } + type SymbolLookup = unsafe extern "C" fn(*const c_char, *mut *mut c_void) -> i32; + let lookup: SymbolLookup = mem::transmute::<*mut c_void, SymbolLookup>(symbol_lookup_method); + let api = unsafe { + Api::load(|name| { + let cname = CString::new(name).map_err(|_| "symbol contains NUL".to_string())?; + let mut address: *mut c_void = ptr::null_mut(); + let code = lookup(cname.as_ptr(), &mut address); + if code != 0 || address.is_null() { + Err(format!("could not find the symbol {} (error {})", name, code)) + } else { + Ok(address) + } + }) + }?; + let wrapper = Self { inner: Inner::new(api, None) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 0; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// Creates a new Calculator instance + /// + /// # Returns + /// * `instance` - New Calculator instance + pub fn create_calculator(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculation_createcalculator)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(Calculator::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.calculation_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.calculation_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.calculation_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.calculation_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.calculation_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Injects an imported component for usage within this component + /// + /// # Arguments + /// * `name_space` - NameSpace of the injected component + /// * `symbol_address_method` - Address of the SymbolAddressMethod of the injected component + /// + /// # Safety + /// The symbol lookup method must be valid for the imported component, and its library must stay loaded for as long as this wrapper is used. Prefer the safe `inject_*` functions. + pub unsafe fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + let __act_inner = &self.inner; + let __act_c_name_space = CString::new(name_space) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; + let __act_code = unsafe { (__act_inner.api.calculation_injectcomponent)(__act_c_name_space.as_ptr(), symbol_address_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + match name_space { + "Numbers" => { + let mut __act_slot = __act_inner.imported_numbers.lock().unwrap_or_else(|e| e.into_inner()); + if __act_slot.is_some() { + return Err(Error::new(error_code::COULDNOTLOADLIBRARY, "the component Numbers has already been injected")); + } + *__act_slot = Some(unsafe { numbers::Wrapper::from_symbol_lookup_method(symbol_address_method) }?); + } + _ => return Err(Error::new(error_code::COULDNOTLOADLIBRARY, format!("unknown namespace {}", name_space))), + } + Ok(()) + } + + /// Returns the address of the SymbolLookupMethod + /// + /// # Returns + /// * `symbol_lookup_method` - Address of the SymbolAddressMethod + pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { + let __act_inner = &self.inner; + let mut __act_out_symbol_lookup_method: *mut c_void = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.calculation_getsymbollookupmethod)(&mut __act_out_symbol_lookup_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(__act_out_symbol_lookup_method) + } + + /// Injects the component Numbers. The wrapper is kept alive for as long as this wrapper is used. + pub fn inject_numbers(&self, component: &numbers::Wrapper) -> Result<()> { + let lookup = component.get_symbol_lookup_method()?; + // the lookup method comes from a live wrapper, which is stored below + unsafe { self.inject_component("Numbers", lookup)? }; + *self.inner.imported_numbers.lock().unwrap_or_else(|e| e.into_inner()) = Some(component.clone()); + Ok(()) + } +} diff --git a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs new file mode 100644 index 00000000..74c7624c --- /dev/null +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -0,0 +1,36 @@ +/*++ + +Copyright (C) 2019 Calculation developers + +All rights reserved. + +Abstract: Rust example that exercises the Rust bindings of Calculation library. + It only needs the example library of this component. + +Interface version: 1.0.0 + +*/ + +use calculation::Wrapper; +fn main() -> calculation::Result<()> { + let a: Vec = std::env::args().collect(); + let wrapper = Wrapper::new(&a[1])?; + let (ma, mi, mc) = wrapper.get_version()?; + println!("Calculation version: {}.{}.{}", ma, mi, mc); + let numbers = numbers::Wrapper::new(&a[2])?; + let (ma, mi, mc) = numbers.get_version()?; + println!("Numbers version: {}.{}.{}", ma, mi, mc); + wrapper.inject_numbers(&numbers)?; + let calc = wrapper.create_calculator()?; + calc.enlist_variable(&numbers.create_variable(10.0)?)?; + calc.enlist_variable(&numbers.create_variable(5.0)?)?; + let s = calc.add()?.get_value()?; + println!(" sum={}", s); + assert_eq!(s, 15.0); + calc.get_enlisted_variable(1)?.set_value(15.0)?; + let s = calc.add()?.get_value()?; + println!("newSum={}", s); + assert_eq!(s, 25.0); + println!("multiply={}", calc.multiply()?.get_value()?); + Ok(()) +} diff --git a/Examples/Injection/Calculation_component/Examples/Rust/Cargo.toml b/Examples/Injection/Calculation_component/Examples/Rust/Cargo.toml new file mode 100644 index 00000000..ff6e29cf --- /dev/null +++ b/Examples/Injection/Calculation_component/Examples/Rust/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "calculation_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +calculation = { path = "../../Bindings/Rust" } +numbers = { path = "../../../Numbers_component/Bindings/Rust" } + +[[bin]] +name = "calculation_example" +path = "Calculation_example.rs" diff --git a/Examples/Injection/Calculation_component/Examples/Rust/build.sh b/Examples/Injection/Calculation_component/Examples/Rust/build.sh new file mode 100755 index 00000000..d3286d01 --- /dev/null +++ b/Examples/Injection/Calculation_component/Examples/Rust/build.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -euxo pipefail + +cd "$(dirname "$0")" +source ../../../../../Build/build.inc + +echo "Build Rust example" +export CARGO_TARGET_DIR=build +cargo build + +echo "Test C++ library" +./build/debug/calculation_example $PWD/../../Implementations/Cpp/build/calculation$OSLIBEXT $PWD/../../../Numbers_component/Implementations/Cpp/build/numbers$OSLIBEXT + +echo "Test Pascal library" +./build/debug/calculation_example $PWD/../../Implementations/Pascal/build/calculation$OSLIBEXT $PWD/../../../Numbers_component/Implementations/Pascal/build/numbers$OSLIBEXT diff --git a/Examples/Injection/Numbers.xml b/Examples/Injection/Numbers.xml index bead17f0..c6a0bfcb 100644 --- a/Examples/Injection/Numbers.xml +++ b/Examples/Injection/Numbers.xml @@ -10,6 +10,7 @@ + diff --git a/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..0969bca4 --- /dev/null +++ b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "numbers" +version = "1.0.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of Numbers library" diff --git a/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..d8ae0571 --- /dev/null +++ b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,696 @@ +/*++ + +Copyright (C) 2019 Numbers developers + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of Numbers library + +Interface version: 1.0.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; +} + +/// Error returned by the Numbers library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "NumbersError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + numbers_createvariable: unsafe extern "C" fn(f64, *mut Handle) -> i32, + numbers_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + numbers_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + numbers_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + numbers_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + numbers_getsymbollookupmethod: unsafe extern "C" fn(*mut *mut c_void) -> i32, + numbers_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + numbers_variable_getvalue: unsafe extern "C" fn(Handle, *mut f64) -> i32, + numbers_variable_setvalue: unsafe extern "C" fn(Handle, f64) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + numbers_createvariable: mem::transmute(load_symbol("numbers_createvariable")?), + numbers_getversion: mem::transmute(load_symbol("numbers_getversion")?), + numbers_getlasterror: mem::transmute(load_symbol("numbers_getlasterror")?), + numbers_releaseinstance: mem::transmute(load_symbol("numbers_releaseinstance")?), + numbers_acquireinstance: mem::transmute(load_symbol("numbers_acquireinstance")?), + numbers_getsymbollookupmethod: mem::transmute(load_symbol("numbers_getsymbollookupmethod")?), + numbers_base_classtypeid: mem::transmute(load_symbol("numbers_base_classtypeid")?), + numbers_variable_getvalue: mem::transmute(load_symbol("numbers_variable_getvalue")?), + numbers_variable_setvalue: mem::transmute(load_symbol("numbers_variable_setvalue")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.numbers_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.numbers_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the Numbers library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.numbers_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.numbers_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == Variable::TYPE_ID { + return BaseKind::Variable(Variable::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.numbers_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + Variable(Variable), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0x27799F69B3FD1C9E, 0x23934EDF762423EA]; + const TYPE_ID: u64 = 0x27799F69B3FD1C9E; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.numbers_releaseinstance)(self.handle) }; + } + } +} + +/// A variable number +pub struct Variable { + parent: Base, +} + +impl std::ops::Deref for Variable { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Variable { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.numbers_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns the current value of this Variable + /// + /// # Returns + /// * `value` - The current value of this Variable + pub fn get_value(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_value: f64 = 0.0; + let __act_code = unsafe { (__act_inner.api.numbers_variable_getvalue)(__act_handle, &mut __act_out_value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_value) + } + + /// Set the numerical value of this Variable + /// + /// # Arguments + /// * `value` - The new value of this Variable + pub fn set_value(&self, value: f64) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.numbers_variable_setvalue)(__act_handle, value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +impl fmt::Debug for Variable { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Variable").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Variable {} + +impl Class for Variable { + const TYPE_IDS: &'static [u64] = &[0x23934EDF762423EA]; + const TYPE_ID: u64 = 0x23934EDF762423EA; + + fn from_base(base: Base) -> Self { + Variable { parent: base } + } +} + +/// Entry point to the Numbers library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Creates a wrapper that resolves the functions of the library through the address of its symbol lookup + /// method, as returned by `get_symbol_lookup_method`. This is used to inject a component into another one. + /// The library that provides the symbol lookup method has to stay loaded for as long as the wrapper is used. + /// + /// # Safety + /// `symbol_lookup_method` must be the address of a valid symbol lookup method of a compatible library + /// (`int32 fn(const char*, void**)`), and that library must outlive the wrapper and all objects created from it. + pub unsafe fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + if symbol_lookup_method.is_null() { + return Err(Error::new(error_code::INVALIDPARAM, "the symbol lookup method is null")); + } + type SymbolLookup = unsafe extern "C" fn(*const c_char, *mut *mut c_void) -> i32; + let lookup: SymbolLookup = mem::transmute::<*mut c_void, SymbolLookup>(symbol_lookup_method); + let api = unsafe { + Api::load(|name| { + let cname = CString::new(name).map_err(|_| "symbol contains NUL".to_string())?; + let mut address: *mut c_void = ptr::null_mut(); + let code = lookup(cname.as_ptr(), &mut address); + if code != 0 || address.is_null() { + Err(format!("could not find the symbol {} (error {})", name, code)) + } else { + Ok(address) + } + }) + }?; + let wrapper = Self { inner: Inner::new(api, None) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 0; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// Creates a new Variable instance + /// + /// # Arguments + /// * `initial_value` - Initial value of the new Variable + /// + /// # Returns + /// * `instance` - New Variable instance + pub fn create_variable(&self, initial_value: f64) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.numbers_createvariable)(initial_value, &mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.numbers_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.numbers_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.numbers_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.numbers_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.numbers_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Returns the address of the SymbolLookupMethod + /// + /// # Returns + /// * `symbol_lookup_method` - Address of the SymbolAddressMethod + pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { + let __act_inner = &self.inner; + let mut __act_out_symbol_lookup_method: *mut c_void = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.numbers_getsymbollookupmethod)(&mut __act_out_symbol_lookup_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(__act_out_symbol_lookup_method) + } +} diff --git a/Examples/Injection/build.sh b/Examples/Injection/build.sh index 97ce415c..04bc21ba 100755 --- a/Examples/Injection/build.sh +++ b/Examples/Injection/build.sh @@ -22,6 +22,7 @@ echo "Build and test bindings examples with C++ library" ./Calculation_component/Examples/Cpp/build.sh ./Calculation_component/Examples/CppDynamic/build.sh ./Calculation_component/Examples/Python/build.sh +./Calculation_component/Examples/Rust/build.sh ./Calculation_component/Examples/Pascal/build.sh ./Calculation_component/Examples/Java9/build.sh diff --git a/Examples/OptionalClass/OptionalClass.xml b/Examples/OptionalClass/OptionalClass.xml index 31614490..dbdbaf19 100644 --- a/Examples/OptionalClass/OptionalClass.xml +++ b/Examples/OptionalClass/OptionalClass.xml @@ -11,6 +11,7 @@ + diff --git a/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..dd29b739 --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "libprimes" +version = "1.2.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of Prime Numbers Library" diff --git a/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..a1addb8c --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,951 @@ +/*++ + +Copyright (C) 2019 PrimeDevelopers + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of Prime Numbers Library + +Interface version: 1.2.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +use std::sync::Mutex; + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; + pub const NORESULTAVAILABLE: i32 = 9; + pub const CALCULATIONABORTED: i32 = 10; +} + +/// Error returned by the LibPrimes library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + error_code::NORESULTAVAILABLE => "NORESULTAVAILABLE", + error_code::CALCULATIONABORTED => "CALCULATIONABORTED", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + error_code::NORESULTAVAILABLE => "no result is available", + error_code::CALCULATIONABORTED => "a calculation has been aborted", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "LibPrimesError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +#[repr(C, packed)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct PrimeFactor { + pub prime: u64, + pub multiplicity: u32, +} + +// the size has to match the packed layout of the C ABI +const _: () = assert!(std::mem::size_of::() == 12); + +/// Callback to report calculation progress and query whether it should be aborted +/// +/// The function is called by the library and has to follow the C ABI: it cannot return a `Result`, +/// so failures have to be reported through the output parameters. It must not panic, as a panic +/// that would unwind into the library aborts the process. +pub type ProgressCallback = unsafe extern "C" fn(f32, *mut bool); + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + libprimes_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + libprimes_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + libprimes_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + libprimes_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + libprimes_createfactorizationcalculator: unsafe extern "C" fn(*mut Handle) -> i32, + libprimes_createsievecalculator: unsafe extern "C" fn(*mut Handle) -> i32, + libprimes_setjournal: unsafe extern "C" fn(*const c_char) -> i32, + libprimes_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + libprimes_calculator_getvalue: unsafe extern "C" fn(Handle, *mut u64) -> i32, + libprimes_calculator_setvalue: unsafe extern "C" fn(Handle, u64) -> i32, + libprimes_calculator_calculate: unsafe extern "C" fn(Handle) -> i32, + libprimes_calculator_setprogresscallback: unsafe extern "C" fn(Handle, ProgressCallback) -> i32, + libprimes_factorizationcalculator_getprimefactors: unsafe extern "C" fn(Handle, u64, *mut u64, *mut PrimeFactor) -> i32, + libprimes_sievecalculator_getprimes: unsafe extern "C" fn(Handle, u64, *mut u64, *mut u64) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + libprimes_getversion: mem::transmute(load_symbol("libprimes_getversion")?), + libprimes_getlasterror: mem::transmute(load_symbol("libprimes_getlasterror")?), + libprimes_acquireinstance: mem::transmute(load_symbol("libprimes_acquireinstance")?), + libprimes_releaseinstance: mem::transmute(load_symbol("libprimes_releaseinstance")?), + libprimes_createfactorizationcalculator: mem::transmute(load_symbol("libprimes_createfactorizationcalculator")?), + libprimes_createsievecalculator: mem::transmute(load_symbol("libprimes_createsievecalculator")?), + libprimes_setjournal: mem::transmute(load_symbol("libprimes_setjournal")?), + libprimes_base_classtypeid: mem::transmute(load_symbol("libprimes_base_classtypeid")?), + libprimes_calculator_getvalue: mem::transmute(load_symbol("libprimes_calculator_getvalue")?), + libprimes_calculator_setvalue: mem::transmute(load_symbol("libprimes_calculator_setvalue")?), + libprimes_calculator_calculate: mem::transmute(load_symbol("libprimes_calculator_calculate")?), + libprimes_calculator_setprogresscallback: mem::transmute(load_symbol("libprimes_calculator_setprogresscallback")?), + libprimes_factorizationcalculator_getprimefactors: mem::transmute(load_symbol("libprimes_factorizationcalculator_getprimefactors")?), + libprimes_sievecalculator_getprimes: mem::transmute(load_symbol("libprimes_sievecalculator_getprimes")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, + /// closures registered as callbacks, kept alive for as long as the library is in use + #[allow(dead_code, clippy::type_complexity)] + callbacks: Mutex>>, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + callbacks: Mutex::new(std::collections::HashMap::new()), + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.libprimes_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.libprimes_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the LibPrimes library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libprimes_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.libprimes_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == Calculator::TYPE_ID { + return BaseKind::Calculator(Calculator::from_base(self.into_base())); + } + if id == FactorizationCalculator::TYPE_ID { + return BaseKind::FactorizationCalculator(FactorizationCalculator::from_base(self.into_base())); + } + if id == SieveCalculator::TYPE_ID { + return BaseKind::SieveCalculator(SieveCalculator::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.libprimes_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + Calculator(Calculator), + FactorizationCalculator(FactorizationCalculator), + SieveCalculator(SieveCalculator), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0x8769D2BB89D05D4D, 0x11F9CFC626592744, 0x6C7A0FD2ECC65118, 0x58F1CCC31D38375B]; + const TYPE_ID: u64 = 0x8769D2BB89D05D4D; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.libprimes_releaseinstance)(self.handle) }; + } + } +} + +/// Calculator class of the LibPrimes library. +pub struct Calculator { + parent: Base, +} + +impl std::ops::Deref for Calculator { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Calculator { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libprimes_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> CalculatorKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return CalculatorKind::Other(self), + }; + if id == FactorizationCalculator::TYPE_ID { + return CalculatorKind::FactorizationCalculator(FactorizationCalculator::from_base(self.into_base())); + } + if id == SieveCalculator::TYPE_ID { + return CalculatorKind::SieveCalculator(SieveCalculator::from_base(self.into_base())); + } + CalculatorKind::Other(self) + } + + /// Returns the current value of this Calculator + /// + /// # Returns + /// * `value` - The current value of this Calculator + pub fn get_value(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_value: u64 = 0; + let __act_code = unsafe { (__act_inner.api.libprimes_calculator_getvalue)(__act_handle, &mut __act_out_value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_value) + } + + /// Sets the value to be factorized + /// + /// # Arguments + /// * `value` - The value to be factorized + pub fn set_value(&self, value: u64) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libprimes_calculator_setvalue)(__act_handle, value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Performs the specific calculation of this Calculator + pub fn calculate(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libprimes_calculator_calculate)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Sets the progress callback function + /// + /// # Arguments + /// * `progress_callback` - The progress callback + /// + /// # Safety + /// The library passes progress_callback on to callbacks or uses it as is: callback functions must follow the C ABI, + /// must not panic, and pointers must stay valid for as long as the library may use them. + pub unsafe fn set_progress_callback(&self, progress_callback: ProgressCallback) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libprimes_calculator_setprogresscallback)(__act_handle, progress_callback) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +/// The most specific class of a `Calculator`, see `Calculator::into_kind`. +pub enum CalculatorKind { + FactorizationCalculator(FactorizationCalculator), + SieveCalculator(SieveCalculator), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Calculator), +} + +impl fmt::Debug for Calculator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Calculator").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Calculator {} + +impl Class for Calculator { + const TYPE_IDS: &'static [u64] = &[0x11F9CFC626592744, 0x6C7A0FD2ECC65118, 0x58F1CCC31D38375B]; + const TYPE_ID: u64 = 0x11F9CFC626592744; + + fn from_base(base: Base) -> Self { + Calculator { parent: base } + } +} + +/// FactorizationCalculator class of the LibPrimes library. +pub struct FactorizationCalculator { + parent: Calculator, +} + +impl std::ops::Deref for FactorizationCalculator { + type Target = Calculator; + + fn deref(&self) -> &Calculator { + &self.parent + } +} + +impl FactorizationCalculator { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Calculator::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libprimes_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns the prime factors of this number (without multiplicity) + /// + /// # Returns + /// * `prime_factors` - The prime factors of this number + pub fn get_prime_factors(&self) -> Result> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_needed_prime_factors: u64 = 0; + let mut __act_buffer_prime_factors: Vec = Vec::new(); + let __act_code = unsafe { (__act_inner.api.libprimes_factorizationcalculator_getprimefactors)(__act_handle, 0, &mut __act_needed_prime_factors, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_prime_factors.resize(__act_needed_prime_factors as usize, unsafe { mem::zeroed() }); + let __act_code = unsafe { (__act_inner.api.libprimes_factorizationcalculator_getprimefactors)(__act_handle, __act_buffer_prime_factors.len() as u64, &mut __act_needed_prime_factors, __act_buffer_prime_factors.as_mut_ptr()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_prime_factors.truncate(__act_needed_prime_factors as usize); + Ok(__act_buffer_prime_factors) + } +} + +impl fmt::Debug for FactorizationCalculator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("FactorizationCalculator").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for FactorizationCalculator {} + +impl Class for FactorizationCalculator { + const TYPE_IDS: &'static [u64] = &[0x6C7A0FD2ECC65118]; + const TYPE_ID: u64 = 0x6C7A0FD2ECC65118; + + fn from_base(base: Base) -> Self { + FactorizationCalculator { parent: Calculator { parent: base } } + } +} + +/// SieveCalculator class of the LibPrimes library. +pub struct SieveCalculator { + parent: Calculator, +} + +impl std::ops::Deref for SieveCalculator { + type Target = Calculator; + + fn deref(&self) -> &Calculator { + &self.parent + } +} + +impl SieveCalculator { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Calculator::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libprimes_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns all prime numbers lower or equal to the sieve's value + /// + /// # Returns + /// * `primes` - The primes lower or equal to the sieve's value + pub fn get_primes(&self) -> Result> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_needed_primes: u64 = 0; + let mut __act_buffer_primes: Vec = Vec::new(); + let __act_code = unsafe { (__act_inner.api.libprimes_sievecalculator_getprimes)(__act_handle, 0, &mut __act_needed_primes, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_primes.resize(__act_needed_primes as usize, Default::default()); + let __act_code = unsafe { (__act_inner.api.libprimes_sievecalculator_getprimes)(__act_handle, __act_buffer_primes.len() as u64, &mut __act_needed_primes, __act_buffer_primes.as_mut_ptr()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_primes.truncate(__act_needed_primes as usize); + Ok(__act_buffer_primes) + } +} + +impl fmt::Debug for SieveCalculator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SieveCalculator").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for SieveCalculator {} + +impl Class for SieveCalculator { + const TYPE_IDS: &'static [u64] = &[0x58F1CCC31D38375B]; + const TYPE_ID: u64 = 0x58F1CCC31D38375B; + + fn from_base(base: Base) -> Self { + SieveCalculator { parent: Calculator { parent: base } } + } +} + +/// Entry point to the LibPrimes library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 2; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.libprimes_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.libprimes_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.libprimes_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Acquire shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.libprimes_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.libprimes_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Creates a new FactorizationCalculator instance + /// + /// # Returns + /// * `instance` - New FactorizationCalculator instance + pub fn create_factorization_calculator(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libprimes_createfactorizationcalculator)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(FactorizationCalculator::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// Creates a new SieveCalculator instance + /// + /// # Returns + /// * `instance` - New SieveCalculator instance + pub fn create_sieve_calculator(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libprimes_createsievecalculator)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(SieveCalculator::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// Handles Library Journaling + /// + /// # Arguments + /// * `file_name` - Journal FileName + pub fn set_journal(&self, file_name: &str) -> Result<()> { + let __act_inner = &self.inner; + let __act_c_file_name = CString::new(file_name) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter file_name contains a NUL byte"))?; + let __act_code = unsafe { (__act_inner.api.libprimes_setjournal)(__act_c_file_name.as_ptr()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } +} diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/Cargo.toml b/Examples/Primes/LibPrimes_component/Examples/Rust/Cargo.toml new file mode 100644 index 00000000..87a7a5c7 --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "libprimes_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +libprimes = { path = "../../Bindings/Rust" } + +[[bin]] +name = "libprimes_example" +path = "LibPrimes_example.rs" diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs new file mode 100644 index 00000000..1a7c10ea --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs @@ -0,0 +1,53 @@ +/*++ + +Copyright (C) 2019 PrimeDevelopers + +All rights reserved. + +Abstract: Rust example that exercises the Rust bindings of Prime Numbers Library. + It only needs the example library of this component. + +Interface version: 1.2.0 + +*/ + +use libprimes::*; +use std::sync::atomic::{AtomicBool, Ordering}; + +static ABORT_REQUESTED: AtomicBool = AtomicBool::new(false); + +unsafe extern "C" fn progress(p: f32, should_abort: *mut bool) { + println!("Progress = {}%", (p * 100.0).round()); + if !should_abort.is_null() && p > 0.5 { + *should_abort = true; + ABORT_REQUESTED.store(true, Ordering::SeqCst); + } +} +unsafe extern "C" fn quiet(_p: f32, _a: *mut bool) {} +fn main() -> Result<()> { + let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?; + let (a, b, c) = wrapper.get_version()?; + println!("LibPrimes version: {}.{}.{}", a, b, c); + let f = wrapper.create_factorization_calculator()?; + f.set_value(735)?; + // SAFETY: the callback follows the C ABI and does not panic + unsafe { f.set_progress_callback(progress)? }; + // like the python example, the callback aborts once progress exceeds 50%. The result has to + // agree with what the callback requested (an implementation might not report progress at all). + match f.calculate() { + Err(e) => { + println!("{}", e); + assert_eq!(e.name(), "CALCULATIONABORTED"); + assert!(ABORT_REQUESTED.load(Ordering::SeqCst)); + } + Ok(()) => assert!(!ABORT_REQUESTED.load(Ordering::SeqCst)), + } + // without abort the calculation completes + unsafe { f.set_progress_callback(quiet)? }; + f.calculate()?; + let factors = f.get_prime_factors()?; + let text: Vec = factors.iter().map(|p| { let (pr, m) = (p.prime, p.multiplicity); format!("{}^{}", pr, m) }).collect(); + println!("{} = {}", f.get_value()?, text.join(" * ")); + assert_eq!(text.join(" * "), "3^1 * 5^1 * 7^2"); + Ok(()) +} diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/build.sh b/Examples/Primes/LibPrimes_component/Examples/Rust/build.sh new file mode 100755 index 00000000..9666f2c6 --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/build.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -euxo pipefail + +cd "$(dirname "$0")" +source ../../../../../Build/build.inc + +echo "Build Rust example" +export CARGO_TARGET_DIR=build +cargo build + +echo "Test C++ library" +./build/debug/libprimes_example $PWD/../../Implementations/Cpp/build/libprimes$OSLIBEXT + +echo "Test Pascal library" +./build/debug/libprimes_example $PWD/../../Implementations/Pascal/build/libprimes$OSLIBEXT diff --git a/Examples/Primes/build.sh b/Examples/Primes/build.sh index 5fd0b788..46b6bfe3 100755 --- a/Examples/Primes/build.sh +++ b/Examples/Primes/build.sh @@ -21,4 +21,5 @@ echo "Build and test bindings examples with C++ library" ./LibPrimes_component/Examples/Java9/build.sh ./LibPrimes_component/Examples/Pascal/build.sh ./LibPrimes_component/Examples/Python/build.sh +./LibPrimes_component/Examples/Rust/build.sh echo "Build and test are done and successful" diff --git a/Examples/Primes/libPrimes.xml b/Examples/Primes/libPrimes.xml index e73377fe..fe91b674 100644 --- a/Examples/Primes/libPrimes.xml +++ b/Examples/Primes/libPrimes.xml @@ -12,6 +12,7 @@ + diff --git a/Examples/RTTI/RTTI.xml b/Examples/RTTI/RTTI.xml index 58d58379..e755724e 100644 --- a/Examples/RTTI/RTTI.xml +++ b/Examples/RTTI/RTTI.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..f1995b55 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "rtti" +version = "1.0.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of RTTI" diff --git a/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..feaef297 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,1472 @@ +/*++ + +Copyright (C) 2021 ADSK + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of RTTI + +Interface version: 1.0.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; +} + +/// Error returned by the RTTI library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "RTTIError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + rtti_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + rtti_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + rtti_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + rtti_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + rtti_injectcomponent: unsafe extern "C" fn(*const c_char, *mut c_void) -> i32, + rtti_getsymbollookupmethod: unsafe extern "C" fn(*mut *mut c_void) -> i32, + rtti_createzoo: unsafe extern "C" fn(*mut Handle) -> i32, + rtti_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + rtti_animal_name: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char) -> i32, + rtti_tiger_roar: unsafe extern "C" fn(Handle) -> i32, + rtti_animaliterator_getnextanimal: unsafe extern "C" fn(Handle, *mut Handle) -> i32, + rtti_animaliterator_getnextoptinalanimal: unsafe extern "C" fn(Handle, *mut Handle, *mut bool) -> i32, + rtti_animaliterator_getnextmandatoryanimal: unsafe extern "C" fn(Handle, *mut Handle, *mut bool) -> i32, + rtti_zoo_iterator: unsafe extern "C" fn(Handle, *mut Handle) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + rtti_getversion: mem::transmute(load_symbol("rtti_getversion")?), + rtti_getlasterror: mem::transmute(load_symbol("rtti_getlasterror")?), + rtti_releaseinstance: mem::transmute(load_symbol("rtti_releaseinstance")?), + rtti_acquireinstance: mem::transmute(load_symbol("rtti_acquireinstance")?), + rtti_injectcomponent: mem::transmute(load_symbol("rtti_injectcomponent")?), + rtti_getsymbollookupmethod: mem::transmute(load_symbol("rtti_getsymbollookupmethod")?), + rtti_createzoo: mem::transmute(load_symbol("rtti_createzoo")?), + rtti_base_classtypeid: mem::transmute(load_symbol("rtti_base_classtypeid")?), + rtti_animal_name: mem::transmute(load_symbol("rtti_animal_name")?), + rtti_tiger_roar: mem::transmute(load_symbol("rtti_tiger_roar")?), + rtti_animaliterator_getnextanimal: mem::transmute(load_symbol("rtti_animaliterator_getnextanimal")?), + rtti_animaliterator_getnextoptinalanimal: mem::transmute(load_symbol("rtti_animaliterator_getnextoptinalanimal")?), + rtti_animaliterator_getnextmandatoryanimal: mem::transmute(load_symbol("rtti_animaliterator_getnextmandatoryanimal")?), + rtti_zoo_iterator: mem::transmute(load_symbol("rtti_zoo_iterator")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.rtti_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.rtti_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the RTTI library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.rtti_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == Animal::TYPE_ID { + return BaseKind::Animal(Animal::from_base(self.into_base())); + } + if id == Mammal::TYPE_ID { + return BaseKind::Mammal(Mammal::from_base(self.into_base())); + } + if id == Reptile::TYPE_ID { + return BaseKind::Reptile(Reptile::from_base(self.into_base())); + } + if id == Giraffe::TYPE_ID { + return BaseKind::Giraffe(Giraffe::from_base(self.into_base())); + } + if id == Tiger::TYPE_ID { + return BaseKind::Tiger(Tiger::from_base(self.into_base())); + } + if id == Snake::TYPE_ID { + return BaseKind::Snake(Snake::from_base(self.into_base())); + } + if id == Turtle::TYPE_ID { + return BaseKind::Turtle(Turtle::from_base(self.into_base())); + } + if id == AnimalIterator::TYPE_ID { + return BaseKind::AnimalIterator(AnimalIterator::from_base(self.into_base())); + } + if id == Zoo::TYPE_ID { + return BaseKind::Zoo(Zoo::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.rtti_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + Animal(Animal), + Mammal(Mammal), + Reptile(Reptile), + Giraffe(Giraffe), + Tiger(Tiger), + Snake(Snake), + Turtle(Turtle), + AnimalIterator(AnimalIterator), + Zoo(Zoo), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0x1549AD28813DAE05, 0x8B40467DA6D327AF, 0xBC9D5FA7750C1020, 0x6756AA8EA5802EC3, 0x9751971BD2C2D958, 0x08D007E7B5F7BAF4, 0x5F6826EF909803B2, 0x8E551B208A2E8321, 0xF1917FE6BBE77831, 0x2262ABE80A5E7878]; + const TYPE_ID: u64 = 0x1549AD28813DAE05; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.rtti_releaseinstance)(self.handle) }; + } + } +} + +/// Animal class of the RTTI library. +pub struct Animal { + parent: Base, +} + +impl std::ops::Deref for Animal { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Animal { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> AnimalKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return AnimalKind::Other(self), + }; + if id == Mammal::TYPE_ID { + return AnimalKind::Mammal(Mammal::from_base(self.into_base())); + } + if id == Reptile::TYPE_ID { + return AnimalKind::Reptile(Reptile::from_base(self.into_base())); + } + if id == Giraffe::TYPE_ID { + return AnimalKind::Giraffe(Giraffe::from_base(self.into_base())); + } + if id == Tiger::TYPE_ID { + return AnimalKind::Tiger(Tiger::from_base(self.into_base())); + } + if id == Snake::TYPE_ID { + return AnimalKind::Snake(Snake::from_base(self.into_base())); + } + if id == Turtle::TYPE_ID { + return AnimalKind::Turtle(Turtle::from_base(self.into_base())); + } + AnimalKind::Other(self) + } + + /// Get the name of the animal + /// + /// # Returns + /// * `result` - + pub fn name(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_needed_result: u32 = 0; + let mut __act_filled_result: u32 = 0; + let mut __act_buffer_result: Vec = Vec::new(); + let __act_code = unsafe { (__act_inner.api.rtti_animal_name)(__act_handle, 0, &mut __act_needed_result, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_result.resize(__act_needed_result as usize, 0); + let __act_code = unsafe { (__act_inner.api.rtti_animal_name)(__act_handle, __act_buffer_result.len() as u32, &mut __act_filled_result, __act_buffer_result.as_mut_ptr() as *mut c_char) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(string_from_buffer(&__act_buffer_result, __act_filled_result)) + } +} + +/// The most specific class of a `Animal`, see `Animal::into_kind`. +pub enum AnimalKind { + Mammal(Mammal), + Reptile(Reptile), + Giraffe(Giraffe), + Tiger(Tiger), + Snake(Snake), + Turtle(Turtle), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Animal), +} + +impl fmt::Debug for Animal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Animal").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Animal {} + +impl Class for Animal { + const TYPE_IDS: &'static [u64] = &[0x8B40467DA6D327AF, 0xBC9D5FA7750C1020, 0x6756AA8EA5802EC3, 0x9751971BD2C2D958, 0x08D007E7B5F7BAF4, 0x5F6826EF909803B2, 0x8E551B208A2E8321]; + const TYPE_ID: u64 = 0x8B40467DA6D327AF; + + fn from_base(base: Base) -> Self { + Animal { parent: base } + } +} + +/// Mammal class of the RTTI library. +pub struct Mammal { + parent: Animal, +} + +impl std::ops::Deref for Mammal { + type Target = Animal; + + fn deref(&self) -> &Animal { + &self.parent + } +} + +impl Mammal { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Animal::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> MammalKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return MammalKind::Other(self), + }; + if id == Giraffe::TYPE_ID { + return MammalKind::Giraffe(Giraffe::from_base(self.into_base())); + } + if id == Tiger::TYPE_ID { + return MammalKind::Tiger(Tiger::from_base(self.into_base())); + } + MammalKind::Other(self) + } +} + +/// The most specific class of a `Mammal`, see `Mammal::into_kind`. +pub enum MammalKind { + Giraffe(Giraffe), + Tiger(Tiger), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Mammal), +} + +impl fmt::Debug for Mammal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Mammal").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Mammal {} + +impl Class for Mammal { + const TYPE_IDS: &'static [u64] = &[0xBC9D5FA7750C1020, 0x9751971BD2C2D958, 0x08D007E7B5F7BAF4]; + const TYPE_ID: u64 = 0xBC9D5FA7750C1020; + + fn from_base(base: Base) -> Self { + Mammal { parent: Animal { parent: base } } + } +} + +/// Reptile class of the RTTI library. +pub struct Reptile { + parent: Animal, +} + +impl std::ops::Deref for Reptile { + type Target = Animal; + + fn deref(&self) -> &Animal { + &self.parent + } +} + +impl Reptile { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Animal::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> ReptileKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return ReptileKind::Other(self), + }; + if id == Snake::TYPE_ID { + return ReptileKind::Snake(Snake::from_base(self.into_base())); + } + if id == Turtle::TYPE_ID { + return ReptileKind::Turtle(Turtle::from_base(self.into_base())); + } + ReptileKind::Other(self) + } +} + +/// The most specific class of a `Reptile`, see `Reptile::into_kind`. +pub enum ReptileKind { + Snake(Snake), + Turtle(Turtle), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Reptile), +} + +impl fmt::Debug for Reptile { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Reptile").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Reptile {} + +impl Class for Reptile { + const TYPE_IDS: &'static [u64] = &[0x6756AA8EA5802EC3, 0x5F6826EF909803B2, 0x8E551B208A2E8321]; + const TYPE_ID: u64 = 0x6756AA8EA5802EC3; + + fn from_base(base: Base) -> Self { + Reptile { parent: Animal { parent: base } } + } +} + +/// Giraffe class of the RTTI library. +pub struct Giraffe { + parent: Mammal, +} + +impl std::ops::Deref for Giraffe { + type Target = Mammal; + + fn deref(&self) -> &Mammal { + &self.parent + } +} + +impl Giraffe { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Mammal::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } +} + +impl fmt::Debug for Giraffe { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Giraffe").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Giraffe {} + +impl Class for Giraffe { + const TYPE_IDS: &'static [u64] = &[0x9751971BD2C2D958]; + const TYPE_ID: u64 = 0x9751971BD2C2D958; + + fn from_base(base: Base) -> Self { + Giraffe { parent: Mammal { parent: Animal { parent: base } } } + } +} + +/// Tiger class of the RTTI library. +pub struct Tiger { + parent: Mammal, +} + +impl std::ops::Deref for Tiger { + type Target = Mammal; + + fn deref(&self) -> &Mammal { + &self.parent + } +} + +impl Tiger { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Mammal::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Roar like a tiger + pub fn roar(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.rtti_tiger_roar)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +impl fmt::Debug for Tiger { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Tiger").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Tiger {} + +impl Class for Tiger { + const TYPE_IDS: &'static [u64] = &[0x08D007E7B5F7BAF4]; + const TYPE_ID: u64 = 0x08D007E7B5F7BAF4; + + fn from_base(base: Base) -> Self { + Tiger { parent: Mammal { parent: Animal { parent: base } } } + } +} + +/// Snake class of the RTTI library. +pub struct Snake { + parent: Reptile, +} + +impl std::ops::Deref for Snake { + type Target = Reptile; + + fn deref(&self) -> &Reptile { + &self.parent + } +} + +impl Snake { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Reptile::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } +} + +impl fmt::Debug for Snake { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Snake").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Snake {} + +impl Class for Snake { + const TYPE_IDS: &'static [u64] = &[0x5F6826EF909803B2]; + const TYPE_ID: u64 = 0x5F6826EF909803B2; + + fn from_base(base: Base) -> Self { + Snake { parent: Reptile { parent: Animal { parent: base } } } + } +} + +/// Turtle class of the RTTI library. +pub struct Turtle { + parent: Reptile, +} + +impl std::ops::Deref for Turtle { + type Target = Reptile; + + fn deref(&self) -> &Reptile { + &self.parent + } +} + +impl Turtle { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Reptile::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } +} + +impl fmt::Debug for Turtle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Turtle").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Turtle {} + +impl Class for Turtle { + const TYPE_IDS: &'static [u64] = &[0x8E551B208A2E8321]; + const TYPE_ID: u64 = 0x8E551B208A2E8321; + + fn from_base(base: Base) -> Self { + Turtle { parent: Reptile { parent: Animal { parent: base } } } + } +} + +/// AnimalIterator class of the RTTI library. +pub struct AnimalIterator { + parent: Base, +} + +impl std::ops::Deref for AnimalIterator { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl AnimalIterator { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Return next animal + /// + /// # Returns + /// * `animal` - + pub fn get_next_animal(&self) -> Result> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_animal: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.rtti_animaliterator_getnextanimal)(__act_handle, &mut __act_out_animal) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(if __act_out_animal.is_null() { None } else { Some(Animal::from_handle(__act_inner.clone(), __act_out_animal)) }) + } + + /// Return next animal + /// + /// # Returns + /// * `animal` - + /// * `error` - + pub fn get_next_optinal_animal(&self) -> Result<(Option, bool)> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_animal: Handle = ptr::null_mut(); + let mut __act_out_error: bool = false; + let __act_code = unsafe { (__act_inner.api.rtti_animaliterator_getnextoptinalanimal)(__act_handle, &mut __act_out_animal, &mut __act_out_error) }; + __act_inner.check(__act_handle, __act_code)?; + Ok((if __act_out_animal.is_null() { None } else { Some(Animal::from_handle(__act_inner.clone(), __act_out_animal)) }, __act_out_error)) + } + + /// Return next animal + /// + /// # Returns + /// * `animal` - + /// * `error` - + pub fn get_next_mandatory_animal(&self) -> Result<(Option, bool)> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_animal: Handle = ptr::null_mut(); + let mut __act_out_error: bool = false; + let __act_code = unsafe { (__act_inner.api.rtti_animaliterator_getnextmandatoryanimal)(__act_handle, &mut __act_out_animal, &mut __act_out_error) }; + __act_inner.check(__act_handle, __act_code)?; + Ok((if __act_out_animal.is_null() { None } else { Some(Animal::from_handle(__act_inner.clone(), __act_out_animal)) }, __act_out_error)) + } +} + +impl fmt::Debug for AnimalIterator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AnimalIterator").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for AnimalIterator {} + +impl Class for AnimalIterator { + const TYPE_IDS: &'static [u64] = &[0xF1917FE6BBE77831]; + const TYPE_ID: u64 = 0xF1917FE6BBE77831; + + fn from_base(base: Base) -> Self { + AnimalIterator { parent: base } + } +} + +/// Zoo class of the RTTI library. +pub struct Zoo { + parent: Base, +} + +impl std::ops::Deref for Zoo { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl Zoo { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.rtti_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Return an iterator over all zoo animals + /// + /// # Returns + /// * `iterator` - + pub fn iterator(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_iterator: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.rtti_zoo_iterator)(__act_handle, &mut __act_out_iterator) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(AnimalIterator::from_handle(__act_inner.clone(), __act_out_iterator)) + } +} + +impl fmt::Debug for Zoo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Zoo").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Zoo {} + +impl Class for Zoo { + const TYPE_IDS: &'static [u64] = &[0x2262ABE80A5E7878]; + const TYPE_ID: u64 = 0x2262ABE80A5E7878; + + fn from_base(base: Base) -> Self { + Zoo { parent: base } + } +} + +/// Entry point to the RTTI library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Creates a wrapper that resolves the functions of the library through the address of its symbol lookup + /// method, as returned by `get_symbol_lookup_method`. This is used to inject a component into another one. + /// The library that provides the symbol lookup method has to stay loaded for as long as the wrapper is used. + /// + /// # Safety + /// `symbol_lookup_method` must be the address of a valid symbol lookup method of a compatible library + /// (`int32 fn(const char*, void**)`), and that library must outlive the wrapper and all objects created from it. + pub unsafe fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + if symbol_lookup_method.is_null() { + return Err(Error::new(error_code::INVALIDPARAM, "the symbol lookup method is null")); + } + type SymbolLookup = unsafe extern "C" fn(*const c_char, *mut *mut c_void) -> i32; + let lookup: SymbolLookup = mem::transmute::<*mut c_void, SymbolLookup>(symbol_lookup_method); + let api = unsafe { + Api::load(|name| { + let cname = CString::new(name).map_err(|_| "symbol contains NUL".to_string())?; + let mut address: *mut c_void = ptr::null_mut(); + let code = lookup(cname.as_ptr(), &mut address); + if code != 0 || address.is_null() { + Err(format!("could not find the symbol {} (error {})", name, code)) + } else { + Ok(address) + } + }) + }?; + let wrapper = Self { inner: Inner::new(api, None) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 0; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.rtti_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.rtti_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.rtti_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.rtti_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.rtti_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Injects an imported component for usage within this component + /// + /// # Arguments + /// * `name_space` - NameSpace of the injected component + /// * `symbol_address_method` - Address of the SymbolAddressMethod of the injected component + /// + /// # Safety + /// The library passes symbol_address_method on to callbacks or uses it as is: callback functions must follow the C ABI, + /// must not panic, and pointers must stay valid for as long as the library may use them. + pub unsafe fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + let __act_inner = &self.inner; + let __act_c_name_space = CString::new(name_space) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; + let __act_code = unsafe { (__act_inner.api.rtti_injectcomponent)(__act_c_name_space.as_ptr(), symbol_address_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Returns the address of the SymbolLookupMethod + /// + /// # Returns + /// * `symbol_lookup_method` - Address of the SymbolAddressMethod + pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { + let __act_inner = &self.inner; + let mut __act_out_symbol_lookup_method: *mut c_void = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.rtti_getsymbollookupmethod)(&mut __act_out_symbol_lookup_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(__act_out_symbol_lookup_method) + } + + /// Create a new zoo with animals + /// + /// # Returns + /// * `instance` - + pub fn create_zoo(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.rtti_createzoo)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(Zoo::from_handle(__act_inner.clone(), __act_out_instance)) + } +} diff --git a/Examples/RTTI/RTTI_component/Examples/Rust/Cargo.toml b/Examples/RTTI/RTTI_component/Examples/Rust/Cargo.toml new file mode 100644 index 00000000..6ea25dbd --- /dev/null +++ b/Examples/RTTI/RTTI_component/Examples/Rust/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "rtti_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +rtti = { path = "../../Bindings/Rust" } + +[[bin]] +name = "rtti_example" +path = "RTTI_example.rs" diff --git a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs new file mode 100644 index 00000000..574140a3 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs @@ -0,0 +1,47 @@ +/*++ + +Copyright (C) 2021 ADSK + +All rights reserved. + +Abstract: Rust example that exercises the Rust bindings of RTTI. + It only needs the example library of this component. + +Interface version: 1.0.0 + +*/ + +use rtti::*; +fn main() { + // exception methods against a missing library (first part of the python example) + let e = Wrapper::new("nonexistent_library").err().expect("should fail"); + println!("{}", e); + assert_eq!(e.code, error_code::COULDNOTLOADLIBRARY); + assert_eq!(e.name(), "COULDNOTLOADLIBRARY"); + assert_eq!(e.description(), "the library could not be loaded"); + assert!(e.message.contains("nonexistent_library")); + assert!(e.to_string().contains("RTTIError") && e.to_string().contains(&e.code.to_string())); + + let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap()).unwrap(); + let (a, b, c) = wrapper.get_version().unwrap(); + println!("RTTI version: {}.{}.{}", a, b, c); + let zoo = wrapper.create_zoo().unwrap(); + let iter = zoo.iterator().unwrap(); + let expect = [("Gerald Giraffe", "Giraffe"), ("Timmy Tiger", "Tiger"), ("Tony Tiger", "Tiger"), ("Sebastian Snake", "Snake"), + ("Tobias Turtle", "Turtle"), ("Theo Turtle", "Turtle"), ("Tomás Turtle", "Turtle"), ("Slytherin Snake", "Snake"), + ("Travis Tiger", "Tiger"), ("Gary Giraffe", "Giraffe")]; + for (name, kind) in expect { + let animal = iter.get_next_animal().unwrap().expect("animal"); + assert_eq!(animal.name().unwrap(), name); + // every kind check from python's isinstance + let kinds = [("Giraffe", animal.is::()), ("Tiger", animal.is::()), ("Snake", animal.is::()), ("Turtle", animal.is::())]; + for (k, v) in kinds { assert_eq!(v, k == kind, "{} is {}?", name, k); } + // hierarchy: Giraffe/Tiger are Mammals, Snake/Turtle Reptiles + assert_eq!(animal.is::(), kind == "Giraffe" || kind == "Tiger"); + assert_eq!(animal.is::(), kind == "Snake" || kind == "Turtle"); + println!("Animal name: {} ({})", name, kind); + if kind == "Tiger" { animal.downcast::().expect("tiger").roar().unwrap(); } + } + assert!(iter.get_next_animal().unwrap().is_none()); + println!("No more Animals\nDone!"); +} diff --git a/Examples/RTTI/RTTI_component/Examples/Rust/build.sh b/Examples/RTTI/RTTI_component/Examples/Rust/build.sh new file mode 100755 index 00000000..3a1b6f18 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Examples/Rust/build.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -euxo pipefail + +cd "$(dirname "$0")" +source ../../../../../Build/build.inc + +echo "Build Rust example" +export CARGO_TARGET_DIR=build +cargo build + +echo "Test C++ library" +./build/debug/rtti_example $PWD/../../Implementations/Cpp/build/rtti$OSLIBEXT + +echo "Test Pascal library" +./build/debug/rtti_example $PWD/../../Implementations/Pascal/build/rtti$OSLIBEXT diff --git a/Examples/RTTI/build.sh b/Examples/RTTI/build.sh index 876b76ba..fc501020 100755 --- a/Examples/RTTI/build.sh +++ b/Examples/RTTI/build.sh @@ -20,6 +20,7 @@ python3 ./RTTI_component/Examples/WASM/buildExample.py ./RTTI_component/Examples/Go/build.sh ./RTTI_component/Examples/Java9/build.sh ./RTTI_component/Examples/Python/build.sh +./RTTI_component/Examples/Rust/build.sh ./RTTI_component/Examples/Pascal/build.sh ./RTTI_component/Examples/CSharp/build.sh echo "Build and test are done and successful" \ No newline at end of file diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..db02de5f --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "libthreadsafe" +version = "1.0.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of Thread-safe library" diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..b7ec9aec --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,952 @@ +/*++ + +Copyright (C) 2025 Thread-safe library developers + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of Thread-safe library + +Interface version: 1.0.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; + pub const NORESULTAVAILABLE: i32 = 9; + pub const CALCULATIONABORTED: i32 = 10; +} + +/// Error returned by the LibThreadSafe library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + error_code::NORESULTAVAILABLE => "NORESULTAVAILABLE", + error_code::CALCULATIONABORTED => "CALCULATIONABORTED", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + error_code::NORESULTAVAILABLE => "no result is available", + error_code::CALCULATIONABORTED => "a calculation has been aborted", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "LibThreadSafeError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + libthreadsafe_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + libthreadsafe_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + libthreadsafe_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + libthreadsafe_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + libthreadsafe_createstringreturner: unsafe extern "C" fn(*mut Handle) -> i32, + libthreadsafe_createsoftstringreturner: unsafe extern "C" fn(*mut Handle) -> i32, + libthreadsafe_createstrictstringreturner: unsafe extern "C" fn(*mut Handle) -> i32, + libthreadsafe_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + libthreadsafe_base__lockinstance: unsafe extern "C" fn(Handle) -> i32, + libthreadsafe_base__unlockinstance: unsafe extern "C" fn(Handle) -> i32, + libthreadsafe_stringreturner_getstring: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char) -> i32, + libthreadsafe_stringreturner_threadsafetycheck: unsafe extern "C" fn(Handle) -> i32, + libthreadsafe_softstringreturner_getstring: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char) -> i32, + libthreadsafe_softstringreturner_threadsafetycheck: unsafe extern "C" fn(Handle) -> i32, + libthreadsafe_strictstringreturner_getstring: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char) -> i32, + libthreadsafe_strictstringreturner_threadsafetycheck: unsafe extern "C" fn(Handle) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + libthreadsafe_getversion: mem::transmute(load_symbol("libthreadsafe_getversion")?), + libthreadsafe_getlasterror: mem::transmute(load_symbol("libthreadsafe_getlasterror")?), + libthreadsafe_acquireinstance: mem::transmute(load_symbol("libthreadsafe_acquireinstance")?), + libthreadsafe_releaseinstance: mem::transmute(load_symbol("libthreadsafe_releaseinstance")?), + libthreadsafe_createstringreturner: mem::transmute(load_symbol("libthreadsafe_createstringreturner")?), + libthreadsafe_createsoftstringreturner: mem::transmute(load_symbol("libthreadsafe_createsoftstringreturner")?), + libthreadsafe_createstrictstringreturner: mem::transmute(load_symbol("libthreadsafe_createstrictstringreturner")?), + libthreadsafe_base_classtypeid: mem::transmute(load_symbol("libthreadsafe_base_classtypeid")?), + libthreadsafe_base__lockinstance: mem::transmute(load_symbol("libthreadsafe_base__lockinstance")?), + libthreadsafe_base__unlockinstance: mem::transmute(load_symbol("libthreadsafe_base__unlockinstance")?), + libthreadsafe_stringreturner_getstring: mem::transmute(load_symbol("libthreadsafe_stringreturner_getstring")?), + libthreadsafe_stringreturner_threadsafetycheck: mem::transmute(load_symbol("libthreadsafe_stringreturner_threadsafetycheck")?), + libthreadsafe_softstringreturner_getstring: mem::transmute(load_symbol("libthreadsafe_softstringreturner_getstring")?), + libthreadsafe_softstringreturner_threadsafetycheck: mem::transmute(load_symbol("libthreadsafe_softstringreturner_threadsafetycheck")?), + libthreadsafe_strictstringreturner_getstring: mem::transmute(load_symbol("libthreadsafe_strictstringreturner_getstring")?), + libthreadsafe_strictstringreturner_threadsafetycheck: mem::transmute(load_symbol("libthreadsafe_strictstringreturner_threadsafetycheck")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.libthreadsafe_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.libthreadsafe_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +/// Holds the lock of an instance of a class with a thread safety option for the duration of a call. +struct InstanceLock<'a> { + inner: &'a Inner, + handle: Handle, +} + +impl<'a> InstanceLock<'a> { + fn new(inner: &'a Inner, handle: Handle) -> Result { + let code = unsafe { (inner.api.libthreadsafe_base__lockinstance)(handle) }; + inner.check(handle, code)?; + Ok(Self { inner, handle }) + } +} + +impl Drop for InstanceLock<'_> { + fn drop(&mut self) { + unsafe { (self.inner.api.libthreadsafe_base__unlockinstance)(self.handle) }; + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the LibThreadSafe library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libthreadsafe_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.libthreadsafe_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == StringReturner::TYPE_ID { + return BaseKind::StringReturner(StringReturner::from_base(self.into_base())); + } + if id == SoftStringReturner::TYPE_ID { + return BaseKind::SoftStringReturner(SoftStringReturner::from_base(self.into_base())); + } + if id == StrictStringReturner::TYPE_ID { + return BaseKind::StrictStringReturner(StrictStringReturner::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } + + /// If thread safety for class in library is enabled it should lock object for calling thread + /// + /// # Safety + /// Locks the instance's internal mutex directly. The caller must not already hold the lock on this thread and must pair it with the corresponding unlock call. + pub unsafe fn _lock_instance(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_base__lockinstance)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// If thread safety for class in library is enabled it should unlock object for other threads + /// + /// # Safety + /// Unlocks the instance's internal mutex directly. The caller must currently hold the lock on this thread. + pub unsafe fn _unlock_instance(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_base__unlockinstance)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + StringReturner(StringReturner), + SoftStringReturner(SoftStringReturner), + StrictStringReturner(StrictStringReturner), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0x82FEB223BA4B6B0E, 0x01755067BCC5ED81, 0x6C0744711291F198, 0xC8D8EB62D68DF429]; + const TYPE_ID: u64 = 0x82FEB223BA4B6B0E; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.libthreadsafe_releaseinstance)(self.handle) }; + } + } +} + +/// StringReturner class of the LibThreadSafe library. +pub struct StringReturner { + parent: Base, +} + +impl std::ops::Deref for StringReturner { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl StringReturner { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libthreadsafe_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns a string + /// + /// # Returns + /// * `value` - + pub fn get_string(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_needed_value: u32 = 0; + let mut __act_filled_value: u32 = 0; + let mut __act_buffer_value: Vec = Vec::new(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_stringreturner_getstring)(__act_handle, 0, &mut __act_needed_value, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_value.resize(__act_needed_value as usize, 0); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_stringreturner_getstring)(__act_handle, __act_buffer_value.len() as u32, &mut __act_filled_value, __act_buffer_value.as_mut_ptr() as *mut c_char) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(string_from_buffer(&__act_buffer_value, __act_filled_value)) + } + + /// Function that may crash when called from different threads at the same time + pub fn thread_safety_check(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_stringreturner_threadsafetycheck)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +impl fmt::Debug for StringReturner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StringReturner").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for StringReturner {} + +impl Class for StringReturner { + const TYPE_IDS: &'static [u64] = &[0x01755067BCC5ED81]; + const TYPE_ID: u64 = 0x01755067BCC5ED81; + + fn from_base(base: Base) -> Self { + StringReturner { parent: base } + } +} + +/// SoftStringReturner class of the LibThreadSafe library. +pub struct SoftStringReturner { + parent: Base, +} + +impl std::ops::Deref for SoftStringReturner { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl SoftStringReturner { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libthreadsafe_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns a string + /// + /// # Returns + /// * `value` - + pub fn get_string(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_needed_value: u32 = 0; + let mut __act_filled_value: u32 = 0; + let mut __act_buffer_value: Vec = Vec::new(); + let __act_lock = InstanceLock::new(__act_inner, __act_handle)?; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_softstringreturner_getstring)(__act_handle, 0, &mut __act_needed_value, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_value.resize(__act_needed_value as usize, 0); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_softstringreturner_getstring)(__act_handle, __act_buffer_value.len() as u32, &mut __act_filled_value, __act_buffer_value.as_mut_ptr() as *mut c_char) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(string_from_buffer(&__act_buffer_value, __act_filled_value)) + } + + /// Function that may crash when called from different threads at the same time + pub fn thread_safety_check(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_softstringreturner_threadsafetycheck)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +impl fmt::Debug for SoftStringReturner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SoftStringReturner").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for SoftStringReturner {} + +impl Class for SoftStringReturner { + const TYPE_IDS: &'static [u64] = &[0x6C0744711291F198]; + const TYPE_ID: u64 = 0x6C0744711291F198; + + fn from_base(base: Base) -> Self { + SoftStringReturner { parent: base } + } +} + +/// StrictStringReturner class of the LibThreadSafe library. +pub struct StrictStringReturner { + parent: Base, +} + +unsafe impl Sync for StrictStringReturner {} + +impl std::ops::Deref for StrictStringReturner { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl StrictStringReturner { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libthreadsafe_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns a string + /// + /// # Returns + /// * `value` - + pub fn get_string(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_needed_value: u32 = 0; + let mut __act_filled_value: u32 = 0; + let mut __act_buffer_value: Vec = Vec::new(); + let __act_lock = InstanceLock::new(__act_inner, __act_handle)?; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_strictstringreturner_getstring)(__act_handle, 0, &mut __act_needed_value, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_value.resize(__act_needed_value as usize, 0); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_strictstringreturner_getstring)(__act_handle, __act_buffer_value.len() as u32, &mut __act_filled_value, __act_buffer_value.as_mut_ptr() as *mut c_char) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(string_from_buffer(&__act_buffer_value, __act_filled_value)) + } + + /// Function that shouldn't crash when called from different threads at the same time + pub fn thread_safety_check(&self) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_lock = InstanceLock::new(__act_inner, __act_handle)?; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_strictstringreturner_threadsafetycheck)(__act_handle) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } +} + +impl fmt::Debug for StrictStringReturner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StrictStringReturner").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for StrictStringReturner {} + +impl Class for StrictStringReturner { + const TYPE_IDS: &'static [u64] = &[0xC8D8EB62D68DF429]; + const TYPE_ID: u64 = 0xC8D8EB62D68DF429; + + fn from_base(base: Base) -> Self { + StrictStringReturner { parent: base } + } +} + +/// Entry point to the LibThreadSafe library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 0; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Acquire shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.libthreadsafe_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Creates a new StringReturner instance + /// + /// # Returns + /// * `instance` - New StringReturner instance + pub fn create_string_returner(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_createstringreturner)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(StringReturner::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// Creates a new SoftStringReturner instance + /// + /// # Returns + /// * `instance` - New SoftStringReturner instance + pub fn create_soft_string_returner(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_createsoftstringreturner)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(SoftStringReturner::from_handle(__act_inner.clone(), __act_out_instance)) + } + + /// Creates a new StrictStringReturner instance + /// + /// # Returns + /// * `instance` - New StrictStringReturner instance + pub fn create_strict_string_returner(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libthreadsafe_createstrictstringreturner)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(StrictStringReturner::from_handle(__act_inner.clone(), __act_out_instance)) + } +} diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/Cargo.toml b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/Cargo.toml new file mode 100644 index 00000000..fe8ffb39 --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "libthreadsafe_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +libthreadsafe = { path = "../../Bindings/Rust" } + +[[bin]] +name = "libthreadsafe_example" +path = "LibThreadSafe_example.rs" diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs new file mode 100644 index 00000000..a932add9 --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs @@ -0,0 +1,30 @@ +/*++ + +Copyright (C) 2025 Thread-safe library developers + +All rights reserved. + +Abstract: Rust example that exercises the Rust bindings of Thread-safe library. + It only needs the example library of this component. + +Interface version: 1.0.0 + +*/ + +use libthreadsafe::*; +use std::sync::Arc; +fn main() -> Result<()> { + let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?; + let sr = wrapper.create_string_returner()?; + let soft = wrapper.create_soft_string_returner()?; + let strict = Arc::new(wrapper.create_strict_string_returner()?); + println!("created: {} {} {}", sr.get_string()?, soft.get_string()?, strict.get_string()?); + let mut handles = vec![]; + for _ in 0..5 { + let s = strict.clone(); + handles.push(std::thread::spawn(move || { for _ in 0..10000 { s.get_string().unwrap(); s.thread_safety_check().unwrap(); } })); + } + for h in handles { h.join().unwrap(); } + println!("threads done"); + Ok(()) +} diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/build.sh b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/build.sh new file mode 100755 index 00000000..3b3091dc --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/build.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +set -euxo pipefail + +cd "$(dirname "$0")" +source ../../../../../Build/build.inc + +echo "Build Rust example" +export CARGO_TARGET_DIR=build +cargo build + +echo "Test C++ library" +./build/debug/libthreadsafe_example $PWD/../../Implementations/Cpp/build/libthreadsafe$OSLIBEXT diff --git a/Examples/ThreadSafety/build.sh b/Examples/ThreadSafety/build.sh index bd8245dd..647e2d63 100755 --- a/Examples/ThreadSafety/build.sh +++ b/Examples/ThreadSafety/build.sh @@ -13,4 +13,5 @@ echo "Build libraries" echo "Build and test bindings examples with C++ library" ./LibThreadSafe_component/Examples/CppDynamic/build.sh +./LibThreadSafe_component/Examples/Rust/build.sh echo "Build and test are done and successful" diff --git a/Examples/ThreadSafety/threadSafeLibrary.xml b/Examples/ThreadSafety/threadSafeLibrary.xml index 083994cd..62c97231 100644 --- a/Examples/ThreadSafety/threadSafeLibrary.xml +++ b/Examples/ThreadSafety/threadSafeLibrary.xml @@ -8,6 +8,7 @@ + diff --git a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml new file mode 100644 index 00000000..92f0bae3 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "libunittest" +version = "1.0.0" +edition = "2021" +rust-version = "1.65" +description = "Rust bindings of ACT UnitTest FrameWork" diff --git a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs new file mode 100644 index 00000000..f5655fb6 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,887 @@ +/*++ + +Copyright (C) 2018 Autodesk + +All rights reserved. + +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop. + +Abstract: This is an autogenerated Rust file in order to allow an easy + use of ACT UnitTest FrameWork + +Interface version: 1.0.0 + +*/ + +use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} + +/// Error codes reported by the library. +pub mod error_code { + pub const SUCCESS: i32 = 0; + pub const NOTIMPLEMENTED: i32 = 1; + pub const INVALIDPARAM: i32 = 2; + pub const INVALIDCAST: i32 = 3; + pub const BUFFERTOOSMALL: i32 = 4; + pub const GENERICEXCEPTION: i32 = 5; + pub const COULDNOTLOADLIBRARY: i32 = 6; + pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7; + pub const INCOMPATIBLEBINARYVERSION: i32 = 8; +} + +/// Error returned by the LibUnitTest library or by the Rust binding. +#[derive(Clone, PartialEq, Eq)] +pub struct Error { + pub code: i32, + pub message: String, +} + +impl Error { + pub fn new(code: i32, message: impl Into) -> Self { + Self { code, message: message.into() } + } + + /// Name of the error code. + pub fn name(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "SUCCESS", + error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED", + error_code::INVALIDPARAM => "INVALIDPARAM", + error_code::INVALIDCAST => "INVALIDCAST", + error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL", + error_code::GENERICEXCEPTION => "GENERICEXCEPTION", + error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY", + error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT", + error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION", + _ => "UNKNOWN", + } + } + + /// Generic description of the error code. + pub fn description(&self) -> &'static str { + match self.code { + error_code::SUCCESS => "success", + error_code::NOTIMPLEMENTED => "functionality not implemented", + error_code::INVALIDPARAM => "an invalid parameter was passed", + error_code::INVALIDCAST => "a type cast failed", + error_code::BUFFERTOOSMALL => "a provided buffer is too small", + error_code::GENERICEXCEPTION => "a generic exception occurred", + error_code::COULDNOTLOADLIBRARY => "the library could not be loaded", + error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library", + error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface", + _ => "unknown error", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = if self.message.is_empty() { self.description() } else { self.message.as_str() }; + write!(f, "LibUnitTestError {} ({}): {}", self.name(), self.code, message) + } +} + +// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl std::error::Error for Error {} + +pub type Result = std::result::Result; + +#[allow(non_camel_case_types)] +#[repr(i32)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum TestEnum { + Option1 = 1, + Option20 = 20, + Option55 = 55, +} + +impl TestEnum { + #[doc(hidden)] + #[allow(dead_code)] + pub fn from_raw(value: i32) -> Result { + match value { + 1 => Ok(TestEnum::Option1), + 20 => Ok(TestEnum::Option20), + 55 => Ok(TestEnum::Option55), + _ => Err(Error::new(error_code::INVALIDCAST, "invalid enumeration value for TestEnum")), + } + } +} + +#[repr(C, packed)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct TestStruct { + pub x: u32, + pub y: f64, + pub z: f64, +} + +// the size has to match the packed layout of the C ABI +const _: () = assert!(std::mem::size_of::() == 20); + +/// Table of the functions exported by the library. +#[allow(non_snake_case)] +struct Api { + libunittest_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32, + libunittest_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32, + libunittest_releaseinstance: unsafe extern "C" fn(Handle) -> i32, + libunittest_acquireinstance: unsafe extern "C" fn(Handle) -> i32, + libunittest_injectcomponent: unsafe extern "C" fn(*const c_char, *mut c_void) -> i32, + libunittest_getsymbollookupmethod: unsafe extern "C" fn(*mut *mut c_void) -> i32, + libunittest_createtestclasss: unsafe extern "C" fn(*mut Handle) -> i32, + libunittest_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32, + libunittest_testclass_value: unsafe extern "C" fn(Handle, *mut f64) -> i32, + libunittest_testclass_setvalue: unsafe extern "C" fn(Handle, f64) -> i32, + libunittest_testclass_setvalueint: unsafe extern "C" fn(Handle, i64) -> i32, + libunittest_testclass_setvaluestring: unsafe extern "C" fn(Handle, *const c_char) -> i32, + libunittest_testclass_unittest1: unsafe extern "C" fn(Handle, u8, u16, u32, u64, *mut u8, *mut u16, *mut u32, *mut u64) -> i32, + libunittest_testclass_unittest2: unsafe extern "C" fn(Handle, i8, i16, i32, i64, *mut i8, *mut i16, *mut i32, *mut i64) -> i32, + libunittest_testclass_unittest3: unsafe extern "C" fn(Handle, bool, f32, f64, i32, *mut bool, *mut f32, *mut f64, *mut i32) -> i32, + libunittest_testclass_unittest4: unsafe extern "C" fn(Handle, *const c_char, u32, *mut u32, *mut c_char, u32, *mut u32, *mut c_char) -> i32, +} + +impl Api { + /// Loads all functions using a function that resolves the address of a symbol by its name. + #[allow(clippy::missing_transmute_annotations)] + unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result { + let load_symbol = |name: &str| -> Result<*mut c_void> { + lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e)) + }; + Ok(Self { + libunittest_getversion: mem::transmute(load_symbol("libunittest_getversion")?), + libunittest_getlasterror: mem::transmute(load_symbol("libunittest_getlasterror")?), + libunittest_releaseinstance: mem::transmute(load_symbol("libunittest_releaseinstance")?), + libunittest_acquireinstance: mem::transmute(load_symbol("libunittest_acquireinstance")?), + libunittest_injectcomponent: mem::transmute(load_symbol("libunittest_injectcomponent")?), + libunittest_getsymbollookupmethod: mem::transmute(load_symbol("libunittest_getsymbollookupmethod")?), + libunittest_createtestclasss: mem::transmute(load_symbol("libunittest_createtestclasss")?), + libunittest_base_classtypeid: mem::transmute(load_symbol("libunittest_base_classtypeid")?), + libunittest_testclass_value: mem::transmute(load_symbol("libunittest_testclass_value")?), + libunittest_testclass_setvalue: mem::transmute(load_symbol("libunittest_testclass_setvalue")?), + libunittest_testclass_setvalueint: mem::transmute(load_symbol("libunittest_testclass_setvalueint")?), + libunittest_testclass_setvaluestring: mem::transmute(load_symbol("libunittest_testclass_setvaluestring")?), + libunittest_testclass_unittest1: mem::transmute(load_symbol("libunittest_testclass_unittest1")?), + libunittest_testclass_unittest2: mem::transmute(load_symbol("libunittest_testclass_unittest2")?), + libunittest_testclass_unittest3: mem::transmute(load_symbol("libunittest_testclass_unittest3")?), + libunittest_testclass_unittest4: mem::transmute(load_symbol("libunittest_testclass_unittest4")?), + }) + } +} + +/// State shared by the wrapper and all instances created through it, so that the library +/// stays loaded for as long as any instance is alive. +struct Inner { + api: Api, + _lib: Option, +} + +// The function table and the library handle are immutable after loading. +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +impl Inner { + fn new(api: Api, lib: Option) -> Arc { + Arc::new(Self { + api, + _lib: lib, + }) + } + + fn check(&self, handle: Handle, code: i32) -> Result<()> { + if code == 0 { + return Ok(()); + } + Err(Error::new(code, self.last_error_message(handle))) + } + + fn last_error_message(&self, handle: Handle) -> String { + if handle.is_null() { + return String::new(); + } + let mut needed: u32 = 0; + let mut has_error = false; + let code = unsafe { (self.api.libunittest_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) }; + if code != 0 || !has_error || needed == 0 { + return String::new(); + } + let mut buffer = vec![0u8; needed as usize]; + let mut filled: u32 = 0; + let code = unsafe { (self.api.libunittest_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) }; + if code != 0 || !has_error { + return String::new(); + } + string_from_buffer(&buffer, filled) + } +} + +mod private { + pub trait Sealed {} +} + +/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class +/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances. +pub trait Class: private::Sealed + Sized { + #[doc(hidden)] + const TYPE_IDS: &'static [u64]; + #[doc(hidden)] + const TYPE_ID: u64; + #[doc(hidden)] + fn from_base(base: Base) -> Self; +} + +/// Base class of the LibUnitTest library. +pub struct Base { + inner: Arc, + handle: Handle, +} + +// Instances may be moved between threads. They may only be shared between threads if the class is +// declared with the strict threadsafetyoption in the ACT class definition. +unsafe impl Send for Base {} + +impl Base { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { inner, handle } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libunittest_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn inner_arc(&self) -> &Arc { + &self.inner + } + + /// Raw handle of the instance inside of the library. + pub fn handle(&self) -> Handle { + self.handle + } + + fn into_base(self) -> Base { + self + } + + /// Tells whether the instance is of class `T` or of a class derived from it. + pub fn is(&self) -> bool { + matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id)) + } + + /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`. + /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes. + pub fn cast(&self) -> Option { + if !self.is::() { + return None; + } + let code = unsafe { (self.inner.api.libunittest_acquireinstance)(self.handle) }; + if code != 0 { + return None; + } + Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle })) + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Resolves the most specific class of the instance, to be used in a `match`. + pub fn into_kind(self) -> BaseKind { + let id = match self.class_type_id() { + Ok(id) => id, + Err(_) => return BaseKind::Other(self), + }; + if id == TestClass::TYPE_ID { + return BaseKind::TestClass(TestClass::from_base(self.into_base())); + } + BaseKind::Other(self) + } + + /// Get Class Type Id + /// + /// # Returns + /// * `class_type_id` - Class type as a 64 bits integer + pub fn class_type_id(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_class_type_id: u64 = 0; + let __act_code = unsafe { (__act_inner.api.libunittest_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_class_type_id) + } +} + +/// The most specific class of a `Base`, see `Base::into_kind`. +pub enum BaseKind { + TestClass(TestClass), + /// The instance is not of a more specific class (or the class is unknown to this binding). + Other(Base), +} + +impl fmt::Debug for Base { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Base").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for Base {} + +impl Class for Base { + const TYPE_IDS: &'static [u64] = &[0x70F323A5414D8639, 0x7F4DF478E28956D1]; + const TYPE_ID: u64 = 0x70F323A5414D8639; + + fn from_base(base: Base) -> Self { + base + } +} + +impl Drop for Base { + fn drop(&mut self) { + if !self.handle.is_null() { + let _ = unsafe { (self.inner.api.libunittest_releaseinstance)(self.handle) }; + } + } +} + +/// A class for unit testing purposes +pub struct TestClass { + parent: Base, +} + +impl std::ops::Deref for TestClass { + type Target = Base; + + fn deref(&self) -> &Base { + &self.parent + } +} + +impl TestClass { + #[allow(dead_code)] + fn from_handle(inner: Arc, handle: Handle) -> Self { + Self { parent: Base::from_handle(inner, handle) } + } + + /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one + /// reference of the handle. This is meant for bindings of components that import this component. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + #[doc(hidden)] + pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self { + Self::from_handle(wrapper.inner.clone(), handle) + } + + /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a + /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller. + /// + /// # Safety + /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`. + pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result { + let inner = &wrapper.inner; + let code = (inner.api.libunittest_acquireinstance)(handle); + inner.check(handle, code)?; + Ok(Self::from_handle(inner.clone(), handle)) + } + + fn into_base(self) -> Base { + self.parent.into_base() + } + + /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise. + pub fn downcast(self) -> std::result::Result { + if self.is::() { + Ok(T::from_base(self.into_base())) + } else { + Err(self) + } + } + + /// Returns the value of the number + /// + /// # Returns + /// * `value` - Returns the new value of this number + pub fn value(&self) -> Result { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_value: f64 = 0.0; + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_value)(__act_handle, &mut __act_out_value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(__act_out_value) + } + + /// Sets the value of the number + /// + /// # Arguments + /// * `value` - The new value of this number + pub fn set_value(&self, value: f64) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_setvalue)(__act_handle, value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Sets the value of the number + /// + /// # Arguments + /// * `value` - The new value of this number + pub fn set_value_int(&self, value: i64) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_setvalueint)(__act_handle, value) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Sets the value of the number by a specified string + /// + /// # Arguments + /// * `value` - The new value of this number + pub fn set_value_string(&self, value: &str) -> Result<()> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_c_value = CString::new(value) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter value contains a NUL byte"))?; + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_setvaluestring)(__act_handle, __act_c_value.as_ptr()) }; + __act_inner.check(__act_handle, __act_code)?; + Ok(()) + } + + /// Passes basic types and outputs them again + /// + /// # Arguments + /// * `value1` - param1 + /// * `value2` - param2 + /// * `value3` - param3 + /// * `value4` - param4 + /// + /// # Returns + /// * `out_value1` - returns param1 + /// * `out_value2` - returns param2 + /// * `out_value3` - returns param3 + /// * `out_value4` - returns param4 + pub fn unit_test1(&self, value1: u8, value2: u16, value3: u32, value4: u64) -> Result<(u8, u16, u32, u64)> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_out_value1: u8 = 0; + let mut __act_out_out_value2: u16 = 0; + let mut __act_out_out_value3: u32 = 0; + let mut __act_out_out_value4: u64 = 0; + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_unittest1)(__act_handle, value1, value2, value3, value4, &mut __act_out_out_value1, &mut __act_out_out_value2, &mut __act_out_out_value3, &mut __act_out_out_value4) }; + __act_inner.check(__act_handle, __act_code)?; + Ok((__act_out_out_value1, __act_out_out_value2, __act_out_out_value3, __act_out_out_value4)) + } + + /// Passes basic types and outputs them again + /// + /// # Arguments + /// * `value1` - param1 + /// * `value2` - param2 + /// * `value3` - param3 + /// * `value4` - param4 + /// + /// # Returns + /// * `out_value1` - returns param1 + /// * `out_value2` - returns param2 + /// * `out_value3` - returns param3 + /// * `out_value4` - returns param4 + pub fn unit_test2(&self, value1: i8, value2: i16, value3: i32, value4: i64) -> Result<(i8, i16, i32, i64)> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_out_value1: i8 = 0; + let mut __act_out_out_value2: i16 = 0; + let mut __act_out_out_value3: i32 = 0; + let mut __act_out_out_value4: i64 = 0; + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_unittest2)(__act_handle, value1, value2, value3, value4, &mut __act_out_out_value1, &mut __act_out_out_value2, &mut __act_out_out_value3, &mut __act_out_out_value4) }; + __act_inner.check(__act_handle, __act_code)?; + Ok((__act_out_out_value1, __act_out_out_value2, __act_out_out_value3, __act_out_out_value4)) + } + + /// Passes basic types and outputs them again + /// + /// # Arguments + /// * `value1` - param1 + /// * `value2` - param2 + /// * `value3` - param3 + /// * `value4` - param4 + /// + /// # Returns + /// * `out_value1` - returns param1 + /// * `out_value2` - returns param2 + /// * `out_value3` - returns param3 + /// * `out_value4` - returns param4 + pub fn unit_test3(&self, value1: bool, value2: f32, value3: f64, value4: TestEnum) -> Result<(bool, f32, f64, TestEnum)> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let mut __act_out_out_value1: bool = false; + let mut __act_out_out_value2: f32 = 0.0; + let mut __act_out_out_value3: f64 = 0.0; + let mut __act_out_out_value4: i32 = 0; + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_unittest3)(__act_handle, value1, value2, value3, value4 as i32, &mut __act_out_out_value1, &mut __act_out_out_value2, &mut __act_out_out_value3, &mut __act_out_out_value4) }; + __act_inner.check(__act_handle, __act_code)?; + Ok((__act_out_out_value1, __act_out_out_value2, __act_out_out_value3, TestEnum::from_raw(__act_out_out_value4)?)) + } + + /// Passes a string and outputs it again + /// + /// # Arguments + /// * `value` - param + /// + /// # Returns + /// * `out_value` - returns param + /// * `return_value` - returns param + pub fn unit_test4(&self, value: &str) -> Result<(String, String)> { + let __act_inner = self.inner_arc(); + let __act_handle = self.handle(); + let __act_c_value = CString::new(value) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter value contains a NUL byte"))?; + let mut __act_needed_out_value: u32 = 0; + let mut __act_filled_out_value: u32 = 0; + let mut __act_buffer_out_value: Vec = Vec::new(); + let mut __act_needed_return_value: u32 = 0; + let mut __act_filled_return_value: u32 = 0; + let mut __act_buffer_return_value: Vec = Vec::new(); + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_unittest4)(__act_handle, __act_c_value.as_ptr(), 0, &mut __act_needed_out_value, ptr::null_mut(), 0, &mut __act_needed_return_value, ptr::null_mut()) }; + __act_inner.check(__act_handle, __act_code)?; + __act_buffer_out_value.resize(__act_needed_out_value as usize, 0); + __act_buffer_return_value.resize(__act_needed_return_value as usize, 0); + let __act_code = unsafe { (__act_inner.api.libunittest_testclass_unittest4)(__act_handle, __act_c_value.as_ptr(), __act_buffer_out_value.len() as u32, &mut __act_filled_out_value, __act_buffer_out_value.as_mut_ptr() as *mut c_char, __act_buffer_return_value.len() as u32, &mut __act_filled_return_value, __act_buffer_return_value.as_mut_ptr() as *mut c_char) }; + __act_inner.check(__act_handle, __act_code)?; + Ok((string_from_buffer(&__act_buffer_out_value, __act_filled_out_value), string_from_buffer(&__act_buffer_return_value, __act_filled_return_value))) + } +} + +impl fmt::Debug for TestClass { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TestClass").field("handle", &self.handle()).finish() + } +} + +impl private::Sealed for TestClass {} + +impl Class for TestClass { + const TYPE_IDS: &'static [u64] = &[0x7F4DF478E28956D1]; + const TYPE_ID: u64 = 0x7F4DF478E28956D1; + + fn from_base(base: Base) -> Self { + TestClass { parent: base } + } +} + +/// Entry point to the LibUnitTest library. Loads the shared library and gives access to its global functions. +#[derive(Clone)] +pub struct Wrapper { + inner: Arc, +} + +impl Wrapper { + /// Loads the library from the given path. + pub fn new(library_path: &str) -> Result { + let lib = unsafe { Library::new(library_path) } + .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?; + let api = unsafe { Api::load(|name| lib.get(name)) }?; + let wrapper = Self { inner: Inner::new(api, Some(lib)) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Creates a wrapper that resolves the functions of the library through the address of its symbol lookup + /// method, as returned by `get_symbol_lookup_method`. This is used to inject a component into another one. + /// The library that provides the symbol lookup method has to stay loaded for as long as the wrapper is used. + /// + /// # Safety + /// `symbol_lookup_method` must be the address of a valid symbol lookup method of a compatible library + /// (`int32 fn(const char*, void**)`), and that library must outlive the wrapper and all objects created from it. + pub unsafe fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + if symbol_lookup_method.is_null() { + return Err(Error::new(error_code::INVALIDPARAM, "the symbol lookup method is null")); + } + type SymbolLookup = unsafe extern "C" fn(*const c_char, *mut *mut c_void) -> i32; + let lookup: SymbolLookup = mem::transmute::<*mut c_void, SymbolLookup>(symbol_lookup_method); + let api = unsafe { + Api::load(|name| { + let cname = CString::new(name).map_err(|_| "symbol contains NUL".to_string())?; + let mut address: *mut c_void = ptr::null_mut(); + let code = lookup(cname.as_ptr(), &mut address); + if code != 0 || address.is_null() { + Err(format!("could not find the symbol {} (error {})", name, code)) + } else { + Ok(address) + } + }) + }?; + let wrapper = Self { inner: Inner::new(api, None) }; + wrapper.check_binary_version()?; + Ok(wrapper) + } + + /// Checks that the loaded library is compatible with the version this binding was generated for. + #[allow(clippy::absurd_extreme_comparisons)] + fn check_binary_version(&self) -> Result<()> { + const BINDING_VERSION_MAJOR: u32 = 1; + const BINDING_VERSION_MINOR: u32 = 0; + let (major, minor, _micro) = self.get_version()?; + if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR { + return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding")); + } + Ok(()) + } + + /// retrieves the binary version of this library. + /// + /// # Returns + /// * `major` - returns the major version of this library + /// * `minor` - returns the minor version of this library + /// * `micro` - returns the micro version of this library + pub fn get_version(&self) -> Result<(u32, u32, u32)> { + let __act_inner = &self.inner; + let mut __act_out_major: u32 = 0; + let mut __act_out_minor: u32 = 0; + let mut __act_out_micro: u32 = 0; + let __act_code = unsafe { (__act_inner.api.libunittest_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((__act_out_major, __act_out_minor, __act_out_micro)) + } + + /// Returns the last error recorded on this object + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Returns + /// * `error_message` - Message of the last error + /// * `has_error` - Is there a last error to query + pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> { + let __act_inner = &self.inner; + let mut __act_needed_error_message: u32 = 0; + let mut __act_filled_error_message: u32 = 0; + let mut __act_buffer_error_message: Vec = Vec::new(); + let mut __act_out_has_error: bool = false; + let __act_code = unsafe { (__act_inner.api.libunittest_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + __act_buffer_error_message.resize(__act_needed_error_message as usize, 0); + let __act_code = unsafe { (__act_inner.api.libunittest_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + /// + /// # Safety + /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired. + pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.libunittest_releaseinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let __act_inner = &self.inner; + let __act_code = unsafe { (__act_inner.api.libunittest_acquireinstance)(instance.handle()) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Injects an imported component for usage within this component + /// + /// # Arguments + /// * `name_space` - NameSpace of the injected component + /// * `symbol_address_method` - Address of the SymbolAddressMethod of the injected component + /// + /// # Safety + /// The library passes symbol_address_method on to callbacks or uses it as is: callback functions must follow the C ABI, + /// must not panic, and pointers must stay valid for as long as the library may use them. + pub unsafe fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + let __act_inner = &self.inner; + let __act_c_name_space = CString::new(name_space) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; + let __act_code = unsafe { (__act_inner.api.libunittest_injectcomponent)(__act_c_name_space.as_ptr(), symbol_address_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(()) + } + + /// Returns the address of the SymbolLookupMethod + /// + /// # Returns + /// * `symbol_lookup_method` - Address of the SymbolAddressMethod + pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { + let __act_inner = &self.inner; + let mut __act_out_symbol_lookup_method: *mut c_void = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libunittest_getsymbollookupmethod)(&mut __act_out_symbol_lookup_method) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(__act_out_symbol_lookup_method) + } + + /// Create a new TestClass instance + /// + /// # Returns + /// * `instance` - New TestClass instance + pub fn create_test_classs(&self) -> Result { + let __act_inner = &self.inner; + let mut __act_out_instance: Handle = ptr::null_mut(); + let __act_code = unsafe { (__act_inner.api.libunittest_createtestclasss)(&mut __act_out_instance) }; + __act_inner.check(ptr::null_mut(), __act_code)?; + Ok(TestClass::from_handle(__act_inner.clone(), __act_out_instance)) + } +} diff --git a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/Cargo.toml b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/Cargo.toml new file mode 100644 index 00000000..e9e98f7d --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "libunittest_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +libunittest = { path = "../../Bindings/Rust" } + +[[bin]] +name = "libunittest_example" +path = "LibUnitTest_example.rs" diff --git a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs new file mode 100644 index 00000000..57dce813 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs @@ -0,0 +1,32 @@ +/*++ + +Copyright (C) 2018 Autodesk + +All rights reserved. + +Abstract: Rust example that exercises the Rust bindings of ACT UnitTest FrameWork. + It only needs the example library of this component. + +Interface version: 1.0.0 + +*/ + +use libunittest::*; +fn main() -> Result<()> { + let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?; + let (a, b, c) = wrapper.get_version()?; + println!("libunittest.version = {}.{}.{}", a, b, c); + let t = wrapper.create_test_classs()?; + t.set_value(2.5)?; + assert_eq!(t.value()?, 2.5); + let r = t.unit_test1(255, 65535, u32::MAX, u64::MAX)?; + println!("{:?}", r); + assert_eq!(r, (255, 65535, u32::MAX, u64::MAX)); + let r = t.unit_test2(-128, -32768, i32::MIN, i64::MIN)?; + assert_eq!(r, (-128, -32768, i32::MIN, i64::MIN)); + let r = t.unit_test3(true, 1.5, -2.25, TestEnum::Option20)?; + println!("{:?}", r); + let (s1, s2) = t.unit_test4("héllo wörld")?; + println!("{:?} {:?}", s1, s2); + Ok(()) +} diff --git a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/build.sh b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/build.sh new file mode 100755 index 00000000..19149fb1 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/build.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -euxo pipefail + +cd "$(dirname "$0")" +source ../../../../../Build/build.inc + +echo "Build Rust example" +export CARGO_TARGET_DIR=build +cargo build + +echo "Test C++ library" +./build/debug/libunittest_example $PWD/../../Implementations/Cpp/build/libunittest$OSLIBEXT + +echo "Test Pascal library" +./build/debug/libunittest_example $PWD/../../Implementations/Pascal/build/libunittest$OSLIBEXT diff --git a/Examples/UnitTest/build.sh b/Examples/UnitTest/build.sh index 0af809f0..cd28f749 100755 --- a/Examples/UnitTest/build.sh +++ b/Examples/UnitTest/build.sh @@ -19,4 +19,5 @@ echo "Build and test bindings examples with C++ library" ./LibUnitTest_component/Examples/Go/build.sh ./LibUnitTest_component/Examples/Pascal/build.sh ./LibUnitTest_component/Examples/Python/build.sh +./LibUnitTest_component/Examples/Rust/build.sh echo "Build and test are done and successful" diff --git a/Examples/UnitTest/libUnitTest.xml b/Examples/UnitTest/libUnitTest.xml index c2eba040..df3b983f 100644 --- a/Examples/UnitTest/libUnitTest.xml +++ b/Examples/UnitTest/libUnitTest.xml @@ -12,6 +12,7 @@ + diff --git a/Examples/Version/libVersion.1.1.0.xml b/Examples/Version/libVersion.1.1.0.xml index 444ac45d..de5f73fb 100644 --- a/Examples/Version/libVersion.1.1.0.xml +++ b/Examples/Version/libVersion.1.1.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.1.2.0.xml b/Examples/Version/libVersion.1.2.0.xml index 522f8548..80456eb8 100644 --- a/Examples/Version/libVersion.1.2.0.xml +++ b/Examples/Version/libVersion.1.2.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.1.3.0.xml b/Examples/Version/libVersion.1.3.0.xml index e013c70a..abeb9c6e 100644 --- a/Examples/Version/libVersion.1.3.0.xml +++ b/Examples/Version/libVersion.1.3.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.2.0.0.xml b/Examples/Version/libVersion.2.0.0.xml index 50382f4d..a1f859ed 100644 --- a/Examples/Version/libVersion.2.0.0.xml +++ b/Examples/Version/libVersion.2.0.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.3.0.0.xml b/Examples/Version/libVersion.3.0.0.xml index f6c44b71..d4ec46cd 100644 --- a/Examples/Version/libVersion.3.0.0.xml +++ b/Examples/Version/libVersion.3.0.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.3.1.0.xml b/Examples/Version/libVersion.3.1.0.xml index a5cc7066..a84ee351 100644 --- a/Examples/Version/libVersion.3.1.0.xml +++ b/Examples/Version/libVersion.3.1.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.4.0.0.xml b/Examples/Version/libVersion.4.0.0.xml index bd798da3..f33ba3d9 100644 --- a/Examples/Version/libVersion.4.0.0.xml +++ b/Examples/Version/libVersion.4.0.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.4.1.0.xml b/Examples/Version/libVersion.4.1.0.xml index 2bc07cf6..0d271e9f 100644 --- a/Examples/Version/libVersion.4.1.0.xml +++ b/Examples/Version/libVersion.4.1.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.4.2.0.xml b/Examples/Version/libVersion.4.2.0.xml index 34aacbc3..7f47de01 100644 --- a/Examples/Version/libVersion.4.2.0.xml +++ b/Examples/Version/libVersion.4.2.0.xml @@ -13,6 +13,7 @@ + diff --git a/Examples/Version/libVersion.xml b/Examples/Version/libVersion.xml index b42f035f..236dff61 100644 --- a/Examples/Version/libVersion.xml +++ b/Examples/Version/libVersion.xml @@ -13,6 +13,7 @@ + diff --git a/README.md b/README.md index ff2e6af4..1ceadafa 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ __Not using ACT for any of these purposes will either make you one of those thre ### Interface Description Language (IDL) The IDL file defines the types and functions of your API and serves as the source for the automatically generated Code. -The exact schema of the IDL and explanation of each element is described in [Documentation/IDL.md](Documentation/IDL.md). +The exact schema of the IDL and explanation of each element is described in [Documentation/IDL.md](Documentation/IDL.md). Notes on the Rust bindings are in [Documentation/Rust.md](Documentation/Rust.md). ### Thin C89-API A thin C89-API is a C header file that declares all functions, structs, enums and constants exported by your software component. The C89-API unambiguously defines the binary interface (ABI) of the component. @@ -53,7 +53,7 @@ Alternatively to 1) build ACT from source ([master](../../tree/master) for a rel
`Build\build.bat` on Windows or
`Build\build.sh` on Unix ## Language Support -ACT supports generation of bindings or implementation stubs for C++, C, Pascal, Golang, NodeJS and Python3. However, not all features of the IDL are yet supported by the individual binding or implementation language: +ACT supports generation of bindings or implementation stubs for C++, C, Pascal, Golang, NodeJS, Python3 and Rust. However, not all features of the IDL are yet supported by the individual binding or implementation language: #### Feature Matrix: Bindings | Binding | Status | Operating Systems | class | scalar type | struct | enumeration | string | basicarray | structarray | Callbacks | Error Message Propagation | Injection | API Documentation | @@ -68,6 +68,7 @@ ACT supports generation of bindings or implementation stubs for C++, C, Pascal, | NodeJS | ![](Documentation/images/O.png) partial support | Win, Linux, MacOS | in,return | in,out,return | in,out,return | in,out,return | in,out,return | ? | ? | - | + | - | - | | C# | ![](Documentation/images/O.png) experimental | Win, Linux, MacOS | in,return | in,out,return | in,out,return | in,out,return | in,out,return | - | - | - | + | - | - | | Java | ![](Documentation/images/Tick.png) experimental | Win, Linux, MacOS | in,return | in,out,return | in,out,return | in,out,return | in,out,return | in,out | in,out | in | + | + | - | +| Rust | ![](Documentation/images/O.png) experimental (tested on MacOS and Linux) | Win, Linux, MacOS | in,return | in,out,return | in,out,return | in,out,return | in,out,return | in,out | in,out | in | + | + | + | | PHP | ![](Documentation/images/X.png) not implemented | Win, Linux, MacOS | - | - | - | - | - | - | - | - | - | - | - | #### Feature Matrix: Implementation Stubs diff --git a/Source/ACT.xsd b/Source/ACT.xsd index 0fdfb5d3..0811af02 100644 --- a/Source/ACT.xsd +++ b/Source/ACT.xsd @@ -229,6 +229,7 @@ + diff --git a/Source/automaticcomponenttoolkit.go b/Source/automaticcomponenttoolkit.go index 0526dcd1..e3e1a0e6 100644 --- a/Source/automaticcomponenttoolkit.go +++ b/Source/automaticcomponenttoolkit.go @@ -276,6 +276,28 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } } + case "Rust": + { + outputFolderBindingRust := outputFolderBindings + "/Rust" + err = os.MkdirAll(outputFolderBindingRust, os.ModePerm) + if err != nil { + return err + } + + outputFolderExampleRust := "" + if !suppressExamples { + outputFolderExampleRust = outputFolderExamples + "/Rust" + err = os.MkdirAll(outputFolderExampleRust, os.ModePerm) + if err != nil { + return err + } + } + + err = BuildBindingRustDynamic(component, outputFolderBindingRust, outputFolderExampleRust, indentString) + if err != nil { + return err + } + } case "Node": { diff --git a/Source/buildbindingrust.go b/Source/buildbindingrust.go new file mode 100644 index 00000000..1631d2c7 --- /dev/null +++ b/Source/buildbindingrust.go @@ -0,0 +1,2296 @@ +/*++ + +Copyright (C) 2026 Autodesk Inc. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--*/ + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// buildbindingrust.go +// functions to generate dynamic Rust bindings of a library's API in form of explicitly loaded +// function handles. +// +// The generated crate exposes +// - a Wrapper type that loads the shared library from an explicit path (like the other bindings), +// - one struct per class (derived classes dereference to their parent class, the base class +// releases the instance when it is dropped), +// - plain Rust enums and #[repr(C)] structs, +// - an Error type carrying the error code and the message reported by the library. +// Every method returns a Result and follows the usual Rust naming conventions (snake_case). +////////////////////////////////////////////////////////////////////////////////////////////////////// + +package main + +import ( + "fmt" + "log" + "os" + "path" + "strconv" + "strings" + "unicode" +) + +var rustKeywords = map[string]bool{ + "as": true, "break": true, "const": true, "continue": true, "crate": true, "else": true, "enum": true, + "extern": true, "false": true, "fn": true, "for": true, "if": true, "impl": true, "in": true, "let": true, + "loop": true, "match": true, "mod": true, "move": true, "mut": true, "pub": true, "ref": true, + "return": true, "self": true, "Self": true, "static": true, "struct": true, "super": true, "trait": true, + "true": true, "type": true, "unsafe": true, "use": true, "where": true, "while": true, "async": true, + "await": true, "dyn": true, "abstract": true, "become": true, "box": true, "do": true, "final": true, + "macro": true, "override": true, "priv": true, "typeof": true, "unsized": true, "virtual": true, + "yield": true, "try": true, +} + +// rl writes a line of already formatted text. Percent signs must not be interpreted as format verbs. +func rl(w LanguageWriter, line string) { + w.Writeln(strings.ReplaceAll(line, "%", "%%")) +} + +// rustDoc makes IDL text safe to be written into a single line of a Rust doc comment. +func rustDoc(text string) string { + return strings.TrimSpace(sanitizeCommentText(text, "\n")) +} + +// rustSnakeCase converts a CamelCase IDL name into a snake_case Rust identifier. +func rustSnakeCase(name string) string { + runes := []rune(name) + var b strings.Builder + for i, r := range runes { + if unicode.IsUpper(r) { + if i > 0 { + prev := runes[i-1] + nextLower := i+1 < len(runes) && unicode.IsLower(runes[i+1]) + // a plural acronym such as "IDs" keeps its trailing "s" and is not split + if nextLower && runes[i+1] == 's' && (i+2 >= len(runes) || !unicode.IsLower(runes[i+2])) { + nextLower = false + } + if unicode.IsLower(prev) || unicode.IsDigit(prev) || (unicode.IsUpper(prev) && nextLower) { + b.WriteRune('_') + } + } + b.WriteRune(unicode.ToLower(r)) + } else { + b.WriteRune(r) + } + } + s := b.String() + if rustKeywords[s] { + s += "_" + } + return s +} + +// rustTypeName turns a class name from the IDL (that might refer to another component) into a Rust type name. +func rustTypeName(className string) string { + if namespace, name, ok := rustImportedClass(className); ok { + return strings.ToLower(namespace) + "::" + name + } + return className +} + +// rustImportedClass splits the name of a class of an imported component ("Namespace:Class"). +func rustImportedClass(className string) (string, string, bool) { + parts := strings.SplitN(className, ":", 2) + if len(parts) == 2 && len(parts[0]) > 0 { + return parts[0], parts[1], true + } + return "", className, false +} + +// rustImportedNamespaces returns the namespaces of the imported components in a stable order. +func rustImportedNamespaces(component ComponentDefinition) []string { + namespaces := []string{} + for _, importComponent := range component.ImportComponents { + namespaces = append(namespaces, importComponent.Namespace) + } + return namespaces +} + +// rustErrorConst returns the expression for a well known error code of the component. +func rustErrorConst(component ComponentDefinition, name string, fallback int) string { + for _, e := range component.Errors.Errors { + if e.Name == name { + return "error_code::" + name + } + } + return fmt.Sprintf("%d", fallback) +} + +func findRustGlobalMethod(component ComponentDefinition, name string) (ComponentDefinitionMethod, bool) { + if len(name) == 0 { + return ComponentDefinitionMethod{}, false + } + for _, method := range component.Global.Methods { + if method.MethodName == name { + return method, true + } + } + return ComponentDefinitionMethod{}, false +} + +// BuildBindingRustDynamic builds dynamic Rust bindings of a library's API in form of explicitly loaded +// function handles. +func BuildBindingRustDynamic(component ComponentDefinition, outputFolder string, outputFolderExample string, indentString string) error { + forceRecreation := false + + libraryname := component.LibraryName + + srcFolder := path.Join(outputFolder, "src") + err := os.MkdirAll(srcFolder, os.ModePerm) + if err != nil { + return err + } + + rustLibFile := path.Join(srcFolder, "lib.rs") + log.Printf("Creating \"%s\"", rustLibFile) + libfile, err := CreateLanguageFile(rustLibFile, indentString) + if err != nil { + return err + } + libfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated Rust file in order to allow an easy\n use of %s", libraryname), + true) + err = buildRustBinding(component, libfile) + if err != nil { + return err + } + + cargoFile := path.Join(outputFolder, "Cargo.toml") + log.Printf("Creating \"%s\"", cargoFile) + cargofile, err := CreateLanguageFile(cargoFile, indentString) + if err != nil { + return err + } + buildRustCargo(component, cargofile) + + if len(outputFolderExample) > 0 { + crateName := strings.ToLower(component.NameSpace) + + exampleCargoFile := path.Join(outputFolderExample, "Cargo.toml") + if forceRecreation || !FileExists(exampleCargoFile) { + log.Printf("Creating \"%s\"", exampleCargoFile) + examplecargofile, err := CreateLanguageFile(exampleCargoFile, indentString) + if err != nil { + return err + } + buildRustExampleCargo(component, examplecargofile) + } else { + log.Printf("Omitting recreation of Rust example \"%s\"", exampleCargoFile) + } + + exampleFile := path.Join(outputFolderExample, fmt.Sprintf("%s_example.rs", component.NameSpace)) + if forceRecreation || !FileExists(exampleFile) { + log.Printf("Creating \"%s\"", exampleFile) + examplefile, err := CreateLanguageFile(exampleFile, indentString) + if err != nil { + return err + } + examplefile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated Rust application that demonstrates the\n usage of the Rust bindings of %s", libraryname), + true) + err = buildRustExample(component, examplefile, crateName) + if err != nil { + return err + } + } else { + log.Printf("Omitting recreation of Rust example \"%s\"", exampleFile) + } + } + + return nil +} + +func buildRustCargo(component ComponentDefinition, w LanguageWriter) { + rl(w, "[package]") + rl(w, fmt.Sprintf("name = \"%s\"", strings.ToLower(component.NameSpace))) + rl(w, fmt.Sprintf("version = \"%s\"", component.Version)) + rl(w, "edition = \"2021\"") + // older compilers build the crate too, but warn about nested unsafe blocks + rl(w, "rust-version = \"1.65\"") + rl(w, fmt.Sprintf("description = %s", strconv.Quote("Rust bindings of "+component.LibraryName))) + if len(component.ImportComponents) > 0 { + rl(w, "") + rl(w, "[dependencies]") + for _, namespace := range rustImportedNamespaces(component) { + rl(w, fmt.Sprintf("%s = { path = \"../../../%s_component/Bindings/Rust\" }", strings.ToLower(namespace), namespace)) + } + } +} + +func buildRustExampleCargo(component ComponentDefinition, w LanguageWriter) { + crateName := strings.ToLower(component.NameSpace) + rl(w, "[package]") + rl(w, fmt.Sprintf("name = \"%s_example\"", crateName)) + rl(w, "version = \"0.1.0\"") + rl(w, "edition = \"2021\"") + rl(w, "") + rl(w, "[dependencies]") + rl(w, fmt.Sprintf("%s = { path = \"../../Bindings/Rust\" }", crateName)) + for _, namespace := range rustImportedNamespaces(component) { + rl(w, fmt.Sprintf("%s = { path = \"../../../%s_component/Bindings/Rust\" }", strings.ToLower(namespace), namespace)) + } + rl(w, "") + rl(w, "[[bin]]") + rl(w, fmt.Sprintf("name = \"%s_example\"", crateName)) + rl(w, fmt.Sprintf("path = \"%s_example.rs\"", component.NameSpace)) +} + +func buildRustExample(component ComponentDefinition, w LanguageWriter, crateName string) error { + rl(w, fmt.Sprintf("use %s::Wrapper;", crateName)) + rl(w, "use std::env;") + rl(w, "use std::process;") + rl(w, "") + rl(w, "fn main() {") + rl(w, " let args: Vec = env::args().collect();") + usage := fmt.Sprintf("", component.BaseName) + for _, namespace := range rustImportedNamespaces(component) { + usage += fmt.Sprintf(" ", namespace) + } + rl(w, fmt.Sprintf(" if args.len() < %d {", 2+len(component.ImportComponents))) + rl(w, fmt.Sprintf(" eprintln!(\"usage: {} %s\", args[0]);", usage)) + rl(w, " process::exit(1);") + rl(w, " }") + rl(w, " let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| {") + rl(w, " eprintln!(\"{}\", e);") + rl(w, " process::exit(1);") + rl(w, " });") + rl(w, "") + if len(component.Global.VersionMethod) > 0 { + rl(w, fmt.Sprintf(" let (major, minor, micro) = wrapper.%s().expect(\"could not query the version\");", rustSnakeCase(component.Global.VersionMethod))) + mutable := "" + if len(component.Global.PrereleaseMethod) > 0 || len(component.Global.BuildinfoMethod) > 0 { + mutable = "mut " + } + rl(w, fmt.Sprintf(" let %sversion = format!(\"%s.version = {}.{}.{}\", major, minor, micro);", mutable, component.BaseName)) + if len(component.Global.PrereleaseMethod) > 0 { + rl(w, fmt.Sprintf(" let (has_info, info) = wrapper.%s().expect(\"could not query the prerelease information\");", rustSnakeCase(component.Global.PrereleaseMethod))) + rl(w, " if has_info {") + rl(w, " version.push_str(&format!(\"-{}\", info));") + rl(w, " }") + } + if len(component.Global.BuildinfoMethod) > 0 { + rl(w, fmt.Sprintf(" let (has_info, info) = wrapper.%s().expect(\"could not query the build information\");", rustSnakeCase(component.Global.BuildinfoMethod))) + rl(w, " if has_info {") + rl(w, " version.push_str(&format!(\"+{}\", info));") + rl(w, " }") + } + rl(w, " println!(\"{}\", version);") + } else { + if len(component.ImportComponents) == 0 { + rl(w, " let _ = wrapper;") + } + rl(w, fmt.Sprintf(" println!(\"%s library loaded\");", component.BaseName)) + } + // load and inject the imported components + for i, namespace := range rustImportedNamespaces(component) { + lower := strings.ToLower(namespace) + rl(w, "") + rl(w, fmt.Sprintf(" let %s = %s::Wrapper::new(&args[%d]).unwrap_or_else(|e| {", lower, lower, 2+i)) + rl(w, " eprintln!(\"{}\", e);") + rl(w, " process::exit(1);") + rl(w, " });") + if imported, ok := component.ImportedComponentDefinitions[namespace]; ok && len(imported.Global.VersionMethod) > 0 { + rl(w, fmt.Sprintf(" let (major, minor, micro) = %s.%s().expect(\"could not query the version\");", lower, rustSnakeCase(imported.Global.VersionMethod))) + rl(w, fmt.Sprintf(" println!(\"%s.version = {}.{}.{}\", major, minor, micro);", imported.BaseName)) + } + if imported, ok := component.ImportedComponentDefinitions[namespace]; ok && len(imported.Global.SymbolLookupMethod) > 0 && len(component.Global.InjectionMethod) > 0 { + rl(w, fmt.Sprintf(" wrapper.inject_%s(&%s).expect(\"could not inject the component\");", lower, lower)) + } + } + rl(w, "}") + return nil +} + +const rustDynlibTemplate = `use std::ffi::CString; +use std::fmt; +use std::mem; +use std::os::raw::{c_char, c_void}; +use std::ptr; +use std::sync::Arc; + +#[cfg(unix)] +mod dynlib { + use super::*; + use std::ffi::CStr; + type DynResult = std::result::Result; + #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))] + extern "C" { + fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; + fn dlclose(handle: *mut c_void) -> i32; + fn dlerror() -> *const c_char; + } + const RTLD_NOW: i32 = 2; + pub struct Library { + handle: *mut c_void, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = dlopen(cpath.as_ptr(), RTLD_NOW); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = dlsym(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + dlclose(self.handle); + } + } + } + } + fn last_error() -> String { + unsafe { + let err = dlerror(); + if err.is_null() { + "unknown dlerror".to_string() + } else { + CStr::from_ptr(err).to_string_lossy().into_owned() + } + } + } +} + +#[cfg(windows)] +mod dynlib { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + type DynResult = std::result::Result; + type HModule = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(lpLibFileName: *const u16) -> HModule; + fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void; + fn FreeLibrary(hModule: HModule) -> i32; + fn GetLastError() -> u32; + } + pub struct Library { + handle: HModule, + } + impl Library { + pub unsafe fn new(path: &str) -> DynResult { + if path.contains('\0') { + return Err("library path contains NUL".to_string()); + } + let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect(); + let handle = LoadLibraryW(wide.as_ptr()); + if handle.is_null() { + return Err(last_error()); + } + Ok(Self { handle }) + } + pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> { + let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?; + let sym = GetProcAddress(self.handle, csym.as_ptr()); + if sym.is_null() { + return Err(last_error()); + } + Ok(sym) + } + } + impl Drop for Library { + fn drop(&mut self) { + unsafe { + if !self.handle.is_null() { + FreeLibrary(self.handle); + } + } + } + } + fn last_error() -> String { + let code = unsafe { GetLastError() }; + format!("Win32 error {}", code) + } +} + +use dynlib::Library; + +/// Raw handle of an instance living inside of the library. +pub type Handle = *mut c_void; + +/// Converts a buffer filled by the library (including the trailing zero) into a String. +#[allow(dead_code)] +fn string_from_buffer(buffer: &[u8], filled: u32) -> String { + let length = (filled as usize).saturating_sub(1).min(buffer.len()); + String::from_utf8_lossy(&buffer[..length]).into_owned() +} +` + +// rustBasicType returns the Rust type of the basic IDL types. +func rustBasicType(paramType string) (string, error) { + switch paramType { + case "uint8": + return "u8", nil + case "uint16": + return "u16", nil + case "uint32": + return "u32", nil + case "uint64": + return "u64", nil + case "int8": + return "i8", nil + case "int16": + return "i16", nil + case "int32": + return "i32", nil + case "int64": + return "i64", nil + case "bool": + return "bool", nil + case "single": + return "f32", nil + case "double": + return "f64", nil + case "pointer": + return "*mut c_void", nil + } + return "", fmt.Errorf("invalid basic type \"%s\" for Rust", paramType) +} + +func rustZeroValue(paramType string) string { + switch paramType { + case "bool": + return "false" + case "single", "double": + return "0.0" + case "pointer": + return "ptr::null_mut()" + } + return "0" +} + +func isRustBasicType(paramType string) bool { + _, err := rustBasicType(paramType) + return err == nil +} + +// rustStructMemberType returns the type of a member of a #[repr(C)] struct. +func rustStructMemberType(member ComponentDefinitionMember) (string, error) { + var typeString string + var err error + switch member.Type { + case "enum", "struct": + typeString = rustTypeName(member.Class) + default: + typeString, err = rustBasicType(member.Type) + if err != nil { + return "", err + } + } + rows := member.Rows + cols := member.Columns + if rows == 0 { + rows = 1 + } + if cols == 0 { + cols = 1 + } + if rows == 1 && cols == 1 { + return typeString, nil + } + if cols == 1 { + return fmt.Sprintf("[%s; %d]", typeString, rows), nil + } + // same index order as the other bindings: [column][row] + return fmt.Sprintf("[[%s; %d]; %d]", typeString, rows, cols), nil +} + +// rustTypeFromCParamType maps the type of a parameter of the C ABI to the type used in the function table. +func rustTypeFromCParamType(cType string, component ComponentDefinition) string { + nameSpace := component.NameSpace + t := strings.TrimSpace(cType) + isConst := strings.HasPrefix(t, "const ") + if isConst { + t = strings.TrimSpace(strings.TrimPrefix(t, "const ")) + } + isPtr := strings.HasSuffix(t, "*") + if isPtr { + t = strings.TrimSpace(strings.TrimSuffix(t, "*")) + } + + base := "" + switch { + case t == "char": + base = "c_char" + case t == "bool": + base = "bool" + case strings.HasSuffix(t, "_uint8"): + base = "u8" + case strings.HasSuffix(t, "_uint16"): + base = "u16" + case strings.HasSuffix(t, "_uint32"): + base = "u32" + case strings.HasSuffix(t, "_uint64"): + base = "u64" + case strings.HasSuffix(t, "_int8"): + base = "i8" + case strings.HasSuffix(t, "_int16"): + base = "i16" + case strings.HasSuffix(t, "_int32"): + base = "i32" + case strings.HasSuffix(t, "_int64"): + base = "i64" + case strings.HasSuffix(t, "_single"): + base = "f32" + case strings.HasSuffix(t, "_double"): + base = "f64" + case strings.HasSuffix(t, "_pvoid"): + // the typedef already is a void pointer, a pointer to it is a pointer to a pointer + base = "*mut c_void" + case strings.HasPrefix(t, "e"+nameSpace): + // enumerations travel as plain integers and are converted by the wrappers + base = "i32" + case strings.HasPrefix(t, "s"+nameSpace): + base = rustTypeName(strings.TrimPrefix(t, "s"+nameSpace)) + case strings.HasPrefix(t, nameSpace+"_"): + base = "Handle" + case strings.HasPrefix(t, nameSpace): + base = rustTypeName(strings.TrimPrefix(t, nameSpace)) + default: + if mapped, ok := rustImportedCType(t, component); ok { + base = mapped + } else { + base = t + } + } + + if isPtr { + if isConst { + return "*const " + base + } + return "*mut " + base + } + return base +} + +// rustImportedCType maps a C ABI type belonging to an imported component (enum, struct, handle, or callback). +func rustImportedCType(cType string, component ComponentDefinition) (string, bool) { + for _, namespace := range rustImportedNamespaces(component) { + lower := strings.ToLower(namespace) + switch { + case strings.HasPrefix(cType, "e"+namespace): + return "i32", true + case strings.HasPrefix(cType, "s"+namespace): + return lower + "::" + strings.TrimPrefix(cType, "s"+namespace), true + case strings.HasPrefix(cType, namespace+"_"): + return "Handle", true + case strings.HasPrefix(cType, namespace): + return lower + "::" + strings.TrimPrefix(cType, namespace), true + } + } + return "", false +} + +func rustCParamTypes(method ComponentDefinitionMethod, component ComponentDefinition, className string) ([]string, error) { + nameSpace := component.NameSpace + types := []string{} + for _, p := range method.Params { + cParams, err := generateCCPPParameter(p, className, method.MethodName, nameSpace, false) + if err != nil { + return nil, err + } + for _, cParam := range cParams { + types = append(types, rustTypeFromCParamType(cParam.ParamType, component)) + } + } + return types, nil +} + +func buildRustBinding(component ComponentDefinition, w LanguageWriter) error { + NameSpace := component.NameSpace + + if len(component.Classes) > 0 && len(component.Global.BaseClassName) == 0 { + return fmt.Errorf("the Rust binding requires a base class for the component %s", NameSpace) + } + + for _, line := range strings.Split(rustDynlibTemplate, "\n") { + rl(w, line) + } + if len(component.ImportComponents) > 0 || len(component.Functions) > 0 { + rl(w, "use std::sync::Mutex;") + rl(w, "") + } + + buildRustErrors(component, w) + buildRustEnums(component, w) + err := buildRustStructs(component, w) + if err != nil { + return err + } + err = buildRustFunctionTypes(component, w) + if err != nil { + return err + } + err = buildRustApi(component, w) + if err != nil { + return err + } + if rustHasClassTypeId(component) { + rl(w, "mod private {") + rl(w, " pub trait Sealed {}") + rl(w, "}") + rl(w, "") + rl(w, "/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class") + rl(w, fmt.Sprintf("/// with `%s::is` and `downcast`, which Rust cannot do automatically for returned instances.", rustTypeName(component.Global.BaseClassName))) + rl(w, "pub trait Class: private::Sealed + Sized {") + rl(w, " #[doc(hidden)]") + rl(w, " const TYPE_IDS: &'static [u64];") + rl(w, " #[doc(hidden)]") + rl(w, " const TYPE_ID: u64;") + rl(w, " #[doc(hidden)]") + rl(w, fmt.Sprintf(" fn from_base(base: %s) -> Self;", rustTypeName(component.Global.BaseClassName))) + rl(w, "}") + rl(w, "") + } + for _, class := range component.Classes { + err = buildRustClass(component, class, w) + if err != nil { + return err + } + } + return buildRustWrapper(component, w) +} + +func buildRustErrors(component ComponentDefinition, w LanguageWriter) { + NameSpace := component.NameSpace + + rl(w, "/// Error codes reported by the library.") + rl(w, "pub mod error_code {") + rl(w, " pub const SUCCESS: i32 = 0;") + for _, e := range component.Errors.Errors { + rl(w, fmt.Sprintf(" pub const %s: i32 = %d;", e.Name, e.Code)) + } + rl(w, "}") + rl(w, "") + rl(w, fmt.Sprintf("/// Error returned by the %s library or by the Rust binding.", NameSpace)) + rl(w, "#[derive(Clone, PartialEq, Eq)]") + rl(w, "pub struct Error {") + rl(w, " pub code: i32,") + rl(w, " pub message: String,") + rl(w, "}") + rl(w, "") + rl(w, "impl Error {") + rl(w, " pub fn new(code: i32, message: impl Into) -> Self {") + rl(w, " Self { code, message: message.into() }") + rl(w, " }") + rl(w, "") + rl(w, " /// Name of the error code.") + rl(w, " pub fn name(&self) -> &'static str {") + rl(w, " match self.code {") + rl(w, " error_code::SUCCESS => \"SUCCESS\",") + seenName := map[int]bool{0: true} + for _, e := range component.Errors.Errors { + if seenName[e.Code] { + continue + } + seenName[e.Code] = true + rl(w, fmt.Sprintf(" error_code::%s => \"%s\",", e.Name, e.Name)) + } + rl(w, " _ => \"UNKNOWN\",") + rl(w, " }") + rl(w, " }") + rl(w, "") + rl(w, " /// Generic description of the error code.") + rl(w, " pub fn description(&self) -> &'static str {") + rl(w, " match self.code {") + rl(w, " error_code::SUCCESS => \"success\",") + seenDesc := map[int]bool{0: true} + for _, e := range component.Errors.Errors { + if seenDesc[e.Code] { + continue + } + seenDesc[e.Code] = true + rl(w, fmt.Sprintf(" error_code::%s => %s,", e.Name, strconv.Quote(rustDoc(e.Description)))) + } + rl(w, " _ => \"unknown error\",") + rl(w, " }") + rl(w, " }") + rl(w, "}") + rl(w, "") + rl(w, "impl fmt::Display for Error {") + rl(w, " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {") + rl(w, " let message = if self.message.is_empty() { self.description() } else { self.message.as_str() };") + rl(w, fmt.Sprintf(" write!(f, \"%sError {} ({}): {}\", self.name(), self.code, message)", NameSpace)) + rl(w, " }") + rl(w, "}") + rl(w, "") + rl(w, "// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text.") + rl(w, "impl fmt::Debug for Error {") + rl(w, " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {") + rl(w, " fmt::Display::fmt(self, f)") + rl(w, " }") + rl(w, "}") + rl(w, "") + rl(w, "impl std::error::Error for Error {}") + rl(w, "") + for _, namespace := range rustImportedNamespaces(component) { + lower := strings.ToLower(namespace) + rl(w, fmt.Sprintf("impl From<%s::Error> for Error {", lower)) + rl(w, fmt.Sprintf(" fn from(e: %s::Error) -> Self {", lower)) + rl(w, " Error::new(e.code, e.message)") + rl(w, " }") + rl(w, "}") + rl(w, "") + } + rl(w, "pub type Result = std::result::Result;") + rl(w, "") +} + +func buildRustEnums(component ComponentDefinition, w LanguageWriter) { + invalidCast := rustErrorConst(component, "INVALIDCAST", 3) + for _, enum := range component.Enums { + name := rustTypeName(enum.Name) + rl(w, "#[allow(non_camel_case_types)]") + rl(w, "#[repr(i32)]") + rl(w, "#[derive(Debug, Copy, Clone, PartialEq, Eq)]") + rl(w, fmt.Sprintf("pub enum %s {", name)) + for _, option := range enum.Options { + rl(w, fmt.Sprintf(" %s = %d,", option.Name, option.Value)) + } + rl(w, "}") + rl(w, "") + rl(w, fmt.Sprintf("impl %s {", name)) + rl(w, " #[doc(hidden)]") + rl(w, " #[allow(dead_code)]") + rl(w, " pub fn from_raw(value: i32) -> Result {") + rl(w, " match value {") + seen := map[int]bool{} + for _, option := range enum.Options { + if seen[option.Value] { + continue + } + seen[option.Value] = true + rl(w, fmt.Sprintf(" %d => Ok(%s::%s),", option.Value, name, option.Name)) + } + rl(w, fmt.Sprintf(" _ => Err(Error::new(%s, \"invalid enumeration value for %s\")),", invalidCast, name)) + rl(w, " }") + rl(w, " }") + rl(w, "}") + rl(w, "") + } +} + +// rustStructLayout returns the fixed-byte size, pointer count, alignment, and whether the natural layout of C +// yields the same layout as the packed C ABI (i.e. whether no padding would be inserted). +func rustStructLayout(component ComponentDefinition, name string) (uint64, uint64, uint64, bool) { + if ns, structName, ok := rustImportedClass(name); ok { + if imported, exists := component.ImportedComponentDefinitions[ns]; exists { + return rustStructLayout(imported, structName) + } + return 0, 0, 1, false + } + var structure *ComponentDefinitionStruct + for i := range component.Structs { + if component.Structs[i].Name == name { + structure = &component.Structs[i] + } + } + if structure == nil { + return 0, 0, 1, false + } + var fixedBytes, ptrCount, maxAlign uint64 = 0, 0, 1 + natural := true + for _, m := range structure.Members { + var size, ptrs, align uint64 + switch m.Type { + case "uint8", "int8", "bool": + size, align = 1, 1 + case "uint16", "int16": + size, align = 2, 2 + case "uint32", "int32", "single", "enum": + size, align = 4, 4 + case "uint64", "int64", "double": + size, align = 8, 8 + case "struct": + var nested bool + size, ptrs, align, nested = rustStructLayout(component, m.Class) + if !nested { + align = 1 + natural = false + } + default: + // pointers depend on the platform + ptrs, align = 1, 8 + natural = false + } + count := uint64(1) + if m.Rows > 0 { + count *= uint64(m.Rows) + } + if m.Columns > 0 { + count *= uint64(m.Columns) + } + if ptrCount > 0 || fixedBytes%align != 0 { + natural = false + } + fixedBytes += size * count + ptrCount += ptrs * count + if align > maxAlign { + maxAlign = align + } + } + if ptrCount > 0 || fixedBytes%maxAlign != 0 { + natural = false + } + return fixedBytes, ptrCount, maxAlign, natural +} + +func buildRustStructs(component ComponentDefinition, w LanguageWriter) error { + for _, s := range component.Structs { + // the C ABI of ACT components packs structs without padding (#pragma pack(1)). Where the natural layout of + // C has no padding either, a plain repr(C) struct is used, which allows to borrow its fields. + fixedBytes, ptrCount, _, natural := rustStructLayout(component, s.Name) + if natural { + rl(w, "#[repr(C)]") + } else { + rl(w, "#[repr(C, packed)]") + } + rl(w, "#[derive(Debug, Copy, Clone, PartialEq)]") + rl(w, fmt.Sprintf("pub struct %s {", rustTypeName(s.Name))) + for _, m := range s.Members { + memberType, err := rustStructMemberType(m) + if err != nil { + return err + } + rl(w, fmt.Sprintf(" pub %s: %s,", rustSnakeCase(m.Name), memberType)) + } + rl(w, "}") + rl(w, "") + rl(w, "// the size has to match the packed layout of the C ABI") + sizeExpr := fmt.Sprintf("%d", fixedBytes) + if ptrCount > 0 { + ptrExpr := "std::mem::size_of::<*mut c_void>()" + if ptrCount > 1 { + ptrExpr = fmt.Sprintf("%d * %s", ptrCount, ptrExpr) + } + if fixedBytes == 0 { + sizeExpr = ptrExpr + } else { + sizeExpr = fmt.Sprintf("%d + %s", fixedBytes, ptrExpr) + } + } + rl(w, fmt.Sprintf("const _: () = assert!(std::mem::size_of::<%s>() == %s);", rustTypeName(s.Name), sizeExpr)) + rl(w, "") + if rustStructNeedsRaw(component, s.Name) { + if err := buildRustRawStruct(component, s, natural, w); err != nil { + return err + } + } + } + return nil +} + +// rustStructNeedsRaw tells whether a struct contains enumerations (directly or through other structs). The library +// may write any integer into an enumeration member, which is not a valid value of a Rust enum. Such structs are +// received into a twin with integer members, whose values are checked on conversion. +func rustStructNeedsRaw(component ComponentDefinition, name string) bool { + if ns, structName, ok := rustImportedClass(name); ok { + if imported, exists := component.ImportedComponentDefinitions[ns]; exists { + return rustStructNeedsRaw(imported, structName) + } + return false + } + for _, s := range component.Structs { + if s.Name != name { + continue + } + for _, m := range s.Members { + if m.Type == "enum" || (m.Type == "struct" && m.Class != name && rustStructNeedsRaw(component, m.Class)) { + return true + } + } + } + return false +} + +func rustRawStructName(name string) string { + if namespace, structName, ok := rustImportedClass(name); ok { + return strings.ToLower(namespace) + "::Raw" + structName + } + return "Raw" + rustTypeName(name) +} + +// rustCheckedExpr builds the expression converting the (possibly nested array of) raw value to the checked one. +func rustCheckedExpr(component ComponentDefinition, m ComponentDefinitionMember, value string) string { + rows, cols := m.Rows, m.Columns + if rows == 0 { + rows = 1 + } + if cols == 0 { + cols = 1 + } + convert := func(v string) string { + switch { + case m.Type == "enum": + return fmt.Sprintf("%s::from_raw(%s)?", rustTypeName(m.Class), v) + case m.Type == "struct" && rustStructNeedsRaw(component, m.Class): + return fmt.Sprintf("%s.into_checked()?", v) + } + return v + } + rowsOf := func(v string) string { + if rows == 1 { + return convert(v) + } + return fmt.Sprintf("{ let row = %s; let mut out = Vec::with_capacity(%d); for item in row { out.push(%s); } out.try_into().map_err(|_| Error::new(__act_invalid_cast, \"array size\"))? }", v, rows, convert("item")) + } + if cols == 1 { + return rowsOf(value) + } + return fmt.Sprintf("{ let columns = %s; let mut out = Vec::with_capacity(%d); for column in columns { out.push(%s); } out.try_into().map_err(|_| Error::new(__act_invalid_cast, \"array size\"))? }", value, cols, rowsOf("column")) +} + +func buildRustRawStruct(component ComponentDefinition, s ComponentDefinitionStruct, natural bool, w LanguageWriter) error { + name := rustTypeName(s.Name) + raw := rustRawStructName(s.Name) + invalidCast := rustErrorConst(component, "INVALIDCAST", 3) + rl(w, fmt.Sprintf("/// %s as written by the library: enumerations are plain integers until they are checked.", name)) + rl(w, "#[doc(hidden)]") + if natural { + rl(w, "#[repr(C)]") + } else { + rl(w, "#[repr(C, packed)]") + } + rl(w, "#[derive(Copy, Clone)]") + rl(w, fmt.Sprintf("pub struct %s {", raw)) + for _, m := range s.Members { + member := m + var memberType string + switch { + case m.Type == "enum": + member.Type = "int32" + t, err := rustStructMemberType(member) + if err != nil { + return err + } + memberType = t + case m.Type == "struct" && rustStructNeedsRaw(component, m.Class): + if ns, sn, ok := rustImportedClass(m.Class); ok { + member.Class = ns + ":Raw" + sn + } else { + member.Class = "Raw" + m.Class + } + t, err := rustStructMemberType(member) + if err != nil { + return err + } + memberType = t + default: + t, err := rustStructMemberType(m) + if err != nil { + return err + } + memberType = t + } + rl(w, fmt.Sprintf(" pub %s: %s,", rustSnakeCase(m.Name), memberType)) + } + rl(w, "}") + rl(w, "") + rl(w, fmt.Sprintf("impl %s {", raw)) + rl(w, " #[doc(hidden)]") + rl(w, " #[allow(dead_code)]") + rl(w, fmt.Sprintf(" pub fn into_checked(self) -> Result<%s> {", name)) + hasArray := false + for _, m := range s.Members { + if m.Rows > 1 || m.Columns > 1 { + hasArray = true + } + } + if hasArray { + rl(w, fmt.Sprintf(" let __act_invalid_cast = %s;", invalidCast)) + } + rl(w, fmt.Sprintf(" Ok(%s {", name)) + for _, m := range s.Members { + field := rustSnakeCase(m.Name) + rl(w, fmt.Sprintf(" %s: %s,", field, rustCheckedExpr(component, m, "self."+field))) + } + rl(w, " })") + rl(w, " }") + rl(w, "}") + rl(w, "") + return nil +} + +func buildRustFunctionTypes(component ComponentDefinition, w LanguageWriter) error { + for _, functiontype := range component.Functions { + types := []string{} + for _, p := range functiontype.Params { + cParams, err := generateCCPPParameter(p, "", functiontype.FunctionName, component.NameSpace, false) + if err != nil { + return err + } + for _, cParam := range cParams { + types = append(types, rustTypeFromCParamType(cParam.ParamType, component)) + } + } + rl(w, fmt.Sprintf("/// %s", rustDoc(functiontype.FunctionDescription))) + rl(w, "///") + rl(w, "/// The function is called by the library and has to follow the C ABI: it cannot return a `Result`,") + rl(w, "/// so failures have to be reported through the output parameters. It must not panic, as a panic") + rl(w, "/// that would unwind into the library aborts the process.") + rl(w, fmt.Sprintf("pub type %s = unsafe extern \"C\" fn(%s);", rustTypeName(functiontype.FunctionName), strings.Join(types, ", "))) + rl(w, "") + } + return nil +} + +type rustExport struct { + field string + signature string +} + +func rustExports(component ComponentDefinition) ([]rustExport, error) { + NameSpace := component.NameSpace + exports := []rustExport{} + for _, method := range component.Global.Methods { + types, err := rustCParamTypes(method, component, "Wrapper") + if err != nil { + return nil, err + } + exports = append(exports, rustExport{ + field: GetCExportName(NameSpace, "Wrapper", method, true), + signature: fmt.Sprintf("unsafe extern \"C\" fn(%s) -> i32", strings.Join(types, ", ")), + }) + } + for _, class := range component.Classes { + for _, method := range class.Methods { + types, err := rustCParamTypes(method, component, class.ClassName) + if err != nil { + return nil, err + } + types = append([]string{"Handle"}, types...) + exports = append(exports, rustExport{ + field: GetCExportName(NameSpace, class.ClassName, method, false), + signature: fmt.Sprintf("unsafe extern \"C\" fn(%s) -> i32", strings.Join(types, ", ")), + }) + } + } + return exports, nil +} + +func buildRustApi(component ComponentDefinition, w LanguageWriter) error { + NameSpace := component.NameSpace + + exports, err := rustExports(component) + if err != nil { + return err + } + + rl(w, "/// Table of the functions exported by the library.") + rl(w, "#[allow(non_snake_case)]") + rl(w, "struct Api {") + for _, e := range exports { + rl(w, fmt.Sprintf(" %s: %s,", e.field, e.signature)) + } + rl(w, "}") + rl(w, "") + rl(w, "impl Api {") + rl(w, " /// Loads all functions using a function that resolves the address of a symbol by its name.") + rl(w, " #[allow(clippy::missing_transmute_annotations)]") + rl(w, " unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result {") + rl(w, " let load_symbol = |name: &str| -> Result<*mut c_void> {") + rl(w, fmt.Sprintf(" lookup(name).map_err(|e| Error::new(%s, e))", rustErrorConst(component, "COULDNOTFINDLIBRARYEXPORT", 7))) + rl(w, " };") + rl(w, " Ok(Self {") + for _, e := range exports { + rl(w, fmt.Sprintf(" %s: mem::transmute(load_symbol(\"%s\")?),", e.field, e.field)) + } + rl(w, " })") + rl(w, " }") + rl(w, "}") + rl(w, "") + + // Shared state of the wrapper and all instances that were created by it + rl(w, "/// State shared by the wrapper and all instances created through it, so that the library") + rl(w, "/// stays loaded for as long as any instance is alive.") + rl(w, "struct Inner {") + rl(w, " api: Api,") + rl(w, " _lib: Option,") + if len(component.Functions) > 0 { + rl(w, " /// closures registered as callbacks, kept alive for as long as the library is in use") + rl(w, " #[allow(dead_code, clippy::type_complexity)]") + rl(w, " callbacks: Mutex>>,") + } + for _, namespace := range rustImportedNamespaces(component) { + rl(w, fmt.Sprintf(" imported_%s: Mutex>,", strings.ToLower(namespace), strings.ToLower(namespace))) + } + rl(w, "}") + rl(w, "") + rl(w, "// The function table and the library handle are immutable after loading.") + rl(w, "unsafe impl Send for Inner {}") + rl(w, "unsafe impl Sync for Inner {}") + rl(w, "") + rl(w, "impl Inner {") + rl(w, " fn new(api: Api, lib: Option) -> Arc {") + rl(w, " Arc::new(Self {") + rl(w, " api,") + rl(w, " _lib: lib,") + if len(component.Functions) > 0 { + rl(w, " callbacks: Mutex::new(std::collections::HashMap::new()),") + } + for _, namespace := range rustImportedNamespaces(component) { + rl(w, fmt.Sprintf(" imported_%s: Mutex::new(None),", strings.ToLower(namespace))) + } + rl(w, " })") + rl(w, " }") + rl(w, "") + for _, namespace := range rustImportedNamespaces(component) { + lower := strings.ToLower(namespace) + rl(w, fmt.Sprintf(" /// Wrapper of the imported component %s, available after it was injected.", namespace)) + rl(w, " #[allow(dead_code)]") + rl(w, fmt.Sprintf(" fn imported_%s(&self) -> Result<%s::Wrapper> {", lower, lower)) + rl(w, fmt.Sprintf(" let guard = self.imported_%s.lock().unwrap_or_else(|e| e.into_inner());", lower)) + rl(w, " guard.clone().ok_or_else(|| {") + rl(w, " Error::new(") + rl(w, fmt.Sprintf(" %s,", rustErrorConst(component, "COULDNOTLOADLIBRARY", 6))) + rl(w, fmt.Sprintf(" \"the component %s has not been injected\",", namespace)) + rl(w, " )") + rl(w, " })") + rl(w, " }") + rl(w, "") + } + rl(w, " fn check(&self, handle: Handle, code: i32) -> Result<()> {") + rl(w, " if code == 0 {") + rl(w, " return Ok(());") + rl(w, " }") + rl(w, " Err(Error::new(code, self.last_error_message(handle)))") + rl(w, " }") + rl(w, "") + rl(w, " fn last_error_message(&self, handle: Handle) -> String {") + errorMethod, ok := findRustGlobalMethod(component, component.Global.ErrorMethod) + if ok && len(errorMethod.Params) == 3 && + errorMethod.Params[0].ParamType == "class" && errorMethod.Params[0].ParamPass == "in" && + errorMethod.Params[1].ParamType == "string" && errorMethod.Params[1].ParamPass != "in" && + errorMethod.Params[2].ParamType == "bool" && errorMethod.Params[2].ParamPass != "in" { + exportName := GetCExportName(NameSpace, "Wrapper", errorMethod, true) + rl(w, " if handle.is_null() {") + rl(w, " return String::new();") + rl(w, " }") + rl(w, " let mut needed: u32 = 0;") + rl(w, " let mut has_error = false;") + rl(w, fmt.Sprintf(" let code = unsafe { (self.api.%s)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) };", exportName)) + rl(w, " if code != 0 || !has_error || needed == 0 {") + rl(w, " return String::new();") + rl(w, " }") + rl(w, " let mut buffer = vec![0u8; needed as usize];") + rl(w, " let mut filled: u32 = 0;") + rl(w, fmt.Sprintf(" let code = unsafe { (self.api.%s)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) };", exportName)) + rl(w, " if code != 0 || !has_error {") + rl(w, " return String::new();") + rl(w, " }") + rl(w, " string_from_buffer(&buffer, filled)") + } else { + rl(w, " let _ = handle;") + rl(w, " String::new()") + } + rl(w, " }") + rl(w, "}") + rl(w, "") + + if component.isMultiThreadedEnv() { + baseClass := component.baseClass() + lockExport := GetCExportName(NameSpace, baseClass.ClassName, LockInstanceMethod(), false) + unlockExport := GetCExportName(NameSpace, baseClass.ClassName, UnlockInstanceMethod(), false) + rl(w, "/// Holds the lock of an instance of a class with a thread safety option for the duration of a call.") + rl(w, "struct InstanceLock<'a> {") + rl(w, " inner: &'a Inner,") + rl(w, " handle: Handle,") + rl(w, "}") + rl(w, "") + rl(w, "impl<'a> InstanceLock<'a> {") + rl(w, " fn new(inner: &'a Inner, handle: Handle) -> Result {") + rl(w, fmt.Sprintf(" let code = unsafe { (inner.api.%s)(handle) };", lockExport)) + rl(w, " inner.check(handle, code)?;") + rl(w, " Ok(Self { inner, handle })") + rl(w, " }") + rl(w, "}") + rl(w, "") + rl(w, "impl Drop for InstanceLock<'_> {") + rl(w, " fn drop(&mut self) {") + rl(w, fmt.Sprintf(" unsafe { (self.inner.api.%s)(self.handle) };", unlockExport)) + rl(w, " }") + rl(w, "}") + rl(w, "") + } + return nil +} + +// rustWriteFromRaw writes the constructor that lets another component create instances of this class. +func rustWriteFromRaw(component ComponentDefinition, w LanguageWriter) { + rl(w, " /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one") + rl(w, " /// reference of the handle. This is meant for bindings of components that import this component.") + rl(w, " ///") + rl(w, " /// # Safety") + rl(w, " /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.") + rl(w, " #[doc(hidden)]") + rl(w, " pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self {") + rl(w, " Self::from_handle(wrapper.inner.clone(), handle)") + rl(w, " }") + if acquireMethod, ok := findRustGlobalMethod(component, component.Global.AcquireMethod); ok { + exportName := GetCExportName(component.NameSpace, "Wrapper", acquireMethod, true) + rl(w, "") + rl(w, " /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a") + rl(w, " /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller.") + rl(w, " ///") + rl(w, " /// # Safety") + rl(w, " /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.") + rl(w, " pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result {") + rl(w, " let inner = &wrapper.inner;") + rl(w, fmt.Sprintf(" let code = (inner.api.%s)(handle);", exportName)) + rl(w, " inner.check(handle, code)?;") + rl(w, " Ok(Self::from_handle(inner.clone(), handle))") + rl(w, " }") + } +} + +// rustParentClassName returns the IDL name of the class a class derives from, or an empty string for the base class. +func rustParentClassName(component ComponentDefinition, class ComponentDefinitionClass) string { + if class.ClassName == component.Global.BaseClassName { + return "" + } + if len(class.ParentClass) > 0 { + return class.ParentClass + } + return component.Global.BaseClassName +} + +// rustParentClass returns the Rust name of the class a class derives from, or an empty string for the base class. +func rustParentClass(component ComponentDefinition, class ComponentDefinitionClass) string { + return rustTypeName(rustParentClassName(component, class)) +} + +func findRustClass(component ComponentDefinition, name string) (ComponentDefinitionClass, bool) { + for _, class := range component.Classes { + if class.ClassName == name { + return class, true + } + } + return ComponentDefinitionClass{}, false +} + +// rustHasClassTypeId tells whether the component allows to query the dynamic class of an instance. +func rustHasClassTypeId(component ComponentDefinition) bool { + if len(component.Classes) == 0 || len(component.Global.BaseClassName) == 0 || len(component.Global.ClassTypeIdMethod) == 0 { + return false + } + if _, ok := findRustClass(component, component.Global.BaseClassName); !ok { + return false + } + return component.classTypeIdMethod().MethodName == component.Global.ClassTypeIdMethod +} + +// rustAncestors returns the Rust names of all classes a class derives from, nearest parent first, ending with the base class. +func rustAncestors(component ComponentDefinition, class ComponentDefinitionClass) []string { + ancestors := []string{} + current := class + for { + parentName := rustParentClassName(component, current) + if len(parentName) == 0 { + return ancestors + } + ancestors = append(ancestors, rustTypeName(parentName)) + parent, ok := findRustClass(component, parentName) + if !ok { + return ancestors + } + current = parent + } +} + +// rustDescendants returns all classes that are derived from a class, directly or indirectly. +func rustDescendants(component ComponentDefinition, class ComponentDefinitionClass) []ComponentDefinitionClass { + result := []ComponentDefinitionClass{} + for _, candidate := range component.Classes { + if candidate.ClassName == class.ClassName { + continue + } + for _, ancestor := range rustAncestors(component, candidate) { + if ancestor == rustTypeName(class.ClassName) { + result = append(result, candidate) + break + } + } + } + return result +} + +// rustTypeIds returns the class type ids of a class and of all classes derived from it. +func rustTypeIds(component ComponentDefinition, class ComponentDefinitionClass) []string { + ids := []string{} + for _, candidate := range component.Classes { + isDerived := candidate.ClassName == class.ClassName + for _, ancestor := range rustAncestors(component, candidate) { + if ancestor == rustTypeName(class.ClassName) { + isDerived = true + } + } + if isDerived { + c := candidate + id, _ := c.classTypeId(component.NameSpace) + ids = append(ids, fmt.Sprintf("0x%016X", id)) + } + } + return ids +} + +func buildRustClass(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter) error { + className := rustTypeName(class.ClassName) + parent := rustParentClass(component, class) + + if len(class.ClassDescription) > 0 { + rl(w, fmt.Sprintf("/// %s", rustDoc(class.ClassDescription))) + } else { + rl(w, fmt.Sprintf("/// %s class of the %s library.", className, component.NameSpace)) + } + + if len(parent) == 0 { + rl(w, fmt.Sprintf("pub struct %s {", className)) + rl(w, " inner: Arc,") + rl(w, " handle: Handle,") + rl(w, "}") + rl(w, "") + rl(w, "// Instances may be moved between threads. They may only be shared between threads if the class is") + rl(w, "// declared with the strict threadsafetyoption in the ACT class definition.") + rl(w, fmt.Sprintf("unsafe impl Send for %s {}", className)) + if component.isMultiThreadedEnv() && component.getRealThreadSafetyOption(&class) == eThreadSafetyStrict { + rl(w, fmt.Sprintf("unsafe impl Sync for %s {}", className)) + } + rl(w, "") + rl(w, fmt.Sprintf("impl %s {", className)) + rl(w, " #[allow(dead_code)]") + rl(w, " fn from_handle(inner: Arc, handle: Handle) -> Self {") + rl(w, " Self { inner, handle }") + rl(w, " }") + rl(w, "") + rustWriteFromRaw(component, w) + rl(w, "") + rl(w, " fn inner_arc(&self) -> &Arc {") + rl(w, " &self.inner") + rl(w, " }") + rl(w, "") + rl(w, " /// Raw handle of the instance inside of the library.") + rl(w, " pub fn handle(&self) -> Handle {") + rl(w, " self.handle") + rl(w, " }") + } else { + rl(w, fmt.Sprintf("pub struct %s {", className)) + rl(w, fmt.Sprintf(" parent: %s,", parent)) + rl(w, "}") + rl(w, "") + if component.isMultiThreadedEnv() && component.getRealThreadSafetyOption(&class) == eThreadSafetyStrict { + rl(w, fmt.Sprintf("unsafe impl Sync for %s {}", className)) + rl(w, "") + } + rl(w, fmt.Sprintf("impl std::ops::Deref for %s {", className)) + rl(w, fmt.Sprintf(" type Target = %s;", parent)) + rl(w, "") + rl(w, fmt.Sprintf(" fn deref(&self) -> &%s {", parent)) + rl(w, " &self.parent") + rl(w, " }") + rl(w, "}") + rl(w, "") + rl(w, fmt.Sprintf("impl %s {", className)) + rl(w, " #[allow(dead_code)]") + rl(w, " fn from_handle(inner: Arc, handle: Handle) -> Self {") + rl(w, fmt.Sprintf(" Self { parent: %s::from_handle(inner, handle) }", parent)) + rl(w, " }") + rl(w, "") + rustWriteFromRaw(component, w) + } + + hasTypeId := rustHasClassTypeId(component) + if hasTypeId { + baseClassName := rustTypeName(component.Global.BaseClassName) + classTypeIdMethodName := rustSnakeCase(component.Global.ClassTypeIdMethod) + rl(w, "") + if len(parent) == 0 { + rl(w, fmt.Sprintf(" fn into_base(self) -> %s {", baseClassName)) + rl(w, " self") + rl(w, " }") + rl(w, "") + rl(w, " /// Tells whether the instance is of class `T` or of a class derived from it.") + rl(w, " pub fn is(&self) -> bool {") + rl(w, fmt.Sprintf(" matches!(self.%s(), Ok(id) if T::TYPE_IDS.contains(&id))", classTypeIdMethodName)) + rl(w, " }") + if acquireMethod, ok := findRustGlobalMethod(component, component.Global.AcquireMethod); ok { + exportName := GetCExportName(component.NameSpace, "Wrapper", acquireMethod, true) + rl(w, "") + rl(w, " /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`.") + rl(w, " /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes.") + rl(w, " pub fn cast(&self) -> Option {") + rl(w, " if !self.is::() {") + rl(w, " return None;") + rl(w, " }") + rl(w, fmt.Sprintf(" let code = unsafe { (self.inner.api.%s)(self.handle) };", exportName)) + rl(w, " if code != 0 {") + rl(w, " return None;") + rl(w, " }") + rl(w, fmt.Sprintf(" Some(T::from_base(%s { inner: self.inner.clone(), handle: self.handle }))", className)) + rl(w, " }") + } + } else { + rl(w, fmt.Sprintf(" fn into_base(self) -> %s {", baseClassName)) + rl(w, " self.parent.into_base()") + rl(w, " }") + } + rl(w, "") + rl(w, " /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise.") + rl(w, fmt.Sprintf(" pub fn downcast(self) -> std::result::Result {", className)) + rl(w, " if self.is::() {") + rl(w, " Ok(T::from_base(self.into_base()))") + rl(w, " } else {") + rl(w, " Err(self)") + rl(w, " }") + rl(w, " }") + if descendants := rustDescendants(component, class); len(descendants) > 0 { + kindName := className + "Kind" + rl(w, "") + rl(w, " /// Resolves the most specific class of the instance, to be used in a `match`.") + rl(w, fmt.Sprintf(" pub fn into_kind(self) -> %s {", kindName)) + rl(w, fmt.Sprintf(" let id = match self.%s() {", classTypeIdMethodName)) + rl(w, " Ok(id) => id,") + rl(w, fmt.Sprintf(" Err(_) => return %s::Other(self),", kindName)) + rl(w, " };") + for _, d := range descendants { + dn := rustTypeName(d.ClassName) + rl(w, fmt.Sprintf(" if id == %s::TYPE_ID {", dn)) + rl(w, fmt.Sprintf(" return %s::%s(%s::from_base(self.into_base()));", kindName, dn, dn)) + rl(w, " }") + } + rl(w, fmt.Sprintf(" %s::Other(self)", kindName)) + rl(w, " }") + } + } + + for _, method := range class.Methods { + rl(w, "") + err := writeRustMethod(component, method, w, class.ClassName, false) + if err != nil { + return err + } + } + rl(w, "}") + rl(w, "") + + if hasTypeId { + if descendants := rustDescendants(component, class); len(descendants) > 0 { + rl(w, fmt.Sprintf("/// The most specific class of a `%s`, see `%s::into_kind`.", className, className)) + rl(w, fmt.Sprintf("pub enum %sKind {", className)) + for _, d := range descendants { + rl(w, fmt.Sprintf(" %s(%s),", rustTypeName(d.ClassName), rustTypeName(d.ClassName))) + } + rl(w, fmt.Sprintf(" /// The instance is not of a more specific class (or the class is unknown to this binding).")) + rl(w, fmt.Sprintf(" Other(%s),", className)) + rl(w, "}") + rl(w, "") + } + } + + rl(w, fmt.Sprintf("impl fmt::Debug for %s {", className)) + rl(w, " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {") + rl(w, fmt.Sprintf(" f.debug_struct(\"%s\").field(\"handle\", &self.handle()).finish()", className)) + rl(w, " }") + rl(w, "}") + rl(w, "") + + if hasTypeId { + // build the nested structure from the base class outwards + ancestors := rustAncestors(component, class) + expr := "base" + for i := len(ancestors) - 2; i >= 0; i-- { + expr = fmt.Sprintf("%s { parent: %s }", ancestors[i], expr) + } + if len(parent) != 0 { + expr = fmt.Sprintf("%s { parent: %s }", className, expr) + } + rl(w, fmt.Sprintf("impl private::Sealed for %s {}", className)) + rl(w, "") + rl(w, fmt.Sprintf("impl Class for %s {", className)) + rl(w, fmt.Sprintf(" const TYPE_IDS: &'static [u64] = &[%s];", strings.Join(rustTypeIds(component, class), ", "))) + ownId, _ := class.classTypeId(component.NameSpace) + rl(w, fmt.Sprintf(" const TYPE_ID: u64 = 0x%016X;", ownId)) + rl(w, "") + rl(w, fmt.Sprintf(" fn from_base(base: %s) -> Self {", rustTypeName(component.Global.BaseClassName))) + rl(w, " "+expr) + rl(w, " }") + rl(w, "}") + rl(w, "") + } + + if len(parent) == 0 { + if releaseMethod, ok := findRustGlobalMethod(component, component.Global.ReleaseMethod); ok { + exportName := GetCExportName(component.NameSpace, "Wrapper", releaseMethod, true) + rl(w, fmt.Sprintf("impl Drop for %s {", className)) + rl(w, " fn drop(&mut self) {") + rl(w, " if !self.handle.is_null() {") + rl(w, fmt.Sprintf(" let _ = unsafe { (self.inner.api.%s)(self.handle) };", exportName)) + rl(w, " }") + rl(w, " }") + rl(w, "}") + rl(w, "") + } + } + return nil +} + +func buildRustWrapper(component ComponentDefinition, w LanguageWriter) error { + rl(w, fmt.Sprintf("/// Entry point to the %s library. Loads the shared library and gives access to its global functions.", component.NameSpace)) + rl(w, "#[derive(Clone)]") + rl(w, "pub struct Wrapper {") + rl(w, " inner: Arc,") + rl(w, "}") + rl(w, "") + rl(w, "impl Wrapper {") + rl(w, " /// Loads the library from the given path.") + rl(w, " pub fn new(library_path: &str) -> Result {") + rl(w, " let lib = unsafe { Library::new(library_path) }") + rl(w, fmt.Sprintf(" .map_err(|e| Error::new(%s, e))?;", rustErrorConst(component, "COULDNOTLOADLIBRARY", 6))) + rl(w, " let api = unsafe { Api::load(|name| lib.get(name)) }?;") + rl(w, " let wrapper = Self { inner: Inner::new(api, Some(lib)) };") + if len(component.Global.VersionMethod) > 0 { + rl(w, " wrapper.check_binary_version()?;") + } + rl(w, " Ok(wrapper)") + rl(w, " }") + if len(component.Global.SymbolLookupMethod) > 0 { + rl(w, "") + rl(w, " /// Creates a wrapper that resolves the functions of the library through the address of its symbol lookup") + rl(w, " /// method, as returned by `get_symbol_lookup_method`. This is used to inject a component into another one.") + rl(w, " /// The library that provides the symbol lookup method has to stay loaded for as long as the wrapper is used.") + rl(w, " ///") + rl(w, " /// # Safety") + rl(w, " /// `symbol_lookup_method` must be the address of a valid symbol lookup method of a compatible library") + rl(w, " /// (`int32 fn(const char*, void**)`), and that library must outlive the wrapper and all objects created from it.") + rl(w, " pub unsafe fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result {") + rl(w, " if symbol_lookup_method.is_null() {") + rl(w, fmt.Sprintf(" return Err(Error::new(%s, \"the symbol lookup method is null\"));", rustErrorConst(component, "INVALIDPARAM", 2))) + rl(w, " }") + rl(w, " type SymbolLookup = unsafe extern \"C\" fn(*const c_char, *mut *mut c_void) -> i32;") + rl(w, " let lookup: SymbolLookup = mem::transmute::<*mut c_void, SymbolLookup>(symbol_lookup_method);") + rl(w, " let api = unsafe {") + rl(w, " Api::load(|name| {") + rl(w, " let cname = CString::new(name).map_err(|_| \"symbol contains NUL\".to_string())?;") + rl(w, " let mut address: *mut c_void = ptr::null_mut();") + rl(w, " let code = lookup(cname.as_ptr(), &mut address);") + rl(w, " if code != 0 || address.is_null() {") + rl(w, " Err(format!(\"could not find the symbol {} (error {})\", name, code))") + rl(w, " } else {") + rl(w, " Ok(address)") + rl(w, " }") + rl(w, " })") + rl(w, " }?;") + rl(w, " let wrapper = Self { inner: Inner::new(api, None) };") + if len(component.Global.VersionMethod) > 0 { + rl(w, " wrapper.check_binary_version()?;") + } + rl(w, " Ok(wrapper)") + rl(w, " }") + } + if len(component.Global.VersionMethod) > 0 { + rl(w, "") + rl(w, " /// Checks that the loaded library is compatible with the version this binding was generated for.") + rl(w, " #[allow(clippy::absurd_extreme_comparisons)]") + rl(w, " fn check_binary_version(&self) -> Result<()> {") + rl(w, fmt.Sprintf(" const BINDING_VERSION_MAJOR: u32 = %d;", majorVersion(component.Version))) + rl(w, fmt.Sprintf(" const BINDING_VERSION_MINOR: u32 = %d;", minorVersion(component.Version))) + rl(w, fmt.Sprintf(" let (major, minor, _micro) = self.%s()?;", rustSnakeCase(component.Global.VersionMethod))) + rl(w, " if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR {") + rl(w, fmt.Sprintf(" return Err(Error::new(%s, \"the loaded library is not compatible with this binding\"));", rustErrorConst(component, "INCOMPATIBLEBINARYVERSION", 8))) + rl(w, " }") + rl(w, " Ok(())") + rl(w, " }") + } + for _, method := range component.Global.Methods { + rl(w, "") + err := writeRustMethod(component, method, w, "Wrapper", true) + if err != nil { + return err + } + } + if len(component.Global.InjectionMethod) > 0 && len(component.ImportComponents) > 0 { + for _, namespace := range rustImportedNamespaces(component) { + imported, ok := component.ImportedComponentDefinitions[namespace] + if !ok || len(imported.Global.SymbolLookupMethod) == 0 { + continue + } + lower := strings.ToLower(namespace) + rl(w, "") + rl(w, fmt.Sprintf(" /// Injects the component %s. The wrapper is kept alive for as long as this wrapper is used.", namespace)) + rl(w, fmt.Sprintf(" pub fn inject_%s(&self, component: &%s::Wrapper) -> Result<()> {", lower, lower)) + rl(w, fmt.Sprintf(" let lookup = component.%s()?;", rustSnakeCase(imported.Global.SymbolLookupMethod))) + rl(w, " // the lookup method comes from a live wrapper, which is stored below") + rl(w, fmt.Sprintf(" unsafe { self.%s(\"%s\", lookup)? };", rustSnakeCase(component.Global.InjectionMethod), namespace)) + rl(w, fmt.Sprintf(" *self.inner.imported_%s.lock().unwrap_or_else(|e| e.into_inner()) = Some(component.clone());", lower)) + rl(w, " Ok(())") + rl(w, " }") + } + } + rl(w, "}") + return nil +} + +// rustWrapHandle returns the expression that turns a handle returned by the library into an instance of a class. +// Classes of imported components are created through the wrapper of the component they belong to. +func rustWrapHandle(paramClass string, handle string) string { + if namespace, name, ok := rustImportedClass(paramClass); ok { + lower := strings.ToLower(namespace) + return fmt.Sprintf("unsafe { %s::%s::from_raw(&__act_inner.imported_%s()?, %s) }", lower, name, lower, handle) + } + return fmt.Sprintf("%s::from_handle(__act_inner.clone(), %s)", rustTypeName(paramClass), handle) +} + +// writeRustMethod writes the safe wrapper of a method of the C ABI. +// rustCallbackSpec describes how the library calls a function type and how that call is passed on to a Rust closure. +type rustCallbackSpec struct { + cParams []string // parameters of the extern "C" trampoline + closureArgs []string // types of the arguments of the closure + closureNames []string // names of the arguments of the closure + conversions []string // statements that build the closure arguments from the C parameters + callArgs []string // expressions passed to the closure + returnTypes []string // types the closure returns + outPointers []string // C parameters the returned values are written to + outEnums []string // class of the enumeration of an output, or an empty string + userDataName string + usesClassArgs bool +} + +// rustCallbackSpecFor maps a function type to a closure. Function types that carry something that cannot be +// expressed safely (arrays or strings returned to the library, structs, several untyped pointers) are not supported, +// as are function types without a pointer for user data, because a closure needs somewhere to be passed through. +func rustCallbackSpecFor(component ComponentDefinition, functiontype ComponentDefinitionFunctionType) (rustCallbackSpec, bool) { + spec := rustCallbackSpec{} + _, hasAcquire := findRustGlobalMethod(component, component.Global.AcquireMethod) + for _, p := range functiontype.Params { + name := rustSnakeCase(p.ParamName) + class := rustTypeName(p.ParamClass) + if _, _, imported := rustImportedClass(p.ParamClass); imported { + return spec, false + } + switch p.ParamPass { + case "in": + switch p.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double": + tp, _ := rustBasicType(p.ParamType) + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: %s", name, tp)) + spec.closureArgs = append(spec.closureArgs, tp) + spec.closureNames = append(spec.closureNames, name) + spec.callArgs = append(spec.callArgs, name) + case "enum": + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: i32", name)) + spec.closureArgs = append(spec.closureArgs, class) + spec.closureNames = append(spec.closureNames, name) + spec.conversions = append(spec.conversions, fmt.Sprintf("let %s = match %s::from_raw(%s) { Ok(value) => value, Err(_) => return };", name, class, name)) + spec.callArgs = append(spec.callArgs, name) + case "string": + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: *const c_char", name)) + spec.closureArgs = append(spec.closureArgs, "&str") + spec.closureNames = append(spec.closureNames, name) + spec.conversions = append(spec.conversions, fmt.Sprintf("let %s = if %s.is_null() { std::borrow::Cow::Borrowed(\"\") } else { std::ffi::CStr::from_ptr(%s).to_string_lossy() };", name, name, name)) + spec.callArgs = append(spec.callArgs, "&"+name) + case "class": + if !hasAcquire { + return spec, false + } + spec.usesClassArgs = true + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: Handle", name)) + spec.closureArgs = append(spec.closureArgs, "&"+class) + spec.closureNames = append(spec.closureNames, name) + spec.conversions = append(spec.conversions, fmt.Sprintf("let %s = match %s::from_borrowed(&__act_cb_wrapper, %s) { Ok(value) => value, Err(_) => return };", name, class, name)) + spec.callArgs = append(spec.callArgs, "&"+name) + case "basicarray": + tp, err := rustBasicType(p.ParamClass) + if err != nil || p.ParamClass == "pointer" { + return spec, false + } + spec.cParams = append(spec.cParams, fmt.Sprintf("%s_size: u64", name), fmt.Sprintf("%s_data: *const %s", name, tp)) + spec.closureArgs = append(spec.closureArgs, "&["+tp+"]") + spec.closureNames = append(spec.closureNames, name) + spec.conversions = append(spec.conversions, fmt.Sprintf("let %s: &[%s] = if %s_data.is_null() || %s_size == 0 { &[] } else { std::slice::from_raw_parts(%s_data, %s_size as usize) };", name, tp, name, name, name, name)) + spec.callArgs = append(spec.callArgs, name) + case "pointer": + if spec.userDataName != "" { + return spec, false + } + spec.userDataName = name + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: *mut c_void", name)) + default: + return spec, false + } + case "out", "return": + switch p.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double": + tp, _ := rustBasicType(p.ParamType) + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: *mut %s", name, tp)) + spec.returnTypes = append(spec.returnTypes, tp) + spec.outPointers = append(spec.outPointers, name) + spec.outEnums = append(spec.outEnums, "") + case "enum": + spec.cParams = append(spec.cParams, fmt.Sprintf("%s: *mut i32", name)) + spec.returnTypes = append(spec.returnTypes, class) + spec.outPointers = append(spec.outPointers, name) + spec.outEnums = append(spec.outEnums, class) + default: + return spec, false + } + default: + return spec, false + } + } + return spec, spec.userDataName != "" +} + +// rustClosureType is the type of the closure for a function type, without the bounds. +func (spec rustCallbackSpec) closureType() string { + result := fmt.Sprintf("FnMut(%s)", strings.Join(spec.closureArgs, ", ")) + switch len(spec.returnTypes) { + case 0: + case 1: + result += " -> " + spec.returnTypes[0] + default: + result += fmt.Sprintf(" -> (%s)", strings.Join(spec.returnTypes, ", ")) + } + return result +} + +// rustCallbackMethodSpecs returns the specifications of the function type parameters of a method when the method can +// be offered with closures: it needs at least one function type and one pointer for user data, which is handed to +// every callback of the method. +func rustCallbackMethodSpecs(component ComponentDefinition, method ComponentDefinitionMethod) (map[string]rustCallbackSpec, string, bool) { + specs := map[string]rustCallbackSpec{} + userData := "" + for _, p := range method.Params { + switch { + case p.ParamPass == "in" && p.ParamType == "functiontype": + var found *ComponentDefinitionFunctionType + for i := range component.Functions { + if component.Functions[i].FunctionName == p.ParamClass { + found = &component.Functions[i] + } + } + if found == nil { + return nil, "", false + } + spec, ok := rustCallbackSpecFor(component, *found) + if !ok { + return nil, "", false + } + specs[p.ParamName] = spec + case p.ParamPass == "in" && p.ParamType == "pointer": + if userData != "" { + return nil, "", false + } + userData = p.ParamName + } + } + if len(specs) == 0 || userData == "" { + return nil, "", false + } + return specs, userData, true +} + +type rustCallbackMode int + +const ( + rustCallbackNone rustCallbackMode = iota // plain function, unsafe if it takes raw pointers or callbacks + rustCallbackRaw // the unsafe function with the C ABI callbacks, next to a closure variant + rustCallbackSafe // closures instead of callbacks and user data +) + +// writeRustMethod writes a method. Methods that take callbacks and a pointer for user data are written twice: with +// closures, which is safe, and as an unsafe function with the callbacks of the C ABI, suffixed with _raw. +func rustCallbackWrite(spec rustCallbackSpec, index int, value string) string { + pointer := spec.outPointers[index] + if spec.outEnums[index] != "" { + value += " as i32" + } + return fmt.Sprintf(" if !%s.is_null() { *%s = %s; }", pointer, pointer, value) +} + +func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMethod, w LanguageWriter, className string, isGlobal bool) error { + if method.MethodName != component.Global.InjectionMethod { + if _, _, ok := rustCallbackMethodSpecs(component, method); ok { + if err := writeRustMethodMode(component, method, w, className, isGlobal, rustCallbackSafe); err != nil { + return err + } + rl(w, "") + return writeRustMethodMode(component, method, w, className, isGlobal, rustCallbackRaw) + } + } + return writeRustMethodMode(component, method, w, className, isGlobal, rustCallbackNone) +} + +func writeRustMethodMode(component ComponentDefinition, method ComponentDefinitionMethod, w LanguageWriter, className string, isGlobal bool, mode rustCallbackMode) error { + var callbackSpecs map[string]rustCallbackSpec + callbackUserData := "" + if mode != rustCallbackNone { + callbackSpecs, callbackUserData, _ = rustCallbackMethodSpecs(component, method) + } + NameSpace := component.NameSpace + exportName := GetCExportName(NameSpace, className, method, isGlobal) + + var parameters []string + var declarations []string + var callArgs []string + var initCallArgs []string + var initLines []string + var postLines []string + var rawParams []string + var returnTypes []string + var returnValues []string + var inDocs []string + var outDocs []string + requiresInitCall := false + + invalidParam := rustErrorConst(component, "INVALIDPARAM", 2) + + for _, param := range method.Params { + name := rustSnakeCase(param.ParamName) + class := rustTypeName(param.ParamClass) + doc := rustDoc(param.ParamDescription) + + if mode == rustCallbackSafe && param.ParamPass == "in" { + if param.ParamName == callbackUserData { + // the closures carry the user data + callArgs = append(callArgs, "__act_cb_user_data") + initCallArgs = append(initCallArgs, "__act_cb_user_data") + continue + } + if spec, ok := callbackSpecs[param.ParamName]; ok { + inDocs = append(inDocs, fmt.Sprintf("/// * `%s` - %s The closure is kept alive for as long as the wrapper exists.", name, doc)) + bound := spec.closureType() + parameters = append(parameters, fmt.Sprintf("%s: impl %s + Send + 'static", name, bound)) + callArgs = append(callArgs, "__act_"+name+"_trampoline") + initCallArgs = append(initCallArgs, "__act_"+name+"_trampoline") + continue + } + } + + switch param.ParamPass { + case "in": + inDocs = append(inDocs, fmt.Sprintf("/// * `%s` - %s", name, doc)) + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer": + tp, _ := rustBasicType(param.ParamType) + if param.ParamType == "pointer" { + rawParams = append(rawParams, name) + } + parameters = append(parameters, fmt.Sprintf("%s: %s", name, tp)) + callArgs = append(callArgs, name) + initCallArgs = append(initCallArgs, name) + case "string": + parameters = append(parameters, fmt.Sprintf("%s: &str", name)) + declarations = append(declarations, fmt.Sprintf("let __act_c_%s = CString::new(%s)", name, name)) + declarations = append(declarations, fmt.Sprintf(" .map_err(|_| Error::new(%s, \"the string parameter %s contains a NUL byte\"))?;", invalidParam, name)) + callArgs = append(callArgs, fmt.Sprintf("__act_c_%s.as_ptr()", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("__act_c_%s.as_ptr()", name)) + case "enum": + parameters = append(parameters, fmt.Sprintf("%s: %s", name, class)) + callArgs = append(callArgs, fmt.Sprintf("%s as i32", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("%s as i32", name)) + case "struct": + parameters = append(parameters, fmt.Sprintf("%s: &%s", name, class)) + callArgs = append(callArgs, name) + initCallArgs = append(initCallArgs, name) + case "basicarray": + tp, err := rustBasicType(class) + if err != nil { + return fmt.Errorf("%v for %s.%s (%s)", err, className, method.MethodName, param.ParamName) + } + parameters = append(parameters, fmt.Sprintf("%s: &[%s]", name, tp)) + callArgs = append(callArgs, fmt.Sprintf("%s.len() as u64, %s.as_ptr()", name, name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("%s.len() as u64, %s.as_ptr()", name, name)) + case "structarray": + parameters = append(parameters, fmt.Sprintf("%s: &[%s]", name, class)) + callArgs = append(callArgs, fmt.Sprintf("%s.len() as u64, %s.as_ptr()", name, name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("%s.len() as u64, %s.as_ptr()", name, name)) + case "class": + parameters = append(parameters, fmt.Sprintf("%s: &%s", name, class)) + callArgs = append(callArgs, fmt.Sprintf("%s.handle()", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("%s.handle()", name)) + case "optionalclass": + parameters = append(parameters, fmt.Sprintf("%s: Option<&%s>", name, class)) + callArgs = append(callArgs, fmt.Sprintf("%s.map_or(ptr::null_mut(), |c| c.handle())", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("%s.map_or(ptr::null_mut(), |c| c.handle())", name)) + case "functiontype": + rawParams = append(rawParams, name) + parameters = append(parameters, fmt.Sprintf("%s: %s", name, class)) + callArgs = append(callArgs, name) + initCallArgs = append(initCallArgs, name) + default: + return fmt.Errorf("invalid method parameter type \"%s\" for %s.%s (%s)", param.ParamType, className, method.MethodName, param.ParamName) + } + + case "out", "return": + outDocs = append(outDocs, fmt.Sprintf("/// * `%s` - %s", name, doc)) + outVar := "__act_out_" + name + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer": + tp, _ := rustBasicType(param.ParamType) + declarations = append(declarations, fmt.Sprintf("let mut %s: %s = %s;", outVar, tp, rustZeroValue(param.ParamType))) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", outVar)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", outVar)) + returnTypes = append(returnTypes, tp) + returnValues = append(returnValues, outVar) + case "enum": + declarations = append(declarations, fmt.Sprintf("let mut %s: i32 = 0;", outVar)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", outVar)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", outVar)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, fmt.Sprintf("%s::from_raw(%s)?", class, outVar)) + case "struct": + if rustStructNeedsRaw(component, param.ParamClass) { + raw := rustRawStructName(param.ParamClass) + declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", outVar, raw)) + callArgs = append(callArgs, fmt.Sprintf("(&mut %s as *mut %s).cast::<%s>()", outVar, raw, class)) + initCallArgs = append(initCallArgs, fmt.Sprintf("(&mut %s as *mut %s).cast::<%s>()", outVar, raw, class)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, fmt.Sprintf("%s.into_checked()?", outVar)) + } else { + declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", outVar, class)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", outVar)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", outVar)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, outVar) + } + case "string": + requiresInitCall = true + declarations = append(declarations, fmt.Sprintf("let mut __act_needed_%s: u32 = 0;", name)) + declarations = append(declarations, fmt.Sprintf("let mut __act_filled_%s: u32 = 0;", name)) + declarations = append(declarations, fmt.Sprintf("let mut __act_buffer_%s: Vec = Vec::new();", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut __act_needed_%s, ptr::null_mut()", name)) + initLines = append(initLines, fmt.Sprintf("__act_buffer_%s.resize(__act_needed_%s as usize, 0);", name, name)) + callArgs = append(callArgs, fmt.Sprintf("__act_buffer_%s.len() as u32, &mut __act_filled_%s, __act_buffer_%s.as_mut_ptr() as *mut c_char", name, name, name)) + returnTypes = append(returnTypes, "String") + returnValues = append(returnValues, fmt.Sprintf("string_from_buffer(&__act_buffer_%s, __act_filled_%s)", name, name)) + case "basicarray", "structarray": + var elementType, zero string + bufferType, bufferPtr, resultExpr := "", "", "" + if param.ParamType == "basicarray" { + tp, err := rustBasicType(class) + if err != nil { + return fmt.Errorf("%v for %s.%s (%s)", err, className, method.MethodName, param.ParamName) + } + elementType = tp + zero = "Default::default()" + if class == "pointer" { + zero = "ptr::null_mut()" + } + } else { + elementType = class + zero = "unsafe { mem::zeroed() }" + if rustStructNeedsRaw(component, param.ParamClass) { + bufferType = rustRawStructName(param.ParamClass) + bufferPtr = fmt.Sprintf(".cast::<%s>()", class) + if _, _, imported := rustImportedClass(param.ParamClass); imported { + resultExpr = ".into_iter().map(|v| v.into_checked().map_err(Error::from)).collect::>>()?" + } else { + resultExpr = fmt.Sprintf(".into_iter().map(%s::into_checked).collect::>>()?", bufferType) + } + } + } + if bufferType == "" { + bufferType = elementType + } + requiresInitCall = true + declarations = append(declarations, fmt.Sprintf("let mut __act_needed_%s: u64 = 0;", name)) + declarations = append(declarations, fmt.Sprintf("let mut __act_buffer_%s: Vec<%s> = Vec::new();", name, bufferType)) + initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut __act_needed_%s, ptr::null_mut()", name)) + initLines = append(initLines, fmt.Sprintf("__act_buffer_%s.resize(__act_needed_%s as usize, %s);", name, name, zero)) + callArgs = append(callArgs, fmt.Sprintf("__act_buffer_%s.len() as u64, &mut __act_needed_%s, __act_buffer_%s.as_mut_ptr()%s", name, name, name, bufferPtr)) + postLines = append(postLines, fmt.Sprintf("__act_buffer_%s.truncate(__act_needed_%s as usize);", name, name)) + returnTypes = append(returnTypes, fmt.Sprintf("Vec<%s>", elementType)) + returnValues = append(returnValues, fmt.Sprintf("__act_buffer_%s%s", name, resultExpr)) + case "class": + declarations = append(declarations, fmt.Sprintf("let mut %s: Handle = ptr::null_mut();", outVar)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", outVar)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", outVar)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, rustWrapHandle(param.ParamClass, outVar)) + case "optionalclass": + declarations = append(declarations, fmt.Sprintf("let mut %s: Handle = ptr::null_mut();", outVar)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", outVar)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", outVar)) + returnTypes = append(returnTypes, fmt.Sprintf("Option<%s>", class)) + returnValues = append(returnValues, fmt.Sprintf("if %s.is_null() { None } else { Some(%s) }", outVar, rustWrapHandle(param.ParamClass, outVar))) + default: + return fmt.Errorf("invalid method parameter type \"%s\" for %s.%s (%s)", param.ParamType, className, method.MethodName, param.ParamName) + } + + default: + return fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s (%s)", param.ParamPass, className, method.MethodName, param.ParamName) + } + } + + if mode == rustCallbackSafe { + names := []string{} + for _, param := range method.Params { + if _, ok := callbackSpecs[param.ParamName]; ok { + names = append(names, param.ParamName) + } + } + usesClasses := false + for _, n := range names { + usesClasses = usesClasses || callbackSpecs[n].usesClassArgs + } + declarations = append(declarations, "#[allow(clippy::type_complexity)]") + declarations = append(declarations, "struct CallbackState {") + if usesClasses { + declarations = append(declarations, " inner: std::sync::Weak,") + } + for _, n := range names { + declarations = append(declarations, fmt.Sprintf(" %s: Mutex>,", rustSnakeCase(n), callbackSpecs[n].closureType())) + } + declarations = append(declarations, "}") + for _, n := range names { + spec := callbackSpecs[n] + field := rustSnakeCase(n) + declarations = append(declarations, fmt.Sprintf("unsafe extern \"C\" fn __act_%s_trampoline(%s) {", field, strings.Join(spec.cParams, ", "))) + declarations = append(declarations, fmt.Sprintf(" if %s.is_null() { return; }", spec.userDataName)) + declarations = append(declarations, fmt.Sprintf(" let __act_cb_state = &*(%s as *const CallbackState);", spec.userDataName)) + if spec.usesClassArgs { + declarations = append(declarations, " let __act_cb_inner = match __act_cb_state.inner.upgrade() { Some(inner) => inner, None => return };") + declarations = append(declarations, " let __act_cb_wrapper = Wrapper { inner: __act_cb_inner };") + } + for _, c := range spec.conversions { + declarations = append(declarations, " "+c) + } + declarations = append(declarations, " let __act_cb_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {") + declarations = append(declarations, fmt.Sprintf(" let mut __act_callback = __act_cb_state.%s.lock().unwrap_or_else(|e| e.into_inner());", field)) + declarations = append(declarations, fmt.Sprintf(" (*__act_callback)(%s)", strings.Join(spec.callArgs, ", "))) + declarations = append(declarations, " }));") + declarations = append(declarations, " // a panic must not unwind into the library") + if len(spec.outPointers) == 0 { + declarations = append(declarations, " if __act_cb_result.is_err() { std::process::abort(); }") + } else { + declarations = append(declarations, " let __act_cb_values = match __act_cb_result { Ok(values) => values, Err(_) => std::process::abort() };") + } + switch len(spec.outPointers) { + case 0: + case 1: + declarations = append(declarations, rustCallbackWrite(spec, 0, "__act_cb_values")) + default: + for i := range spec.outPointers { + declarations = append(declarations, rustCallbackWrite(spec, i, fmt.Sprintf("__act_cb_values.%d", i))) + } + } + declarations = append(declarations, "}") + } + fields := []string{} + if usesClasses { + fields = append(fields, "inner: Arc::downgrade(__act_inner)") + } + for _, n := range names { + fields = append(fields, fmt.Sprintf("%s: Mutex::new(std::boxed::Box::new(%s))", rustSnakeCase(n), rustSnakeCase(n))) + } + declarations = append(declarations, fmt.Sprintf("let __act_cb_state = std::boxed::Box::new(CallbackState { %s });", strings.Join(fields, ", "))) + declarations = append(declarations, "let __act_cb_user_data = (&*__act_cb_state as *const CallbackState) as *mut c_void;") + key := "0usize" + if !isGlobal { + key = "__act_handle as usize" + } + postLines = append(postLines, fmt.Sprintf("__act_inner.callbacks.lock().unwrap_or_else(|e| e.into_inner()).insert((%s, \"%s\"), __act_cb_state as std::boxed::Box);", key, rustSnakeCase(method.MethodName))) + } + + isUnsafe := false + safetyDoc := "" + if len(rawParams) > 0 { + isUnsafe = true + } + if isGlobal && len(component.Global.ReleaseMethod) > 0 && method.MethodName == component.Global.ReleaseMethod { + isUnsafe = true + safetyDoc = "Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired." + } + if !isGlobal && component.isMultiThreadedEnv() { + if method.MethodName == LockInstanceMethod().MethodName { + isUnsafe = true + safetyDoc = "Locks the instance's internal mutex directly. The caller must not already hold the lock on this thread and must pair it with the corresponding unlock call." + } else if method.MethodName == UnlockInstanceMethod().MethodName { + isUnsafe = true + safetyDoc = "Unlocks the instance's internal mutex directly. The caller must currently hold the lock on this thread." + } + } + if isGlobal && len(method.MethodName) > 0 && method.MethodName == component.Global.InjectionMethod && len(component.ImportComponents) > 0 { + namespaceParam, symbolParam := "", "" + for _, p := range method.Params { + if p.ParamType == "string" && namespaceParam == "" { + namespaceParam = rustSnakeCase(p.ParamName) + } + if p.ParamType == "pointer" && symbolParam == "" { + symbolParam = rustSnakeCase(p.ParamName) + } + } + if namespaceParam != "" && symbolParam != "" { + couldNotLoad := rustErrorConst(component, "COULDNOTLOADLIBRARY", 6) + postLines = append(postLines, fmt.Sprintf("match %s {", namespaceParam)) + for _, namespace := range rustImportedNamespaces(component) { + lower := strings.ToLower(namespace) + postLines = append(postLines, fmt.Sprintf(" \"%s\" => {", namespace)) + postLines = append(postLines, fmt.Sprintf(" let mut __act_slot = __act_inner.imported_%s.lock().unwrap_or_else(|e| e.into_inner());", lower)) + postLines = append(postLines, " if __act_slot.is_some() {") + postLines = append(postLines, fmt.Sprintf(" return Err(Error::new(%s, \"the component %s has already been injected\"));", couldNotLoad, namespace)) + postLines = append(postLines, " }") + postLines = append(postLines, fmt.Sprintf(" *__act_slot = Some(unsafe { %s::Wrapper::from_symbol_lookup_method(%s) }?);", lower, symbolParam)) + postLines = append(postLines, " }") + } + postLines = append(postLines, fmt.Sprintf(" _ => return Err(Error::new(%s, format!(\"unknown namespace {}\", %s))),", couldNotLoad, namespaceParam)) + postLines = append(postLines, "}") + isUnsafe = true + safetyDoc = "The symbol lookup method must be valid for the imported component, and its library must stay loaded for as long as this wrapper is used. Prefer the safe `inject_*` functions." + } + } + + var returnType, returnExpr string + switch len(returnTypes) { + case 0: + returnType = "()" + returnExpr = "Ok(())" + case 1: + returnType = returnTypes[0] + returnExpr = fmt.Sprintf("Ok(%s)", returnValues[0]) + if v := returnValues[0]; strings.HasSuffix(v, "?") && strings.Count(v, "?") == 1 { + returnExpr = strings.TrimSuffix(v, "?") + } + default: + returnType = fmt.Sprintf("(%s)", strings.Join(returnTypes, ", ")) + returnExpr = fmt.Sprintf("Ok((%s))", strings.Join(returnValues, ", ")) + } + + // Documentation + if len(method.MethodDescription) > 0 { + rl(w, fmt.Sprintf(" /// %s", rustDoc(method.MethodDescription))) + } else { + rl(w, fmt.Sprintf(" /// Calls %s.", method.MethodName)) + } + if mode == rustCallbackSafe { + rl(w, " ///") + rl(w, fmt.Sprintf(" /// The callbacks are closures. They may be called from any thread the library uses, and must not panic out of the")) + rl(w, fmt.Sprintf(" /// closure: a panic aborts the process, as it cannot unwind through the library. See `%s_raw` for the variant", rustSnakeCase(method.MethodName))) + rl(w, " /// with the callbacks of the C ABI and a pointer for user data.") + } + if mode == rustCallbackRaw { + rl(w, " ///") + rl(w, fmt.Sprintf(" /// This is the variant with the callbacks of the C ABI, `%s` takes closures instead.", rustSnakeCase(method.MethodName))) + } + if len(inDocs) > 0 { + rl(w, " ///") + rl(w, " /// # Arguments") + for _, line := range inDocs { + rl(w, " "+line) + } + } + if len(outDocs) > 0 { + rl(w, " ///") + rl(w, " /// # Returns") + for _, line := range outDocs { + rl(w, " "+line) + } + } + + if len(safetyDoc) > 0 { + rl(w, " ///") + rl(w, " /// # Safety") + rl(w, " /// "+safetyDoc) + } else if len(rawParams) > 0 { + rl(w, " ///") + rl(w, " /// # Safety") + rl(w, fmt.Sprintf(" /// The library passes %s on to callbacks or uses it as is: callback functions must follow the C ABI,", strings.Join(rawParams, ", "))) + rl(w, " /// must not panic, and pointers must stay valid for as long as the library may use them.") + } + + // Signature + signature := "&self" + if len(parameters) > 0 { + signature += ", " + strings.Join(parameters, ", ") + } + if len(parameters) >= 7 { + rl(w, " #[allow(clippy::too_many_arguments)]") + } + switch rustSnakeCase(method.MethodName) { + case "clone", "default", "drop", "next", "from_str", "add", "sub", "mul", "div", "neg", "not", "eq", "cmp", "hash": + rl(w, " #[allow(clippy::should_implement_trait)]") + } + unsafeKeyword := "" + if isUnsafe { + unsafeKeyword = "unsafe " + } + functionName := rustSnakeCase(method.MethodName) + if mode == rustCallbackRaw { + functionName += "_raw" + } + rl(w, fmt.Sprintf(" pub %sfn %s(%s) -> Result<%s> {", unsafeKeyword, functionName, signature, returnType)) + + handleExpr := "ptr::null_mut()" + if isGlobal { + rl(w, " let __act_inner = &self.inner;") + } else { + rl(w, " let __act_inner = self.inner_arc();") + rl(w, " let __act_handle = self.handle();") + handleExpr = "__act_handle" + callArgs = append([]string{"__act_handle"}, callArgs...) + initCallArgs = append([]string{"__act_handle"}, initCallArgs...) + } + for _, line := range declarations { + rl(w, " "+line) + } + + // classes with a thread safety option are locked for the duration of the call, like in the other bindings + if !isGlobal && component.isMultiThreadedEnv() { + if class, ok := findRustClass(component, className); ok { + option := component.getRealThreadSafetyOption(&class) + if (option == eThreadSafetySoft && requiresInitCall) || option == eThreadSafetyStrict { + rl(w, " let __act_lock = InstanceLock::new(__act_inner, __act_handle)?;") + } + } + } + + if requiresInitCall { + rl(w, fmt.Sprintf(" let __act_code = unsafe { (__act_inner.api.%s)(%s) };", exportName, strings.Join(initCallArgs, ", "))) + rl(w, fmt.Sprintf(" __act_inner.check(%s, __act_code)?;", handleExpr)) + for _, line := range initLines { + rl(w, " "+line) + } + } + rl(w, fmt.Sprintf(" let __act_code = unsafe { (__act_inner.api.%s)(%s) };", exportName, strings.Join(callArgs, ", "))) + rl(w, fmt.Sprintf(" __act_inner.check(%s, __act_code)?;", handleExpr)) + for _, line := range postLines { + rl(w, " "+line) + } + rl(w, " "+returnExpr) + rl(w, " }") + return nil +}