Home / Docs / Language guide / Capabilities and effects

handler

Release v0.4.0Edition 0.1 and laterU2001U3008U3009U3010U3011U5001

What it does

A handler implements a capability in Una: it gives a body to each operation. A caller installs it for one statement with with, or an example (a test written next to the code) installs it with given, so code that needs the capability runs against the handler instead of the outside world, as a fake store does in a test. Handler bodies are ordinary Una code, fully checked and verified (their contracts proved by the checker).

Learn more: Your own capabilities and handlers.

una
module shop

pub capability Store
  op get(key: Text) -> Text

handler fixed(value: Text) for Store
  op get(key) = value

read(key: Text) -> Text
  uses @store: Store[get]
=
  @store.get(key)

pub preview_name() -> Text
=
  let name = read("LAMP-01") with @store = fixed(value: "Desk lamp")
  name

Forms

In the grammar below, each rule gives a name, =, what the name stands for and ;, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, [ ] marks an optional part, { } a part that may repeat, | separates alternatives, ( ) groups them, and (* *) holds a comment.

ebnf
handler_decl    = [ "pub" ] "handler" lower_ident "(" [ params ] ")" "for" upper_ident NEWLINE
                  INDENT { "uses" cap_ref ":" cap_type NEWLINE }
                  handler_op { handler_op } DEDENT ;
handler_op      = "op" lower_ident "(" [ lower_ident { "," lower_ident } ] ")"
                  "=" inline_or_block ;

Examples

A handler implements every operation of its capability:

una
-- fails with U3011
module shop

pub capability Store
  op get(key: Text) -> Text
  op put(key: Text, value: Text) -> Unit

handler fixed(value: Text) for Store
  op get(key) = value

A handler body must keep the operation's ensures, which callers rely on:

una
-- fails with U5001
module shop

pub capability Store
  op get(key: Text) -> Text
    ensures result.len > 0

handler blank() for Store
  op get(key) = ""

Edge cases

Only the capability's operations:

una
-- fails with U3010
module shop

pub capability Store
  op get(key: Text) -> Text

handler fixed(value: Text) for Store
  op get(key) = value
  op extra(key) = value

for names a capability:

una
-- fails with U3010
module shop

pub kind Address
  street: Text

handler shipping() for Address
  op get(key) = key

Failures of the operation's kind only. An operation body fails only with its operation's error kind, and passes only an equal kind (U3008):

una
-- fails with U3009
module shop

pub kind StoreError = | Timeout

pub kind PaymentError = | Declined

pub capability Store
  op get(key: Text) -> Text
    fails StoreError

handler broken() for Store
  op get(key) = fail Declined

Further rules:

Diagnostics

Edition

Handlers are the same in editions 0.1 and 0.2.

Normative source