---
title: "Calls"
description: "Call forms, evaluation order, defaults, mutable arguments, method and static dispatch, explicit generic arguments, trailing closures, errors, and effects."
---

> 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.

# Calls

A call supplies one value for each parameter in a callable's static signature.
Free functions, methods, static functions, function values, and closures all
use the same rules.

```atoll
struct User {
    first string
    last  string

    fn display_name(&self) string => "${self.first} ${self.last}"
    fn anonymous() User => User { first: "anon", last: "" }
}

fn add(a int, b int) int => a + b

fn main() void {
    total := add(20, 22)
    name := User { first: "Ada", last: "Lovelace" }.display_name()
    fallback := User.anonymous()
    empty := List.new[string]()
    mapped := [1, 2, 3].map { value => value * 2 }.collect()

    println("${total} ${name} ${fallback.first} ${empty.len()} ${mapped.len()}")
}
```

## Forms

| Form | Selects |
| --- | --- |
| `function(args)` | A named function in scope |
| `value.method(args)` | A method for the receiver's static type |
| `Type.function(args)` | A static function on the type |
| `callable(args)` | A function or closure value |
| `function[Types](args)` | A call with explicit generic arguments |
| `function(args) { closure }` | A call whose last argument is a trailing closure |

Parentheses are required even when there are no arguments — a bare name is a
function *value*, not a call.

```atoll run=0
fn now() int => 7

fn apply(op fn() -> int) int => op()

fn main() void {
    called := now()
    as_value := now
    println("${called} ${apply(as_value)} ${apply(now)}")
}
```

Using the name where a value is not expected is a type error, which is the
diagnostic you get if you forget the parentheses:

```atoll fail
fn now() int => 7

fn main() void {
    v: int = now
    println("${v}")
}
```

## Line breaks

A `(` at the start of a fresh line does not continue the previous expression.
`operation` on one line and `(value)` on the next are two statements, and the
first one is just a function value:

```atoll fail
fn twice(v int) int => v * 2

fn main() void {
    value := 3
    result: int = twice
    (value)
    println("${result}")
}
```

Keep `(` on the callee's line. Inside an already open argument list, line
breaks are ordinary trivia, and a trailing comma is allowed:

```atoll
fn combine(first string, second string, third string) string =>
    "${first}-${second}-${third}"

fn main() void {
    joined := combine("alpha", "beta", "gamma")
    println(joined)
}
```

A member chain may also break across lines, because the leading `.` makes the
connection explicit:

```atoll
fn main() void {
    result := [3, 1, 2]
        .sorted()
        .map { v => v * 10 }.collect()
        .len()
    println("${result}")
}
```

## Evaluation

Call evaluation is deterministic:

1. evaluate the callee or receiver, once;
2. evaluate the written arguments left to right, once each;
3. materialize omitted trailing defaults;
4. enter the callable;
5. produce its success value, error value, or suspension.

```atoll
fn step(label string, value int) int {
    println("evaluating ${label}")
    return value
}

fn combine(a int, b int) int => a + b

fn main() void {
    total := combine(step("first", 20), step("second", 22))
    println("total ${total}")
}
```

That prints `evaluating first`, then `evaluating second`, then `total 42`. The
compiler does not reorder calls because one looks pure, and method lookup
never executes user code.

The whole argument list is established before the callee body begins, so a
later argument cannot observe mutation performed inside the callee, and a call
that fails while evaluating an argument never enters the callee at all.

## Arity and defaults

Calls are positional: supply every required parameter and no extras.

```atoll fail
fn add(a int, b int) int => a + b

fn main() void {
    println("${add(1)}")
}
```

Defaults fill only an omitted trailing suffix, so a caller cannot skip `port`
and supply only `secure`:

```atoll
fn connect(host string, port int = 5432, secure bool = true) string {
    scheme := if secure { "https" } else { "http" }
    return "${scheme}://${host}:${port}"
}

fn main() void {
    println(connect("db.internal"))
    println(connect("db.internal", 6432))
    println(connect("db.internal", 6432, false))
}
```

