# 01 — Codes: the grammar and the table {#codes}

## 1. A code {#codes-code}

A unit is named by its UCUM code, the case-sensitive form (UCUM §1). The case-insensitive
form is read by one function, which answers the case-sensitive code for it (§5). A code
is checked, never guessed at: a string that is not a code is refused with the reason it
is not, so a typo (`sec`) never reads as some unit.

`Ucum.parse/1` reads a code into its **components**, left to right:

```elixir
%{prefix: String.t() | nil, atom: String.t() | nil, factor: pos_integer() | nil,
  annotation: String.t() | nil, exponent: integer()}
```

A component is a prefixed atom with its exponent, an integer factor, or an annotation
standing alone; an annotation may also follow an atom or a factor. A component after `/`
has its exponent negated. `parse/1` answers `{:ok, components}`, or `{:error, reason}`
(spec/03). `Ucum.valid?/1` is whether a term is a string `parse/1` reads.

## 2. The grammar {#codes-grammar}

The library reads all of UCUM's grammar: the syntax rules of its specification (§2.2,
§§6–12) and their Backus-Naur form (Exhibit 1), which is this:

```
main-term   = "/" term | term
term        = term "." component | term "/" component | component
component   = annotatable annotation | annotatable | annotation | factor
            | "(" term ")"
annotatable = simple-unit exponent | simple-unit
simple-unit = ATOM-SYMBOL | PREFIX-SYMBOL ATOM-SYMBOL[metric]
exponent    = sign digits | digits
factor      = digits
annotation  = "{" ANNOTATION-STRING "}"                ASCII 33–126 except "{" and "}"
```

and one thing more, which the functional tests ask for (spec/04, `1{c}`) and codes in
use depend on: **a factor may carry an annotation** (`1{core}`).

- **Left to right.** `.` and `/` have one precedence (UCUM §7): `g/m.s2` is (g/m)·s², so
  `s` keeps a positive exponent; `g/m/s2` divides by both.
- **A leading `/`** divides by the whole term after it: `/s.m` is s⁻¹·m⁻¹. Only a code
  begins with one; a term in parentheses does not (`(/s)` is not a code).
- **Parentheses** hold a term in place of a simple unit (UCUM §10), to any depth:
  `g/(m.s2)` divides by both, `mmol/(8.h.kg)`, `m/(s/(g/K))`. A term in parentheses takes
  no prefix, and **no exponent and no annotation** of its own: UCUM struck the exponent
  after its revision 1.9, so `(m/s)2` and `(m){a}` are not codes. `parse/1` answers the
  components of a nested term in line with the rest, each with the exponent the term's
  place gives it, so `g/(m.s2)` and `g/m/s2` read the same.
- **A symbol** is a run of letters, `%`, `*`, `^`, `_` and `'`, and bracketed parts (`[` up to the
  next `]`), so `[ft_i]`, `m[Hg]`, `mm[Hg]`, `B[SPL]` and `dB[SPL]` are each one symbol,
  as UCUM writes them. An exponent or an annotation ends it (`[ft_i]2`, `By{heap}`).
- **Digits are a number only when nothing of a symbol follows them** (UCUM §8). Digits
  with a symbol's character after them are one symbol with it: `10*` and `10^` are atoms,
  the number ten for arbitrary powers, read with an exponent (`10*3/uL`, `10^-7`), and
  `10m` and `12h` are symbols no table holds (`10.m` and `12.h` are codes).
- **A factor** is a positive integer and takes no exponent: `10+3` is not a code, though
  `10*3` is. The factor 0 is not a code.
- **A symbol is matched whole before it is split** into a prefix and an atom: `min` is
  the minute and `m` the meter, never a milli-`in`; `h`, `d`, `t`, `cal`, `bar`, `Pa` and
  `cd` (the candela, not a centi-day) are atoms. Only a symbol that is not an atom is read
  as a prefix and an atom, the longest prefix first: `MiBy` is `Mi`·`By`, `dam` is
  `da`·`m`, `mm[Hg]` is `m`·`m[Hg]`, `dB` is `d`·`B`. Over the whole table no prefix on a
  metric atom reads as anything else.
