(rontolisp) docs

WIT interfaces and worlds

A program of the subset calls a WIT interface through a Java interface annotated @WitImport, and implements a WIT world through a class annotated @WitExport (Exporting a WIT world). The annotation comes from rontolisp-java-api, a library of plain Java with no dependency, so the same source compiles with javac and runs on a JDK. The interface's implementation is a service provider: the program's own under a JDK, on the interpreter and on the JVM, the host's in a WASM module or component. It is the Java side of rontolisp:wit-import.

import java.util.List;
import java.util.Optional;

import am.ik.rontolisp.wit.WitImport;

@WitImport(value = "wasi:keyvalue/store", wit = "wit/keyvalue.wit")
public interface Store {

    Bucket open(String identifier);

    interface Bucket extends AutoCloseable {

        Optional<byte[]> get(String key);

        void set(String key, byte[] value);

        KeyResponse listKeys(Optional<Long> cursor);

        @Override
        void close();
    }

    record KeyResponse(List<String> keys, Optional<Long> cursor) {
    }

    sealed interface Error {

        record NoSuchStore() implements Error {
        }

        record AccessDenied() implements Error {
        }

        record Other(String value) implements Error {
        }
    }
}
Store store = ServiceLoader.load(Store.class).findFirst().orElseThrow();
try (Store.Bucket bucket = store.open("")) {
    bucket.set("visits", "41".getBytes(StandardCharsets.UTF_8));
}

The library goes on the program's source path, and on the class path of a JDK:

API="--java-source-path rontolisp-java-api/src/main/java"
rontolisp PageHits.java $API                                     # interpreter
rontolisp PageHits.java $API -o PageHits.class && java PageHits  # JVM
rontolisp PageHits.java $API -o kv.wasm --component && wasmtime run -S keyvalue=y kv.wasm
java -cp rontolisp-java-api.jar PageHits.java                    # a JDK

examples/wit/keyvalue/PageHits.java is a counter over wasi:keyvalue/store that prints the same report in all four, the component's from wasmtime's own store.

The interface

value is the WIT interface: its id, or the id without the version, which the WIT read gives. wit is the WIT: a .wit file, or the directory of a package as published (its .wit files and deps/), named as Class.getResource names a resource: relative to the interface's package, or from the top after a leading /. It is looked for where the interface's class loader looks: the program's source tree, then each root of the source path in order, a directory or a jar (--java-source-dep, the Maven plugin's target/classes first). So a WIT beside the file declaring the interface is found, and so is one in src/main/resources under the package's directory:

src/main/java/com/example/kv/Store.java          @WitImport(..., wit = "wit/keyvalue.wit")
src/main/resources/com/example/kv/wit/keyvalue.wit

A .. is resolved within the root; one that climbs above its top is refused. A program read from no file (-e, a session) looks in the working directory before the source path.

The interface declares the functions the program calls, no more, and each is checked against the WIT when the program is compiled, on every target: a function the WIT does not have, a parameter or a result of another type, is refused at the declaration with the WIT member's line:

Store.java:12:21: listKeys (bucket-list-keys of wasi:keyvalue/store@0.2.0-draft2,
wit/keyvalue.wit:20): its parameter cursor is option<string>, which is Optional<String>
in Java, not Optional<Long>

So an interface declaring what two versions of a WIT interface share is checked against either, whichever wit names, and the version of the import is that WIT's.

The names follow the WIT's, in Java's case:

WITJava
a function list-keysthe method listKeys
a resource bucketthe member interface Bucket, its methods the resource's
a resource's releaseclose() of that interface
a resource's constructor, its static function createthe methods bucketNew, bucketCreate of the annotated interface
a record, a variant, an enum or flags key-responsethe member type KeyResponse
a case or a label no-such-storethe record NoSuchStore, the enum constant NO_SUCH_STORE

A name that is a Java keyword ends in _ (default_).

The implementation

ServiceLoader.load(Store.class) finds the interface's implementation:

  • under a JDK, on the interpreter and on the JVM, the program's own: a public class with a public constructor of no parameter, named in META-INF/services/Store (the interface's binary name) of the source tree, as for any service;
  • in a module or component rontolisp compiles, the host's alone: the module imports the WIT interface, and a provider the program names is not consulted.

So the program says nothing about where it runs: a store of its own answers where it is developed, the host where it is deployed. On a WASM target the module imports the functions the program calls and no other.

A --no-wasi module imports the interface the way a component does, through the canonical ABI, and its host is the JavaScript glue --emit-js-glue writes (WIT interfaces beyond the flat set). The glue answers wasi:keyvalue/store@0.2.0-draft2 over Workers KV itself, so a program keeping its state there is a Cloudflare Worker as it stands; a call the program makes while the module loads (from main) is refused, since such a host may answer with a promise.

