Home / Learn / 8 Choosing

Release v0.4.0Edition 0.2

8.3 What a branch proves: guards

Page 4 of 10

8.3.1 What a branch knows

Inside a branch, the verifier knows why the program is there. In the then branch of if units > 0, it knows that units > 0 holds; in the else branch, that it does not. In an arm in 1..12, it knows that the subject is between 1 and 12, and in an arm is Returned, that the subject is that variant. These are the facts of the path: what is known at a point of the code because of the conditions that lead to it.

A guard is a condition you write so that a branch has the fact a step needs. Think of a cashier who checks that a customer is old enough before selling a bottle: the sale happens only after the check, and only there. Section 3.4 used one to divide safely. This section shows every way a guard gives a fact, how far that fact reaches, and when a guard is the right tool, rather than a precondition or a refined kind.

8.3.2 Why a guard is needed

Section 2.2 showed that a division by a value that is not a literal is a proof obligation: the verifier must show the divisor is never 0. Here is a price per unit without any guard:

src/guards.unadiff
--- a/src/guards.una
+++ b/src/guards.una
@@ -8 +8 @@
-per_unit(pack_cents: Int, units: Int) -> Int = if units > 0 then pack_cents / units else 0
+per_unit(pack_cents: Int, units: Int) -> Int = pack_cents / units
Diagnostic
[U5001] Error: division obligation `units != 0` is refuted
   ╭─[ src/guards.una:8:48 ]
   │
 8 │ per_unit(pack_cents: Int, units: Int) -> Int = pack_cents / units
   │                                                ─────────┬────────
   │                                                         ╰────────── division obligation `units != 0` is refuted
   │ Help: repair 1: guard the division with `if units != 0`
   │ Note 2: counterexample: units = 0

The verifier knows nothing about units, so it finds a value that breaks the division: units = 0, the counterexample. Nothing has gone wrong yet; the program has not run. But a pack recorded with 0 units would stop the run at that line, so una refuses the function until the code says what happens then. The Help line proposes the repair: a guard.

8.3.3 How to write a guard

The step of this section prices one unit of a pack in four ways, each with its own guard, and its main prints each price for a pack of 4 units, then for an empty pack:

src/guards.unacheckrununa
module guards

--- Why a pack has no price per unit.
kind PackError = | NoUnits

--- The price of one unit of a pack, or 0 for an empty pack. The division is in the branch
--- where `units > 0` holds.
per_unit(pack_cents: Int, units: Int) -> Int = if units > 0 then pack_cents / units else 0

--- The same price, failing for an empty pack. The branch that fails never reaches the
--- division, so after the `if`, `units == 0` is false.
per_unit_or_fail(pack_cents: Int, units: Int) -> Int
  fails PackError
=
  if units == 0
    fail NoUnits
  pack_cents / units

--- The same price, dividing by a count that a guard keeps from being 0.
per_unit_counted(pack_cents: Int, units: Int) -> Int
=
  let count = if units > 0 then units else 1
  pack_cents / count

--- The same price for a pack of 1 to 12 units. Inside the range arm, `units` is never 0.
per_unit_boxed(pack_cents: Int, units: Int) -> Int
=
  when units
    in 1..12 -> pack_cents / units
    else -> 0

--- Prints each guarded price for a pack of 4 units, then for an empty pack.
pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("{per_unit(1_000, units: 4)}, {per_unit(1_000, units: 0)}")
  let full = per_unit_or_fail(1_000, units: 4)
    if error use -1
  let empty = per_unit_or_fail(1_000, units: 0)
    if error use -1
  @console.print("{full}, {empty}")
  @console.print("{per_unit_counted(1_000, units: 4)}, {per_unit_counted(1_000, units: 0)}")
  @console.print("{per_unit_boxed(1_000, units: 4)}, {per_unit_boxed(1_000, units: 0)}")
Output
250, 0
250, -1
250, 1000
250, 0

8.3.3.1 A guard with a fallback value

per_unit divides only in the then branch, where units > 0 holds, and gives 0 in the else branch. This is the guard of section 3.4: the condition is the fact the division needs, or a stronger one.

8.3.3.2 A guard that fails

per_unit_or_fail has an if without else whose branch fails, as in section 8.1. The branch that fails never reaches the lines after the if. So on the line after it, the verifier knows that units == 0 was false, and the division is proven, outside any branch. The empty pack fails with NoUnits, and main recovers with -1.

8.3.3.3 A guard that picks a safe value

per_unit_counted uses the guard to choose the divisor: let count = if units > 0 then units else 1. The verifier knows the value of each branch under its condition, so it knows that count is units when units > 0 and 1 otherwise, and never 0. The empty pack is priced as a pack of one, 1000.

8.3.3.4 A range arm

per_unit_boxed divides inside an arm in 1..12. The arm gives the fact units is between 1 and 12, which rules out 0 as well as any condition would.

8.3.4 Proving a product with a guard

A guard can also give a fact that the verifier cannot work out for itself. Section 5.4 showed that the solver cannot read a product of two values: for unit_cents * quantity, it cannot prove that the result is not negative, even when both factors are not, and it reports U5002. The first repair is a guard:

src/invoice.unacheckrununa
module invoice

--- An amount of money in cents. It is never negative.
kind Cents = Int where it >= 0

--- One line of an invoice.
kind Line
  sku: Text
  unit_cents: Cents
  quantity: Int in 1..99

--- Loyalty points: one for each whole 1.00 spent.
points(total: Cents) -> Int
  ensures result >= 0
  ensures result * 100 <= total
=
  total / 100