- **A prefix only on a metric atom** (UCUM §11). `kmin` and `k[in_i]` are refused, with
  `{:not_metric, prefix, atom}`.
- **An annotation means the unity** (UCUM §6): `{request}/s` has the dimension and
  factor of `/s`, whatever its text. `{iso4217:USD}` is an annotation like any other. An
  empty annotation `{}` is not a code, and an annotation does not come before a unit
  (`{a}rad2`).

So `s`, `ms`, `us`, `min`, `By`, `KiBy`, `%`, `Hz`, `Cel`, `[degF]`, `m/s`, `km/h`, `s-1`,
`m+2`, `kW.h`, `mm[Hg]`, `dB[SPL]`, `1`, `1{core}`, `{request}/s`, `/s`, `By{heap}`,
`10*3/uL`, `10^-7.m`, `g/(m.s2)`, `((m))` and `/(m.s)` are codes; `sec`, `fts`, `kmin`, `k%`, `{x`, `{}`, `[in_i`, `m//s`, `.s`, `s^2`, `s-`, `0`, `10m`,
`10+3`, `(m/s)2`, `(m){a}`, `(/s)`, `()`, `(m`, `m)`, `k(m)` and `""` are not.

A string that is a code is read as that code, whatever its writer meant: `ft` is the
femto-tonne (the foot is `[ft_i]`), and `Pa` the pascal, not a peta-year.

```test:units-grammar
every code listed reads, and every string listed as no code is refused with its reason; a symbol is matched whole before a prefix is split from it; a quotient negates its exponents left to right, and a term in parentheses is read in place of a unit, to any depth, with no exponent or annotation of its own; digits with a symbol's character after them are a symbol; an annotation stands alone or follows a unit or a factor, and has no unit meaning
```

## 3. The table {#codes-table}

The table is UCUM's own: its **essence table**, `ucum-essence.xml`, version 2.2 of
2024-06-17 (`Ucum.essence_version/0`). The file is in the library as `priv/ucum-essence.xml`,
Regenstrief's file byte for byte, with its notice beside it (`priv/UCUM-NOTICE`: the
copyright, the UCUM License, its disclaimer of warranties and its address). A test holds
the file's SHA-256, so an edit fails. The library is compiled from the file: nothing in
`lib/` writes a unit's definition, and the compiled library reads no file.

The file holds 24 prefixes and 312 units. **Every row of it is this specification's**,
by reference: a prefix or unit is what the file says it is, and this section says only how
the file is read.

```test:units-essence-file
the vendored file is Regenstrief's byte for byte and says its version, ships with its notice in the package, and holds UCUM's 24 prefixes and 312 units
```

**What is read.** All of it: the 24 prefixes and the 312 units.

**A prefix** has the file's `Code`, and its `value` as its factor: `k` is 10³, `Ki` 2¹⁰,
`y` 10⁻²⁴.

**A unit** has the file's `Code` as its atom, and is metric where the file says
`isMetric`: only then does it take a prefix (§2).

**A value** of the file is a decimal (`254e-2`, `1.66053906660e-24`), and is read as the
rational it writes: 127/50, and 166,053,906,660 over 10³⁵. Nothing is rounded.

**A definition** is a value times a code (`[in_i]` is 2.54 `cm`; `[ly]` is 1 `[c].a_j`).
The library reads the code with its own grammar (§2) and follows it, definition by
definition, down to the seven **base units**, which the file marks with their dimension:

| Base unit | `m` | `s` | `g` | `rad` | `K` | `C` | `cd` |
|---|---|---|---|---|---|---|---|
| The file's `dim` | L | T | M | A | C | Q | F |
| Dimension (spec/02 §1) | `:length` | `:time` | `:mass` | `:angle` | `:temperature` | `:charge` | `:luminous_intensity` |