A host's own interface is imported the same way. jdbc-spin-postgres declares Spin's spin:postgres/postgres (its Postgres.java) and is a JDBC driver over it: Spin opens the connections to PostgreSQL, pools them and, with sslmode=require, speaks TLS (JDBC, under Spin). Nothing implements the interface on a JDK, where the driver leaves the URL to another one.

The types

WITJava
boolboolean
s8, u8byte
s16, u16short
s32, u32int
s64, u64long
f32, f64float, double
charint, the code point
stringString
list<u8>byte[]
list<T>List<T>
option<T>Optional<T>
tuple<A, B>a record of the program's with those components
recorda member record, a component a field
varianta member sealed interface permitting a record for each case (the payload its one component)
enuma member enum
flagsa Set of a member enum
a resource, own<R>, borrow<R>the member interface
result<T, E>what the method answers, the error arm a WitException

An unsigned integer is held in the Java type of its width, its bits as Java holds them: the u8 200 is the byte -56 (Byte.toUnsignedInt gives 200 back).

result<T, E> is what a method answers: its ok arm is the method's value (void for none), and its error arm is thrown as an am.ik.rontolisp.wit.WitException, whose error() is the error of its Java type (a case record, an enum constant, a string; null for none). A provider of the program's throws it for its own error arm.

try {
    store.open("not-a-store-anyone-has");
}
catch (WitException e) {
    if (e.error() instanceof Store.Error.NoSuchStore) {
        System.out.println("no such store");
    }
}

A resource is released by close(): the handle goes back to the host, and the store stays. A closed resource throws IllegalStateException, and a second close() does nothing. An own handle given to a function passes to it, and the object is closed.

Exporting a WIT world

A class annotated @WitExport implements a WIT world: each function the world exports is a static method of the class, named in camel case, and each interface the world exports is a static member class named after the interface in upper camel case (export docs:adder/add; is Add), whose static methods are the interface's functions. It is the Java side of rontolisp:wit-export.

package example:vowels;

world counter {
  export vowel-count: func(text: string) -> s32;
}
import am.ik.rontolisp.wit.WitExport;

@WitExport(value = "counter", wit = "wit/vowels.wit")
public class Counter {

    public static int vowelCount(String text) {
        int n = 0;
        for (int i = 0; i < text.length(); i++) {
            if ("aeiouAEIOU".indexOf(text.charAt(i)) >= 0) {
                n++;
            }
        }
        return n;
    }
}

value is the world's name, and wit the WIT, found as an interface's is (The interface).

A program whose entry class has no main starts at the classes @WitExport marks in its source tree, which join the program. Its entry points are their worlds' exports, and it compiles to a reactor component: the component exports the worlds and no wasi:cli/run, and the first call of an export runs the program's static initialization. A host, or a component composed with it, calls the exports:

API="--java-source-path rontolisp-java-api/src/main/java"
rontolisp Counter.java $API -o counter.wasm --component
wasmtime run --invoke 'vowel-count("hello world")' counter.wasm   # 3

examples/java/rust-calls-java/ composes it with a Rust component that calls vowel-count, and builds it with the Maven plugin, whose wasm goal compiles the classes @WitExport marks when no main class is set.

Under a JDK, on the interpreter and on the JVM the annotation does nothing: vowelCount is an ordinary static method, which a program or a test calls. A program with no main is refused there, and on a module and --native: a world is exported by a component. A program with a main is a command, whose @WitExport classes are exported nowhere. A program with neither is a module's reactor: A reactor of public static methods.

Each method is checked against its export when the program is compiled, on every target, whether the program has a main or not: a missing method, one that is not static, a parameter or a result of another type is refused at the declaration with the WIT line:

Counter.java:6:24: vowelCount (vowel-count of world counter, wit/vowels.wit:4): its result
is s32, which is int in Java, not long

The types are those of the table above that a world's export carries: bool, the integers, f64 and string. Any other is refused at its WIT line, as rontolisp:wit-export refuses it. An unsigned integer is the Java type of its width holding its bits both ways: a u32 of 4294967295 is the int -1, and the int -1 an export answers for a u32 is 4294967295.

Limitations

  • A WASM module takes the types rontolisp:wit-import takes there: a Preview 1 core module the flat set (the integers up to 32 bits, the floats, bool, string, list<u8>, handles), a component and a --no-wasi module everything but flags. A member of any other type is refused at its WIT line where the program calls it, as wit-import refuses it.
  • A u64 past Long.MAX_VALUE crosses no WASM boundary.
  • A native executable (--native) runs a Preview 1 module whose runner provides no WIT interface, so a program calling one does not start there.
  • Refused at the declaration: a stream, a future, an async func; a result anywhere but a method's answer; an option of a bool, a list, flags or an option, whose none the boundary cannot tell apart; a resource of another interface; a tuple in an error arm.
  • A world's export takes the types rontolisp:wit-export takes; an async func export and two exports of one label (a function of the world and an interface's, or two interfaces') are refused.
  • An exception an export leaves uncaught traps: the host sees the trap, with no line of its own.