Home / Docs / Specification
25. Units of measure
Status: Normative, v0.3 preview (ADR 0104), with the other number types of ADR 0114 rule 12 and ADR 0120 rules 61 to 65 (§9).
A unit of measure is part of a number type. Int of Meter is neither Int nor Int of Second, so a program cannot add meters to seconds, pass seconds where milliseconds are expected, or compare grams with milliliters. Units exist only at compile time: they are erased after the type check, so they cost nothing at run time or in verification, and they do not change a program's output.
Editions. The rules of this chapter apply only to packages of edition 0.3 (spec/13 §7) and later. In editions 0.1 and 0.2, a measure declaration and of after a type are syntax errors (U0101). F64 takes a unit from edition 0.3, and F32, Decimal[s], the complex types and the elements of dense values in edition 0.5, the edition that has them (§9).
1. Declarations
measure_decl = [ "pub" ] "measure" upper_ident [ "=" unit_expr ] NEWLINE ;
unit_expr = unit_term { ( "*" | "/" ) unit_term } ;
unit_term = upper_ident | "(" unit_expr ")" | integer_literal ;- The keyword.
measureis a contextual keyword: it is the keyword only at the start of a top-level declaration, after an optionalpub, and only before an upper identifier. Elsewhere it is an identifier, andmeasure(x)is a function. - Base and derived units. A declaration without
=declares a base unit, a dimension of its own. A declaration with=declares a derived unit, a unit expression over declared units and positive integer factors (measure Kilometer = 1000 * Meter,measure Millisecond = Second / 1000). - Identity. A base unit is identified by its declaration: its module's path and its name. Two modules that each declare
Meterdeclare two dimensions. - Names. Unit names are upper identifiers, and follow the rules of kind names for
pub,useand qualification. A unit and a kind of the same name in one module, by declaration or import, is U1002. A unit named as a built-in type, a prelude kind or a constraint is U1002 (spec/03 §1, spec/20). - Errors. Each of these is U2029: a cycle among derived units; a unit expression that names an unknown unit, or a name that is not a unit; a factor that is not a positive integer literal; a scale too large; a derived unit with no base unit and scale 1, which would be no unit.
2. Measured types
- Syntax.
type = [ label ] type_core [ "of" unit_expr ] [ "in" range ] ;.offollowsIntor a fixed-width integer type (spec/18),F64, and in edition0.5F32,Decimal[s],Complex[F64]andComplex[F32](§9); after any other type it is U2029. A dense value takes its unit in its element type, asArray[F64 of Meter]. - Normal form. A unit's normal form is a positive rational scale, reduced, and a map from base units to nonzero integer exponents, ordered by module path and then name. Two units are equal exactly when their normal forms are equal.
- No unit. A unit with no base unit and scale 1, as
Meter / Meterin a type, is no unit: the type is the plain integer type. A unit with no base unit and another scale, asKilometer / Meter, stays a unit. - A type of its own. A measured type is distinct from its integer type and from every other measured type. A flow between types that differ only in their units is U2028.
- Refinements.
inandwhereon a measured type constrain its magnitude. - Type arguments. A measured type MAY be a type argument (
List[Int of Meter]). A refined measured kind follows the rule for refined type arguments (spec/03 §3). - Labels. A measured value carries labels as its integer type does (spec/07).
3. Arithmetic and comparison
+,-,mod, unary-,==,!=,<,<=,>,>=andinneed one unit on both sides, and the result of+,-,modand unary-has it. Different units are U2028.*multiplies the operands' units, and/divides them;/is Euclidean (spec/10 §3).- Constants. A constant expression, made only of integer literals and
+,-,*,/,mod, unary-and parentheses, takes the unit its context expects, as a literal takes a fixed-width type (spec/18 §2). A constant operand of*or/is unitless, so2 * dkeepsd's unit. - Fixed-width magnitudes. The operands of an operator have one integer type, and the
overflowobligations of spec/18 §3 apply to the magnitude. - Ranges. In
for i in a..b, both bounds have one unit, andihas it. - Declarations. A function's parameters and result declare their units. A
letwithout a type takes its value's unit. There are no unit variables.
4. Constraints and built-in methods
- A measured type satisfies
EqandOrdwhen its integer type does, and neverInteger(U2025):to_int()would remove its unit. - On a measured receiver, the built-in methods of spec/18 §4 and
§5:- the conversions
to_i8()toto_u64()andto_int()keep the unit; wrapping_add,wrapping_sub,saturating_addandsaturating_subtake an argument of the receiver's type and keep the unit;wrapping_mulandsaturating_mulmultiply the units of the receiver and the argument;shift_rightandwrapping_shift_leftkeep the unit and take a unitless amount;- every other method needs a unitless receiver (U2028).
- the conversions
5. Conversions
n.measured()gives a unitless integer the unit of the expected type, with the same integer type.d.magnitude()gives a measured value's integer type, without its unit.d.convert()changes a measured value to the expected unit, of the same dimension, when the ratio of the scales, source over target, is a positive integerk: the magnitude is multiplied byk, with anoverflowobligation on a fixed-width magnitude. A scaled dimensionless unit converts to the plain integer type the same way.- Each of these is U2030:
measured()orconvert()with no expected unit;measured()on a measured value;convert()on a unitless value; aconvert()whose ratio is not an integer, whose dimensions differ, or whosekdoes not fit the magnitude's integer type.magnitude()on a unitless value is U2028. - Resolution. In edition
0.3,x.measured(),x.magnitude()andx.convert()with no argument are these built-ins, ahead of a function of the same name in scope (spec/10 §5). Every use where neither the receiver nor the expected type carries a unit is an error.
6. Clauses
- In a clause, a measured type reads as its integer type (spec/18 §2), and the unit rules of §3 still apply.
magnitude(),measured()andconvert()are terms of the refinement language (spec/03 §3): the first two the identity on the magnitude,convert()the multiplication by its literal ratio.- A unit error in a lock condition of
[contracts]is U7002 at its entry (spec/13 §7).
7. Erasure
- The map. The erasure
Eof a program deletes everymeasuredeclaration and everyof unit_expr;E(x.measured())andE(x.magnitude())areE(x);E(x.convert())isE(x)whenkis 1, andE(x) * kotherwise, in that operand order,ka literal of the magnitude's integer type. Elaboration appliesEbefore A-normalization. - Runtime and output. Values carry no unit.
to_text, interpolation, traces and--jsonoutputs write the magnitude. - Verification. Obligations are generated from the erased Core IR, and the query texts of a program are those of
Eof it (spec/12 §2). - Core export.
una coreexports the erased program. - The preview rule. For a program that edition
0.3accepts,Eof it is a program that edition0.2accepts, with the same behavior.
8. Diagnostics
| Code | Meaning |
|---|---|
| U2028 | Values of different units meet, or a measured and a unitless value |
| U2029 | An invalid unit declaration or unit expression |
| U2030 | A unit conversion without an expected unit, or not exact |
9. Floats, decimals, complex values and dense values
The rules of §1 to §8 apply to every number type that takes a unit, with these rules for the types that are not integers (ADR 0114 rule 12, ADR 0120 rules 61 to 65). An operator or a method is typed on the magnitudes by the rules of its type (spec/29), and its unit is the one these rules give.
-
F64(ADR 0114 rule 12).+,-, unary-, the comparisons, the IEEE comparisons,ieee_min,ieee_maxandinneed one unit, and the results of+,-, unary-,ieee_minandieee_maxhave it.x.clamp(lo:, hi:)needs one unit for all three, and has it.*and/multiply and divide units.abs,floor,ceil,trunc, both roundings andcopy_signkeep the receiver's unit, andcopy_signtakes any unit forfrom.x.rem(by: y)needs one unit and keeps it.x.fma(times: y, plus: z)needszin the unit ofx * y, and has it. The classifications take any unit.to_bitsneeds a unitless receiver (U2028).x.sqrt()gives the unit whose normal form has half of each exponent and the square root of the scale, when every exponent is even and the scale is the square of a rational:F64 of Meter * MetergivesF64 of Meter. Otherwise it is U2028, andx.magnitude().sqrt().measured()writes the conversion out.- A constant expression made only of float literals and the operators takes the unit its context expects, as an integer constant does (§3 rule 3).
convert()accepts a ratio of scales k or 1/k, with k a positive integer of at most 2^53, so that k is exact as anF64: it multiplies or divides the magnitude by k, rounded once. Any other ratio, as inch to centimeter (127/50), is U2030.- Conversions between number types keep the unit:
n.to_f64()onInt of MeterisF64 of Meter, andx.to_int_exact()onF64 of MeterisOption[Int of Meter].
-
F32follows rule 1 exactly (ADR 0120 rule 62), with k of aconvert()at most 2^24, so that k is exact as anF32.to_f32()andto_f64()between the float types keep the unit. -
Decimal[s](ADR 0120 rule 63).+,-, the comparisons,widen,rescale,rescale_exact,absandto_intneed or keep one unit, the comparisons across scales;*multiplies units;dividedivides them;remainderneeds one unit on both operands and keeps it;to_f64()keeps the unit, andcoefficient()needs a unitless receiver (U2028).convert()accepts an integer ratio k and multiplies the coefficient by k, exactly; a ratio 1/k would need a rounding, so it is U2030, andx.magnitude().divide(...).measured()writes the division out with its scale and its rounding. A currency is a unit, so dollars cannot be added to euros, and an exchange rate is a value of a quotient unit:unameasure Usd measure Eur let rate: Decimal[6] of Eur / Usd = 0.921350 let paid: Decimal[2] of Eur = (price * rate).rescale(scale: 2, rounding: HalfEven) -
Complex[F64]andComplex[F32](ADR 0120 rule 64). A measured complex value has one unit for both components:complex(re:, im:)takes it from its arguments, which need one unit (U2028 otherwise), or from the expected type for literals;+and-need one unit,*and/multiply and divide,conjkeeps,scale(by:)multiplies by the scalar's unit,norm_sqr()squares, andreandimhave the unit. A measured complex value satisfiesEqand notOrd, as its magnitude does.convert()on a complex value is U2030; its components convert one by one. -
Dense values (ADR 0120 rule 64). The element type carries the unit, one unit for every element: per-row units are not expressible. The element-wise operators follow the scalar rules, and the unit of a scalar multiplies or divides the elements' in
k * x,x * kandx / k.multiply_elements,dot,multiplyandmultiply_arraymultiply the units of their operands, anddivide_elementsdivides them.add_productandadd_scaledadd a product to their receiver, so the product is in the receiver's unit, andscale(by:)changes its receiver in place, so its factor is unitless (U2028 otherwise).sum,norm2, the row and column sums and the reads keep the unit.x.magnitude()andx.measured()on a dense value are O(1): the representation is the same.convert()on a dense value is U2030;mapconverts its elements. The units ofsolve,choleskyandlu()(ADR 0120 rule 64) apply when those methods land. -
Erasure (§7):
E(x.convert())on anF64or anF32isE(x) * korE(x) / k, with k the float literal of the ratio, and on a decimalE(x) * k, with k aDecimal[0]literal, which keeps the scale. Every other unit operation erases as in §7, so units cost nothing and change no value. A program withF64erases to a program of edition0.3without units, and one with the types of edition0.5to a program of edition0.5without units (ADR 0114 rule 15).