Home / Learn / 12 Capabilities
12.4 Passing authority: with, rebinding and narrowing
Page 5 of 10
12.4.1 What passing authority means
A capability moves from a caller to a callee, and only that way. A store manager lends a colleague a key for one errand: the colleague uses it for that errand and hands it back. They cannot copy it, keep it in a drawer, or give it to a stranger. In Una, the caller is the manager, the callee is the colleague, and the errand is one call.
Three things can happen at a call:
- By name. The callee's header asks for
@customers, and the caller holds a@customers. It is handed over with nothing written at the call. - Rebinding. The callee asks for
@audit, and the caller holds the same capability under another name,@console.with @audit = @consolehands it over under the callee's name. - Installing. The caller holds no such capability, or wants another provider.
with @customers = directory(customers)installs a handler.
And whatever the callee receives, it may use only the operations its own header lists: authority narrows on its way down.
A capability can also travel inside a function that is passed as an argument, such as a lambda that prints. Edition 0.2 lets a header say so, with uses of, as Authority inside a function argument shows.
12.4.2 Why authority moves only downward
If a capability were a value, a function could keep it: store it in a record, return it, or pass it to code that its header never mentions. A reviewer would then have to follow every value to know who can print or send mail. Una forbids it. Try to keep the console in a variable:
module slips
pub main() -> Unit
uses @console: Console[print]
=
let saved = @console
saved.print("Packing slip for order A-1001")[U3005] Error: capability `@console` is used as a value; capabilities pass by name, through `uses` and `with`
╭─[ src/slips.una:6:15 ]
│
6 │ let saved = @console
│ ────┬───
│ ╰───── capability `@console` is used as a value; capabilities pass by name, through `uses` and `with`
│
│ Note: run `una explain U3005` for an explanation
───╯U3005 says that the capability is "used as a value", and how capabilities move instead: "by name, through uses and with". Because a capability never travels any other way, every function's reach is in its header, and in the headers of the functions that call it.
12.4.3 How to write with
12.4.3.1 Passing by name: nothing to write
When the names match, write nothing. main holds @console, and print_line in section 12.1 asks for @console, so print_line("LAMP-01", quantity: 2) passes it.
12.4.3.2 Rebinding: with @x = @y
with, at the end of a statement, then the callee's name, = and the caller's binding. Both must be the same capability, and the caller's binding must permit at least the operations the callee lists.
12.4.3.3 Installing a handler: with @x = handler(args)
The callee's name, = and a call of a handler for the capability the callee needs at that name. The handler's own uses must be held by the caller.
12.4.3.4 Several bindings
One with takes several bindings, separated by commas: with @customers = directory(customers), @audit = @console.
12.4.3.5 How far with reaches
A with belongs to the statement it ends, or to the let it ends, and to nothing after it. The next statement gets its bindings by name again, or from its own with.
| Write | The callee's @x is |
|---|---|
| nothing | the caller's @x, if it has one |
with @x = @y |
the caller's @y, which has the same capability |
with @x = handler(args) |
a new instance of that handler |
12.4.4 Narrowing: a greeting that may only look up
In this step, the customer directory has two operations, looking a customer up and erasing one. The page greeting may look up, and only the erase request may erase:
module accounts
kind Customer
id: Text
name: Text
--- The customer directory. Looking a customer up and erasing one are separate operations.
capability Customers
op find(id: Text) -> Option[Customer]
op forget(id: Text) -> Unit
--- The greeting on an order page. It may look customers up, and never erase one.
greeting(id: Text) -> Text
uses @customers: Customers[find]
=
let customer = @customers.find(id)
if none use Customer(id: id, name: "guest")
"Welcome back, {customer.name}"
--- Erases a customer at their request, and writes the request to the audit trail.
erase(id: Text) -> Unit
uses @customers: Customers[forget]
uses @audit: Console[print]
=
@customers.forget(id)
@audit.print("audit: erased customer {id}")
--- A directory held in memory. It is a fixed value, so `forget` changes nothing here.
handler directory(customers: Map[Text, Customer]) for Customers
op find(id) = customers.get(key: id)
op forget(id) = unit
pub main() -> Unit
uses @console: Console[print]
=
let customers = empty_map().with(key: "C-17", value: Customer(id: "C-17", name: "Rosa"))
let page = greeting("C-17") with @customers = directory(customers)
@console.print(page)
let unknown = greeting("C-99") with @customers = directory(customers)
@console.print(unknown)
erase("C-20") with @customers = directory(customers), @audit = @consolecapability Customerswithfindandforget. Two operations with different risks. Neither has afailsclause: these two cannot fail.uses @customers: Customers[find]ongreeting. Thedirectoryhandler implements both operations, butgreetingholds onlyfind. An@customers.forget(id)in its body would not check.if none use Customer(id: id, name: "guest").findreturns anOption, so the handling clauses of section 7.3 apply to an operation as to any call.uses @audit: Console[print]onerase. The audit trail is a console here, under the name@audit, so the header says what the console is for.let page = greeting("C-17") with @customers = directory(customers). Awithat the end of alet: it installs the handler for that call. The line above it,empty_map().with(key: …, value: …), is something else: the map method of section 10.4 that adds an entry, not thewithclause.with @customers = directory(customers), @audit = @console. Two bindings. The first installs a handler. The second is a rebinding: the callee's@auditis the caller's@console.mainholds no@auditof its own, so without the rebinding the call would not check.
una run . prints:
Welcome back, Rosa
Welcome back, guest
audit: erased customer C-2012.4.5 How with behaves
12.4.5.1 A callee holds only what its header lists
A callee may receive a binding with more operations than it needs. It then holds only the operations its own header lists. directory can forget customers, but inside greeting the binding permits find and nothing else.
12.4.5.2 Each installation is a new instance
Each with @customers = directory(customers) installs a new instance. A handler holds no state between calls, and directory takes its map as a parameter, so forget has nothing to change here. A handler for a real directory would call the service.
12.4.5.3 Where a handler's own capabilities come from
A handler installed with with takes its own uses from the code around the statement, by name. printed, in section 12.3, holds @console because main, which installs it, holds @console.
12.4.5.4 A binding of the wrong capability
A rebinding needs the same capability on both sides, and a handler must implement the capability the callee needs at that name. Installing a Customers handler as @mailer is U3010, as installing a handler of another capability shows.
12.4.5.5 Checking that authority narrows
Important
Narrowing is a promise you can check. Because greeting holds Customers[find], no change to its body can make it erase a customer without a change to its header, which a reviewer sees.
12.4.6 Authority inside a function argument: uses of
12.4.6.1 What a function argument may carry
A function can take another function as an argument (section 10.2): each_sku below runs an action once for each SKU of a shelf. The function it receives, often a lambda, may do something outside the program, such as print a label. Then the effect happens inside each_sku, so its header must say so.
12.4.6.2 Why the parameter's type is not enough
The type fn(Text) -> Unit says nothing about effects, and a function type with no uses is pure. Pass a lambda that prints:
module shelf
--- Runs `action` once for each SKU of a shelf. Its parameter's type says nothing about
--- effects, so `action` must be pure.
pub each_sku(skus: List[Text], action: fn(Text) -> Unit) -> Unit
=
for sku in skus
action(sku)
pub main() -> Unit
uses @console: Console[print]
=
each_sku(["LAMP-01", "DESK-02"], action: fn(sku) -> @console.print("label {sku}"))[U3004] Error: `@console` is used in a lambda whose type declares no `uses`, so the lambda is pure; pass it directly as an argument for a parameter whose type or `uses of` clause allows the effect
╭─[ src/shelf.una:13:55 ]
│
13 │ each_sku(["LAMP-01", "DESK-02"], action: fn(sku) -> @console.print("label {sku}"))
│ ────┬───
│ ╰───── `@console` is used in a lambda whose type declares no `uses`, so the lambda is pure; pass it directly as an argument for a parameter whose type or `uses of` clause allows the effect
│
│ Note: run `una explain U3004` for an explanation
────╯U3004 marks @console inside the lambda: the lambda's type comes from the parameter, fn(Text) -> Unit, which declares no uses, so the lambda is pure. The message also names the way out: a parameter "whose type or uses of clause allows the effect". Writing uses @console: Console[print] on each_sku would be wrong too: each_sku does not print, its argument does, and another caller may pass an action that writes a file instead.
12.4.6.3 How to write uses of
uses of action means "this function may do whatever action does". It is the twin of fails of action, which section 7.2 taught: "this function fails as action fails". uses of goes among the uses lines, and fails of goes where fails goes. Both exist from edition 0.2 on. The parameter's type is written without uses or fails of its own:
module shelf
--- Runs `action` once for each SKU of a shelf. It may do what `action` does, and fails as
--- `action` fails.
pub each_sku(skus: List[Text], action: fn(Text) -> Unit) -> Unit
uses of action
fails of action
=
for sku in skus
action(sku)
if error pass
--- Saves a shelf label to a file of its own.
save_label(sku: Text) -> Unit
uses @files: Files[write]
fails FileError
=
@files.write("{sku}.txt", content: "label {sku}")
if error pass
pub main() -> Unit
uses @console: Console[print]
uses @files: Files[write]
=
each_sku(["LAMP-01", "DESK-02"], action: fn(sku) -> @console.print("label {sku}"))
let saved = attempt each_sku(["LAMP-01", "DESK-02"], action: save_label)
@console.print("saved: {saved}")una run . prints:
label LAMP-01
label DESK-02
saved: Ok(unit)12.4.6.4 How it behaves
- The caller pays. At each call, the effects of
each_skuare its ownusesplus those of the argument given foraction. The first call inmainprints, somainmust hold@console; the second saves files, somainmust hold@files. Each lambda runs on the bindings of the code where it is written. - A named function works too. The second call passes
save_labelby its name. It writes a file and can fail withFileError, andmainholds@files, so the call checks. - One error kind.
fails of actionletseach_skufail with whatever the argument fails with: nothing for the printing lambda,FileErrorforsave_label, whichattemptkeeps as a value. - Nothing escapes. Inside
each_sku,actionmay only be called, or passed on to a parameter that is itself named by anofclause. It cannot be stored or returned, so the authority it carries never outlives the call. - Private functions infer it. A private function without
usesgetsuses of pinferred for a function parameterpthat its body only calls.
12.4.7 Pass, rebind or install
Which to use:
| At the call… | Write |
|---|---|
| The caller holds the capability under the callee's name | Nothing |
| The caller holds it under another name | with @callee_name = @caller_name |
| The caller must choose a provider, or holds none | with @x = handler(args) |
| The caller wants the callee to use fewer operations | Nothing: the callee's header already limits it |
| The callee runs a function it is given, which may have effects | uses of p and fails of p on the callee (edition 0.2) |
Name bindings after what they are for, as @audit and @log are. A rebinding at the call then reads as a decision: "the audit trail is the console, here".
Edition 0.3 adds limits on top of these rules: a condition on an operation, such as "never in a dry run" (section 13.1); a ceiling on what a module may receive (section 13.2); a narrower rebinding at the call, with @x = @y[ops] (Granting less at the call); and a lock in una.toml on the uses of a public function, so that its header may never grant more (section 13.3). Chapter 13 teaches them.
12.4.8 Check yourself: with
In the step, remove @audit = @console from the last line of main, so that it reads erase("C-20") with @customers = directory(customers). Does it check?
Show the answer
No. erase needs @audit: Console[print], and main holds no binding named @audit: bindings are found by name, never by type, so @console does not count. una check . reports U3001 at the call, as forgetting to hand over a binding shows for the day-to-day program.
A second one: main in Authority inside a function argument gives each_sku the function save_label, which writes files. Remove uses @files: Files[write] from the header of main. Does it check?
Show the answer
No. With uses of action, a call of each_sku performs the effects of its argument, so the second call writes files on behalf of main, through save_label, which needs @files, and main no longer holds it. una check . reports U3001, as for any binding that is not in scope: authority still comes only from the caller's header.