LEVIATHAN vd52e79c4 · d52e79c486

Declarations

Foreign functions (@extern, @export)

Declare a C function with @extern and call it like any other function; which types cross to C and how, errors, variadic functions, exports and the build permission.

since 0.1.0-alpha.1linuxwindowswasm

Description

A program calls a C library by declaring the C function in Leviathan: an ordinary free function with an empty body, marked @extern with the library it comes from. A call then looks like any other call; each argument is converted to its C type for the call and the result is converted back. The attributes and helpers live in the ffi namespace of the standard library, which a file imports with uses ffi;.

Declaring and calling C functions

uses ffi;
use io::console;

@extern("c")
int strlen(string s);

@extern("c", "abs")
int32 cAbs(int32 n);

@extern("m")
float cos(float x);

void main() {
    console.writeln(strlen("hello"));
    console.writeln(cAbs(-7));
    console.writeln(cos(0.0));
}
main();
5
7
1.0e0

The first argument of @extern names the library. "c" and "m" are the C library and the maths library, which are always available. Any other name is the nickname of a [[native]] table in the package's trident.toml, which tells trident how to find and link the library. The second argument is the C symbol when it differs from the Leviathan name, as abs does above.

Calling C is a permission, not a default. A program that declares @extern or @export functions, or calls the parts of the ffi namespace that reach raw memory or load code (ffi::ptr, ffi::view, ffi::alloc, ffi::free, ffi::toString of a pointer, ffi::callback, ffi::provide, ffi::Library, Ptr.offset and Block.ptr), compiles only when it is allowed to: through trident, the declaring package must list its libraries in [[native]] tables, and a package that depends on one must opt in with native = true on that dependency. A single file compiled without trident needs the --native option; with a build plan the option is an error, because the plan carries the permission. The rest of the namespace (layouts, pack and unpack, nullPtr, errno, lastError, available, strerror, the Ptr queries and FfiException) is pure and needs no permission.

leviathan --native --run tool.lev

C sees only C types. Every parameter and the result of a foreign function must have one of the types in the table below; anything else (an Array, a Map, a class object, a union other than Ptr? and string?) is a compile error that names the parameter and suggests passing a Block or a Ptr instead.

Leviathan C notes
int int64_t also the spelling for long, size_t, uintptr_t and ssize_t on 64-bit systems
int32, int16, int8 int32_t, int16_t, int8_t C's int is int32
uint uint32_t
byte uint8_t C's unsigned char
float, float32 double, float float16 and float8 have no C type
bool uint8_t holding 0 or 1 C's _Bool
char uint32_t a Unicode scalar, not C's char (use int8 or byte)
Ptr void* Ptr? is a pointer that may be NULL: None is passed as NULL, and a NULL result arrives as None
string const char* borrowed for the call; string? passes None as NULL
Block void* the address of the block's bytes, borrowed for the call (parameters only)
a function type (A, B) => R R (*)(A, B) a callback (parameters only); see lang.ffi.callbacks
a @repr("C") struct the struct, by value see lang.ffi.repr
void (result only) void

Strings and buffers

A string argument is passed as a pointer to the string's bytes, which are followed by a zero byte (on the native backends a string of up to seven bytes is held inside its value, so C gets a copy made for the call). The pointer is valid only for the duration of the call: if the C function keeps it, pass ffi::cstring(s) instead, which is a Block holding a copy of the text and a zero byte, and keep that block alive while C uses it. A string result is copied into a new Leviathan string before the call returns to your code; the C buffer is never freed by the runtime. A C function that may return NULL where a string is expected should be declared to return Ptr?, and the text read with ffi::toString(p): a NULL string result throws RuntimeException (extern 'f' returned NULL for a string), as does C passing NULL for a string parameter of an @exported function (the body does not run; the exception is reported like an uncaught one and C gets the zero value).

A Block argument passes only the address of the block's bytes; the length is whatever integer parameter the C function takes beside it. A foreign function cannot return a Block, because the runtime cannot know who owns the memory: return a Ptr and read through ffi::view(p, len), which gives a block over the foreign bytes without copying them. Strings and blocks cross as bytes, with no conversion of the text's encoding.

