.nib std
nib 0.3.1-pre

Pre-release documentation. This describes nib 0.3.1-pre, which is on main and has no release yet: what it documents beyond 0.3.0 may change before it ships.

module always in scope

Switch

A scope for concurrent fibres. Switch.run opens one, fork starts fibres in it, and the scope does not end until every fibre it started has finished.

A Switch is the scope that fibres live in. Switch.run opens one and hands its body the Switch; inside, fork(sw) { -> … } starts a fibre under it and answers the fibre's Fiber handle. When the body has answered, Switch.run waits for every fibre forked under the switch before it returns, so no fibre outlives the scope that started it — the structure of the code is the structure of the concurrency, and a function that opens a switch has finished all of its work when it returns.

Switch.run { sw ->
  let _ = fork(sw) { -> @Io.Print.print("a ") };
  let _ = fork(sw) { -> @Io.Print.print("b ") };
  "the body answered first; "
}
a b the body answered first; 

fork takes the switch and a block of no arguments that answers (), either trailing (fork(sw) { -> … }) or inside the parentheses (fork(sw, { -> … })). A fork body may not raise: a tag in its row is refused, because once the fibre has started there is no caller left to catch it. The fibres take turns on one executor, in the order they were forked; see Fiber for when a fibre runs and how to wait for one.

A Switch has no literal and is only good inside its own Switch.run: it prints as Switch(#<n>), a diagnostic number.

Functions

funcrun
Switch.run :: body: (Switch -> 'a raises R) -> 'a raises R

Opens a switch, runs body with it, waits for every fibre forked under it, and answers what the body answered. A raise from the body goes on to the caller, after the fibres have finished and the switch's cleanups (Switch.defer) have run. The body is a block (Switch.run { sw -> … }) or any function of type Switch -> 'a:

module Demo where
  func body :: sw: Switch -> Int =
    let _ = fork(sw) { -> () };
    42

  func main :: -> Int = Switch.run(Demo.body)

wire W runs Demo.main
42

The switch is how a fibre is reached, so a function that should start fibres takes the Switch as a parameter, and its caller decides which scope they belong to:

use "std/io.nib"

module Jobs where
  func start :: sw: Switch, name: String -> () ! Io.Print =
    let _ = fork(sw) { -> @Io.Print.print("{name} ") };
    ()

  func main :: -> String ! Io.Print =
    Switch.run { sw ->
      let _ = Jobs.start(sw, "one");
      let _ = Jobs.start(sw, "two");
      "started; "
    }

wire W runs Jobs.main where Io.Print = Io.Stdout
one two started; 

A fork body handles its own failures. It cannot raise, and everything it can fail by on its own is a raise — a division by zero is Err.DivisionByZero, an index out of range Err.IndexOutOfRange — so the checker refuses a body that leaves one unhandled (a fork body cannot raise (Err.DivisionByZero)), and the body catches it instead:

let zero = Vec.size(#[]) + 0;
Switch.run { sw ->
  let f = fork(sw) { ->
    let _ = try 10 / zero rescue Err.DivisionByZero(_) => 0 end;
    () };
  let _ = Fiber.await(f);
  "the fibre handled it"
}
the fibre handled it

What is left — memory or the step limit run out, an internal failure — is a runtime error, which is fatal: no arm takes it and no cleanup runs.

funcdefer
Switch.defer :: sw: Switch, cleanup: (Option<Failure<R>> -> ()) -> ()

Attaches a cleanup to the switch sw, written where the thing to clean up is made. Cleanups run when the switch closes — after its body and every fibre it forked — newest first, whether the body answered or failed. Each is handed the outcome: None when the body answered, Some(f) when a raise ended it, where f is that Failure and R is the row of the body's raises. After the cleanups, the raise goes on to the caller.

use "std/io.nib"
use "std/option.nib"

data Timeout where Timeout(Int)

module Batch where
  func work :: n: Int -> Int raises Timeout =
    if n == 0 then raise Timeout(5) else n

  func run :: n: Int -> Int ! Io.Print raises Timeout =
    Switch.run { sw ->
      let _ = @Io.Print.print("begin; ");
      let _ = Switch.defer(sw) { outcome ->
        match outcome
          None => @Io.Print.print("commit; ")
          Some(f) => @Io.Print.print("rollback after {Failure.tag(f)}; ")
        end };
      Batch.work(n)
    }

  func main :: -> String ! Io.Print =
    let a = try Batch.run(1) rescue Timeout(ms) => 0 end;
    let b = try Batch.run(0) rescue Timeout(ms) => ms end;
    "answers {a} and {b}"

wire W runs Batch.main where Io.Print = Io.Stdout
begin; commit; begin; rollback after Timeout; answers 1 and 5

A cleanup that ignores the outcome writes { _ -> … }. A cleanup may not raise, since nothing is left to catch it, and its effects are charged to the Switch.run. It is written inside the Switch.run whose switch it names, because the outcome's type is that switch's row. A runtime error — memory or the step limit run out, a trap — runs no cleanups: it leaves no state a cleanup could safely run on, so the program stops where it is.