From 8fe7e2c95b440e77de14ac76af0ee134b35aac5f Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 11:25:34 +0100 Subject: [PATCH 01/16] Add Rust binding generator Generates a Rust crate (dlopen-based, no build-time dependency on the component) from an ACT component description. Working, tested against the example components and lib3mf 2.6.0: - classes with inheritance, Deref to the parent, is/downcast - strings, basic/struct arrays, structs (packed, [column][row] matrices), enums - callbacks, error codes and messages, class type ids - imported components (injection) as path-dependency crates - Send/Sync classes and instance locking for threadsafetyoption - generated example program and Cargo manifests --- Build/build.bat | 2 +- Build/build.sh | 2 +- Source/ACT.xsd | 1 + Source/automaticcomponenttoolkit.go | 22 + Source/buildbindingrust.go | 1544 +++++++++++++++++++++++++++ 5 files changed, 1569 insertions(+), 2 deletions(-) create mode 100644 Source/buildbindingrust.go 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/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..8d027078 --- /dev/null +++ b/Source/buildbindingrust.go @@ -0,0 +1,1544 @@ +/*++ + +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" + "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") + if forceRecreation || !FileExists(cargoFile) { + 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\"") + 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);") + // 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, " wrapper") + rl(w, fmt.Sprintf(" .%s(\"%s\", %s.%s().expect(\"could not get the symbol lookup method\"))", rustSnakeCase(component.Global.InjectionMethod), namespace, lower, rustSnakeCase(imported.Global.SymbolLookupMethod))) + rl(w, " .expect(\"could not inject the component\");") + } + } + } else { + rl(w, " let _ = wrapper;") + rl(w, fmt.Sprintf(" println!(\"%s library loaded\");", component.BaseName)) + } + rl(w, "}") + return nil +} + +const rustDynlibTemplate = `use std::ffi::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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+"_") || rustIsImportedHandle(t, component): + base = "Handle" + case strings.HasPrefix(t, nameSpace): + base = rustTypeName(strings.TrimPrefix(t, nameSpace)) + default: + base = t + } + + if isPtr { + if isConst { + return "*const " + base + } + return "*mut " + base + } + return base +} + +// rustIsImportedHandle tells whether a C type is the handle type of a class of an imported component. +func rustIsImportedHandle(cType string, component ComponentDefinition) bool { + for _, namespace := range rustImportedNamespaces(component) { + if strings.HasPrefix(cType, namespace+"_") { + return 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 { + 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, "/// 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: Sized {") + rl(w, " #[doc(hidden)]") + rl(w, " const TYPE_IDS: &'static [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(Debug, 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\",") + for _, e := range component.Errors.Errors { + 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\",") + for _, e := range component.Errors.Errors { + rl(w, fmt.Sprintf(" error_code::%s => \"%s\",", e.Name, strings.ReplaceAll(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, "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, " #[allow(dead_code)]") + rl(w, " 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, "") + } +} + +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)) + 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, "") + } + 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, 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, " 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,") + 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,") + 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, 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(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, " }") +} + +// 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 + } +} + +// 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 and shared between threads. The library is responsible for protecting") + rl(w, "// its own state (see the threadsafetyoption of the ACT class definition).") + rl(w, fmt.Sprintf("unsafe impl Send for %s {}", className)) + 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(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, "") + 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(w) + } + + hasTypeId := rustHasClassTypeId(component) + if hasTypeId { + rl(w, "") + if len(parent) == 0 { + rl(w, " fn into_base(self) -> Base {") + 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, " self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id))") + rl(w, " }") + } else { + rl(w, " fn into_base(self) -> Base {") + 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, " }") + } + + for _, method := range class.Methods { + rl(w, "") + err := writeRustMethod(component, method, w, class.ClassName, false) + if err != nil { + return err + } + } + 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 Class for %s {", className)) + rl(w, fmt.Sprintf(" const TYPE_IDS: &'static [u64] = &[%s];", strings.Join(rustTypeIds(component, class), ", "))) + 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, " pub 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 = unsafe { mem::transmute(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, " 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 + } + } + 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(&inner.imported_%s()?, %s) }", lower, name, lower, handle) + } + return fmt.Sprintf("%s::from_handle(inner.clone(), %s)", rustTypeName(paramClass), handle) +} + +// writeRustMethod writes the safe wrapper of a method of the C ABI. +func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMethod, w LanguageWriter, className string, isGlobal bool) error { + 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 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) + + 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) + 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 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("c_%s.as_ptr()", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("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": + 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)) + 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;", name, tp, rustZeroValue(param.ParamType))) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + returnTypes = append(returnTypes, tp) + returnValues = append(returnValues, name) + case "enum": + declarations = append(declarations, fmt.Sprintf("let mut %s: i32 = 0;", name)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, fmt.Sprintf("%s::from_raw(%s)?", class, name)) + case "struct": + declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", name, class)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, name) + case "string": + requiresInitCall = true + declarations = append(declarations, fmt.Sprintf("let mut needed_%s: u32 = 0;", name)) + declarations = append(declarations, fmt.Sprintf("let mut filled_%s: u32 = 0;", name)) + declarations = append(declarations, fmt.Sprintf("let mut buffer_%s: Vec = Vec::new();", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut needed_%s, ptr::null_mut()", name)) + initLines = append(initLines, fmt.Sprintf("buffer_%s.resize(needed_%s as usize, 0);", name, name)) + callArgs = append(callArgs, fmt.Sprintf("buffer_%s.len() as u32, &mut filled_%s, buffer_%s.as_mut_ptr() as *mut c_char", name, name, name)) + returnTypes = append(returnTypes, "String") + returnValues = append(returnValues, fmt.Sprintf("string_from_buffer(&buffer_%s, filled_%s)", name, name)) + case "basicarray", "structarray": + var elementType, zero string + 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() }" + } + requiresInitCall = true + declarations = append(declarations, fmt.Sprintf("let mut needed_%s: u64 = 0;", name)) + declarations = append(declarations, fmt.Sprintf("let mut buffer_%s: Vec<%s> = Vec::new();", name, elementType)) + initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut needed_%s, ptr::null_mut()", name)) + initLines = append(initLines, fmt.Sprintf("buffer_%s.resize(needed_%s as usize, %s);", name, name, zero)) + callArgs = append(callArgs, fmt.Sprintf("buffer_%s.len() as u64, &mut needed_%s, buffer_%s.as_mut_ptr()", name, name, name)) + postLines = append(postLines, fmt.Sprintf("buffer_%s.truncate(needed_%s as usize);", name, name)) + returnTypes = append(returnTypes, fmt.Sprintf("Vec<%s>", elementType)) + returnValues = append(returnValues, fmt.Sprintf("buffer_%s", name)) + case "class": + declarations = append(declarations, fmt.Sprintf("let mut %s: Handle = ptr::null_mut();", name)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, rustWrapHandle(param.ParamClass, name)) + case "optionalclass": + declarations = append(declarations, fmt.Sprintf("let mut %s: Handle = ptr::null_mut();", name)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + returnTypes = append(returnTypes, fmt.Sprintf("Option<%s>", class)) + returnValues = append(returnValues, fmt.Sprintf("if %s.is_null() { None } else { Some(%s) }", name, rustWrapHandle(param.ParamClass, name))) + 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 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 slot = inner.imported_%s.lock().unwrap_or_else(|e| e.into_inner());", lower)) + postLines = append(postLines, " if 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(" *slot = Some(%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, "}") + inDocs = append(inDocs, "/// The library providing the symbol lookup method has to stay loaded for as long as this wrapper is used.") + } + } + + var returnType, returnExpr string + switch len(returnTypes) { + case 0: + returnType = "()" + returnExpr = "Ok(())" + case 1: + returnType = returnTypes[0] + returnExpr = fmt.Sprintf("Ok(%s)", returnValues[0]) + 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 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) + } + } + + // Signature + signature := "&self" + if len(parameters) > 0 { + signature += ", " + strings.Join(parameters, ", ") + } + rl(w, fmt.Sprintf(" pub fn %s(%s) -> Result<%s> {", rustSnakeCase(method.MethodName), signature, returnType)) + + handleExpr := "ptr::null_mut()" + if isGlobal { + rl(w, " let inner = &self.inner;") + } else { + rl(w, " let inner = self.inner_arc();") + rl(w, " let handle = self.handle();") + handleExpr = "handle" + callArgs = append([]string{"handle"}, callArgs...) + initCallArgs = append([]string{"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 _lock = InstanceLock::new(inner, handle)?;") + } + } + } + + if requiresInitCall { + rl(w, fmt.Sprintf(" let code = unsafe { (inner.api.%s)(%s) };", exportName, strings.Join(initCallArgs, ", "))) + rl(w, fmt.Sprintf(" inner.check(%s, code)?;", handleExpr)) + for _, line := range initLines { + rl(w, " "+line) + } + } + rl(w, fmt.Sprintf(" let code = unsafe { (inner.api.%s)(%s) };", exportName, strings.Join(callArgs, ", "))) + rl(w, fmt.Sprintf(" inner.check(%s, code)?;", handleExpr)) + for _, line := range postLines { + rl(w, " "+line) + } + rl(w, " "+returnExpr) + rl(w, " }") + return nil +} From 824bd7a454cc43823b293647a02037195c775877 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 11:37:11 +0100 Subject: [PATCH 02/16] Rust binding: cast, from_borrowed, readable Error debug output - cast::() narrows an instance to a derived class without consuming it - from_borrowed() wraps a handle the library passes to a callback - Debug for Error prints the readable message --- Source/buildbindingrust.go | 46 ++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/Source/buildbindingrust.go b/Source/buildbindingrust.go index 8d027078..cd8f9a27 100644 --- a/Source/buildbindingrust.go +++ b/Source/buildbindingrust.go @@ -672,7 +672,7 @@ func buildRustErrors(component ComponentDefinition, w LanguageWriter) { rl(w, "}") rl(w, "") rl(w, fmt.Sprintf("/// Error returned by the %s library or by the Rust binding.", NameSpace)) - rl(w, "#[derive(Debug, Clone, PartialEq, Eq)]") + rl(w, "#[derive(Clone, PartialEq, Eq)]") rl(w, "pub struct Error {") rl(w, " pub code: i32,") rl(w, " pub message: String,") @@ -713,6 +713,13 @@ func buildRustErrors(component ComponentDefinition, w LanguageWriter) { 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) { @@ -971,7 +978,7 @@ func buildRustApi(component ComponentDefinition, w LanguageWriter) error { } // rustWriteFromRaw writes the constructor that lets another component create instances of this class. -func rustWriteFromRaw(w LanguageWriter) { +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, " ///") @@ -981,6 +988,21 @@ func rustWriteFromRaw(w LanguageWriter) { 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. @@ -1083,7 +1105,7 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas rl(w, " Self { inner, handle }") rl(w, " }") rl(w, "") - rustWriteFromRaw(w) + rustWriteFromRaw(component, w) rl(w, "") rl(w, " fn inner_arc(&self) -> &Arc {") rl(w, " &self.inner") @@ -1112,7 +1134,7 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas rl(w, fmt.Sprintf(" Self { parent: %s::from_handle(inner, handle) }", parent)) rl(w, " }") rl(w, "") - rustWriteFromRaw(w) + rustWriteFromRaw(component, w) } hasTypeId := rustHasClassTypeId(component) @@ -1127,6 +1149,22 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas rl(w, " pub fn is(&self) -> bool {") rl(w, " self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id))") 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, " fn into_base(self) -> Base {") rl(w, " self.parent.into_base()") From dc8953ade216c52816f91a4b43bbff8f8f26cdbb Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 12:37:58 +0100 Subject: [PATCH 03/16] Rust binding: class kind enums, plain repr(C) where layout allows, callback docs - into_kind() on classes with descendants returns a Kind enum for match - structs are plain repr(C) when C adds no padding (fields can be borrowed), repr(C, packed) otherwise; compile-time size checks for every struct - document that callbacks must not panic --- Source/buildbindingrust.go | 128 ++++++++++++++++++++++++++++++++++++- 1 file changed, 126 insertions(+), 2 deletions(-) diff --git a/Source/buildbindingrust.go b/Source/buildbindingrust.go index cd8f9a27..eac536da 100644 --- a/Source/buildbindingrust.go +++ b/Source/buildbindingrust.go @@ -647,6 +647,8 @@ func buildRustBinding(component ComponentDefinition, w LanguageWriter) error { 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, "") @@ -768,10 +770,74 @@ func buildRustEnums(component ComponentDefinition, w LanguageWriter) { } } +// rustStructLayout returns the size of a struct with the packed layout of the C ABI, its alignment and whether the +// natural layout of C yields the same layout (i.e. whether no padding would be inserted). +func rustStructLayout(component ComponentDefinition, name string) (uint64, uint64, bool) { + var structure *ComponentDefinitionStruct + for i := range component.Structs { + if component.Structs[i].Name == name { + structure = &component.Structs[i] + } + } + if structure == nil { + return 0, 1, false + } + var offset, maxAlign uint64 = 0, 1 + natural := true + for _, m := range structure.Members { + var size, 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, align, nested = rustStructLayout(component, m.Class) + if !nested { + align = 1 + natural = false + } + default: + // pointers depend on the platform + size, align = 8, 8 + natural = false + } + count := uint64(1) + if m.Rows > 0 { + count *= uint64(m.Rows) + } + if m.Columns > 0 { + count *= uint64(m.Columns) + } + if offset%align != 0 { + natural = false + } + offset += size * count + if align > maxAlign { + maxAlign = align + } + } + if offset%maxAlign != 0 { + natural = false + } + return offset, 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)) - rl(w, "#[repr(C, packed)]") + // 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. + size, _, 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 { @@ -783,6 +849,9 @@ func buildRustStructs(component ComponentDefinition, w LanguageWriter) error { } rl(w, "}") rl(w, "") + rl(w, fmt.Sprintf("// the size has to match the packed layout of the C ABI")) + rl(w, fmt.Sprintf("const _: () = assert!(std::mem::size_of::<%s>() == %d);", rustTypeName(s.Name), size)) + rl(w, "") } return nil } @@ -800,6 +869,10 @@ func buildRustFunctionTypes(component ComponentDefinition, w LanguageWriter) err } } 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, "") } @@ -1059,6 +1132,23 @@ func rustAncestors(component ComponentDefinition, class ComponentDefinitionClass } } +// 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{} @@ -1179,6 +1269,24 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas 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, " let id = match self.class_type_id() {") + 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 { @@ -1191,6 +1299,20 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas 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)) @@ -1210,6 +1332,8 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas } 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) From c24612b736c5da5c9ef3b655fda68c8dc48fb2b1 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 12:40:39 +0100 Subject: [PATCH 04/16] Add Rust to the examples - Rust binding entry in the example IDLs - generated Rust bindings and examples for Calculator, Injection (with injected Numbers), Primes, RTTI, UnitTest and ThreadSafety - Examples/Rust/build.sh for each, run from the example build scripts against the C++ and Pascal libraries - Rust toolchain in the CI Dockerfile, Rust row in the README --- .gitignore | 1 + Build/Dockerfile | 5 + Examples/Calculator/Calculator.xml | 1 + .../Bindings/Rust/Cargo.toml | 4 + .../Bindings/Rust/src/lib.rs | 795 +++++++++ .../Examples/Rust/Calculator_example.rs | 34 + .../Examples/Rust/Cargo.toml | 11 + .../Examples/Rust/build.sh | 16 + Examples/Calculator/build.sh | 6 + Examples/Injection/Calculation.xml | 1 + .../Bindings/Rust/Cargo.toml | 7 + .../Bindings/Rust/src/lib.rs | 763 +++++++++ .../Examples/Rust/Calculation_example.rs | 44 + .../Examples/Rust/Cargo.toml | 12 + .../Examples/Rust/build.sh | 16 + Examples/Injection/Numbers.xml | 1 + .../Bindings/Rust/Cargo.toml | 4 + .../Bindings/Rust/src/lib.rs | 674 ++++++++ Examples/Injection/build.sh | 1 + Examples/OptionalClass/OptionalClass.xml | 1 + .../Bindings/Rust/Cargo.toml | 4 + .../Bindings/Rust/src/lib.rs | 919 +++++++++++ .../Examples/Rust/Cargo.toml | 11 + .../Examples/Rust/LibPrimes_example.rs | 34 + .../Examples/Rust/build.sh | 16 + Examples/Primes/build.sh | 1 + Examples/Primes/libPrimes.xml | 1 + Examples/RTTI/RTTI.xml | 1 + .../RTTI_component/Bindings/Rust/Cargo.toml | 4 + .../RTTI_component/Bindings/Rust/src/lib.rs | 1430 +++++++++++++++++ .../RTTI_component/Examples/Rust/Cargo.toml | 11 + .../Examples/Rust/RTTI_example.rs | 34 + .../RTTI_component/Examples/Rust/build.sh | 16 + Examples/RTTI/build.sh | 1 + .../Bindings/Rust/Cargo.toml | 4 + .../Bindings/Rust/src/lib.rs | 922 +++++++++++ .../Examples/Rust/Cargo.toml | 11 + .../Examples/Rust/LibThreadSafe_example.rs | 34 + .../Examples/Rust/build.sh | 13 + Examples/ThreadSafety/build.sh | 1 + Examples/ThreadSafety/threadSafeLibrary.xml | 1 + .../Bindings/Rust/Cargo.toml | 4 + .../Bindings/Rust/src/lib.rs | 860 ++++++++++ .../Examples/Rust/Cargo.toml | 11 + .../Examples/Rust/LibUnitTest_example.rs | 34 + .../Examples/Rust/build.sh | 16 + Examples/UnitTest/build.sh | 1 + Examples/UnitTest/libUnitTest.xml | 1 + Examples/Version/libVersion.1.1.0.xml | 1 + Examples/Version/libVersion.1.2.0.xml | 1 + Examples/Version/libVersion.1.3.0.xml | 1 + Examples/Version/libVersion.2.0.0.xml | 1 + Examples/Version/libVersion.3.0.0.xml | 1 + Examples/Version/libVersion.3.1.0.xml | 1 + Examples/Version/libVersion.4.0.0.xml | 1 + Examples/Version/libVersion.4.1.0.xml | 1 + Examples/Version/libVersion.4.2.0.xml | 1 + Examples/Version/libVersion.xml | 1 + README.md | 3 +- 59 files changed, 6805 insertions(+), 1 deletion(-) create mode 100644 Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs create mode 100644 Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml create mode 100755 Examples/Calculator/Calculator_component/Examples/Rust/build.sh create mode 100644 Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs create mode 100644 Examples/Injection/Calculation_component/Examples/Rust/Cargo.toml create mode 100755 Examples/Injection/Calculation_component/Examples/Rust/build.sh create mode 100644 Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/Primes/LibPrimes_component/Examples/Rust/Cargo.toml create mode 100644 Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs create mode 100755 Examples/Primes/LibPrimes_component/Examples/Rust/build.sh create mode 100644 Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/RTTI/RTTI_component/Examples/Rust/Cargo.toml create mode 100644 Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs create mode 100755 Examples/RTTI/RTTI_component/Examples/Rust/build.sh create mode 100644 Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/Cargo.toml create mode 100644 Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs create mode 100755 Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/build.sh create mode 100644 Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml create mode 100644 Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs create mode 100644 Examples/UnitTest/LibUnitTest_component/Examples/Rust/Cargo.toml create mode 100644 Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs create mode 100755 Examples/UnitTest/LibUnitTest_component/Examples/Rust/build.sh diff --git a/.gitignore b/.gitignore index 0df76f45..8c457202 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ Examples/**/build Examples/**/build-* Examples/**/bin Examples/**/obj +Cargo.lock # Visual Studio Code debug diff --git a/Build/Dockerfile b/Build/Dockerfile index b2868d0b..367a1b7a 100644 --- a/Build/Dockerfile +++ b/Build/Dockerfile @@ -36,6 +36,11 @@ RUN (cd /opt && curl -O -L 'http://downloads.sourceforge.net/project/freepascal/ 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/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..7b636769 --- /dev/null +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "calculator" +version = "1.0.0" +edition = "2021" 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..81e62a2f --- /dev/null +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,795 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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. + 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) + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.calculator_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut value: f64 = 0.0; + let code = unsafe { (inner.api.calculator_variable_getvalue)(handle, &mut value) }; + inner.check(handle, code)?; + Ok(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 inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.calculator_variable_setvalue)(handle, value) }; + inner.check(handle, 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.calculator_calculator_enlistvariable)(handle, variable.handle()) }; + inner.check(handle, 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut variable: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculator_calculator_getenlistedvariable)(handle, index, &mut variable) }; + inner.check(handle, code)?; + Ok(Variable::from_handle(inner.clone(), variable)) + } + + /// Clears all variables in enlisted in this calculator + pub fn clear_variables(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.calculator_calculator_clearvariables)(handle) }; + inner.check(handle, code)?; + Ok(()) + } + + /// Multiplies all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the product of all enlisted Variables + pub fn multiply(&self) -> Result { + let inner = self.inner_arc(); + let handle = self.handle(); + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculator_calculator_multiply)(handle, &mut instance) }; + inner.check(handle, code)?; + Ok(Variable::from_handle(inner.clone(), instance)) + } + + /// Sums all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the sum of all enlisted Variables + pub fn add(&self) -> Result { + let inner = self.inner_arc(); + let handle = self.handle(); + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculator_calculator_add)(handle, &mut instance) }; + inner.check(handle, code)?; + Ok(Variable::from_handle(inner.clone(), 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 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. + 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.calculator_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.calculator_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.calculator_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.calculator_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.calculator_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), 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 inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculator_createvariable)(initial_value, &mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(Variable::from_handle(inner.clone(), instance)) + } + + /// Creates a new Calculator instance + /// + /// # Returns + /// * `instance` - New Calculator instance + pub fn create_calculator(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculator_createcalculator)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(Calculator::from_handle(inner.clone(), 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..b1efdd57 --- /dev/null +++ b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs @@ -0,0 +1,34 @@ +/*++ + +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 application that demonstrates the + usage of the Rust bindings of Calculator library + +Interface version: 1.0.0 + +*/ + +use calculator::Wrapper; +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + eprintln!("usage: {} ", args[0]); + process::exit(1); + } + let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + + let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); + let version = format!("calculator.version = {}.{}.{}", major, minor, micro); + println!("{}", version); +} 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..7400f87d --- /dev/null +++ b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "calculation" +version = "1.0.0" +edition = "2021" + +[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..ab09af4a --- /dev/null +++ b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,763 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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. + 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. + 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) + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.calculation_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.calculation_calculator_enlistvariable)(handle, variable.handle()) }; + inner.check(handle, 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut variable: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculation_calculator_getenlistedvariable)(handle, index, &mut variable) }; + inner.check(handle, code)?; + Ok(unsafe { numbers::Variable::from_raw(&inner.imported_numbers()?, variable) }) + } + + /// Clears all variables in enlisted in this calculator + pub fn clear_variables(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.calculation_calculator_clearvariables)(handle) }; + inner.check(handle, code)?; + Ok(()) + } + + /// Multiplies all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the product of all enlisted Variables + pub fn multiply(&self) -> Result { + let inner = self.inner_arc(); + let handle = self.handle(); + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculation_calculator_multiply)(handle, &mut instance) }; + inner.check(handle, code)?; + Ok(unsafe { numbers::Variable::from_raw(&inner.imported_numbers()?, instance) }) + } + + /// Sums all enlisted variables + /// + /// # Returns + /// * `instance` - Variable that holds the sum of all enlisted Variables + pub fn add(&self) -> Result { + let inner = self.inner_arc(); + let handle = self.handle(); + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculation_calculator_add)(handle, &mut instance) }; + inner.check(handle, code)?; + Ok(unsafe { numbers::Variable::from_raw(&inner.imported_numbers()?, 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 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. + pub 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 = unsafe { mem::transmute(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. + 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 inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.calculation_createcalculator)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(Calculator::from_handle(inner.clone(), 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.calculation_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.calculation_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.calculation_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.calculation_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.calculation_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), 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 + /// The library providing the symbol lookup method has to stay loaded for as long as this wrapper is used. + pub fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + let inner = &self.inner; + let c_name_space = CString::new(name_space) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; + let code = unsafe { (inner.api.calculation_injectcomponent)(c_name_space.as_ptr(), symbol_address_method) }; + inner.check(ptr::null_mut(), code)?; + match name_space { + "Numbers" => { + let mut slot = inner.imported_numbers.lock().unwrap_or_else(|e| e.into_inner()); + if slot.is_some() { + return Err(Error::new(error_code::COULDNOTLOADLIBRARY, "the component Numbers has already been injected")); + } + *slot = Some(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 inner = &self.inner; + let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); + let code = unsafe { (inner.api.calculation_getsymbollookupmethod)(&mut symbol_lookup_method) }; + inner.check(ptr::null_mut(), code)?; + Ok(symbol_lookup_method) + } +} 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..9a67ef6c --- /dev/null +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -0,0 +1,44 @@ +/*++ + +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 application that demonstrates the + usage of the Rust bindings of Calculation library + +Interface version: 1.0.0 + +*/ + +use calculation::Wrapper; +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 3 { + eprintln!("usage: {} ", args[0]); + process::exit(1); + } + let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + + let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); + let version = format!("calculation.version = {}.{}.{}", major, minor, micro); + println!("{}", version); + + let numbers = numbers::Wrapper::new(&args[2]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + let (major, minor, micro) = numbers.get_version().expect("could not query the version"); + println!("numbers.version = {}.{}.{}", major, minor, micro); + wrapper + .inject_component("Numbers", numbers.get_symbol_lookup_method().expect("could not get the symbol lookup method")) + .expect("could not inject the component"); +} 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..72d2e44d --- /dev/null +++ b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "numbers" +version = "1.0.0" +edition = "2021" 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..805f1a79 --- /dev/null +++ b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,674 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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. + 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) + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.numbers_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut value: f64 = 0.0; + let code = unsafe { (inner.api.numbers_variable_getvalue)(handle, &mut value) }; + inner.check(handle, code)?; + Ok(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 inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.numbers_variable_setvalue)(handle, value) }; + inner.check(handle, 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 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. + pub 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 = unsafe { mem::transmute(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. + 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 inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.numbers_createvariable)(initial_value, &mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(Variable::from_handle(inner.clone(), 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.numbers_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.numbers_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.numbers_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.numbers_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.numbers_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), 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 inner = &self.inner; + let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); + let code = unsafe { (inner.api.numbers_getsymbollookupmethod)(&mut symbol_lookup_method) }; + inner.check(ptr::null_mut(), code)?; + Ok(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..8c2a8b2d --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "libprimes" +version = "1.2.0" +edition = "2021" 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..3d06bde5 --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,919 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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 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. + 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, +} + +// 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.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) + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.libprimes_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut value: u64 = 0; + let code = unsafe { (inner.api.libprimes_calculator_getvalue)(handle, &mut value) }; + inner.check(handle, code)?; + Ok(value) + } + + /// Sets the value to be factorized + /// + /// # Arguments + /// * `value` - The value to be factorized + pub fn set_value(&self, value: u64) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libprimes_calculator_setvalue)(handle, value) }; + inner.check(handle, code)?; + Ok(()) + } + + /// Performs the specific calculation of this Calculator + pub fn calculate(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libprimes_calculator_calculate)(handle) }; + inner.check(handle, code)?; + Ok(()) + } + + /// Sets the progress callback function + /// + /// # Arguments + /// * `progress_callback` - The progress callback + pub fn set_progress_callback(&self, progress_callback: ProgressCallback) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libprimes_calculator_setprogresscallback)(handle, progress_callback) }; + inner.check(handle, 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut needed_prime_factors: u64 = 0; + let mut buffer_prime_factors: Vec = Vec::new(); + let code = unsafe { (inner.api.libprimes_factorizationcalculator_getprimefactors)(handle, 0, &mut needed_prime_factors, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_prime_factors.resize(needed_prime_factors as usize, unsafe { mem::zeroed() }); + let code = unsafe { (inner.api.libprimes_factorizationcalculator_getprimefactors)(handle, buffer_prime_factors.len() as u64, &mut needed_prime_factors, buffer_prime_factors.as_mut_ptr()) }; + inner.check(handle, code)?; + buffer_prime_factors.truncate(needed_prime_factors as usize); + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut needed_primes: u64 = 0; + let mut buffer_primes: Vec = Vec::new(); + let code = unsafe { (inner.api.libprimes_sievecalculator_getprimes)(handle, 0, &mut needed_primes, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_primes.resize(needed_primes as usize, Default::default()); + let code = unsafe { (inner.api.libprimes_sievecalculator_getprimes)(handle, buffer_primes.len() as u64, &mut needed_primes, buffer_primes.as_mut_ptr()) }; + inner.check(handle, code)?; + buffer_primes.truncate(needed_primes as usize); + Ok(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 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. + 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.libprimes_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.libprimes_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.libprimes_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Acquire shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.libprimes_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.libprimes_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Creates a new FactorizationCalculator instance + /// + /// # Returns + /// * `instance` - New FactorizationCalculator instance + pub fn create_factorization_calculator(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.libprimes_createfactorizationcalculator)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(FactorizationCalculator::from_handle(inner.clone(), instance)) + } + + /// Creates a new SieveCalculator instance + /// + /// # Returns + /// * `instance` - New SieveCalculator instance + pub fn create_sieve_calculator(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.libprimes_createsievecalculator)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(SieveCalculator::from_handle(inner.clone(), instance)) + } + + /// Handles Library Journaling + /// + /// # Arguments + /// * `file_name` - Journal FileName + pub fn set_journal(&self, file_name: &str) -> Result<()> { + let inner = &self.inner; + let c_file_name = CString::new(file_name) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter file_name contains a NUL byte"))?; + let code = unsafe { (inner.api.libprimes_setjournal)(c_file_name.as_ptr()) }; + inner.check(ptr::null_mut(), 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..87d3efc3 --- /dev/null +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs @@ -0,0 +1,34 @@ +/*++ + +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 application that demonstrates the + usage of the Rust bindings of Prime Numbers Library + +Interface version: 1.2.0 + +*/ + +use libprimes::Wrapper; +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + eprintln!("usage: {} ", args[0]); + process::exit(1); + } + let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + + let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); + let version = format!("libprimes.version = {}.{}.{}", major, minor, micro); + println!("{}", version); +} 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..9ef92bb3 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "rtti" +version = "1.0.0" +edition = "2021" 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..7b20e7e3 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,1430 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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. + 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) + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.rtti_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut needed_result: u32 = 0; + let mut filled_result: u32 = 0; + let mut buffer_result: Vec = Vec::new(); + let code = unsafe { (inner.api.rtti_animal_name)(handle, 0, &mut needed_result, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_result.resize(needed_result as usize, 0); + let code = unsafe { (inner.api.rtti_animal_name)(handle, buffer_result.len() as u32, &mut filled_result, buffer_result.as_mut_ptr() as *mut c_char) }; + inner.check(handle, code)?; + Ok(string_from_buffer(&buffer_result, 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 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 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 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.rtti_tiger_roar)(handle) }; + inner.check(handle, 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 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 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut animal: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.rtti_animaliterator_getnextanimal)(handle, &mut animal) }; + inner.check(handle, code)?; + Ok(if animal.is_null() { None } else { Some(Animal::from_handle(inner.clone(), animal)) }) + } + + /// Return next animal + /// + /// # Returns + /// * `animal` - + /// * `error` - + pub fn get_next_optinal_animal(&self) -> Result<(Option, bool)> { + let inner = self.inner_arc(); + let handle = self.handle(); + let mut animal: Handle = ptr::null_mut(); + let mut error: bool = false; + let code = unsafe { (inner.api.rtti_animaliterator_getnextoptinalanimal)(handle, &mut animal, &mut error) }; + inner.check(handle, code)?; + Ok((if animal.is_null() { None } else { Some(Animal::from_handle(inner.clone(), animal)) }, error)) + } + + /// Return next animal + /// + /// # Returns + /// * `animal` - + /// * `error` - + pub fn get_next_mandatory_animal(&self) -> Result<(Option, bool)> { + let inner = self.inner_arc(); + let handle = self.handle(); + let mut animal: Handle = ptr::null_mut(); + let mut error: bool = false; + let code = unsafe { (inner.api.rtti_animaliterator_getnextmandatoryanimal)(handle, &mut animal, &mut error) }; + inner.check(handle, code)?; + Ok((if animal.is_null() { None } else { Some(Animal::from_handle(inner.clone(), animal)) }, 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut iterator: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.rtti_zoo_iterator)(handle, &mut iterator) }; + inner.check(handle, code)?; + Ok(AnimalIterator::from_handle(inner.clone(), 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 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. + pub 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 = unsafe { mem::transmute(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. + 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.rtti_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.rtti_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.rtti_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.rtti_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.rtti_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), 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 + pub fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + let inner = &self.inner; + let c_name_space = CString::new(name_space) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; + let code = unsafe { (inner.api.rtti_injectcomponent)(c_name_space.as_ptr(), symbol_address_method) }; + inner.check(ptr::null_mut(), 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 inner = &self.inner; + let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); + let code = unsafe { (inner.api.rtti_getsymbollookupmethod)(&mut symbol_lookup_method) }; + inner.check(ptr::null_mut(), code)?; + Ok(symbol_lookup_method) + } + + /// Create a new zoo with animals + /// + /// # Returns + /// * `instance` - + pub fn create_zoo(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.rtti_createzoo)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(Zoo::from_handle(inner.clone(), 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..c816cc39 --- /dev/null +++ b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs @@ -0,0 +1,34 @@ +/*++ + +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 application that demonstrates the + usage of the Rust bindings of RTTI + +Interface version: 1.0.0 + +*/ + +use rtti::Wrapper; +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + eprintln!("usage: {} ", args[0]); + process::exit(1); + } + let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + + let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); + let version = format!("rtti.version = {}.{}.{}", major, minor, micro); + println!("{}", version); +} 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..a8909f46 --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "libthreadsafe" +version = "1.0.0" +edition = "2021" 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..f637e274 --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,922 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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. + 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) }; + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.libthreadsafe_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(class_type_id) + } + + /// If thread safety for class in library is enabled it should lock object for calling thread + pub fn _lock_instance(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libthreadsafe_base__lockinstance)(handle) }; + inner.check(handle, code)?; + Ok(()) + } + + /// If thread safety for class in library is enabled it should unlock object for other threads + pub fn _unlock_instance(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libthreadsafe_base__unlockinstance)(handle) }; + inner.check(handle, 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut needed_value: u32 = 0; + let mut filled_value: u32 = 0; + let mut buffer_value: Vec = Vec::new(); + let code = unsafe { (inner.api.libthreadsafe_stringreturner_getstring)(handle, 0, &mut needed_value, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_value.resize(needed_value as usize, 0); + let code = unsafe { (inner.api.libthreadsafe_stringreturner_getstring)(handle, buffer_value.len() as u32, &mut filled_value, buffer_value.as_mut_ptr() as *mut c_char) }; + inner.check(handle, code)?; + Ok(string_from_buffer(&buffer_value, filled_value)) + } + + /// Function that may crash when called from different threads at the same time + pub fn thread_safety_check(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libthreadsafe_stringreturner_threadsafetycheck)(handle) }; + inner.check(handle, 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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut needed_value: u32 = 0; + let mut filled_value: u32 = 0; + let mut buffer_value: Vec = Vec::new(); + let _lock = InstanceLock::new(inner, handle)?; + let code = unsafe { (inner.api.libthreadsafe_softstringreturner_getstring)(handle, 0, &mut needed_value, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_value.resize(needed_value as usize, 0); + let code = unsafe { (inner.api.libthreadsafe_softstringreturner_getstring)(handle, buffer_value.len() as u32, &mut filled_value, buffer_value.as_mut_ptr() as *mut c_char) }; + inner.check(handle, code)?; + Ok(string_from_buffer(&buffer_value, filled_value)) + } + + /// Function that may crash when called from different threads at the same time + pub fn thread_safety_check(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libthreadsafe_softstringreturner_threadsafetycheck)(handle) }; + inner.check(handle, 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 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, +} + +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 inner = self.inner_arc(); + let handle = self.handle(); + let mut needed_value: u32 = 0; + let mut filled_value: u32 = 0; + let mut buffer_value: Vec = Vec::new(); + let _lock = InstanceLock::new(inner, handle)?; + let code = unsafe { (inner.api.libthreadsafe_strictstringreturner_getstring)(handle, 0, &mut needed_value, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_value.resize(needed_value as usize, 0); + let code = unsafe { (inner.api.libthreadsafe_strictstringreturner_getstring)(handle, buffer_value.len() as u32, &mut filled_value, buffer_value.as_mut_ptr() as *mut c_char) }; + inner.check(handle, code)?; + Ok(string_from_buffer(&buffer_value, filled_value)) + } + + /// Function that shouldn't crash when called from different threads at the same time + pub fn thread_safety_check(&self) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let _lock = InstanceLock::new(inner, handle)?; + let code = unsafe { (inner.api.libthreadsafe_strictstringreturner_threadsafetycheck)(handle) }; + inner.check(handle, 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 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. + 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.libthreadsafe_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.libthreadsafe_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.libthreadsafe_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Acquire shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.libthreadsafe_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.libthreadsafe_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Creates a new StringReturner instance + /// + /// # Returns + /// * `instance` - New StringReturner instance + pub fn create_string_returner(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.libthreadsafe_createstringreturner)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(StringReturner::from_handle(inner.clone(), instance)) + } + + /// Creates a new SoftStringReturner instance + /// + /// # Returns + /// * `instance` - New SoftStringReturner instance + pub fn create_soft_string_returner(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.libthreadsafe_createsoftstringreturner)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(SoftStringReturner::from_handle(inner.clone(), instance)) + } + + /// Creates a new StrictStringReturner instance + /// + /// # Returns + /// * `instance` - New StrictStringReturner instance + pub fn create_strict_string_returner(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.libthreadsafe_createstrictstringreturner)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(StrictStringReturner::from_handle(inner.clone(), 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..1c38d8d0 --- /dev/null +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs @@ -0,0 +1,34 @@ +/*++ + +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 application that demonstrates the + usage of the Rust bindings of Thread-safe library + +Interface version: 1.0.0 + +*/ + +use libthreadsafe::Wrapper; +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + eprintln!("usage: {} ", args[0]); + process::exit(1); + } + let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + + let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); + let version = format!("libthreadsafe.version = {}.{}.{}", major, minor, micro); + println!("{}", version); +} 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..af440269 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "libunittest" +version = "1.0.0" +edition = "2021" 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..f1125d96 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs @@ -0,0 +1,860 @@ +/*++ + +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::{CStr, 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::*; + type DynResult = std::result::Result; + #[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::*; + type DynResult = std::result::Result; + type HMODULE = *mut c_void; + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryA(lpLibFileName: *const c_char) -> 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 { + let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; + let handle = LoadLibraryA(cpath.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 { + #[allow(dead_code)] + 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. + 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) + } +} + +/// 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: 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 and shared between threads. The library is responsible for protecting +// its own state (see the threadsafetyoption of the ACT class definition). +unsafe impl Send for Base {} +unsafe impl Sync 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 { + self.class_type_id().map_or(false, |id| 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut class_type_id: u64 = 0; + let code = unsafe { (inner.api.libunittest_base_classtypeid)(handle, &mut class_type_id) }; + inner.check(handle, code)?; + Ok(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 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut value: f64 = 0.0; + let code = unsafe { (inner.api.libunittest_testclass_value)(handle, &mut value) }; + inner.check(handle, code)?; + Ok(value) + } + + /// Sets the value of the number + /// + /// # Arguments + /// * `value` - The new value of this number + pub fn set_value(&self, value: f64) -> Result<()> { + let inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libunittest_testclass_setvalue)(handle, value) }; + inner.check(handle, 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 inner = self.inner_arc(); + let handle = self.handle(); + let code = unsafe { (inner.api.libunittest_testclass_setvalueint)(handle, value) }; + inner.check(handle, 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 inner = self.inner_arc(); + let handle = self.handle(); + let c_value = CString::new(value) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter value contains a NUL byte"))?; + let code = unsafe { (inner.api.libunittest_testclass_setvaluestring)(handle, c_value.as_ptr()) }; + inner.check(handle, 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut out_value1: u8 = 0; + let mut out_value2: u16 = 0; + let mut out_value3: u32 = 0; + let mut out_value4: u64 = 0; + let code = unsafe { (inner.api.libunittest_testclass_unittest1)(handle, value1, value2, value3, value4, &mut out_value1, &mut out_value2, &mut out_value3, &mut out_value4) }; + inner.check(handle, code)?; + Ok((out_value1, out_value2, out_value3, 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut out_value1: i8 = 0; + let mut out_value2: i16 = 0; + let mut out_value3: i32 = 0; + let mut out_value4: i64 = 0; + let code = unsafe { (inner.api.libunittest_testclass_unittest2)(handle, value1, value2, value3, value4, &mut out_value1, &mut out_value2, &mut out_value3, &mut out_value4) }; + inner.check(handle, code)?; + Ok((out_value1, out_value2, out_value3, 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 inner = self.inner_arc(); + let handle = self.handle(); + let mut out_value1: bool = false; + let mut out_value2: f32 = 0.0; + let mut out_value3: f64 = 0.0; + let mut out_value4: i32 = 0; + let code = unsafe { (inner.api.libunittest_testclass_unittest3)(handle, value1, value2, value3, value4 as i32, &mut out_value1, &mut out_value2, &mut out_value3, &mut out_value4) }; + inner.check(handle, code)?; + Ok((out_value1, out_value2, out_value3, TestEnum::from_raw(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 inner = self.inner_arc(); + let handle = self.handle(); + let c_value = CString::new(value) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter value contains a NUL byte"))?; + let mut needed_out_value: u32 = 0; + let mut filled_out_value: u32 = 0; + let mut buffer_out_value: Vec = Vec::new(); + let mut needed_return_value: u32 = 0; + let mut filled_return_value: u32 = 0; + let mut buffer_return_value: Vec = Vec::new(); + let code = unsafe { (inner.api.libunittest_testclass_unittest4)(handle, c_value.as_ptr(), 0, &mut needed_out_value, ptr::null_mut(), 0, &mut needed_return_value, ptr::null_mut()) }; + inner.check(handle, code)?; + buffer_out_value.resize(needed_out_value as usize, 0); + buffer_return_value.resize(needed_return_value as usize, 0); + let code = unsafe { (inner.api.libunittest_testclass_unittest4)(handle, c_value.as_ptr(), buffer_out_value.len() as u32, &mut filled_out_value, buffer_out_value.as_mut_ptr() as *mut c_char, buffer_return_value.len() as u32, &mut filled_return_value, buffer_return_value.as_mut_ptr() as *mut c_char) }; + inner.check(handle, code)?; + Ok((string_from_buffer(&buffer_out_value, filled_out_value), string_from_buffer(&buffer_return_value, 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 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. + pub 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 = unsafe { mem::transmute(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. + 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 inner = &self.inner; + let mut major: u32 = 0; + let mut minor: u32 = 0; + let mut micro: u32 = 0; + let code = unsafe { (inner.api.libunittest_getversion)(&mut major, &mut minor, &mut micro) }; + inner.check(ptr::null_mut(), code)?; + Ok((major, minor, 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 inner = &self.inner; + let mut needed_error_message: u32 = 0; + let mut filled_error_message: u32 = 0; + let mut buffer_error_message: Vec = Vec::new(); + let mut has_error: bool = false; + let code = unsafe { (inner.api.libunittest_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + buffer_error_message.resize(needed_error_message as usize, 0); + let code = unsafe { (inner.api.libunittest_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; + inner.check(ptr::null_mut(), code)?; + Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + } + + /// Releases shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn release_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.libunittest_releaseinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), code)?; + Ok(()) + } + + /// Acquires shared ownership of an Instance + /// + /// # Arguments + /// * `instance` - Instance Handle + pub fn acquire_instance(&self, instance: &Base) -> Result<()> { + let inner = &self.inner; + let code = unsafe { (inner.api.libunittest_acquireinstance)(instance.handle()) }; + inner.check(ptr::null_mut(), 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 + pub fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + let inner = &self.inner; + let c_name_space = CString::new(name_space) + .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; + let code = unsafe { (inner.api.libunittest_injectcomponent)(c_name_space.as_ptr(), symbol_address_method) }; + inner.check(ptr::null_mut(), 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 inner = &self.inner; + let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); + let code = unsafe { (inner.api.libunittest_getsymbollookupmethod)(&mut symbol_lookup_method) }; + inner.check(ptr::null_mut(), code)?; + Ok(symbol_lookup_method) + } + + /// Create a new TestClass instance + /// + /// # Returns + /// * `instance` - New TestClass instance + pub fn create_test_classs(&self) -> Result { + let inner = &self.inner; + let mut instance: Handle = ptr::null_mut(); + let code = unsafe { (inner.api.libunittest_createtestclasss)(&mut instance) }; + inner.check(ptr::null_mut(), code)?; + Ok(TestClass::from_handle(inner.clone(), 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..1c7a5181 --- /dev/null +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs @@ -0,0 +1,34 @@ +/*++ + +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 application that demonstrates the + usage of the Rust bindings of ACT UnitTest FrameWork + +Interface version: 1.0.0 + +*/ + +use libunittest::Wrapper; +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + eprintln!("usage: {} ", args[0]); + process::exit(1); + } + let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { + eprintln!("{}", e); + process::exit(1); + }); + + let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); + let version = format!("libunittest.version = {}.{}.{}", major, minor, micro); + println!("{}", version); +} 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..135a63dd 100644 --- a/README.md +++ b/README.md @@ -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) | 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 From 16e5bbcbe56389fae9408ce2a547cdbf84fa61c0 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 12:45:48 +0100 Subject: [PATCH 05/16] Rust examples: exercise the bindings, not only the version call The examples use only the example libraries of ACT and run against both the C++ and the Pascal implementation: - Calculator, Calculation (injection of Numbers), Primes (progress callback) - RTTI (class hierarchy, is/downcast, error codes), UnitTest (all scalar types, enum, strings), ThreadSafety (shared strict instance, 5 threads) --- .../Examples/Rust/Calculator_example.rs | 41 ++++++------ .../Examples/Rust/Calculation_example.rs | 55 +++++++--------- .../Examples/Rust/LibPrimes_example.rs | 62 ++++++++++++------- .../Examples/Rust/RTTI_example.rs | 55 +++++++++------- .../Examples/Rust/LibThreadSafe_example.rs | 40 ++++++------ .../Examples/Rust/LibUnitTest_example.rs | 42 ++++++------- 6 files changed, 155 insertions(+), 140 deletions(-) diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs index b1efdd57..6795053e 100644 --- a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs +++ b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs @@ -4,31 +4,28 @@ 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 application that demonstrates the - usage of the Rust bindings of Calculator library +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::Wrapper; -use std::env; -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - if args.len() < 2 { - eprintln!("usage: {} ", args[0]); - process::exit(1); - } - let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - - let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); - let version = format!("calculator.version = {}.{}.{}", major, minor, micro); - println!("{}", version); +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/Injection/Calculation_component/Examples/Rust/Calculation_example.rs b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs index 9a67ef6c..b70b6c1c 100644 --- a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -4,41 +4,34 @@ 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 application that demonstrates the - usage of the Rust bindings of Calculation library +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; -use std::env; -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - if args.len() < 3 { - eprintln!("usage: {} ", args[0]); - process::exit(1); - } - let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - - let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); - let version = format!("calculation.version = {}.{}.{}", major, minor, micro); - println!("{}", version); - - let numbers = numbers::Wrapper::new(&args[2]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - let (major, minor, micro) = numbers.get_version().expect("could not query the version"); - println!("numbers.version = {}.{}.{}", major, minor, micro); - wrapper - .inject_component("Numbers", numbers.get_symbol_lookup_method().expect("could not get the symbol lookup method")) - .expect("could not inject the component"); +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_component("Numbers", numbers.get_symbol_lookup_method()?)?; + 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); + // the shortcut generated for imported components: wrapper.numbers() gives access to the injected wrapper + println!("multiply={}", calc.multiply()?.get_value()?); + Ok(()) } diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs index 87d3efc3..cb79f482 100644 --- a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs @@ -4,31 +4,49 @@ 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 application that demonstrates the - usage of the Rust bindings of Prime Numbers Library +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::Wrapper; -use std::env; -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - if args.len() < 2 { - eprintln!("usage: {} ", args[0]); - process::exit(1); - } - let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - - let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); - let version = format!("libprimes.version = {}.{}.{}", major, minor, micro); - println!("{}", version); +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)?; + 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 + 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/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs index c816cc39..e046a57f 100644 --- a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs +++ b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs @@ -4,31 +4,44 @@ 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 application that demonstrates the - usage of the Rust bindings of RTTI +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::Wrapper; -use std::env; -use std::process; - +use rtti::*; fn main() { - let args: Vec = env::args().collect(); - if args.len() < 2 { - eprintln!("usage: {} ", args[0]); - process::exit(1); - } - let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - - let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); - let version = format!("rtti.version = {}.{}.{}", major, minor, micro); - println!("{}", version); + // 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::().ok().expect("tiger").roar().unwrap(); } + } + assert!(iter.get_next_animal().unwrap().is_none()); + println!("No more Animals\nDone!"); } diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs index 1c38d8d0..2d4f9b56 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs @@ -4,31 +4,27 @@ 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 application that demonstrates the - usage of the Rust bindings of Thread-safe library +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::Wrapper; -use std::env; -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - if args.len() < 2 { - eprintln!("usage: {} ", args[0]); - process::exit(1); - } - let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - - let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); - let version = format!("libthreadsafe.version = {}.{}.{}", major, minor, micro); - println!("{}", version); +use libthreadsafe::*; +use std::sync::Arc; +fn main() -> Result<()> { + let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?; + let sr = Arc::new(wrapper.create_string_returner()?); + let soft = Arc::new(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/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs index 1c7a5181..57dce813 100644 --- a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs @@ -4,31 +4,29 @@ 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 application that demonstrates the - usage of the Rust bindings of ACT UnitTest FrameWork +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::Wrapper; -use std::env; -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - if args.len() < 2 { - eprintln!("usage: {} ", args[0]); - process::exit(1); - } - let wrapper = Wrapper::new(&args[1]).unwrap_or_else(|e| { - eprintln!("{}", e); - process::exit(1); - }); - - let (major, minor, micro) = wrapper.get_version().expect("could not query the version"); - let version = format!("libunittest.version = {}.{}.{}", major, minor, micro); - println!("{}", version); +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(()) } From fcf28e737ef7383ebf98f7ed63b89f27e3fb896f Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 12:46:29 +0100 Subject: [PATCH 06/16] Rust examples: keep the ACT header and note the hand-written content --- .../Examples/Rust/Calculator_example.rs | 7 +++++-- .../Examples/Rust/Calculation_example.rs | 7 +++++-- .../LibPrimes_component/Examples/Rust/LibPrimes_example.rs | 7 +++++-- Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs | 7 +++++-- .../Examples/Rust/LibThreadSafe_example.rs | 7 +++++-- .../Examples/Rust/LibUnitTest_example.rs | 7 +++++-- 6 files changed, 30 insertions(+), 12 deletions(-) diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs index 6795053e..52c97f84 100644 --- a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs +++ b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs @@ -4,8 +4,11 @@ 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. +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop +and extended by hand to exercise the bindings. ACT does not overwrite it. + +Abstract: This is a Rust application that demonstrates the + usage of the Rust bindings of Calculator library Interface version: 1.0.0 diff --git a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs index b70b6c1c..5abca6cf 100644 --- a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -4,8 +4,11 @@ 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. +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop +and extended by hand to exercise the bindings. ACT does not overwrite it. + +Abstract: This is a Rust application that demonstrates the + usage of the Rust bindings of Calculation library Interface version: 1.0.0 diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs index cb79f482..6952e32e 100644 --- a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs @@ -4,8 +4,11 @@ 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. +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop +and extended by hand to exercise the bindings. ACT does not overwrite it. + +Abstract: This is a Rust application that demonstrates the + usage of the Rust bindings of Prime Numbers Library Interface version: 1.2.0 diff --git a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs index e046a57f..a5fbae82 100644 --- a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs +++ b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs @@ -4,8 +4,11 @@ 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. +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop +and extended by hand to exercise the bindings. ACT does not overwrite it. + +Abstract: This is a Rust application that demonstrates the + usage of the Rust bindings of RTTI Interface version: 1.0.0 diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs index 2d4f9b56..4e117dc0 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs @@ -4,8 +4,11 @@ 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. +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop +and extended by hand to exercise the bindings. ACT does not overwrite it. + +Abstract: This is a Rust application that demonstrates the + usage of the Rust bindings of Thread-safe library Interface version: 1.0.0 diff --git a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs index 57dce813..452d2687 100644 --- a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs @@ -4,8 +4,11 @@ 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. +This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop +and extended by hand to exercise the bindings. ACT does not overwrite it. + +Abstract: This is a Rust application that demonstrates the + usage of the Rust bindings of ACT UnitTest FrameWork Interface version: 1.0.0 From 198526a7cd3c8def311aefe67027927bf8e80488 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 12:48:00 +0100 Subject: [PATCH 07/16] Rust examples: drop the generated wording from the header --- .../Examples/Rust/Calculator_example.rs | 7 ++----- .../Examples/Rust/Calculation_example.rs | 7 ++----- .../LibPrimes_component/Examples/Rust/LibPrimes_example.rs | 7 ++----- Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs | 7 ++----- .../Examples/Rust/LibThreadSafe_example.rs | 7 ++----- .../Examples/Rust/LibUnitTest_example.rs | 7 ++----- 6 files changed, 12 insertions(+), 30 deletions(-) diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs index 52c97f84..6795053e 100644 --- a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs +++ b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs @@ -4,11 +4,8 @@ Copyright (C) 2019 Calculator developers All rights reserved. -This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop -and extended by hand to exercise the bindings. ACT does not overwrite it. - -Abstract: This is a Rust application that demonstrates the - usage of the Rust bindings of Calculator library +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 diff --git a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs index 5abca6cf..b70b6c1c 100644 --- a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -4,11 +4,8 @@ Copyright (C) 2019 Calculation developers All rights reserved. -This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop -and extended by hand to exercise the bindings. ACT does not overwrite it. - -Abstract: This is a Rust application that demonstrates the - usage of the Rust bindings of Calculation library +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 diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs index 6952e32e..cb79f482 100644 --- a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs @@ -4,11 +4,8 @@ Copyright (C) 2019 PrimeDevelopers All rights reserved. -This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop -and extended by hand to exercise the bindings. ACT does not overwrite it. - -Abstract: This is a Rust application that demonstrates the - usage of the Rust bindings of Prime Numbers Library +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 diff --git a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs index a5fbae82..e046a57f 100644 --- a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs +++ b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs @@ -4,11 +4,8 @@ Copyright (C) 2021 ADSK All rights reserved. -This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop -and extended by hand to exercise the bindings. ACT does not overwrite it. - -Abstract: This is a Rust application that demonstrates the - usage of the Rust bindings of RTTI +Abstract: Rust example that exercises the Rust bindings of RTTI. + It only needs the example library of this component. Interface version: 1.0.0 diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs index 4e117dc0..2d4f9b56 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs @@ -4,11 +4,8 @@ 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 -and extended by hand to exercise the bindings. ACT does not overwrite it. - -Abstract: This is a Rust application that demonstrates the - usage of the Rust bindings of Thread-safe library +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 diff --git a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs index 452d2687..57dce813 100644 --- a/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs +++ b/Examples/UnitTest/LibUnitTest_component/Examples/Rust/LibUnitTest_example.rs @@ -4,11 +4,8 @@ Copyright (C) 2018 Autodesk All rights reserved. -This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop -and extended by hand to exercise the bindings. ACT does not overwrite it. - -Abstract: This is a Rust application that demonstrates the - usage of the Rust bindings of ACT UnitTest FrameWork +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 From fe7a583a78e94e3b4ea98427a8441c0eab53532a Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Fri, 4 Dec 2026 13:14:11 +0100 Subject: [PATCH 08/16] Rust binding: close soundness holes - Narrow Sync to strict classes, mark callback/pointer/symbol-lookup entry points unsafe - Add safe inject_ helper that keeps the injected wrapper alive - Validate enums inside structs through a raw twin instead of mem::zeroed - Clippy clean: matches!, annotated transmutes, no needless Ok(?) --- .../Bindings/Rust/src/lib.rs | 10 +- .../Bindings/Rust/src/lib.rs | 36 ++- .../Examples/Rust/Calculation_example.rs | 2 +- .../Bindings/Rust/src/lib.rs | 17 +- .../Bindings/Rust/src/lib.rs | 15 +- .../Examples/Rust/LibPrimes_example.rs | 5 +- .../RTTI_component/Bindings/Rust/src/lib.rs | 23 +- .../Bindings/Rust/src/lib.rs | 11 +- .../Bindings/Rust/src/lib.rs | 23 +- Source/buildbindingrust.go | 243 ++++++++++++++++-- 10 files changed, 320 insertions(+), 65 deletions(-) diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs index 81e62a2f..0946e39b 100644 --- a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs @@ -231,6 +231,7 @@ struct Api { 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)) @@ -317,10 +318,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -365,7 +365,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -653,6 +653,7 @@ impl Calculator { /// /// # Returns /// * `instance` - Variable that holds the sum of all enlisted Variables + #[allow(clippy::should_implement_trait)] pub fn add(&self) -> Result { let inner = self.inner_arc(); let handle = self.handle(); @@ -696,6 +697,7 @@ impl 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; diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs index ab09af4a..064a8760 100644 --- a/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs +++ b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs @@ -238,6 +238,7 @@ struct Api { 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)) @@ -336,10 +337,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -384,7 +384,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -573,6 +573,7 @@ impl Calculator { /// /// # Returns /// * `instance` - Variable that holds the sum of all enlisted Variables + #[allow(clippy::should_implement_trait)] pub fn add(&self) -> Result { let inner = self.inner_arc(); let handle = self.handle(); @@ -618,12 +619,16 @@ impl 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. - pub fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + /// + /// # 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 = unsafe { mem::transmute(symbol_lookup_method) }; + 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())?; @@ -642,6 +647,7 @@ impl 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; @@ -729,8 +735,11 @@ impl Wrapper { /// # Arguments /// * `name_space` - NameSpace of the injected component /// * `symbol_address_method` - Address of the SymbolAddressMethod of the injected component - /// The library providing the symbol lookup method has to stay loaded for as long as this wrapper is used. - pub fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + /// + /// # 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 inner = &self.inner; let c_name_space = CString::new(name_space) .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; @@ -742,7 +751,7 @@ impl Wrapper { if slot.is_some() { return Err(Error::new(error_code::COULDNOTLOADLIBRARY, "the component Numbers has already been injected")); } - *slot = Some(numbers::Wrapper::from_symbol_lookup_method(symbol_address_method)?); + *slot = Some(unsafe { numbers::Wrapper::from_symbol_lookup_method(symbol_address_method) }?); } _ => return Err(Error::new(error_code::COULDNOTLOADLIBRARY, format!("unknown namespace {}", name_space))), } @@ -760,4 +769,13 @@ impl Wrapper { inner.check(ptr::null_mut(), code)?; Ok(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 index b70b6c1c..63462227 100644 --- a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -20,7 +20,7 @@ fn main() -> calculation::Result<()> { let numbers = numbers::Wrapper::new(&a[2])?; let (ma, mi, mc) = numbers.get_version()?; println!("Numbers version: {}.{}.{}", ma, mi, mc); - wrapper.inject_component("Numbers", numbers.get_symbol_lookup_method()?)?; + 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)?)?; diff --git a/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs index 805f1a79..1cbb46ff 100644 --- a/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs +++ b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs @@ -226,6 +226,7 @@ struct Api { 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)) @@ -307,10 +308,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -355,7 +355,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -551,12 +551,16 @@ impl 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. - pub fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + /// + /// # 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 = unsafe { mem::transmute(symbol_lookup_method) }; + 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())?; @@ -575,6 +579,7 @@ impl 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; diff --git a/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs index 3d06bde5..eb611df4 100644 --- a/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs @@ -254,6 +254,7 @@ struct Api { 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)) @@ -340,10 +341,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -388,7 +388,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -584,7 +584,11 @@ impl Calculator { /// /// # Arguments /// * `progress_callback` - The progress callback - pub fn set_progress_callback(&self, progress_callback: ProgressCallback) -> Result<()> { + /// + /// # 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 inner = self.inner_arc(); let handle = self.handle(); let code = unsafe { (inner.api.libprimes_calculator_setprogresscallback)(handle, progress_callback) }; @@ -810,6 +814,7 @@ impl 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; diff --git a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs index cb79f482..1a7c10ea 100644 --- a/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs +++ b/Examples/Primes/LibPrimes_component/Examples/Rust/LibPrimes_example.rs @@ -30,7 +30,8 @@ fn main() -> Result<()> { println!("LibPrimes version: {}.{}.{}", a, b, c); let f = wrapper.create_factorization_calculator()?; f.set_value(735)?; - f.set_progress_callback(progress)?; + // 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() { @@ -42,7 +43,7 @@ fn main() -> Result<()> { Ok(()) => assert!(!ABORT_REQUESTED.load(Ordering::SeqCst)), } // without abort the calculation completes - f.set_progress_callback(quiet)?; + 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(); diff --git a/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs index 7b20e7e3..47f696fa 100644 --- a/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs @@ -231,6 +231,7 @@ struct Api { 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)) @@ -317,10 +318,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -365,7 +365,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -1296,12 +1296,16 @@ impl 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. - pub fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + /// + /// # 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 = unsafe { mem::transmute(symbol_lookup_method) }; + 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())?; @@ -1320,6 +1324,7 @@ impl 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; @@ -1395,7 +1400,11 @@ impl Wrapper { /// # Arguments /// * `name_space` - NameSpace of the injected component /// * `symbol_address_method` - Address of the SymbolAddressMethod of the injected component - pub fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + /// + /// # 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 inner = &self.inner; let c_name_space = CString::new(name_space) .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs index f637e274..88589ce1 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs @@ -239,6 +239,7 @@ struct Api { 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)) @@ -347,10 +348,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -395,7 +395,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -702,6 +702,8 @@ pub struct StrictStringReturner { parent: Base, } +unsafe impl Sync for StrictStringReturner {} + impl std::ops::Deref for StrictStringReturner { type Target = Base; @@ -814,6 +816,7 @@ impl 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; diff --git a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs index f1125d96..28c88c85 100644 --- a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs @@ -265,6 +265,7 @@ struct Api { 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)) @@ -353,10 +354,9 @@ pub struct Base { handle: Handle, } -// Instances may be moved and shared between threads. The library is responsible for protecting -// its own state (see the threadsafetyoption of the ACT class definition). +// 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 {} -unsafe impl Sync for Base {} impl Base { #[allow(dead_code)] @@ -401,7 +401,7 @@ impl Base { /// Tells whether the instance is of class `T` or of a class derived from it. pub fn is(&self) -> bool { - self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id)) + 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`. @@ -726,12 +726,16 @@ impl 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. - pub fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result { + /// + /// # 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 = unsafe { mem::transmute(symbol_lookup_method) }; + 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())?; @@ -750,6 +754,7 @@ impl 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; @@ -825,7 +830,11 @@ impl Wrapper { /// # Arguments /// * `name_space` - NameSpace of the injected component /// * `symbol_address_method` - Address of the SymbolAddressMethod of the injected component - pub fn inject_component(&self, name_space: &str, symbol_address_method: *mut c_void) -> Result<()> { + /// + /// # 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 inner = &self.inner; let c_name_space = CString::new(name_space) .map_err(|_| Error::new(error_code::INVALIDPARAM, "the string parameter name_space contains a NUL byte"))?; diff --git a/Source/buildbindingrust.go b/Source/buildbindingrust.go index eac536da..a58cb436 100644 --- a/Source/buildbindingrust.go +++ b/Source/buildbindingrust.go @@ -308,9 +308,7 @@ func buildRustExample(component ComponentDefinition, w LanguageWriter, crateName 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, " wrapper") - rl(w, fmt.Sprintf(" .%s(\"%s\", %s.%s().expect(\"could not get the symbol lookup method\"))", rustSnakeCase(component.Global.InjectionMethod), namespace, lower, rustSnakeCase(imported.Global.SymbolLookupMethod))) - rl(w, " .expect(\"could not inject the component\");") + rl(w, fmt.Sprintf(" wrapper.inject_%s(&%s).expect(\"could not inject the component\");", lower, lower)) } } } else { @@ -852,7 +850,130 @@ func buildRustStructs(component ComponentDefinition, w LanguageWriter) error { rl(w, fmt.Sprintf("// the size has to match the packed layout of the C ABI")) rl(w, fmt.Sprintf("const _: () = assert!(std::mem::size_of::<%s>() == %d);", rustTypeName(s.Name), size)) 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 { + 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 { + 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(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(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): + 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, " #[allow(dead_code)]") + rl(w, fmt.Sprintf(" 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, " #[allow(non_snake_case)]") + rl(w, fmt.Sprintf(" let 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 } @@ -931,6 +1052,7 @@ func buildRustApi(component ComponentDefinition, w LanguageWriter) error { 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))) @@ -1184,10 +1306,12 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas rl(w, " handle: Handle,") rl(w, "}") rl(w, "") - rl(w, "// Instances may be moved and shared between threads. The library is responsible for protecting") - rl(w, "// its own state (see the threadsafetyoption of the ACT class definition).") + 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)) - rl(w, fmt.Sprintf("unsafe impl Sync 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)]") @@ -1210,6 +1334,10 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas 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, "") @@ -1237,7 +1365,7 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas 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, " self.class_type_id().map_or(false, |id| T::TYPE_IDS.contains(&id))") + rl(w, " matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id))") rl(w, " }") if acquireMethod, ok := findRustGlobalMethod(component, component.Global.AcquireMethod); ok { exportName := GetCExportName(component.NameSpace, "Wrapper", acquireMethod, true) @@ -1382,12 +1510,16 @@ func buildRustWrapper(component ComponentDefinition, w LanguageWriter) error { 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, " pub fn from_symbol_lookup_method(symbol_lookup_method: *mut c_void) -> Result {") + 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 = unsafe { mem::transmute(symbol_lookup_method) };") + 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())?;") @@ -1410,6 +1542,7 @@ func buildRustWrapper(component ComponentDefinition, w LanguageWriter) error { 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))) @@ -1427,6 +1560,24 @@ func buildRustWrapper(component ComponentDefinition, w LanguageWriter) error { 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 } @@ -1452,6 +1603,7 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe var initCallArgs []string var initLines []string var postLines []string + var rawParams []string var returnTypes []string var returnValues []string var inDocs []string @@ -1471,6 +1623,9 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe 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) @@ -1509,6 +1664,7 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe 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) @@ -1533,11 +1689,20 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe returnTypes = append(returnTypes, class) returnValues = append(returnValues, fmt.Sprintf("%s::from_raw(%s)?", class, name)) case "struct": - declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", name, class)) - callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) - returnTypes = append(returnTypes, class) - returnValues = append(returnValues, name) + if rustStructNeedsRaw(component, param.ParamClass) { + raw := rustRawStructName(param.ParamClass) + declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", name, raw)) + callArgs = append(callArgs, fmt.Sprintf("(&mut %s as *mut %s).cast::<%s>()", name, raw, class)) + initCallArgs = append(initCallArgs, fmt.Sprintf("(&mut %s as *mut %s).cast::<%s>()", name, raw, class)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, fmt.Sprintf("%s.into_checked()?", name)) + } else { + declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", name, class)) + callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) + initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + returnTypes = append(returnTypes, class) + returnValues = append(returnValues, name) + } case "string": requiresInitCall = true declarations = append(declarations, fmt.Sprintf("let mut needed_%s: u32 = 0;", name)) @@ -1550,6 +1715,7 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe returnValues = append(returnValues, fmt.Sprintf("string_from_buffer(&buffer_%s, 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 { @@ -1563,16 +1729,24 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe } else { elementType = class zero = "unsafe { mem::zeroed() }" + if rustStructNeedsRaw(component, param.ParamClass) { + bufferType = rustRawStructName(param.ParamClass) + bufferPtr = fmt.Sprintf(".cast::<%s>()", class) + resultExpr = fmt.Sprintf(".into_iter().map(%s::into_checked).collect::>>()?", bufferType) + } + } + if bufferType == "" { + bufferType = elementType } requiresInitCall = true declarations = append(declarations, fmt.Sprintf("let mut needed_%s: u64 = 0;", name)) - declarations = append(declarations, fmt.Sprintf("let mut buffer_%s: Vec<%s> = Vec::new();", name, elementType)) + declarations = append(declarations, fmt.Sprintf("let mut buffer_%s: Vec<%s> = Vec::new();", name, bufferType)) initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut needed_%s, ptr::null_mut()", name)) initLines = append(initLines, fmt.Sprintf("buffer_%s.resize(needed_%s as usize, %s);", name, name, zero)) - callArgs = append(callArgs, fmt.Sprintf("buffer_%s.len() as u64, &mut needed_%s, buffer_%s.as_mut_ptr()", name, name, name)) + callArgs = append(callArgs, fmt.Sprintf("buffer_%s.len() as u64, &mut needed_%s, buffer_%s.as_mut_ptr()%s", name, name, name, bufferPtr)) postLines = append(postLines, fmt.Sprintf("buffer_%s.truncate(needed_%s as usize);", name, name)) returnTypes = append(returnTypes, fmt.Sprintf("Vec<%s>", elementType)) - returnValues = append(returnValues, fmt.Sprintf("buffer_%s", name)) + returnValues = append(returnValues, fmt.Sprintf("buffer_%s%s", name, resultExpr)) case "class": declarations = append(declarations, fmt.Sprintf("let mut %s: Handle = ptr::null_mut();", name)) callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) @@ -1594,6 +1768,11 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe } } + isUnsafe := false + unsafeDocs := false + if len(rawParams) > 0 { + isUnsafe = true + } if isGlobal && len(method.MethodName) > 0 && method.MethodName == component.Global.InjectionMethod && len(component.ImportComponents) > 0 { namespaceParam, symbolParam := "", "" for _, p := range method.Params { @@ -1614,12 +1793,13 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe postLines = append(postLines, " if 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(" *slot = Some(%s::Wrapper::from_symbol_lookup_method(%s)?);", lower, symbolParam)) + postLines = append(postLines, fmt.Sprintf(" *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, "}") - inDocs = append(inDocs, "/// The library providing the symbol lookup method has to stay loaded for as long as this wrapper is used.") + isUnsafe = true + unsafeDocs = true } } @@ -1631,6 +1811,9 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe 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, ", ")) @@ -1657,12 +1840,32 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe } } + if unsafeDocs { + rl(w, " ///") + rl(w, " /// # Safety") + rl(w, " /// The symbol lookup method must be valid for the imported component, and its library must stay loaded") + rl(w, " /// for as long as this wrapper is used. Prefer the safe `inject_*` functions.") + } 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, ", ") } - rl(w, fmt.Sprintf(" pub fn %s(%s) -> Result<%s> {", rustSnakeCase(method.MethodName), signature, returnType)) + 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 " + } + rl(w, fmt.Sprintf(" pub %sfn %s(%s) -> Result<%s> {", unsafeKeyword, rustSnakeCase(method.MethodName), signature, returnType)) handleExpr := "ptr::null_mut()" if isGlobal { From 963f997b6a87c1f8686c12bc1b29926d22d1973c Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:14:52 +0100 Subject: [PATCH 09/16] Dockerfile: download Free Pascal from the official site - sourceforge dropped the connection mid-download - fail on HTTP errors, retry and resume --- Build/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/Dockerfile b/Build/Dockerfile index 367a1b7a..0707714e 100644 --- a/Build/Dockerfile +++ b/Build/Dockerfile @@ -29,7 +29,7 @@ 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 From 7249992c219decb4e925cc4419eb983f4b6bf2aa Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:31:22 +0100 Subject: [PATCH 10/16] Rust binding: safe closure callbacks, Go tests, Cargo description - Methods with callbacks and user data take closures; the C ABI variant is kept as an unsafe _raw function - A panic in a closure aborts instead of unwinding into the library - Go unit tests for the generator, including a generated crate compiled with clippy - Windows: no unused CStr import; Cargo.toml gets a description --- .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/src/lib.rs | 3 +- .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/src/lib.rs | 3 +- .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/src/lib.rs | 3 +- .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/src/lib.rs | 9 +- .../RTTI_component/Bindings/Rust/Cargo.toml | 1 + .../RTTI_component/Bindings/Rust/src/lib.rs | 3 +- .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/src/lib.rs | 3 +- .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/src/lib.rs | 3 +- Source/buildbindingrust.go | 301 ++++++++++++++++- Source/buildbindingrust_test.go | 306 ++++++++++++++++++ 16 files changed, 631 insertions(+), 10 deletions(-) create mode 100644 Source/buildbindingrust_test.go diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml index 7b636769..19737420 100644 --- a/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml @@ -2,3 +2,4 @@ name = "calculator" version = "1.0.0" edition = "2021" +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 index 0946e39b..c64d4cdc 100644 --- a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.0.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml index 7400f87d..7751d268 100644 --- a/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml +++ b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml @@ -2,6 +2,7 @@ name = "calculation" version = "1.0.0" edition = "2021" +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 index 064a8760..cc1e194c 100644 --- a/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs +++ b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.0.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { diff --git a/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml index 72d2e44d..3ab1218f 100644 --- a/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml +++ b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml @@ -2,3 +2,4 @@ name = "numbers" version = "1.0.0" edition = "2021" +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 index 1cbb46ff..3fd3fd62 100644 --- a/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs +++ b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.0.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { diff --git a/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml index 8c2a8b2d..790bf963 100644 --- a/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml @@ -2,3 +2,4 @@ name = "libprimes" version = "1.2.0" edition = "2021" +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 index eb611df4..da4f4fcf 100644 --- a/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.2.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { @@ -134,6 +135,8 @@ fn string_from_buffer(buffer: &[u8], filled: u32) -> String { 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; @@ -283,6 +286,9 @@ impl Api { 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. @@ -294,6 +300,7 @@ impl Inner { Arc::new(Self { api, _lib: lib, + callbacks: Mutex::new(std::collections::HashMap::new()), }) } diff --git a/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml index 9ef92bb3..211b8874 100644 --- a/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml @@ -2,3 +2,4 @@ name = "rtti" version = "1.0.0" edition = "2021" +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 index 47f696fa..07cf4b14 100644 --- a/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.0.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml index a8909f46..5edf5367 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml @@ -2,3 +2,4 @@ name = "libthreadsafe" version = "1.0.0" edition = "2021" +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 index 88589ce1..a9b1787d 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.0.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { diff --git a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml index af440269..ef41c7da 100644 --- a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml @@ -2,3 +2,4 @@ name = "libunittest" version = "1.0.0" edition = "2021" +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 index 28c88c85..ec499bdb 100644 --- a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs @@ -13,7 +13,7 @@ Interface version: 1.0.0 */ -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -23,6 +23,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { diff --git a/Source/buildbindingrust.go b/Source/buildbindingrust.go index a58cb436..c881d580 100644 --- a/Source/buildbindingrust.go +++ b/Source/buildbindingrust.go @@ -228,6 +228,7 @@ func buildRustCargo(component ComponentDefinition, w LanguageWriter) { rl(w, fmt.Sprintf("name = \"%s\"", strings.ToLower(component.NameSpace))) rl(w, fmt.Sprintf("version = \"%s\"", component.Version)) rl(w, "edition = \"2021\"") + rl(w, fmt.Sprintf("description = \"Rust bindings of %s\"", strings.ReplaceAll(component.LibraryName, "\"", "'"))) if len(component.ImportComponents) > 0 { rl(w, "") rl(w, "[dependencies]") @@ -319,7 +320,7 @@ func buildRustExample(component ComponentDefinition, w LanguageWriter, crateName return nil } -const rustDynlibTemplate = `use std::ffi::{CStr, CString}; +const rustDynlibTemplate = `use std::ffi::CString; use std::fmt; use std::mem; use std::os::raw::{c_char, c_void}; @@ -329,6 +330,7 @@ use std::sync::Arc; #[cfg(unix)] mod dynlib { use super::*; + use std::ffi::CStr; type DynResult = std::result::Result; #[link(name = "dl")] extern "C" { @@ -619,7 +621,7 @@ func buildRustBinding(component ComponentDefinition, w LanguageWriter) error { for _, line := range strings.Split(rustDynlibTemplate, "\n") { rl(w, line) } - if len(component.ImportComponents) > 0 { + if len(component.ImportComponents) > 0 || len(component.Functions) > 0 { rl(w, "use std::sync::Mutex;") rl(w, "") } @@ -1072,6 +1074,11 @@ func buildRustApi(component ComponentDefinition, w LanguageWriter) error { 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))) } @@ -1086,6 +1093,9 @@ func buildRustApi(component ComponentDefinition, w LanguageWriter) error { 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))) } @@ -1593,7 +1603,191 @@ func rustWrapHandle(paramClass string, handle string) string { } // 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(&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) @@ -1617,6 +1811,23 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe 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, "cb_user_data") + initCallArgs = append(initCallArgs, "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, name+"_trampoline") + initCallArgs = append(initCallArgs, name+"_trampoline") + continue + } + } + switch param.ParamPass { case "in": inDocs = append(inDocs, fmt.Sprintf("/// * `%s` - %s", name, doc)) @@ -1768,6 +1979,76 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe } } + 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 %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 cb_state = &*(%s as *const CallbackState);", spec.userDataName)) + if spec.usesClassArgs { + declarations = append(declarations, " let cb_inner = match cb_state.inner.upgrade() { Some(inner) => inner, None => return };") + declarations = append(declarations, " let cb_wrapper = Wrapper { inner: cb_inner };") + } + for _, c := range spec.conversions { + declarations = append(declarations, " "+c) + } + declarations = append(declarations, " let cb_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {") + declarations = append(declarations, fmt.Sprintf(" let mut callback = cb_state.%s.lock().unwrap_or_else(|e| e.into_inner());", field)) + declarations = append(declarations, fmt.Sprintf(" (*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 cb_result.is_err() { std::process::abort(); }") + } else { + declarations = append(declarations, " let cb_values = match cb_result { Ok(values) => values, Err(_) => std::process::abort() };") + } + switch len(spec.outPointers) { + case 0: + case 1: + declarations = append(declarations, rustCallbackWrite(spec, 0, "cb_values")) + default: + for i := range spec.outPointers { + declarations = append(declarations, rustCallbackWrite(spec, i, fmt.Sprintf("cb_values.%d", i))) + } + } + declarations = append(declarations, "}") + } + fields := []string{} + if usesClasses { + fields = append(fields, "inner: Arc::downgrade(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 cb_state = Arc::new(CallbackState { %s });", strings.Join(fields, ", "))) + declarations = append(declarations, "let cb_user_data = Arc::as_ptr(&cb_state) as *mut c_void;") + key := "0usize" + if !isGlobal { + key = "handle as usize" + } + postLines = append(postLines, fmt.Sprintf("inner.callbacks.lock().unwrap_or_else(|e| e.into_inner()).insert((%s, \"%s\"), std::boxed::Box::new(cb_state));", key, rustSnakeCase(method.MethodName))) + } + isUnsafe := false unsafeDocs := false if len(rawParams) > 0 { @@ -1825,6 +2106,16 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe } 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") @@ -1865,7 +2156,11 @@ func writeRustMethod(component ComponentDefinition, method ComponentDefinitionMe if isUnsafe { unsafeKeyword = "unsafe " } - rl(w, fmt.Sprintf(" pub %sfn %s(%s) -> Result<%s> {", unsafeKeyword, rustSnakeCase(method.MethodName), signature, returnType)) + 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 { diff --git a/Source/buildbindingrust_test.go b/Source/buildbindingrust_test.go new file mode 100644 index 00000000..f429d0ed --- /dev/null +++ b/Source/buildbindingrust_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestRustSnakeCase(t *testing.T) { + tests := map[string]string{ + "GetVersion": "get_version", + "SetProgressCallback": "set_progress_callback", + "ClassTypeId": "class_type_id", + "ByteData": "byte_data", + "Value": "value", + "Type": "type_", // a keyword of Rust + "Match": "match_", + "X2Y": "x2_y", + } + for input, expected := range tests { + if got := rustSnakeCase(input); got != expected { + t.Errorf("rustSnakeCase(%q) = %q, expected %q", input, got, expected) + } + } +} + +func TestRustBasicType(t *testing.T) { + tests := map[string]string{ + "uint8": "u8", "uint16": "u16", "uint32": "u32", "uint64": "u64", + "int8": "i8", "int16": "i16", "int32": "i32", "int64": "i64", + "bool": "bool", "single": "f32", "double": "f64", "pointer": "*mut c_void", + } + for input, expected := range tests { + got, err := rustBasicType(input) + if err != nil || got != expected { + t.Errorf("rustBasicType(%q) = %q, %v, expected %q", input, got, err, expected) + } + } + if _, err := rustBasicType("string"); err == nil { + t.Error("rustBasicType(\"string\") should fail") + } +} + +func rustTestStruct(name string, members ...ComponentDefinitionMember) ComponentDefinitionStruct { + return ComponentDefinitionStruct{Name: name, Members: members} +} + +func TestRustStructLayout(t *testing.T) { + component := ComponentDefinition{Structs: []ComponentDefinitionStruct{ + // no padding: the natural layout of C is the packed layout + rustTestStruct("Position", ComponentDefinitionMember{Name: "Coordinates", Type: "single", Rows: 3}), + // the double needs padding after the byte in C, the ABI of ACT packs it + rustTestStruct("Mixed", + ComponentDefinitionMember{Name: "Flag", Type: "uint8"}, + ComponentDefinitionMember{Name: "Value", Type: "double"}), + // a matrix is stored by column + rustTestStruct("Transform", ComponentDefinitionMember{Name: "Fields", Type: "single", Rows: 3, Columns: 4}), + rustTestStruct("Aligned", + ComponentDefinitionMember{Name: "A", Type: "uint32", Rows: 2}, + ComponentDefinitionMember{Name: "B", Type: "double", Rows: 2}), + }} + tests := []struct { + name string + size uint64 + natural bool + }{ + {"Position", 12, true}, + {"Mixed", 9, false}, + {"Transform", 48, true}, + {"Aligned", 24, true}, + } + for _, test := range tests { + size, _, natural := rustStructLayout(component, test.name) + if size != test.size || natural != test.natural { + t.Errorf("rustStructLayout(%s) = %d, %v, expected %d, %v", test.name, size, natural, test.size, test.natural) + } + } +} + +func TestRustStructMemberType(t *testing.T) { + tests := []struct { + member ComponentDefinitionMember + expected string + }{ + {ComponentDefinitionMember{Type: "uint32"}, "u32"}, + {ComponentDefinitionMember{Type: "single", Rows: 3}, "[f32; 3]"}, + // [column][row], like the other bindings + {ComponentDefinitionMember{Type: "single", Rows: 3, Columns: 4}, "[[f32; 3]; 4]"}, + {ComponentDefinitionMember{Type: "enum", Class: "Mode"}, "Mode"}, + {ComponentDefinitionMember{Type: "struct", Class: "Position", Rows: 2}, "[Position; 2]"}, + } + for _, test := range tests { + got, err := rustStructMemberType(test.member) + if err != nil || got != test.expected { + t.Errorf("rustStructMemberType(%+v) = %q, %v, expected %q", test.member, got, err, test.expected) + } + } +} + +func TestRustStructNeedsRaw(t *testing.T) { + component := ComponentDefinition{Structs: []ComponentDefinitionStruct{ + rustTestStruct("Plain", ComponentDefinitionMember{Name: "A", Type: "uint32"}), + rustTestStruct("WithEnum", ComponentDefinitionMember{Name: "Mode", Type: "enum", Class: "Mode"}), + rustTestStruct("Nested", ComponentDefinitionMember{Name: "Inner", Type: "struct", Class: "WithEnum"}), + rustTestStruct("NestedPlain", ComponentDefinitionMember{Name: "Inner", Type: "struct", Class: "Plain"}), + }} + expected := map[string]bool{"Plain": false, "WithEnum": true, "Nested": true, "NestedPlain": false, "Unknown": false} + for name, want := range expected { + if got := rustStructNeedsRaw(component, name); got != want { + t.Errorf("rustStructNeedsRaw(%s) = %v, expected %v", name, got, want) + } + } +} + +const rustTestComponent = ` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +` + +func generateRustTestComponent(t *testing.T) (string, string) { + t.Helper() + dir := t.TempDir() + file := filepath.Join(dir, "rusttest.xml") + if err := os.WriteFile(file, []byte(rustTestComponent), 0644); err != nil { + t.Fatal(err) + } + component, err := ReadComponentDefinition(file, "1.0.0") + if err != nil { + t.Fatal(err) + } + if err := component.CheckComponentDefinition(); err != nil { + t.Fatal(err) + } + crate := filepath.Join(dir, "Bindings", "Rust") + if err := BuildBindingRustDynamic(component, crate, "", " "); err != nil { + t.Fatal(err) + } + source, err := os.ReadFile(filepath.Join(crate, "src", "lib.rs")) + if err != nil { + t.Fatal(err) + } + return crate, string(source) +} + +func TestRustGeneratedBinding(t *testing.T) { + _, source := generateRustTestComponent(t) + + expected := []string{ + // enumerations in structs are received as integers and checked + "pub struct RawPacket {", + "fn into_checked(self) -> Result", + "pub struct RawWrapped {", + "(&mut packet as *mut RawPacket).cast::()", + "into_iter().map(RawPacket::into_checked)", + // the struct has a padding in C, the ABI of ACT does not + "#[repr(C, packed)]", + "const _: () = assert!(std::mem::size_of::() == 21);", + // callbacks with user data come in a safe variant with closures and an unsafe raw variant + "pub fn set_notify(&self, callback: impl FnMut(&Worker, Mode, &str, &[u8]) -> bool + Send + 'static) -> Result<()>", + "pub unsafe fn set_notify_raw(&self, callback: Notify, user_data: *mut c_void) -> Result<()>", + "std::panic::catch_unwind", + // without user data a closure has nowhere to live: only the raw callback is offered, as unsafe + "pub unsafe fn set_stateless(&self, callback: Stateless) -> Result<()>", + // arrays that are filled for the library are not mapped to closures + "pub unsafe fn set_bulk(&self, callback: Bulk, user_data: *mut c_void) -> Result<()>", + // only classes declared with the strict thread safety option are Sync + "unsafe impl Send for Base {}", + } + for _, e := range expected { + if !strings.Contains(source, e) { + t.Errorf("the generated binding does not contain %q", e) + } + } + for _, unexpected := range []string{"fn set_bulk_raw", "fn set_stateless_raw", "unsafe impl Sync for Base"} { + if strings.Contains(source, unexpected) { + t.Errorf("the generated binding should not contain %q", unexpected) + } + } +} + +func TestRustGeneratedCargo(t *testing.T) { + crate, _ := generateRustTestComponent(t) + cargo, err := os.ReadFile(filepath.Join(crate, "Cargo.toml")) + if err != nil { + t.Fatal(err) + } + for _, e := range []string{`name = "rusttest"`, `version = "1.2.3"`, `description = "Rust bindings of Rust Test Library"`} { + if !strings.Contains(string(cargo), e) { + t.Errorf("Cargo.toml does not contain %q:\n%s", e, cargo) + } + } +} + +// the generated crate has to compile without warnings, which needs cargo +func TestRustGeneratedBindingCompiles(t *testing.T) { + if _, err := exec.LookPath("cargo"); err != nil { + t.Skip("cargo is not available") + } + crate, _ := generateRustTestComponent(t) + command := exec.Command("cargo", "clippy", "--quiet", "--", "-D", "warnings") + command.Dir = crate + command.Env = append(os.Environ(), "CARGO_TARGET_DIR="+t.TempDir()) + output, err := command.CombinedOutput() + if err != nil { + if strings.Contains(string(output), "no such command: `clippy`") { + command = exec.Command("cargo", "check", "--quiet") + command.Dir = crate + command.Env = append(os.Environ(), "CARGO_TARGET_DIR="+t.TempDir()) + output, err = command.CombinedOutput() + } + if err != nil { + t.Fatalf("the generated crate does not compile:\n%s", output) + } + } +} From ae19a9a086a64cfb6060bc0754f525bfc8673fb4 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:32:08 +0100 Subject: [PATCH 11/16] Add Rust documentation - Usage, types, classes, threads, callbacks, injection - README: link and tested platforms --- Documentation/Rust.md | 119 ++++++++++++++++++++++++++++++++++++++++++ README.md | 4 +- 2 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 Documentation/Rust.md diff --git a/Documentation/Rust.md b/Documentation/Rust.md new file mode 100644 index 00000000..588468de --- /dev/null +++ b/Documentation/Rust.md @@ -0,0 +1,119 @@ +# 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`. + +## 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. +* 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. +* 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`. + +Not supported: the `enumarray` parameter type. diff --git a/README.md b/README.md index 135a63dd..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. @@ -68,7 +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) | 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 From 58443deae6c8f8dffa4544911ebc4f6e364b19d2 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:43:32 +0100 Subject: [PATCH 12/16] Rust binding: runtime tests, minimum Rust version - Go test builds a C library and runs the generated crate against it: closures, enums in structs, invalid values, panic abort - rust-version 1.65 in the generated Cargo.toml (warning free from 1.65, builds from 1.57) --- Documentation/Rust.md | 4 + .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/Cargo.toml | 1 + .../RTTI_component/Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/Cargo.toml | 1 + .../Bindings/Rust/Cargo.toml | 1 + Source/buildbindingrust.go | 2 + Source/buildbindingrust_runtime_test.go | 263 ++++++++++++++++++ Source/buildbindingrust_test.go | 2 +- 11 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 Source/buildbindingrust_runtime_test.go diff --git a/Documentation/Rust.md b/Documentation/Rust.md index 588468de..e345bea2 100644 --- a/Documentation/Rust.md +++ b/Documentation/Rust.md @@ -21,6 +21,10 @@ 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 diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml index 19737420..1bd4b391 100644 --- a/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml @@ -2,4 +2,5 @@ name = "calculator" version = "1.0.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of Calculator library" diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml index 7751d268..5872e8d6 100644 --- a/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml +++ b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml @@ -2,6 +2,7 @@ name = "calculation" version = "1.0.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of Calculation library" [dependencies] diff --git a/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml index 3ab1218f..0969bca4 100644 --- a/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml +++ b/Examples/Injection/Numbers_component/Bindings/Rust/Cargo.toml @@ -2,4 +2,5 @@ name = "numbers" version = "1.0.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of Numbers library" diff --git a/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml index 790bf963..dd29b739 100644 --- a/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/Cargo.toml @@ -2,4 +2,5 @@ name = "libprimes" version = "1.2.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of Prime Numbers Library" diff --git a/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml index 211b8874..f1995b55 100644 --- a/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/Cargo.toml @@ -2,4 +2,5 @@ name = "rtti" version = "1.0.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of RTTI" diff --git a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml index 5edf5367..db02de5f 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/Cargo.toml @@ -2,4 +2,5 @@ name = "libthreadsafe" version = "1.0.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of Thread-safe library" diff --git a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml index ef41c7da..92f0bae3 100644 --- a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/Cargo.toml @@ -2,4 +2,5 @@ name = "libunittest" version = "1.0.0" edition = "2021" +rust-version = "1.65" description = "Rust bindings of ACT UnitTest FrameWork" diff --git a/Source/buildbindingrust.go b/Source/buildbindingrust.go index c881d580..91b4bd6d 100644 --- a/Source/buildbindingrust.go +++ b/Source/buildbindingrust.go @@ -228,6 +228,8 @@ func buildRustCargo(component ComponentDefinition, w LanguageWriter) { 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 = \"Rust bindings of %s\"", strings.ReplaceAll(component.LibraryName, "\"", "'"))) if len(component.ImportComponents) > 0 { rl(w, "") diff --git a/Source/buildbindingrust_runtime_test.go b/Source/buildbindingrust_runtime_test.go new file mode 100644 index 00000000..7cab2bf4 --- /dev/null +++ b/Source/buildbindingrust_runtime_test.go @@ -0,0 +1,263 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// A minimal library with the C ABI of the component in rustTestComponent. It misbehaves on request: with the +// environment variable RUSTTEST_CORRUPT it writes values into enumerations that do not exist. +const rustTestLibrary = ` +#include +#include +#include + +#define EXPORT __attribute__((visibility("default"))) + +#pragma pack(1) +typedef struct { uint8_t Flag; int32_t Mode; int32_t Modes[2]; double Amount; } Packet; +typedef struct { Packet Inner; } Wrapped; +#pragma pack() + +typedef void * Handle; +typedef struct { int refs; } Worker; +typedef void (*Notify)(Handle, int32_t, const char *, uint64_t, const uint8_t *, void *, bool *); +typedef void (*Stateless)(double); +typedef void (*Bulk)(uint64_t, uint64_t *, uint8_t *, void *); + +EXPORT int32_t rusttest_getversion(uint32_t * a, uint32_t * b, uint32_t * c) { *a = 1; *b = 2; *c = 3; return 0; } + +EXPORT int32_t rusttest_getlasterror(Handle h, uint32_t size, uint32_t * needed, char * buffer, bool * has) { + if (needed) *needed = 1; + if (buffer && size >= 1) buffer[0] = 0; + if (has) *has = false; + return 0; +} + +EXPORT int32_t rusttest_acquireinstance(Handle h) { ((Worker *) h)->refs++; return 0; } +EXPORT int32_t rusttest_releaseinstance(Handle h) { + Worker * w = (Worker *) h; + if (w->refs <= 0) return 5; + if (--w->refs == 0) free(w); + return 0; +} +EXPORT int32_t rusttest_createworker(Handle * out) { + Worker * w = malloc(sizeof(Worker)); + w->refs = 1; + *out = w; + return 0; +} +EXPORT int32_t rusttest_base_classtypeid(Handle h, uint64_t * out) { *out = 0; return 0; } + +// calls the callback with a valid enumeration, an unknown one (which must not reach the closure) and null pointers, +// and checks that the callback leaves the reference count as it was +EXPORT int32_t rusttest_worker_setnotify(Handle h, Notify cb, void * user) { + Worker * w = (Worker *) h; + int before = w->refs; + uint8_t data[3] = {1, 2, 3}; + bool stop = false, ignored = false; + cb(h, 1, "hello", 3, data, user, &stop); + if (w->refs != before) return 5; + cb(h, 99, "unknown", 0, NULL, user, &ignored); + if (w->refs != before) return 5; + cb(h, 0, NULL, 0, NULL, user, &ignored); + if (w->refs != before) return 5; + return stop ? 5 : 0; +} + +EXPORT int32_t rusttest_worker_setstateless(Handle h, Stateless cb) { cb(2.5); return 0; } + +EXPORT int32_t rusttest_worker_setbulk(Handle h, Bulk cb, void * user) { + uint64_t needed = 0; + cb(0, &needed, NULL, user); + if (needed != 4) return 5; + uint8_t buffer[4] = {0, 0, 0, 0}; + uint64_t filled = needed; + cb(4, &filled, buffer, user); + return (buffer[0] == 9 && buffer[3] == 6) ? 0 : 5; +} + +static void fill(Packet * p, int index) { + p->Flag = (uint8_t) (7 + index); + p->Mode = 1; + p->Modes[0] = 0; + p->Modes[1] = 1; + p->Amount = 2.5 + index; + if (getenv("RUSTTEST_CORRUPT") && index == 1) p->Modes[1] = 42; + if (getenv("RUSTTEST_CORRUPT") && index == 0) p->Modes[0] = 77; +} + +EXPORT int32_t rusttest_worker_getpacket(Handle h, Packet * out) { fill(out, 0); return 0; } +EXPORT int32_t rusttest_worker_getpackets(Handle h, uint64_t size, uint64_t * needed, Packet * out) { + if (needed) *needed = 2; + if (out) { + if (size < 2) return 4; + fill(&out[0], 0); + fill(&out[1], 1); + } + return 0; +} +EXPORT int32_t rusttest_worker_getwrapped(Handle h, Wrapped * out) { fill(&out->Inner, 0); return 0; } +` + +const rustTestProgram = ` +use rusttest::*; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +static STATELESS: AtomicU64 = AtomicU64::new(0); + +unsafe extern "C" fn stateless(value: f64) { + STATELESS.store(value.to_bits(), Ordering::SeqCst); +} + +unsafe extern "C" fn bulk(_size: u64, needed: *mut u64, buffer: *mut u8, _user: *mut c_void) { + if buffer.is_null() { + *needed = 4; + } else { + for (i, v) in [9u8, 8, 7, 6].iter().enumerate() { + *buffer.add(i) = *v; + } + } +} + +fn main() { + let args: Vec = std::env::args().collect(); + let wrapper = Wrapper::new(&args[1]).unwrap(); + assert_eq!(wrapper.get_version().unwrap(), (1, 2, 3)); + let worker = wrapper.create_worker().unwrap(); + + if args.get(2).map(|s| s.as_str()) == Some("panic") { + worker.set_notify(|_, _, _, _| panic!("boom")).unwrap(); + println!("survived a panic in a callback"); + return; + } + + // closure with state, enumeration, string, array and a borrowed class argument; the library checks the + // reference count after each call, and the closure calls back into the library through the borrowed worker + let seen = Arc::new(Mutex::new(Vec::new())); + let sink = seen.clone(); + worker + .set_notify(move |source, mode, text, data| { + let packet = source.get_packet().unwrap(); + let flag = packet.flag; + sink.lock().unwrap().push((mode, text.to_string(), data.to_vec(), flag)); + false + }) + .unwrap(); + assert_eq!( + *seen.lock().unwrap(), + vec![(Mode::Slow, "hello".to_string(), vec![1u8, 2, 3], 7), (Mode::Fast, String::new(), vec![], 7)], + "the call with an unknown enumeration must be skipped" + ); + + // the value returned by the closure reaches the library + let error = worker.set_notify(|_, _, _, _| true).unwrap_err(); + assert_eq!(error.code, 5); + + // setting a callback again replaces the closure, and many calls keep the reference counts balanced + for _ in 0..2000 { + worker.set_notify(|source, _, _, _| source.get_packet().is_err()).unwrap(); + } + + // callbacks without user data and with arrays to fill are only available as unsafe functions + unsafe { + worker.set_stateless(stateless).unwrap(); + worker.set_bulk(bulk, std::ptr::null_mut()).unwrap(); + } + assert_eq!(f64::from_bits(STATELESS.load(Ordering::SeqCst)), 2.5); + + // structs with enumerations: single, array and nested + let packet = worker.get_packet().unwrap(); + let (flag, mode, modes, amount) = (packet.flag, packet.mode, packet.modes, packet.amount); + assert_eq!((flag, mode, modes, amount), (7, Mode::Slow, [Mode::Fast, Mode::Slow], 2.5)); + let packets = worker.get_packets().unwrap(); + assert_eq!(packets.len(), 2); + let second = packets[1].flag; + assert_eq!(second, 8); + let wrapped = worker.get_wrapped().unwrap(); + let inner = wrapped.inner; + let inner_mode = inner.mode; + assert_eq!(inner_mode, Mode::Slow); + + // values the library writes into enumerations that do not exist are reported, in every kind of struct result + std::env::set_var("RUSTTEST_CORRUPT", "1"); + for error in [ + worker.get_packet().err().expect("an invalid enumeration in a struct"), + worker.get_packets().err().expect("an invalid enumeration in an array of structs"), + worker.get_wrapped().err().expect("an invalid enumeration in a nested struct"), + ] { + assert_eq!(error.code, error_code::INVALIDCAST); + } + println!("ALL OK"); +} +` + +func TestRustRuntimeAgainstCLibrary(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("needs a C compiler") + } + cargo, err := exec.LookPath("cargo") + if err != nil { + t.Skip("cargo is not available") + } + compiler, err := exec.LookPath("cc") + if err != nil { + t.Skip("cc is not available") + } + crate, _ := generateRustTestComponent(t) + dir := t.TempDir() + + extension := ".so" + if runtime.GOOS == "darwin" { + extension = ".dylib" + } + source := filepath.Join(dir, "rusttest.c") + library := filepath.Join(dir, "rusttest"+extension) + if err := os.WriteFile(source, []byte(rustTestLibrary), 0644); err != nil { + t.Fatal(err) + } + if output, err := exec.Command(compiler, "-shared", "-fPIC", "-fvisibility=hidden", "-o", library, source).CombinedOutput(); err != nil { + t.Fatalf("the test library does not compile:\n%s", output) + } + + program := filepath.Join(dir, "program") + if err := os.MkdirAll(filepath.Join(program, "src"), 0755); err != nil { + t.Fatal(err) + } + manifest := "[package]\nname = \"rusttest_program\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\nrusttest = { path = \"" + filepath.ToSlash(crate) + "\" }\n" + if err := os.WriteFile(filepath.Join(program, "Cargo.toml"), []byte(manifest), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(program, "src", "main.rs"), []byte(rustTestProgram), 0644); err != nil { + t.Fatal(err) + } + environment := append(os.Environ(), "CARGO_TARGET_DIR="+filepath.Join(dir, "target")) + build := exec.Command(cargo, "build", "--quiet") + build.Dir = program + build.Env = environment + if output, err := build.CombinedOutput(); err != nil { + t.Fatalf("the test program does not compile:\n%s", output) + } + binary := filepath.Join(dir, "target", "debug", "rusttest_program") + + run := exec.Command(binary, library) + run.Env = environment + output, err := run.CombinedOutput() + if err != nil || !strings.Contains(string(output), "ALL OK") { + t.Fatalf("the test program failed (%v):\n%s", err, output) + } + + // a panic in a closure must not unwind into the library: the process aborts + panicking := exec.Command(binary, library, "panic") + panicking.Env = environment + output, err = panicking.CombinedOutput() + if err == nil || strings.Contains(string(output), "survived") { + t.Fatalf("a panic in a callback should abort the process, got %v:\n%s", err, output) + } +} diff --git a/Source/buildbindingrust_test.go b/Source/buildbindingrust_test.go index f429d0ed..2934b1e6 100644 --- a/Source/buildbindingrust_test.go +++ b/Source/buildbindingrust_test.go @@ -275,7 +275,7 @@ func TestRustGeneratedCargo(t *testing.T) { if err != nil { t.Fatal(err) } - for _, e := range []string{`name = "rusttest"`, `version = "1.2.3"`, `description = "Rust bindings of Rust Test Library"`} { + for _, e := range []string{`name = "rusttest"`, `version = "1.2.3"`, `rust-version = "1.65"`, `description = "Rust bindings of Rust Test Library"`} { if !strings.Contains(string(cargo), e) { t.Errorf("Cargo.toml does not contain %q:\n%s", e, cargo) } From fdb02711552015bf62a79e5f6c53eaa7ef183865 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:43:40 +0100 Subject: [PATCH 13/16] Rust docs: enumarray is not generated by any binding --- Documentation/Rust.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Rust.md b/Documentation/Rust.md index e345bea2..ec21f1e5 100644 --- a/Documentation/Rust.md +++ b/Documentation/Rust.md @@ -120,4 +120,4 @@ wrapper.inject_numbers(&numbers)?; 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`. -Not supported: the `enumarray` parameter type. +The `enumarray` parameter type is accepted by the IDL but no binding of ACT generates it, so the Rust binding does not either. From 37dd50293d50420056b5d310791b4c947c376bc2 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:44:58 +0100 Subject: [PATCH 14/16] Rust tests: fall back to cargo check when clippy is not installed --- Source/buildbindingrust_test.go | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/Source/buildbindingrust_test.go b/Source/buildbindingrust_test.go index 2934b1e6..2044257a 100644 --- a/Source/buildbindingrust_test.go +++ b/Source/buildbindingrust_test.go @@ -282,25 +282,20 @@ func TestRustGeneratedCargo(t *testing.T) { } } -// the generated crate has to compile without warnings, which needs cargo +// the generated crate has to compile without warnings, which needs cargo (and clippy, if it is installed) func TestRustGeneratedBindingCompiles(t *testing.T) { if _, err := exec.LookPath("cargo"); err != nil { t.Skip("cargo is not available") } crate, _ := generateRustTestComponent(t) - command := exec.Command("cargo", "clippy", "--quiet", "--", "-D", "warnings") + arguments := []string{"check", "--quiet"} + if exec.Command("cargo", "clippy", "--version").Run() == nil { + arguments = []string{"clippy", "--quiet"} + } + command := exec.Command("cargo", arguments...) command.Dir = crate - command.Env = append(os.Environ(), "CARGO_TARGET_DIR="+t.TempDir()) - output, err := command.CombinedOutput() - if err != nil { - if strings.Contains(string(output), "no such command: `clippy`") { - command = exec.Command("cargo", "check", "--quiet") - command.Dir = crate - command.Env = append(os.Environ(), "CARGO_TARGET_DIR="+t.TempDir()) - output, err = command.CombinedOutput() - } - if err != nil { - t.Fatalf("the generated crate does not compile:\n%s", output) - } + command.Env = append(os.Environ(), "CARGO_TARGET_DIR="+t.TempDir(), "RUSTFLAGS=-D warnings") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("the generated crate does not compile without warnings (cargo %s):\n%s", arguments[0], output) } } From 274b678ac9498443e23c20ab2005fbf51eaa269d Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sat, 5 Dec 2026 06:58:58 +0100 Subject: [PATCH 15/16] Rust: remove the generator Go tests - other generators are tested through the Examples only --- Source/buildbindingrust_runtime_test.go | 263 --------------------- Source/buildbindingrust_test.go | 301 ------------------------ 2 files changed, 564 deletions(-) delete mode 100644 Source/buildbindingrust_runtime_test.go delete mode 100644 Source/buildbindingrust_test.go diff --git a/Source/buildbindingrust_runtime_test.go b/Source/buildbindingrust_runtime_test.go deleted file mode 100644 index 7cab2bf4..00000000 --- a/Source/buildbindingrust_runtime_test.go +++ /dev/null @@ -1,263 +0,0 @@ -package main - -import ( - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" -) - -// A minimal library with the C ABI of the component in rustTestComponent. It misbehaves on request: with the -// environment variable RUSTTEST_CORRUPT it writes values into enumerations that do not exist. -const rustTestLibrary = ` -#include -#include -#include - -#define EXPORT __attribute__((visibility("default"))) - -#pragma pack(1) -typedef struct { uint8_t Flag; int32_t Mode; int32_t Modes[2]; double Amount; } Packet; -typedef struct { Packet Inner; } Wrapped; -#pragma pack() - -typedef void * Handle; -typedef struct { int refs; } Worker; -typedef void (*Notify)(Handle, int32_t, const char *, uint64_t, const uint8_t *, void *, bool *); -typedef void (*Stateless)(double); -typedef void (*Bulk)(uint64_t, uint64_t *, uint8_t *, void *); - -EXPORT int32_t rusttest_getversion(uint32_t * a, uint32_t * b, uint32_t * c) { *a = 1; *b = 2; *c = 3; return 0; } - -EXPORT int32_t rusttest_getlasterror(Handle h, uint32_t size, uint32_t * needed, char * buffer, bool * has) { - if (needed) *needed = 1; - if (buffer && size >= 1) buffer[0] = 0; - if (has) *has = false; - return 0; -} - -EXPORT int32_t rusttest_acquireinstance(Handle h) { ((Worker *) h)->refs++; return 0; } -EXPORT int32_t rusttest_releaseinstance(Handle h) { - Worker * w = (Worker *) h; - if (w->refs <= 0) return 5; - if (--w->refs == 0) free(w); - return 0; -} -EXPORT int32_t rusttest_createworker(Handle * out) { - Worker * w = malloc(sizeof(Worker)); - w->refs = 1; - *out = w; - return 0; -} -EXPORT int32_t rusttest_base_classtypeid(Handle h, uint64_t * out) { *out = 0; return 0; } - -// calls the callback with a valid enumeration, an unknown one (which must not reach the closure) and null pointers, -// and checks that the callback leaves the reference count as it was -EXPORT int32_t rusttest_worker_setnotify(Handle h, Notify cb, void * user) { - Worker * w = (Worker *) h; - int before = w->refs; - uint8_t data[3] = {1, 2, 3}; - bool stop = false, ignored = false; - cb(h, 1, "hello", 3, data, user, &stop); - if (w->refs != before) return 5; - cb(h, 99, "unknown", 0, NULL, user, &ignored); - if (w->refs != before) return 5; - cb(h, 0, NULL, 0, NULL, user, &ignored); - if (w->refs != before) return 5; - return stop ? 5 : 0; -} - -EXPORT int32_t rusttest_worker_setstateless(Handle h, Stateless cb) { cb(2.5); return 0; } - -EXPORT int32_t rusttest_worker_setbulk(Handle h, Bulk cb, void * user) { - uint64_t needed = 0; - cb(0, &needed, NULL, user); - if (needed != 4) return 5; - uint8_t buffer[4] = {0, 0, 0, 0}; - uint64_t filled = needed; - cb(4, &filled, buffer, user); - return (buffer[0] == 9 && buffer[3] == 6) ? 0 : 5; -} - -static void fill(Packet * p, int index) { - p->Flag = (uint8_t) (7 + index); - p->Mode = 1; - p->Modes[0] = 0; - p->Modes[1] = 1; - p->Amount = 2.5 + index; - if (getenv("RUSTTEST_CORRUPT") && index == 1) p->Modes[1] = 42; - if (getenv("RUSTTEST_CORRUPT") && index == 0) p->Modes[0] = 77; -} - -EXPORT int32_t rusttest_worker_getpacket(Handle h, Packet * out) { fill(out, 0); return 0; } -EXPORT int32_t rusttest_worker_getpackets(Handle h, uint64_t size, uint64_t * needed, Packet * out) { - if (needed) *needed = 2; - if (out) { - if (size < 2) return 4; - fill(&out[0], 0); - fill(&out[1], 1); - } - return 0; -} -EXPORT int32_t rusttest_worker_getwrapped(Handle h, Wrapped * out) { fill(&out->Inner, 0); return 0; } -` - -const rustTestProgram = ` -use rusttest::*; -use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; - -static STATELESS: AtomicU64 = AtomicU64::new(0); - -unsafe extern "C" fn stateless(value: f64) { - STATELESS.store(value.to_bits(), Ordering::SeqCst); -} - -unsafe extern "C" fn bulk(_size: u64, needed: *mut u64, buffer: *mut u8, _user: *mut c_void) { - if buffer.is_null() { - *needed = 4; - } else { - for (i, v) in [9u8, 8, 7, 6].iter().enumerate() { - *buffer.add(i) = *v; - } - } -} - -fn main() { - let args: Vec = std::env::args().collect(); - let wrapper = Wrapper::new(&args[1]).unwrap(); - assert_eq!(wrapper.get_version().unwrap(), (1, 2, 3)); - let worker = wrapper.create_worker().unwrap(); - - if args.get(2).map(|s| s.as_str()) == Some("panic") { - worker.set_notify(|_, _, _, _| panic!("boom")).unwrap(); - println!("survived a panic in a callback"); - return; - } - - // closure with state, enumeration, string, array and a borrowed class argument; the library checks the - // reference count after each call, and the closure calls back into the library through the borrowed worker - let seen = Arc::new(Mutex::new(Vec::new())); - let sink = seen.clone(); - worker - .set_notify(move |source, mode, text, data| { - let packet = source.get_packet().unwrap(); - let flag = packet.flag; - sink.lock().unwrap().push((mode, text.to_string(), data.to_vec(), flag)); - false - }) - .unwrap(); - assert_eq!( - *seen.lock().unwrap(), - vec![(Mode::Slow, "hello".to_string(), vec![1u8, 2, 3], 7), (Mode::Fast, String::new(), vec![], 7)], - "the call with an unknown enumeration must be skipped" - ); - - // the value returned by the closure reaches the library - let error = worker.set_notify(|_, _, _, _| true).unwrap_err(); - assert_eq!(error.code, 5); - - // setting a callback again replaces the closure, and many calls keep the reference counts balanced - for _ in 0..2000 { - worker.set_notify(|source, _, _, _| source.get_packet().is_err()).unwrap(); - } - - // callbacks without user data and with arrays to fill are only available as unsafe functions - unsafe { - worker.set_stateless(stateless).unwrap(); - worker.set_bulk(bulk, std::ptr::null_mut()).unwrap(); - } - assert_eq!(f64::from_bits(STATELESS.load(Ordering::SeqCst)), 2.5); - - // structs with enumerations: single, array and nested - let packet = worker.get_packet().unwrap(); - let (flag, mode, modes, amount) = (packet.flag, packet.mode, packet.modes, packet.amount); - assert_eq!((flag, mode, modes, amount), (7, Mode::Slow, [Mode::Fast, Mode::Slow], 2.5)); - let packets = worker.get_packets().unwrap(); - assert_eq!(packets.len(), 2); - let second = packets[1].flag; - assert_eq!(second, 8); - let wrapped = worker.get_wrapped().unwrap(); - let inner = wrapped.inner; - let inner_mode = inner.mode; - assert_eq!(inner_mode, Mode::Slow); - - // values the library writes into enumerations that do not exist are reported, in every kind of struct result - std::env::set_var("RUSTTEST_CORRUPT", "1"); - for error in [ - worker.get_packet().err().expect("an invalid enumeration in a struct"), - worker.get_packets().err().expect("an invalid enumeration in an array of structs"), - worker.get_wrapped().err().expect("an invalid enumeration in a nested struct"), - ] { - assert_eq!(error.code, error_code::INVALIDCAST); - } - println!("ALL OK"); -} -` - -func TestRustRuntimeAgainstCLibrary(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("needs a C compiler") - } - cargo, err := exec.LookPath("cargo") - if err != nil { - t.Skip("cargo is not available") - } - compiler, err := exec.LookPath("cc") - if err != nil { - t.Skip("cc is not available") - } - crate, _ := generateRustTestComponent(t) - dir := t.TempDir() - - extension := ".so" - if runtime.GOOS == "darwin" { - extension = ".dylib" - } - source := filepath.Join(dir, "rusttest.c") - library := filepath.Join(dir, "rusttest"+extension) - if err := os.WriteFile(source, []byte(rustTestLibrary), 0644); err != nil { - t.Fatal(err) - } - if output, err := exec.Command(compiler, "-shared", "-fPIC", "-fvisibility=hidden", "-o", library, source).CombinedOutput(); err != nil { - t.Fatalf("the test library does not compile:\n%s", output) - } - - program := filepath.Join(dir, "program") - if err := os.MkdirAll(filepath.Join(program, "src"), 0755); err != nil { - t.Fatal(err) - } - manifest := "[package]\nname = \"rusttest_program\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\nrusttest = { path = \"" + filepath.ToSlash(crate) + "\" }\n" - if err := os.WriteFile(filepath.Join(program, "Cargo.toml"), []byte(manifest), 0644); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(program, "src", "main.rs"), []byte(rustTestProgram), 0644); err != nil { - t.Fatal(err) - } - environment := append(os.Environ(), "CARGO_TARGET_DIR="+filepath.Join(dir, "target")) - build := exec.Command(cargo, "build", "--quiet") - build.Dir = program - build.Env = environment - if output, err := build.CombinedOutput(); err != nil { - t.Fatalf("the test program does not compile:\n%s", output) - } - binary := filepath.Join(dir, "target", "debug", "rusttest_program") - - run := exec.Command(binary, library) - run.Env = environment - output, err := run.CombinedOutput() - if err != nil || !strings.Contains(string(output), "ALL OK") { - t.Fatalf("the test program failed (%v):\n%s", err, output) - } - - // a panic in a closure must not unwind into the library: the process aborts - panicking := exec.Command(binary, library, "panic") - panicking.Env = environment - output, err = panicking.CombinedOutput() - if err == nil || strings.Contains(string(output), "survived") { - t.Fatalf("a panic in a callback should abort the process, got %v:\n%s", err, output) - } -} diff --git a/Source/buildbindingrust_test.go b/Source/buildbindingrust_test.go deleted file mode 100644 index 2044257a..00000000 --- a/Source/buildbindingrust_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package main - -import ( - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -func TestRustSnakeCase(t *testing.T) { - tests := map[string]string{ - "GetVersion": "get_version", - "SetProgressCallback": "set_progress_callback", - "ClassTypeId": "class_type_id", - "ByteData": "byte_data", - "Value": "value", - "Type": "type_", // a keyword of Rust - "Match": "match_", - "X2Y": "x2_y", - } - for input, expected := range tests { - if got := rustSnakeCase(input); got != expected { - t.Errorf("rustSnakeCase(%q) = %q, expected %q", input, got, expected) - } - } -} - -func TestRustBasicType(t *testing.T) { - tests := map[string]string{ - "uint8": "u8", "uint16": "u16", "uint32": "u32", "uint64": "u64", - "int8": "i8", "int16": "i16", "int32": "i32", "int64": "i64", - "bool": "bool", "single": "f32", "double": "f64", "pointer": "*mut c_void", - } - for input, expected := range tests { - got, err := rustBasicType(input) - if err != nil || got != expected { - t.Errorf("rustBasicType(%q) = %q, %v, expected %q", input, got, err, expected) - } - } - if _, err := rustBasicType("string"); err == nil { - t.Error("rustBasicType(\"string\") should fail") - } -} - -func rustTestStruct(name string, members ...ComponentDefinitionMember) ComponentDefinitionStruct { - return ComponentDefinitionStruct{Name: name, Members: members} -} - -func TestRustStructLayout(t *testing.T) { - component := ComponentDefinition{Structs: []ComponentDefinitionStruct{ - // no padding: the natural layout of C is the packed layout - rustTestStruct("Position", ComponentDefinitionMember{Name: "Coordinates", Type: "single", Rows: 3}), - // the double needs padding after the byte in C, the ABI of ACT packs it - rustTestStruct("Mixed", - ComponentDefinitionMember{Name: "Flag", Type: "uint8"}, - ComponentDefinitionMember{Name: "Value", Type: "double"}), - // a matrix is stored by column - rustTestStruct("Transform", ComponentDefinitionMember{Name: "Fields", Type: "single", Rows: 3, Columns: 4}), - rustTestStruct("Aligned", - ComponentDefinitionMember{Name: "A", Type: "uint32", Rows: 2}, - ComponentDefinitionMember{Name: "B", Type: "double", Rows: 2}), - }} - tests := []struct { - name string - size uint64 - natural bool - }{ - {"Position", 12, true}, - {"Mixed", 9, false}, - {"Transform", 48, true}, - {"Aligned", 24, true}, - } - for _, test := range tests { - size, _, natural := rustStructLayout(component, test.name) - if size != test.size || natural != test.natural { - t.Errorf("rustStructLayout(%s) = %d, %v, expected %d, %v", test.name, size, natural, test.size, test.natural) - } - } -} - -func TestRustStructMemberType(t *testing.T) { - tests := []struct { - member ComponentDefinitionMember - expected string - }{ - {ComponentDefinitionMember{Type: "uint32"}, "u32"}, - {ComponentDefinitionMember{Type: "single", Rows: 3}, "[f32; 3]"}, - // [column][row], like the other bindings - {ComponentDefinitionMember{Type: "single", Rows: 3, Columns: 4}, "[[f32; 3]; 4]"}, - {ComponentDefinitionMember{Type: "enum", Class: "Mode"}, "Mode"}, - {ComponentDefinitionMember{Type: "struct", Class: "Position", Rows: 2}, "[Position; 2]"}, - } - for _, test := range tests { - got, err := rustStructMemberType(test.member) - if err != nil || got != test.expected { - t.Errorf("rustStructMemberType(%+v) = %q, %v, expected %q", test.member, got, err, test.expected) - } - } -} - -func TestRustStructNeedsRaw(t *testing.T) { - component := ComponentDefinition{Structs: []ComponentDefinitionStruct{ - rustTestStruct("Plain", ComponentDefinitionMember{Name: "A", Type: "uint32"}), - rustTestStruct("WithEnum", ComponentDefinitionMember{Name: "Mode", Type: "enum", Class: "Mode"}), - rustTestStruct("Nested", ComponentDefinitionMember{Name: "Inner", Type: "struct", Class: "WithEnum"}), - rustTestStruct("NestedPlain", ComponentDefinitionMember{Name: "Inner", Type: "struct", Class: "Plain"}), - }} - expected := map[string]bool{"Plain": false, "WithEnum": true, "Nested": true, "NestedPlain": false, "Unknown": false} - for name, want := range expected { - if got := rustStructNeedsRaw(component, name); got != want { - t.Errorf("rustStructNeedsRaw(%s) = %v, expected %v", name, got, want) - } - } -} - -const rustTestComponent = ` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -` - -func generateRustTestComponent(t *testing.T) (string, string) { - t.Helper() - dir := t.TempDir() - file := filepath.Join(dir, "rusttest.xml") - if err := os.WriteFile(file, []byte(rustTestComponent), 0644); err != nil { - t.Fatal(err) - } - component, err := ReadComponentDefinition(file, "1.0.0") - if err != nil { - t.Fatal(err) - } - if err := component.CheckComponentDefinition(); err != nil { - t.Fatal(err) - } - crate := filepath.Join(dir, "Bindings", "Rust") - if err := BuildBindingRustDynamic(component, crate, "", " "); err != nil { - t.Fatal(err) - } - source, err := os.ReadFile(filepath.Join(crate, "src", "lib.rs")) - if err != nil { - t.Fatal(err) - } - return crate, string(source) -} - -func TestRustGeneratedBinding(t *testing.T) { - _, source := generateRustTestComponent(t) - - expected := []string{ - // enumerations in structs are received as integers and checked - "pub struct RawPacket {", - "fn into_checked(self) -> Result", - "pub struct RawWrapped {", - "(&mut packet as *mut RawPacket).cast::()", - "into_iter().map(RawPacket::into_checked)", - // the struct has a padding in C, the ABI of ACT does not - "#[repr(C, packed)]", - "const _: () = assert!(std::mem::size_of::() == 21);", - // callbacks with user data come in a safe variant with closures and an unsafe raw variant - "pub fn set_notify(&self, callback: impl FnMut(&Worker, Mode, &str, &[u8]) -> bool + Send + 'static) -> Result<()>", - "pub unsafe fn set_notify_raw(&self, callback: Notify, user_data: *mut c_void) -> Result<()>", - "std::panic::catch_unwind", - // without user data a closure has nowhere to live: only the raw callback is offered, as unsafe - "pub unsafe fn set_stateless(&self, callback: Stateless) -> Result<()>", - // arrays that are filled for the library are not mapped to closures - "pub unsafe fn set_bulk(&self, callback: Bulk, user_data: *mut c_void) -> Result<()>", - // only classes declared with the strict thread safety option are Sync - "unsafe impl Send for Base {}", - } - for _, e := range expected { - if !strings.Contains(source, e) { - t.Errorf("the generated binding does not contain %q", e) - } - } - for _, unexpected := range []string{"fn set_bulk_raw", "fn set_stateless_raw", "unsafe impl Sync for Base"} { - if strings.Contains(source, unexpected) { - t.Errorf("the generated binding should not contain %q", unexpected) - } - } -} - -func TestRustGeneratedCargo(t *testing.T) { - crate, _ := generateRustTestComponent(t) - cargo, err := os.ReadFile(filepath.Join(crate, "Cargo.toml")) - if err != nil { - t.Fatal(err) - } - for _, e := range []string{`name = "rusttest"`, `version = "1.2.3"`, `rust-version = "1.65"`, `description = "Rust bindings of Rust Test Library"`} { - if !strings.Contains(string(cargo), e) { - t.Errorf("Cargo.toml does not contain %q:\n%s", e, cargo) - } - } -} - -// the generated crate has to compile without warnings, which needs cargo (and clippy, if it is installed) -func TestRustGeneratedBindingCompiles(t *testing.T) { - if _, err := exec.LookPath("cargo"); err != nil { - t.Skip("cargo is not available") - } - crate, _ := generateRustTestComponent(t) - arguments := []string{"check", "--quiet"} - if exec.Command("cargo", "clippy", "--version").Run() == nil { - arguments = []string{"clippy", "--quiet"} - } - command := exec.Command("cargo", arguments...) - command.Dir = crate - command.Env = append(os.Environ(), "CARGO_TARGET_DIR="+t.TempDir(), "RUSTFLAGS=-D warnings") - if output, err := command.CombinedOutput(); err != nil { - t.Fatalf("the generated crate does not compile without warnings (cargo %s):\n%s", arguments[0], output) - } -} From 2b07dfe0ed9cf22aacd552cbecb7ed9077f73854 Mon Sep 17 00:00:00 2001 From: Vijai Kumar Suriyababu Date: Sun, 6 Dec 2026 01:34:43 +0100 Subject: [PATCH 16/16] Rust binding: review fixes for soundness, portability, and edge cases --- .gitignore | 1 + Documentation/Rust.md | 4 +- .../Bindings/Rust/src/lib.rs | 190 +++++---- .../Bindings/Rust/src/lib.rs | 186 +++++---- .../Examples/Rust/Calculation_example.rs | 1 - .../Bindings/Rust/src/lib.rs | 136 +++--- .../Bindings/Rust/src/lib.rs | 208 ++++----- .../RTTI_component/Bindings/Rust/src/lib.rs | 222 +++++----- .../Examples/Rust/RTTI_example.rs | 2 +- .../Bindings/Rust/src/lib.rs | 252 ++++++----- .../Examples/Rust/LibThreadSafe_example.rs | 4 +- .../Bindings/Rust/src/lib.rs | 251 +++++------ Source/buildbindingrust.go | 394 +++++++++++------- 13 files changed, 1043 insertions(+), 808 deletions(-) diff --git a/.gitignore b/.gitignore index 8c457202..5b7a4172 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ Examples/**/build Examples/**/build-* Examples/**/bin Examples/**/obj +Examples/**/target Cargo.lock # Visual Studio Code diff --git a/Documentation/Rust.md b/Documentation/Rust.md index ec21f1e5..26bd67d0 100644 --- a/Documentation/Rust.md +++ b/Documentation/Rust.md @@ -98,8 +98,8 @@ writer.set_progress_callback(move |progress, _identifier| { * 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. -* 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. +* 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. diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs index c64d4cdc..8cc7bb19 100644 --- a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs +++ b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -302,9 +307,13 @@ impl Inner { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -411,12 +420,12 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.calculator_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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) } } @@ -434,6 +443,8 @@ impl fmt::Debug for Base { } } +impl private::Sealed for Base {} + impl Class for Base { const TYPE_IDS: &'static [u64] = &[0xDDEA9DC03BDC9EC4, 0xC228BBEB32E22A34, 0x5FA5D809D8A728B0]; const TYPE_ID: u64 = 0xDDEA9DC03BDC9EC4; @@ -510,12 +521,12 @@ impl Variable { /// # Returns /// * `value` - The current value of this Variable pub fn get_value(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut value: f64 = 0.0; - let code = unsafe { (inner.api.calculator_variable_getvalue)(handle, &mut value) }; - inner.check(handle, code)?; - Ok(value) + 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 @@ -523,10 +534,10 @@ impl Variable { /// # Arguments /// * `value` - The new value of this Variable pub fn set_value(&self, value: f64) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.calculator_variable_setvalue)(handle, value) }; - inner.check(handle, code)?; + 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(()) } } @@ -537,6 +548,8 @@ impl fmt::Debug for Variable { } } +impl private::Sealed for Variable {} + impl Class for Variable { const TYPE_IDS: &'static [u64] = &[0xC228BBEB32E22A34]; const TYPE_ID: u64 = 0xC228BBEB32E22A34; @@ -605,10 +618,10 @@ impl Calculator { /// # Arguments /// * `variable` - The new variable in this calculator pub fn enlist_variable(&self, variable: &Variable) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.calculator_calculator_enlistvariable)(handle, variable.handle()) }; - inner.check(handle, code)?; + 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(()) } @@ -620,20 +633,20 @@ impl Calculator { /// # Returns /// * `variable` - The Index-th variable in this calculator pub fn get_enlisted_variable(&self, index: u32) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut variable: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculator_calculator_getenlistedvariable)(handle, index, &mut variable) }; - inner.check(handle, code)?; - Ok(Variable::from_handle(inner.clone(), variable)) + 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 inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.calculator_calculator_clearvariables)(handle) }; - inner.check(handle, code)?; + 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(()) } @@ -642,12 +655,12 @@ impl Calculator { /// # Returns /// * `instance` - Variable that holds the product of all enlisted Variables pub fn multiply(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculator_calculator_multiply)(handle, &mut instance) }; - inner.check(handle, code)?; - Ok(Variable::from_handle(inner.clone(), instance)) + 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 @@ -656,12 +669,12 @@ impl Calculator { /// * `instance` - Variable that holds the sum of all enlisted Variables #[allow(clippy::should_implement_trait)] pub fn add(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculator_calculator_add)(handle, &mut instance) }; - inner.check(handle, code)?; - Ok(Variable::from_handle(inner.clone(), instance)) + 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)) } } @@ -671,6 +684,8 @@ impl fmt::Debug for Calculator { } } +impl private::Sealed for Calculator {} + impl Class for Calculator { const TYPE_IDS: &'static [u64] = &[0x5FA5D809D8A728B0]; const TYPE_ID: u64 = 0x5FA5D809D8A728B0; @@ -716,13 +731,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.calculator_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -734,27 +749,30 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.calculator_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.calculator_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.calculator_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -763,9 +781,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.calculator_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -777,11 +795,11 @@ impl Wrapper { /// # Returns /// * `instance` - New Variable instance pub fn create_variable(&self, initial_value: f64) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculator_createvariable)(initial_value, &mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(Variable::from_handle(inner.clone(), instance)) + 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 @@ -789,10 +807,10 @@ impl Wrapper { /// # Returns /// * `instance` - New Calculator instance pub fn create_calculator(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculator_createcalculator)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(Calculator::from_handle(inner.clone(), instance)) + 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/Injection/Calculation_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs index cc1e194c..08d069e7 100644 --- a/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs +++ b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -284,6 +289,7 @@ impl Inner { } /// 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(|| { @@ -321,9 +327,13 @@ impl Inner { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -427,12 +437,12 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.calculation_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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) } } @@ -449,6 +459,8 @@ impl fmt::Debug for Base { } } +impl private::Sealed for Base {} + impl Class for Base { const TYPE_IDS: &'static [u64] = &[0x3BA5271BAB410E5D, 0xB23F514353D0C606]; const TYPE_ID: u64 = 0x3BA5271BAB410E5D; @@ -525,10 +537,10 @@ impl Calculator { /// # Arguments /// * `variable` - The new variable in this calculator pub fn enlist_variable(&self, variable: &numbers::Variable) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.calculation_calculator_enlistvariable)(handle, variable.handle()) }; - inner.check(handle, code)?; + 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(()) } @@ -540,20 +552,20 @@ impl Calculator { /// # Returns /// * `variable` - The Index-th variable in this calculator pub fn get_enlisted_variable(&self, index: u32) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut variable: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculation_calculator_getenlistedvariable)(handle, index, &mut variable) }; - inner.check(handle, code)?; - Ok(unsafe { numbers::Variable::from_raw(&inner.imported_numbers()?, variable) }) + 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 inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.calculation_calculator_clearvariables)(handle) }; - inner.check(handle, code)?; + 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(()) } @@ -562,12 +574,12 @@ impl Calculator { /// # Returns /// * `instance` - Variable that holds the product of all enlisted Variables pub fn multiply(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculation_calculator_multiply)(handle, &mut instance) }; - inner.check(handle, code)?; - Ok(unsafe { numbers::Variable::from_raw(&inner.imported_numbers()?, instance) }) + 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 @@ -576,12 +588,12 @@ impl Calculator { /// * `instance` - Variable that holds the sum of all enlisted Variables #[allow(clippy::should_implement_trait)] pub fn add(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculation_calculator_add)(handle, &mut instance) }; - inner.check(handle, code)?; - Ok(unsafe { numbers::Variable::from_raw(&inner.imported_numbers()?, instance) }) + 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) }) } } @@ -591,6 +603,8 @@ impl fmt::Debug for Calculator { } } +impl private::Sealed for Calculator {} + impl Class for Calculator { const TYPE_IDS: &'static [u64] = &[0xB23F514353D0C606]; const TYPE_ID: u64 = 0xB23F514353D0C606; @@ -664,11 +678,11 @@ impl Wrapper { /// # Returns /// * `instance` - New Calculator instance pub fn create_calculator(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.calculation_createcalculator)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(Calculator::from_handle(inner.clone(), instance)) + 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. @@ -678,13 +692,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.calculation_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -696,27 +710,30 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.calculation_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.calculation_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.calculation_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -725,9 +742,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.calculation_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -738,21 +755,20 @@ impl Wrapper { /// * `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. + /// 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 inner = &self.inner; - let c_name_space = CString::new(name_space) + 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 code = unsafe { (inner.api.calculation_injectcomponent)(c_name_space.as_ptr(), symbol_address_method) }; - inner.check(ptr::null_mut(), code)?; + 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 slot = inner.imported_numbers.lock().unwrap_or_else(|e| e.into_inner()); - if slot.is_some() { + 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")); } - *slot = Some(unsafe { numbers::Wrapper::from_symbol_lookup_method(symbol_address_method) }?); + *__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))), } @@ -764,11 +780,11 @@ impl Wrapper { /// # Returns /// * `symbol_lookup_method` - Address of the SymbolAddressMethod pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { - let inner = &self.inner; - let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); - let code = unsafe { (inner.api.calculation_getsymbollookupmethod)(&mut symbol_lookup_method) }; - inner.check(ptr::null_mut(), code)?; - Ok(symbol_lookup_method) + 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. diff --git a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs index 63462227..74c7624c 100644 --- a/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs +++ b/Examples/Injection/Calculation_component/Examples/Rust/Calculation_example.rs @@ -31,7 +31,6 @@ fn main() -> calculation::Result<()> { let s = calc.add()?.get_value()?; println!("newSum={}", s); assert_eq!(s, 25.0); - // the shortcut generated for imported components: wrapper.numbers() gives access to the injected wrapper println!("multiply={}", calc.multiply()?.get_value()?); Ok(()) } diff --git a/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs index 3fd3fd62..d8ae0571 100644 --- a/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs +++ b/Examples/Injection/Numbers_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -292,9 +297,13 @@ impl Inner { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -398,12 +407,12 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.numbers_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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) } } @@ -420,6 +429,8 @@ impl fmt::Debug for Base { } } +impl private::Sealed for Base {} + impl Class for Base { const TYPE_IDS: &'static [u64] = &[0x27799F69B3FD1C9E, 0x23934EDF762423EA]; const TYPE_ID: u64 = 0x27799F69B3FD1C9E; @@ -496,12 +507,12 @@ impl Variable { /// # Returns /// * `value` - The current value of this Variable pub fn get_value(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut value: f64 = 0.0; - let code = unsafe { (inner.api.numbers_variable_getvalue)(handle, &mut value) }; - inner.check(handle, code)?; - Ok(value) + 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 @@ -509,10 +520,10 @@ impl Variable { /// # Arguments /// * `value` - The new value of this Variable pub fn set_value(&self, value: f64) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.numbers_variable_setvalue)(handle, value) }; - inner.check(handle, code)?; + 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(()) } } @@ -523,6 +534,8 @@ impl fmt::Debug for Variable { } } +impl private::Sealed for Variable {} + impl Class for Variable { const TYPE_IDS: &'static [u64] = &[0x23934EDF762423EA]; const TYPE_ID: u64 = 0x23934EDF762423EA; @@ -599,11 +612,11 @@ impl Wrapper { /// # Returns /// * `instance` - New Variable instance pub fn create_variable(&self, initial_value: f64) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.numbers_createvariable)(initial_value, &mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(Variable::from_handle(inner.clone(), instance)) + 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. @@ -613,13 +626,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.numbers_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -631,27 +644,30 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.numbers_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.numbers_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.numbers_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -660,9 +676,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.numbers_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -671,10 +687,10 @@ impl Wrapper { /// # Returns /// * `symbol_lookup_method` - Address of the SymbolAddressMethod pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { - let inner = &self.inner; - let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); - let code = unsafe { (inner.api.numbers_getsymbollookupmethod)(&mut symbol_lookup_method) }; - inner.check(ptr::null_mut(), code)?; - Ok(symbol_lookup_method) + 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/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs index da4f4fcf..a1addb8c 100644 --- a/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs +++ b/Examples/Primes/LibPrimes_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -331,9 +336,13 @@ impl Inner { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -443,12 +452,12 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.libprimes_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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) } } @@ -467,6 +476,8 @@ impl fmt::Debug for Base { } } +impl private::Sealed for Base {} + impl Class for Base { const TYPE_IDS: &'static [u64] = &[0x8769D2BB89D05D4D, 0x11F9CFC626592744, 0x6C7A0FD2ECC65118, 0x58F1CCC31D38375B]; const TYPE_ID: u64 = 0x8769D2BB89D05D4D; @@ -558,12 +569,12 @@ impl Calculator { /// # Returns /// * `value` - The current value of this Calculator pub fn get_value(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut value: u64 = 0; - let code = unsafe { (inner.api.libprimes_calculator_getvalue)(handle, &mut value) }; - inner.check(handle, code)?; - Ok(value) + 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 @@ -571,19 +582,19 @@ impl Calculator { /// # Arguments /// * `value` - The value to be factorized pub fn set_value(&self, value: u64) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libprimes_calculator_setvalue)(handle, value) }; - inner.check(handle, code)?; + 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 inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libprimes_calculator_calculate)(handle) }; - inner.check(handle, code)?; + 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(()) } @@ -596,10 +607,10 @@ impl Calculator { /// 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 inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libprimes_calculator_setprogresscallback)(handle, progress_callback) }; - inner.check(handle, code)?; + 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(()) } } @@ -618,6 +629,8 @@ impl fmt::Debug for Calculator { } } +impl private::Sealed for Calculator {} + impl Class for Calculator { const TYPE_IDS: &'static [u64] = &[0x11F9CFC626592744, 0x6C7A0FD2ECC65118, 0x58F1CCC31D38375B]; const TYPE_ID: u64 = 0x11F9CFC626592744; @@ -686,17 +699,17 @@ impl FactorizationCalculator { /// # Returns /// * `prime_factors` - The prime factors of this number pub fn get_prime_factors(&self) -> Result> { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut needed_prime_factors: u64 = 0; - let mut buffer_prime_factors: Vec = Vec::new(); - let code = unsafe { (inner.api.libprimes_factorizationcalculator_getprimefactors)(handle, 0, &mut needed_prime_factors, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_prime_factors.resize(needed_prime_factors as usize, unsafe { mem::zeroed() }); - let code = unsafe { (inner.api.libprimes_factorizationcalculator_getprimefactors)(handle, buffer_prime_factors.len() as u64, &mut needed_prime_factors, buffer_prime_factors.as_mut_ptr()) }; - inner.check(handle, code)?; - buffer_prime_factors.truncate(needed_prime_factors as usize); - Ok(buffer_prime_factors) + 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) } } @@ -706,6 +719,8 @@ impl fmt::Debug for FactorizationCalculator { } } +impl private::Sealed for FactorizationCalculator {} + impl Class for FactorizationCalculator { const TYPE_IDS: &'static [u64] = &[0x6C7A0FD2ECC65118]; const TYPE_ID: u64 = 0x6C7A0FD2ECC65118; @@ -774,17 +789,17 @@ impl SieveCalculator { /// # Returns /// * `primes` - The primes lower or equal to the sieve's value pub fn get_primes(&self) -> Result> { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut needed_primes: u64 = 0; - let mut buffer_primes: Vec = Vec::new(); - let code = unsafe { (inner.api.libprimes_sievecalculator_getprimes)(handle, 0, &mut needed_primes, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_primes.resize(needed_primes as usize, Default::default()); - let code = unsafe { (inner.api.libprimes_sievecalculator_getprimes)(handle, buffer_primes.len() as u64, &mut needed_primes, buffer_primes.as_mut_ptr()) }; - inner.check(handle, code)?; - buffer_primes.truncate(needed_primes as usize); - Ok(buffer_primes) + 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) } } @@ -794,6 +809,8 @@ impl fmt::Debug for SieveCalculator { } } +impl private::Sealed for SieveCalculator {} + impl Class for SieveCalculator { const TYPE_IDS: &'static [u64] = &[0x58F1CCC31D38375B]; const TYPE_ID: u64 = 0x58F1CCC31D38375B; @@ -839,13 +856,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.libprimes_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -857,17 +874,17 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.libprimes_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.libprimes_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 @@ -875,9 +892,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.libprimes_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -885,10 +902,13 @@ impl Wrapper { /// /// # Arguments /// * `instance` - Instance Handle - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.libprimes_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -897,11 +917,11 @@ impl Wrapper { /// # Returns /// * `instance` - New FactorizationCalculator instance pub fn create_factorization_calculator(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.libprimes_createfactorizationcalculator)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(FactorizationCalculator::from_handle(inner.clone(), instance)) + 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 @@ -909,11 +929,11 @@ impl Wrapper { /// # Returns /// * `instance` - New SieveCalculator instance pub fn create_sieve_calculator(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.libprimes_createsievecalculator)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(SieveCalculator::from_handle(inner.clone(), instance)) + 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 @@ -921,11 +941,11 @@ impl Wrapper { /// # Arguments /// * `file_name` - Journal FileName pub fn set_journal(&self, file_name: &str) -> Result<()> { - let inner = &self.inner; - let c_file_name = CString::new(file_name) + 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 code = unsafe { (inner.api.libprimes_setjournal)(c_file_name.as_ptr()) }; - inner.check(ptr::null_mut(), code)?; + 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/RTTI/RTTI_component/Bindings/Rust/src/lib.rs b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs index 07cf4b14..feaef297 100644 --- a/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs +++ b/Examples/RTTI/RTTI_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -302,9 +307,13 @@ impl Inner { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -432,12 +441,12 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.rtti_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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) } } @@ -462,6 +471,8 @@ impl fmt::Debug for Base { } } +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; @@ -565,17 +576,17 @@ impl Animal { /// # Returns /// * `result` - pub fn name(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut needed_result: u32 = 0; - let mut filled_result: u32 = 0; - let mut buffer_result: Vec = Vec::new(); - let code = unsafe { (inner.api.rtti_animal_name)(handle, 0, &mut needed_result, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_result.resize(needed_result as usize, 0); - let code = unsafe { (inner.api.rtti_animal_name)(handle, buffer_result.len() as u32, &mut filled_result, buffer_result.as_mut_ptr() as *mut c_char) }; - inner.check(handle, code)?; - Ok(string_from_buffer(&buffer_result, filled_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)) } } @@ -597,6 +608,8 @@ impl fmt::Debug for Animal { } } +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; @@ -690,6 +703,8 @@ impl fmt::Debug for Mammal { } } +impl private::Sealed for Mammal {} + impl Class for Mammal { const TYPE_IDS: &'static [u64] = &[0xBC9D5FA7750C1020, 0x9751971BD2C2D958, 0x08D007E7B5F7BAF4]; const TYPE_ID: u64 = 0xBC9D5FA7750C1020; @@ -783,6 +798,8 @@ impl fmt::Debug for Reptile { } } +impl private::Sealed for Reptile {} + impl Class for Reptile { const TYPE_IDS: &'static [u64] = &[0x6756AA8EA5802EC3, 0x5F6826EF909803B2, 0x8E551B208A2E8321]; const TYPE_ID: u64 = 0x6756AA8EA5802EC3; @@ -853,6 +870,8 @@ impl fmt::Debug for Giraffe { } } +impl private::Sealed for Giraffe {} + impl Class for Giraffe { const TYPE_IDS: &'static [u64] = &[0x9751971BD2C2D958]; const TYPE_ID: u64 = 0x9751971BD2C2D958; @@ -918,10 +937,10 @@ impl Tiger { /// Roar like a tiger pub fn roar(&self) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.rtti_tiger_roar)(handle) }; - inner.check(handle, code)?; + 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(()) } } @@ -932,6 +951,8 @@ impl fmt::Debug for Tiger { } } +impl private::Sealed for Tiger {} + impl Class for Tiger { const TYPE_IDS: &'static [u64] = &[0x08D007E7B5F7BAF4]; const TYPE_ID: u64 = 0x08D007E7B5F7BAF4; @@ -1002,6 +1023,8 @@ impl fmt::Debug for Snake { } } +impl private::Sealed for Snake {} + impl Class for Snake { const TYPE_IDS: &'static [u64] = &[0x5F6826EF909803B2]; const TYPE_ID: u64 = 0x5F6826EF909803B2; @@ -1072,6 +1095,8 @@ impl fmt::Debug for Turtle { } } +impl private::Sealed for Turtle {} + impl Class for Turtle { const TYPE_IDS: &'static [u64] = &[0x8E551B208A2E8321]; const TYPE_ID: u64 = 0x8E551B208A2E8321; @@ -1140,12 +1165,12 @@ impl AnimalIterator { /// # Returns /// * `animal` - pub fn get_next_animal(&self) -> Result> { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut animal: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.rtti_animaliterator_getnextanimal)(handle, &mut animal) }; - inner.check(handle, code)?; - Ok(if animal.is_null() { None } else { Some(Animal::from_handle(inner.clone(), animal)) }) + 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 @@ -1154,13 +1179,13 @@ impl AnimalIterator { /// * `animal` - /// * `error` - pub fn get_next_optinal_animal(&self) -> Result<(Option, bool)> { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut animal: Handle = ptr::null_mut(); - let mut error: bool = false; - let code = unsafe { (inner.api.rtti_animaliterator_getnextoptinalanimal)(handle, &mut animal, &mut error) }; - inner.check(handle, code)?; - Ok((if animal.is_null() { None } else { Some(Animal::from_handle(inner.clone(), animal)) }, error)) + 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 @@ -1169,13 +1194,13 @@ impl AnimalIterator { /// * `animal` - /// * `error` - pub fn get_next_mandatory_animal(&self) -> Result<(Option, bool)> { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut animal: Handle = ptr::null_mut(); - let mut error: bool = false; - let code = unsafe { (inner.api.rtti_animaliterator_getnextmandatoryanimal)(handle, &mut animal, &mut error) }; - inner.check(handle, code)?; - Ok((if animal.is_null() { None } else { Some(Animal::from_handle(inner.clone(), animal)) }, error)) + 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)) } } @@ -1185,6 +1210,8 @@ impl fmt::Debug for AnimalIterator { } } +impl private::Sealed for AnimalIterator {} + impl Class for AnimalIterator { const TYPE_IDS: &'static [u64] = &[0xF1917FE6BBE77831]; const TYPE_ID: u64 = 0xF1917FE6BBE77831; @@ -1253,12 +1280,12 @@ impl Zoo { /// # Returns /// * `iterator` - pub fn iterator(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut iterator: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.rtti_zoo_iterator)(handle, &mut iterator) }; - inner.check(handle, code)?; - Ok(AnimalIterator::from_handle(inner.clone(), iterator)) + 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)) } } @@ -1268,6 +1295,8 @@ impl fmt::Debug for Zoo { } } +impl private::Sealed for Zoo {} + impl Class for Zoo { const TYPE_IDS: &'static [u64] = &[0x2262ABE80A5E7878]; const TYPE_ID: u64 = 0x2262ABE80A5E7878; @@ -1343,13 +1372,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.rtti_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -1361,27 +1390,30 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.rtti_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.rtti_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.rtti_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -1390,9 +1422,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.rtti_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -1406,11 +1438,11 @@ impl Wrapper { /// 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 inner = &self.inner; - let c_name_space = CString::new(name_space) + 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 code = unsafe { (inner.api.rtti_injectcomponent)(c_name_space.as_ptr(), symbol_address_method) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -1419,11 +1451,11 @@ impl Wrapper { /// # Returns /// * `symbol_lookup_method` - Address of the SymbolAddressMethod pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { - let inner = &self.inner; - let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); - let code = unsafe { (inner.api.rtti_getsymbollookupmethod)(&mut symbol_lookup_method) }; - inner.check(ptr::null_mut(), code)?; - Ok(symbol_lookup_method) + 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 @@ -1431,10 +1463,10 @@ impl Wrapper { /// # Returns /// * `instance` - pub fn create_zoo(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.rtti_createzoo)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(Zoo::from_handle(inner.clone(), instance)) + 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/RTTI_example.rs b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs index e046a57f..574140a3 100644 --- a/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs +++ b/Examples/RTTI/RTTI_component/Examples/Rust/RTTI_example.rs @@ -40,7 +40,7 @@ fn main() { 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::().ok().expect("tiger").roar().unwrap(); } + 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/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs index a9b1787d..b7ec9aec 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -332,9 +337,13 @@ impl Drop for InstanceLock<'_> { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -444,29 +453,35 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.libthreadsafe_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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 - pub fn _lock_instance(&self) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libthreadsafe_base__lockinstance)(handle) }; - inner.check(handle, code)?; + /// + /// # 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 - pub fn _unlock_instance(&self) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libthreadsafe_base__unlockinstance)(handle) }; - inner.check(handle, code)?; + /// + /// # 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(()) } } @@ -486,6 +501,8 @@ impl fmt::Debug for Base { } } +impl private::Sealed for Base {} + impl Class for Base { const TYPE_IDS: &'static [u64] = &[0x82FEB223BA4B6B0E, 0x01755067BCC5ED81, 0x6C0744711291F198, 0xC8D8EB62D68DF429]; const TYPE_ID: u64 = 0x82FEB223BA4B6B0E; @@ -562,25 +579,25 @@ impl StringReturner { /// # Returns /// * `value` - pub fn get_string(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut needed_value: u32 = 0; - let mut filled_value: u32 = 0; - let mut buffer_value: Vec = Vec::new(); - let code = unsafe { (inner.api.libthreadsafe_stringreturner_getstring)(handle, 0, &mut needed_value, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_value.resize(needed_value as usize, 0); - let code = unsafe { (inner.api.libthreadsafe_stringreturner_getstring)(handle, buffer_value.len() as u32, &mut filled_value, buffer_value.as_mut_ptr() as *mut c_char) }; - inner.check(handle, code)?; - Ok(string_from_buffer(&buffer_value, filled_value)) + 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 inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libthreadsafe_stringreturner_threadsafetycheck)(handle) }; - inner.check(handle, code)?; + 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(()) } } @@ -591,6 +608,8 @@ impl fmt::Debug for StringReturner { } } +impl private::Sealed for StringReturner {} + impl Class for StringReturner { const TYPE_IDS: &'static [u64] = &[0x01755067BCC5ED81]; const TYPE_ID: u64 = 0x01755067BCC5ED81; @@ -659,26 +678,26 @@ impl SoftStringReturner { /// # Returns /// * `value` - pub fn get_string(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut needed_value: u32 = 0; - let mut filled_value: u32 = 0; - let mut buffer_value: Vec = Vec::new(); - let _lock = InstanceLock::new(inner, handle)?; - let code = unsafe { (inner.api.libthreadsafe_softstringreturner_getstring)(handle, 0, &mut needed_value, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_value.resize(needed_value as usize, 0); - let code = unsafe { (inner.api.libthreadsafe_softstringreturner_getstring)(handle, buffer_value.len() as u32, &mut filled_value, buffer_value.as_mut_ptr() as *mut c_char) }; - inner.check(handle, code)?; - Ok(string_from_buffer(&buffer_value, filled_value)) + 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 inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libthreadsafe_softstringreturner_threadsafetycheck)(handle) }; - inner.check(handle, code)?; + 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(()) } } @@ -689,6 +708,8 @@ impl fmt::Debug for SoftStringReturner { } } +impl private::Sealed for SoftStringReturner {} + impl Class for SoftStringReturner { const TYPE_IDS: &'static [u64] = &[0x6C0744711291F198]; const TYPE_ID: u64 = 0x6C0744711291F198; @@ -759,27 +780,27 @@ impl StrictStringReturner { /// # Returns /// * `value` - pub fn get_string(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut needed_value: u32 = 0; - let mut filled_value: u32 = 0; - let mut buffer_value: Vec = Vec::new(); - let _lock = InstanceLock::new(inner, handle)?; - let code = unsafe { (inner.api.libthreadsafe_strictstringreturner_getstring)(handle, 0, &mut needed_value, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_value.resize(needed_value as usize, 0); - let code = unsafe { (inner.api.libthreadsafe_strictstringreturner_getstring)(handle, buffer_value.len() as u32, &mut filled_value, buffer_value.as_mut_ptr() as *mut c_char) }; - inner.check(handle, code)?; - Ok(string_from_buffer(&buffer_value, filled_value)) + 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 inner = self.inner_arc(); - let handle = self.handle(); - let _lock = InstanceLock::new(inner, handle)?; - let code = unsafe { (inner.api.libthreadsafe_strictstringreturner_threadsafetycheck)(handle) }; - inner.check(handle, code)?; + 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(()) } } @@ -790,6 +811,8 @@ impl fmt::Debug for StrictStringReturner { } } +impl private::Sealed for StrictStringReturner {} + impl Class for StrictStringReturner { const TYPE_IDS: &'static [u64] = &[0xC8D8EB62D68DF429]; const TYPE_ID: u64 = 0xC8D8EB62D68DF429; @@ -835,13 +858,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.libthreadsafe_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -853,17 +876,17 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.libthreadsafe_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.libthreadsafe_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 @@ -871,9 +894,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.libthreadsafe_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -881,10 +904,13 @@ impl Wrapper { /// /// # Arguments /// * `instance` - Instance Handle - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.libthreadsafe_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -893,11 +919,11 @@ impl Wrapper { /// # Returns /// * `instance` - New StringReturner instance pub fn create_string_returner(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.libthreadsafe_createstringreturner)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(StringReturner::from_handle(inner.clone(), instance)) + 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 @@ -905,11 +931,11 @@ impl Wrapper { /// # Returns /// * `instance` - New SoftStringReturner instance pub fn create_soft_string_returner(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.libthreadsafe_createsoftstringreturner)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(SoftStringReturner::from_handle(inner.clone(), instance)) + 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 @@ -917,10 +943,10 @@ impl Wrapper { /// # Returns /// * `instance` - New StrictStringReturner instance pub fn create_strict_string_returner(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.libthreadsafe_createstrictstringreturner)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(StrictStringReturner::from_handle(inner.clone(), instance)) + 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/LibThreadSafe_example.rs b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs index 2d4f9b56..a932add9 100644 --- a/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs +++ b/Examples/ThreadSafety/LibThreadSafe_component/Examples/Rust/LibThreadSafe_example.rs @@ -15,8 +15,8 @@ use libthreadsafe::*; use std::sync::Arc; fn main() -> Result<()> { let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?; - let sr = Arc::new(wrapper.create_string_returner()?); - let soft = Arc::new(wrapper.create_soft_string_returner()?); + 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![]; diff --git a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs index ec499bdb..f5655fb6 100644 --- a/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs +++ b/Examples/UnitTest/LibUnitTest_component/Bindings/Rust/src/lib.rs @@ -25,7 +25,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -78,22 +78,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -221,8 +226,9 @@ pub enum TestEnum { } impl TestEnum { + #[doc(hidden)] #[allow(dead_code)] - fn from_raw(value: i32) -> Result { + pub fn from_raw(value: i32) -> Result { match value { 1 => Ok(TestEnum::Option1), 20 => Ok(TestEnum::Option20), @@ -338,9 +344,13 @@ impl Inner { } } +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: Sized { +pub trait Class: private::Sealed + Sized { #[doc(hidden)] const TYPE_IDS: &'static [u64]; #[doc(hidden)] @@ -444,12 +454,12 @@ impl Base { /// # Returns /// * `class_type_id` - Class type as a 64 bits integer pub fn class_type_id(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut class_type_id: u64 = 0; - let code = unsafe { (inner.api.libunittest_base_classtypeid)(handle, &mut class_type_id) }; - inner.check(handle, code)?; - Ok(class_type_id) + 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) } } @@ -466,6 +476,8 @@ impl fmt::Debug for Base { } } +impl private::Sealed for Base {} + impl Class for Base { const TYPE_IDS: &'static [u64] = &[0x70F323A5414D8639, 0x7F4DF478E28956D1]; const TYPE_ID: u64 = 0x70F323A5414D8639; @@ -542,12 +554,12 @@ impl TestClass { /// # Returns /// * `value` - Returns the new value of this number pub fn value(&self) -> Result { - let inner = self.inner_arc(); - let handle = self.handle(); - let mut value: f64 = 0.0; - let code = unsafe { (inner.api.libunittest_testclass_value)(handle, &mut value) }; - inner.check(handle, code)?; - Ok(value) + 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 @@ -555,10 +567,10 @@ impl TestClass { /// # Arguments /// * `value` - The new value of this number pub fn set_value(&self, value: f64) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libunittest_testclass_setvalue)(handle, value) }; - inner.check(handle, code)?; + 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(()) } @@ -567,10 +579,10 @@ impl TestClass { /// # Arguments /// * `value` - The new value of this number pub fn set_value_int(&self, value: i64) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let code = unsafe { (inner.api.libunittest_testclass_setvalueint)(handle, value) }; - inner.check(handle, code)?; + 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(()) } @@ -579,12 +591,12 @@ impl TestClass { /// # Arguments /// * `value` - The new value of this number pub fn set_value_string(&self, value: &str) -> Result<()> { - let inner = self.inner_arc(); - let handle = self.handle(); - let c_value = CString::new(value) + 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 code = unsafe { (inner.api.libunittest_testclass_setvaluestring)(handle, c_value.as_ptr()) }; - inner.check(handle, code)?; + 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(()) } @@ -602,15 +614,15 @@ impl TestClass { /// * `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 inner = self.inner_arc(); - let handle = self.handle(); - let mut out_value1: u8 = 0; - let mut out_value2: u16 = 0; - let mut out_value3: u32 = 0; - let mut out_value4: u64 = 0; - let code = unsafe { (inner.api.libunittest_testclass_unittest1)(handle, value1, value2, value3, value4, &mut out_value1, &mut out_value2, &mut out_value3, &mut out_value4) }; - inner.check(handle, code)?; - Ok((out_value1, out_value2, out_value3, out_value4)) + 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 @@ -627,15 +639,15 @@ impl TestClass { /// * `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 inner = self.inner_arc(); - let handle = self.handle(); - let mut out_value1: i8 = 0; - let mut out_value2: i16 = 0; - let mut out_value3: i32 = 0; - let mut out_value4: i64 = 0; - let code = unsafe { (inner.api.libunittest_testclass_unittest2)(handle, value1, value2, value3, value4, &mut out_value1, &mut out_value2, &mut out_value3, &mut out_value4) }; - inner.check(handle, code)?; - Ok((out_value1, out_value2, out_value3, out_value4)) + 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 @@ -652,15 +664,15 @@ impl TestClass { /// * `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 inner = self.inner_arc(); - let handle = self.handle(); - let mut out_value1: bool = false; - let mut out_value2: f32 = 0.0; - let mut out_value3: f64 = 0.0; - let mut out_value4: i32 = 0; - let code = unsafe { (inner.api.libunittest_testclass_unittest3)(handle, value1, value2, value3, value4 as i32, &mut out_value1, &mut out_value2, &mut out_value3, &mut out_value4) }; - inner.check(handle, code)?; - Ok((out_value1, out_value2, out_value3, TestEnum::from_raw(out_value4)?)) + 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 @@ -672,23 +684,23 @@ impl TestClass { /// * `out_value` - returns param /// * `return_value` - returns param pub fn unit_test4(&self, value: &str) -> Result<(String, String)> { - let inner = self.inner_arc(); - let handle = self.handle(); - let c_value = CString::new(value) + 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 needed_out_value: u32 = 0; - let mut filled_out_value: u32 = 0; - let mut buffer_out_value: Vec = Vec::new(); - let mut needed_return_value: u32 = 0; - let mut filled_return_value: u32 = 0; - let mut buffer_return_value: Vec = Vec::new(); - let code = unsafe { (inner.api.libunittest_testclass_unittest4)(handle, c_value.as_ptr(), 0, &mut needed_out_value, ptr::null_mut(), 0, &mut needed_return_value, ptr::null_mut()) }; - inner.check(handle, code)?; - buffer_out_value.resize(needed_out_value as usize, 0); - buffer_return_value.resize(needed_return_value as usize, 0); - let code = unsafe { (inner.api.libunittest_testclass_unittest4)(handle, c_value.as_ptr(), buffer_out_value.len() as u32, &mut filled_out_value, buffer_out_value.as_mut_ptr() as *mut c_char, buffer_return_value.len() as u32, &mut filled_return_value, buffer_return_value.as_mut_ptr() as *mut c_char) }; - inner.check(handle, code)?; - Ok((string_from_buffer(&buffer_out_value, filled_out_value), string_from_buffer(&buffer_return_value, filled_return_value))) + 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))) } } @@ -698,6 +710,8 @@ impl fmt::Debug for TestClass { } } +impl private::Sealed for TestClass {} + impl Class for TestClass { const TYPE_IDS: &'static [u64] = &[0x7F4DF478E28956D1]; const TYPE_ID: u64 = 0x7F4DF478E28956D1; @@ -773,13 +787,13 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut major: u32 = 0; - let mut minor: u32 = 0; - let mut micro: u32 = 0; - let code = unsafe { (inner.api.libunittest_getversion)(&mut major, &mut minor, &mut micro) }; - inner.check(ptr::null_mut(), code)?; - Ok((major, minor, micro)) + 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 @@ -791,27 +805,30 @@ impl Wrapper { /// * `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 inner = &self.inner; - let mut needed_error_message: u32 = 0; - let mut filled_error_message: u32 = 0; - let mut buffer_error_message: Vec = Vec::new(); - let mut has_error: bool = false; - let code = unsafe { (inner.api.libunittest_getlasterror)(instance.handle(), 0, &mut needed_error_message, ptr::null_mut(), &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - buffer_error_message.resize(needed_error_message as usize, 0); - let code = unsafe { (inner.api.libunittest_getlasterror)(instance.handle(), buffer_error_message.len() as u32, &mut filled_error_message, buffer_error_message.as_mut_ptr() as *mut c_char, &mut has_error) }; - inner.check(ptr::null_mut(), code)?; - Ok((string_from_buffer(&buffer_error_message, filled_error_message), has_error)) + 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 - pub fn release_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.libunittest_releaseinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + /// + /// # 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(()) } @@ -820,9 +837,9 @@ impl Wrapper { /// # Arguments /// * `instance` - Instance Handle pub fn acquire_instance(&self, instance: &Base) -> Result<()> { - let inner = &self.inner; - let code = unsafe { (inner.api.libunittest_acquireinstance)(instance.handle()) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -836,11 +853,11 @@ impl Wrapper { /// 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 inner = &self.inner; - let c_name_space = CString::new(name_space) + 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 code = unsafe { (inner.api.libunittest_injectcomponent)(c_name_space.as_ptr(), symbol_address_method) }; - inner.check(ptr::null_mut(), code)?; + 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(()) } @@ -849,11 +866,11 @@ impl Wrapper { /// # Returns /// * `symbol_lookup_method` - Address of the SymbolAddressMethod pub fn get_symbol_lookup_method(&self) -> Result<*mut c_void> { - let inner = &self.inner; - let mut symbol_lookup_method: *mut c_void = ptr::null_mut(); - let code = unsafe { (inner.api.libunittest_getsymbollookupmethod)(&mut symbol_lookup_method) }; - inner.check(ptr::null_mut(), code)?; - Ok(symbol_lookup_method) + 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 @@ -861,10 +878,10 @@ impl Wrapper { /// # Returns /// * `instance` - New TestClass instance pub fn create_test_classs(&self) -> Result { - let inner = &self.inner; - let mut instance: Handle = ptr::null_mut(); - let code = unsafe { (inner.api.libunittest_createtestclasss)(&mut instance) }; - inner.check(ptr::null_mut(), code)?; - Ok(TestClass::from_handle(inner.clone(), instance)) + 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/Source/buildbindingrust.go b/Source/buildbindingrust.go index 91b4bd6d..1631d2c7 100644 --- a/Source/buildbindingrust.go +++ b/Source/buildbindingrust.go @@ -47,6 +47,7 @@ import ( "log" "os" "path" + "strconv" "strings" "unicode" ) @@ -177,14 +178,12 @@ func BuildBindingRustDynamic(component ComponentDefinition, outputFolder string, } cargoFile := path.Join(outputFolder, "Cargo.toml") - if forceRecreation || !FileExists(cargoFile) { - log.Printf("Creating \"%s\"", cargoFile) - cargofile, err := CreateLanguageFile(cargoFile, indentString) - if err != nil { - return err - } - buildRustCargo(component, cargofile) + 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) @@ -230,7 +229,7 @@ func buildRustCargo(component ComponentDefinition, w LanguageWriter) { 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 = \"Rust bindings of %s\"", strings.ReplaceAll(component.LibraryName, "\"", "'"))) + rl(w, fmt.Sprintf("description = %s", strconv.Quote("Rust bindings of "+component.LibraryName))) if len(component.ImportComponents) > 0 { rl(w, "") rl(w, "[dependencies]") @@ -298,26 +297,28 @@ func buildRustExample(component ComponentDefinition, w LanguageWriter, crateName rl(w, " }") } rl(w, " println!(\"{}\", version);") - // 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)) - } - } } else { - rl(w, " let _ = wrapper;") + 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 } @@ -334,7 +335,7 @@ mod dynlib { use super::*; use std::ffi::CStr; type DynResult = std::result::Result; - #[link(name = "dl")] + #[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; @@ -387,22 +388,27 @@ mod dynlib { #[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; + type HModule = *mut c_void; #[link(name = "kernel32")] extern "system" { - fn LoadLibraryA(lpLibFileName: *const c_char) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: *const c_char) -> *mut c_void; - fn FreeLibrary(hModule: HMODULE) -> i32; + 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, + handle: HModule, } impl Library { pub unsafe fn new(path: &str) -> DynResult { - let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?; - let handle = LoadLibraryA(cpath.as_ptr()); + 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()); } @@ -571,12 +577,16 @@ func rustTypeFromCParamType(cType string, component ComponentDefinition) string base = "i32" case strings.HasPrefix(t, "s"+nameSpace): base = rustTypeName(strings.TrimPrefix(t, "s"+nameSpace)) - case strings.HasPrefix(t, nameSpace+"_") || rustIsImportedHandle(t, component): + case strings.HasPrefix(t, nameSpace+"_"): base = "Handle" case strings.HasPrefix(t, nameSpace): base = rustTypeName(strings.TrimPrefix(t, nameSpace)) default: - base = t + if mapped, ok := rustImportedCType(t, component); ok { + base = mapped + } else { + base = t + } } if isPtr { @@ -588,14 +598,22 @@ func rustTypeFromCParamType(cType string, component ComponentDefinition) string return base } -// rustIsImportedHandle tells whether a C type is the handle type of a class of an imported component. -func rustIsImportedHandle(cType string, component ComponentDefinition) bool { +// 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) { - if strings.HasPrefix(cType, namespace+"_") { - return true + 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 + return "", false } func rustCParamTypes(method ComponentDefinitionMethod, component ComponentDefinition, className string) ([]string, error) { @@ -643,9 +661,13 @@ func buildRustBinding(component ComponentDefinition, w LanguageWriter) error { 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: Sized {") + rl(w, "pub trait Class: private::Sealed + Sized {") rl(w, " #[doc(hidden)]") rl(w, " const TYPE_IDS: &'static [u64];") rl(w, " #[doc(hidden)]") @@ -691,7 +713,12 @@ func buildRustErrors(component ComponentDefinition, w LanguageWriter) { 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\",") @@ -702,8 +729,13 @@ func buildRustErrors(component ComponentDefinition, w LanguageWriter) { 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 { - rl(w, fmt.Sprintf(" error_code::%s => \"%s\",", e.Name, strings.ReplaceAll(rustDoc(e.Description), "\"", "'"))) + 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, " }") @@ -753,8 +785,9 @@ func buildRustEnums(component ComponentDefinition, w LanguageWriter) { rl(w, "}") rl(w, "") rl(w, fmt.Sprintf("impl %s {", name)) + rl(w, " #[doc(hidden)]") rl(w, " #[allow(dead_code)]") - rl(w, " fn from_raw(value: i32) -> Result {") + rl(w, " pub fn from_raw(value: i32) -> Result {") rl(w, " match value {") seen := map[int]bool{} for _, option := range enum.Options { @@ -772,9 +805,15 @@ func buildRustEnums(component ComponentDefinition, w LanguageWriter) { } } -// rustStructLayout returns the size of a struct with the packed layout of the C ABI, its alignment and whether the -// natural layout of C yields the same layout (i.e. whether no padding would be inserted). -func rustStructLayout(component ComponentDefinition, name string) (uint64, uint64, bool) { +// 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 { @@ -782,12 +821,12 @@ func rustStructLayout(component ComponentDefinition, name string) (uint64, uint6 } } if structure == nil { - return 0, 1, false + return 0, 0, 1, false } - var offset, maxAlign uint64 = 0, 1 + var fixedBytes, ptrCount, maxAlign uint64 = 0, 0, 1 natural := true for _, m := range structure.Members { - var size, align uint64 + var size, ptrs, align uint64 switch m.Type { case "uint8", "int8", "bool": size, align = 1, 1 @@ -799,14 +838,14 @@ func rustStructLayout(component ComponentDefinition, name string) (uint64, uint6 size, align = 8, 8 case "struct": var nested bool - size, align, nested = rustStructLayout(component, m.Class) + size, ptrs, align, nested = rustStructLayout(component, m.Class) if !nested { align = 1 natural = false } default: // pointers depend on the platform - size, align = 8, 8 + ptrs, align = 1, 8 natural = false } count := uint64(1) @@ -816,25 +855,26 @@ func rustStructLayout(component ComponentDefinition, name string) (uint64, uint6 if m.Columns > 0 { count *= uint64(m.Columns) } - if offset%align != 0 { + if ptrCount > 0 || fixedBytes%align != 0 { natural = false } - offset += size * count + fixedBytes += size * count + ptrCount += ptrs * count if align > maxAlign { maxAlign = align } } - if offset%maxAlign != 0 { + if ptrCount > 0 || fixedBytes%maxAlign != 0 { natural = false } - return offset, maxAlign, natural + 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. - size, _, natural := rustStructLayout(component, s.Name) + fixedBytes, ptrCount, _, natural := rustStructLayout(component, s.Name) if natural { rl(w, "#[repr(C)]") } else { @@ -851,8 +891,20 @@ func buildRustStructs(component ComponentDefinition, w LanguageWriter) error { } rl(w, "}") rl(w, "") - rl(w, fmt.Sprintf("// the size has to match the packed layout of the C ABI")) - rl(w, fmt.Sprintf("const _: () = assert!(std::mem::size_of::<%s>() == %d);", rustTypeName(s.Name), size)) + 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 { @@ -867,6 +919,12 @@ func buildRustStructs(component ComponentDefinition, w LanguageWriter) error { // 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 @@ -881,6 +939,9 @@ func rustStructNeedsRaw(component ComponentDefinition, name string) bool { } func rustRawStructName(name string) string { + if namespace, structName, ok := rustImportedClass(name); ok { + return strings.ToLower(namespace) + "::Raw" + structName + } return "Raw" + rustTypeName(name) } @@ -906,12 +967,12 @@ func rustCheckedExpr(component ComponentDefinition, m ComponentDefinitionMember, 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(INVALID_CAST, \"array size\"))? }", v, rows, convert("item")) + 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(INVALID_CAST, \"array size\"))? }", value, cols, rowsOf("column")) + 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 { @@ -939,7 +1000,11 @@ func buildRustRawStruct(component ComponentDefinition, s ComponentDefinitionStru } memberType = t case m.Type == "struct" && rustStructNeedsRaw(component, m.Class): - member.Class = "Raw" + 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 @@ -957,8 +1022,9 @@ func buildRustRawStruct(component ComponentDefinition, s ComponentDefinitionStru rl(w, "}") rl(w, "") rl(w, fmt.Sprintf("impl %s {", raw)) + rl(w, " #[doc(hidden)]") rl(w, " #[allow(dead_code)]") - rl(w, fmt.Sprintf(" fn into_checked(self) -> Result<%s> {", name)) + 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 { @@ -966,8 +1032,7 @@ func buildRustRawStruct(component ComponentDefinition, s ComponentDefinitionStru } } if hasArray { - rl(w, " #[allow(non_snake_case)]") - rl(w, fmt.Sprintf(" let INVALID_CAST = %s;", invalidCast)) + rl(w, fmt.Sprintf(" let __act_invalid_cast = %s;", invalidCast)) } rl(w, fmt.Sprintf(" Ok(%s {", name)) for _, m := range s.Members { @@ -1107,6 +1172,7 @@ func buildRustApi(component ComponentDefinition, w LanguageWriter) error { 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(|| {") @@ -1369,15 +1435,17 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas hasTypeId := rustHasClassTypeId(component) if hasTypeId { + baseClassName := rustTypeName(component.Global.BaseClassName) + classTypeIdMethodName := rustSnakeCase(component.Global.ClassTypeIdMethod) rl(w, "") if len(parent) == 0 { - rl(w, " fn into_base(self) -> Base {") + 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, " matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id))") + 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) @@ -1396,7 +1464,7 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas rl(w, " }") } } else { - rl(w, " fn into_base(self) -> Base {") + rl(w, fmt.Sprintf(" fn into_base(self) -> %s {", baseClassName)) rl(w, " self.parent.into_base()") rl(w, " }") } @@ -1414,7 +1482,7 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas 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, " let id = match self.class_type_id() {") + 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, " };") @@ -1470,6 +1538,8 @@ func buildRustClass(component ComponentDefinition, class ComponentDefinitionClas 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) @@ -1599,9 +1669,9 @@ func buildRustWrapper(component ComponentDefinition, w LanguageWriter) error { 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(&inner.imported_%s()?, %s) }", lower, name, lower, handle) + return fmt.Sprintf("unsafe { %s::%s::from_raw(&__act_inner.imported_%s()?, %s) }", lower, name, lower, handle) } - return fmt.Sprintf("%s::from_handle(inner.clone(), %s)", rustTypeName(paramClass), 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. @@ -1660,7 +1730,7 @@ func rustCallbackSpecFor(component ComponentDefinition, functiontype ComponentDe 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(&cb_wrapper, %s) { Ok(value) => value, Err(_) => return };", name, class, 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) @@ -1816,16 +1886,16 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti if mode == rustCallbackSafe && param.ParamPass == "in" { if param.ParamName == callbackUserData { // the closures carry the user data - callArgs = append(callArgs, "cb_user_data") - initCallArgs = append(initCallArgs, "cb_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, name+"_trampoline") - initCallArgs = append(initCallArgs, name+"_trampoline") + callArgs = append(callArgs, "__act_"+name+"_trampoline") + initCallArgs = append(initCallArgs, "__act_"+name+"_trampoline") continue } } @@ -1844,10 +1914,10 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti initCallArgs = append(initCallArgs, name) case "string": parameters = append(parameters, fmt.Sprintf("%s: &str", name)) - declarations = append(declarations, fmt.Sprintf("let c_%s = CString::new(%s)", name, 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("c_%s.as_ptr()", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("c_%s.as_ptr()", 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)) @@ -1887,45 +1957,46 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti 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;", name, tp, rustZeroValue(param.ParamType))) - callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + 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, name) + returnValues = append(returnValues, outVar) case "enum": - declarations = append(declarations, fmt.Sprintf("let mut %s: i32 = 0;", name)) - callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + 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, name)) + 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() };", name, raw)) - callArgs = append(callArgs, fmt.Sprintf("(&mut %s as *mut %s).cast::<%s>()", name, raw, class)) - initCallArgs = append(initCallArgs, fmt.Sprintf("(&mut %s as *mut %s).cast::<%s>()", name, raw, class)) + 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()?", name)) + returnValues = append(returnValues, fmt.Sprintf("%s.into_checked()?", outVar)) } else { - declarations = append(declarations, fmt.Sprintf("let mut %s: %s = unsafe { mem::zeroed() };", name, class)) - callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + 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, name) + returnValues = append(returnValues, outVar) } case "string": requiresInitCall = true - declarations = append(declarations, fmt.Sprintf("let mut needed_%s: u32 = 0;", name)) - declarations = append(declarations, fmt.Sprintf("let mut filled_%s: u32 = 0;", name)) - declarations = append(declarations, fmt.Sprintf("let mut buffer_%s: Vec = Vec::new();", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut needed_%s, ptr::null_mut()", name)) - initLines = append(initLines, fmt.Sprintf("buffer_%s.resize(needed_%s as usize, 0);", name, name)) - callArgs = append(callArgs, fmt.Sprintf("buffer_%s.len() as u32, &mut filled_%s, buffer_%s.as_mut_ptr() as *mut c_char", name, name, name)) + 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(&buffer_%s, filled_%s)", name, name)) + 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 := "", "", "" @@ -1945,33 +2016,37 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti if rustStructNeedsRaw(component, param.ParamClass) { bufferType = rustRawStructName(param.ParamClass) bufferPtr = fmt.Sprintf(".cast::<%s>()", class) - resultExpr = fmt.Sprintf(".into_iter().map(%s::into_checked).collect::>>()?", bufferType) + 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 needed_%s: u64 = 0;", name)) - declarations = append(declarations, fmt.Sprintf("let mut buffer_%s: Vec<%s> = Vec::new();", name, bufferType)) - initCallArgs = append(initCallArgs, fmt.Sprintf("0, &mut needed_%s, ptr::null_mut()", name)) - initLines = append(initLines, fmt.Sprintf("buffer_%s.resize(needed_%s as usize, %s);", name, name, zero)) - callArgs = append(callArgs, fmt.Sprintf("buffer_%s.len() as u64, &mut needed_%s, buffer_%s.as_mut_ptr()%s", name, name, name, bufferPtr)) - postLines = append(postLines, fmt.Sprintf("buffer_%s.truncate(needed_%s as usize);", name, name)) + 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("buffer_%s%s", name, resultExpr)) + 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();", name)) - callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + 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, name)) + returnValues = append(returnValues, rustWrapHandle(param.ParamClass, outVar)) case "optionalclass": - declarations = append(declarations, fmt.Sprintf("let mut %s: Handle = ptr::null_mut();", name)) - callArgs = append(callArgs, fmt.Sprintf("&mut %s", name)) - initCallArgs = append(initCallArgs, fmt.Sprintf("&mut %s", name)) + 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) }", name, rustWrapHandle(param.ParamClass, name))) + 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) } @@ -2004,58 +2079,71 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti for _, n := range names { spec := callbackSpecs[n] field := rustSnakeCase(n) - declarations = append(declarations, fmt.Sprintf("unsafe extern \"C\" fn %s_trampoline(%s) {", field, strings.Join(spec.cParams, ", "))) + 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 cb_state = &*(%s as *const CallbackState);", spec.userDataName)) + declarations = append(declarations, fmt.Sprintf(" let __act_cb_state = &*(%s as *const CallbackState);", spec.userDataName)) if spec.usesClassArgs { - declarations = append(declarations, " let cb_inner = match cb_state.inner.upgrade() { Some(inner) => inner, None => return };") - declarations = append(declarations, " let cb_wrapper = Wrapper { inner: cb_inner };") + 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 cb_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {") - declarations = append(declarations, fmt.Sprintf(" let mut callback = cb_state.%s.lock().unwrap_or_else(|e| e.into_inner());", field)) - declarations = append(declarations, fmt.Sprintf(" (*callback)(%s)", strings.Join(spec.callArgs, ", "))) + 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 cb_result.is_err() { std::process::abort(); }") + declarations = append(declarations, " if __act_cb_result.is_err() { std::process::abort(); }") } else { - declarations = append(declarations, " let cb_values = match cb_result { Ok(values) => values, Err(_) => std::process::abort() };") + 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, "cb_values")) + declarations = append(declarations, rustCallbackWrite(spec, 0, "__act_cb_values")) default: for i := range spec.outPointers { - declarations = append(declarations, rustCallbackWrite(spec, i, fmt.Sprintf("cb_values.%d", i))) + 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(inner)") + 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 cb_state = Arc::new(CallbackState { %s });", strings.Join(fields, ", "))) - declarations = append(declarations, "let cb_user_data = Arc::as_ptr(&cb_state) as *mut c_void;") + 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 = "handle as usize" + key = "__act_handle as usize" } - postLines = append(postLines, fmt.Sprintf("inner.callbacks.lock().unwrap_or_else(|e| e.into_inner()).insert((%s, \"%s\"), std::boxed::Box::new(cb_state));", key, rustSnakeCase(method.MethodName))) + 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 - unsafeDocs := 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 { @@ -2072,17 +2160,17 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti for _, namespace := range rustImportedNamespaces(component) { lower := strings.ToLower(namespace) postLines = append(postLines, fmt.Sprintf(" \"%s\" => {", namespace)) - postLines = append(postLines, fmt.Sprintf(" let mut slot = inner.imported_%s.lock().unwrap_or_else(|e| e.into_inner());", lower)) - postLines = append(postLines, " if slot.is_some() {") + 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(" *slot = Some(unsafe { %s::Wrapper::from_symbol_lookup_method(%s) }?);", lower, symbolParam)) + 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 - unsafeDocs = 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." } } @@ -2133,11 +2221,10 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti } } - if unsafeDocs { + if len(safetyDoc) > 0 { rl(w, " ///") rl(w, " /// # Safety") - rl(w, " /// The symbol lookup method must be valid for the imported component, and its library must stay loaded") - rl(w, " /// for as long as this wrapper is used. Prefer the safe `inject_*` functions.") + rl(w, " /// "+safetyDoc) } else if len(rawParams) > 0 { rl(w, " ///") rl(w, " /// # Safety") @@ -2150,6 +2237,9 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti 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)]") @@ -2166,13 +2256,13 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti handleExpr := "ptr::null_mut()" if isGlobal { - rl(w, " let inner = &self.inner;") + rl(w, " let __act_inner = &self.inner;") } else { - rl(w, " let inner = self.inner_arc();") - rl(w, " let handle = self.handle();") - handleExpr = "handle" - callArgs = append([]string{"handle"}, callArgs...) - initCallArgs = append([]string{"handle"}, initCallArgs...) + 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) @@ -2183,20 +2273,20 @@ func writeRustMethodMode(component ComponentDefinition, method ComponentDefiniti if class, ok := findRustClass(component, className); ok { option := component.getRealThreadSafetyOption(&class) if (option == eThreadSafetySoft && requiresInitCall) || option == eThreadSafetyStrict { - rl(w, " let _lock = InstanceLock::new(inner, handle)?;") + rl(w, " let __act_lock = InstanceLock::new(__act_inner, __act_handle)?;") } } } if requiresInitCall { - rl(w, fmt.Sprintf(" let code = unsafe { (inner.api.%s)(%s) };", exportName, strings.Join(initCallArgs, ", "))) - rl(w, fmt.Sprintf(" inner.check(%s, code)?;", handleExpr)) + 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 code = unsafe { (inner.api.%s)(%s) };", exportName, strings.Join(callArgs, ", "))) - rl(w, fmt.Sprintf(" inner.check(%s, code)?;", handleExpr)) + 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) }