Errors

C reports errors through return values and errno, and a binding decides what to do with them. With errno: true, the C errno (and on Windows GetLastError()) is saved immediately after each call, before anything else can change it; ffi::errno() and ffi::lastError() read the saved values, and ffi::strerror(e) gives C's description. Wrap the raw declaration in a function that turns a failure into an exception or an optional result:

Turning errno into an exception

uses ffi;
use ffi;
use io::console;

@extern("c", "chdir", errno: true)
int32 cChdir(string path);

void changeDirectory(string path) {
    if (cChdir(path) != 0)
        throw RuntimeException("chdir " + path + ": " + ffi::strerror(ffi::errno()));
}

void main() {
    try {
        changeDirectory("/no/such/directory");
    } catch (RuntimeException e) {
        console.writeln(e.message);
    }
}
main();
chdir /no/such/directory: No such file or directory

The machinery itself raises ffi::FfiException: for a library or symbol that cannot be found, a call to an optional library that was not available when the program was built, and the misuse cases of ffi::view, ffi::toString, callbacks and ffi::Library.

Variadic functions

A C function such as printf takes a variable number of arguments. A Leviathan declaration fixes one shape: variadic: k says that parameters from index k on are passed as C variadic arguments. For another shape, declare another function. Only int, int32, float, Ptr and string may sit in a variadic position: C promotes narrower types, so declare the promoted type instead (int32 rather than int16, float rather than float32).

Two shapes of snprintf

uses ffi;
use io::console;

@extern("c", "snprintf", variadic: 3)
int32 formatInt(Block buf, int size, string fmt, int value);

@extern("c", "snprintf", variadic: 3)
int32 formatText(Block buf, int size, string fmt, string value);

void main() {
    Block out = Block(32);
    int32 n = formatInt(out, 32, "%ld apples", 12);
    console.writeln(out.toString(0, n));
    n = formatText(out, 32, "hello, %s", "world");
    console.writeln(out.toString(0, n));
}
main();
12 apples
hello, world

Exporting functions to C

@export goes the other way: it makes a Leviathan function callable from C under a C symbol, for a program built as a library. The function needs a body, may not be generic or a method, and its signature follows the same table without callbacks and without Block parameters: C hands over a bare pointer with no length, so take a Ptr and a length and read the bytes through ffi::view(p, len). The symbol defaults to the function's name, must be unique among the program's exports (overloads of one name cannot all be exported under it), and may not begin with lv_ or lvrt_ or be leviathan_init, leviathan_shutdown or main, which belong to the runtime and the host. To Leviathan code an exported function is an ordinary function. The library itself is built with leviathan --build-native <out> --lib shared (or static) and its C header with --header <file>; the header's comment states the lifetime rules (leviathan_init before the first call on a thread, a returned const char* valid until the next call into the runtime on that thread, an uncaught exception reported on standard output — as every uncaught report is — with the C zero value returned). Each thread that calls leviathan_init has its own copy of the program's top-level variables, as the top-level code left them, until its leviathan_shutdown (see lang.threads for the values that stay shared); on Windows and wasm32 a library runs on one thread and has one copy. On a thread other than the first, leviathan_shutdown called while an export or a callback is running on that thread (from C code it reached) is a fatal abort. See lang.compiler-cli.

An exported function

uses ffi;
use io::console;

@export("lev_area")
int32 area(int32 w, int32 h) => w * h;

void main() {
    console.writeln(area(6, 7));
}

Libraries loaded at run time

A [[native]] table with dynamic = true is not linked: its library is loaded the first time one of its functions is called, from the path given with ffi::provide(name, path), else from the table's path, else from the system's search path. ffi::available(name) tells whether an optional library was found when the program was built, so a program can choose another path. ffi::Library::open(path) loads a library directly to look up raw addresses with sym(name); it never calls anything.

A plugin loaded at run time

uses ffi;
use ffi;
use io::console;

