C libraries and Rust crates
structop bind turns an existing C library (or, below, a Rust crate) into a provider. It reads the library's header, writes one ability kind per function, and a project then calls the library like any other provider: ability "sqlite3_open" "Open" { ... }.
For the examples in this chapter, run export STRUCTOP_DEV_BINDINGS=1 in a development shell before initializing and running the project. Use unset STRUCTOP_DEV_BINDINGS when finished. Normal builds require an approved package. See provider verification.
On this page
From header to provider#
$ structop bind bind/zlib.bind.st Skipped uncompress2: parameter source is const Bytef * Wrote provider C/zlib 1.2.12 with 10 abilities to ~/.structop/providers/C/zlib/1.2.12
bind runs clang twice on the header: once for its declarations (-ast-dump=json), once for its #defines (-E -dD). STRUCTOP_CLANG names another clang. Every function it cannot express is printed with the reason, so nothing is dropped silently.
The provider lands in ~/.structop/providers/C/<library>/<version>/, versioned like the library itself unless the hints file sets version. A project names it in intent.st beside StructOp/c:
lib_provider {
C_lang = {
source = "StructOp/c"
version = "@latest"
}
Db = {
source = "C/sqlite3"
version = "@latest"
}
}Without a hints file, structop bind -header=zlib.h -package=zlib binds every function the header declares.
What the header becomes#
| In the header | In the provider |
|---|---|
a struct never defined, used as T * | a handle type (Sqlite3, Curl), stored in a value |
T ** parameter | a target attribute that writes the handle into a value |
int, unsigned long, size_t, double … | the exact number type (Int32, UInt64, Size, Float64) |
non-const pointer to a number | a target attribute of that number type |
const char * | a String attribute |
| a data pointer with its length | one Bytes attribute (or a Bytes target: capacity in, length out) |
| function-pointer parameter | a handler list (below) |
| return value | an optional result target |
enum | a provider enum that keeps the C names: CURLcode.CURLE_OK |
integer or text #define | a provider constant, read as const.SQLITE_ERROR |
A provider constant with the same name as a project constant is a validate error.
ability "value" "db" {
type = Sqlite3
}
ability "value" "rc" {
type = Int32
}
ability "sqlite3_open" "Open" {
filename = ":memory:"
target = ability.value.db
result = ability.value.rc
}Callbacks#
A function-pointer parameter becomes a handler list named after the parameter. Its arguments are a data kind called <function>_<parameter>, readable only inside that list:
ability "sqlite3_exec" "List" {
db = ability.value.db
sql = "SELECT name, n FROM fruit ORDER BY n"
callback = [ability.print.Row]
}
data "sqlite3_exec_callback" "Row" {
of = ability.sqlite3_exec.List
}
ability "print" "Row" {
message = "${data.sqlite3_exec_callback.Row.columns[0]}=${data.sqlite3_exec_callback.Row.values[0]}"
}- A count plus a text array (
int n, char **values) becomes aListofString. - The
void *user-data parameter disappears: the generated C passes the program state there. A callback without one (qsort's comparator) gets the state through one static pointer set just before the call. - The callback's return value is the attribute
<parameter>_result(callback_result,value_result); left unset it is 0. - A callback registered now and called later works the same way: libcurl's write function is set by
curl_easy_setoptand run bycurl_easy_perform.
The hints file#
A header does not say everything: who frees returned text, which pointer goes with which length, what a variadic function accepts. A hints file, NAME.bind.st, fills the gaps:
bind "curl" {
header = "curl/curl.h"
package = "libcurl"
prefix = ["curl_easy_"]
}
function "curl_easy_setopt" {
variant "curl_setopt_text" {
value = String
}
variant "curl_setopt_long" {
value = Int64
}
variant "curl_setopt_write" {
value = callback("size_t (*)(char *, size_t, size_t, void *)")
user_data = "CURLOPT_WRITEDATA"
arg_names = { value = ["ptr", "size", "nmemb", ""] }
text = [{ data = "ptr", length = ["size", "nmemb"] }]
}
}The bind block names the library:
| Attribute | Meaning |
|---|---|
header | the header to read (sqlite3.h), also the provider's includes |
package | the pkg-config package that links it (sqlite3) |
version | the provider version, when the library's own cannot be read |
prefix | keep only functions, enums and constants starting with one of these |
skip | names to leave out even when a prefix matches |
Each function block refines one function:
| Attribute | Meaning | Example |
|---|---|---|
names | attribute names for the parameters, by position ("" keeps the header's) | names = ["base", "count", "width", "compar"] |
returns_text | returned text is owned by the library, or freed with this function | returns_text = "curl_free" |
out_text | a char ** parameter that returns text, and the function that frees it | out_text = { errmsg = "sqlite3_free" } |
bytes | a data pointer and its length parameter, as one Bytes attribute | bytes = [{ data = "dest", length = "destLen" }] |
out | output parameters the types do not reveal | out = ["ppDb"] |
array | a void * that is an array: its count, element size and type | array = [{ data = "base", count = "count", size = "width", of = Int32 }] |
arg_names | names for a callback's arguments ("" marks the user data) | arg_names = { callback = ["", "count", "values", "columns"] } |
text | a callback argument that is text of a given length (lengths multiply) | text = [{ data = "ptr", length = ["size", "nmemb"] }] |
points_to | what the callback's void * arguments point to | points_to = Int32 |
variant | for a variadic function: one ability kind per accepted value type | variant "curl_setopt_long" { value = Int64 } |
Obvious pairs such as buf and len are found without hints. A hint naming a function or parameter the header does not have is an error. bind also stops when clang is missing, when clang cannot read the header, or when pkg-config cannot find the package.
The proofs#
Four libraries are bound and tested on every change; each example lists its hints file and runs only where clang and the library are installed.
Rust crates#
The same command turns a Rust crate into a Rust provider. A hints file names the crate instead of a header:
bind "rusqlite" {
crate = "rusqlite"
version = "0.31.0"
features = ["bundled"]
items = ["Connection::open_in_memory", "Connection::execute_batch", "Connection::prepare", "Row::get"]
}
function "Connection::prepare" {
then = ["Statement::query_map"]
variant "connection_prepare_query_map" {
P = Nothing
T = Int
}
}structop bind documents the crate with the nightly toolchain's cargo rustdoc (found through rustup, or STRUCTOP_CARGO), reads its rustdoc JSON and writes ~/.structop/providers/Crate/<crate>/<version>/ with a dependencies.toml, so cargo fetches the crate when the program builds. A project names it as source = "Crate/rusqlite"; only Rust projects can use it. crate = "std" reads the standard library from the toolchain (std, core and alloc).
| In the crate | In the provider |
|---|---|
| a struct | a handle type stored in a value; one with a lifetime (Row<'_>) is never stored, only passed on |
| a method | an ability kind <type>_<method> (connection_open_in_memory); the object it is called on is an attribute named after the type |
i8 … u64, usize, f32, f64, bool, char | the exact number types, Bool, Char |
&str, String (and AsRef<str>, AsRef<Path>, Into<String>) | String |
&[u8], Vec<u8> (and AsRef<[u8]>) | Bytes; a Vec of numbers or text is a List |
Result<T, E> | target, and error for the error text; without error a failure stops the program with ability.<kind>.<name> failed: … |
Option<T> | target and found |
| an enum without data | a provider enum, read as Color.Red |
| a closure parameter | a handler list, its arguments read through a data kind, its result in <parameter>_result |
| an iterator result | consumed at once; an optional each handler list runs per item |
Hints for crates:
| Hint | Meaning |
|---|---|
crate, version, features | the crate on crates.io and the cargo features to turn on |
path | a local crate folder instead, relative to the hints file |
items | bind only these ("Connection::open", "write::ZlibEncoder::new", "env::var") |
struct "T" { W = Bytes } | pins a generic struct's type parameter |
variant "kind" { T = Int } | pins a function's type parameters; Nothing passes () |
then | joins methods called on the result into one ability, so a borrowing value (Statement<'_>) lives only inside it |
A closure that must be 'static (the curl crate's Easy::write_function) cannot reach the program, so it is skipped with the reason; the crate's scoped form (transfer, then write_function and perform) is bound as a chain instead.