That gives each unit its dimension and its exact factor to the base (spec/02 §2). So a
watt is 1,000 g·m²·s⁻³; the pound-force of `[HP]` and `[psi]` is `[lb_av]` times the
standard acceleration of free fall `[g]`, 9.80665 `m/s2`; and a light-year is
9,460,730,472,580,800 `m`. The bit is `1`, as UCUM defines it, so data has no dimension of
its own: `By/s` has the dimension of `Hz`, and a byte converts to a percent (spec/02 §4).
The mole is UCUM's number, 6.02214076 × 10²³. A program that wants data, or amounts, kept
apart from ratios adds that rule itself (spec/00 §1).

**π** is the unit `[pi]`, and is kept as itself, not as the file's decimal for it, so a
factor holding it stays exact: `deg` is π/180 `rad`, `circ` 2π, `[mu_0]` π/2,500
g·m·C⁻².

**A special unit** is one the file defines by a function of an argument, not a value
(`isSpecial`; `Cel` is `cel(1 K)`, `B[SPL]` is `2lg(2 10*-5.Pa)`): 21 of them. Each has
the dimension of its function's argument (`B[SPL]` is the level of a pressure) and no
factor (spec/02 §2). `Cel`, `[degF]` and `[degRe]` are affine, a scale with an offset
(spec/02 §4): the file gives the scale (`degf(5 K/9)`), and the offset is UCUM's
specification's. Every other special unit converts through its function (spec/02 §6),
which the definition's special expression names; the file's `<function>` element, which
says it again, is not read.

