Skip to content

Latest commit

 

History

History
220 lines (176 loc) · 8.75 KB

EFFECTS.md

File metadata and controls

220 lines (176 loc) · 8.75 KB

Effects in Bend

An AI wrote this text from the runtime's source (bend2/comp.ts and bend2/effs/). A human will revise it later. Report anything wrong on GitHub.

An effect def

An effect is a def of type IO(R) whose body is two imports:

def Clock.now() -> IO(U32):
  import "./clock.c"
  import "./clock.js"

Each file registers the effect under its def with io_eff(CID(Clock.now), ..). The .c file serves bend x.bend -o x; the .js file serves bend x.bend -o x.js and bend x.bend. Every effect in Base is built this way: bend2/effs/*.c and *.js are the reference.

The C side

The compiler splices your .c into the program's C source after the runtime, so every runtime symbol is in scope. Define the effect and register it in a constructor:

Term clock_now_run(Env e, Term* f, IoWork* w);

static void __attribute__((constructor)) clock_now_use(void) {
  io_eff(CID(Clock.now), clock_now_run);
}

CID(Name) is the C id of a constructor or of an effect def: the compiler replaces it with the name's own id, reading Name in the effect's namespace first (the file that declares the def), then in Base's, as the def's body would. A constructor the program does not use has no id, so #ifdef CID(Name) tests for it. FID(name) is a def's function id the same way. f holds the def's arguments in order: a U32 is the word ((u32)f[0]), a String is taken with io_cstr(e, f[0], &len) (a malloced copy you free), a packed handle with io_hand_v(f[0]). The loop calls the effect at once; an effect that waits (for a handle, or for time) parks itself, as below.

The effect returns a Term: a U32 is (Term)n, Unit is term_pak(CID(Unit), 0), a String is io_str(e, p, n), a two-field constructor is io_node(e, CID(K), a, b). A Result is io_done(e, v) or io_fail(e, code, text) (text NULL prints strerror(code)). io_sys_end(w, n) stores errno in w->code when a call fails.

Descriptor and window handles pack one word with io_hand(v). Their type must be one of Base's handle laws (File, Socket, ...): a user handle type is a WONTFIX entry for now, see WONTFIX.txt. An effect on a handle hands it back beside its result: io_tup(e, io_hand(h), r), also on failure.

A handle owns its descriptor, on both sides. An effect that answers a new handle gives its fd away open: it does not close it later or keep its number. An effect that takes a handle borrows the fd and hands back the same one, still open; only a close effect (Socket.close, ...), which consumes the handle, closes it. A descriptor that never becomes a handle is the effect's own, closed on every path, as tcp_connect.c does when its setup fails. Since handles are affine, this keeps every parked fd open: an fd closed under the loop is a bug in the effect that closed it, and the number it freed may already belong to another open.

Chan instead owns a native heap block containing its row and buffered Terms, wrapped in a reference count at birth so a shared Data cell may hold it. Handle copies use the ordinary native reference count. Close wakes waiters but preserves buffered values for copied handles; dropping the last handle releases the block and unread values. A parked channel operation retains its input handle until it wakes or times out. The C effect consumes that handle, rather than returning it beside the result. Channels share the native heap's reference-counting lifetime model, not a tracing garbage collector.

Blocking work leaves the loop in two ways. io_work(w, call, pack) runs call(w) on a helper thread, then pack(e, w) on the loop; pack's value is the answer. call has no Env: it may only touch w. A job that can reach stdout's destination (a file it opens, reads or writes, or a process that can read that file) calls io_sync() first: it flushes stdout, so IO.print's earlier output lands before the job's. Other io_work jobs keep stdout buffered. io_wait_on(w, fd, POLLIN, 0, more) parks until fd is ready (POLLIN or POLLOUT), then runs more(e, w) on the loop; more may call io_wait_on again. Both return IO_PARK, which the effect returns. Replace 0 with an absolute io_tick() deadline to also wake on time; with no events (io_wait_on(w, 0, 0, deadline, more)) it waits on time alone, as sleep.c does. An effect that can meet a steady backlog (an accept, a datagram recv) parks before its first try, as tcp_accept.c does: one that answers at once never lets the loop poll, so the backlog would starve its timers.

w is the effect's scratch space: hand, made, size, data, text, code, and word until it parks (io_wait_on keeps its fd there). The runtime owns w and f. The effect owns w->data: allocate it in the run function and free it in pack. In bend2/effs/, file_read.c is the pattern for io_work and tcp_recv.c for io_wait_on.

The JS side

The .js file is a plain script, run once in a closure of its own, that registers the effect: io_eff(CID(Clock.now), clock_now). The effect takes the def's arguments as JS values: a U32 is a number, a Nat a number, a String a string, a constructor {$: CID(Name), field: value}, a handle its host value (a descriptor). CID(Name) is the constructor's tag, read as on the C side. It returns the answer the same way: io_done(v), io_fail(code), io_tup(handle, result), {$: CID(Unit)}. A Nat answer that is not a whole number from 0 to 2^53 stops the run; a Nat inside an answer goes unchecked, so the host keeps it in that range.

A blocking effect takes one more argument, k, and parks with io_park_on(fd, out, k, more): it returns undefined, and the loop calls more() when fd is ready; more answers the value, or undefined to park again. Add an absolute performance.now() deadline as a fifth argument to also wake on time; with no fd (io_park_on(undefined, false, k, more, deadline)) it waits on time alone, as sleep.js does. An effect that can meet a steady backlog parks before its first try, as on the C side. io_sys() is libc through bun:ffi (read, recv, select, errno); tcp_accept.js shows the full shape.

A complete example

main.bend:

import Base

def Clock.now() -> IO(U32):
  import "./clock.c"
  import "./clock.js"

def main() -> IO(Unit):
  do IO<Unit>:
    t : U32 <- Clock.now()
    IO.print("ms: " ++ U32.show(t))

clock.c:

Term clock_now_run(Env e, Term* f, IoWork* w) {
  return (Term)(uint32_t)(io_tick() / 1000000ull);
}

static void __attribute__((constructor)) clock_now_use(void) {
  io_eff(CID(Clock.now), clock_now_run);
}

clock.js:

function clock_now() {
  return Math.floor(performance.now()) >>> 0;
}

io_eff(CID(Clock.now), clock_now);

bend main.bend -o main && ./main prints a line; so do bend main.bend -o main.js && bun main.js and bend main.bend. The output name must not be one of the effect's files. The two sides count from different zeros: io_tick() reads CLOCK_MONOTONIC, whose zero the OS picks (on Linux, boot), and performance.now() starts with the process. Only the difference between two reads means the same on every lane.

Building the C yourself

bend x.bend -o x builds with a fixed command and takes no flags. When your .c calls a library, or the binary needs a flag, emit the C and build it yourself:

bend x.bend -o x.c
clang -std=c11 -O3 x.c -lpthread -lm -o x

That is the command bend runs, with clang 14 or newer. Some programs need more:

  • A window on Linux: add -lX11 -ldl. Audio on Linux: add -lasound.
  • A window, audio or a ! on macOS: add -x objective-c -fobjc-arc -fmodules before x.c.
  • A library your .c calls: add -lfoo after x.c, or the path of its libfoo.a to link it statically, then the libraries it depends on.

A program with a ! needs clang 19 or newer (Apple clang 17) and a second step, which writes the GPU program to x.gpu, beside the binary. On macOS:

clang -DBEND_METAL=1 -x objective-c -fobjc-arc -fmodules \
  -std=c11 -O3 x.c -lpthread -lm -o x
./x +RTS --gpu-build

On Linux, with the CUDA toolkit at $CUDA (/usr/local/cuda, usually):

clang -DBEND_CUDA=1 -I$CUDA/include -L$CUDA/lib64 -L$CUDA/lib \
  -std=c11 -O3 x.c -lpthread -lm -o x -lcuda -lnvrtc
./x +RTS --gpu-build

Without -DBEND_CUDA=1, the ! runs on the CPU.

On macOS, a binary targets the machine that built it: its macOS version and its CPU. To also run on older Macs and on Intel ones, add -mmacosx-version-min=11.0 -arch arm64 -arch x86_64. -static does not work there, since Apple ships no static libc: link your own libraries by their .a and leave the system's dynamic.

Compatibility

The C side tracks the exact compiler version: the names above are the runtime's internals, and a release may rename any of them. There is no ABI promise. Rebuild your effects with every update.