| @@ -0,0 +1,78 @@ |
| 1 | +# ADR 0070: `Dec`, a fixed-point decimal for money |
| 2 | + |
| 3 | +**Status:** Proposed (2026-10-29, issue #340); needs engineering review (#44). Extends [ADR 0013](0013-numeric-code.md) and [ADR 0035](0035-numbers-bits-and-u64.md); keeps [ADR 0034](0034-string-interpolation.md)'s no-implicit-conversion discipline. |
| 4 | + |
| 5 | +## Context |
| 6 | + |
| 7 | +`Float` cannot represent `0.1`; a language whose web stack (std/http, the postgres package, #145) is meant to bill people owes them a decimal type. Roc ships `Dec`, a 128-bit fixed-point decimal, as its default fractional number, for exactly this reason. Louise has `Int` (63-bit small or bigint, ADR 0014), `Float` (boxed double, ADR 0045) and `U64` (ADR 0035), and no implicit coercions anywhere (ADR 0034). |
| 8 | + |
| 9 | +The integration that justifies the feature is PostgreSQL's `NUMERIC`: the postgres package has no `Decimal` in its `Value` enum, and OID 1700 appears nowhere in it. |
| 10 | + |
| 11 | +## Decision |
| 12 | + |
| 13 | +### Representation: an `i128` scaled by 10^18, in a new block kind |
| 14 | + |
| 15 | +A `Dec` is a 128-bit signed integer counting units of 10^-18 (Roc's choice): 18 decimal places, integral part up to about ±1.7 · 10^20. It is boxed in a `TL_TAG_DEC` block (0xFF0E, the next free tag) whose raw area is the `i128` as two `u64` limbs — a block's raw area is 8-byte aligned and an `i128` wants 16; the limbs keep the write defined — a leaf block like `U64`: `plain()` covers its drop, `check_sendable` defaults to sendable, and nothing else in the runtime changes. **Runtime ABI 11** (the tag, in `louise_rt.h` and `abi.rs` together, per the change rule). |
| 16 | + |
| 17 | +### Canonical form: the fixed scale is the canonicalization rule |
| 18 | + |
| 19 | +`Int` equality can shortcut on the word because small is canonical. A `Dec` is canonical *by construction*: with one fixed scale, every value has exactly one `i128` (there is no trailing-zero question — `1.2` and `1.20` are the same integer; there is no negative zero). So `Eq` is `i128` equality, `Ord` is `i128` comparison, and `Hash` hashes the raw limbs. The rejected alternative — a scale in the value, like `NUMERIC` itself — is what would have needed a trailing-zero policy; it buys `1.20` remembering its two places, at the price of a canonicalization pass on every operation. |
| 20 | + |
| 21 | +### Rounding: half-even, everywhere an operation is inexact |
| 22 | + |
| 23 | +One rule, stated once: **every inexact operation rounds to the nearest representable value, ties to even**. That covers `*` and `/` (whose true results can exceed 18 places), `parse` of more than 18 fractional digits, `from_float`, and `round ~places:`. Half-even is IEEE 754's default and keeps sums of rounded values unbiased, which is what money wants. |
| 24 | + |
| 25 | +### Overflow: operators panic; conversions return `Result` |
| 26 | + |
| 27 | +`Num`'s methods return `a`, not `Result<a, e>`, so `+`, `-`, `*` (and `negate`, `round`, `from_int`) **panic on overflow**, as division by zero already panics everywhere in the language. Money must never wrap (the `U64` answer), and promotion to a wider type would be a second representation (the `Int` answer) with a canonicalization problem of its own. Where the signature allows it, failures are values: `parse` and `from_float` return `Result`, and `from_scaled` reports an out-of-range integer as `False`. `/` by zero panics. |
| 28 | + |
| 29 | +### No literals |
| 30 | + |
| 31 | +Following the `U64` precedent (ADR 0035: `u64.from_int(n)`, no literals), there is **no `1.20d` suffix**. It would touch the lexer (`1.20d` lexes as `FLOAT` + `IDENT` today), both token kinds and both grammars plus the legacy pair, HIR and Core `Lit`, inference, codegen's `atom()`/`static_field`/`switch_lit`, the interpreter's `Val`, and the tree-sitter grammar — a large change whose payoff is writing `1.20d` instead of a parsed or scaled construction. `dec.parse "1.20"` and `dec.from_int` cover it; money arrives from databases and strings in practice, not from source text. The issue listed the full path; it is recorded here so a future ADR can revisit it with the cost already written down. |
| 32 | + |
| 33 | +### No implicit `Float`↔`Dec`, ever |
| 34 | + |
| 35 | +ADR 0034's spirit: conversions are named functions. `dec.from_float` goes through the float's shortest decimal text (`0.1` the float is `"0.1"` the string is `0.1` the `Dec`), so it gives the decimal the user wrote, not the binary expansion; NaN and infinities are an `Error`, as is an out-of-range float. `dec.to_float` is the nearest double to the exact decimal (show, then a correctly rounded parse). Both are explicit calls. |
| 36 | + |
| 37 | +### `std/dec` |
| 38 | + |
| 39 | +`@builtin pub type Dec` with externs, then `impl Num/Eq/Ord/Show/Debug/Hash/Default`, modeled on `std/u64.lse` (coherence: the type's module; no prelude or type-checker change, no `WellKnown` entry — the checker never names the type, as with `U64`): |
| 40 | + |
| 41 | +- `from_int(n)` (exact; panics on overflow), `to_int(x)` (truncates toward zero); |
| 42 | +- `from_float(x)` / `to_float(x)` as above; |
| 43 | +- `parse(s)` / `show`: `show` trims trailing zeros and drops the point of an integral value (`1.20` shows as `"1.2"`, `42` as `"42"`); `parse` takes an optional sign, digits, an optional point and more digits (no exponent), rounding half-even past 18 places; |
| 44 | +- `scaled(x)` / `from_scaled(n)`: the raw count of 10^-18 units as an `Int` (a big integer outside 63 bits), for binary codecs — the postgres `NUMERIC` codec is built on it; |
| 45 | +- `round(x, ~places:)`: half-even to `places` decimal places (`0..=18`), for money; |
| 46 | +- `hash` is `mix(hash_limbs(negative, [lo, hi]))`, the big-integer scheme over the two limbs, pinned by tests so both backends agree. |
| 47 | + |
| 48 | +Both backends compute alike (the parity rule): the kernels — arithmetic with its rounding, parse, show, `round`, the hash — live in `louise_rt_prims` over `num-bigint` intermediates for `*` and `/` (already linked into every native program for `Int`, so no new dependency weight), and the interpreter gains a `Val::Dec(i128)` variant. |
| 49 | + |
| 50 | +### PostgreSQL `NUMERIC` (OID 1700) |
| 51 | + |
| 52 | +The postgres package gains `Value.Decimal(Dec)`, declares OID 1700 in `Parse` (the type is unambiguous, like `Bytea`), binds in binary, and reads both formats: |
| 53 | + |
| 54 | +- **Binary** (`ndigits`, `weight`, `sign`, `dscale`, then base-10000 digits): decode sums the digits as an exact `Int`, scales by 10^18 with half-even rounding when the value has more than 18 places (the same rule as `parse`), and is an `Error` on `NaN`/`Infinity` or an integral part out of range. Encode is always exact: 18 places fit `NUMERIC`'s 16383. |
| 55 | +- **Text** is `dec.show` / `dec.parse`. |
| 56 | + |
| 57 | +"Round-trips without loss" (the issue's acceptance) therefore means: every `Dec` encodes exactly, and every `NUMERIC` within `Dec`'s range decodes exactly or, past 18 places, with the one documented rounding. Unrepresentable values are errors, never silent truncations. |
| 58 | + |
| 59 | +### Deferred |
| 60 | + |
| 61 | +Unboxed workers (ADR 0045's child, the generalized boxing analysis) should eventually cover `Dec` arithmetic; boxing every result costs an allocation per operation, as with `U64` (ADR 0035). Not required here. |
| 62 | + |
| 63 | +## Consequences |
| 64 | + |
| 65 | +- Money can be represented exactly: `0.1 + 0.2 == 0.3` holds. |
| 66 | +- Every `Dec` operation on the native backend allocates a block (24 bytes), as `Float` and `U64` do. |
| 67 | +- `louise_rt_prims` gains a `num-bigint` dependency (its first beyond optional `ring`); native programs already link it for `Int`. |
| 68 | +- `1.20` written in source stays a `Float`. Users who mean money must say so (`dec.parse`), which is the point of the no-implicit-conversion discipline, if occasionally inconvenient. |
| 69 | +- The postgres package dev-depends on `gen` for `Dec` property tests — the first use of ADR 0064's `[dev-dependencies]` for a std type, since std itself cannot depend on a package and `tests/run` programs compile against std only. |
| 70 | + |
| 71 | +## Alternatives considered |
| 72 | + |
| 73 | +- **A scale in the value (true `NUMERIC` semantics):** preserves `1.20`'s two places; needs a canonicalization rule before equality can shortcut, and a variable-size representation (bigint-backed) for `dscale` up to 16383 — a much larger runtime surface for a display concern. |
| 74 | +- **Bigint-backed decimal:** unbounded range and places; every operation allocates variable-size limbs, and equality still needs canonicalization. |
| 75 | +- **Wrapping arithmetic (the `U64` answer):** silently wrong money. Rejected. |
| 76 | +- **`Result`-returning operators:** breaks `Num`'s shape; callers that want checks get them through `from_scaled`/`parse`/`from_float`. |
| 77 | +- **A `1.20d` literal:** rejected above; the full touch list is recorded for a future ADR. |
| 78 | +- **Text-only `NUMERIC` codec:** simpler, but the driver's rule is binary where a codec exists (so results come back binary), and the binary form is exact and compact. |