15. Program execution
Entry point
Section titled “Entry point”An entry file is a file that declares a top-level fn main. A program runs one entry’s main, after its boot when it has one. How a program is started, from a file or a project, is in the tooling reference.
Entry callbacks
Section titled “Entry callbacks”fn main takes no parameters. A main that declares one is the error `main` takes no parameters over its parameter list, whose help says a program reads its arguments in fn boot(startup: Startup) as startup.args.
main returns Unit, with or without the annotation, or Result<Unit, E> for any E. Any other result type is the error `main` must return `Unit` or `Result<Unit, E>` at the annotation, since a run would drop the value; its help says to print the value with io.print and return Ok(Unit).
fn boot is optional and is declared in the entry file beside main (Scoped application fields below). A program with no boot runs under a root context and has no application fields.
Exit status
Section titled “Exit status”A main that returns Unit or Ok(Unit) exits with status 0.
A main that returns Err(e) prints error: and e’s text to standard error and exits with status 1. The text is Display.to_string(e) when e’s type implements Display, so a String prints without quotes, and Debug.inspect(e) otherwise. An Err that holds an AssertionFailure, which a failed assert in main returns, prints the assertion’s report.
fn run() -> Result<Unit, String> Err("config file not found") end // as `main`: prints `error: config file not found` and exits 1
To choose the status, main returns std::process’s Exit in its Err. Exit is a struct with the fields code: ExitCode = 1 and message: String = "", where ExitCode is std::process’s subtype ExitCode Int when fn code -> code >= 0 and code <= 255. A main declared -> Result<Unit, Exit> that returns Err(e) prints e.message and a newline to standard error, with no error: before it, when the message is not empty, and exits with e.code. A code of 0 exits 0, and its message still prints. A literal code outside 0 to 255 does not compile (300 is not an ExitCode: ...), and a computed one goes through ExitCode.try_from.
import std::process.Exit fn run() -> Result<Unit, Exit> Err(Exit{code: 2, message: "usage: count <file>"}) end // as `main`: prints `usage: count <file>` and exits 2
Only std’s Exit does this. A program’s own type named Exit is an ordinary error and prints after error: . No function exits on the spot: an Exit returned through ? ends the program from anywhere main calls. A test checks an exit as a value: assert main() == Err(Exit{code: 2, message: "usage"}).
A boot that returns Err ends the program the same way, before main runs (Cleanup and boot failure below). For a boot declared -> Result<App, Exit>, supervised tasks drain and boot’s deferred calls run before the program exits with the code, so the message prints after them.
Scoped application fields
Section titled “Scoped application fields”Taught in App Fields, Defer & Context.
Boot and Startup
Section titled “Boot and Startup”An entry file may declare a boot, fn boot() -> Result<App, E> or fn boot(startup: Startup) -> Result<App, E>, for any struct App and any error type E. Boot builds the application value and returns it in Ok, or returns Err when the program cannot start. A boot that cannot fail still returns a Result, so adding a step that can fail does not change its signature. The struct in the Ok of an entry boot is an application type. Its name is not reserved and it needs no impl. A boot may also return an anonymous record (fn boot() -> Result<{n: Int}, String>); its fields are published, but no read can name them.
An application type has at most one field of type Context, under any name. Boot receives no context; one that wants a Context field builds it with Context.root() or a deriver such as Context.with_timeout(Context.root(), d). An application with no Context field runs under the root context.
Startup, in the prelude, holds snapshots of the process’s environment and arguments:
pub struct Startup env: Map<String, String> = {} args: List<String> = [] end
Startup is not ambient. Boot passes what helpers need as ordinary arguments, and a test builds one as an ordinary struct (Startup{args: ["-v"]}). The runtime calls a boot that takes no parameter with no arguments, and passes the process’s Startup to one that takes it. The parameter may have a default, startup: Startup = Startup{}; the runtime always passes the real one, so the default serves only a group’s boot line that passes none (§17 Groups).
import std::io struct App name: String end fn boot(startup: Startup) -> Result<App, String> Ok(App{name: List.first(startup.args) |> Maybe.with_default("world")}) end fn main() io.print("Hello, ${App.name}!") // Hello, world! end
The boot’s signature is checked:
| Violation | Error |
|---|---|
Any parameters but none or one Startup | boot must be `fn boot() -> Result<App, E>` or `fn boot(startup: Startup) -> Result<App, E>`, taking no parameter or one Startup and returning the application struct in a Result |
A result that is not a Result of a struct | boot must return `Result<App, E>`: the application struct, or the error that stops the program |
Two Context fields | an application struct may have at most one Context-typed field |
fn boot in a file with no fn main | `boot` belongs in an entry file, one that defines `fn main`; a `group` names an entry's boot with `boot entry.boot(startup)` |
| A call of boot outside a test, or a reference to it as a value | entry-point boot cannot be called or captured as an ordinary function; a `group` calls it on its `boot` line, and a test may call it to check the Result it returns |
An entry boot is called in two places: a group’s boot line, which publishes the app for the group’s tests (§17 Groups), and a test, which calls it as an ordinary function to check the Result it returns (§17 Calling boot in a test). A test file names the boot through an import of its entry file, so a boot that tests run is pub, and so is its struct.
Reading a field
Section titled “Reading a field”App.field reads one top-level field of the application value in force. T.field is a field read only when T is an application type, which the checker learns from the project’s entry boots: the entry file’s own and those of the entry files it imports. A file that reads a field imports the type as it imports any name. On an application type, App.field always names the field, so the type may not declare an inherent function or once with a field’s name: `App` is an application type, so `App.n` reads its field `n`; rename this member. On any other type, Type.member keeps its owner-qualified meaning.
Taught in App Fields, Defer & Context.
with App.field = expr is a statement that replaces one field from that line to the end of the enclosing block: the extent a defer on the same line would have. Every function called in that extent reads the replacement. However the block exits (its end, return, ?, a failure), the previous value comes back. The value must have the field’s type, and a .Variant value resolves against it. A struct literal needs no parentheses: with App.store = FakeStore{}.
Several fields take several lines. Each value is evaluated when its line runs, so a later line reads what an earlier one replaced:
fn in_region() with App.region = "eu" with App.endpoint = "https://${App.region}.example.com" sync() end
with works in any block: a function body, an if or case arm, a begin block, a lambda body, a test body, a group’s setup. It has no value and takes no block. To limit an override to part of a function, put the line in a begin block or a helper function. There is no override of the whole application value or of a nested field; replace a structured field with an update, with App.database = {..App.database, host: "localhost"}.
| Violation | Error |
|---|---|
| A comma after the value | a `with` statement replaces one field; write one `with` line per field |
A { after the value on its line | `with` is a statement and takes no block: the override lasts to the end of the enclosing block |
| A target that is not an application field | `with` replaces an application field, such as `MyApp.logger`; `Point.x` is not one |
| A value of the wrong type | `App.port` replacement expects Int, got String |
An override changes the fields in force; it does not change values already computed. A closure reads the fields in force when it is called, not when it was created. A task started with Task.spawn takes a snapshot of the fields in force when it starts.
import std::io struct App greeting: String end fn boot() -> Result<App, String> Ok(App{greeting: "hello"}) end fn greet() -> String "${App.greeting}, world" end fn quiet_greeter() -> () -> String with App.greeting = "psst" io.print(greet()) // psst, world fn -> greet() end fn main() later = quiet_greeter() io.print(later()) // hello, world end
Which boot code runs under
Section titled “Which boot code runs under”Each entry’s main runs under its file’s boot, or none, and each test under its group’s boot line, or none (§17 Groups). A boot must return the application type that every field read reachable from the code it runs names: the main or test body, a group’s setup, and every function they call, across files and through callbacks and lambdas. Code that reads no field runs under any boot or none.
| Violation | Error |
|---|---|
| A read of another application type | this test boots `Fake`, but code it runs reads `MyApp.logger` (server.nomi:2), at the boot |
| A read with no boot | this program has no boot, but code it runs reads `App.n` (main.nomi:4) at main, or this test has no boot, but code it runs reads `MyApp.logger` (server.nomi:10) at the test |
| A read of a type no entry boot returns | `App.port` reads an application field only when an entry boot returns `App`, and no `fn boot` in this project does; check the entry file that boots it |
| Reads of two application types | code this program runs reads `App.port` (main.nomi:12) and `Other.n` (other.nomi:4); one boot publishes one application type |
A read during boot, or in a boot line’s argument | boot runs before any application field is published, but code it runs reads `App.port` (main.nomi:4) |
The runtime finds the Context field by its type, so a field named execution is read and replaced as App.execution and gets the same protections.
Cleanup and boot failure
Section titled “Cleanup and boot failure”Taught in App Fields, Defer & Context.
A defer in the outer block of an entry boot runs after main returns and the tasks it owns have stopped. A defer in a test’s boot or setup runs after that test and its work, and so does one in a boot a test calls directly. A defer anywhere else runs when its block ends. A deferred call keeps the arguments and the field values in force when it was registered. A failing cleanup does not hide the first failure or stop the rest of the cleanup.
A boot that returns Err(e) fails the program: main does not run, work boot started is stopped, the calls boot registered with defer run, most recent first, and the program exits as one whose main returned Err(e) does (Exit status above). A program with exported functions returns that error in place of the booted program (§7 Exported Functions). In a group, a boot that returns Err fails each test it serves before the body runs, with the report of an early ? (§17 Groups). A trap in boot is a trap like any other.
import std::io struct App name: String end fn boot(startup: Startup) -> Result<App, String> defer io.print("boot cleanup") name = List.first(startup.args) |> Maybe.to_result("pass a name")? Ok(App{name:}) end
Run with no arguments, a program with this boot prints boot cleanup, then error: pass a name on standard error, and exits 1.
Context
Section titled “Context”Taught in App Fields, Defer & Context.
A Context is an opaque value that carries a deadline and execution-scoped values through a call chain. Only the runtime, Context.root() and the Context.with_* derivers make one. A deadline is the only control state it carries. Stopping a task (Task.cancel, a supervisor’s drain, shutdown) travels with task ownership and takes effect at safe points (§16 Safe points); it is never written onto a Context.
A program holds its context in the application type’s Context field and replaces it with with:
struct Config context: Context end fn handle(req: Request) -> Response with Config.context = Context.with_timeout(Config.context, Duration.seconds(30)) do_expensive_work(req) end
The context is a field rather than an ambient value so that each with line is the one place a deadline is fixed: the runtime derives one wait context there for every blocking operation in its extent, not one per read. An embedder’s cancellation and an inherited deadline stay in force when a program replaces its context field.
Context values
Section titled “Context values”A context value is metadata that follows the current unit of work: a trace ID, an auth subject, a request ID. It is not how a program passes dependencies (use application fields such as App.store) or a locale (pass a Locale, std::locale).
A value’s Nomi type is its key. Context.with_value(c, v) returns a child of c holding v under v’s type, and Context.value(c, TraceId) the nearest value of that type from c up through its ancestors; TraceId there is a type witness (§4 Type witnesses). std::context has the functions.
import std::io type TraceId String struct App context: Context end fn boot() -> Result<App, String> Ok(App{context: Context.root()}) end fn main() with App.context = Context.with_value(App.context, TraceId("trace-123")) case Context.value(App.context, TraceId) Some(TraceId(id)) -> io.print("trace ${id}") // trace trace-123 None -> io.print("no trace") end end
The functions of Context are in std::context.