@extern("plugin", "plugin_version")
int32 pluginVersion();

void main() {
    ffi::provide("plugin", "/opt/example/libplugin.so");
    console.writeln(pluginVersion());

    ffi::Library lib = ffi::Library::open("/opt/example/libplugin.so");
    Ptr entry = lib.sym("plugin_version");
    console.writeln(entry.isNull());
    lib.close();
}

The package's manifest marks the library as loaded at run time:

[[native]]
name    = "plugin"
dynamic = true
path    = "plugins"

A C function can also be a static method, so a class groups the foreign functions it wraps; it is called as MathLib::Abs(...), or by its bare name inside the class:

A foreign function as a static method

uses ffi;
use io::console;

class MathLib {
    static int calls = 0;
    @extern(lib: "c", symbol: "abs") static int32 Abs(int32 x);
    static int32 Counted(int32 x) {
        calls += 1;
        return Abs(x);
    }
}

void main() {
    console.writeln(MathLib::Abs((-4).toInt32()));
    console.writeln(MathLib::Counted((-9).toInt32()));
    console.writeln(MathLib::calls);
}
main();
4
9
1

Rules

  1. @extern(lib, symbol, variadic, errno, slots) decorates a free function, at the top level or in a namespace, or a static method of a class or struct (lang.static-members), whose body is empty (;). A body is an error: extern functions have no body ('name'). An instance method, constructor, field or class cannot be @extern (@extern applies to free functions and static methods only ('name')); neither can a generic function.
  2. The attribute's fields may be given by position or by name. lib is required and may not be empty (name the library; use "c" for libc); symbol defaults to the function's name; variadic defaults to -1 (not variadic); errno defaults to false; slots (callbacks, see lang.ffi.callbacks) to 16. Attribute arguments must be literals.
  3. Each parameter and the result must have a type from the table above. Otherwise the error is 'T' is not marshalable in extern position <n> of 'name' (<hint>; see the 'Foreign functions' reference entry) (export position for an @export), where position 0 is the result and parameters count from 1, and the hint suggests what to declare instead. Block and function types are parameter-only, string? is parameter-only (declare Ptr? for a result that may be NULL), and void is result-only.
  4. Two declarations may bind the same C symbol with different Leviathan signatures, and several declarations may share a Leviathan name as overloads; each declaration is its own foreign function. Default parameter values work as for any function.
  5. variadic: k must lie between -1 and the number of parameters: variadic index <k> out of range for 'name'. A variadic position holding another marshalable type is 'T' is not allowed in a variadic position (declare the promoted type).
  6. @export(symbol) decorates a free function or a static method with a body that is not generic (a static method exports under its bare name unless symbol is given); its signature follows rule 3 without function types or Block parameters ('Block' is not allowed in export position <n> of 'name' (take a Ptr and a length, then ffi::view(p, len))). A symbol beginning with lv_ or lvrt_ is @export symbol '<symbol>' collides with the runtime namespace; leviathan_init, leviathan_shutdown and main are @export symbol '<symbol>' is reserved by the runtime; a symbol exported twice is @export symbol '<symbol>' is already exported by '<function>'. A function cannot be both @extern and @export.
  7. A module that declares an @extern or @export function compiles only with permission: through a build plan, module '<name>' uses FFI but its trident.toml has no [[native]] table; without one, FFI requires --native without a build plan. A use, in a module without the permission, of the gated runtime surface named above is refused at the use: module '<name>' uses FFI ('ffi::view') but its trident.toml has no [[native]] table / FFI ('ffi::view') requires --native without a build plan. A use is a call, or a reference to a gated function or member as a function value (var v = ffi::view;, Block::ptr, apply(ffi::alloc, 16), a bound b.ptr). The standard library's own uses are exempt, and the natives it builds the surface on are its own: a program cannot call them at all (lang.system-floor). --native together with a build plan is an error. Type checking alone (leviathan file.lev, --expand) needs no permission.
  8. comptime code may not call a foreign function: comptime code may not call foreign functions ('name'). A foreign function is not a value either: extern 'name' cannot be used as a value; wrap it in a lambda.
  9. Arguments are borrowed for the call. Nothing a C function receives is retained, released or freed by the runtime, and nothing C returns enters Leviathan's memory management: a string result is copied, a Ptr is a plain address.
  10. On the WebAssembly target a foreign function is an import of the host page, and only scalar and pointer types cross; a struct passed by value is a compile error there.
  11. The @extern attribute is ffi::extern. On the WebAssembly target the standard library also has a Dom::extern attribute; a file that imports both namespaces writes @ffi::extern(...).

