---
title: "Host functions in a module"
description: "Ship a module whose `@host` declarations are answered by a Rust crate, and use one from an app."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Host functions in a module

A `@host` declaration says a function is answered outside the program. The
stdlib's are answered by the `atoll` binary you already have. A module can
declare its own — an image codec, a metrics sink, a driver for something
Atoll has no bindings for — and ship the Rust that answers them.

A program that calls a declaration nobody implements cannot run: binding
refuses it by name, at startup, before anything executes. So `atoll` builds
an `atoll` that can, caches it, and runs your program on that. You do not
invoke the build; `atoll run` does.

## Declare

A module is an ordinary project. The declarations sit beside the Atoll that
wraps them:

```atoll project=imaging file=imaging.at
// imaging.at
@host
fn decoded_size(w int, h int) int

pub fn area(w int, h int) int {
    return decoded_size(w, h)
}
```

```toml
# atoll.toml
module = "acme.dev/imaging"
```

`@host` takes no arguments. The declaration is bound by the module it is in
and its own name, `acme.dev/imaging.decoded_size`, so there is nothing to
write and nothing another module's declarations can collide with.

A declaration whose call may wait is also `@suspend`. That decorator is the
host declaration's own: nothing else can say that the host parks the task.
The Atoll that wraps one never repeats it — `area` above would suspend because
what it calls does, and `@suspend` on a function with a body is refused
(`ATOLL2026`).

## Generate

```text output
$ cd imaging
$ atoll bindings --mode crate -o host .
wrote Cargo.toml, src/lib.rs, src/imports.rs, src/hosts.rs to host

Fill in the bodies in host/src/hosts.rs, then name the crate in your `atoll.toml`:

    [host]
    implementation = { crate = "acme-imaging", path = "host" }

`atoll run` then builds an `atoll` that carries it.
```

Four files, and exactly one of them is yours:

| file | whose |
| --- | --- |
| `src/imports.rs` | generated — the wasm import arms. Never edit; regenerate. |
| `src/lib.rs` | generated — `all()`, the set `atoll` looks for. |
| `Cargo.toml` | generated — rewritten when the atoll tree moves. |
| `src/hosts.rs` | **yours**, written once and never overwritten. |

No entry point is needed and nothing has to call the declarations. The
project's own `@host` declarations are what it generates, every one of
them whether the module calls it or not. The standard library's, which
`atoll` already carries, are left out.

> **Note**
>
> Regenerating is safe: it rewrites the three generated files and leaves
> `src/hosts.rs` alone. Delete that file to start the skeleton over.

## Implement

`src/hosts.rs` arrives as a skeleton. Fill in the bodies:

```rust
pub fn decoded_size(w: i64, h: i64) -> i64 {
    w * h * 4
}
```

The module's own declarations sit at the root of `hosts.rs`, and a module
below it is a Rust module of the same name: `acme.dev/imaging/codec`'s are in
`pub mod codec`.

Plain functions. No attribute, no macro. The generated arm calls this with
the types the declaration names, so a signature that has drifted is a
compile error at the call, naming both sides.

The types come from the declaration and are not negotiable:

| Atoll | Rust argument | Rust argument, `@suspend` |
| --- | --- | --- |
| `int`, `f64`, `bool`, `byte` | `i64`, `f64`, `bool`, `u8` | the same |
| `string` | `atoll::Str<'_>` | `atoll::GuestBytes` |
| `List[T]` | `atoll::List<'_, T>` | `atoll::GuestBytes` |
| `Map[K, V]`, `Set[T]` | `atoll::Map<'_, K, V>`, `atoll::Set<'_, T>` | not available |
| `T?`, `Result[T, E]` | `Option<T>`, `Result<T, E>` | the same |
| a `struct` or `enum` you declared | its generated view, `crate::bindings::PointRef<'_>` | a mirror you write, which the generated module reads |
| a type of another module | its host crate's view: `::acme_geo::bindings::PointRef<'_>` | its host crate's type: `::atoll_hosts::hosts::fs::Error` for the standard library's |

A plain body reads a struct or an enum through the **view** `atoll bindings`
generates for it from the declaration: `PointRef<'_>` has one accessor per
member, `p.lat()`, each read once where the program keeps the value, and an
enum's view answers `get()`, its variant with the payload's view, to `match`
on. Nothing a pointer leads to is copied: a `string` member is the program's
own `atoll::Str`. Nobody writes a view, so a body cannot read a member the
declaration does not have.