There are no named arguments and no variadic parameters — `name: value` inside
an argument list is not call syntax, and the diagnostic reflects that the
compiler is trying to read it as an ordinary expression:

```atoll fail
fn connect(host string, port int) string => "${host}:${port}"

fn main() void {
    println(connect(port: 5432, host: "db.internal"))
}
```

Default expressions are folded at compile time; they do not execute in the
caller's scope. Changing a public default changes the behaviour of source that
still compiles unchanged, so treat it as API surface. When several optional
settings evolve independently, take a struct — the field names then do the
work named arguments would have:

```atoll
struct ConnectOptions {
    host   string
    port   int
    secure bool
}

fn connect(options ConnectOptions) string {
    scheme := if options.secure { "https" } else { "http" }
    return "${scheme}://${options.host}:${options.port}"
}

fn main() void {
    println(
        connect(
            ConnectOptions {
                host:   "db.internal"
                port:   6432
                secure: true
            }
        )
    )
}
```

## Arguments

Each argument is checked against its parameter's expected type, and that
expectation flows *into* the argument. Numeric literals adopt the parameter's
width, and a closure argument's parameter types come from the function type.

```atoll
fn write(port u16, transform fn(string) -> string) string {
    return "${transform("  payload  ")}@${port}"
}

fn main() void {
    println(write(443, text => text.trim().clone()))
}
```

`443` is created as a `u16`, and `text` is known to be a `string` without an
annotation. A mismatched argument is reported in argument position:

```atoll fail
fn takes_int(value int) int => value

fn main() void {
    println("${takes_int("nope")}")
}
```

## Mutable arguments

`mut` on a binding is a writable place in this frame. It does not write the
caller's argument slot. Inout is a mut pointer; scratch is a mut local.

```atoll
fn append_marker(values &mut []string) void {
    values.push("done")
}

fn main() void {
    mut names := ["start"]
    append_marker(&mut names)
    println("${names.len()} ${names.get(1) ?? "?"}")
}
```

```atoll run=2
struct Queue {
    items []int

    fn push(&mut self, value int) void {
        self.items.push(value)
    }

    fn count(&self) int => self.items.len()
}

fn main() int {
    mut q: Queue = Queue { items: [] }
    q.push(1)
    q.push(2)
    return q.count()
}
```

The argument must be a mutable place — a `mut` binding, or a field or index of
one. A plain binding cannot satisfy it:

```atoll fail
fn append_marker(values &mut []string) void {
    values.push("done")
}

fn main() void {
    names := ["start"]
    append_marker(&mut names)
    println("${names.len()}")
}
```

Mutation through `&mut self` uses the same model, and the receiver is still
evaluated once — the run-gated block above is exactly that shape.

**Writing the caller's value is `p &mut T` plus `&mut place` at the call.**
Taking `&mut a` requires `mut a`. `&mut self` still aliases the receiver. A frozen pin cannot be written through (ATOLL2007). Every
ordinary place is:

| argument | what the address names |
|---|---|
| `&b` | the binding's own storage (`mut b`) |
| `&b.items`, `&b.inner.c.items` | the field, at any depth |
| `self.items` inside `&mut self` | the caller's bytes, through the receiver |
| `&mut p.c` on `mut p: ^T` | the block; the pin itself must be `mut` |

A **temporary** is the one thing that is not — `make().c.bump()` has no name
at its root, so there is nothing for the write to reach and the call is
refused. A bare temporary receiver is fine, because the write is meant to be
discarded: `xs.iterator().filter(p).count()` advances a receiver nobody else
names.

## Generic arguments

Generic arguments are normally inferred from the argument types and the
expected result:

```atoll
fn identity[T](value T) T => value

fn first_or[T](xs []T, fallback T) T where T: Clone => (xs.get(0) ?? fallback).clone()

fn main() void {
    println("${identity(42)} ${identity("text")}")
    println("${first_or([3, 4], 0)} ${first_or([], "none")}")
}
```

Write them explicitly, immediately before `(`, when nothing constrains the
choice — most often when constructing an empty collection:

```atoll
fn empty_of[T]() []T => []

fn main() void {
    names := List.new[string]()
    counts := Map.new[string, int]()
    seen := Set.new[int]()
    blank := empty_of[float]()

    println("${names.len()} ${counts.len()} ${seen.len()} ${blank.len()}")
}
```

Square brackets *not* followed by `(` remain indexing syntax, so the two forms
never collide. Each call receives an independent substitution: a call with
`int` does not specialize the declaration for a later call with `string`.

## Method and static dispatch

Method selection uses the receiver's static type together with inherent
methods, receiver-prefix declarations, applicable trait implementations, and
bounds in scope. It is resolved at compile time — there is no runtime method
table.

```atoll
struct Article {
    title string
    body  string
}

impl Article {
    fn summary(&self) string => "${self.title} (${self.body.len()} chars)"
}

fn Article.headline(&self) string => self.title.clone()

trait Sized {
    fn approximate_size(&self) int
}

impl Sized for Article {
    fn approximate_size(&self) int => self.title.len() + self.body.len()
}

fn report[T](item T) string where T: Sized => "size ${item.approximate_size()}"

fn main() void {
    a := Article { title: "Atoll", body: "a systems language" }
    println(a.summary())
    println(a.headline())
    println(report(a))
}
```

Missing selection is a compile-time error naming the receiver type:

```atoll fail
struct Point { x float, y float }

fn main() void {
    p := Point { x: 1.0, y: 2.0 }
    println("${p.magnitude()}")
}
```

Static functions have no receiver and are selected through the type:

```atoll
struct Point {
    x float
    y float

    fn zero() Point => Point { x: 0.0, y: 0.0 }
    fn along_x(distance float) Point => Point { x: distance, y: 0.0 }
}

fn main() void {
    println("${Point.zero().x} ${Point.along_x(3.5).x}")
}
```

## Calling function values

A local, parameter, or field with function type is called with the same
parentheses. The callable expression is evaluated once, so a call that
produces a function can be invoked immediately:

```atoll
struct Route {
    path    string
    handler fn(int) -> int
}

fn choose_handler(kind string) fn(int) -> int {
    if kind == "double" {
        return v => v * 2
    }
    return v => v + 1
}

fn main() void {
    r := Route { path: "/scale", handler: choose_handler("double") }
    println("${r.handler(21)}")
    println("${choose_handler("inc")(41)}")
}
```

`choose_handler("inc")` runs first and yields a function value; the second
parentheses invoke it.

## Trailing closures

When the last argument is a closure, it may be written in braces after the
argument list instead of inside it. Both forms mean the same thing.

```atoll
fn retry(times int, body fn(int) -> bool) bool {
    for attempt in 0..times {
        if body(attempt) {
            return true
        }
    }
    return false
}

fn main() void {
    inline_form := retry(3, attempt => attempt == 2)
    trailing_form := retry(3) { attempt => attempt == 2 }
    println("${inline_form} ${trailing_form}")
}
```

The braces belong to the closure argument, not to the call's result. This is
what makes multi-line callbacks readable, and it is how the collection
higher-order methods are normally written:

```atoll
fn each_path(paths []string, body fn(string) -> void) void {
    for p in paths {
        body(p)
    }
}

fn main() void {
    values := [1, -2, 3, -4]

    positive := values.filter { v => v > 0 }.collect()
    doubled := values.map { v => v * 2 }.collect()
    total := values.fold(0) { (acc, v) => acc + v }

    println("${positive.len()} ${doubled.len()} ${total}")

    each_path(["/health", "/metrics"]) { path =>
        println("checking ${path}")
    }
}
```

## Errors at a call site

Calling a fallible function produces a `Result[T, E]`. The caller must store,
match, convert, or propagate it.

```atoll
error CfgError { Missing }

fn read(key string) string ! CfgError {
    if key == "" {
        error Missing
    }
    return "value-of-${key}"
}

fn build() string ! CfgError {
    host := read("host")?
    port := read("port")?
    return "${host}:${port}"
}

fn main() void {
    println(build().unwrap_or("unconfigured"))

    direct := read("") catch {
        err => {
            println("missing key")
            return
        }
    }
    println(direct)
}
```