**An arbitrary unit** is one whose meaning is its measuring procedure alone, with no
relation to any other unit (UCUM §24; the file's `isArbitrary`: `[IU]`, `[arb'U]`,
`[USP'U]`): 41 of them. The file writes each as 1 times the
unity only to give it a row, and that is not read as a definition. An arbitrary unit is
**a dimension of its own**, under its code (spec/02 §1), with the factor 1: so it is
commensurable with itself, alone, under a prefix and inside a term, and with nothing
else, the unity and every other arbitrary unit included (spec/02 §4). One is defined by
another: `[IU]` is 1 `[iU]`, the two codes of the international unit, and so has
`[iU]`'s dimension and converts to it. Two take a prefix, `[iU]` and `[IU]`, which the
file calls metric.

```test:units-arbitrary
an arbitrary unit is a dimension of its own under its code; it converts to itself alone, under a prefix and inside a term, and to no other unit, the unity and every other arbitrary unit included; the two codes of the international unit are one unit, as the file defines them; it takes a prefix only where the file calls it metric
```

**A display symbol** is the file's `printSymbol` (spec/02 §5), its superscript and
subscript marks written in Unicode where it has the characters (`m H₂O`, `mₑ`) and
plainly where it does not (`cal15°C`). The file gives 103 units no print symbol; such a
unit is written as its code without the brackets (`[gal_us]` as `gal_us`). A prefix is
written as the file's print symbol: `u` as `μ`.

```test:units-atoms
the table holds every prefix and every unit of the file; each unit's factor and dimension is the file's definition, exactly, worked down to the base units, with π kept as itself; a special unit has its argument's dimension and no factor; every prefix reads on every metric atom, with the product of their factors, and none on an atom that is not metric; the atoms the hand-written table held have what it gave them
```

## 4. Reading the table {#codes-lookup}

A program that keeps its own rules on top of UCUM (spec/00 §1) composes them from each
component's definition, so the table is public, read through four functions:

- `Ucum.atom(code)` answers `{:ok, %{code:, dimension:, factor:, metric:, kind:, symbol:}}`
  for an atom of the table: its dimension (spec/02 §1), its factor to its base in
  `factor/1`'s form, `nil` for a special unit (spec/02 §2), whether it is metric, its kind
  (spec/02 §3) and its display symbol (spec/02 §5). Each equals what the atom answers as a
  code. A string that is not one atom is `{:error, {:unknown_atom, string}}`, a prefixed
  code (`km`) or a term (`m/s`) among them.
- `Ucum.prefix(code)` answers `{:ok, %{code:, factor:, symbol:}}` for a prefix of the
  table, its factor an exact `{n, d}`; any other string is
  `{:error, {:unknown_prefix, string}}`. A prefixed code's factor is the prefix's times the
  atom's.
- `Ucum.atoms/0` and `Ucum.prefixes/0` list the codes of every atom and every prefix,
  sorted.

A term that is no string is `{:error, {:syntax, text}}` from `atom/1` and `prefix/1`.

```test:codes-lookup
each atom's definition equals what it answers as a code; a prefix's factor times a metric atom's is the prefixed code's; a string that is not one atom or prefix is refused with its reason; the lists hold the whole table, sorted
```

## 5. The case-insensitive codes {#codes-insensitive}

UCUM has two sets of codes (its specification's §1, and the columns "c/s" and "c/i" of
every table): the case-sensitive, which every function of this library reads, and the
**case-insensitive**, for a system that cannot keep the case of what it carries. The
second is not the first in capitals. A code of it is the table's `CODE`, where the
case-sensitive is its `Code`:

| | milli | mega | hour | henry | pascal | siemens | second | gram | gauss |
|---|---|---|---|---|---|---|---|---|---|
| case-sensitive | `m` | `M` | `h` | `H` | `Pa` | `S` | `s` | `g` | `G` |
| case-insensitive | `M` | `MA` | `HR` | `H` | `PAL` | `SIE` | `S` | `G` | `GS` |

`Ucum.case_sensitive/1` reads a case-insensitive code and answers its case-sensitive
code, `{:ok, code}`, which the other functions take: `MM[HG]` is `mm[Hg]`, `MAM/HR` is
`Mm/h`, `10*3/UL` is `10*3/ul`.

- **The grammar is the same** (§2): the operators, parentheses, exponents, factors and
  annotations; a symbol matched whole before it is split into a prefix and a metric atom.
- **The form has no case**, so it is read in any: `mm[hg]`, `Mm[Hg]` and `MM[HG]` are one
  code. A symbol and the table's `CODE` are compared upper-cased, the table's too, since
  the file writes two of its codes in mixed case (`[degR]`, `[degRe]`).
- **An annotation is kept as it is written**: `KG{Wet}` is `kg{Wet}`.
- **Two pairs of units share a code**: `L` is both `l` and `L`, the liter's two
  spellings, and `[IU]` both `[iU]` and `[IU]`, the international unit's. Each pair is one
  unit by the table's own definitions, and the first in the file is answered: `l`, and
  `[iU]`. No other code of the form reads two ways: over the whole table a prefix on a
  metric atom is never another atom's code, nor another prefix on another atom.
- **The answer is written plainly**: an exponent of 1 and the `+` of a positive one are
  left out (`M+2` is `m2`), and nothing else of the code changes.
- **A string that is no case-insensitive code** is refused with `parse/1`'s reasons
  (spec/03 §1): `SEC` is `{:unknown_atom, "SEC"}`, the symbol as it was written, and `KMIN`
  is `{:not_metric, "k", "min"}`, the prefix and atom by their case-sensitive codes.

A string may be a code of both forms and name two units: `G` is the gauss
case-sensitively and the gram case-insensitively, `S` the siemens and the second. Which
form a string is in is the caller's to know; the library does not guess it, and reads the
case-insensitive form through this function only.

```test:codes-insensitive
every unit's and every prefixed metric unit's case-insensitive code is answered as a case-sensitive code of the same unit, in any case; the two shared codes answer the first of their pair, the pair being one unit; the grammar is the same and an annotation is kept as written; a string that is no case-insensitive code is refused with parse/1's reasons
```

## 6. The size of a code's numbers {#codes-size}

UCUM's grammar bounds neither a number's digits nor an exponent's (§2): `m999999` is a
code, and so is a factor of a million digits. A machine holds no such number: the Erlang
VM refuses an integer past a few million bits, and reading or multiplying one short of
that costs time out of all proportion to the code's length. So the library has one bound
of its own, stated here, and what is past it is refused with a reason (spec/03 §1) before
anything is computed. Nothing raises, and no function works longer than its string's
length accounts for.

**The bound is 65,536 bits: a number up to 2⁶⁵⁵³⁶.** That is 64 times the bits of a
float's whole range (2¹⁰²⁴, spec/02 §9), so nothing a float could hold is near it, and
arithmetic at it takes milliseconds.

- **A number written in a code**, as a factor or as an exponent, is read up to 19,729
  digits, the digits of 2⁶⁵⁵³⁶. One of more digits is `{:too_large, code}`, the whole code,
  from `parse/1` and so from every function. The digits are counted, not read. Digits
  that begin a symbol (§2) are no number, and are not counted.
- **A code's factor** (spec/02 §2) is held when its numerator and its denominator are
  each of at most 65,536 bits, a number below 2ᵇ having b bits, and π's power is at most
  32,768 either way, π² being under 2⁴. A code past that is `{:too_large, code}` from
  `factor/1` and from each function that takes a factor: `canonical/1`, `conversion/2`,
  `convert/3`, `multiply/2` and `divide/2`.

So `10*19728` has its factor, 10¹⁹⁷²⁸ being of 65,535 bits, and `10*19729` is too large;
`km6576` has one and `km6577` does not; `Kibit6553` is 2⁶⁵⁵³⁰ and `Kibit6554` is too
large; `[in_i]5333` has one, 5000⁵³³³ below it being of 65,531 bits, and `[in_i]5334` does
not; `[pi]32768` has one and `[pi]32769` does not.

**The bound is of the factor the code has, not of its parts.** UCUM's units are a group
under multiplication (its §3): a unit over itself is the unit 1, whatever its size. So
`km999999/km999999` has the factor `{1, 1}` and `km999999/km999998` has `{1000, 1}`,
though `km999999` alone has none; and what cancels between components that are not the
same cancels too: `km6576/m6576` is 1000⁶⁵⁷⁶, `Mibit500000/Kibit999999` is `{1024, 1}`
and `[in_i]18000/[ft_i]18000` is one over 12¹⁸⁰⁰⁰. The size is known before any power is
taken: the numbers of the components' own factors are first made numbers no two of which
share a divisor, each with the sum of its powers, and between such numbers nothing
cancels. A factor past the bound still costs nothing to refuse.

It is each code's own factor. `multiply/2` of a quantity in `km999999` and one in
`km-999999` is `{:too_large, "km999999"}`: two codes are not worked as one, and the
reason names the code that is too large.

**The numbers a code writes have a bound of their own**, since finding what they share
is work in their size: the distinct numerators and denominators of its components' own
factors, each counted once and those whose powers sum to nothing not at all, are of at
most 131,072 bits together, twice the bound. A code past that is `{:too_large, code}`
whatever its factor. No code of a factor inside the bound comes near it but one made to:
it takes thousands of numbers, or three of nineteen thousand digits. A number repeated
is one number. A code at that bound made to be the worst that is known, thousands of
numbers each sharing divisors with thousands, is worked in about a second.

**A code too large is still a code.** `km999999` is valid; `parse/1`, `dimension/1`,
`kind/1`, `symbol/2`, `name/1` and `case_sensitive/1` answer it, having no use for its
factor. A unit of factor 1 costs nothing at any exponent: `m` to a power of 19,729 digits
has the factor `{1, 1}`. And a code converts to itself by `{{1, 1}, {0, 1}}` whatever its
factor (spec/02 §4).

```test:codes-size
a number written in a code is read up to 19,729 digits and refused past them by every function, at once; a factor is answered up to 65,536 bits of numerator and of denominator and refused past them, what cancels between its components having cancelled; the numbers a code writes are worked up to 131,072 bits of them, in time whatever they share; a product of factors to their powers is the powers multiplied and reduced; a code too large is still a code to what takes no factor; within the bound thousands of components are worked in time; every function answers a code of numbers of any length, never raising, in time
```
