Home / Learn / 19 Editions

Release v0.4.0Edition 0.1, 0.2, 0.3, 0.4

19.3 Edition 0.3, a preview

Page 4 of 11

19.3.1 What a preview is

A preview is an edition that is still being completed. Its rules arrive one by one, release after release, until every rule planned for it has landed. You can use it today, and in exchange you accept that a later release may reject code it accepts now.

19.3.2 Why a preview exists

Some rules are worth having before all of their companions are ready. A dry run that the checker proves, as the day-to-day program of this chapter has, is useful the day it lands. A preview lets a package opt into those rules early, and lets the rules be tried on real code before the edition becomes stable. A package that does not opt in sees none of it: edition 0.2 keeps its promise.

19.3.3 What edition 0.3 adds

Edition 0.3 adds constructs that narrow what a program may do, rules that reject code that can never run, and one rule that accepts code that 0.2 rejects, refined type arguments:

The day-to-day program uses the first two, and writes its tests with test (section 19.7). The rest of this section shows units, refined type arguments and the rules on failure handling.

19.3.4 Units of measure

A number alone does not say what it counts. 1200 can be grams, cents or units on a shelf, and adding grams to cents is a mistake that no type of 0.2 catches. In 0.3, a unit is part of the type.

19.3.4.1 A base unit: measure Gram

steps/10-parcel/src/parcel.unacheckrununa
module parcel

--- A unit of weight.
measure Gram

--- What one lamp weighs.
lamp_weight() -> Int of Gram = 1200

--- The weight of a parcel of `units` lamps.
parcel_weight(units: Int) -> Int of Gram = units * lamp_weight()

pub main() -> Unit
  uses @console: Console[print]
=
  let weight = parcel_weight(3)
  let limit: Int of Gram = 5000
  @console.print("{weight} grams, within the limit: {weight <= limit}")
Output
3600 grams, within the limit: true
  1. measure Gram. Declares a base unit, one that is not defined from another, at the top level of a module.
  2. -> Int of Gram. of after an integer type gives it a unit. Int of Gram is a type of its own: neither Int nor any other unit.
  3. = 1200. A literal number takes the unit its place expects, so 1200 here is 1200 grams.
  4. units * lamp_weight(). * multiplies the units: a plain count times grams is grams. +, -, mod and the comparisons need the same unit on both sides.

Units exist only while the package is checked: the program prints a plain number, and a unit costs nothing when the program runs.

19.3.4.2 A derived unit, and changing a unit: convert, measured, magnitude

A derived unit is defined from units already declared, with a whole-number factor: measure Kilogram = 1000 * Gram is a kilogram, a thousand grams, and measure Milligram = Gram / 1000 would be a thousandth of a gram. A value never changes its unit by itself. Three methods change it, each where you write it, and they are the only ways:

steps/11-parcel-units/src/parcel.unacheckrununa
module parcel

--- A unit of weight.
measure Gram

--- A thousand grams.
measure Kilogram = 1000 * Gram

--- The most a parcel may weigh, as the carrier states it.
parcel_limit() -> Int of Kilogram = 5

--- A scale's reading, a plain number of grams, as a weight.
from_scale(reading: Int) -> Int of Gram = reading.measured()

--- The postage in cents, from a price list of plain numbers: 1 cent for every 10 grams.
postage(grams: Int) -> Int = grams / 10

pub main() -> Unit
  uses @console: Console[print]
=
  let weight = from_scale(3650)
  let limit: Int of Gram = parcel_limit().convert()
  @console.print("{weight} grams, limit {limit} grams, within: {weight <= limit}")
  @console.print("postage: {postage(weight.magnitude())} cents")
Output
3650 grams, limit 5000 grams, within: true
postage: 365 cents
  1. reading.measured(). Gives a plain number the unit that its place expects: here the result type, Int of Gram. Use it where a number enters the program without a unit, such as a scale's reading.
  2. parcel_limit().convert(). Changes a value to the unit its place expects, of the same kind of quantity: from kilograms to grams, it multiplies by 1000, the exact ratio. The place must say which unit it expects, here the type of limit.
  3. weight.magnitude(). Gives the plain number without its unit, for code that takes a plain Int, such as postage.

