Docs/Language/Capabilities
Capabilities
Grant an imported module only the access it needs, checked at compile time.
~2 min read
On this page
The idea
Capabilities limit what a module may do: IO (printing, console), FS (files), Net, Alloc, Spawn. The check runs at compile time and costs nothing at run time. It is opt-in: a program whose imports have no with clause is not checked. Once any import has one, the program is in strict mode and a module imported with use name with { ... } may use only the capabilities listed.
Grants on imports
// logger.fd
pub fn log_line(msg: str) {
println(msg);
}use logger with { IO }; // logger may print, nothing else
fn main() -> i64 {
log_line("started"); // prints: started
return 0;
}With use logger with { FS }; the same program is rejected:
Capability error: 'println()' requires 'IO' capability (not granted to module 'logger')The check looks at each call by name and does not follow calls: a function that calls another function which prints is not itself checked for IO. Capabilities are matched by the names of the runtime and standard-library functions called, so code that reaches the operating system another way (a helper function, raw extern "C" calls) is not covered. Use effect annotations, which do follow calls, where that matters.
Effects in signatures
A function can also declare its effects. A declared set that leaves out an effect the body has is an error, wherever the module came from:
fn helper() -> i64 {
println("side effect");
return 1;
}
fn pure_sum(a: i64, b: i64) -> i64 !{} {
return a + b + helper();
}Effect error: function 'pure_sum' has inferred effect '!IO' but only declared effects not including itSee Errors & Effects for the effect syntax.
Sandbox blocks
sandbox { } revokes all capabilities for the code written inside it:
fn main() -> i64 {
sandbox {
print("hello");
}
return 0;
}Sandbox error: 'print()' requires 'IO' capability -- all capabilities are revoked inside sandboxPure computation inside a sandbox is fine. The sandbox checks only calls written directly in the block (IO builtins, p_malloc); functions called from it are not checked, even ones that print.
fn score(x: i64) -> i64 { return x * 2; }
fn main() -> i64 {
var result = 0;
sandbox {
result = score(21);
}
println(result); // 42
return 0;
}cap as interface
The same cap keyword declares traits; see Traits & Generics.