Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

FFI and host imports

Calque’s current FFI is a WebAssembly host-import FFI. A Calque extern declaration becomes a Wasm import; an embedding host must supply a function with the same module and import names. It is not a C ABI, plugin system, or callback framework.

Declare an import

(extern env add_one add-one! (Int -> Int))

(add-one! 41)
; 42 when the host supplies env.add_one

The declaration syntax is:

(extern module import local-name! Type)

Rules:

  • extern is top-level only.
  • A local external name must end in !.
  • External calls are treated as effectful by the compiler.
  • The declaration has a concrete type; it is not dynamically typed.

Zero-argument imports use unit as their argument:

(extern env clock_now_ms clock-now-ms! (() -> Int))

Supported declared shapes

Extern signatures use the familiar core type syntax:

Int
Dec
Bool
Char
()
[Char]
[Int]
{Int Int}
(Int -> Int)
([Char] [Char] -> ())

At the Wasm ABI boundary, scalar core values lower to i32. Vectors, tuples, and strings lower to an i32 pointer into Calque’s linear memory. Dec is a fixed-point i32, not an f64. Calque’s managed representation is internal to the runtime: a host returning a managed value must construct a valid Calque heap object, while managed values received from Calque are borrowed unless the host explicitly retains them using the runtime convention.

Built-in effect operations

The normal que runner supplies these operations through its WASI adapter. They have ordinary, statically checked Calque types; ! marks the operations that perform an external effect. println! is the standard-library convenience form of print! plus a newline, but has the same source-level type.

Files and directories

OperationTypePermissionMeaning
read![Char] -> [Char]readRead a complete text file.
list-dir![Char] -> [[Char]]readList directory-entry names.
read/chunks![Char] -> Int -> ([Char] -> Bool) -> BoolreadVisit successive text chunks.
read/lines![Char] -> ([Char] -> Bool) -> BoolreadVisit successive lines, without newline terminators.
write![Char] -> [Char] -> ()writeWrite text to a path.
mkdir![Char] -> ()writeCreate a directory path.
move![Char] -> [Char] -> ()writeRename or move a path.
delete![Char] -> ()deleteDelete a file or directory path.

Paths and text are both [Char], normally written as string literals:

(let config (read! "config.txt"))
(write! "copy.txt" config)
(let names (list-dir! "."))

Standard input and callbacks

OperationTypePermissionMeaning
stdin!() -> [Char]stdinRead all standard input as text.
stdin/chunks!Int -> ([Char] -> Bool) -> BoolstdinVisit standard input in chunks.

All three callback operations—read/chunks!, read/lines!, and stdin/chunks!—share one control convention:

  • The callback receives a [Char] chunk or line.
  • Return false to continue.
  • Return true to stop early.
  • The operation itself returns true when it stopped early and false when it reached end of input.

Chunk size must be positive. For example, print at most ten lines:

(&mut seen 0)
(let stopped?
  (read/lines! "input.txt"
    (lambda (line)
      (&alter! seen (+ (&get seen) 1))
      (println! line)
      (>= (&get seen) 10))))

The callback API avoids constructing a vector of all lines or chunks. The current external WASI adapter reads its input text before it partitions it for callbacks; an embedding or native-C host may stream at the host level. Do not assume the callback spelling alone guarantees bounded host-side input memory on every target.

Terminal and clock

OperationTypePermissionMeaning
print![Char] -> ()printPrint text without adding a newline.
println![Char] -> ()printPrint text followed by a newline.
clear!() -> ()printRequest a terminal clear.
sleep!Int -> ()clockSleep for a non-negative number of milliseconds.
time!() -> IntclockCurrent wall-clock time in whole Unix seconds.
random!() -> IntclockGet one host-provided random Int.

println! accepts text, not an arbitrary value. Convert an integer explicitly:

(println! (Integer->String (time!)))
(sleep! 250)

random! is effectful host randomness. The library’s random, random/int, random., and random/dec are separate deterministic seed-to-next-state functions for reproducible computations.

Serialization

OperationTypePermissionMeaning
serializeT -> [Char]noneConvert a statically known supported Calque value to text.
deserialize[Char] -> TnoneDecode text as the statically expected type.

deserialize cannot infer a target type from characters alone. State the expected result with sig before the binding:

(let saved (serialize {42 "Ada"}))

(sig restored {Int [Char]})
(let restored (deserialize saved))
; {42 "Ada"}

Enums serialize by their declared variant name and are checked against the expected enum on decode. See Enum-keyed table round trip for a table example.

Compatibility and persistence

serialize is designed for Calque-to-Calque data within a compatible compiler release. It is not yet a versioned, stable public storage or network format. Do not make a database schema, long-lived cache, or external API depend on its exact textual spelling without pinning the Calque compiler version and testing the decoder during upgrades.

For persistent application data today, store an explicit version field next to the serialized value and own the migration in source:

(let saved {1 (serialize value)})
; On read, inspect the version before choosing the expected decoder and migration.

Serialization needs a concrete, fully known value type. It cannot serialize an unresolved generic or a function/closure, and deserialize needs an expected type through its binding, sig, or surrounding context. Malformed input or a type mismatch is a decoding failure, not an implicit conversion.

Run a program using an operation only after granting the matching capability:

que program.que --allow read write print

--allow all grants every group. See Effects and permissions for the short permission overview.

Custom hosts

The normal que runner delegates to an external WASI runtime. It can run the built-in operations through Calque’s WASI adapter, but it does not load arbitrary user host modules from command-line configuration. A program containing a custom extern therefore needs an embedding/application that instantiates the generated Wasm module and supplies the declared import.

For example, a Rust Wasmtime host conceptually registers:

#![allow(unused)]
fn main() {
linker.func_wrap("env", "add_one", |x: i32| -> i32 { x + 1 })?;
}

before instantiating the compiled module. The exact initialization needed for Calque-managed values belongs to that host integration, not the source program.

Current limits

The current supported model deliberately excludes:

  • callbacks from host code into Calque closures
  • an async/await runtime or automatic future bridging
  • a stable public C ABI for Calque objects
  • a generic CLI plugin loader for arbitrary imports
  • automatic marshalling of arbitrary managed data

The optional wasm2c/native-C runner still uses this host-import model: wasm2c translates the guest code, while the adapter supplies the imports. It does not turn Calque’s internal memory representation into a general C interface.