convert() works only when the ratio from the value's unit to the expected one is a whole number, as kilograms to grams is. Grams to kilograms would divide, and lose the grams below a thousand, so una rejects it with U2030 rather than round. measured() with no expected unit, or convert() between units of different quantities, such as grams and meters, is U2030 too.

19.3.5 Refined type arguments

The type in brackets after a generic type, such as Int in List[Int], is a type argument: it fills the generic type's type parameter (chapter 4). In editions 0.1 and 0.2, a type argument cannot be a refined kind, so a list cannot say that its elements keep a rule: the elements of a List[Int] carry no facts. In 0.3 it can:

steps/12-shelf-counts/src/shelves.unacheckrununa
module shelves

--- Units on a shelf, which holds at most 100.
kind Units = Int in 0..100

--- The counts of this morning's shelves, each a `Units`.
counts() -> List[Units] = [4, 12, 9]

--- The largest count, which is a `Units` too, or 0 for no shelf.
fullest(shelves: List[Units]) -> Units
=
  let edit top: Units = 0
  for units in shelves
    if units > top
      top = units
  top

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("fullest shelf: {fullest(counts())} units")
Output
fullest shelf: 12 units

The verifier proves that each element of the literal [4, 12, 9] is in 0..100, and inside the loop it knows that each units is a Units, so it proves that top stays one. In edition 0.2, the same code is rejected at each such type:

Diagnostic
[U2002] Error: this type argument is the refined kind `Units`, and a refined type cannot instantiate a type parameter; write its base type `Int` and check the refinement where the value is used

19.3.6 Failure handling that no longer runs

A restock list in edition 0.2 computes how many units to order for each line. order_quantity once parsed a typed number and could fail, so its callers handled a failure, with an if error clause and with attempt (chapter 7, section 7.4): if error use 0 gives a default when the call fails, and attempt keeps the outcome as a Result, Ok with the value or Err with the failure. It has since become a plain calculation, which cannot fail, and the handling stayed:

steps/14-restock/src/restock.unacheckrununa
module restock

--- A line of a stock list: a SKU and the units on hand.
kind Line
  sku: Text
  units: Int

--- How many units to order so that the shelf holds 10.
order_quantity(line: Line) -> Int = if line.units >= 10 then 0 else 10 - line.units

--- The order line for `line`, or a note when nothing is needed.
order_text(line: Line) -> Text
=
  let wanted = order_quantity(line)
    if error use 0
  if wanted == 0 then "{line.sku}: enough" else "{line.sku}: order {wanted}"

--- The total of every order quantity.
total(lines: List[Line]) -> Int
=
  let edit sum = 0
  for line in lines
    let outcome = attempt order_quantity(line)
    sum = when outcome
      is Ok(wanted) -> sum + wanted
      is Err -> sum
  sum

pub main() -> Unit
  uses @console: Console[print]
=
  let lines = [Line(sku: "LAMP-01", units: 4), Line(sku: "SHELF-03", units: 12), Line(sku: "DESK-02", units: 9)]
  for line in lines
    @console.print(order_text(line))
  @console.print("{total(lines)} units to order")

In edition 0.2 this is accepted, and una run . prints:

Output
LAMP-01: order 6
SHELF-03: enough
DESK-02: order 1
7 units to order

19.3.7 What 0.3 reports: U3025 and U3026

The if error use 0 clause never runs, and the Err arm of total is never taken. They are harmless, but they mislead a reader into thinking order_quantity can fail. Edition 0.3 rejects both:

una.tomldiff
--- a/una.toml
+++ b/una.toml
@@ -1,7 +1,7 @@
 [package]
 name = "restock"
 version = "0.1.0"
-edition = "0.2"
+edition = "0.3"
 
 [run]
 entry = "restock"