A `string` argument is an `atoll::Str<'_>`: the program's own bytes, read
where the program keeps them, with nothing copied and nothing checked. A
`string` is UTF-8 by the language's rule, but a program may slice one
mid-letter, so the check is the body's to ask for: `as_str()` checks once
and answers a `Result`. Shown with `{}`, a byte that is not part of a
letter is a replacement character. A `Str` compares with `==` against a
`&str` or bytes, and answers `len`, `starts_with`, `ends_with`,
`contains`, `find` and `split`, whose parts are windows into the same
bytes; `as_bytes()` is the bytes themselves. The bytes are found where they
are read: a body that only asks the length, or hands the argument back,
reads none of them.

```rust
pub fn tag_count(tags: atoll::Str<'_>) -> i64 {
    tags.split(",").filter(|t| !t.is_empty()).count() as i64
}
```

A body's own tests hand it text they have: `"a,b".into()`.

A `@suspend` declaration's body is an `async fn` when it may wait, and its
arguments are held **by address** rather than borrowed: the guest runs
between the call and the await that follows, so a borrow of its memory would
be reading a block it may have freed. A body that never waits may be a plain
`fn` returning its answer. The declaration is the same either way, since
`@suspend` says a call may wait, and the body decides whether it can. A plain
`fn` is called and answered on the spot, which is the import one would write
by hand; an `async` body that answers on its first poll still goes through
the box its member keeps for a future that might wait, a few instructions a
call more (49 against 45 for a call with no arguments, on the
`host_boundary` bench). A `Map` has no address form — nothing yet pins a
guest block against collection across a suspension — so a suspending
declaration cannot take one.

### An answer written where the program reads it

A declaration that answers a `string` or a `List` is lent the call's writer
as its last argument, `out: atoll::Out<'a>`, and returns the answer as the
declaration names it: an `atoll::String<'a>` for a `string`, an
`atoll::List<'a, T>` for a `List[T]`. Each is made in a block of the
program's own heap, through `out`, written once, and handed over; the
program owns it from then on, as if it had built the value itself. Nothing
is staged in the host and nothing is copied afterwards.

```rust
pub fn describe<'a>(name: atoll::Str<'a>, out: atoll::Out<'a>) -> atoll::String<'a> {
    atoll::format!(out, "image:{name}")
}

pub fn label<'a>(lat: f64, lon: f64, out: atoll::Out<'a>) -> atoll::String<'a> {
    atoll::format!(out, "{lat:.4}, {lon:.4}")
}

pub fn unit<'a>(out: atoll::Out<'a>) -> atoll::String<'a> {
    atoll::String::from_str(out, "degrees")
}

pub fn squares<'a>(n: i64, out: atoll::Out<'a>) -> atoll::List<'a, i64> {
    atoll::List::from_iter(out, (0..n).map(|i| i * i))
}

pub fn primes<'a>(out: atoll::Out<'a>) -> atoll::List<'a, i64> {
    atoll::List::from_slice(out, &[2, 3, 5, 7])
}
```

`atoll::format!` measures what it formats, reserves exactly that, and
formats into it. `String::from_str` copies text the body already has once.
`List::from_slice` copies a slice, in one write when its elements are
numbers; `List::from_iter` writes each item where it will be read,
reserving what the iterator says it yields and moving to a bigger block if
it yields more. A reservation larger than the heap has room for grows the
memory, and the arguments the body is still reading stay where they are.

An answer borrows the `out` it was made through, so the compiler holds it to
the call: it cannot be kept for a later one. An answer the heap has no room
for **refuses the call**, naming the declaration, rather than answering what
fit; so does text that writes more than it measured. A block reserved and
left empty is given back, and so is one an answer dropped without handing
it over.

An argument handed back as the answer is the program's own block, counted
once more, as the program's own copy of it would be: nothing is copied. A
`List` is handed back as it came, and a `string` as `atoll::String::from`
the argument:

```rust
pub fn longer<'a>(a: atoll::Str<'a>, b: atoll::Str<'a>, _out: atoll::Out<'a>) -> atoll::String<'a> {
    atoll::String::from(if a.len() >= b.len() { a } else { b })
}
```

A window into somebody else's block owns no count of its own: a part of a
`split`, or a string the program trimmed. Handed back, its bytes are
copied into a block of the answer's own.

### A suspending answer

A `@suspend` declaration's `string` or `List` answer is written in place
too. Its body is lent `out` the same way and returns the same `String` or
`List`; what differs is that the body is a future, and it may make its
answer on any poll of it — before it waits, after, or across a wait while
the program runs:

```rust
pub async fn describe<'a>(name: atoll::GuestBytes, out: atoll::Out<'a>) -> atoll::String<'a> {
    tokio::task::yield_now().await;
    atoll::format!(out, "image:{}", std::str::from_utf8(name.as_slice()).unwrap_or("?"))
}
```

Wherever the future runs, the call's writer is lent to it, and the answer
is written into the block reserved for it: the program cannot reach that
block until the answer is handed over, so its running in between changes
nothing there. A call whose task is cancelled while it waits throws its
answer away when the body gives it, and the block goes back.

### Your own types as answers

A plain declaration that answers a `struct` or `enum` you declared answers
the type `atoll bindings` generates for it beside its view:
`crate::bindings::Point`, with the declaration's members as public fields.
Its `HostRet` is generated from the artifact too, so the offsets are the
compiler's and nobody writes a type that could disagree with the
declaration. A type with a `string` or `List` anywhere inside it borrows
the call's writer, `Place<'a>`, and its declaration is lent `out` as a
`string` answer's is:

```rust
use crate::bindings::{Place, Point};

pub fn origin() -> Point {
    Point { x: 0, y: 0 }
}

pub fn place<'a>(lat: f64, lon: f64, out: atoll::Out<'a>) -> Place<'a> {
    Place { name: atoll::format!(out, "{lat:.4}, {lon:.4}"), lat, lon }
}
```

An enum's answer type is a Rust enum of the same variants, each carrying
its payload's answer type; an `error` answered in a `Result` is
`Result<i64, Failure<'a>>`.

A `@suspend` declaration answers its types the same way, through `out`
wherever its future runs. A type of another module is answered as its host
crate's answer type: `::atoll_hosts::bindings::fs::Error<'a>` for the
standard library's `fs.Error`. A module's crate defines every type the
module declares, taken and answered alike, so another crate can answer
one whether or not the module's own declarations do.

## Name the crate

```toml
# atoll.toml
[host]
implementation = { crate = "acme-imaging", path = "host" }
```

Exactly one of `path`, `git` + `rev`, or `version`. `version` parses and is
refused at build time: it would be a Rust crate's version, and Atoll's versions
are tags of `.at` modules' repositories, not crates.

That is the module finished. It carries its declarations, its Rust, and the
line that connects them.

## Use one

An app depends on the module, and allows its native code:

```toml
# atoll.toml
module = "acme.dev/app"

[dependencies]
"acme.dev/imaging" = { path = "../imaging" }

[host]
native = ["acme.dev/imaging"]
```

```atoll project=imaging-app file=main.at
import acme.dev/imaging

fn main() int {
    return imaging.area(2, 3)
}
```

```text nooutput the first run is a cargo build of the host crate, minutes long — run by hand, not in a test
$ atoll run main.at
atoll run: `main` returned 24
```

The first run compiles an `atoll` carrying `acme-imaging` — minutes, once.
Later runs are the cache: measured at 0.027 s. A project that declares no
implementation never reaches any of this and costs nothing.

`[host] native` is the consent: a dependency's implementation is native code
that will run with your program's privileges, so it is linked only when the app
names the module. Without that line the build stops and says which module wants
which crate compiled. The app's own implementation needs no such line, and a workspace
decides once, at its root, for every member. With it, an app using three modules
with host functions gets one binary carrying all three — and the same holds for
a dependency's dependency, all the way down, each named in `[host] native`.

## Shipping it as one file

```text nooutput a cargo build of the host crate, as above — run by hand, not in a test
$ atoll build main.at --binary ./app
Wrote target/atoll/units/main.wasm
  entry points: main
Wrote ./app — runs `main`

$ ./app; echo $?
24
```

The program, the runtime and every host implementation it needs, in one
executable that needs no `atoll` and no `.wasm` beside it. The answer is
the exit code.

Which entry it runs is fixed when it is built — a module may export
several and a binary is one program. `--entry` names it; the default is
what `atoll run` picks with no argument.

## The cache

```text nooutput the cache this machine holds, which no two machines share
$ atoll toolchain list
fingerprint              size       built  carries
1566ec9bd1c1dfc4       112 MB    just now  acme-metrics
5f19c67d79236982       112 MB      2m ago  acme-imaging

