Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Examples/**/build
Examples/**/build-*
Examples/**/bin
Examples/**/obj
Examples/**/target
Cargo.lock

# Visual Studio Code
debug
Expand Down
7 changes: 6 additions & 1 deletion Build/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,18 @@ RUN dnf -y module enable python39 && \
# RUN dnf -y install libicu libicu-devel

# Free Pascal 3.0.4
RUN (cd /opt && curl -O -L 'http://downloads.sourceforge.net/project/freepascal/Linux/3.0.4/fpc-3.0.4-1.x86_64.rpm' \
RUN (cd /opt && curl -f -O -L --retry 5 --retry-delay 5 -C - 'https://downloads.freepascal.org/fpc/dist/3.0.4/x86_64-linux/fpc-3.0.4-1.x86_64.rpm' \
&& rpm -i fpc-3.0.4-1.x86_64.rpm)

# Go
RUN (cd /opt && curl -O -L https://golang.org/dl/go1.17.2.linux-amd64.tar.gz && tar zxvf go1.17.2.linux-amd64.tar.gz)
ENV PATH="${PATH}:/opt/go/bin"

# Rust
ENV RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --no-modify-path
ENV PATH="${PATH}:/opt/cargo/bin"

# Java & Mono
RUN dnf -y install java-11-openjdk-devel
RUN rpm --import https://download.mono-project.com/repo/xamarin.gpg \
Expand Down
2 changes: 1 addition & 1 deletion Build/build.bat
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Build/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
123 changes: 123 additions & 0 deletions Documentation/Rust.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Rust bindings

ACT generates a Rust crate that loads a component at run time (`dlopen`/`LoadLibrary`), like the other dynamic bindings. Rust is a binding language only; ACT does not generate implementation stubs in Rust.

## Generating

Add a binding to the component description:

```xml
<bindings>
<binding language="Rust" indentation="2spaces" />
</bindings>
```

ACT writes `Bindings/Rust/Cargo.toml` and `Bindings/Rust/src/lib.rs`. The crate has no dependencies besides other generated crates of imported components. Add it to your project as a path dependency:

```toml
[dependencies]
libprimes = { path = "LibPrimes_component/Bindings/Rust" }
```

Unless ACT is called with `-suppressexamples`, ACT also writes a small application to `Examples/Rust`.

## Requirements

Rust 1.65 or newer. Older compilers down to 1.57 build the crates but warn about nested `unsafe` blocks.

## Using a component

```rust
use libprimes::Wrapper;

fn main() -> libprimes::Result<()> {
let wrapper = Wrapper::new("path/to/libprimes")?; // the platform's file extension is not added
let (major, minor, micro) = wrapper.get_version()?;
println!("version {major}.{minor}.{micro}");
let calculator = wrapper.create_factorization_calculator()?;
calculator.set_value(735)?;
calculator.calculate()?;
for factor in calculator.get_prime_factors()? {
let (prime, multiplicity) = (factor.prime, factor.multiplicity);
println!("{prime}^{multiplicity}");
}
Ok(())
}
```

* Function names are snake case (`GetPrimeFactors` becomes `get_prime_factors`). Names that are keywords in Rust get a trailing underscore.
* `return` and `out` parameters are returned: a single value as is, several as a tuple. Every call returns `Result<T>`.
* 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 `<Namespace>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::<Giraffe>()` tells whether an instance is, or derives from, a class.
* `instance.cast::<Giraffe>()` returns a new reference as `Option<Giraffe>`.
* `instance.downcast::<Giraffe>()` consumes the instance and returns `Result<Giraffe, Animal>`.
* `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<Mutex<..>>`.
* 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 `<name>_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_<namespace>` keeps the imported wrapper alive. The injection function of the IDL (named by `injectionmethod`, `inject_component` in the example) takes the raw symbol lookup method and is `unsafe`.

## Platforms and status

The binding is tested on macOS (arm64) and in the Linux image of the CI, and its Windows code path is checked with `cargo check --target x86_64-pc-windows-gnu`. Generated crates build without warnings with `cargo clippy`.

The `enumarray` parameter type is accepted by the IDL but no binding of ACT generates it, so the Rust binding does not either.
1 change: 1 addition & 0 deletions Examples/Calculator/Calculator.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<binding language="CppDynamic" indentation="tabs" />
<binding language="Pascal" indentation="2spaces" />
<binding language="Python" indentation="tabs" />
<binding language="Rust" indentation="2spaces" />
</bindings>
<implementations>
<implementation language="Cpp" indentation="tabs"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "calculator"
version = "1.0.0"
edition = "2021"
rust-version = "1.65"
description = "Rust bindings of Calculator library"
Loading
Loading