Language reference
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 onlypurefunctions. A function with no effect written ispure.io— the function may callpureandiofunctions.
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.
// 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)
}
// 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:
// 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)
}
// 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
- What it prints, in program order. Output printed before a trap stays printed.
- The value
mainreturns:mul runand a built executable exit with it (the low 8 bits, as every process exit code). With--print-resultthey print it on the last line instead and exit with 0. - A run-time error (a trap), described in errors.
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.
This page is docs/language/ in the repository, published as it is. Every mul code block on it is compiled and run by the test suite.