Diagnostic
[U3025] Error: this `if error` clause never runs, since the call of `order_quantity` cannot fail; remove the clause
    ╭─[ src/restock.una:15:5 ]
    │
 15 │     if error use 0
    │     ─┬
    │      ╰── this `if error` clause never runs, since the call of `order_quantity` cannot fail; remove the clause
    │
    │ Help: repair 1: remove the clause; edit src/restock.una:14:36..15:19 to ""
    │
    │ Note: run `una explain U3025` for an explanation
────╯
[U3026] Error: the call of `order_quantity` cannot fail, so `attempt` gives a `Result` whose `Err` is never taken; use the value of the call directly
    ╭─[ src/restock.una:23:19 ]
    │
 23 │     let outcome = attempt order_quantity(line)
    │                   ──────────────┬─────────────
    │                                 ╰─────────────── the call of `order_quantity` cannot fail, so `attempt` gives a `Result` whose `Err` is never taken; use the value of the call directly
    │
    │ Help: repair 1: remove `attempt` and use the value of the call directly, then unwrap each use of the `Result`: a `when ... is Ok(v)` becomes the value `v`, its `is Err` arm goes, and a declared `Result[T, E]` becomes `T`
    │
    │ Note: run `una explain U3026` for an explanation
────╯
1 of 2 diagnostics have an edit that `una fix` applies (`una fix --dry-run` lists them)

Each diagnostic names its repair. U3025's repair deletes the clause, an exact edit. U3026's repair is a description, because the uses of the Result have to be unwrapped by hand. The last line counts one of the two as fixable.

19.3.8 How a preview behaves

Important

A package that checks today on 0.3 may get a new obligation or a new error after an upgrade. Use 0.3 where its rules help, and rerun una check . and una test . after each upgrade.

19.3.9 When to choose 0.3

Which to use:

Your package… Edition
Needs a condition on an operation, a locked contract, a boundary, a narrowed rebinding or units 0.3
Should stay exactly as it is across upgrades 0.2
Has failure handling you want the checker to keep honest 0.3
Is maintained by a team that cannot react to a new error after an upgrade 0.2

19.3.10 Check yourself: grams and kilograms

Declare a second unit, a kilogram, and write the parcel's limit in kilograms:

src/parcel.unadiff
--- a/src/parcel.una
+++ b/src/parcel.una
@@ -4,2 +4,5 @@
 measure Gram
+
+--- A thousand grams.
+measure Kilogram = 1000 * Gram
 
@@ -15,3 +18,3 @@
   let weight = parcel_weight(3)
-  let limit: Int of Gram = 5000
+  let limit: Int of Kilogram = 5
   @console.print("{weight} grams, within the limit: {weight <= limit}")

A kilogram is 1,000 grams, and 3,600 grams is under 5 kilograms. Does the package check?

Show the answer

It does not. A unit is part of the type, and <= needs one type on both sides:

Diagnostic
[U2028] Error: `<=` needs operands of one type, and these are `Int of Gram` and `Int of 1000 * Gram`
    ╭─[ src/parcel.una:20:54 ]
    │
 20 │   @console.print("{weight} grams, within the limit: {weight <= limit}")
    │                                                      ───────┬───────
    │                                                             ╰───────── `<=` needs operands of one type, and these are `Int of Gram` and `Int of 1000 * Gram`
    │
    │ Note: run `una explain U2028` for an explanation
────╯

Int of 1000 * Gram is how the checker writes a kilogram: a scale of 1000 on the unit Gram. una never converts implicitly: two values of different units never meet in +, - or a comparison, and each such place is U2028. To compare them, convert one explicitly, where a gram is expected: let limit_grams: Int of Gram = limit.convert() multiplies by 1000, the exact ratio, and weight <= limit_grams checks, as in the derived unit above.

One more, without code. Two packages check clean with una 0.4.0: the restock list after its move, on edition 0.3, and the stock list of section 19.2, on edition 0.2. A later release comes out. Which of them can get a new error?

Show the answer

Only the package on edition 0.3. It is on the preview, which a later release may make stricter: a new rule may add an obligation or an error to it. The package on edition 0.2, a stable edition, keeps exactly what it accepts and rejects, except for a fix of a soundness or security error. That is why the preview's packages rerun una check . and una test . after each upgrade.

Next:19.4 Moving a package forward