2 toolchains, 224 MB under /home/you/.atoll/toolchains
```

One entry per distinct set of implementations, keyed by the atoll source,
the rustc, the target, the profile and the crates. Editing a host body
rebuilds; editing `.at` files does not — the binary takes the compiled
module as an argument, so the dev loop is not a cargo build.

`atoll toolchain where` says where the cache is and how large the shared
build directory has grown. `atoll toolchain clean --keep 2` keeps the two
most recent; `--all --build` removes everything, build directory included.
A bare `clean` removes nothing and names the flags.

### Modules you depend on

A module you import is checked once and then loaded, not re-checked on
every build. Measured on a 1,200-function dependency: 0.36 s the first
time, **0.01 s** after.

The cached form is a sealed world — the same thing the stdlib is — so
your app starts from a world that already has the dependency in it rather
than from nothing. That makes your own functions cheaper too, not only
the dependency's: a sealed module sits in a half of the symbol table that
per-function checking never copies.

An entry is keyed by the module's file contents, the world beneath it,
and the compiler that produced it. Editing a dependency's `.at` file
invalidates that layer and everything sealed after it. Touching a file
without changing it does not.

Two things to know about it:

- **A cached module still says what it said.** Its errors and warnings
  are stored beside it and reported on every build, so a warning cannot
  appear once and then go quiet. You should not be able to tell a loaded
  dependency from a freshly checked one, and that is the point of it.
- **The editor uses it too.** Without it, every keystroke in your app
  re-checked every module it imports — the language server's own cache
  is per file, and checking a project is one job. With it, a 1,200-
  function dependency costs 87 ms per keystroke less.

`ATOLL_LAYER_CACHE=0` turns it off, for telling a compiler bug apart from
a stale entry.

## Locking

`atoll lock` records every implementation, the project's own and its
dependencies':

```toml
[hosts."acme.dev/imaging"]
krate = "acme-imaging"
kind = "path"
source = "../imaging/host"
content_hash = "3eb119301f7e96ff0c…"   # SHA-256 of the crate's Rust tree
```

`atoll lock --check` reports three kinds of drift: the crate's Rust changed,
the declared source changed, or the declaration is gone while the lock still
claims it.

> **Caution**
>
> The digest answers "is this the tree that was reviewed" — never "is this
> tree safe to compile and run". A host implementation is native code linked
> into the binary that runs your program. Read what you link.

## Asking about the call

A body that needs to know something about the call — where in the guest's
memory its argument sits, whether there is a task — takes the context
first:

```rust
    pub fn inspect(cx: &atoll::HostCx<'_>, s: atoll::Str<'_>) -> i64 {
        let guest = cx.memory().as_ptr_range();
        // …
    }
```

Nothing in the declaration says so, and nothing has to: the generated
import reads it from this signature. It costs the bodies that do not ask
nothing at all — the two shapes are two trait impls, and choosing between
them happens when the crate is compiled rather than when the host is
called.

A **suspending** body cannot take one, and that is not a gap: the context
borrows the guest's memory and the body's future outlives the call. What
it usually wants is the task, and `atoll::calling_task()` answers that —
on both suspending routes, including across an `await`, so a body that
opens something for its task and records the association after waiting
for it gets the same task on both sides. A direct body answers `None`,
because a direct call has no task: the guest is on its stack.

## System libraries, native only

A program built native calls its platform's own libraries through the C ABI:
libc and Linux's libraries, the macOS and iOS frameworks, and later Windows's
DLLs. A declaration with no body names the library and gives the C signature:

```atoll planned
@native(lib: "c")
fn getpid() i32

fn main() int {
    return getpid().to_int() * 0
}
```

`@native(framework: "Foundation")` names a framework on Apple's platforms. The
types are C's: integers and floats of stated width, `rawptr`, which never owns,
structs marked `@native` and laid out as C lays them out, and callbacks as
`@native fn` types. Only a native build provides `@native`, on the platforms
its file is for, so system bindings live in platform variants (`tls.linux.at`,
`tls.macos.at`), and a wasm or web build that reaches one is refused at the use
(`ATOLL1132`). A call that can block, or whose cost grows with its input, is
marked `@suspend` and runs on the blocking pool, as a host stub does. A package
that declares `@native` is granted in the program's manifest as a host module
is (`[host] allow`, `ATOLL4001`), and `atoll-link` links the named libraries
dynamically.

`planned` marks a design not built yet. Today's compiler passes the check of
such a declaration and stops building the call with an internal error
(`ATOLL5405`).

Source: https://docs.atoll.workreef.dev/language/modules/host-functions/index.mdx