Examples

ffi::FfiException is a RuntimeException, so code that handles runtime errors handles the foreign-call machinery's errors too:

Catching the machinery's errors

uses ffi;
use ffi;
use io::console;

void main() {
    try {
        throw ffi::FfiException("library 'plugin' was not available when this program was built");
    } catch (RuntimeException e) {
        console.writeln("caught: " + e.message);
    }
}
main();
caught: library 'plugin' was not available when this program was built

A binding for part of zlib, as it would appear in a package whose trident.toml has a [[native]] table named z:

A zlib binding

uses ffi;
use io::console;

namespace zlib {
    @extern("z")
    int compressBound(int sourceLen);

    @extern("z", "compress2")
    int32 compress2(Block dest, Ptr destLen, Block source, int sourceLen, int32 level);

    @extern("z", "uncompress")
    int32 uncompress(Block dest, Ptr destLen, Block source, int sourceLen);

    Block compress(Block data) {
        Block out = Block(compressBound(data.length()));
        Block outLen = Block(8);
        outLen.setInt64(0, out.length());
        int32 rc = compress2(out, outLen.ptr(), data, data.length(), 6);
        if (rc != 0) throw RuntimeException("compress2 failed: " + rc.toString());
        return out.slice(0, outLen.int64At(0));
    }

    Block decompress(Block packed, int originalLength) {
        Block out = Block(originalLength);
        Block outLen = Block(8);
        outLen.setInt64(0, originalLength);
        int32 rc = uncompress(out, outLen.ptr(), packed, packed.length());
        if (rc != 0) throw RuntimeException("uncompress failed: " + rc.toString());
        return out.slice(0, outLen.int64At(0));
    }
}

void main() {
    string text = "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc";
    Block original = Block::fromString(text);
    Block packed = zlib::compress(original);
    console.writeln(packed.length() < original.length());
    Block back = zlib::decompress(packed, original.length());
    console.writeln(back.toString(0, back.length()) == text);
}
main();
true
true

The manifest side of that package:

[[native]]
name = "z"
pkg  = "zlib"

Notes

  • The ffi namespace is part of the standard library on every target but is never imported implicitly; Ptr needs no import.
  • The C ABI is the only one: C++ name mangling and exceptions do not cross. Libraries written in other languages are reached through their C interfaces.
  • A program's foreign calls are checked against the table above when it is compiled, but C itself is not: a declaration whose types do not match the real C function is undefined behaviour, exactly as a wrong prototype is in C.

See also

  • C-layout structs (@repr C) — Give a value struct C's field layout so it can cross to C by value or be packed into bytes; ffi::sizeOf, alignOf and offsetOf read the layout.
  • Callbacks, threads and tasks in foreign calls — Pass a Leviathan function to C with ffi::callback; where foreign calls run, when a callback may await, and the marks @mayCallback, @shallow and @reentrant.
  • Ptr — the foreign address — The primitive that holds an address of C memory or code; it is never dereferenced, freed or kept alive by the runtime.
  • ffi — Calling C libraries, and describing C data, from Leviathan.
  • Block — A fixed-length, mutable buffer of bytes.
  • Attributes — inert, typed annotations — Declare an attribute with attribute Name { fields }, attach it with @Name(args), and let rules read it.
  • The leviathan command line — Every option of the leviathan compiler, grouped by what it does, with the exit statuses and how arguments reach your program.
  • The native floor — std::sys* — What the sys* functions in std are, why compile-time code cannot call them, and which two are public.