# Effects

Normative sources: RFC-009,
RFC-010 (`print`).

## Effects in signatures

Every function has one effect, written after the return type:

- `pure` — the function may call only `pure` functions. A function with no
  effect written is `pure`.
- `io` — the function may call `pure` and `io` functions.

A `pure` function that calls an `io` one is `MUL-T013`, so a `pure`
signature guarantees that no chain of calls from it reaches an `io`
function. `io` is an upper bound: an `io` function does not have to do
anything with the outside world. `main` may be either.

```mul
// expect: 41
module demo

fn double(n: i32) -> i32 pure {
    return n * 2
}

fn report(n: i32) -> i32 io {
    return double(n) + 1
}

pub fn main() -> i32 io {
    return report(20)
}
```

```mul
// expect-error: MUL-T013
module demo

fn log(n: i32) -> i32 io {
    return n
}

// No effect written, so `total` is pure and cannot call `log`.
fn total(n: i32) -> i32 {
    return log(n) + 1
}

pub fn main() -> i32 io {
    return total(1)
}
```

Fix: mark the caller `io`, or make the callee `pure` if it does no `io`.

## `print`, the first `io` operation

`print(text)` writes a `string` and a line feed to standard output. It is an
`io` operation, so only an `io` function can call it, directly or through
other `io` functions:

```mul
// expect: checking 3
// expect: 9
module demo

fn square(n: i32) -> i32 pure {
    return n * n
}

fn checked(n: i32) -> i32 io {
    print("checking 3")
    return square(n)
}

pub fn main() -> i32 io {
    return checked(3)
}
```

```mul
// expect-error: MUL-T013
module demo

// No effect written, so `greet` is pure and cannot print.
fn greet() -> i32 {
    print("hi")
    return 0
}

pub fn main() -> i32 io {
    return greet()
}
```

## What a program can observe

1. What it prints, in program order. Output printed before a trap stays
   printed.
2. The value `main` returns: `mul run` and a built executable exit with it
   (the low 8 bits, as every process exit code). With `--print-result` they
   print it on the last line instead and exit with 0.
3. A run-time error (a trap), described in [errors.md](errors.md).

A `pure` function observes none of this from the inside: a `var` lives only
inside its own call, and a `pure` function returns the same value for the
same arguments.

## Planned

The design document also names `alloc`, `async` and `unsafe`;
they are not part of the language yet.