`?` applies after the call and exits the enclosing fallible function. Argument
evaluation that already happened is not rolled back when a call returns `Err`;
compensation stays an explicit policy. See [Errors](https://docs.atoll.workreef.dev/language/errors/).

## Effects at a call site

A call inherits the callee's effect row, so ordinary call syntax may allocate,
suspend, spawn, or exit through the error channel.

```atoll
fn slow(value int) int => value * 2

fn parallel(a int, b int) int {
    left := spawn { slow(a) }
    right := spawn { slow(b) }
    return left.await().unwrap_or(0) + right.await().unwrap_or(0)
}

fn main() void {
    println("${parallel(2, 3)}")
}
```

An enclosing declared `using` row must permit every inherited effect; without
one, the compiler infers the union transitively. If a call suspends, values
that are live afterwards are kept in the generated continuation — a
consequence of the callee's signature, not of any special call punctuation.

## Contexts

A parameter marked `@context` is filled from the caller's own context of its
type, so a call leaves it out. A local marked `@context` is that context
from there to the end of its block:

```atoll run=11
struct Tenant {
    name string
}

fn label(word string, @context t &Tenant) string => "${word}:${t.name}"

fn report() string => label("report")

fn main() int {
    @context t := Tenant { name: "acme" }
    return report().len()
}
```

`report` names no tenant. A function whose callees read a context is handed
it by its callers, inferred up the call tree as effect rows are, and an
editor's hover over `report` says so: *contexts handed by its callers:
`Tenant`*. One context of each type is in scope at a time; a `@context`
local of the same type bound in an inner block is what that block's calls
are handed. A spawned task takes its own copy of each context it is handed,
so it holds no borrow of the frame that spawned it.

A root has no callers to be handed one by: `main`, a `test`, a served
operation's dispatch, or a function declared `@context(root)`. One that
neither binds nor makes a context its callees read is refused at the call,
naming the path, here "`main` has no `Tenant`: main → report → label":

```atoll refused=ATOLL3246
struct Tenant {
    name string
}

fn label(@context t &Tenant) string => t.name

fn report() string => label()

fn main() void {
    println(report())
}
```

### Roots make what they need

A context's type may name its maker: `@context(made_by: of)` on its
declaration names the static method that makes one. A root that needs one
and binds none makes it before its body, the maker handed the root's
parameters that hold what it takes, and makes none that its calls do not
end up reading. A call of a root asks its caller for nothing:

```atoll run=4
struct Name {
    text string
}

@context(made_by: of)
struct Tenant {
    name string

    fn of(n &Name) Tenant => Tenant { name: n.text.clone() }
}

fn label(@context t &Tenant) string => t.name.clone()

@context(root)
fn answer(n &Name) string => label()

fn main() int {
    return answer(Name { text: "acme" }).len()
}
```

`answer` makes its `Tenant` of the `Name` it takes, and `main` needs none.
Where a root's parameters hold nothing its maker takes, the root is refused,
and the refusal says which maker would make one and from what.

A function declared `@context(maker)` is another maker of the context type
it answers, wherever it is declared. A root makes the context with the
maker whose parameters its own hold, and of two that do, with the one that
takes all the other takes and more:

```atoll run=8
struct Request {
    tenant string
}

@context(made_by: anon)
struct Tenant {
    name string

    fn anon() Tenant => Tenant { name: "anon" }
}

@context(maker)
fn tenant_of(r &Request) Tenant => Tenant { name: r.tenant.clone() }

fn label(@context t &Tenant) string => t.name.clone()

@context(root)
fn serve(r &Request) string => label()

fn main() int {
    return serve(Request { tenant: "acme" }).len() + label().len()
}
```

`main` makes its `Tenant` with `Tenant.anon`, which takes nothing, and
`serve` with `tenant_of`, which takes what `anon` takes and a `Request`
besides. So `std/http` declares a maker of `locale.Locale` of a call's peer,
and a served operation writes in the language its request prefers where
`main` writes in the environment's. Two makers that fit a root, neither
taking all the other takes, are refused, naming both.

### Context-only types

`@context` on a type's declaration makes its values live only as contexts:
in a binding or a parameter marked `@context`, or a capture of one. A maker
answers one into a `@context` binding, and its own methods take it as
`self`, so a narrower one can be bound beneath it:

```atoll run=1
@context struct Grant {
    who   string
    level int

    fn only(&self, level int) Grant => Grant { who: self.who.clone(), level: level }
}

fn level(@context g &Grant) int => g.level

fn lowered(@context g &Grant) int {
    @context less := g.only(g.level - 1)
    return level()
}

fn main() int {
    @context g := Grant { who: "ann", level: 2 }
    return lowered()
}
```

Anywhere else, a value of one is refused: a field or a variant's payload of
another type, a plain local, a plain parameter, or an element held in one of
those. So the authority a context-only type stands for goes only where the
call tree and its tasks go, and no cache or queue hands one call tree's to
another. What a program keeps of one is plain data (`g.level`).

```atoll refused=ATOLL3247
@context struct Grant {
    who string
}

struct Cache {
    last Grant
}

fn main() void {
    println("cached")
}
```

A type declared `@context(plain)` is a context whose values are plain data
besides: it is bound, handed and made as any context is, and a field, a list
or a plain local may hold one as well. `locale.Locale` is one, so a program
may keep a locale it read and bind it where it writes.

## A complete example

```atoll
error FetchError { Offline, NotFound }

struct Client {
    base    string
    retries int

    fn get(&self, path &string) string ! FetchError {
        if path == "" {
            error NotFound
        }
        if self.retries == 0 {
            error Offline
        }
        return "${self.base}${path}"
    }
}

impl Client {
    fn local() Client => Client { base: "http://localhost", retries: 3 }
}

fn with_retries(c Client, n int) Client => Client { base: c.base, retries: n }

fn each_path(paths []string, body fn(string) -> void) void {
    for p in paths {
        body(p)
    }
}

fn main() void {
    client := with_retries(Client.local(), 2)

    each_path(["/health", "/metrics", ""]) { path =>
        body := client.get(path) catch {
            err => {
                println("${path} -> failed")
                return
            }
        }
        println("${path} -> ${body}")
    }
}
```

Every call form appears here: a static function through the type
(`Client.local()`), a free function (`with_retries`), a method on a value
(`client.get`), a trailing-closure call (`each_path(...) { ... }`), a call to
a function value (`body(p)`), and a fallible call discharged with `catch`.

## Diagnostics

Call diagnostics name the contract that failed, and each one has its own fix:

| Diagnostic | Cause | Fix |
| --- | --- | --- |
| unresolved name / no method on type | The callee or method does not exist for that type | Import it, or add the method |
| takes N arguments, but M supplied | Wrong arity | Match the signature; defaults only fill a trailing suffix |
| type mismatch in argument position | Incompatible argument | Convert explicitly, or change the parameter |
| must be a mutable place | Immutable binding passed to a `&mut` parameter or a `&mut self` method | Declare the binding `mut` |
| unsatisfied bound | The type argument does not implement a required trait | Add the implementation or `@derive` it |
| unhandled `Result` | A fallible call whose error channel was ignored | `?`, `catch`, or `unwrap_or` |
| no context of the type its callee reads (ATOLL3246) | A root, or a call nothing hands one, has no `@context` binding of that type | Bind one with `@context` at the root, or above the call |
| lives only as a context (ATOLL3247) | A value of a type declared `@context` held in a field, an element, a plain local or a plain parameter | Mark the binding or the parameter `@context`, and keep what it says as plain data |

Adding a cast does not repair missing mutability, a missing error boundary, or
an unsatisfied bound — fix the dimension the diagnostic names.

Source: https://docs.atoll.workreef.dev/language/fundamentals/calls/index.mdx
