DS Unit System#
The DS unit system. Prefix LUNI.
Every conversion this document defines, tier-2 and unit formula included, is
bit-identical on every engine ([LUNI.18.3]); bitexact and nofpu are not
capabilities. §17 and §18 record what is outstanding for embedded targets;
they are non-normative. §15 states the
unit-name resolution rules, and [LLEX.12.5] cites it as their home.
1. Philosophy [LUNI.1]#
Units are first-class types. The unit system enforces dimensional correctness at compile time, auto-converts within dimensions, and requires explicit formulas for cross-dimension relationships. There are no implicit coercions that change physical meaning.
The standard library (units.si) follows the SI International System of Units
(9th edition, 2019) exactly. Where SI makes distinctions that pure dimensional
analysis would collapse, the DS unit system follows SI:
frequency(Hz) andradioactivity(Bq) are separate dimensions even though both are dimensionally1/s. Adding a decay rate to a signal frequency is a compile error.absorbed_dose(Gy) andequivalent_dose(Sv) are separate dimensions even though both are dimensionallyJ/kg. The biological weighting context is distinct.
This is the same protection the unit system provides everywhere: the compiler rejects physically meaningless arithmetic even when the dimensional formula happens to be identical.
2. Rational type [LUNI.2]#
2.1 Definition [LUNI.2.1]#
Rational is an exact compile-time numeric type representing p/q where p and q
are integers, q > 0, stored in reduced form (GCD-reduced, sign on numerator).
Integers are a subset: 5 = Rational(5, 1).
2.2 Literal syntax [LUNI.2.2]#
INT_LIT / INT_LIT — wherever it appears in DS — produces a Rational node,
reduced to lowest terms at parse time. This is uniform across all contexts:
unit expressions, const declarations, rule expressions. There are no
exceptions.
Division by literal zero is a compile error (DS_VALIDATE_DIV_BY_ZERO). // remains floor division for
Int // Int. / with at least one non-literal operand is runtime division.
2.3 Type hierarchy and promotion [LUNI.2.3]#
Int → Rational → Float
Both are implicit widening promotions (no change in meaning, only precision).
These are categorically different from the coercions the unit system forbids:
Float → celsius changes physical meaning; Rational → Float only reduces
precision.
Rational * Rational→RationalRational * Int→Rational(Int promoted ton/1)Rational + Float→Float(Rational promoted to float64)Float * 5/9→Float(5/9 promoted to 0.5555…)
2.4 Compile-time only [LUNI.2.4]#
Rational is a compile-time constant type. Rational literals in rule expressions promote to Float at runtime. The
compiler folds all Rational arithmetic before code generation, exactly: at compile
time a Rational's numerator and denominator are integers of any size. What becomes
of a constant that a runtime value cannot hold is [LUNI.2.4.1]'s.
see also: LUNI.2.4.1
[LUNI.2.4.1] A constant the compiler emits must fit the runtime value it
becomes. The compiler emits an exact constant as an Int or as a Float. It
must refuse, with DS_VALIDATE_CONSTANT_OUT_OF_RANGE, a constant it must emit
as an Int whose exact value lies outside the 64-bit signed range, and one it must
emit as a Float whose value rounds past the largest finite Float. It must
not wrap, truncate or saturate either. The constants are:
a unit literal's value in its base unit ([LUNI.3.1.9]), refused at the literal;
a unit's constants ([LUNI.4.3]), refused at the unit's declaration: in integer storage the integers $P$, $Q$ and $R$ that [RLOW.6.1.10] writes and the $-R$ that [RLOW.7.3.9] writes, so an $R$ of $-2^{63}$ is refused, and in
float64storageaandbas [LUNI.2.7.1] rounds them. Anathat is not zero and rounds to zero is refused the same way, since its inverse has no value;in integer storage, a value known at compile time that a
callfolds into a kwarg's unit ([RLOW.7.3.9]), refused at thecall.
Int arithmetic is not a constant the compiler emits: it wraps, folded or not
([LEXP.7.13.1], [LEXP.8.8.1]). A literal written past its range is a lexer error
([LLEX.11.1.5], [LLEX.11.2.4]).
ratified — see also: LEXP.7.13.1, LEXP.8.8.1, LLEX.11.1.5, LLEX.11.2.4, LUNI.2.7.1, LUNI.3.1.9, LUNI.4.3, RLOW.6.1.10, RLOW.7.3.9
2.5 Compile-time arithmetic [LUNI.2.5]#
Op |
Rule |
|---|---|
|
|
|
|
|
|
|
|
|
|
2.6 Interaction with pi and transcendentals [LUNI.2.6]#
math.pi ([LIMP.3.3.4]) is a Float constant, the binary64 nearest π.
Rational * math.pi → Float. Exact rational
arithmetic stops at the transcendental boundary; the compiler does not attempt
symbolic representation of irrationals.
see also: LIMP.3.3.4
2.7 Cross-host baking determinism [LUNI.2.7]#
[LUNI.2.7.1] The compiler bakes Rational→float64 conversions and the tier-2
build-time round-trip test ([§4.3]) using round-to-nearest-even (IEEE 754
roundTiesToEven) and a fixed left-to-right evaluation order. The same
.ds source therefore yields byte-identical baked factors in the emitted
.dsc on any IEEE-754-compliant build host — DSC reproducibility holds at the
unit-system layer.
Concretely: an affine factor = <expr> ([§4.3]) is folded as a Rational
operand-by-operand left-to-right, then a single roundTiesToEven cast to
float64 produces the baked constant. A tier-2 to_base/from_base pair
applies the same roundTiesToEven rule to every intermediate float64
operation. No host-dependent transcendental enters the bake — irrational
factors (e.g. year_tropical, [§16.2]) are pre-rounded to their pinned
int64-ns constant at spec-authoring time and committed as such, never
re-derived from float64 at build.
The device side carries the other half of the guarantee: a runtime MUST
use the baked constant as emitted and MUST NOT recompute the factor. A
tier-1 conversion is then a·x + b in correctly-rounded basic operations, and
so cross-platform bit-exact; recomputing the factor on-device forfeits that.
3. Unit literal syntax [LUNI.3]#
3.1 The _ separator [LUNI.3.1]#
A unit literal is a numeric literal, an optional _ separator, and a
unit symbol. That holds for every unit including the three plane-angle
glyphs ° ′ ″.
The _ is the orthographic stand-in for the SI inter-token space, and DS
neither requires it nor forbids it: 30s and 30_s are the same
literal, and so are 45° and 45_°. Neither direction of the SI
spacing rule is enforced: people are too
inconsistent about how they write these things for a prohibition to be
worth its cost, and a rule that is hard to enforce is harder to explain.
What SI decides instead is the canonical form, which is a different job from the accepted one ([LUNI.3.1.6]).
The production is [LLEX.12]'s UNIT_LIT, whose '_'? is this optional
separator; its UNIT_SUFFIX is restricted by [LUNI.3.1.5]. The plane-angle
glyphs have no production of their own: they are UNIT_SUFFIX characters like
Ω or µ ([LUNI.3.2]), and the one production covers 45°, 45_°, 30′
and 45″ alike.
Because the separator is optional it does not mark a unit
structurally, so the reserved-letter rule of [LUNI.3.1.5] is what
carries the disambiguation instead: it is what keeps 5i out of
the unit grammar and 1e6 a float rather than reading either as a unit.
ratified — see also: LLEX.11.1, LLEX.12, LUNI.3.1.5, LUNI.3.1.6, LUNI.3.2
[LUNI.3.1.1] _ is optional on a decimal prefix, and that holds for every
unit. Every unit accepts the separator and none requires it: 5_s and 5s are the same literal, as
are 100_km / 100km, 23_°C / 23°C, 100_Ω / 100Ω, 45_deg /
45deg — and 45° / 45_°, 30′ / 30_′,
45″ / 45_″.
⚠ The numeric prefix is decimal. Hex, binary and octal prefixes are not unit-literal prefixes at all ([LUNI.3.1.8]) — they are ambiguous with the integer literals they are built from. So the separator is optional universally, with no exception on either the unit or the base.
SI decides the canonical spelling of a quantity, and it is carried by what the toolchain renders, not by what it refuses ([LUNI.3.1.6]).
One apparent exception is not one: 50% is a syntax error, because a
bare % is the modulo operator rather than a unit symbol
([LUNI.3.1.3]). That is an operator collision, not a spacing rule.
see also: LUNI.3.1.8, LUNI.3.1.3, LUNI.3.1.6
[LUNI.3.1.3] Percent vs modulo. % is always the modulo operator
([LGRA.9.2.1]) and never a unit symbol: it is not a UNIT_SUFFIX character
([LUNI.3.2]). A percentage is written with the percent unit or its alias
pct: 50_percent and 50_pct are 0.5. % is that unit's label, which
is display only and gives no way to write the unit ([LUNI.5.2.1]).
So 50% alone is a dangling-modulo syntax error, and the lexer refuses
50_%, whose _ no unit suffix follows ([LLEX.11.1]), both as DS_PARSE_GENERIC.
see also: LGRA.9.2.1, LLEX.11.1, LUNI.3.2, LUNI.5.2.1
[LUNI.3.1.4] Adjacency commits to a unit, never to multiplication.
A numeric literal directly adjacent to a letter token is a unit
literal: 30x is thirty of a unit named x, and if no such unit is
declared it is an unknown-unit error — not 30 * x.
The reading does not compete with an arithmetic one: an author who means multiplication writes the operator. The diagnostic for an unknown unit should nevertheless say so, because the mistake is easy to make and the fix is a single character.
[LUNI.3.1.5] Scientific literals are unaffected. 1e6 (FLOAT_LIT
scientific) keeps its standard spelling. With the separator optional, the
machinery that keeps it apart from a unit literal is load-bearing, not
belt-and-braces: the e<digit> shadow rule
([LLEX.11.2]) is what decides the case, and removing
it makes 1e6 ambiguous.
The rule, stated as the lexer applies it: a numeric followed directly by
a suffix is a unit literal unless the suffix is an e/E followed by
digits (scientific), or a bare i or j. So 1e6 is a float while 1eV
is electronvolts, and 5in is inches.
Bare i/j is withheld from UNIT_SUFFIX outright ([LLEX.11.3.1]), and
COMPLEX_LIT is not a v1 token class ([LUNI.14]) — so 5i and 5_i
alike reach no token class, and the compiler refuses them with
DS_VALIDATE_COMPLEX_NOT_IN_V1 ([LUNI.14.9]). The separator does not
change the reading: it is optional, so it cannot be what distinguishes
them. A literal in a dimension stored as an integer is [LUNI.3.1.9]'s.
see also: LLEX.11.2, LLEX.11.3.1, LUNI.14, LUNI.14.9, LUNI.3.1.9
[LUNI.3.1.9] A literal in an integer-stored dimension is a whole number of
its base unit. Where the literal's dimension declares storage int64 or
int32 ([LUNI.4.1.1]), the compiler converts the literal to the base unit
exactly ([LUNI.2.4]) and lowers it as an Int ([LUNI.8.7.3]). The compiler
must refuse a literal whose value is not a whole number of the base unit
(DS_VALIDATE_UNIT_LITERAL_NOT_WHOLE), and must not truncate or round it:
1.5_us is 1500 nanoseconds, and 0.5_ns and 1.5_bit are refused. A negated
literal is checked after negation, with the value [LUNI.3.3] gives it. A whole
number outside the 64-bit signed range is [LUNI.2.4.1]'s.
A value computed at run time that lands in integer storage is [LUNI.7.2]'s.
ratified — see also: LUNI.2.4, LUNI.2.4.1, LUNI.3.3, LUNI.4.1.1, LUNI.7.2, LUNI.8.7.3
[LUNI.3.1.6] Canonical form is SI, and canonical is not the same job as accepted.
The accepted set is wide ([LUNI.3.1.1]): the separator may be present or absent anywhere. The canonical spelling is exactly one of those, and it is the SI one — the separator before a unit symbol, none before a plane-angle glyph.
Where canonical binds is presentation, not acceptance. Anything the toolchain renders — a diagnostic's suggested spelling, a formatter's output, an example in a message — writes the canonical form. Nothing rejects the other one.
What the compiler shows teaches the convention at the moment the author is
looking, and costs nothing when they ignore it. So a diagnostic's example is
load-bearing: a suggestion for a plane-angle literal writes 45°, not 45_°.
see also: LUNI.3.1.1
[LUNI.3.1.7] The suffix must name a declared unit. Adjacency commits to a unit ([LUNI.3.1.4]), so a suffix that is not a declared or imported unit symbol has no other reading available: it is a compile error, and the diagnostic names the suffix and the literal it was attached to.
ratified — see also: LUNI.3.1.4
[LUNI.3.1.8] A unit literal's numeric prefix is decimal. Hex, binary and octal prefixes are excluded, and the exclusion is forced rather than chosen: the based form is ambiguous with the integer literal it is built from, provably and from the clause text alone.
[LLEX.11.1]makes_an internal digit separator inHEX_LIT, and aUNIT_SUFFIXmay be spelled entirely from characters that are also hex digits. Whenever it is, both productions match the same input at the same length:input
as
HEX_LITas a based unit literal
0xFF_FF0xFFFF= 655350xFFwith unitFF0xFF_A0xFFA= 40900xFFwith unitA— 255 amperesThe two readings are opposite and a lexer has one priority ordering, so either setting is wrong for one of these rows.
Ais the SI symbol for the ampere; the collision is not contrived on either side.0xFF_FFis the spelling the numeric-literal examples use and[LLEX.11.1]grants it directly, so any resolution reading it as a unit literal breaks a documented integer form.A decimal prefix has no such overlap:
DEC_LITadmits no letters, so noUNIT_SUFFIXcan continue it.
3.2 Unit suffix token class [LUNI.3.2]#
UNIT_SUFFIX, UNIT_START and UNIT_CONT are [LLEX.12]'s productions.
UNIT_SUFFIX is not constrained to the NAME identifier class. It starts with any
ASCII letter or one of the SI Unicode characters and contains letters, digits,
_, or those same characters. Case-sensitive.
_ is in UNIT_CONT only: a _ before the first character of a suffix is
the separator ([LUNI.3.1]), so 5_meter_squared is 5, the separator and
meter_squared.
ₙ is in UNIT_CONT only, deliberately: a subscript never begins a unit
symbol, it qualifies the letter before it. Admitting it to UNIT_START would
let a symbol open with a mark that modifies nothing.
The allowed non-ASCII characters in UNIT_SUFFIX are:
°(U+00B0 DEGREE SIGN) — for°C,°F,°R, and for degree itself′(U+2032 PRIME) — for arcminute″(U+2033 DOUBLE PRIME) — for arcsecondΩ(U+03A9 GREEK CAPITAL OMEGA) — for ohmµ(U+00B5 MICRO SIGN) — forµs,µA,µm, etc.Å(U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE) — for ångströmₙ(U+2099 LATIN SUBSCRIPT SMALL LETTER N) — forgₙ, standard gravity. Continuation only, per the production.
The lexer normalises confusable look-alikes automatically:
μ (U+03BC GREEK SMALL LETTER MU) → µ (U+00B5)
Ω (U+2126 OHM SIGN) → Ω (U+03A9)
ʹ (U+02B9 MODIFIER LETTER PRIME) → ′ (U+2032); ʺ (U+02BA MODIFIER LETTER DOUBLE PRIME) → ″ (U+2033)
The three plane-angle glyphs — ° (degree), ′ (arcminute) and
″ (arcsecond) — are ordinary UNIT_SUFFIX characters ([LLEX.12.2]).
′/″ are Unicode-only: ASCII '/" are not aliases, since " is the
string delimiter. No other non-ASCII characters are permitted.
ratified — see also: LLEX.12, LLEX.12.2, LUNI.3.1
3.2.1 Spacing class and the degree dual-role [LUNI.3.2.1]#
The separator is optional for every unit ([LUNI.3.1.1]), so
45° and 45_° are both degree, and 23°C and 23_°C are both
celsius.
What the degree glyph does have is a dual role in the suffix
alphabet: ° is both a complete suffix on its own (degree) and the
first character of longer suffixes (°C, °F, °R). The lexer takes
the longest suffix available, so 45° is degree and 45°C is celsius —
resolved by the suffix, not by the separator.
Canonical name vs Unicode alias convention#
The standard library uses ASCII word forms as canonical unit names (the name
valid in schema field declarations) and Unicode SI symbols as aliases (valid
in unit literals only, per §7.5). One deliberate exception: Hz is the
canonical name for hertz (not hertz), because freq: Hz is the universal
convention in practice and freq: hertz would surprise every user. Examples:
Canonical name |
Unicode alias |
Schema field |
Literal |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Authors who prefer the Unicode form in literals may use it freely. Schema field declarations always use the ASCII canonical name.
see also: LUNI.3.1.1
3.3 Negative unit literals [LUNI.3.3]#
A unary minus whose operand is a unit literal, written with or without
parentheses around it, negates the literal's number. -10_celsius is the
quantity whose number in celsius is −10. The compiler must convert −10
through the unit's formula ([LUNI.4.3]), giving 263.15 K, and must not
negate the converted base-unit value, which would give −283.15 K.
The time units are the exception. A Duration is never negative
([LTIM.1.3.1]), so the compiler must refuse a unary minus on a
value of the time dimension ([LTIM.1.3.5]), a unit literal such as -15_min
among them, with DS_VALIDATE_BAD_OPERAND_TYPE ([LEXP.7.10]). A position whose own clause
refuses a negative duration — within ([LGRA.2.8.10]), a rate modifier
([LGRA.6.6.7]), after ([LTAC.7.1]) — refuses it as that clause says.
A unary minus on any other operand, such as a slot, a binding or a larger expression, negates the stored base-unit value ([LUNI.7.2]).
For a unit whose formula only scales, the two readings agree. They differ
for a unit whose formula adds a constant, such as celsius or fahrenheit.
ratified — see also: LEXP.7.10, LGRA.2.8.10, LGRA.6.6.7, LTAC.7.1, LTIM.1.3.1, LTIM.1.3.5, LUNI.4.3, LUNI.7.2
3.4 Complex literals — COMPLEX_LIT [LUNI.3.4]#
Not v1. This is the surface syntax of the
complextype, which is deferred ([LUNI.14]). No v1 lexer producesCOMPLEX_LIT, and5iis refused ([LUNI.14.9]), not read as a complex literal. Everything below describes the token as it will be when the type is built. It is kept in §3 beside the literal forms v1 does admit only because thei/jsuffix reservation in [LUNI.3.1.5] is live and needs something to point at.
Complex number literals use a bare i or j suffix with no _ sigil. These are
a distinct token class from unit literals:
COMPLEX_LIT ::= (INT_LIT | FLOAT_LIT | SCI_LIT) ('i' | 'j')
i and j are the same type and produce identical values (see §14). Display
convention is set at the module or interpolation site, not in the value. No lexer
ambiguity: identifiers cannot start with a digit, so 2i is always COMPLEX_LIT,
never INT(2) NAME(i).
Deferred: not binding in this edition.
see also: LUNI.14, LUNI.14.9, LUNI.3.1.5
4. Declaration system [LUNI.4]#
All unit-system declarations begin with the unit keyword:
unit_decl ::= unit_dimension # [LUNI.4.1] a physical dimension
| unit_scalar # [LUNI.4.2] a dimensionless scalar group
| unit_symbol # [LUNI.4.3] a unit within a dimension or group
| unit_formula # [LUNI.4.5] a cross-dimension formula pair
| unit_fx_pair # [LUNI.4.6] a runtime-rate currency conversion
Residue the grammar does not carry: the second token selects the form. One
of [LUNI.4.4]'s four form words — dimension, scalar, formula, fx_pair —
selects its form when no : follows it. Any other second token, or a form word
followed by :, begins a unit_symbol.
see also: LUNI.4.1, LUNI.4.2, LUNI.4.3, LUNI.4.4, LUNI.4.5, LUNI.4.6
4.1 unit dimension [LUNI.4.1]#
unit_dimension ::= 'unit' 'dimension' NAME 'storage' NAME 'base' TYPE_SYM NEWLINE
Declares a physical dimension. storage is the runtime storage type for all
fields of this dimension. base names the base unit (must be declared subsequently
or inline).
ratified — checks: alloy
[LUNI.4.1.2] The baked base. The seven SI base dimensions and their
canonical anchors are primitive: they are the coordinate axes of the
dimensional algebra, always in scope, and non-redefinable (a redeclaration is
DS_VALIDATE_UNIT_IMPORT_COLLISION). They are
not content an author imports — they are the basis everything else is
expressed over. The compiler pre-loads them as an implicit module
units.core, a .ds module of the library the compiler ships with
([LIMP.3.3.1]), read from there on every compilation:
Dimension |
Storage |
Anchor |
|---|---|---|
|
int64 |
nanosecond |
|
float64 |
meter |
|
float64 |
kilogram |
|
float64 |
kelvin |
|
float64 |
ampere |
|
float64 |
mole |
|
float64 |
candela |
units.core provides, for each base axis, the anchor unit above and its
canonical short alias — nanosecond/ns, meter/m, kilogram/kg,
kelvin/K, ampere/A, mole/mol, candela/cd — so the short-form base
literals resolve with no import.
The time axis is baked in full, at every scale [LUNI.10.2] declares on it —
microsecond/us, millisecond/ms, second/s, minute/min, hour/h
and day/d, alongside the nanosecond/ns anchor. It is the one axis whose
literals occupy core grammar positions — cooldown
([LGRA.6.6]), after ([LTAC.2.1]), ttl, within, sliding and tumbling — so
a duration literal is a term of the language rather than library content, and
making those productions depend on an import would leave them unwritable in a
file that imports nothing. minute, hour and day are baked with the rest
despite being non-SI: the set an author reaches for is the set that must be in
scope.
A program uses 5_kg, 100_m, 30_s and 5_min with no import. Scaled and
prefixed forms on the other six axes (gram, kilometer, …), affine units
(celsius), and the derived SI units (watt, Hz, …) are not baked: they
are declared in units.si, which builds on units.core and may not redeclare a
base axis. Only these 7 axes are baked — the six non-time axes at anchor plus
short alias, time at every scale [LUNI.10.2] declares — and everything else,
SI or otherwise, is earned by declaration.
ratified — see also: LGRA.6.6, LIMP.3.3.1, LTAC.2.1, LUNI.10.2
[LUNI.4.1.3] Dimension representation. A dimension is an integer
exponent vector over the axis set — the 7 baked axes plus any
declared independent axes ([LUNI.4.1.4]). watt is (length=2, mass=1, time=−3). A non-base unit dimension introduces either a
derived dimension (a span of existing axes) or a new independent
axis.
see also: LUNI.4.1.4
[LUNI.4.1.4] Declared independent axes. A unit dimension whose
quantity is not spanned by the existing axes introduces a new
independent axis — primitive in the dimensional sense, but not baked.
Two flavours exist in the standard library:
fixed-ratio —
data(base bit, int64; bit↔byte = 8): ordinary compile-time conversion.runtime-ratio —
currency_usd/currency_eur/currency_cny, each its own axis (int64 minor units): cross-axis conversion is runtime, fact-sourced (unit fx_pair/FxRate, §4.6 / LUNI.13), never an implicit compile-time factor.
Dimensionless quantities (angle, proportion) are not axes; they
are unit scalar groups (§4.2).
The time dimension is special: storage int64 base nanosecond
([LUNI.10.2]).
[LUNI.4.1.5] A dimension or a unit is its declaration. The compiler must treat each
unit dimension and unit scalar declaration as one dimension or scalar group
of its own. Two declarations are two, whatever their names, storage types and
units, so a value of one meeting a value of the other is [LUNI.8.2]'s error. A
file that imports a declaration holds that declaration: units.customary's
psi and units.si's pascal share pressure, which units.customary imports.
Each unit symbol's declaration is one unit of its own, with its own scale and
label ([LUNI.4.3], [LUNI.11.2]). Two libraries' marks in one dimension are two
units: a value of one meeting a value of the other converts as any two units of
a dimension do ([LUNI.8.1]), and x::mark naming the other is no identity
([LCST.4.5.1]), so the compiler must refuse it ([LCST.4.5.3]). A slot or a
constant holds the unit its declaring file resolved ([LIMP.1.5]).
A dimension, a scalar group, a unit and an opaque type have no own name ([LIMP.13.1]). A slot's artefact holds its kind ([RDSC.5.5.4]), and nothing past the source tells two of them apart.
ratified — see also: LCST.4.5.1, LCST.4.5.3, LIMP.1.5, LIMP.13.1, LUNI.11.2, LUNI.4.3, LUNI.8.1, LUNI.8.2, RDSC.5.5.4
4.1.1 Storage types [LUNI.4.1.1]#
v1 admits three storage types:
Storage |
Width |
Use |
|---|---|---|
|
4 B inline |
Small counted quantities (rare for |
|
8 B inline |
The default integer storage — time (nanoseconds), currency (cents / minor units), counted quantities |
|
8 B inline |
IEEE 754 binary64 — physical quantities (length, mass, temperature, …) |
4.2 unit scalar [LUNI.4.2]#
unit_scalar ::= 'unit' 'scalar' NAME 'storage' NAME unit_label? NEWLINE
unit_label is [LUNI.4.3]'s. Declares a dimensionless scalar group. Same mechanics as unit dimension — units
within the group are interchangeable, affine conversions apply — but signals to
readers and tools that the quantity has no physical dimension.
Angle — a dimensionless scalar group#
angle is declared as a unit scalar, not a unit dimension. Radians are
physically dimensionless (arc length / radius; units cancel). This makes exp(),
sin(), cos(), tan() accept angle values naturally without special carve-outs.
All angle values are stored in radians (base unit), so 45_deg and
0.7854_radian are the same value converted. The ° / ′ / ″
glyph aliases take the separator as every unit does, optionally
([LUNI.3.2.1]): 45° and 45_° are both degree.
see also: LUNI.3.2.1, LUNI.4.3
Solid angle — also a scalar group [LUNI.4.2.1]#
solid_angle is likewise a unit scalar, not a unit dimension
(steradian is dimensionless, sr = m²/m²) — consistent with angle. The
physical distinction lumen ≠ candela (luminous flux is not luminous
intensity) is preserved by the named-distinction mechanism — the
same device that keeps Hz ≠ Bq and Gy ≠ Sv — so luminous_flux is a
named-distinct dimension, not defined as cd·sr. Steradian carries
no exponent.
Standalone dimensionless units (no derived units, no interconversion) are also declared as scalars with a single unit member — every dB-family variant (generic, full-scale, carrier-relative, SPL, antenna gain) is one of these.
4.3 unit <symbol> : <dimension> [LUNI.4.3]#
unit_symbol ::= 'unit' TYPE_SYM ':' NAME unit_inline # base or tier-1
| 'unit' TYPE_SYM ':' NAME ':' unit_label? NEWLINE # tier-2
INDENT
'to_base' ':' expression NEWLINE
'from_base' ':' expression NEWLINE
DEDENT
unit_inline ::= ('=' expression)? unit_label? unit_aliases? NEWLINE
unit_label ::= 'label' STRING_LIT
unit_aliases ::= 'alias' TYPE_SYM (',' TYPE_SYM)*
Residue the grammar does not carry: label and alias are not reserved
words. Each is read as this production's keyword only when a string literal
follows label, or a symbol follows alias; elsewhere either is an ordinary
name. That a tier-1 expression is affine in x, and what a tier-2 body may use,
are the rules below.
The base unit of a dimension is the one its unit dimension names as base, and
of a unit scalar group ([LUNI.4.2]) the first declared. All values are stored
internally in base units. A unit_inline with no = declares the base unit. The
compiler must refuse a unit_inline with no = that declares any other unit,
with DS_VALIDATE_UNIT_BODY_MISSING. A unit that equals the base writes = x.
Tier-1 affine conversions#
= <affine_expr> uses variable x (the value in the declared unit), constants,
+, -, *, / (Rational division), **, parentheses, and math's pi. The compiler
must check that the expression is affine in x, reducing to a*x + b with
a not zero, and must refuse one that is not with
DS_VALIDATE_UNIT_BODY_NOT_AFFINE. A body whose x term vanishes, such as
= 5 or = x * 0, has no inverse. A negative a is a unit whose numbers run
against the base unit's. The inverse x = (y - b) / a is derived automatically. Conversion factors a and b are
extracted as exact Rationals ([LUNI.2.4]). Where the dimension's storage is
float64 they are stored as float64 ([LUNI.2.7.1]). Where it is an integer they
stay exact, and each conversion is Int arithmetic over them that gives a whole
number of base units or raises ([RLOW.6.1.10], [RLOW.7.3.9]).
Tier-2 non-affine conversions (same dimension)#
For rare same-dimension conversions that are not affine (e.g. empirical viscosity scales, psychoacoustic scales). Both directions are required.
Expression vocabulary extends tier-1 with sqrt, abs, ln, log10, log2,
exp, and ** with any exponent, each correctly rounded ([LEXP.3.9.2]). The
expression is evaluated as it is written, one rounded operation at a time
([LDET.3.4.4]). No trigonometric functions. The compiler must refuse a
tier-2 body that uses anything outside this vocabulary, with
DS_VALIDATE_UNIT_TIER2_BAD_BODY.
pi, sqrt, ln, log10, log2 and exp are members of math, and a body
reaches them through its file's import of math, as any expression does
([LIMP.3.3.4]).
ratified — see also: LDET.3.4.4, LEXP.3.9.2, LIMP.3.3.4, LUNI.2.4, LUNI.2.7.1, LUNI.4.2, RLOW.6.1.10, RLOW.7.3.9
4.4 Prefixed units are declared [LUNI.4.4]#
All prefixed unit names (kilogram, milliampere, megohm, kilometre, MHz, kPa, etc.) are declared explicitly in the standard library with their correct canonical names and aliases.
Unit symbol resolution is simply: look up the symbol (or alias) in the module's import scope. If not found: compile error. Authors who need a unit not in the standard library declare it explicitly.
4.5 unit formula [LUNI.4.5]#
Cross-dimension named conversions, declared as a pair — one formula in each
direction. Each formula is called at the call site by default; an implicit pair additionally
auto-applies at an assignment boundary ([LUNI.4.5.1]).
A formula's expression may use the transcendental functions and ** with any
exponent, each correctly rounded ([LEXP.3.9.2]), and is evaluated as it is
written, one rounded operation at a time ([LDET.3.4.4]). Every call in it is to a
built-in ([LGRA.9.8.11]).
unit_formula ::= 'unit' 'formula' NAME formula_modifier* ':' NEWLINE
INDENT
formula_line+
DEDENT
formula_modifier ::= 'inverting' | 'implicit'
formula_line ::= NAME '(' NAME ':' TYPE_SYM ')' ':' TYPE_SYM '=' expression NEWLINE
The body holds exactly two formulas, each converting in the opposite direction
to the other; the compiler must reject a body with any other count
(DS_VALIDATE_UNIT_FORMULA_PAIR_ARITY).
Each formula's parameter type and return type name a unit symbol or an alias of
one, declared in the file or imported. A dimension is not a unit symbol. The
compiler must reject any other name (DS_VALIDATE_UNIT_UNKNOWN_SYMBOL).
Modifiers#
The modifiers may be written in either order; each appears at most once.
implicit: compiler auto-applies at an assignment boundary ([LUNI.4.5.1]) when the source and target dimension pair is unambiguous (exactly one implicit formula for that pair). Ordering-preserving.inverting: the function is monotone decreasing — larger input yields smaller output. At variable-to-variable comparisons the compiler flips the comparison operator. Can be combined withimplicit.inverting implicit: auto-applied at assignment, operator-flipping at comparisons.
ratified — see also: LDET.3.4.4, LGRA.9.8.11, LUNI.4.5.1, LEXP.3.9.2
[LUNI.4.5.1] Assignment boundary — enumerated, closed. The positions an
implicit unit formula auto-applies at:
A typed
letbinding, when the annotated type's dimension differs from the RHS expression's.A cross-dimension
where-clause comparison between two pattern-bound variables (a.freq > b.period) —invertingadditionally flips the comparison operator here.A schema-slot keyword argument to
emitorpublish(the same slot-kwarg shape at both).A service
callkeyword argument.
Every other position is a dimension error unless the formula is called explicitly.
ratified
[LUNI.4.5.2] At a comparison, the left operand converts. At the
where-clause boundary of [LUNI.4.5.1] (its second position), the compiler
must apply the pair's formula from the left operand's dimension to the right
operand's, to the left operand alone, and compare the result with the right
operand in the right operand's dimension. The right operand is not converted.
For an inverting pair the compiler must also flip the comparison operator:
< and > exchange, as do <= and >=, and == and != are unchanged.
This is the flip [LUNI.4.5.1] names: a monotone decreasing formula applied to
one side of a comparison reverses its order.
ratified — see also: LUNI.4.5.1
4.6 unit fx_pair [LUNI.4.6]#
Cross-currency formulas backed by runtime, fact-sourced exchange rates.
The conversion factor is never inlined into the .dsc; the compiler emits a
runtime binding that consults the latest matching fact at the conversion
site. The full conversion semantics live in [LUNI.13];
this section pins the declaration form.
unit_fx_pair ::= 'unit' 'fx_pair' TYPE_SYM ':' NAME 'to' NAME NEWLINE
INDENT
'via' NAME 'where' expression NEWLINE
'field' NAME '/' NAME NEWLINE
DEDENT
In order of appearance:
The two names after
:andtoare the from- and to-currencyunit dimensionnames (LUNI.13.2).The name after
viais the schema whose facts publish the rate. By convention this isFxRate(LUNI.13.3); any schema with the right slot shape is admitted.The
whereexpression is the rate selector: a comma- orand-separated equality match on the schema's slots, restricted to string equality.The two names after
fieldnameInt-typed slots of that schema carrying the rate as an exact integer fraction, numerator first. The compiler validates both slots exist and areInt-typed.
Both directions (forward + inverse) are declared as separate unit fx_pairs.
The compiler does NOT auto-derive the inverse by floating-point reciprocation —
that would introduce a 1-ULP drift; authors who want a derived inverse compute
it explicitly with the round mode they intend.
Deferred: not binding in this edition.
see also: LUNI.13, LUNI.13.2, LUNI.13.3
[LUNI.4.6.1] A unit fx_pair whose selector matches no live fact
converts at 1:1. It does not raise, and it does not short-circuit the rule's
continuation.
This follows from the determinism contract ([LDET.1]): a conversion that faults in one deployment and succeeds in another makes behaviour a property of the environment rather than of the rules.
Two facts bound what 1:1 means here. DS never validates a supplied rate —
a stale or wrong FxRate fact produces a wrong result and raises nothing — and
rate freshness is the integrator's concern, so a ruleset written by someone
who cares about currency must still run for someone who does not.
1:1 is the defined semantic for "no rate supplied", not a substitute for a knowable value. No rate exists to compute; where a correct value is computable and the runtime declines to compute it, that is a defect.
The fallback must be observable ([LUNI.13.8] is the house pattern — the dev-default adapter ships a loud do-not-settle warning rather than failing). An implementation must surface that a conversion ran unconverted, through the metric surface or a one-shot warning. Observability does not affect the computed value or control flow, so it does not qualify the rule above — but without it, "converted at 1:1" and "converted correctly" are indistinguishable from outside.
Rates that ARE published are consumed unchanged ([LUNI.13.3]): 1:1 is the fallback when the selector matches nothing, never a replacement for the lookup.
see also: LDET.1, LUNI.13.3, LUNI.13.8
[LUNI.4.6.2] "The latest matching fact" means the greatest asof.
When several live FxRate facts satisfy one fx_pair selector, the
conversion uses the one whose asof ([LUNI.13.3]) is greatest. Ties
on asof are a malformed feed: the conversion uses either, and an
implementation should surface the collision the same way it surfaces
the 1:1 fallback ([LUNI.4.6.1]).
Multiple live matches are the normal case, not an edge case:
FxRate is scope ttl 1_h ([LUNI.13.3]), and a ttl base
accumulates rather than upserting ([LSCP.2.5.7]), so a feed that
republishes hourly has several live facts per pair for most of the
hour.
asof is what the rest of the language already means by the word:
latest on a sequence anchor pins it to its most recent match
([LTHE.2.5.3]), lowered as a timestamp comparison ([LTHE.4.3]).
FxRate carries asof — "rate observation time" — for precisely this
purpose.
This does not force a scan. An implementation may keep a table
keyed by the selector tuple holding the greatest-asof entry seen,
updated on assert and retract; the requirement is only that asof
breaks the tie, not that arrival order does.
see also: LSCP.2.5.7, LTHE.2.5.3, LTHE.4.3, LUNI.13.3, LUNI.4.6.1
[LUNI.4.6.3] Both directions are declared. A conversion in
each direction requires its own unit fx_pair; v1 derives no
inverse. An auto-derived inverse would introduce a Float
round-trip and up to 1 ULP of drift, which an author opts into
deliberately rather than by omission.
5. Compound/derived units [LUNI.5]#
5.1 Naming convention [LUNI.5.1]#
An author's compound unit canonical names should use _per_ as the separator
between numerator and denominator units. Examples:
meters_per_second, kilograms_per_m3, watts_per_m2, millimeters_per_hour.
5.2 Aliases [LUNI.5.2]#
Common short forms are declared as aliases and are valid in unit literals only —
not as schema field types. 23_mph and 23_miles_per_hour both work in
literals (an alias and its canonical unit); schema fields must use the
canonical name.
[LUNI.5.2.1] A label is display only. It creates no way to write the
unit. Only the canonical name and explicit alias entries reach the
symbol table; a label is the string rendered by the u format
specifier ([LUNI.11.2]) and nothing else.
The two are easy to confuse because a label usually looks like a symbol —
label "grad", label "frac" — and a reader of a unit library reasonably
assumes a short form printed beside a unit is one they may type. It is not.
A unit whose label is not also an alias advertises a spelling the compiler
will reject as an unknown unit.
So the rule for an author declaring a unit: if the short form should be
writable, it is an alias; a label is for the reader of output. Where
both are wanted, declare both — they are independent clauses of the same
declaration ([LUNI.4.3]) and naming the same string twice is correct, not
redundant.
[LUNI.5.2.2] A label is the unit's SI-correct symbol. Not an abbreviation someone found readable — the symbol SI actually writes. Where SI has no symbol for a quantity, a label is a convenience and should say so by not looking like one.
This matters because SI distinguishes some symbols typographically, and
a label is a plain string that cannot. Unit symbols are set upright and
quantity symbols italic, so the gram (roman g) and the standard
acceleration of free fall (italic g) are different symbols in SI and
identical as label text.
Standard gravity is the worked case. Labelled "g", g_force would collide
in output with gram's "g" —
two units rendering the same string, with the distinction that separates
them unavailable in the medium. The SI symbol is gₙ, subscript n, and
using it removes the collision by being correct rather than by being
different.
Related, and not the same thing: g-force is not an SI unit at all. The
SI unit of acceleration is m/s², a derived unit with no special name.
gₙ names a conventional constant fixed at exactly 9.80665 m/s², and a
DS unit declaration for it is a convenience for authors who think in g,
not a promotion of it to unit status.
see also: LUNI.5.2.1
5.3 Built-in derived dimensions and units (partial list) [LUNI.5.3]#
Dimension |
Base unit |
Notable units |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
see standard library |
|
|
see standard library |
|
|
|
|
|
|
|
|
|
|
|
see standard library |
|
|
alias |
|
|
|
6. dB family [LUNI.6]#
6.1 Grouped scalars (interconvertible) [LUNI.6.1]#
Units within the same scalar group are interconvertible via affine conversion (offset only — all dB variants of the same reference type differ by a constant).
The affine expression gives the stored base value: = x + c means base = declared + c.
6.2 Standalone scalars (no interconversion) [LUNI.6.2]#
A dimensionless quantity with no derived units and no interconversion is
declared as a unit scalar group with a single unit member.
6.3 dB ↔ linear [LUNI.6.3]#
Non-affine cross-dimension relationships. Outside the unit system. Authors use
explicit let bindings, or via declared unit formula pairs (see §4.5).
7. Unit types in schemas [LUNI.7]#
7.1 Unit names as field types [LUNI.7.1]#
Any declared unit symbol is a valid field type, alongside the primitive types
(Int, String, Bool, …) and Float. The compiler resolves the unit to
its dimension, storage type, and conversion parameters.
A declared dimension name ([LUNI.4.1]) or scalar-group name ([LUNI.4.2]) is a valid field type too. Such a slot is typed by its dimension and names no unit. It holds its value in the dimension's base unit and storage type ([LUNI.7.2]), so a value of the same dimension written to it is converted to the base unit, and the rules of [LUNI.8] apply to it as to any unit-typed slot.
A dimension name is a type only for a slot and for a service kwarg
([LGRA.23.2]). It names no unit, so no unit literal is written with it, and a
let or const annotation refuses it ([LUNI.8.6], [LGRA.4.1]).
Float still works for untyped fields. Migration from Float to a unit type is
gradual and author-driven.
ratified — see also: LGRA.23.2, LGRA.4.1, LUNI.4.1, LUNI.4.2, LUNI.7.2, LUNI.8, LUNI.8.6
7.2 Storage [LUNI.7.2]#
A unit-typed field is stored in the base unit of its dimension, regardless of
which unit was declared. temp: fahrenheit stores values as kelvin (float64) per
§4.1 (base kelvin for the temperature dimension). distance: kilometer stores
as meters (float64). duration: millisecond stores as nanoseconds (int64).
Float→int storage cast (§17.5): when a float64 value lands in a
field whose dimension declares storage int64 (notably the time dimension,
§4.1), the cast uses IEEE 754 roundTiesToEven to avoid ±1-quantum drift across
platforms. Conversion formulas (unit formula, §4.5) that produce a float64
result destined for int64 storage — hz_to_period(x) = 1e9 / x is the
canonical example — apply the same rule at the final cast.
ratified
7.6 Units are the compiler's [LUNI.7.6]#
The compiler must resolve every unit, dimension and conversion, and must lower them to numbers and to the operations the artefact carries ([LUNI.2.7.1]). The engine must not convert a value from one unit to another except by those operations.
What crosses between a host and a slot typed by a unit or a dimension
([LUNI.7.1]) is the slot's stored number, in its dimension's base unit and
storage type ([LUNI.7.2]). An integrator must assert that number, and the number
it reads from the slot, by whichever surface reads it, is that number. A
temp: celsius slot holds an asserted 300.0 as 300 kelvin, and a read of it
gives 300.0.
A host holding a number in any other unit must convert it before asserting it.
Where the number is in the unit the slot names, the slot converts it
([NFCT.1.4.6]). An author may instead declare the slot Float and assert the
unit in the rule ([LUNI.8.5]).
The number a service receives is the one the compiler lowered ([LADP.8.5.2]).
ratified — see also: LADP.8.5.2, LUNI.2.7.1, LUNI.7.1, LUNI.7.2, LUNI.8.5, NFCT.1.4.6
7.3 Modifiers [LUNI.7.3]#
tolerance and the other slot modifiers attach to unit-typed fields
normally. A tolerance literal carries no unit ([LGRA.5.1]): it is a
difference in the field's declared unit, and the compiler converts it to the
base unit by scale only ([LUNI.7.4]).
7.4 Tolerance and offset conversions [LUNI.7.4]#
Tolerance is a difference, not an absolute value. For a slot whose declared
unit converts to its base unit as y = a*x + b ([LUNI.4.3]), the compiler
must write the slot's tolerance in the base unit, converted by scale
only: tolerance_base = |a| * tolerance_declared, where tolerance_declared
is the literal's value: an INT_LIT's integer, or the Float a FLOAT_LIT
reads as ([LLEX.11.2.4]). The offset b is dropped,
so tolerance 1 on a fahrenheit slot is a deadband of 5/9 kelvin, not 1.
A slot declared in its base unit has a = 1. The product is a bundle-bound
value, computed as [LDET.3.3a.7] requires and written as a Float, even where
the dimension's storage is an integer ([LUNI.7.2]).
Slot tolerance ([LUNI.7.3]): the tolerance keyword on a schema slot
declares a physical no-meaningful-change deadband Δ in the slot's
dimension, compared against stored base-unit values ([LFAC.2.5.1]). It is the
keyword's only meaning.
ratified — see also: LDET.3.3a.7, LFAC.2.5.1, LLEX.11.2.4, LUNI.4.3, LUNI.7.2, LUNI.7.3
7.5 Aliases not valid as field types [LUNI.7.5]#
The compiler must reject an alias as a schema field type
(DS_VALIDATE_SLOT_TYPE_ALIAS); only the canonical unit name is valid
there.
ratified
8. Type checking in expressions [LUNI.8]#
checks: alloy×5
8.1 Same dimension — valid, auto-converted [LUNI.8.1]#
+, -, % and the comparisons between values of the same physical dimension
are valid; the compiler converts both operands to the dimension's base unit
before combining, at compile time when an operand is a literal and at runtime
otherwise.
/ and // between values of the same dimension are valid too, and need no
annotation. The compiler converts both operands the same way, and the result is a
bare number ([LUNI.8.3]): / is a Float ([LEXP.7.4]) and // follows the
operand rule ([LEXP.7.5]). A unit scalar group ([LUNI.4.2]) is a dimension for
this clause. The other operators are [LUNI.8.4]'s.
checks: alloy×2 — see also: LEXP.7.4, LEXP.7.5, LUNI.4.2, LUNI.8.3, LUNI.8.4
8.2 Cross-dimension — compile error [LUNI.8.2]#
Operations between values of different physical dimensions (or different
scalar groups, e.g. power_db and proportion) are a compile error, and the
operator decides the code. The compiler must refuse, with
DS_VALIDATE_DIM_MISMATCH, an operator that takes two values of one dimension
when its operands have two: +, -, % and the comparisons ([LUNI.8.1]), and
[LUNI.8.8]'s forms. A *, /, // or ** over two dimensions has a result with
no dimension DS can state, and is [LUNI.8.4]'s refusal, with
DS_VALIDATE_DIM_AMBIGUOUS.
ratified — checks: alloy×2 — see also: LUNI.8.1, LUNI.8.4, LUNI.8.8
8.3 Dimensioned value and bare number [LUNI.8.3]#
A number with no unit is dimensionless. It takes no dimension and no unit from
the operand beside it. A value of a unit scalar group ([LUNI.4.2]) is
dimensioned for this clause.
A bare number scales a dimensioned value: x * n, n * x, x / n and x // n
have x's dimension. [LTIM.4.1.1] states what a Duration scaled this way holds.
The compiler must refuse a bare number beside a dimensioned value with
DS_VALIDATE_DIM_MISMATCH as an operand of +, - or %, in either order, and
in a comparison, a literal zero included. A unit formula's function checks a
bare argument the same way ([LGRA.9.8.11]). n / x and n // x are [LUNI.8.4]'s.
A literal, a slot typed Int or Float, a ::Float strip ([LUNI.8.7.2]) and a
same-dimension quotient ([LUNI.8.1]) are bare numbers. An operand whose type the compiler cannot determine is not one. This
clause does not reach the body of a unit declaration or a unit formula ([LUNI.4.3], [LUNI.4.5]), which is
arithmetic on plain numbers.
ratified — checks: alloy×3 — see also: LGRA.9.8.11, LTIM.4.1.1, LUNI.4.2, LUNI.4.3, LUNI.4.5, LUNI.8.1, LUNI.8.4, LUNI.8.7.2
8.4 Dimensioned × dimensioned — strip and assert [LUNI.8.4]#
No unit algebra. * of two dimensioned values, / and // of two values of
different dimensions, / and // of a bare number by a dimensioned value, and ** or math.pow with a dimensioned operand on either side
produce a result with no dimension DS can state. The compiler must refuse each
with DS_VALIDATE_DIM_AMBIGUOUS, under a let annotation too: an annotation
checks a type the value already has ([LUNI.8.6]). An author who wants the raw
numeric result strips the units on the operands first, and may assert a unit on
the result: (r.w::Float * r.h::Float)::meter_squared.
The strip yields base-unit numbers, and an assertion takes its number as being in
the unit it names ([LUNI.8.5]), so the scale of the result is the author's to state. A value of the
time dimension strips to nanoseconds ([LUNI.7.2]).
This rule applies to both scalar and complex dimensioned values. The built-in
library pre-declares common multiplication results (e.g. watt = volt × ampere,
joule = newton × meter), so those results have a unit to assert.
ratified — checks: alloy×3 — see also: LUNI.7.2, LUNI.8.5, LUNI.8.6
8.5 Unit assertion function [LUNI.8.5]#
Asserting a number into a unit type and stripping a unit back to a number are
:: conversion casts ([LCST.4.5.2]). The number is of the kind the unit's
dimension stores ([LUNI.8.7.3]): Float for a float64 dimension, Int for an
int64 or int32 one. Both casts are total.
<number> → <unit> takes the number as being in that unit: the result is the
value that number names, held in the base unit ([LUNI.7.2]), so 35.0::celsius
is 35 celsius and 5::second is 5 seconds. [RLOW.6.1.10] states how it lowers.
<unit> → <number> strips the dimension and is an identity at runtime. It applies
to a unit-typed value and a dimension-typed value ([LUNI.7.1]) alike, and yields
the stored base-unit number. A strip and an assertion into the dimension's base
unit are inverses. A strip followed by an assertion into any other unit reads the
base-unit number as a number in that unit.
A source of any other kind, such as a String asserted into a unit, has no
conversion and is refused as an undefined pair ([LCST.4.5.3]).
Assigning a number to a unit-typed field without the ::<unit> assertion is a
compiler error; the message suggests the cast form.
ratified — see also: LCST.4.5.2, LCST.4.5.3, LUNI.7.1, LUNI.7.2, LUNI.8.7.3, RLOW.6.1.10
8.6 let binding type annotation [LUNI.8.6]#
A let <name>: <type> = <expr> binding may annotate the bound name, no space
before the colon — consistent with field declaration style. <type> is a scalar
builtin (String, Int, Float, Bool, Json), a temporal type (Time,
Date, Duration, [LTIM.1]) or a canonical unit symbol.
The annotation is a claim about the type the right-hand side already has, and
the compiler must check it. It never converts the value and never drops a
unit; conversion is the :: operator's ([LCST.4]). The check is on the
right-hand side's result, not on the arithmetic that produced it. Once it
passes, the binding has the annotated type.
The compiler must refuse:
a scalar or temporal annotation whose right-hand side is of another kind —
Inton aFloat,Stringon aBool,Timeon aDuration— and a unit annotation on a value that is not a number, withDS_VALIDATE_LET_TYPE_MISMATCH;a right-hand side whose type the compiler cannot determine, with
DS_VALIDATE_LET_TYPE_MISMATCH. A value whose kind is known only at runtime is one ([LCST.4.5.11]): aJsonleaf, a value computed from one, andx ?? dover one, whatever type [LNUL.5.3] gives??;a unitless
FloatorIntannotation on a value that carries a unit, and a unit annotation on a value of another dimension, withDS_VALIDATE_LET_DIM_MISMATCH, unless exactly oneimplicitformula bridges the two dimensions ([LUNI.4.5]);a unit annotation on a bare number ([LUNI.8.3]), with
DS_VALIDATE_LET_DIM_MISMATCH;an alias ([LUNI.7.5]), a dimension name, or a name that is a type but none of those above, such as a schema, with
DS_VALIDATE_LET_BAD_ANNOTATION;a name that resolves to no type, with
DS_VALIDATE_UNKNOWN_TYPE([LGRA.5.7.1]).
A unit annotation on a value of the same dimension is valid and changes
nothing, because the value is held in the dimension's base unit ([LUNI.7.2],
[LUNI.8.1]). Asserting a unit on a number is the ::<unit> cast's ([LUNI.8.5]),
and an annotation answers neither [LUNI.8.4] nor [LUNI.9.2].
ratified — see also: LCST.4, LCST.4.5.11, LGRA.5.7.1, LNUL.5.3, LTIM.1, LUNI.4.5, LUNI.7.2, LUNI.7.5, LUNI.8.1, LUNI.8.3, LUNI.8.4, LUNI.8.5, LUNI.9.2
8.7 Dimension propagation through :: casts [LUNI.8.7]#
A :: conversion cast ([LCST.4.5.2]) whose target is a unit symbol produces a
dimensioned value. The compiler must track that dimension through the
[LUNI.8.1]–[LUNI.8.4] expression checks exactly as it tracks the dimension of
a unit-typed slot ([LUNI.7.1]) or an inline unit literal ([LUNI.4.3]) — a
cast-to-unit result and a native value of that unit are indistinguishable for
every dimensional check.
see also: LCST.4.5.2, LUNI.4.3, LUNI.7.1, LUNI.8.1, LUNI.8.4
[LUNI.8.7.1] A ::<unit> cast carries the target unit's dimension. The
dimension of x::<unit> is the dimension of <unit>. The result must
participate in same-dimension auto-conversion ([LUNI.8.1]), cross-dimension
rejection ([LUNI.8.2]), the bare-number rule ([LUNI.8.3]), and the dimensioned × dimensioned refusal
([LUNI.8.4]).
see also: LUNI.8.1, LUNI.8.2, LUNI.8.3, LUNI.8.4
[LUNI.8.7.2] A ::Float cast strips the dimension. The dimension of
x::Float is none; the result is a bare scalar for every subsequent dimensional
check. This is the author's explicit unit-strip escape hatch already relied on by
[LUNI.8.4]: let q: Float = r.dist::Float / r.mass::Float strips both operands to
Float, removing the dimensioned × dimensioned ambiguity so the division is a
plain Float operation.
see also: LUNI.8.4
[LUNI.8.7.3] Dimension is tracked independently of leaf kind. The static
leaf kind of a ::<unit> cast ([LCST.4] — the Int/Float/String/Bool/Json
classification) is the kind its dimension's storage gives ([LUNI.4.1.1]):
Float for storage float64, Int for storage int64 or int32. Its dimension
is the target unit's per [LUNI.8.7.1]. A unit-typed slot access and a ::<unit>
cast therefore report the same pair: the storage's leaf kind, and the unit's
dimension. A quantity in an int64 dimension (data, a currency) is
an Int with a dimension, and arithmetic on it is Int arithmetic
([LEXP.7.3]). A value of the time dimension is a Duration ([LTIM.1.3.5]),
held in the same storage. The two facets are independent: the leaf kind drives the [LEXP.7.7]
bitwise / numeric-operand checks, the dimension drives the [LUNI.8.1]–[LUNI.8.4]
checks.
ratified — see also: LCST.4, LEXP.7.3, LEXP.7.7, LTIM.1.3.5, LUNI.4.1.1, LUNI.8.1, LUNI.8.4, LUNI.8.7.1
[LUNI.8.7.4] The dimension is the scale-free dimension. A value a
::<unit> cast gives is held in the base unit ([LUNI.8.5]). The facet the cast contributes to the [LUNI.8] checks is therefore the
unit's dimension (temperature, length, …), not its scale (celsius vs
kelvin). Same-dimension checks resolve at the base-unit level, so
r.a::celsius + r.b::kelvin is valid ([LUNI.8.1]) — both are temperature.
8.8 Forms over two values of one type [LUNI.8.8]#
The operands of the two-argument min and max ([LEXP.3.8.1]), of ??
([LNUL.5.3]) and of .. ([LINT.2.2]), the point and the interval of in
([LINT.3.1.3]), and two intervals that a relation or an equality compares
([LINT.3.2.2], [LINT.4.2], [LINT.5.4]) stand beside each other as the operands of
+ do. The compiler must refuse a bare number beside a dimensioned value
([LUNI.8.3]), a Duration included ([LTIM.1.3.5]), and two values of different
dimensions ([LUNI.8.2]), with DS_VALIDATE_DIM_MISMATCH.
Values of one dimension are valid, and the result has that dimension. An interval of them carries it, and a point or another interval is checked against it. An operand whose type the compiler cannot determine is not refused here ([LUNI.8.3]).
ratified — see also: LEXP.3.8.1, LINT.2.2, LINT.3.1.3, LINT.3.2.2, LINT.4.2, LINT.5.4, LNUL.5.3, LTIM.1.3.5, LUNI.8.2, LUNI.8.3
8.9 Builtins over a dimensioned value [LUNI.8.9]#
round, math.floor, math.ceil, math.trunc and math.sign ([LEXP.3.2]) over
a dimensioned value work in the value's own unit. The first four give a value of
that unit, holding the number rounded in it: round of a celsius value of 21.5
is 22 celsius. math.sign gives a bare Int.
A value's own unit is the unit its static type names: the declared unit of a slot
or a kwarg, a literal's unit, the target of a ::<unit> cast, a let annotation
([LUNI.8.6]), and, for an operation over values of one dimension, its left
operand's unit ([LUNI.8.1]). A value whose type names no unit, such as a
dimension-typed slot ([LUNI.7.1]), is in its dimension's base unit.
The compiler must refuse, with DS_VALIDATE_DIM_MISMATCH, a dimensioned
argument to any other builtin whose parameter [LEXP.17.2] types Int or Float.
A value of a unit scalar group ([LUNI.4.2]) and a Duration ([LTIM.1.3.5]) are
dimensioned for this clause. The author strips the unit first ([LUNI.8.7.2]), and
the builtin receives the base-unit number.
This refusal does not reach abs ([LEXP.3.2]), min and max ([LUNI.8.8]),
math.fma ([LEXP.3.2.2]), an angle argument where [LEXP.3.9.1] or
[LEXP.5.11.1] admits one, an operand whose type the compiler cannot determine, or
the body of a unit declaration or a unit formula ([LUNI.8.3]). math.pow is
[LUNI.8.4]'s. [RLOW.6.1.9] states how the five functions lower.
ratified — see also: LEXP.17.2, LEXP.3.2, LEXP.3.2.2, LEXP.3.9.1, LEXP.5.11.1, LTIM.1.3.5, LUNI.4.2, LUNI.7.1, LUNI.8.1, LUNI.8.3, LUNI.8.4, LUNI.8.6, LUNI.8.7.2, LUNI.8.8, RLOW.6.1.9
9. Series aggregation result types [LUNI.9]#
9.1 Unit-preserving aggregations [LUNI.9.1]#
Return the same unit as the series field. No annotation required.
min, max, mean, median, pXX, stdev, pstdev, sum, first, last
ratified — see also: LSER.16.4.1
9.2 Unit-changing aggregations — strip and assert [LUNI.9.2]#
integral, variance, pvariance and rate change dimension. Over a slot of
dimension $U$, integral is $U \cdot \mathrm{s}$ ([LSIG.1.5.1]), variance and
pvariance are $U^2$, and rate is $U / \mathrm{s}$ ([LSER.16.9]). The compiler
must reject a let whose value reads one of them over a slot that carries a
unit, a Duration slot included ([LTIM.1.3.5]), annotated or not, with
DS_VALIDATE_DIM_AGG_UNANNOTATED, unless the value strips the read. The strip,
integral(f)::Float or, for the nullable three, variance(f)::Float?
([LCST.4.3.1]), is a bare number in the slot's base unit: times
seconds for integral, squared for variance and pvariance, per second for
rate. The author may assert a unit on it with ::<unit> ([LUNI.8.5]), such as
degree_second, the base unit of a compound unit dimension the author declares.
The
diagnostic names the slot's unit and the aggregation, since the compound unit
itself has no name until the author declares one.
Only the let is gated. A read of these four in a where, an emit slot or an
interpolation needs no strip. Over a slot with no unit there is no dimension to
state, and the let needs none: the read carries no dimension.
onset_rate is never gated. It reads only a Bool
slot ([LSIG.1.4.3]), which carries no unit, so a let over it needs no
strip.
This is [LUNI.8.4]'s rule reached by a second route: each of the four multiplies or divides the slot's dimension, by time or by itself, and the result has no dimension DS can state.
The dimension is not the representation. [LSIG.1.1]'s Returns column gives
integral Float, and [LSER.17.2]'s gives the other three Float?; that is
their representation, and the dimension they carry is this clause's subject. A unit-typed value is an Int or a Float
carrying a compile-time dimension ([LNUL.4.9]), so the two statements describe
different axes of one value and neither constrains the other.
ratified — see also: LCST.4.3.1, LNUL.4.9, LSER.16.9, LSER.17.2, LSIG.1.1, LSIG.1.4.3, LSIG.1.5.1, LTIM.1.3.5, LUNI.8.4, LUNI.8.5
9.3 count and direction [LUNI.9.3]#
count always returns Int, and direction returns Int? ([LSER.17.2]).
Both are dimensionless over every slot. No annotation.
see also: LSER.17.2
10. The time dimension and duration literals [LUNI.10]#
10.2 The time dimension [LUNI.10.2]#
time is a unit dimension based on the nanosecond, with the standard
ladder of units (microsecond through day) declared as affine multiples of
it. It uses int64 nanosecond storage.
10.4 Language construct sites [LUNI.10.4]#
Every construct that takes a duration accepts a time_expr ([LGRA.2.8.1]) — a
schema's ttl, a rule's cooldown, and a pattern's within, among others.
see also: LGRA.2.8.1
11. String interpolation — unit extensions [LUNI.11]#
11.1 Display unit [LUNI.11.1]#
Interpolation always displays in the declared field unit, never the storage
base. A fahrenheit-typed field displays in fahrenheit. To display in a different
unit, convert explicitly with a let binding first.
[LUNI.11.1.1] The declared→base→declared display round-trip is not the
identity for non-trivial affine units. For a fahrenheit-typed field, the
storage path is value_F → kelvin = (value_F - 32) * 5/9 + 273.15 and the
display path is kelvin → value_F = (kelvin - 273.15) * 9/5 + 32. Each leg
emits IEEE 754 RNE rounding (per [§2.7]) on a non-exact rational ratio
(5/9, 9/5), so the displayed value can differ from the source by up to a
few ULP. Authors who require bit-identical display of a literal as-entered
should bind it via let and interpolate the let-binding, not round-trip
through a unit-typed slot. The same caveat applies to every tier-1 affine
unit whose factor is not a power of two (celsius, fahrenheit, rankine,
degree, minute, hour, psi, the unit fx_pair rate path, ...).
11.2 Format types [LUNI.11.2]#
One of the interpolation format types ([LGRA.2.9.6.1]) exists for unit-typed values, and [LGRA.2.9.6.10] states how it renders.
u— the unit's label alone ("celsius"). A value with its label is written as two sites,{x} {x:u}. On a number with no unit,uis refused withDS_VALIDATE_INTERP_UNIT_NON_UNIT.
The complex type's i and j ([LUNI.14.8]) are deferred with it, and v1
refuses them ([LUNI.14.9]).
ratified — see also: LGRA.2.9.6.1, LGRA.2.9.6.10, LUNI.14.8, LUNI.14.9
11.3 Default behaviour [LUNI.11.3]#
Field type |
No format spec |
|
|
|---|---|---|---|
|
bare number |
bare number |
refused ([LUNI.11.2]) |
unit-typed |
bare number |
bare number |
the label alone |
see also: LUNI.11.2
11.4 Label [LUNI.11.4]#
The label used is the unit declaration's label string if declared, else the
unit symbol.
[LUNI.11.4.1] Label strings are display-plane only. On builds with no
interpolation surface — e.g. nofpu embedded targets where the
runtime omits the format-string lowering to save flash / RAM, or any
target with display_strip opt-in — the lowering pass drops every
declared label string from the emitted DSC; bare unit symbols still
serve as the fallback at interpolation sites when they re-enter. The
strip is a pure tail elision and does not change any
arithmetic or conversion factor.
No build in this edition lacks the interpolation surface, so every build keeps
its labels ([LUNI.11.4]). The strip pairs with the fixed-point storage backing
[LUNI.17.3] proposes for the nofpu targets.
Deferred: not binding in this edition.
12. Adapter interop [LUNI.12]#
12.1 Float stays Float [LUNI.12.1]#
Adapters that declare state: Float produce Float. Rules consuming that field
work with plain Float. No automatic unit semantics.
12.2 Unit-typed adapter fields [LUNI.12.2]#
Adapters that want unit semantics declare unit types directly, using a unit symbol as a schema field's type exactly as an author schema would.
The adapter contract now includes unit information. Mismatched units between adapter output and rule schema are a compile error.
12.3 Assertion at the boundary [LUNI.12.3]#
When consuming a Float from a legacy adapter and needing unit semantics, authors
use the :: assertion cast explicitly ([LUNI.8.5]).
This is the author's explicit responsibility. No compiler verification of the physical correctness of the assertion.
see also: LUNI.8.5
13. Currency [LUNI.13]#
Currency is the one unit family where conversion factors are runtime, not
compile-time. Exchange rates change continuously, come from an integrator-
provided rate source (LUNI.13.8), and must never be inlined into the .dsc. This section pins how currencies are
declared, stored, converted, and rounded.
Deferred: not binding in this edition.
see also: LUNI.13.8
[LUNI.13.11] Currency is not part of this edition. This section and
unit fx_pair ([LUNI.4.6]) are deferred: no conforming compiler or runtime is
obliged to implement them. The compiler must refuse every construct that
reaches them, with DS_VALIDATE_FINANCE_DEFERRED, at the construct:
an import of
units.currency([LUNI.16.5]);a
unit fx_pairdeclaration;a
.to_currency(...)call;a
.round(...)or.round_to(...)method call ([LUNI.13.5]).
The function round(x) ([LEXP.3.2]) is not a currency construct and is
unaffected. The section's own diagnostic codes stay allocated.
ratified — see also: LEXP.3.2, LUNI.13.5, LUNI.16.5, LUNI.4.6
13.1 Overview [LUNI.13.1]#
Each currency is its own
unit dimension(currency_usd,currency_eur,currency_jpy, …) withstorage int64and base = the ISO 4217 minor unit (cent / pence / yen / fils / …). The standard library ([LUNI.16.5]units.currency) declares the canonical ISO 4217 set.Cross-currency conversion is declared via [LUNI.4.6]
unit fx_pair, backed at runtime byFxRatefacts ([LUNI.13.3]).Every operation that lands a non-exact intermediate (
Float × currency,currency / Float, FX conversion) into currency storage requires an explicit.round("<mode>")call ([LUNI.13.5]). The<mode>argument is a required string literal — there is no default. This is the load-bearing rule.
13.2 Per-currency dimensions and storage [LUNI.13.2]#
Each currency is a separate unit dimension. The base unit is the ISO 4217
minor unit; storage is always int64. Minor-unit storage gives exact
integer representation for every routine balance.
Family |
Base unit |
dp |
Notes |
|---|---|---|---|
USD / EUR / GBP / CAD / AUD / CHF / etc. |
cent / pence / rappen / … |
2 |
Bulk of ISO 4217 |
JPY / HUF / KRW / IDR / etc. |
yen / forint / won / rupiah |
0 |
No minor unit in ISO 4217 |
KWD / JOD / BHD / LYD / etc. |
fils / qirsh / … |
3 |
Gulf dinars |
Sub-currency precision (pip, equity 4dp) |
|
4–8 |
Each precision is its own dimension |
Sub-minor precision is a separate unit dimension per currency — currency_usd_4dp
(pip-precision USD) is distinct from currency_usd. Conversion within a single
currency (USD_dollar ↔ USD_cent ↔ USD_pip) is exact tier-1 affine
(unit <sym>: ... = <power_of_10>). Cross-currency conversion always goes
through unit fx_pair.
Per-currency dimensions are never interchangeable for arithmetic — currency_usd + currency_eur is a compile error ([LUNI.8.2] cross-dimension). To add them, the
author explicitly converts one side via unit fx_pair and .round("<mode>").
see also: LUNI.8.2
13.3 FxRate schema [LUNI.13.3]#
The integration contract is a published schema, not a service call.
Integrators emit FxRate facts; DS rules and unit fx_pair declarations
consume them like any other fact. The standard library's is
units.currency.FxRate by its own name ([LIMP.13.1]), which is the name an
integrator asserts it by. FxRate is ttl-scoped at 1_h, with
slots:
Slot |
Type |
Meaning |
|---|---|---|
|
String |
ISO 4217 code, e.g. |
|
String |
ISO 4217 code, e.g. |
|
Int |
numerator |
|
Int |
denominator — rate = |
|
Int |
decimal places the rate source reported (display / audit) |
|
Time |
rate observation time |
see also: LIMP.13.1
[LUNI.13.3.1] rate_num / rate_den carry the exact rate. The integrator
converts whatever the rate source reports (such as a decimal string like
"0.9215") into the equivalent integer fraction ((num=9215, den=10000, rate_dp=4)) once on ingestion. No Float parse appears in the rate
application path.
[LUNI.13.3.2] scope ttl 1_h is the default freshness; integrators may pin
tighter or looser TTL via a different schema name with the same shape (the
via <Schema> clause names which schema to consult).
[LUNI.13.3.3] A unit fx_pair whose selector finds no matching live fact
converts at 1:1 — see [LUNI.4.6.1], which owns the rule and carries the
reasoning. This clause states no behaviour of its own, deliberately: a
restatement is a second copy to find and change when the rule moves, and one
of them not being found is the failure mode.
see also: LUNI.4.6.1
13.4 Conversion via unit fx_pair [LUNI.13.4]#
See [LUNI.4.6] for the declaration form. Conversions
are explicit at call sites — <amount>.to_currency(<fx_pair>) — and produce a
fractional-currency intermediate in the target dimension that is not
assignable to a currency slot without explicit rounding ([LUNI.13.5]).
The target dimension comes from the pair's to side, never from the method
name. There is one conversion method, not one per currency: the pair already
states both ends, and a second spelling of the target would be a fact stated
twice with nothing checking the two agree.
The reverse direction is a separately-declared unit fx_pair. The compiler
does not auto-derive the inverse — different rate sources may report different
bid / ask rates, and a naive reciprocation introduces a 1-ULP drift.
13.5 Explicit rounding [LUNI.13.5]#
<amount>.round("<mode>") rounds a currency-typed value to its storage's
minor-unit precision and yields the same dimension at exact int64.
<amount>.round_to(<unit>, "<mode>") rounds to a coarser unit in the same
dimension (e.g. .round_to(USD_dollar, "half_up") from currency_usd).
The mode is a string literal (not a bare identifier or keyword), so no mode
name is a reserved word. String args are unambiguous in
the parser, validate at compile time, and follow the established pattern
of decimal libraries in Python / Java / JS.
[LUNI.13.5.1] No default mode. The <mode> argument is required;
there is no nullary .round() form. Compile error:
DS_VALIDATE_CURRENCY_ROUND_NO_MODE.
[LUNI.13.5.2] No implicit rounding. Any expression producing a
fractional-currency intermediate (Float × currency, currency / Float, FX
conversion) must be wrapped in an explicit .round("<mode>") before
assignment to a currency slot, comparison against a currency slot, or use as an
emit-action argument typed as currency. Compile error:
DS_VALIDATE_CURRENCY_IMPLICIT_ROUND.
is / is not ([LNUL.4.9]) is not a fourth position.
The three positions above share a property the tag test does not: each consumes the value — stores it, compares its magnitude, or ships it — so a rounding the author did not write would change what is stored, matched or sent. A tag test consumes only the discriminant, and reads it before any value conversion ([LNUL.4.9]), so there is no implicit rounding for it to be implicit about.
An unrounded fractional-currency intermediate is a Ratio, and a Ratio
answers false to all six tag names ([LNUL.4.9]). That is the true answer
about the value in hand, not a silently wrong one: the author who asks whether
an unrounded intermediate is an Int is told that it is not. Refusing the
spelling would make is the one operator forbidden to observe a
representation the language admits.
see also: LNUL.4.9
[LUNI.13.5.3] currency.round() is the method form, distinct from the
generic round(x) builtin function ([LEXP.3.2]) which uses the
IEEE 754 roundTiesToEven default. The method .round(...) on any
receiver is treated as the currency form and gated; the function
round(x) is the Float-default form and ungated. The parser
discriminates by MethodCall vs FunctionCall AST shape (different rule).
see also: LEXP.3.2
13.6 Round modes [LUNI.13.6]#
The six canonical mode string values:
Mode |
Behavior |
Typical use |
|---|---|---|
|
Round half to nearest even ("banker's") |
ISO 80000-1; high-volume accounting (no bias) |
|
Round half away from zero |
EU VAT line items; consumer display |
|
Round half toward zero |
Some IRR / loss-attribution paths |
|
Always toward +∞ |
Conservative billing |
|
Always toward −∞ |
Bank interest accrual (don't over-credit) |
|
Toward zero |
Audit / forensic — discard fractional |
Any other string value at the mode position: DS_VALIDATE_CURRENCY_UNKNOWN_ROUND_MODE.
Non-string expression at the mode position (variable reference, computed
value, etc.): DS_VALIDATE_CURRENCY_ROUND_ARG_NOT_STRING. The mode must
be a string literal so the validator can check it at compile time;
runtime-computed mode strings are not admitted (a runtime-typo'd mode is
a footgun the type system can prevent).
13.7 Cross-currency comparison [LUNI.13.7]#
Comparing two currency values of different dimensions is a compile error
([LUNI.8.2] cross-dimension). To compare, the author converts one side
explicitly with a rate AND a round mode, via .to_currency(<pair>) then
.round(<mode>), before the comparison operator.
The compiler does NOT auto-insert the conversion-and-round chain for comparisons. The truth value depends on a runtime fact (the FX rate); making that dependency invisible at the call site would be a footgun.
see also: LUNI.8.2
13.8 Sourcing FX rates [LUNI.13.8]#
An integrator supplies the rate source —
Bloomberg, Reuters, an exchange feed, internal sourcing — and the contract
is fixed: emit FxRate facts with the slots in [LUNI.13.3].
see also: LUNI.13.3
[LUNI.13.10] The exact-money path refuses rather than wraps, and this is
the one arithmetic surface where it does. An operation on a currency-typed
value whose exact result has no Int64 representation — a product, a rounding
at the boundary, or an FX conversion — must not produce a wrapped value. It
raises NOT_REPRESENTABLE ([LERR.1.4.9]).
This is a deliberate exception to [LEXP.7.13.1], which makes two's-complement
wraparound the defined behaviour of Int arithmetic and declines to guard it.
That rule is right for ordinary integers and wrong here, and the difference is
the one [LERR.1.4.9] already draws: wrapping is admissible when the wrapped
value still means something an author can reason about. INT64_MAX + 1 is an
algebra, closed and predictable. A monetary amount that wraps bears no relation
to the amount it came from, so there is nothing left to reason about — it is the
same loss of meaning that puts a failed conversion in NOT_REPRESENTABLE
rather than in the wrapping rule.
see also: LERR.1.4.9, LEXP.7.13.1
14. Complex type [LUNI.14]#
COMPLEX_LIT is not a token of this edition's lexer. Storing a complex value
needs a new slot type, which is a format change ([STYL.2.8.7]).
Deferred: not binding in this edition.
14.1 Overview [LUNI.14.1]#
complex is a runtime type representing a complex number as two float64 values
(real and imaginary components). It is a full runtime type: schema fields may be
complex-typed, facts store complex values, rules pattern-match on them.
14.2 Proto representation [LUNI.14.2]#
message ComplexDouble {
double real = 1;
double imag = 2;
}
No display flag in the wire format. Display convention is a context property, not a value property — it belongs to the module or interpolation site, not the stored value (see §14.8).
14.3 Literals [LUNI.14.3]#
COMPLEX_LIT (see §3.4). i and j suffixes produce identical values.
Both suffix forms remain valid syntax; which to write is a style choice. i and
j are also available as built-in constants equal to Complex(0, 1).
Polar form uses exp(), extended to accept a complex argument.
exp(i * theta) where theta is an angle scalar (dimensionless, stored in
radians) returns dimensionless complex. Euler's formula applies naturally:
complex * scalar → complex per §8.3, no special exp carve-out needed.
14.4 Schema field type [LUNI.14.4]#
complex <unit> — two-token field type. complex keyword followed by an optional
unit symbol; omitting the unit leaves both components plain Float64. Both real
and imaginary components carry the declared unit. Values are
stored in base units of the declared dimension, same as scalar unit fields.
14.5 Built-in operations [LUNI.14.5]#
real(z) and imag(z) return the real/imaginary component in z's unit;
abs(z) returns the magnitude in z's unit, implemented as
distance.hypotenuse(real(z), imag(z)); arg(z) returns the phase angle as radian,
atan2(imag(z), real(z)); conjugate(z) returns complex <unit> (a - bi); exp(z) returns complex, extended to accept a complex argument.
Determinism class per [LDET.3.3a]:
Op |
Class |
Notes |
|---|---|---|
|
EXACT |
field access / sign flip — basic ops |
|
EXACT |
basic IEEE 754, correctly-rounded |
|
EXACT |
computed as |
|
EXACT |
one correctly-rounded |
|
EXACT |
Euler's formula, decomposed as below |
exp(z) is this composition, and no other. For $z = a + bi$, with
$\circ(\cdot)$ the correctly-rounded result of one operation:
$$\operatorname{Re} \exp(z) = \circ\big(\circ(e^{a}) \times \circ(\cos b)\big), \qquad \operatorname{Im} \exp(z) = \circ\big(\circ(e^{a}) \times \circ(\sin b)\big)$$
$e^{a}$ is evaluated once and used in both products. The result is not the
correctly-rounded complex exponential, and it is identical on every conforming
engine because every step is fixed ([LDET.3.4.4]). At the special values each
step follows [LEXP.3.9.3] and [LDET.3.6.2], so exp(inf + 0i) has an imaginary
part of inf × 0, which is NaN.
checks: k — see also: LDET.3.3a, LEXP.5.5, LEXP.3.9.2, LDET.3.4.4, LEXP.3.9.3, LDET.3.6.2
14.6 Type checking rules [LUNI.14.6]#
Valid. complex <unit> supports + / - with another complex <unit> of the same unit (preserves the unit), + / - with a bare
<unit> value (a real-component shift), and * with a bare Float
(scalar scaling, preserves the unit). abs() returns the scalar
magnitude in <unit>; arg() returns radian; conjugate() returns
complex <unit>.
Refused ([LUNI.8.4]): complex <unit> * complex <unit> and
complex <unit> / complex <unit> are compile errors.
No ordering on complex — compile error. <, >, <=, >= are
rejected; authors compare abs(), real(), or imag() instead. ==
and != are valid (component-wise equality).
see also: LUNI.8.4
14.7 Series aggregations [LUNI.14.7]#
Direct aggregation of complex-typed series fields is a compile error. Authors
extract a scalar component first, via a derived series over one of the
extraction functions, then aggregate that.
Derived series grammar#
series_decl ::= 'series' NAME '=' extract_fn '(' NAME ')' ('sliding' time_expr)?
extract_fn ::= 'abs' | 'arg' | 'real' | 'imag'
The outer NAME is the new series name. The inner NAME must be a field in the
same schema. sliding is optional; if omitted the series uses the schema-level
default window.
Result types:
abs(f)→ base unit off's dimension (e.g.ohmforcomplex ohm)arg(f)→radian(angle scalar, dimensionless)real(f)→ base unit off's dimensionimag(f)→ base unit off's dimension
conjugate is excluded — it returns complex, not a scalar. Arbitrary
expressions are not allowed in derived series declarations; complex transformations
belong in rules.
Untyped complex fields#
complex without a unit annotation is valid in schemas (useful for FFT output,
raw signal buffers, etc.). Extraction function return types for untyped vs typed:
Function |
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
arg() always returns radian — phase angle is always angular regardless of the
unit (or absence of unit) of the complex value.
14.8 Display and interpolation [LUNI.14.8]#
Display convention (i vs j) is a context property, not stored in the value.
The convention is i, and it is set per interpolation site or not at all.
A site that wants j says so at the site.
Per-interpolation override#
i and j join the format types ([LGRA.2.9.6.1]) when the type is built:
i— force imaginary unit display asiat this sitej— force imaginary unit display asjat this site
Negative imaginary displays as subtraction: "3.0 - 2.0i ohm" not
"3.0 + -2.0i ohm".
see also: LGRA.2.9.6.1
[LUNI.14.9] Not in v1. The complex type is deferred: the clauses of this
section state it as it will be when it is built, and none of them binds v1. The
compiler must refuse each of its surface forms with
DS_VALIDATE_COMPLEX_NOT_IN_V1, naming the form:
a slot whose type is written
complex, with or without a unit ([LUNI.14.4]), where no declared type has that name;a numeric literal with a bare
iorjsuffix ([LLEX.12.7]);iorjas an interpolation format type ([LUNI.14.8]).
i and j stay withheld from unit suffixes ([LUNI.3.1.5]), so the literal
form remains free for the type when it is built.
ratified — see also: LLEX.12.7, LUNI.14.4, LUNI.14.8, LUNI.3.1.5
15. Unit name resolution [LUNI.15]#
[LUNI.15.1] A unit symbol resolves by one lookup. The lexer produces a
UNIT_SUFFIX token opaquely, and the compiler must look its full symbol, or an
alias of it, up in the file's unit scope: units.core ([LUNI.4.1.2]), the units
the file imports, and the units it declares. A symbol found nowhere is a compile
error (DS_VALIDATE_UNKNOWN_UNIT). A symbol bound twice is refused ([LIMP.5.1.5]), so the order of the
imports never decides what a literal means. 5_MHz resolves because units.si declares MHz as
an alias of megahertz, and 5_molar because units.chemistry declares
molar. A unit no imported module declares is the author's to declare.
see also: LIMP.5.1.5, LUNI.4.1.2
[LUNI.15.2] The standard library's unit modules. An author imports the modules a program needs.
Module |
Contents |
|---|---|
|
SI base + prefixed forms + derived |
|
litre, tonne, bar, eV, etc. |
|
US: inch, foot, mile, lb, psi, liquid and dry measure… |
|
UK: stone, long ton, UK gallon… |
|
grain, oz, lb, short/long ton |
|
troy oz, troy lb, pennyweight |
|
gauss, maxwell (CGS EM); SI EM units in |
|
molar, pH, ppm, ppb… |
|
dB family, dBm↔watt, MIDI↔Hz, sone, phon |
|
nautical mile, knot, fathom |
|
week, fortnight, year variants |
|
torque, rpm, viscosity, CGS legacy |
|
ly, pc, jansky, solar mass (IAU 2015) |
|
data, data_rate, baud, energy_per_bit… |
16. Standard library module catalogue [LUNI.16]#
16.1 Design principles [LUNI.16.1]#
No unit is declared in more than one module with a different conversion factor. Same quantity appearing in multiple modules (e.g.
grainin bothunits.avoirdupoisandunits.troy) resolves to the same numeric value. A program still imports it from one of them: importing it from both is refused ([LIMP.5.1.5]).units.imperialmeans UK imperial.units.customarymeans US customary. These are distinct modules because many unit names (gallon, pint, fl oz, hundredweight, ton) differ in value between the two systems.Import order never chooses between two units ([LIMP.5.1.5]). A program that needs a name two modules declare reaches each by qualified access (
avoirdupois.grain,troy.grain).No module re-exports another's declarations. Authors import what they need.
see also: LIMP.5.1.5
16.2 Module catalogue [LUNI.16.2]#
units.si#
SI base units, all explicitly-prefixed derived names, and SI derived units.
Follows the SI 9th edition (2019) exactly. No algorithmic prefix expansion —
all prefixed forms (kilogram, milliampere, megohm, MHz, etc.) are
declared explicitly.
Dimensions covered: length, mass, time, temperature, current,
luminous_intensity, amount, frequency, radioactivity,
force, energy, power, pressure, voltage, resistance,
conductance, capacitance, inductance, charge, magnetic_flux,
magnetic_flux_density, absorbed_dose, equivalent_dose, illuminance,
luminous_flux, luminance, catalytic_activity, area, volume,
velocity, acceleration, solid_angle.
Scalars covered: angle, proportion.
units.metric#
Non-SI units officially accepted for use with the SI (BIPM 9th ed, Table 8), plus universally-used metric-adjacent units.
Unit |
Value |
Alias |
|---|---|---|
|
0.001 m³ |
|
|
0.000001 m³ |
|
|
1000 kg |
|
|
10,000 m² |
|
|
100,000 Pa |
— |
|
100 Pa |
|
|
1×10⁻¹⁰ m |
|
|
149,597,870,700 m (exact) |
|
|
1.602176634×10⁻¹⁹ J (exact) |
|
|
1.66053906660×10⁻²⁷ kg |
|
|
4186.8 J (IT) |
|
|
735.49875 W (exact) |
|
units.customary#
US customary units. Length units here are shared with UK (inch, foot, yard, mile are identical in both systems since the International Yard and Pound Agreement, 1959).
Length: inch (25.4 mm), foot (304.8 mm), yard (0.9144 m),
mile (1609.344 m), mil (25.4 µm), thou = mil.
Mass (avoirdupois — declared here, at units.avoirdupois's values):
grain, dram, ounce, pound, short_hundredweight (100 lb),
short_ton (2000 lb).
Volume (liquid): fluid_ounce (29.5735295625 mL), cup (236.5882365 mL),
pint (473.176473 mL), quart (946.352946 mL), gallon (3.785411784 L).
Volume (dry): dry_pint (550.6104713575 mL), dry_quart
(1101.220942715 mL), peck (8810.56754172 mL), bushel (35242.2701669 mL),
alias bu. Dry and liquid measure share the volume dimension and have
distinct unit names.
Temperature: fahrenheit, rankine.
Pressure: psi (6894.757293168 Pa — absolute only; see §7 note on gauge).
Power: mechanical_horsepower (745.69987158227022 W), alias hp.
Speed: miles_per_hour, alias mph.
units.imperial#
UK imperial units. Length is not duplicated here — import units.customary
for inch/foot/yard/mile (identical values).
Mass: stone (6.35029318 kg), long_hundredweight (50.80234544 kg,
112 lb), long_ton (1016.0469088 kg, 2240 lb).
Volume: imperial_fluid_ounce (28.4130625 mL), imperial_pint
(568.26125 mL), imperial_quart (1136.5225 mL), imperial_gallon
(4546.09 mL).
units.avoirdupois#
The avoirdupois mass system used across US and UK for general commerce.
Unit |
Value |
Notes |
|---|---|---|
|
64.79891 mg (exact) |
shared with |
|
1.7718451953125 g |
27+11/32 grains |
|
28.349523125 g (exact) |
avoirdupois ounce |
|
453.59237 g (exact) |
|
|
45.359237 kg |
100 lb, US |
|
50.80234544 kg |
112 lb, UK |
|
907.18474 kg |
2000 lb, US |
|
1016.0469088 kg |
2240 lb, UK |
units.troy#
Troy mass system used for precious metals and gemstones.
Unit |
Value |
Notes |
|---|---|---|
|
64.79891 mg (exact) |
shared with |
|
1.55517384 g |
24 grains |
|
31.1034768 g (exact) |
|
|
373.2417216 g |
12 troy ounces |
units.nautical#
International nautical units. All defined in exact SI.
Unit |
Value |
Alias |
|---|---|---|
|
1852 m (exact) |
|
|
1852/3600 m/s (exact) |
|
|
1.8288 m (exact) |
— |
|
185.2 m (exact) |
— |
|
5556 m (exact) |
— |
units.time#
Extension of the time dimension beyond the units [LUNI.10.2] declares.
Unit |
Value |
Notes |
|---|---|---|
|
604,800,000,000,000 ns |
7 days (exact) |
|
1,209,600,000,000,000 ns |
14 days (exact) |
|
31,557,600,000,000,000 ns |
365.25 days (exact) |
|
31,556,952,000,000,000 ns |
365.2425 days (exact) |
|
31,556,925,974,880,000 ns |
365.24219878… days (float64, not exact Rational) |
year_tropical is irrational with respect to SI base units, so its conversion
factor cannot be expressed as an exact Rational (§2); the float64-derived value
is rounded at compile time to the pinned int64 nanosecond constant shown
above, which is then the exact stored representation at runtime — no
runtime float is involved. The "float64" note refers to factor derivation,
not the stored value.
units.electrical#
Non-SI electromagnetic units. All SI-named electrical units (ohm, farad,
henry, siemens, coulomb, weber, tesla with all prefixes) are declared in
units.si — import that first. units.electrical adds CGS survivors and
the electrical horsepower definition.
Notable units: gauss (10⁻⁴ T), maxwell (10⁻⁸ Wb),
electrical_horsepower (746 W exactly, IEEE Std 100).
units.audio#
Units for audio and psychoacoustics.
Power-referenced dB (interconvertible scalar group power_db):
dBm, dBW, dBf, dBk.
Voltage-referenced dB (interconvertible scalar group voltage_db):
dBu, dBV.
Standalone scalars ([LUNI.6.2]), each unit the single member of its own
group: dB (generic_db), dBFS (full_scale_db), dBc (carrier_db),
dBSPL (spl_db), dBi (antenna_gain_db).
Power: the implicit formula pair dBm_watt ([LUNI.4.5]):
dBm_to_watt is $10^{x/10} / 1000$ and watt_to_dBm is
$10 \log_{10}(1000,x)$, between dBm and units.si's watt.
Loudness (dimension loudness): sone, the base; phon, tier-2
non-affine ([LUNI.4.3]), with to_base $2^{(x - 40)/10}$ and from_base
$10 \log_2 x + 40$. The conversion is defined at every value; the
psychoacoustic relation it encodes holds at 40 phon and above.
Musical pitch: midi_note, a Float note number (fractional values
represent tunings between semitones); the formula pair midi_hz
([LUNI.4.5]): midi_to_hz is $440 \cdot 2^{(x - 69)/12}$ and hz_to_midi is
$69 + 12 \log_2(x / 440)$, between midi_note and units.si's Hz.
units.chemistry#
Units for chemical and laboratory contexts.
Unit |
Dimension |
Notes |
|---|---|---|
|
|
mol/L |
|
|
0.001 mol/L |
|
|
1×10⁻⁶ mol/L |
|
|
1×10⁻⁹ mol/L |
|
|
base: hydrogen-ion concentration, mol/L |
|
|
tier-2 non-affine ([LUNI.4.3]): |
|
|
1×10⁻⁶ (dimensionless scalar) |
|
|
1×10⁻⁹ |
|
|
1×10⁻¹² (IUPAC; see note in file on oceanographic usage) |
units.physics#
Compound physical dimensions requiring explicit naming in DS's no-unit-algebra system, and CGS legacy units common in datasheets.
New dimensions: torque (≠ energy, both N·m), angular_velocity (≠
frequency, both 1/s), dynamic_viscosity, kinematic_viscosity,
heat_capacity, specific_heat, thermal_conductivity, electric_field,
surface_charge.
Notable units: rpm, centipoise (cP), centistokes (cSt), curie
(3.7×10¹⁰ Bq), erg (10⁻⁷ J), dyne (10⁻⁵ N), rad_dose (0.01 Gy —
named rad_dose to avoid collision with the rad alias for radian).
units.astro#
Astronomical units for embedded systems interacting with instruments: telescope mount controllers, satellite ground stations, radio telescope pipelines, spacecraft telemetry. Cosmological-scale quantities explicitly out of scope. Conforms to IAU 2015 Resolution B3 nominal mass constants.
Notable units: light_year, parsec, kiloparsec, milliarcsecond (mas),
microarcsecond (µas), solar_mass, earth_mass, jupiter_mass,
lunar_mass, jansky (Jy), millijansky, microjansky.
units.computer#
Computer engineering units for embedded firmware and real-time rules.
Follows IEC 80000-13 binary/decimal prefix split; no KB alias (ambiguous).
Dimensions: data (int64/bit base), data_rate, symbol_rate (baud ≠ bps),
energy_per_bit, energy_per_flop, energy_per_mac, energy_per_instruction,
compute_efficiency, request_rate (RPS), transaction_rate (TPS) and
query_rate (QPS), each ≠ the others, ≠ Hz, ≠ Bq.
Notable units: IEC KiB–PiB, SI kB–PB, baud/kBd/MBd,
light_nanosecond (≈ 29.98 cm), light_picosecond, nJ_per_bit,
pJ_per_flop, pJ_per_mac, TOPS_per_watt. Inverting formula pair:
energy_per_flop ↔ compute_efficiency.
ratified — see also: LUNI.10.2, LUNI.4.3, LUNI.4.5, LUNI.6.2
16.5 units.currency [LUNI.16.5]#
This module is deferred with currency ([LUNI.13.11]). It will declare three
anchor currencies — USD, EUR, CNY (the People's Republic Yuan Renminbi, ISO
4217 code CNY, colloquially "RMB") — with the full directed conversion
graph between them (six unit fx_pair declarations). All three sit in ISO
4217's 2-dp tier; storage is int64 cents / fen.
The companion FxRate schema ([LUNI.13.3]) will be declared here so an
integrator can publish rate facts without re-declaring the contract. Detailed
semantics — rounding rules, conversion via unit fx_pair, where rates come from
— are [LUNI.13]'s.
The wider ISO 4217 set (0-dp currencies like JPY / KRW / ISK / CLP, 3-dp Gulf
dinars KWD / BHD / JOD / OMR, and the rest of the ~178 codes), the sub-minor
precision tiers (currency_<ccy>_4dp for FX pip precision, currency_<ccy>_8dp
for sub-pip), and crypto dimensions are outside the module. Explicit rounding
([LUNI.13.5]) and cross-currency comparison ([LUNI.13.7]) apply to any declared
currency dimension. Crypto currencies need precision beyond int64.
Deferred: not binding in this edition.
see also: LUNI.13, LUNI.13.11, LUNI.13.3, LUNI.13.5, LUNI.13.7
16.3 Expected import patterns [LUNI.16.3]#
Each library takes its own import statement. A file combining the SI base with one domain library reads:
Context |
Libraries |
|---|---|
scientific / embedded — most files |
|
European engineering |
|
US engineering |
|
adds CGS EM units (gauss, maxwell) |
|
motor / thermal / fluid / radiation work |
|
US mass-heavy context |
|
cross-region product |
|
lab / sensor chemistry |
|
DSP / audio processing |
|
marine / aviation |
|
telescope / spacecraft telemetry |
|
firmware / embedded comms budget |
|
The commas above separate library names in prose, not source. units.imperial
has no length dimension — units.customary provides inch/foot/yard/mile for
both regions.
16.4 What the standard library does not carry [LUNI.16.4]#
No units.archaic module. Units from defunct or field-specific historical
systems (apothecary, surveying chains, cubit, etc.) are not in the standard
library. Authors who need them declare them locally using the same
unit <name>: <dimension> = <expr> syntax.
17. Real-time / embedded / determinism [LUNI.17]#
The compile-time core is sound. The one open exposure is float64-only
storage on no-FPU targets ([LUNI.17.3]). A tier-2 conversion or a
unit formula that uses a transcendental function is bit-identical on every
engine, because each function is correctly rounded and the expression is
evaluated as written ([LDET.3.4.4]).
see also: LDET.3.4.4, LUNI.17.3
17.3 float64-only storage is nofpu-hostile. BLOCKER. [LUNI.17.3]#
Every dimension but time, data and the currencies is storage float64 (§4.1). No-FPU targets
(Cortex-M0+, low-end RISC-V) have no hardware float64 → softfloat for every
celsius/meter/watt field, and the storage clause offers no fixed-point /
scaled-integer option. Recommend: admit a fixed-point storage backing
(e.g. storage int32 scale <rational> / Q-format) selectable under nofpu,
with conversion factors baked to that representation. Pairs with
realtime/linear_scan: false.
17.5 int64-time ↔ float64-frequency formulas: pin the float→int rounding [LUNI.17.5]#
Pinned in [§7.2]: a float64 value cast into an
int64-typed storage field uses IEEE 754 roundTiesToEven. The
hz_to_period(x) = 1e9 / x formula and any other float64-producing
conversion that lands in the time dimension applies the same rule at the
final cast, so platforms do not diverge by ±1 ns.
17.6 Slot tolerance is a physical deadband [LUNI.17.6]#
The tolerance keyword on a schema slot declares a physical deadband Δ in the
slot's dimension ([LUNI.7.4]). It has no other meaning: a series observation
line takes no accuracy phrase ([LSER.15.1]).
17.7 Compiler constant-baking must be cross-host deterministic [LUNI.17.7]#
Pinned normatively in [§2.7]: Rational→float64 baking
and the tier-2 build-time round-trip test use IEEE 754 roundTiesToEven plus a
fixed left-to-right evaluation order, so the same .ds yields byte-identical
baked factors on any IEEE-754-compliant build host (DSC reproducibility).
Cross-host conformance vector: the current-state proxy
is LUNI.2.7_float_repr_roundtrip, which pins the FloatLit source-text →
Python float() → repr() → lowered-form round-trip for a representative
literal set (a non-binary-representable decimal 0.1, a small-exponent form
1e-6, a full-precision irrational 3.141592653589793). The chain inherits
IEEE 754 roundTiesToEven at parse and produces the shortest round-trippable
decimal at emit, so any IEEE-754-compliant host produces byte-identical
lowered output. The runtime serializes a Float value to JSON in this
same shortest-round-trip form ([LDET.3.2.7]), so a value serialized at runtime
(a cache value, a call body) is byte-identical to the same value written as a
source literal here, and round-trips. The full unit-factor-table cross-host vector — bit-comparing
the emitted .dsc factor table across architectures — lands with the unit
factor emission slice; a .dsc factor table does not exist in the current
emission set.
see also: LDET.3.2.7, LUNI.2.7
18. Promotion to v1 — gate [LUNI.18]#
The bar for calling this design v1-normative.
18.1 What is outstanding [LUNI.18.1]#
The cross-platform bit-exact golden vectors for tier-1 affine conversion
are not landed. LUNI.2.7_float_repr_roundtrip pins the current-state
float representation; the full .dsc factor-table vector lands with unit
factor emission.
see also: LUNI.2.7
18.3 Net [LUNI.18.3]#
What is left is [LUNI.18.1]. A unit
conversion or unit formula needing a transcendental computes it correctly
rounded, on every target and in every dialect ([LDET.3.4.4]) — so unit
semantics are cross-platform bit-identical everywhere.
see also: LDET.3.4.4, LUNI.18.1