StructOp Handbook
Contents Examples Commands
Handbook / Providers and libraries

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
$ 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:

intent.st (excerpt)
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 headerIn the provider
a struct never defined, used as T *a handle type (Sqlite3, Curl), stored in a value
T ** parametera 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 numbera target attribute of that number type
const char *a String attribute
a data pointer with its lengthone Bytes attribute (or a Bytes target: capacity in, length out)
function-pointer parametera handler list (below)
return valuean optional result target
enuma provider enum that keeps the C names: CURLcode.CURLE_OK
integer or text #definea provider constant, read as const.SQLITE_ERROR

A provider constant with the same name as a project constant is a validate error.

main.st (lib-sqlite)
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:

main.st (lib-sqlite)
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]}"
}

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.bind.st
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:

AttributeMeaning
headerthe header to read (sqlite3.h), also the provider's includes
packagethe pkg-config package that links it (sqlite3)
versionthe provider version, when the library's own cannot be read
prefixkeep only functions, enums and constants starting with one of these
skipnames to leave out even when a prefix matches

Each function block refines one function:

AttributeMeaningExample
namesattribute names for the parameters, by position ("" keeps the header's)names = ["base", "count", "width", "compar"]
returns_textreturned text is owned by the library, or freed with this functionreturns_text = "curl_free"
out_texta char ** parameter that returns text, and the function that frees itout_text = { errmsg = "sqlite3_free" }
bytesa data pointer and its length parameter, as one Bytes attributebytes = [{ data = "dest", length = "destLen" }]
outoutput parameters the types do not revealout = ["ppDb"]
arraya void * that is an array: its count, element size and typearray = [{ data = "base", count = "count", size = "width", of = Int32 }]
arg_namesnames for a callback's arguments ("" marks the user data)arg_names = { callback = ["", "count", "values", "columns"] }
texta callback argument that is text of a given length (lengths multiply)text = [{ data = "ptr", length = ["size", "nmemb"] }]
points_towhat the callback's void * arguments point topoints_to = Int32
variantfor a variadic function: one ability kind per accepted value typevariant "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.bind.st
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 crateIn the provider
a structa handle type stored in a value; one with a lifetime (Row<'_>) is never stored, only passed on
a methodan 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, charthe 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 dataa provider enum, read as Color.Red
a closure parametera handler list, its arguments read through a data kind, its result in <parameter>_result
an iterator resultconsumed at once; an optional each handler list runs per item

Hints for crates:

HintMeaning
crate, version, featuresthe crate on crates.io and the cargo features to turn on
patha local crate folder instead, relative to the hints file
itemsbind 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 ()
thenjoins 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.