C bindings
Avin calls a C library directly, through bindings written in Avin whose C prototypes clang checks against the library’s own headers.
A C library reaches Avin through a C binding: an Avin declaration that copies the C function’s prototype from the library’s header and states the signature Avin code calls it with, in Avin types. The compiler calls the C function directly from Avin’s own code, converting each argument and the result at the call, and links the library the package’s manifest names.
module mlt
@c(type: "mlt_properties", release: "mlt_properties_close", retain: "mlt_properties_inc_ref")
class Properties
@c("char *mlt_properties_get(mlt_properties self, const char *name)")
get(name: string) -> Option[string]
@c("int mlt_properties_set(mlt_properties self, const char *name, const char *value)")
set(name: string, value: string) -> Result[unit, int]
@c("mlt_properties mlt_properties_new(void)")
newProperties() -> Option[Properties]
A binding is a declaration without a body, as a Sysl binding is: a top-level
function, or a method of a C handle. @c takes the prototype as one string, written as the header
writes it, parameter names optional; the C parameters correspond to the Avin parameters by
position, the receiver first for a method. Bindings are usually private, with a public function
giving the Avin-shaped API. A binding is otherwise an ordinary function: it is called, overloaded,
given defaults and passed as a value like any other.
A prototype the header does not declare, or declares otherwise, is rejected at the binding with clang’s own words:
error: the C binding `get` does not match `mlt_properties_get` in framework/mlt.h: the header declares 'char *(mlt_properties, const char *)', but the binding says 'char *(mlt_properties, char *)'
How a C binding is compiled
A C binding is a direct call. Settled on the user’s question (“Why should C interop go through Sysl since avin generates LLVM IR?”): Avin emits LLVM IR, and a C function is called from LLVM IR by declaring its symbol and calling it. The Sysl shim exists so that Sysl checks a binding against a Sysl signature; a C binding has no Sysl signature, so a shim would add a compile step, a cache and a Sysl dependency and check nothing.
- Check reads each prototype into a C signature — scalar types, pointers,
const, the names of typedefs, function pointers — and holds it against the Avin signature by the rules below, so a binding whose Avin types cannot carry its C types is rejected before anything is built. - The driver generates one C file for the program, the C unit, and compiles it with clang,
using the include flags of the C libraries the program names. It holds:
- the header check: for every binding, a
_Static_assertthat the function the header declares has exactly the type the prototype says (__builtin_types_compatible_p), and, for every typedef a prototype names, that it is the kind of type its Avin position needs (an integer, a pointer, a struct); - the measurements: the width and sign of each typedef in an integer position, the size, alignment and field offsets of each mirrored struct, the value of each enumerator and constant, stored as data in the object file, which the driver reads without running it, so a build for another machine measures that machine;
- the glue: a small C function for each thing that is a C expression rather than a function
— a field read, a
retainorreleasewritten as an expression, a conversion between handle types, a buffer’s length, a struct passed by value, a macro.
- the header check: for every binding, a
- Lower gives each binding a body: convert the arguments, call the C symbol (or its glue),
convert the result, as MIR the rest of the compiler already knows. Emit declares the C symbol
(
declare i32 @mlt_properties_set(ptr, ptr, ptr)) with the attributes the target’s C convention asks for —signextorzeroexton an integer narrower than 32 bits, as the Sysl boundary already does. - Link passes the C unit’s object, the objects of the C sources the packages ship and the libraries’ link flags to clang with the program.
The C unit is cached by a hash of its source, the include and link flags pkg-config answers, and
clang --version. Nothing about a C binding needs the sysl command. avin check builds the C
unit too, so a binding its headers refuse is refused by check exactly as by a build.
C libraries
A package that binds a C library names it in its manifest, under c-libraries, with the
pkg-config module that finds it and the headers its bindings are checked against:
c-libraries {
mlt {
pkg-config = "mlt-framework-7"
headers = ["framework/mlt.h"]
install = "MLT 7: `brew install mlt`; Debian's libmlt-dev"
}
libc { headers = ["<stdlib.h>", "<string.h>"] }
}
-
pkg-confignames the module whose--cflagsthe C unit is compiled with and whose--libsthe program is linked with; both are asked at every build, so a library that moved is still found.link = ["z"]names libraries directly instead, each passed as-l<name>; an entry with neither needs nothing at the link (the C library itself, whose headers are named only to check against). -
headersare included by the C unit, in order, for every binding of the package. A binding is checked against a header, always: a package with a@cbinding and noheadersis refused. -
A header may be named by a macro (proposed). An entry that is a C identifier rather than a path is included as
#include NAME, which C expands to the header the macro names, so it must be defined by an entry before it. FreeType names its headers this way, each through a macro<ft2build.h>defines:c-libraries { freetype { pkg-config = "freetype2" headers = ["<ft2build.h>", "FT_FREETYPE_H", "FT_MODULE_H", "FT_MULTIPLE_MASTERS_H", "FT_TRUETYPE_TABLES_H"] install = "FreeType 2: `brew install freetype`; Debian's libfreetype-dev" } }A macro no earlier header defines is reported at the entry, with clang’s own words:
error: the header `FT_FREETYPE_H` of the C library `freetype` of package `freetype` is not a macro any earlier header defines: clang says 'expected "FILENAME" or <FILENAME>' -
installis what a build that cannot find the module says to do:error: the C library `mlt` of package `mlt` was not found: `pkg-config --cflags mlt-framework-7` failed. MLT 7: `brew install mlt`; Debian's libmlt-dev -
What else links it (settled), each optional and added to what
pkg-configorlinkgives:filesnames archives and shared libraries by their paths, linked as named;searchnames the directories itslinknames are searched in, passed as-Lwhen it is linked dynamically;includenames the directories its headers are included from, passed to the C unit as-I;frameworksnames macOS frameworks, each passed as-framework <name>;link-flagsare passed to the linker as they are, the way out for anything else.
The paths of
files,searchandincludeare relative to the package’s directory, and none may be absolute or leave it (a..segment), so a package that vendors its library builds wherever it is fetched:c-libraries { foo { files = ["vendor/libfoo.a"] include = ["vendor/include"] headers = ["foo.h"] } }A file that is not there, or a search directory that is not one, stops the build with the library, the package and the path;
avin checksays the same. -
dynamic-onlysays why the library is never linked statically, for a licence that asks for it or an installation that has no archive. It is a requirement, not a choice: how a program meets it is in How a program links its C libraries. -
sourcesnames C files the package ships, compiled into the program, andcflagsthe flags they are compiled with: C sources a package ships.
A program builds with the C libraries of every package in it, as it does with their Sysl dependencies, so a library that binds MLT works in a program that never names MLT itself. A package whose bindings name a handle of another package is checked with that package’s headers too.
C sources a package ships
A package that ships its C library’s source names the files in sources, and the build compiles
them into the program (settled). Many small libraries are distributed
this way, one sqlite3.c or a directory of .c files, and a package binding one builds wherever it
is fetched, with nothing installed:
c-libraries {
sqlite {
sources = ["vendor/sqlite/sqlite3.c"]
cflags = ["-DSQLITE_THREADSAFE=0", "-DSQLITE_OMIT_LOAD_EXTENSION"]
include = ["vendor/sqlite"]
headers = ["sqlite3.h"]
}
miniz { sources = ["vendor/miniz/*.c"], include = ["vendor/miniz"], headers = ["miniz.h"] }
}
-
sourcesare paths relative to the package’s directory, under the rules offiles: none absolute, none with a..segment. A*matches any run of characters within one name (vendor/*/*.creaches one directory down;**is refused), never a name beginning with.unless the pattern’s does, and never a directory. A pattern’s matches are taken in sorted order, and a file named twice is compiled once. -
They are compiled by the clang the C unit is compiled with, for the machine the build is for, with
-O2unlesscflagsnames a level, whatever the program’s own-O(the library is not what a debug build of the program is debugging, and both builds share one object); then the library’sincludedirectories, as-I; then the--cflagsof itspkg-configmodule, when it names one; thencflags, last, so each of them has the last word. The C unit is not compiled withcflags. -
cflagssays what the package’s C means and how well it is compiled: defines (-D,-U), the optimization level (-O0to-O3,-Os,-Oz), warnings (-W…,-w,-pedantic), the language standard (-std=) and code generation (-f…). Any other flag is refused where it is written: an include directory is the library’sinclude, a flag for the linker itslink-flags, and the target, the output and the like are the build’s.cflagswith nosourcesis an error too.error: `-Ivendor` names an include directory, which a C library names in `include`, relative to its package's directory: `cflags` holds defines (`-D`, `-U`), an optimization level (`-O`), warnings (`-W`, `-w`), the language standard (`-std=`) and code generation (`-f`) -
The objects are linked into the program, statically, always, before the libraries’ link flags, whatever
c-linking,static-c-librariesor the command line say of the library: they are part of the program, sootool -Llists nothing for them. A library naming bothsourcesanddynamic-onlyis refused at the entry.sourcesmay go withpkg-configorlink, for a source compiled against, or calling, a library that is installed. -
Each source compiles once. Its object is kept in the build cache by a key over its text, its flags, the target, the compiler’s version and
clang --version, and the path and text of every header it includes; an edited source, an edited header it includes or a changed flag compiles it again, and nothing else does. Two packages of a program shipping the same file, with the same headers and flags, share one object, compiled once and linked once. The sources of a build compile at the same time, one clang per processor at most. -
A source that does not compile stops the build with clang’s own words, which name the file and the line, after the library and its package; a source that compiles shows no warnings:
error: the source `vendor/vend.c` of the C library `vend` of package `vend` does not compile: /home/ana/vend/vendor/vend.c:3:38: error: expected ';' after return statementA source that is not there and a pattern matching no file are errors naming the path;
avin checkreports those too, and compiles no source:error: the sources `vendor/*.c` of the C library `vend` of package `vend` match no file: `/home/ana/vend/vendor/*.c` -
Sources that differ by machine are entries with an
if: what is common in one entry, and each machine’s own in another, each a C library of the package.c-libraries { vend { sources = ["vendor/common.c"], include = ["vendor"], headers = ["vend.h"] } vend-macos { if = "macos", sources = ["vendor/macos.c"] } vend-linux { if = "linux", sources = ["vendor/linux/*.c"] } } -
A header-only library needs nothing more: its package ships the one-line source that asks for the implementation, and names it in
sources.#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
Linking statically
A program whose manifest says static-c-libraries = true links its C libraries from their static
archives, so the machine it runs on needs none of them installed
(settled):
package { name = "tend", version = "0.1.0" }
static-c-libraries = true
dependencies {
ssh { git = "github.com/avin-lang/ssh", version = "0.0.1" }
}
-
The program decides, for every package in it. Only the root package’s key is read: a library package that says it is built dynamically into a program that does not, and a program that says it links the C libraries of its dependencies statically too. Without the key, or with
false, every library is linked aspkg-config --libsanswers. -
For each library a
pkg-configmodule finds, the build askspkg-config --static --libs, which adds the libraries it links privately (Libs.private: libssh2’s OpenSSL), and replaces each-l<name>whoselib<name>.ais in one of the answer’s-Ldirectories by the archive’s path, the first directory holding one winning. The path, because on macOS the linker takes a.dylibover a.ain the same directory, and Homebrew installs both side by side. The-Land run-path flags are dropped; every other flag (-framework,-pthread) is kept. -
The system’s own libraries stay dynamic. A name none of the
-Ldirectories holds is one the linker finds by itself, in the system (libSystem and libz on macOS), and stays-l<name>, unless the program names it instatic-system. -
A library
linknames is linked the same way, from its library’ssearchdirectories: each-l<name>whoselib<name>.ais in one of them becomes the archive’s path, and a name none of them holds is the system’s. -
A library with no archive stops the build. A name whose shared library is in one of the search directories but whose archive is in none would be linked dynamically, the very program the key is there to prevent, so it is an error naming what is missing;
avin checkreports it too:error: the C library `libssh2` of package `ssh` is linked statically (`static-c-libraries = true`), but `-lcrypto`, which `pkg-config --static --libs libssh2` names, has no static archive: `/opt/homebrew/opt/openssl@4/lib/libcrypto.dylib` has no `libcrypto.a` beside it -
A file named by its path is linked as named, an archive always statically. A shared library (
.dylib,.tbd,.so) of a library linked statically is replaced by the archive of the same name beside it, and is an error without one.
otool -L is the check: a program binding libssh2 and built this way lists only
/usr/lib/libSystem.B.dylib and /usr/lib/libz.1.dylib.
How a program links its C libraries
The program chooses library by library in its c-linking block (settled),
read from the root package only, as static-c-libraries is:
c-linking {
default = "static" # or "dynamic", the default when unsaid
dynamic = ["mlt"] # linked dynamically whatever the default
static = ["ssh/libssh2"] # linked statically whatever the default
static-system = ["z"] # the system's libz, from its archive
search = ["/opt/homebrew/opt/zlib/lib"]
}
- A library is named as its package’s
c-librariesnames it,mlt, or with its package,ssh/libssh2, where two packages name libraries alike; a bare name names each library of that name. A name that is no C library of the program is an error at the name, listing the program’s libraries, and so is one name in both lists. defaultis how every library neither list names is linked.static-c-libraries = trueisdefault = "static", kept as its shorthand; a manifest saying both is refused, so there is never a question which wins.- Linked dynamically means as named: the flags
pkg-config --libsanswers,-Land-lforlinkandsearch, andfilesas they are, so a vendored archive is linked statically either way. Linked statically is a promise: no shared library of a search directory is taken, and one that would be is an error.
The command line overrides the default for one build. avin build, run, test and check
take --static-c-libraries or --dynamic-c-libraries, which stand in for the manifest’s default:
- a library
c-linkingnames instaticordynamicis linked that way; - any other is linked as the command line says, when it says;
- and otherwise by the manifest’s
default(orstatic-c-libraries), dynamically when it says none.
A name in the manifest is the program saying something about one library, often for a reason (a
licence, an archive that does not exist), so a flag about all of them does not overrule it. A build
cached by avin run or avin test is kept apart for each way of linking.
A library package may require being linked dynamically, never statically, with
dynamic-only = "<why>". A program that would link it statically, by its default, by
--static-c-libraries or by naming it in static, is refused with the package’s reason:
error: the C library `mlt` of package `mlt` is never linked statically, as its package says (`dynamic-only`): LGPL-2.1: its users may replace it; the program links it statically by `static-c-libraries = true`: name it in `c-linking { dynamic = ["mlt"] }` to link it dynamically
Naming it in dynamic is how the program says it has seen the requirement; the rest of the program
stays static. The library is not linked dynamically silently: a program asking to be static would
otherwise ship needing the library installed, and learn it on another machine.
The system’s libraries
static-system names -l names the program links from their archives although the system
provides them, an opt-in; without it the system’s libraries stay dynamic. Each name is looked for
as lib<name>.a in the search directories of the library that links it, then in c-linking‘s
search, each absolute or relative to the root package’s directory (the program’s own machine is
its business, so absolute paths are allowed here and nowhere else). It applies however the library
is linked. A name found in none of them is an error listing the directories searched, and a name no
library of the program links is an error too.
On Linux
Linux is not built yet. The surface maps onto its linker as follows: an archive is still linked by
its path, which needs no flag; a -l<name> kept for the system stays -l<name>; and a name
static-system asks for may equally be written -Wl,-Bstatic -l<name> -Wl,-Bdynamic, which takes
lib<name>.a from the linker’s own path. frameworks are macOS’s alone, and a package for Linux
names none.
Prototypes
The prototype is C’s declaration with three words of its own, which say what C’s types cannot. They are written before the parameter’s type and removed before the header check:
| Word | Meaning |
|---|---|
out | A pointer C writes a value through; the value is part of the binding’s result, and the parameter is not an Avin parameter |
inout | A pointer C reads a value through and writes one back; an Avin parameter and part of the result |
userdata | The void * that travels beside a callback; not an Avin parameter |
null | A pointer, a function pointer among them, the binding passes null; not an Avin parameter |
length(data) before an integer parameter says it is the length of the array parameter data, and
it is filled in from the array rather than written by the caller. It is written first, before the
parameter’s type and before inout.
A binding whose Avin result is unit discards the C result, whatever it is. Every other C result is
converted.
Scalars
| C type | Avin type | Crossing |
|---|---|---|
signed char, short, int, long, long long, intN_t, ssize_t, ptrdiff_t, intptr_t and their unsigned forms, size_t, uintN_t, an integer typedef, an enum | any integer type | Converted with a check, in each direction, as a Sysl integer is: a value the other side cannot hold stops the program at the call, naming the C type by its sign and width |
unsigned char, uint8_t, char | byte | By value. A C char as a value is a byte, whatever its sign on the machine |
bool, _Bool | bool | By value |
an integer type or typedef used as a truth value (Cairo’s cairo_bool_t is an int) | bool | A result is false for zero and true otherwise; a parameter passes 0 or 1 (proposed) |
double | real | By value |
float | real | A parameter is rounded to the nearest float, as C converts one; a result is widened exactly |
Avin has no unsigned integers, so a size_t or a uint32_t is a long (or an int, where the
values fit) and a negative value passed for one stops the program:
avin: trap: value out of range for u64 (size_t) at main.avin:12:5
The width of long, size_t and each typedef is the target’s, measured by the C unit; the check is
emitted for the widths measured. long double, _Complex types and vector types are refused.
A typedef crosses as the Avin type of its kind, which the C unit checks: an integer typedef as an
integer type, one an integer one byte wide as byte, a bool as bool, and a float or a double
as real. signed char crosses only as an integer type, and char only as byte. A result one past
what the binding’s Avin type holds stops the program naming that type, as a Sysl binding’s does:
avin: trap: value out of range for long at main.avin:13:13
Strings
-
A
const char *parameter takes astring, copied into NUL-terminated memory that lives for the call, and until its result is converted, since C may answer a pointer into it (strchr). A string holding U+0000 stops the program at the call, since C would read the NUL as its end:avin: trap: the string passed to `name` of `set` holds a NUL at byte 3 at main.avin:9:5 -
A
char *result, or aconst char *one, is copied into a newstring, up to its NUL. The bytes must be UTF-8; text that is not stops the program at the call, naming the byte the first ill-formed sequence starts at:avin: trap: `mlt_properties_get` answered a string that is not UTF-8 at byte 2 at main.avin:7:9A binding that wants the bytes as they are answers
Array[byte]instead, copied up to the NUL, and nothing is checked. -
C keeps its own string. A string C answers is borrowed: it is copied and left as it was. One the caller must free is bound with
free:naming the function that frees it, called once the copy is made:@c("char *mlt_properties_serialise_yaml(mlt_properties self)", free: "free"). The C unit checks that the headers declare it taking the string or any pointer and answering nothing; it is not called for null. A binding withfree:whose result isunitfrees what C answered and discards it (proposed). -
A string C answers through an
outpointer is freed by an entry offree:naming it (proposed):"name: how",howa C function of the string or a C expression in its name, compiled in the C unit’s glue and called once the copy is made, never for null; where a status fails, a string C answered is freed unread. A method’s expression may also useself, its receiver’skept:name and the values the receiver holds, as its class’srelease:does. libssh2 answers a channel’s exit signal and its message in strings freed bylibssh2_free(session, p), and the session is the one the channel keeps:@c( "int libssh2_channel_get_exit_signal(LIBSSH2_CHANNEL *self, out char **exitsignal, out size_t *exitsignal_len, out char **errmsg, out size_t *errmsg_len, null char **langtag, null size_t *langtag_len)", free: ["exitsignal: libssh2_free(session, exitsignal)", "errmsg: libssh2_free(session, errmsg)"] ) private exitSignalRaw() -> Result[(Option[string], long, Option[string], long), int]free:names each out string once, anoutone answering a string or its bytes, neverinout, since C may answer the copy it was passed; an entry without a name frees the result as before, and a binding whosearray:names arrays frees them by position and no out string besides. -
A typedef of either pointer crosses as the header’s type is: as a result a
char *or aconst char *typedef, as a parameter only aconst char *one, which the C unit checks. -
So does one pointer to a typedef of
char(proposed), as FreeType’sconst FT_String *is (typedef char FT_String): through a chain of typedefs, withconstbefore the typedef, after it or inside it (typedef const char T), at a parameter, a result, anoutvalue, a callback’s parameter and a field, whereverchar *andconst char *cross as a string. Only the headers say what the typedef is, so the C unit checks the whole pointer ischar *orconst char *by the rule above; a typedef ofunsigned charorsigned charholds bytes rather than text, and is refused saying so (the C type `const FT_Byte *` of the result points at `unsigned char` or `signed char` in the headers, which hold bytes rather than text), as a field pointing at either is. -
A
char *parameter, which C may write, does not take astring: it takes an array.
Null
A pointer C may answer null is bound as an Option: null is None. Bound as the type itself, a null
result stops the program at the call:
avin: trap: `mlt_profile_init` answered null at main.avin:4:15
A pointer parameter bound as an Option passes null for None. Strings, handles and arrays may each
be wrapped this way, and so may a mirror passed by const pointer; nothing
else is.
Status results
C reports most failures as an integer. A C integer result bound as Result[unit, int] is Ok(())
when it is zero and Err(code) otherwise. The code may be any integer type, converted with the check
a scalar result has (Result[unit, long] for a long long status). With out parameters, a status result
bound as Result[T, int] holds the out values in its Ok, and they are read only when the status is
zero. A function that answers -1 and says why in errno is bound with errno; other
conventions, a negative error number among them, are written in Avin over the integer, and a public
function maps the code to the library’s own error type.
A status that is a C enum may be bound as Result[unit, E] with E its mirror:
Ok(()) for the enumerator whose value is zero, Err of the variant otherwise. The mirror keeps its
zero variant, since the same type is what a callback answers C with
(proposed):
@c("cairo_status_t cairo_surface_write_to_png(cairo_surface_t *self, const char *filename)")
private writePngRaw(filename: string) -> Result[unit, Status]
errno
A binding marked errno answers Err of errno where C answers -1 (settled).
The word is written among @c‘s arguments, as blocking is, and the binding answers a Result:
Ok of what the C result and the out values make, by the rules for a result that is
not a status (the C result kept as an integer or left out, followed by
the out values), and Err of why. The error is an avin.c.Errno, each POSIX error number by its
own name, ENOENT, ESRCH, EACCES, whatever value it has on the machine the program is built for,
which the C unit measures, and Other(code) for a number no named case is; or it is the number
itself, any integer type. An Errno is an Error, whose message is the number’s sentence, the same
on every platform (no such process).
import avin.c.{Errno, ENOENT, EACCES}
@c("int access(const char *path, int mode)", errno)
private access(path: string, mode: int) -> Result[unit, Errno]
describe(path: string) -> string = access(path, 4) match
Ok(()) -> "readable"
Err(ENOENT) -> "missing"
Err(EACCES) -> "forbidden"
Err(e) -> e.message
errno is read by the binding’s glue in the C unit straight after the call, before anything else
runs, a length: expression and a blocking call’s return among them, so what it holds is what the
function left. It is read only where the C result is -1, which is the failure, whatever errno
holds; a function that sets errno and answers anything else has not failed, and the out values are
read only where it has not, as a status’s are. A C result of an unsigned type fails at its greatest
value, which -1 converts to. A binding marked errno answers a Result whose error is an Errno or
an integer, over a C integer result, and its Ok holds no status of its own; each is refused at the
binding otherwise:
error: the result of the C binding `text` is `Result[string, Errno]` in Avin and `const char *` in C: `errno` marks a C function that answers -1 where it fails, so its result is a C integer
Errors kept on the object
Some libraries do not answer a failure at all: they latch it on the object, which turns inert, and
answer it when asked. Every Cairo call on a context or surface in error does nothing, and a
constructor that fails answers a static object in an error state rather than null. A binding needs
nothing new for this: the query is bound like any other (@c("cairo_status_t cairo_status(cairo_t *self)") status() -> Result[unit, Status]), and the library’s public functions
ask it where the user can act on the answer — after a constructor, before output is produced, and on
request — while the drawing calls answer unit. A latched error is never lost, since every later
query answers it, so checking at those points sees every failure the calls before them made.
Handles
A C object Avin holds without seeing inside is a handle: a class declared with @c(type: …)
naming the C pointer type, and the function that gives the object back:
@c(type: "mlt_producer", release: "mlt_producer_close", retain: "mlt_properties_inc_ref(mlt_producer_properties(self))")
class Producer
@c("int mlt_producer_get_length(mlt_producer self)")
length() -> int
A handle is the Sysl handle over a C pointer, and keeps its rules:
-
Only a binding makes a handle, and each handle owns one reference to its C object, given back by
releaseexactly once: byclose(), or by the collector’s finalizer when the object is freed. Closing again does nothing; a closed handle used stops the program at the call. -
releaseandretainname a C function of the handle’s pointer, or a C expression inself, compiled in the C unit’s glue and type-checked there by clang. -
A pointer C answers is owned by default: the handle takes the reference the call gave. A binding whose pointer C only lends — MLT’s
mlt_playlist_get_clip,mlt_tractor_get_track— saysborrowed, and the handle takes a reference of its own throughretainbefore it is made. A handle with noretaincannot be borrowed, and the binding is refused, since nothing could keep the lent object alive:error: the C binding `clip` lends a `Producer`, and `Producer` declares no `retain`: a lent object is kept only by a reference of its own -
A handle passed to C is lent for the call. C’s own convention is that a pointer it is handed is borrowed, and most functions keep to it. One that keeps what it is handed past the call — MLT’s producers keep a pointer to their profile and take no reference to it — is bound with
keeps:naming the parameter, or a list of them (keeps: ["library", "base"]): the handle the binding makes (or, for a method, the receiver) then holds the Avin object passed, so it is not collected while the holder lives; a kept handle whose class declaresretainis held by a C reference instead. One that takes the reference it is handed is bound withconsumes:, and the handle passed is closed by the call withoutrelease. -
A handle belongs to one owner at a time, checked at every use as a Sysl handle’s is: C libraries rarely let two threads use one object at once. A class whose C object is safe to use from any thread is declared
shared; its owner is not checked, and it is sendable. Whether a handle passed across threads hands its ownership on follows the Sysl handle’s rule. -
A handle is compared by identity, and has no
Displayof its own. -
A handle’s own method without a body is a C binding whose prototype takes the receiver first, named
self, and the method’s parameters after it, by position; a method with a body is an ordinary method and may call the bound ones.sharedis written among the class’s words,@c(type: …, release: …, shared)(proposed). -
What keeps is the handle the binding answers, and for a method that answers none, its receiver; a method answering a handle names its receiver as
selfto have the new handle keep it (@c("FT_Error FT_Get_MM_Var(FT_Face self, …)", keeps: "self")). What a call keeps is kept only when it succeeds: the handle answered is not null, or the status answered is zero.consumes:closes the handle passed whatever the call answers, and it may nameself; what a consumed handle keeps it goes on keeping until it is collected or closed (proposed). -
A parameter may take a handle as its class’s C type
const-qualified (const cairo_t *), the same pointer to C; a result answers exactly the class’s type.
When C holds the object longer than Avin does
keeps: holds the kept object on the Avin handle, and that is enough while the handle’s reference is
the C object’s last. It is not enough where C takes references of its own: a Cairo context and a
surface pattern each reference their surface, so the Avin Surface may be collected, and its
reference given back, while C still draws into the surface — and into the pixel memory or font file
the surface was made over. A library that tells its objects’ owner when C frees one (Cairo’s
cairo_surface_set_user_data, MLT’s mlt_properties_set_data with a destructor) lets the binding
tie a kept object to the C object’s lifetime instead, with attach::
@c(
type: "cairo_surface_t *",
release: "cairo_surface_destroy",
retain: "cairo_surface_reference",
attach: "cairo_surface_set_user_data(self, key, data, destroy)",
key: "cairo_user_data_key_t"
)
class Surface
attach: is a C expression, compiled in the glue, over four names: self; key, the address of a
static object of the type key: names, one per class, defined by the C unit; data, the address of
the runtime’s record of what the handle keeps; and destroy, the runtime’s function that releases the
record. On a class with attach:, the first keeps: of a C object puts its kept objects in that
record, made a root of the collector, and attaches it; C’s call of destroy, whenever and on whichever
thread the last reference goes, unpins it, and runs no Avin code. An attach: expression that answers
non-zero stops the program at the call, since what it would keep could not be kept. Without attach:,
keeps: holds only as long as the handle (proposed).
A binding answering its handle in a Result[H, E] answers that failure instead
(proposed): Ok of the handle where C was told, and otherwise Err of
what attach: answered — E an integer type, checked against its width, or an enum mirror, a value no
variant holds stopping the program — the handle’s reference given back and nothing kept. Cairo answers
a surface it could not make as a surface in an error state, and cairo_surface_set_user_data on it
answers that surface’s status, so the status comes back as the error, with no check before the call:
@c(
"cairo_surface_t *cairo_image_surface_create_for_data(unsigned char *pixels, cairo_format_t format, int width, int height, int stride)",
keeps: "pixels"
)
private surfaceForData(
pixels: ByteBlock,
format: Format,
width: int,
height: int,
stride: int
) -> Result[Surface, Status]
Such a binding answers no out values, its handle is never in an Option, its class has attach: and
it keeps something; a C result that is null still stops the program.
The record belongs to one handle object: a later keeps: through the same handle adds to it, and the
handle lets go of it when its reference goes back, by close() or its finalizer, while C keeps it until
destroy. On such a class every kept object, a handle or a ByteBlock, is held as the Avin object, so
a kept handle’s own reference lives as long as the record. key: may be left out, and key is then the
address of a char of the class’s own; attach: must name self, data and destroy, key: comes
only with attach:, and a shared class has no attach:, since the handle’s owner alone updates the
record (proposed).
Kept handles, and the order they are given back
The collector frees what is unreachable in no order of its own: a holder and the handle it keeps,
found dead in one collection, are finalized in either order. That is harmless where the holder’s
release never touches what it keeps, and a use after free where it does. A FreeType face belongs to
its library, freeing the library frees every face still in it, and FT_Done_Face on one of them
afterwards frees it twice.
So a kept handle whose class declares retain is held by a C reference
(proposed): when the call succeeds the holder takes a reference of its
own through the kept class’s retain, records the C pointer, and gives it back through that class’s
release after its own release. Whichever finalizer the collector runs first, C sees the holder
released before what it keeps. FreeType counts both its libraries (FT_Reference_Library) and its
faces (FT_Reference_Face), so a face keeps its library this way. The release gives back one
reference and no more: FT_Done_Library drops the count and frees the library with its last, so
the library’s own handle, given back while a face still holds a reference, only drops a count.
FT_Done_FreeType, the pair of FT_Init_FreeType, is not a release: after dropping the count it
frees the library’s memory manager whatever the count is, and a face kept past it allocates through
freed memory at its next load:
@c(type: "FT_Library", release: "FT_Done_Library", retain: "FT_Reference_Library")
class Library
@c("FT_Error FT_New_Face(FT_Library library, const char *path, FT_Long index, out FT_Face *face)", keeps: "library")
private newFace(library: Library, path: string, index: long) -> Result[Face, int]
The holder also takes a reference to each C object the kept handle so holds, after the kept
one’s, and gives them back after it (proposed). A variation descriptor
keeping a face keeps the face’s library too, so when the face’s own handle is collected first, and
gives back its reference to the library, the library still outlives the face the descriptor’s
release reaches through.
A kept handle with no retain that no kept: names, a ByteBlock and a callback’s closure are held
as the Avin object, as before, and the holder’s release must not use them: that is taken on
trust. One a kept: names is kept for the holder’s release, as below.
A holder’s release may name what it keeps. A class declaring kept: "face: Face" is made only
by bindings that keep exactly one Face, and its release: and retain: may use face as that
handle’s C pointer, valid until after release since the reference to it is given back last. A
FreeType variation descriptor is freed through the library its face belongs to, and FreeType
publishes that library in the face’s glyph slot:
@c(type: "FT_MM_Var *", kept: "face: Face", release: "FT_Done_MM_Var(face->glyph->library, self)")
class MMVar
@c("FT_Error FT_Get_MM_Var(FT_Face face, out FT_MM_Var **master)", keeps: "face")
private mmVar(face: Face) -> Result[MMVar, int]
A class with kept: made by a binding that does not keep one handle of that class is refused at the
binding, as is a kept: name that release: and retain: never use. The class kept: names is a C
handle of the holder’s module, or one written with its module (freetype.Face). retain: sees the
name where it takes the reference of a borrowed result, as the pointer of the handle the binding
keeps (proposed).
A kept handle no C reference can hold is kept from the collector until the holder’s release has
run (proposed): one whose class declares no retain, or a kept: of its
own. libssh2 counts no references: a channel belongs to its session, libssh2_session_free frees
every channel still open, and libssh2_channel_free reaches through the channel to its session. So
the channel’s class names its session with kept:, and the session’s handle is held as its Avin
object, a root of every collection while the channel’s handle holds it; the collector may find both
dead at once, and finalizes the channel then and the session in a later collection. The name is the
kept handle’s pointer, or null once that handle was closed, so a release that must not run after
the kept object’s own says so:
@c(type: "LIBSSH2_CHANNEL *", kept: "session: Session", release: "session ? libssh2_channel_free(self) : 0")
class Channel
A chain is given back in its order: a handle keeping a channel this way is finalized first, the channel in the next collection and the session in the one after. What the closed handle freed with it is the release’s to know; only its own pointer is passed. A cycle through such a kept handle is never collected: a session whose handle keeps, as its Avin object, a channel that keeps the session this way is reachable from the channel’s root for as long as both are open, and both are given back once either is closed (proposed). The handle is kept by one root for each holder, and a holder closed lets go of its own at once.
Values a handle holds
A handle may hold C integers for its release: (proposed), declared by
its class with holds:, a C declaration or a list of them, each starting at the value written
(= -1) or zero. A binding names with hold: the parameters whose values the handle it answers, or
for a method answering none its receiver, holds, when the call succeeds, converted to the declared
type; a later hold: of the same name replaces the value. release: uses each by its name.
libssh2 is handed the socket of a session and never closes it, and libssh2_session_free writes to
it. An Avin TcpStream closes its socket when it is closed or collected, and its descriptor’s number
goes to the next one opened, so a session given the stream’s own descriptor could write its farewell
into an unrelated connection. Given a descriptor of its own, duped from the stream’s, the session
owns what its release writes to, whichever is collected first and whether or not the stream was
closed before it:
@c(
type: "LIBSSH2_SESSION *",
holds: "int sock = -1",
release: "(libssh2_session_set_blocking(self, 1), libssh2_session_free(self), sock >= 0 ? close(sock) : 0)"
)
class Session
@c("int libssh2_session_handshake(LIBSSH2_SESSION *self, int sock)", hold: "sock")
private handshakeRaw(sock: int) -> Result[unit, int]
A value held is a C integer, no wider than a pointer, never a reference: what it names is the
release’s to give back, and a holder holds nothing for another. A class with holds: is not shared,
since only the handle’s owner sets what it holds, and declares no retain:, since what it holds is the
one handle’s. Each name is used by release:, and is neither self nor the kept: name; hold:
names integer parameters, on a binding answering a handle or a method of one whose class declares
each name.
Handles of another package
A binding may take or answer a handle class another package declares
(proposed), when its package depends on that one and the class is
public. Cairo’s FreeType font faces are made from FreeType’s FT_Face, so avin-lang/cairo depends
on avin-lang/freetype and names its Face:
module cairo
import freetype.Face
@c("cairo_font_face_t *cairo_ft_font_face_create_for_ft_face(FT_Face face, int load_flags)", keeps: "face")
private ftFontFace(face: Face, loadFlags: int) -> FontFace
- The prototype names the class’s own C type, or one of its
as:types, by the rule for any handle; the class’stype:,retain,releaseandas:glue are the declaring package’s, compiled once in the C unit, and called by the other package’s bindings. - The C unit checks the binding with the declaring package’s headers and flags first: a
package’s bindings are compiled after the
headersof every package whose handle classes they name, in dependency order, and with those packages’pkg-configflags beside its own, soFT_Faceis declared whether or not Cairo’s header includes FreeType’s. A header included twice is guarded by the header itself, as C’s always are. - Ownership crosses unchanged. A handle passed is lent for the call, and
keeps:,consumes:andattach:hold, take or tie it exactly as they would a handle of the binding’s own package; a pointer answered makes the declaring class’s handle, owned, orborrowedthrough itsretain. The owner check is the handle’s own, whichever package’s binding uses it.
A binding naming a handle class of a package its own does not depend on cannot name it at all, since the class is not in scope; one naming a private class is refused as any use of it is.
Handles and C’s inheritance
C libraries model inheritance by a struct whose first member is its parent: an MLT producer is a service, and a service is a property bag. A handle declares the other C types it may be passed as, each with the C function or expression that makes one:
@c(
type: "mlt_playlist",
release: "mlt_playlist_close",
retain: "mlt_properties_inc_ref(mlt_playlist_properties(self))",
as: [
"mlt_producer = mlt_playlist_producer(self)",
"mlt_service = mlt_playlist_service(self)",
"mlt_properties = mlt_playlist_properties(self)"
]
)
class Playlist
@c("int mlt_properties_set_int(mlt_properties self, const char *name, int value)")
setInt(name: string, value: int) -> Result[unit, int]
A handle is passed where a prototype names one of its as types, receiver or parameter, through
that conversion; the conversion lends, and the handle stays the owner. A method whose receiver’s C
type is neither the handle’s type nor an as type is refused at the method.
-
An entry is a C pointer type,
=, and a C function of the handle’s pointer or an expression inself, asrelease:is:"mlt_service = mlt_playlist_service"calls the function with the handle’s pointer.as:is one string or a list; each type is named once, and never the class’s own. The C unit compiles each into glue and checks that what the expression makes is the entry’s type, so a conversion to the wrong type is refused at the class rather than passing C the wrong pointer:error: the `as:` conversion of the C handle `Derived` to `fxf_middle` makes another type: `&self->middle.base` is not a `fxf_middle` in its headers -
The conversion is made at the call, after the closed and owner checks, from the handle’s own pointer: a closed handle stops the program at the call whichever type it is passed as, and
Nonepasses null with no conversion made. A parameter takes anastypeconst-qualified as it takes the class’s own. -
What a binding keeps or takes is the handle, not the converted pointer:
keeps:of a handle passed as anastype holds it by its class’s ownretain, andconsumes:closes it (proposed). -
A result answers only the class’s own type: a pointer C answers as another type is a handle of the class on that type.
-
The glue is the declaring package’s, so another package’s bindings pass the handle through it as they pass it as its own type.
Field accessors
A handle on a struct whose layout the header publishes reads and writes its fields through methods
bound with field:. The reader takes no parameters and answers the field; the writer takes one and
answers unit:
@c(type: "mlt_profile", release: "mlt_profile_close")
class Profile
@c(field: "width")
width() -> int
@c(field: "frame_rate_num")
frameRateNum() -> int
The field’s C type is the header’s, so its conversion is the scalar one for that type; a field that is a pointer is read as a string or a borrowed handle by the same rules as a result.
-
The field is a member path of the struct
selfpoints at,"width","origin.x","glyph->bitmap.rows", read asself->followed by it. The handle’s type must point at a struct the headers define; one they only declare is refused when the C unit compiles the accessor. -
A field is read as an integer type,
byte,bool,real, an enum mirror, a struct mirror, a string or a handle, or the memory a byte pointer points at is lent as a view withviewandlength:. The C unit checks the field is the kind its Avin type needs (an integer or enumeration, one byte wide forbyte, aboolor an integer forbool, a floating-point type forreal,char *orconst char *for a string, and the class’s own C type for a handle) and measures its width and sign, so an integer the Avin type cannot hold stops the program at the read, as a result does. A null string isNonefor anOption[string]and stops the program otherwise; a string is copied and checked as UTF-8, and never freed, since the struct owns it. -
A field may be read and written as an enum mirror (proposed): the field is of an integer type, the enum the mirror mirrors or another (a union member C declares
int), measured as any integer field is. A value read that no variant holds stops the program at the read (the field `cells[i].header.kind` of `Path` held a value no variant of `PathDataType` holds), and a variant is written as its enumerator’s value. A mirror in anOptionis neither, since a field is never null. Cairo’s path data is a union whose header holds the element’s kind:@c(field: "data[i].header.type", bound: "self->num_data") kind(i: int) -> PathDataType -
A field may be read and written as a struct mirror, whole (proposed): the field is the struct the mirror mirrors, which the C unit checks, reached by any member path, through pointers and into arrays. The reader copies the struct into memory of its own and reads a new value of the mirror out of it, each field converted as a mirror C fills is, with the same traps, its strings copied and left to C, the mirrors and enum mirrors it holds read in place; the writer lays the value out as C’s struct and assigns it. A mirror holding a string, in a field of its own or of a mirror it holds, is only read, as a string field is, and a mirror in an
Optionis neither. FreeType’s face box and size metrics:@c(field: "bbox") boundingBox() -> BBox @c(field: "size->metrics") sizeMetrics() -> SizeMetrics -
A handle read from a field is lent, as a
borrowedresult is: it takes a reference of its own through its class’sretain, so the class must declare one, and a class withkept:cannot be read, since the accessor keeps nothing.borrowedis not written. -
A writer answers
unit, and its last parameter is the value, written as an argument of the field’s type is converted: a value the field cannot hold stops the program at the call. Only a scalar, an enum mirror or a struct mirror holding no string is written: a string or a handle stored into a struct would leave C holding memory or a reference no one gives back, so those fields are read only (proposed). Aconstfield, an array, or anything else C cannot assign is refused at the accessor. -
Every other parameter is an index, an
intor alongthe field names, passed to C as along long.bound:gives each one’s bound in order, one string for one index or a list for more (bound: ["self->rows", "self->columns"]), each a C expression inselfand the indices. An index the field does not name, abound:on an accessor with no index, and a count of bounds that is not the count of indices are refused. -
The accessor checks its receiver as any method does: it stops the program on a closed handle, or one another thread owns, before anything is read.
A field may be an expression: a C lvalue in self and the accessor’s parameters, reaching through
the struct to an array it points at, and a union’s members. An integer parameter used as an index is
given a bound:, a C expression in self; the accessor stops the program unless 0 <= i < bound
before C reads anything (proposed). That is how a C-owned array of a
union is read — Cairo’s cairo_path_t, whose data is num_data elements of a union of a header
(type, length) and a point (x, y), freed whole by cairo_path_destroy:
@c(type: "cairo_path_t *", release: "cairo_path_destroy")
class CPath
@c(field: "num_data")
count() -> int
@c(field: "data[i].header.type", bound: "self->num_data")
kind(i: int) -> PathDataType
@c(field: "data[i].header.length", bound: "self->num_data")
span(i: int) -> int
@c(field: "data[i].point.x", bound: "self->num_data")
x(i: int) -> real
@c(field: "data[i].point.y", bound: "self->num_data")
y(i: int) -> real
The library walks the handle once, by each header’s length, into immutable Avin data (a
Vector[PathElement] of MoveTo, LineTo, CurveTo and ClosePath) and closes it; the union never
reaches Avin code. An accessor with an index and no bound: is refused.
Structs
Structs by pointer
A struct C allocates and Avin reaches through a pointer is a handle, its fields read
through accessors. A struct Avin makes and passes by pointer, for C to read or
fill, is a mirror passed as const T * (read) or out T * (filled, part of the
result); the pointer is to a copy that lives for the call. A const T * C may be given null for —
Cairo’s cairo_recording_surface_create takes null extents for an unbounded surface — takes an
Option of the mirror (proposed). Cairo’s cairo_matrix_t,
cairo_text_extents_t, cairo_font_extents_t and cairo_rectangle_t are mirrors: C fills them
through out (cairo_text_extents), reads them through const (cairo_set_matrix) and updates them
through inout (cairo_matrix_translate).
Structs by value
A struct passed by value is mirrored by a data type with one variant named as the type, as a
Sysl struct is (proposed). struct:
names the struct by its typedef or its tag, struct as_tagged; a union, a pointer or a scalar is
refused. Its fields are matched by name, the Avin lowerCamelCase to C’s snake_case (maxXAdvance
is max_x_advance), or by a field’s own @c("name"); every C field is mirrored, in the header’s
order, and each field is an integer type, byte, bool, real, a string or Option[string] (a
const char *, null None), an enum mirror, or another struct mirror that
does not hold it. The C unit measures each field’s offset and C type and the struct’s size, and
asserts that the fields come in the header’s order, each where C’s alignment places it after the one
before, nothing after the last, and none left out between them; a field crosses at its C type’s
width, converted as a scalar argument or result is, with the same traps. A mirror’s value is a copy
in C memory that lives for the call: strings in it are copies freed after the call, and strings C
writes into one it fills are copied out and left to C.
@c(struct: "mlt_color")
data Color
Color(r: byte, g: byte, b: byte, a: byte)
A struct passed by value whose layout Avin does not mirror — a union, a struct with a bit-field or a
flexible array, one a library documents as opaque but passes by value — is an opaque value: a
class declared with @c(value: "mlt_event_data"), whose object holds a copy of the C value’s bytes
and is passed and answered by value, never through a pointer, inout or in an Option; each object
is its own, compared by identity, and made only by a binding that answers one. Its methods are
bindings taking the value as their receiver:
@c(value: "mlt_event_data")
class EventData
@c("int mlt_event_data_to_int(mlt_event_data self)")
toInt() -> int
A call that passes or answers a struct by value goes through glue. LLVM IR does not lower an aggregate to the registers the platform’s C convention names; clang does. So a binding with a struct by value is called through a C function the C unit defines, which takes and answers the struct through pointers and makes the real call, and clang classifies the aggregate for whatever target the program is built for (proposed; a classification of Avin’s own, per target, in lowering, may replace it where a measurement says the extra call matters). Scalars, pointers and structs by pointer need no classification and are called directly.
Enums and constants
A C enum is an integer, and a binding may take or answer it as one. Mirrored, it is a data type
whose variants have no fields, each the enumerator of its words in snake_case after a prefix, or the
one its own @c("name") names:
@c(enum: "mlt_image_format", prefix: "mlt_image_")
data ImageFormat
None
Rgb
Rgba
Yuv422
@c("mlt_image_yuv420p")
Yuv420p
The words are matched in the prefix’s case, so an upper-case prefix matches upper-case enumerators:
@c(enum: "cairo_format_t", prefix: "CAIRO_FORMAT_") mirrors CAIRO_FORMAT_ARGB32 as Argb32 and
CAIRO_FORMAT_A8 as A8 (proposed). A word starts at each upper-case
letter of the variant’s name, and a digit or _ stays with the word before it: ColorDodge is
COLOR_DODGE and Rgb16_565 is RGB16_565. An enumerator whose name starts with a digit after the
prefix, CAIRO_PDF_VERSION_1_4, is no variant’s words, so its variant names it with @c. Two mirrors
of one module may share a variant’s name, as Cairo’s slant and weight share Normal.
A mirror’s variant may have a core library variant’s name, as ImageFormat.None does. In the
binding’s module it hides Option‘s, yet wherever an Option is expected, a -> Option[T]
result, an Option parameter or a pattern on an option, the bare None is still Option‘s
(data types; proposed).
Each enumerator’s value is measured by the C unit, which checks the mirrored type is an enumeration or an integer type and that the headers declare every enumerator. A mirror crosses where the prototype writes the type it mirrors, as a parameter, a result, a status or an out value, at that type’s width. A value C answers that no variant holds stops the program at the call:
avin: trap: `cairo_status` answered a value no variant of `Status` holds at status.avin:7:1
Where two enumerators have one value, both variants cross as it, and the value comes back as the
first. A mirror need not list every enumerator: one it leaves out is a value it cannot
take. An enum whose values are flags combined with | (Cairo’s cairo_pdf_outline_flags_t) is
bound as an integer, its flags as constants, and the library gives it an Avin type of its own.
A constant the header defines — an enumerator, a #define, a static const — is bound as a
top-level val without an initializer, measured by the C unit and folded into the program as a
constant:
@c(const: "LIBMLT_VERSION_INT")
val mltVersion: int
A constant is an integer, a real or a string: a string literal the header defines (Cairo’s
CAIRO_TAG_DEST, "cairo.dest") is stored by the C unit as its bytes, read by the driver like any
measurement, and checked as UTF-8 then (proposed). An integer constant
may be any integer constant expression, an enumerator or a character among them, and one its Avin
type cannot hold is refused at the constant, naming its value; a real may be given an integer
constant, and holds NaN, the infinities and minus zero as C defines them.
Arrays and out parameters
-
An array parameter is a pointer. An
Array[byte]goes to auint8_t *,char *orunsigned char *, anArray[int]to anint32_t *orint *, anArray[long]to anint64_t *, anArray[real]to adouble *; the element types must be the same size and kind, and nothing is converted. A typedef of such a type takes the array too; the C unit checks what the pointer points at, by kind and size, and anintor alongelement as signed (proposed). Aconstpointer is only read; a pointer that is notconstmay be written, and what C writes is in the array after the call. Its length goes to the parameter markedlength(data), which is not an Avin parameter, converted to that parameter’s C type as anyintargument is: an array too long for it stops the program at the call. The length may come before the array or after it, and a call may take several arrays, each with its own. A binding taking an array whose length nothing carries is refused, since C could read past its end; one C fills with as many elements as another call says is anoutarray the binding allocates. AnOptionof an array passes null and a length of zero forNone.@c("ssize_t read(int fd, uint8_t *into, length(into) size_t count)") private readInto(fd: int, into: Array[byte]) -> longlength(data)may also mark aninoutpointer to an integer, for C that is told the length and answers how much it used (proposed): the array’s length is written in before the call, and the value C writes back is part of the result, an integer, stopping the program if it exceeds the array’s length. AnOptionof the array passes null and a length of zero forNone, which is how a C function is asked the size it needs, and bounds nothing. FreeType’sFT_Load_Sfnt_Tableis asked twice, once with no buffer for the table’s size and once to fill one:@c( "FT_Error FT_Load_Sfnt_Table(FT_Face self, FT_ULong tag, FT_Long offset, FT_Byte *buffer, length(buffer) inout FT_ULong *length)" ) private loadSfntTableRaw(tag: long, offset: long, buffer: Option[Array[byte]]) -> Result[long, int] -
An array of a mirror goes to a
constpointer to its struct (proposed). A mirror’s Avin layout is not C’s, so the elements are converted into C memory that lives for the call, laid out as the header lays the struct out, and nothing is written back; a pointer that is notconstdoes not take one. Cairo’s glyphs are drawn this way, with nocairo_glyph_allocate:@c(struct: "cairo_glyph_t") data Glyph Glyph(index: long, x: real, y: real) @c("void cairo_show_glyphs(cairo_t *self, const cairo_glyph_t *glyphs, length(glyphs) int num_glyphs)") showGlyphs(glyphs: Array[Glyph]) -
An array C allocates and answers is copied, as an
Arrayof a scalar or a mirror: anoutpointer named witharray:, given alength:(a C expression, as for buffers) and afree:naming the C function or the C expression in the array’s name that frees it once the copy is made — Cairo’scairo_scaled_font_text_to_glyphs, freed bycairo_glyph_free(glyphs). The length is computed in the C unit’s glue after the call, over the parameters and the out values by their names; the length’s own out value stays in the result. Null isNonefor anOptionof the array, an empty array where the length is zero, and stops the program otherwise, as a negative length does; where a status fails, the array is freed unread (proposed).bytes:is the same for anArray[byte]. -
An array C fills is allocated by the binding (proposed): an
outpointer to the elements themselves,out double *dashes, named witharray:and given alength:, a C expression over the parameters evaluated in the glue before the call, since C writes as many elements as some other call says and no parameter tells it how many. The glue allocates that many, C fills them, and the array is copied into a newArrayand freed. Cairo’s dash pattern is as long ascairo_get_dash_countsays:@c( "void cairo_get_dash(cairo_t *self, out double *dashes, out double *offset)", array: "dashes", length: "cairo_get_dash_count(self)" ) dash() -> (Array[real], real)A length of zero is an empty array, C still called. A negative length, or one longer than an array holds, calls nothing and stops the program (
`cairo_get_dash` answered through `dashes` a negative length). The array is never null, so never in anOption, and the binding frees it, so it takes nofree:; its elements are those of an array C allocates, and an out value’s name is not yet written when the length is evaluated, so alength:naming one is refused by clang in the glue. -
Several arrays in one call are named as a list (proposed):
array:(orbytes:) a list of the out parameters,length:a list of their lengths in the same order, andfree:, where it is given, a list of how each is freed,""for an array C fills or one nothing frees. Each array is copied and freed by its own entry, and where a status fails every array C answered is freed unread. The result keeps the prototype’s order whatever order the lists name the arrays in. A list names each array once, each anoutparameter, and a list of lengths or of frees comes only with a list of arrays. -
A pointer marked
nullis passed null (proposed): the word is written before the parameter’s type, asoutis, for a pointer C allows to be null — an out value the binding does not want, or an optional pointer it leaves out. It is no Avin parameter and no part of the result, and the header check holds it to the header’s type like any other. A function whose caller chooses is bound twice. Cairo’scairo_scaled_font_text_to_glyphsanswers glyphs and clusters, each allocated by Cairo with its own count and its own free function, and takes null for the clusters, their count and their flags where they are not wanted:@c( "cairo_status_t cairo_scaled_font_text_to_glyphs(cairo_scaled_font_t *self, double x, double y, const char *utf8, int utf8_len, out cairo_glyph_t **glyphs, out int *num_glyphs, out cairo_text_cluster_t **clusters, out int *num_clusters, out cairo_text_cluster_flags_t *cluster_flags)", array: ["glyphs", "clusters"], length: ["num_glyphs", "num_clusters"], free: ["cairo_glyph_free", "cairo_text_cluster_free"] ) private textToGlyphsRaw(x: real, y: real, utf8: string, length: int) -> Result[ (Array[Glyph], int, Array[TextCluster], int, ClusterFlags), Status ] @c( "cairo_status_t cairo_scaled_font_text_to_glyphs(cairo_scaled_font_t *self, double x, double y, const char *utf8, int utf8_len, out cairo_glyph_t **glyphs, out int *num_glyphs, null cairo_text_cluster_t **clusters, null int *num_clusters, null cairo_text_cluster_flags_t *cluster_flags)", array: "glyphs", length: "num_glyphs", free: "cairo_glyph_free" ) private glyphsRaw(x: real, y: real, utf8: string, length: int) -> Result[(Array[Glyph], int), Status]nullis neverout,inoutoruserdatabesides, never written twice, never an array a length is filled in from, and never a callback’s parameter; a struct passed by value or a scalar is no pointer, and is refused.A function pointer marked
nullis passed null too (proposed), for C that takes optional hooks and uses its own where it is given none. libssh2 makes a session only throughlibssh2_session_init_ex, which takes an allocator, a free function, a reallocator and thevoid *they share,libssh2_session_init()being a macro that passes four nulls:@c( "LIBSSH2_SESSION *libssh2_session_init_ex(null void *(*my_alloc)(size_t count, void **abstract), null void (*my_free)(void *ptr, void **abstract), null void *(*my_realloc)(void *ptr, size_t count, void **abstract), null void *abstract)" ) private sessionInit() -> Option[Session]C never calls a function it is passed null for, so its parameters are read only as C’s types, for the header check: it is named, as every function pointer is, takes no
userdataorlengthamong its parameters, and may answer any type, a string too. A function pointer passed null sits beside a callback C does call, and beside every other kind of parameter. -
An out parameter is part of the result. The Avin result is the C result followed by each
outandinoutvalue in order, as a tuple; a C result bound asunitleaves the tuple without it, one value alone is not a tuple, and a status bound asResult[T, int]holds the rest in itsOk. An out value is a scalar, a string, a handle (owned, unless the binding saysborrowed) or a mirror.outandinoutare written before the parameter’s type, which is a pointer to what is answered, never toconst. A C result that is notvoidis left out where the binding answers the out values alone. Each is a slot in the call’s frame, zero or null until C writes it; aninoutone holds the converted argument first, a string as a copy C may move the pointer into, and a handle is never passedinout(proposed). A handle answered through an out pointer keeps what the callkeeps:where the C result is no handle.@c("int mlt_service_get_frame(mlt_service self, out mlt_frame *frame, int index)") private getFrame(index: int) -> Result[Frame, int]
Memory of no type
A void * or const void * parameter takes an array of any element type an array crosses as, or
a ByteBlock, and its length counts bytes (settled). C’s untyped
buffers are memory whose type the caller chooses: sysctlbyname writes an int or a long, write
reads any bytes. So an Array[byte], Array[int], Array[long] or Array[real] goes to the pointer
as it is, its elements where they are, and the header has no element type to check. The parameter
marked length(p) is told the array’s length times the size of its element, as a long, converted
to the parameter’s C type as any long argument is; an inout length C writes back through is in
bytes too, and stops the program where it exceeds the array’s bytes. C writes through void *, and
what it wrote is in the array after the call, and only reads through const void *. An Option of
the array passes null and a length of zero for None, and a void * marked null is passed null.
A ByteBlock is passed as a pointer to its bytes, as to any pointer.
@c(
"int sysctlbyname(const char *name, void *oldp, length(oldp) inout size_t *oldlenp, null void *newp, size_t newlen)"
)
private sysctlRaw(name: string, into: Array[int], newlen: long) -> (int, long)
// The `int` the kernel holds under `name`, where it holds one.
sysctlInt(name: string) -> Option[int] =
val v = Array.fill(1, 0)
sysctlRaw(name, v, 0) match
(0, 4) -> Some(v(0))
_ -> None
sysctlInt("kern.maxfilesperproc") answers the limit; the same binding over an Array[long] reads
hw.memsize, and asked with None for the array (bound as an Option), C answers the size it
needs. The header check holds a void * to the header’s type as it holds every pointer, so a binding
saying const void * where the header writes void * is refused, and so is one saying void *
where the header writes a typed pointer.
A pointer to an opaque pointer points at memory of no type too (settled):
void **, and a pointer to a typedef the headers make void * or const void *, as Apple’s
rusage_info_t * is. Headers write one where C writes whatever the caller’s flavour says through it.
Passed in, it takes what void * takes, its length in bytes. Only the headers say what a typedef
is, so the C unit measures it, and checks the elements of an array passed to a pointer to a typedef
are either what the typedef is or the typedef is void *; a typedef of an integer type points at
elements, which its length counts. The header check still holds the prototype to the header’s own
type, so the binding writes rusage_info_t *, as the header does, never void * or the struct.
C fills memory of no type through out: through out void * or a pointer to a typedef that is
void *, out rusage_info_t *buffer, it fills an array the binding allocates,
named with array:, its length: counting bytes, as many elements of the array’s type as hold
them, the last zero past what C writes; or a struct mirror, which out void ** takes as well, the
C unit checking a typedef is the mirror’s struct or void *. proc_pid_rusage writes a
struct rusage_info_v2 through its rusage_info_t *, sixteen bytes of ri_uuid, which no mirror’s
field holds, then eighteen uint64_t fields, so its bytes are answered as longs:
import avin.c.Errno
@c(
"int proc_pid_rusage(int pid, int flavor, out rusage_info_t *buffer)",
array: "buffer",
length: "sizeof(struct rusage_info_v2)",
errno
)
private rusage(pid: int, flavor: int) -> Result[Array[long], Errno]
@c(const: "RUSAGE_INFO_V2")
val rusageInfoV2: int
// The physical footprint of the process `pid`, in bytes: the ninth `uint64_t` after `ri_uuid`'s
// two `long`s. A process that does not exist is `Err(ESRCH)`.
footprintBytes(pid: int) -> Result[long, Errno] = rusage(pid, rusageInfoV2).map(info -> info(9))
Memory of no type C allocates and answers through out void **, named with bytes: or array:, is
an Array[byte], as long as its length: says in bytes, which need not be a whole number of wider
elements. What is still refused:
- an array whose length no parameter carries, as everywhere:
memcmp(const void *a, const void *b, size_t n)carries one length for two, and its second array is refused; - a value through
out void *, andinout void *: C writes no value of a type through one (C writes no value through `out void *p`, which points at memory of no type), so the memory is an array or a block passed in, or an array or a struct mirror C fills; - an array of anything but bytes for memory of no type C allocates (
C allocates memory of no type for `p`, whose length in bytes need not be a whole number of `long`s, so it is answered as an `Array[byte]`); - anything else for a
void *parameter: a scalar, a string or an array of strings (`const void *` points at memory of no type, so it takes an `Array[byte]`, `Array[int]`, `Array[long]` or `Array[real]`, its length in bytes carried by the parameter marked `length(buf)`, or a `ByteBlock`); - a
void *result, whose length nothing says, except that a binding answeringunitdiscards it.
Buffers
Pixels and samples are memory C owns, often megabytes of it, valid while the object that owns them is unchanged. A binding answers such memory in one of two ways:
-
Copied, as an
Array[byte]: anoutpointer to bytes named withbytes:and given alength:, a C expression over the call’s parameters and out values, evaluated in the glue after the call. The array never reads C’s memory. -
Borrowed, as a
ByteViewfromavin.c, named withview:and given alength:: a handle on the C memory that reads it in place, bounds-checked —length,apply(i),slice(from, until)copying a range out, andcopy()— and holds a reference to the handle that owns the memory, so the owner is not collected while the view is open. A view is valid until its owner is used again: any bound method of the owner, or itsclose(), closes every view it lent first, since a second call may free or replace the memory (MLT converts a frame’s image in place). A closed view used stops the program (proposed):avin: trap: the `ByteView` of `Frame` was closed when `Frame` was used again at main.avin:22:17
@c(type: "mlt_frame", release: "mlt_frame_close", retain: "mlt_properties_inc_ref(mlt_frame_properties(self))")
class Frame
@c(
"int mlt_frame_get_image(mlt_frame self, out uint8_t **buffer, inout mlt_image_format *format, out int *width, out int *height, int writable)",
view: "buffer",
length: "mlt_image_format_size(format, width, height, NULL)"
)
private imageRaw(format: ImageFormat, writable: int) -> Result[(ByteView, ImageFormat, int, int), int]
A binding whose C result is the pointer to the memory says view with no name, and its length:
is a C expression over the parameters:
@c(
"unsigned char *cairo_image_surface_get_data(cairo_surface_t *self)",
view,
writable,
length: "cairo_image_surface_get_stride(self) * cairo_image_surface_get_height(self)"
)
private dataRaw() -> Option[MutByteView]
A field accessor whose field is a byte pointer says view the same way, its
length: a C expression in self (proposed). A FreeType glyph’s bitmap
is a field of the face’s glyph slot, |pitch| * rows bytes that the face’s next load replaces — the
view’s own rule, since that load is a use of the face. pitch is negative for a bitmap stored bottom
row first, and the buffer then begins with the bottom row, so the length takes its magnitude:
@c(
field: "glyph->bitmap.buffer",
view,
length: "(self->glyph->bitmap.pitch < 0 ? -self->glyph->bitmap.pitch : self->glyph->bitmap.pitch) * self->glyph->bitmap.rows"
)
private bitmapRaw() -> Option[ByteView]
The buffer is null for a glyph with no pixels (a space), answered as None. Reading a row as row * pitch with a negative pitch is caught by the view’s bounds check rather than read from before the
buffer.
Such an accessor takes view, length: and writable beside field: and bound:, and nothing
else: length: is a C expression in self and the indices, evaluated after the field is read, and
an index is checked against its bound before either. The C unit checks the field points at an integer
type one byte wide, and that a writable one is not const (proposed):
error: the field `name` of the C handle `Face` points at `const` memory in the headers, so `Face.name` cannot lend it `writable`
A field view is lent and closed by the rules of every view below: its handle’s next use closes it,
another field accessor among them, and a shared handle lends none. A writer lends nothing, and an
accessor answering a view without saying view, or a ByteBlock at all, is refused.
Writing into C’s memory
A ByteView is read-only. A binding marked writable answers an avin.c.MutByteView, which is
a ByteView with update(i, b), fill(from, until, b) and write(at, bytes) added, every one
bounds-checked, and is closed by the same rule: the owner’s next use closes it
(proposed). A writable binding needs a pointer that is not const. Whether
C sees the bytes is the library’s own protocol, written in Avin over the owner: Cairo’s surface is
flushed before its data is lent and told with cairo_surface_mark_dirty once it was written, and since
markDirty() is a use of the owner it closes the view, so a write after it is caught:
val px = surface.pixels()?
px.fill(0, 4, byte(255))
surface.markDirty()
px.update(4, byte(0))
avin: trap: the `MutByteView` of `Surface` was closed when `Surface` was used again at main.avin:4:5
Memory Avin gives C
Memory C keeps, and writes into, is an avin.c.ByteBlock (proposed):
a fixed number of bytes outside the collected heap, zeroed when made by ByteBlock(length), read and
written in place by the methods of a MutByteView and freed when it is collected. It is passed where a
prototype names a byte pointer, as an array is, with its length filled into length(p), but never
copied: its address does not move, so it may be passed to a blocking call, and kept by C past the
call. A binding that hands it to C for keeps says keeps:, and on a class with
attach: the block lives as long as C’s object:
@c(
"cairo_surface_t *cairo_image_surface_create_for_data(unsigned char *pixels, cairo_format_t format, int width, int height, int stride)",
keeps: "pixels"
)
private surfaceForData(pixels: ByteBlock, format: Format, width: int, height: int, stride: int) -> Surface
Cairo reads height * stride bytes from pixels and no prototype says so; the library checks
pixels.length >= height * stride before the call, a precondition the binding takes on trust like
any length.
ByteBlock(length) with a negative length stops the program, and the class’s own constructor,
ByteBlock(), makes a block of no bytes, passed to C as null. A block is a MutByteView that nothing
closes, since nothing lent it; it belongs to the code that made it and moves between threads as a handle
does, so another thread’s use stops the program ( `ByteBlock` belongs to another thread). Only a
block is passed to C: a view is memory C lent, never passed back. It is never in an Option and never
inout, and the C unit checks that the pointer it is passed to points at bytes one byte wide.
The rules of views and blocks
A view’s length and its indices are ints, as an array’s are. Where the binding’s length: is
negative, or longer than the greatest int, the program stops at the call ( `bf_frame_static` answered more bytes than a view holds). C lending null is None where the binding answers an
Option, whatever the length; otherwise null with a length of zero is an empty view, and null with any
other length stops the program ( `frame_data` answered null). bytes: answers the same way, with an
empty array for a null of length zero (proposed).
A view is lent only by a method of a C handle, its lender, and only by a handle that is not shared:
the view belongs to the code that owns its lender, wherever that code runs, so a lightweight thread
reads its view across its own switches, a thread’s body that captures a view takes its lender with it,
and any other thread’s use stops the program ( the `ByteView` of `Frame` belongs to another thread). A field accessor is a use of its handle as a method is, and closes the view it lent. Each
operation of a view or a block checks, in order, the code running, that a view is still open, and the
indices: index out of range for apply and update, slice out of range for slice and fill,
and write out of range for a write that does not fit, which writes nothing. A failed status lends
nothing (proposed).
Calls that wait
A C function that may wait — for a frame, for a thread, for input — is bound with blocking, as a
Sysl one is: @c("…", blocking). The call is bracketed by
the runtime’s avin_rt_enter_safe and avin_rt_leave_safe, so a collection runs while it waits.
Every argument is converted first, and none points into the Avin heap during the call: a string’s
copy is not on the heap, an array is copied into memory outside it and back after the call, and a
handle’s C pointer is a plain value whose object the call’s frame keeps alive. The result is
converted once the thread is running again.
A blocking array’s copy is copied back only where the pointer is not const, and freed, before
the result is converted; a handle’s object is used once the thread is running again, so the frame
keeps it alive across the wait (proposed).
A call that is not blocking is made with the thread running, so it holds up every collection for
as long as it runs, and may be passed pointers into the Avin heap — an array’s elements — directly.
Callbacks
C calls back through a function pointer with a void * beside it. A binding’s parameter of
function-pointer type takes an Avin function, and the void * marked userdata, in the binding’s
prototype and in the function pointer’s own, carries it:
@c(
"mlt_event mlt_events_listen(mlt_properties self, userdata void *data, const char *id, void (*listener)(mlt_properties owner, userdata void *data, mlt_event_data event))",
keeps: "listener"
)
on(event: string, @threaded listener: (Properties, EventData) -> unit)
-
The Avin function’s parameters are the C function’s, without the
userdata, in order, each crossing out of C as a result does: a pointer to a handle’s type is a handle C lends, made throughretain, a string copied and checked, a value no Avin type holds stopping the program where the binding was called; and the function’s answer crosses into C as a parameter does: a scalar, a truth value or an enum mirror, andunitexactly where C’s function answersvoid(proposed). A string or a handle is never a callback’s answer: it would have to outlive the call, with nothing to free it. A binding takes one function peruserdata, which the function pointer’s ownuserdatanames (listener‘sdataabove), and a function pointer with nouserdatabeside it is refused: there is nowhere to find the closure. One C allows null is markednulland passed null instead. libc’sqsortandbsearchare such functions; a binding reaches them through a C function that passes auserdataof its own, asqsort_rdoes. -
Memory C lends a callback is a view (proposed). In a function pointer’s prototype, a byte pointer with a
length(p)parameter beside it crosses as aByteViewwhen it isconstand aMutByteViewwhen it is not, the length filled from C’s and not an Avin parameter, and the view is closed when the callback returns. That is Cairo’s PNG stream, written (cairo_write_func_t) and read (cairo_read_func_t) through a closure. A function-pointer typedef is written out in the binding’s prototype, where the marker words go; clang finds the two the same type:@c( "cairo_status_t cairo_surface_write_to_png_stream(cairo_surface_t *self, cairo_status_t (*write)(userdata void *closure, const unsigned char *data, length(data) unsigned int length), userdata void *closure)" ) private writePngStream(write: (ByteView) -> Status) -> Result[unit, Status] toPng(surface: Surface) -> Result[Array[byte], CairoError] = val out = Buffer[byte]() collect(chunk: ByteView) -> Status = out.appendAll(chunk.copy()) Status.Success surface.writePngStream(collect).mapErr(CairoError.from)? Ok(out.toArray())The length may come before its pointer and be of any integer type; a function may be lent several views; and null crosses by the rules of views,
Nonefor anOption[ByteView], an empty view for a length of zero, and otherwise a stop where the binding was called (C lent the function given to `writePngStream` null). A view lent a callback has no lender: it belongs to the code the callback runs in, so a thread the callback starts cannot read it (the `ByteView` lent to the function given to `writePngStream` belongs to another thread), and a view kept past the call stops the program at its use (proposed):avin: trap: the `ByteView` lent to the function given to `writePngStream` was closed when it returned at main.avin:14:13A callback answers no view, and the C unit checks each lent pointer points at bytes one byte wide.
-
The compiler makes one trampoline per parameter taking a function, a function with C’s convention whose address is passed for the pointer (proposed): two bindings of one C type may cross it as different Avin types. It finds the closure through the
userdata, which points at the runtime’s record of it (the record Sysl callbacks use,callback_pin), enters the runtime as a Sysl callback does (callback_enter), converts the arguments, calls the function, converts its answer and leaves. A callback with a struct by value among its parameters has a C trampoline in the glue that copies the struct out and calls the compiler’s. -
A callback C calls only during the binding is released when the binding returns. A callback C keeps is bound with
keeps:naming its parameter: the record is held by the receiver (or the handle the binding makes), so the closure lives as long as that handle. When the handle is released, its class’sforget:expression is run for each callback it holds, withuserdatathe record’s address, beforerelease— MLT’smlt_events_disconnect— so a C object something else keeps alive cannot call into a freed record; aforget:that is a C function’s name alone is calledname(self, userdata). A handle class that keeps callbacks and declares noforgetis refused, as is a binding whosekeeps:names a function with no handle to keep it, and aconsumes:naming a function. The record roots the function until then, so a kept function that captures its own holder keeps both untilclose()(proposed). -
Any C call may run a callback C keeps, so in a program that passes C a function every call of a C library function is one during which the collector may run.
-
A callback belongs to the code that gave it, and a call from any other thread stops the program, as for a Sysl callback. A parameter marked
@threadedtakes a function any thread may call, checked by its captures as a Sysl@threadedparameter is. A thread C started — MLT’s consumer renders on one and firesconsumer-frame-showthere — is attached to the runtime for the call and detached after, so it may allocate, and a collection waits for it as for any running thread. A binding with a@threadedparameter isblocking. -
C cannot say whether it calls from another thread, as Sysl’s
&sync Fndoes. A binding that leaves@threadedoff a function C calls from its own thread is caught at run time, by the owner check, at the first such call. -
A trap inside a callback stops the program, reported at its own place, however deep in C.
What is refused
| Refused | Instead |
|---|---|
A variadic function (...) | A fixed-arity function the library offers, or a C wrapper the package carries (proposed) |
void * other than a callback’s userdata or a parameter taking an array or a ByteBlock (memory of no type) | A handle on a typed pointer |
| A pointer type in Avin code | Handles, arrays, out parameters and views |
| A function pointer C answers | Bind the C functions it would point at |
long double, _Complex, vector types, va_list | — |
| A binding with no header to check it against | Name the header in c-libraries |
Writing through a ByteView, or a writable binding of a const pointer | A MutByteView from a writable binding, an array C fills, or a ByteBlock |
An array of mirrors to a pointer that is not const | An out array C allocates (array:), or a binding per element |
An array of strings, handles, bool, or integers narrower than int; an Array[int] or Array[long] to unsigned elements | A binding per element, or a buffer |
An array whose length no parameter carries, or one passed inout | Mark the length length(data) |
An indexed field accessor with no bound: | Name the C expression that bounds the index |
keeps: naming an array parameter, whose C copy lives for the call (proposed) | A ByteBlock, which is never copied |
kept: on a class some binding makes without keeping one handle of the named class | Keep it in every binding that makes the class |
Soundness
Avin has no pointer type and no unsafe block. Every pointer lives inside a binding’s
conversions, and safe Avin code sees only strings, arrays, handles, views, byte blocks and mirrors, each of which
is bounds-checked, owner-checked and closed-checked. The binding declarations are the trusted
surface, and the whole of it: what a reviewer reads to trust a library is the lines that begin
@c(, and the C glue they generate (proposed).
What the compiler checks of that surface is what it can: the prototype against the header, by clang;
the Avin types against the prototype; every integer at run time; every typedef’s kind and width and
every mirror’s layout on the target built for. What it takes on trust is what no header says: that a
result is owned or borrowed, that a function keeps or consumes a pointer, that a buffer’s
length or bound: is right, that C calls a function only from the thread a missing @threaded
implies, that forget stops the callbacks, that attach:‘s destroy is called only once C has
finished with what it keeps, that a holder’s release does not use a kept object held as the Avin
object (a handle with no retain that no kept: names, a ByteBlock), which the collector may free
first, that a value a handle holds: is its own to use in its release (a descriptor duped for it,
not one another object closes), that what a closed kept: handle freed with it is not touched, and that C
reads no more of a ByteBlock than the library checked. A wrong borrowed or length is a binding bug of the kind a wrong
extern is in C.
An example: two clips rendered with MLT
The bindings, in the mlt package’s own module (abridged to what the program uses):
module mlt
import avin.threads
import avin.time
data MltError
UnknownService(kind: string, name: string)
InvalidProfile(name: string)
Failed(call: string, code: int)
@c(type: "mlt_profile", release: "mlt_profile_close")
class Profile
@c(field: "width")
width() -> int
@c("mlt_profile mlt_profile_init(const char *name)")
private profileInit(name: string) -> Option[Profile]
profile(name: string) -> Result[Profile, MltError] =
profileInit(name).toRight(InvalidProfile(name))
@c(type: "mlt_properties", release: "mlt_properties_close", retain: "mlt_properties_inc_ref")
class Properties
@c(value: "mlt_event_data")
class EventData
@c(
type: "mlt_producer",
release: "mlt_producer_close",
retain: "mlt_properties_inc_ref(mlt_producer_properties(self))",
as: ["mlt_service = mlt_producer_service(self)"]
)
class Producer
@c(
"mlt_producer mlt_factory_producer(mlt_profile profile, const char *service, const char *resource)",
keeps: "profile"
)
private factoryProducer(profile: Profile, service: Option[string], resource: string) -> Option[Producer]
producer(profile: Profile, resource: string) -> Result[Producer, MltError] =
factoryProducer(profile, None, resource).toRight(UnknownService("producer", resource))
@c(
type: "mlt_playlist",
release: "mlt_playlist_close",
retain: "mlt_properties_inc_ref(mlt_playlist_properties(self))",
as: ["mlt_service = mlt_playlist_service(self)"]
)
class Playlist
@c("int mlt_playlist_append_io(mlt_playlist self, mlt_producer producer, int in, int out)")
private appendIoRaw(clip: Producer, from: int, to: int) -> Result[unit, int]
appendIo(clip: Producer, from: int, to: int) -> Result[unit, MltError] =
appendIoRaw(clip, from, to).mapErr(code -> Failed("mlt_playlist_append_io", code))
@c("mlt_playlist mlt_playlist_new(mlt_profile profile)", keeps: "profile")
private playlistNew(profile: Profile) -> Option[Playlist]
playlist(profile: Profile) -> Result[Playlist, MltError] =
playlistNew(profile).toRight(Failed("mlt_playlist_new", 0))
@c(
type: "mlt_consumer",
release: "mlt_consumer_close",
retain: "mlt_properties_inc_ref(mlt_consumer_properties(self))",
as: ["mlt_properties = mlt_consumer_properties(self)"],
forget: "mlt_events_disconnect(mlt_consumer_properties(self), userdata)"
)
class Consumer
@c("int mlt_properties_set(mlt_properties self, const char *name, const char *value)")
private setRaw(name: string, value: string) -> Result[unit, int]
@c("int mlt_properties_set_int(mlt_properties self, const char *name, int value)")
private setIntRaw(name: string, value: int) -> Result[unit, int]
@c(
"mlt_event mlt_events_listen(mlt_properties self, userdata void *data, const char *id, void (*listener)(mlt_properties owner, userdata void *data, mlt_event_data event))",
keeps: "listener"
)
on(event: string, @threaded listener: (Properties, EventData) -> unit)
@c("int mlt_consumer_connect(mlt_consumer self, mlt_service producer)", keeps: "source")
private connectRaw(source: Playlist) -> Result[unit, int]
@c("int mlt_consumer_start(mlt_consumer self)")
private startRaw() -> Result[unit, int]
@c("int mlt_consumer_is_stopped(mlt_consumer self)")
private isStoppedRaw() -> int
@c("int mlt_consumer_stop(mlt_consumer self)", blocking)
private stopRaw() -> Result[unit, int]
set(name: string, value: string) -> Result[unit, MltError] =
setRaw(name, value).mapErr(code -> Failed("mlt_properties_set", code))
setInt(name: string, value: int) -> Result[unit, MltError] =
setIntRaw(name, value).mapErr(code -> Failed("mlt_properties_set_int", code))
connect(source: Playlist) -> Result[unit, MltError] =
connectRaw(source).mapErr(code -> Failed("mlt_consumer_connect", code))
run() -> Result[unit, MltError] =
startRaw().mapErr(code -> Failed("mlt_consumer_start", code))?
while isStoppedRaw() == 0 do threads.sleep(time.millis(10))
stopRaw().mapErr(code -> Failed("mlt_consumer_stop", code))
@c(
"mlt_consumer mlt_factory_consumer(mlt_profile profile, const char *service, const char *input)",
keeps: "profile"
)
private factoryConsumer(profile: Profile, service: string, input: string) -> Option[Consumer]
consumer(profile: Profile, service: string, target: string) -> Result[Consumer, MltError] =
factoryConsumer(profile, service, target).toRight(UnknownService("consumer", service))
The program: two coloured clips, one second each, rendered to an MP4, counting the frames the consumer shows from its render thread.
import mlt.{profile, playlist, producer, consumer, MltError}
import avin.threads.Atomic
renderTitle(file: string) -> Result[int, MltError] =
val prof = profile("atsc_720p_25")?
val show = playlist(prof)?
show.appendIo(producer(prof, "color:#202020")?, 0, 24)?
show.appendIo(producer(prof, "color:#c04000")?, 0, 24)?
val out = consumer(prof, "avformat", file)?
val frames = Atomic(0)
out.set("vcodec", "mpeg4")?
out.setInt("an", 1)?
out.on("consumer-frame-show", (_, _) -> frames.add(1))
out.connect(show)?
out.run()?
Ok(frames.load())
What each piece of the chapter does here: profile answers None for a null mlt_profile_init;
the producers and the playlist keep the profile, since MLT keeps only its pointer; appendIo lends
each producer, and MLT takes its own reference, so the producers made inline are collected without
leaving the playlist; the listener is @threaded, captures only a val holding an Atomic, and is
called on MLT’s render thread, attached for each call; the consumer keeps it until it is released,
and forget disconnects it first; run waits by polling, each sleep safe for the collector, and
stop, which joins the render thread, is blocking.
An example: a glyph from FreeType, and the same face drawn by Cairo
The freetype package binds FreeType 2, with the manifest above; abridged to what the
program uses:
module freetype
data FreeTypeError
Failed(call: string, code: int)
@c(enum: "FT_Render_Mode", prefix: "FT_RENDER_MODE_")
data RenderMode
Normal
Light
Mono
Lcd
LcdV
@c(const: "FT_LOAD_DEFAULT")
val loadDefault: int
@c(type: "FT_Library", release: "FT_Done_Library", retain: "FT_Reference_Library")
class Library
@c("FT_Error FT_Init_FreeType(out FT_Library *library)")
private initRaw() -> Result[Library, int]
init() -> Result[Library, FreeTypeError] = initRaw().mapErr(code -> Failed("FT_Init_FreeType", code))
@c("FT_Error FT_New_Face(FT_Library library, const char *path, FT_Long index, out FT_Face *face)", keeps: "library")
private newFaceRaw(library: Library, path: string, index: long) -> Result[Face, int]
@c(
"FT_Error FT_New_Memory_Face(FT_Library library, const FT_Byte *base, length(base) FT_Long size, FT_Long index, out FT_Face *face)",
keeps: ["library", "base"]
)
private memoryFaceRaw(library: Library, base: ByteBlock, index: long) -> Result[Face, int]
openFace(library: Library, path: string) -> Result[Face, FreeTypeError] =
newFaceRaw(library, path, 0).mapErr(code -> Failed("FT_New_Face", code))
data Glyph
Glyph(width: int, rows: int, left: int, top: int, advance: real, pixels: Array[byte])
@c(struct: "FT_BBox")
data BBox(@c("xMin") xMin: long, @c("yMin") yMin: long, @c("xMax") xMax: long, @c("yMax") yMax: long)
@c(struct: "FT_Size_Metrics")
data SizeMetrics(
xPpem: int,
yPpem: int,
xScale: long,
yScale: long,
ascender: long,
descender: long,
height: long,
maxAdvance: long
)
@c(type: "FT_Face", release: "FT_Done_Face", retain: "FT_Reference_Face", as: ["FT_GlyphSlot = self->glyph"])
class Face
@c(field: "family_name")
familyName() -> Option[string]
@c(field: "num_glyphs")
glyphCount() -> long
@c(field: "bbox")
boundingBox() -> BBox
@c(field: "size->metrics")
sizeMetrics() -> SizeMetrics
@c("FT_Error FT_Set_Pixel_Sizes(FT_Face self, FT_UInt width, FT_UInt height)")
private setPixelSizesRaw(width: int, height: int) -> Result[unit, int]
@c("FT_Error FT_Load_Char(FT_Face self, FT_ULong code, FT_Int32 flags)")
private loadCharRaw(code: long, flags: int) -> Result[unit, int]
@c("FT_Error FT_Render_Glyph(FT_GlyphSlot self, FT_Render_Mode mode)")
private renderRaw(mode: RenderMode) -> Result[unit, int]
@c(field: "glyph->bitmap.width")
private bitmapWidth() -> int
@c(field: "glyph->bitmap.rows")
private bitmapRows() -> int
@c(field: "glyph->bitmap.pitch")
private bitmapPitch() -> int
@c(field: "glyph->bitmap_left")
private bitmapLeft() -> int
@c(field: "glyph->bitmap_top")
private bitmapTop() -> int
@c(field: "glyph->advance.x")
private advanceX() -> long
@c(
field: "glyph->bitmap.buffer",
view,
length: "(self->glyph->bitmap.pitch < 0 ? -self->glyph->bitmap.pitch : self->glyph->bitmap.pitch) * self->glyph->bitmap.rows"
)
private bitmapRaw() -> Option[ByteView]
setPixelSizes(width: int, height: int) -> Result[unit, FreeTypeError] =
setPixelSizesRaw(width, height).mapErr(code -> Failed("FT_Set_Pixel_Sizes", code))
render(c: char, mode: RenderMode = RenderMode.Normal) -> Result[Glyph, FreeTypeError] =
loadCharRaw(long(int(c)), loadDefault).mapErr(code -> Failed("FT_Load_Char", code))?
renderRaw(mode).mapErr(code -> Failed("FT_Render_Glyph", code))?
val (width, rows, pitch) = (bitmapWidth(), bitmapRows(), bitmapPitch())
val (left, top, advance) = (bitmapLeft(), bitmapTop(), real(advanceX()) / 64.0)
val stride = if pitch < 0 then -pitch else pitch
val pixels = Buffer[byte]()
bitmapRaw() match
Some(bits) ->
for r in 0 ..< rows
val row = if pitch > 0 then r else rows - 1 - r
pixels.appendAll(bits.slice(row * stride, row * stride + width))
None -> ()
Ok(Glyph(width, rows, left, top, advance, pixels.toArray()))
What each piece does here: a Face holds a C reference to its Library, so the two are given back
in FreeType’s order whichever the collector finalizes first, each reference by FT_Done_Library,
which frees the library only with its last; a face’s box and its size’s metrics are read whole as
struct mirrors, and the family name, an FT_String *, a typedef of char, is a string; a face made
over memory keeps the ByteBlock FreeType reads lazily for the face’s whole life, which an array,
copied for the call, could not be (FT_Done_Face reads none of it, so the block may be freed first). The glyph slot is
the face’s own, reached through field expressions and passed to FT_Render_Glyph through as:,
since it has no reference count of its own to be a handle by. Its scalar fields are read before the
bitmap is lent, because each read is a use of the face and would close the view; the bitmap is copied
row by row into immutable data, top row first whatever the sign of pitch, and the advance, in 26.6
fixed point, is divided by 64. A load or render that fails answers the library’s error; the glyph’s
pixels are never read from a failed load.
The cairo package depends on freetype and makes a Cairo font face from a FreeType one. Cairo
keeps the FT_Face without referencing it, and the face must outlive every Cairo font face made from
it — Cairo’s own documentation asks for the face to be given back from the font face’s user-data
destructor. Contexts and scaled fonts reference the font face, so it can outlive the Avin FontFace,
and keeps: on the handle alone would let the Face be collected while Cairo still draws with it.
The FontFace class ties what it keeps to the C object instead, with
attach::
module cairo
import freetype.Face
@c(
type: "cairo_font_face_t *",
release: "cairo_font_face_destroy",
retain: "cairo_font_face_reference",
attach: "cairo_font_face_set_user_data(self, key, data, destroy)",
key: "cairo_user_data_key_t"
)
class FontFace
@c("cairo_status_t cairo_font_face_status(cairo_font_face_t *self)")
status() -> Result[unit, Status]
@c("cairo_font_face_t *cairo_ft_font_face_create_for_ft_face(FT_Face face, int load_flags)", keeps: "face")
private ftFontFace(face: Face, loadFlags: int) -> FontFace
fontFace(face: Face) -> Result[FontFace, CairoError] =
val made = ftFontFace(face, 0)
made.status().mapErr(CairoError.from)?
Ok(made)
The manifest adds the cairo-ft module (pkg-config = "cairo-ft", headers = ["<cairo-ft.h>"]),
and the binding is checked with freetype‘s headers included first. The Face goes into the font
face’s attached record, a root of the collector, and Cairo’s call of destroy when the last
reference to the font face goes — from a context, a scaled font or the Avin handle, in any order —
unpins it; the Face is then collected like any other, and its finalizer gives back the face, and
after it the face’s reference to its library. Cairo answers the font face it already has for an
FT_Face and flags it was given before, and attaching again replaces the record, calling destroy
for the old one, while the new record keeps the Face. A failure is latched on the font face, as
Cairo’s errors kept on the object are, and fontFace asks it at once.
Cairo uses the FT_Face itself: drawing text with the font face sets its size and loads glyphs
into its slot, so a glyph rendered through the Face after Cairo has drawn must be loaded again,
which render always does, and the two are used on one thread, the Face‘s owner check holding for
the Avin calls. cairo_ft_font_options_substitute takes a fontconfig pattern, and is left to a
fontconfig binding.
Relationship to Sysl bindings
The two kinds of binding sit side by side, and a program may use both. A library Sysl already binds
well is reached through Sysl; a C library is bound directly. The Sysl boundary’s rules are the C
boundary’s wherever both have the same question — integer conversions, Option, handles and their
owners, blocking, callbacks and @threaded — and differ where C has no Sysl signature to check
against: the header is checked instead, by clang, and what no header says is written in the binding.