--- What one line costs. The guard handles a case that cannot happen, since both factors
--- are at least 0; the solver cannot see that for itself.
line_total(line: Line) -> Cents
=
  let total = line.unit_cents * line.quantity
  if total < 0 then 0 else total

pub main() -> Unit
  uses @console: Console[print]
=
  let desk = Line(sku: "DESK-02", unit_cents: 14900, quantity: 2)
  let total = line_total(desk)
  @console.print("{total} cents, {points(total)} points")
  1. kind Cents = Int where it >= 0. A refined kind of section 5.3: an amount that is never negative. line_total promises a Cents, so its result must be proven to be at least 0.
  2. points. Division by the literal 100 is linear, so the verifier proves both clauses with no help. result * 100 is allowed in a clause: one side is a literal.
  3. let total = line.unit_cents * line.quantity. The product, named. The verifier knows nothing of its sign.
  4. if total < 0 then 0 else total. In the else branch, the verifier knows total >= 0, so the result is a Cents. The then branch gives 0, which is a Cents too.

una run . prints:

Output
29800 cents, 298 points

The then branch never runs, since both factors are at least 0. The verifier does not check that claim: it proves the result whichever branch runs. You check it, from the kinds of the factors, and when one of those kinds changes, you read the guard again. The guard costs one comparison at run time.

8.3.5 How a guard behaves

8.3.5.1 The fact holds only on its path

A fact holds inside its branch, and after an if only when the other branch can never get there, as with fail. Once both branches of an if have joined, the condition is no longer known. Keep the guarded count of per_unit_counted, but divide by units:

src/guards.unadiff
--- a/src/guards.una
+++ b/src/guards.una
@@ -22,3 +22,3 @@
   let count = if units > 0 then units else 1
-  pack_cents / count
+  pack_cents / units
 
Diagnostic
[U5001] Error: division obligation `units != 0` is refuted
    ╭─[ src/guards.una:23:3 ]
    │
 23 │   pack_cents / units
    │   ─────────┬────────
    │            ╰────────── division obligation `units != 0` is refuted
    │ Help: repair 1: guard the division with `if units != 0`
    │ Note 2: counterexample: count = 1, units = 0

The counterexample, count = 1, units = 0, is a run that took the else branch: count is 1, and units is still 0. The guard protected count, not units. This is what makes guards safe to edit: a division moved out of the branch that guards it fails its proof at once.

8.3.5.2 A weak condition proves nothing

The condition must rule out every bad value. Weaken the guard of per_unit to units >= 0:

src/guards.unadiff
--- a/src/guards.una
+++ b/src/guards.una
@@ -8 +8 @@
-per_unit(pack_cents: Int, units: Int) -> Int = if units > 0 then pack_cents / units else 0
+per_unit(pack_cents: Int, units: Int) -> Int = if units >= 0 then pack_cents / units else 0
Diagnostic
[U5001] Error: division obligation `units != 0` is refuted
   ╭─[ src/guards.una:8:67 ]
   │
 8 │ per_unit(pack_cents: Int, units: Int) -> Int = if units >= 0 then pack_cents / units else 0
   │                                                                   ─────────┬────────
   │                                                                            ╰────────── division obligation `units != 0` is refuted
   │ Help: repair 1: guard the division with `if units != 0`
   │ Note 2: counterexample: units = 0

The counterexample, units = 0, passes the new condition and still divides by zero. The Help line proposes a guard, if units != 0, which is exactly what a correct condition must imply.

8.3.5.3 Facts do not cross a call

The verifier proves each function on its own, with the facts of its own paths. A guard in a caller tells the callee nothing: a function that divides by its parameter needs its own guard, or a requires that every caller must prove (section 5.1). A fact reaches another function only through a header, as section 5.4 said.

8.3.5.4 is gives the variant, not its fields

The condition status is Returned gives the fact that status is that variant, but, as section 4.3 showed, the checker does not let you read its fields after it. To use the fields of a variant, bind them in a when arm.

8.3.6 A precondition, a guard or a kind

All three state a rule about a value. Choose by who can keep the rule:

Which to use:

The bad value… Use
Is a mistake of the caller, which can always avoid it, such as 0 months of installments requires: every caller proves it (section 5.1)
Can come from a person or another system A guard in the function that receives it, or a failure (section 7.6)
Is a normal case with a sensible answer, such as an empty pack A guard with a fallback value
Is impossible by the type already Nothing: a refined kind (section 5.3) carries the fact
Holds of every value of a kind, everywhere A refined kind, instead of the same guard in many functions
Is ruled out by the factors, but the solver cannot see it, as for a product A guard that the program never takes, as in line_total
Can only be decided by running code, such as the format of a text checked with an opaque predicate (section 7.5)

A precondition moves the work to the callers: each one must show the condition. That is right when the condition is the caller's to keep. When the value comes from outside the program, no caller can promise anything about it, and the function that receives it must check it. And when the same rule holds everywhere, a refined kind says it once.

8.3.7 Check yourself: guards

Here is per_unit with another guard:

src/guards.unauna
--- The price of one unit of a pack, or 0 for an empty pack. The division is in the branch
--- where `units > 0` holds.
per_unit(pack_cents: Int, units: Int) -> Int = if units < 0 then 0 else pack_cents / units

Does it check? If not, what is the counterexample?

Show the answer

No:

Diagnostic
error U5001 at src/guards.una:8:73: division obligation `units != 0` is refuted
  counterexample: units = 0

The guard rules out negative units, which is not the fact the division needs. units = 0 is not below 0, so it takes the else branch, which divides by it. The guard must rule out 0: if units <= 0 then 0 else pack_cents / units checks.

Next:8.4 Kinds that contain themselves