Source/Packages

Std.Natural

packages/foundation/standard/src/Std/Natural.alpha

376 lines51 declarations16.0 KiBSHA-256 7e7128c5e781

Complete file · line 317

Natural.alpha

Definition view
1module Std.Natural
2
3family NaturalArithmeticErrorCode : Type 0
4constructor NaturalArithmeticModuloByZero
5constructor NaturalArithmeticDivideByZero
6
7end-family
8
9family NaturalModuloResult : Type 0
10constructor NaturalModuloSucceeded
11field unrestricted naturalModuloValue : Nat
12constructor NaturalModuloFailed
13field unrestricted naturalModuloError : (family NaturalArithmeticErrorCode)
14
15end-family
16
17family NaturalDivisionState : Type 0
18constructor NaturalDivisionStateValue
19field unrestricted naturalDivisionRemainder : Nat
20field unrestricted naturalDivisionQuotient : Nat
21
22end-family
23
24family NaturalDivideResult : Type 0
25constructor NaturalDivideSucceeded
26field unrestricted naturalDivideValue : Nat
27constructor NaturalDivideFailed
28field unrestricted naturalDivideError : (family NaturalArithmeticErrorCode)
29
30end-family
31
32def naturalArithmeticErrorCodeBytes =
33  (lambda unrestricted code : (family NaturalArithmeticErrorCode) .
34    eliminate
35      NaturalArithmeticErrorCode
36      (lambda unrestricted current : (family NaturalArithmeticErrorCode) . Bytes)
37      code
38      (branch NaturalArithmeticModuloByZero . b"ALPHA-STD-001")
39      (branch NaturalArithmeticDivideByZero . b"ALPHA-STD-002"))
40
41def naturalSelect =
42  (lambda unrestricted condition : Nat .
43    unrestricted whenTrue : Nat .
44    unrestricted whenFalse : Nat .
45    nat-eliminate
46      (lambda unrestricted current : Nat . Nat)
47      whenFalse
48      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . whenTrue)
49      condition)
50
51def naturalMinimum =
52  (lambda unrestricted left : Nat . unrestricted right : Nat .
53    nat-eliminate
54      (lambda unrestricted current : Nat . Nat)
55      right
56      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . left)
57      (nat-less-than left right))
58
59-- Zero tests and ordering go through the ONE constant-time primitive the
60-- runtime offers on naturals, `nat-less-than`. A `nat-eliminate` over a
61-- natural is executed as a loop over its whole magnitude (measured
62-- 2026-09-16: asking whether the length of a 1 MiB string is zero cost 68 ms
63-- per call, about 65 ns per unit; the same question through nat-less-than
64-- costs nothing measurable), so no comparison may recurse on the value it
65-- compares. The 0/1 flag nat-less-than returns is the only thing eliminated.
66def naturalNonzero =
67  (lambda unrestricted value : Nat . nat-less-than 0 value)
68
69def naturalIsZero =
70  (lambda unrestricted value : Nat .
71    nat-eliminate
72      (lambda unrestricted current : Nat . Nat)
73      1
74      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . 0)
75      (nat-less-than 0 value))
76
77-- The flag operations below are written on the primitives themselves, not
78-- on one another: a realization calls them millions of times, and each call
79-- of one helper from another costs the machine an application chain (an
80-- equality through naturalAnd, naturalIsZero and naturalSelect took 44 steps
81-- where these take a handful; they were three fifths of realizing a tiled
82-- product).  Each eliminates only a 0/1 flag from nat-less-than.
83def naturalAnd =
84  (lambda unrestricted left : Nat . unrestricted right : Nat .
85    nat-eliminate
86      (lambda unrestricted current : Nat . Nat)
87      0
88      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . nat-less-than 0 right)
89      (nat-less-than 0 left))
90
91def naturalOr =
92  (lambda unrestricted left : Nat . unrestricted right : Nat .
93    nat-eliminate
94      (lambda unrestricted current : Nat . Nat)
95      (nat-less-than 0 right)
96      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . 1)
97      (nat-less-than 0 left))
98
99-- D21: the arithmetic below is the language's own (`nat-add` and friends run in
100-- one machine operation at run time and fold at compile time); the folds that
101-- counted step by step are gone. Semantics are unchanged: subtraction
102-- saturates at zero, x / 0 = 0, x mod 0 = x.
103def naturalAdd =
104  (lambda unrestricted left : Nat . unrestricted right : Nat . nat-add left right)
105
106def naturalPredecessor =
107  (lambda unrestricted value : Nat . nat-subtract value 1)
108
109def naturalSaturatingSubtract =
110  (lambda unrestricted left : Nat . unrestricted right : Nat . nat-subtract left right)
111
112def naturalMultiply =
113  (lambda unrestricted left : Nat . unrestricted right : Nat . nat-multiply left right)
114
115def naturalEqual =
116  (lambda unrestricted left : Nat . unrestricted right : Nat .
117    nat-eliminate
118      (lambda unrestricted current : Nat . Nat)
119      (nat-eliminate
120        (lambda unrestricted current : Nat . Nat)
121        1
122        (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . 0)
123        (nat-less-than left right))
124      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . 0)
125      (nat-less-than right left))
126
127def naturalLess =
128  (lambda unrestricted left : Nat . unrestricted right : Nat . nat-less-than left right)
129
130def naturalLessOrEqual =
131  (lambda unrestricted left : Nat . unrestricted right : Nat .
132    nat-eliminate
133      (lambda unrestricted current : Nat . Nat)
134      1
135      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat . 0)
136      (nat-less-than right left))
137
138def naturalModuloUnchecked =
139  (lambda unrestricted value : Nat . unrestricted divisor : Nat . nat-modulo value divisor)
140
141def naturalModulo =
142  (lambda unrestricted value : Nat . unrestricted divisor : Nat .
143    nat-eliminate
144      (lambda unrestricted current : Nat . family NaturalModuloResult)
145      (constructor
146        NaturalModuloResult
147        NaturalModuloFailed
148        (constructor NaturalArithmeticErrorCode NaturalArithmeticModuloByZero))
149      (lambda unrestricted predecessor : Nat .
150        unrestricted induction : (family NaturalModuloResult) .
151        constructor
152          NaturalModuloResult
153          NaturalModuloSucceeded
154          (naturalModuloUnchecked value divisor))
155      divisor)
156
157def naturalDivisionStep =
158  (lambda unrestricted divisor : Nat . unrestricted state : (family NaturalDivisionState) .
159    eliminate
160      NaturalDivisionState
161      (lambda unrestricted current : (family NaturalDivisionState) . family NaturalDivisionState)
162      state
163      (branch NaturalDivisionStateValue remainder quotient .
164        app
165          (lambda unrestricted incremented : Nat .
166            nat-eliminate
167              (lambda unrestricted condition : Nat . family NaturalDivisionState)
168              (constructor NaturalDivisionState NaturalDivisionStateValue incremented quotient)
169              (lambda unrestricted predecessor : Nat .
170                unrestricted induction : (family NaturalDivisionState) .
171                constructor NaturalDivisionState NaturalDivisionStateValue 0 (succ quotient))
172              (naturalEqual incremented divisor))
173          (succ remainder)))
174
175def naturalDivisionState =
176  (lambda unrestricted value : Nat . unrestricted divisor : Nat .
177    nat-eliminate
178      (lambda unrestricted current : Nat . family NaturalDivisionState)
179      (constructor NaturalDivisionState NaturalDivisionStateValue 0 0)
180      (lambda unrestricted predecessor : Nat .
181        unrestricted induction : (family NaturalDivisionState) .
182        naturalDivisionStep divisor induction)
183      value)
184
185def naturalDivideUnchecked =
186  (lambda unrestricted value : Nat . unrestricted divisor : Nat . nat-divide value divisor)
187
188def naturalDivide =
189  (lambda unrestricted value : Nat . unrestricted divisor : Nat .
190    nat-eliminate
191      (lambda unrestricted current : Nat . family NaturalDivideResult)
192      (constructor
193        NaturalDivideResult
194        NaturalDivideFailed
195        (constructor NaturalArithmeticErrorCode NaturalArithmeticDivideByZero))
196      (lambda unrestricted predecessor : Nat .
197        unrestricted induction : (family NaturalDivideResult) .
198        constructor
199          NaturalDivideResult
200          NaturalDivideSucceeded
201          (naturalDivideUnchecked value divisor))
202      divisor)
203
204def naturalPowerOfTwo =
205  (lambda unrestricted exponent : Nat .
206    nat-eliminate
207      (lambda unrestricted current : Nat . Nat)
208      1
209      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat .
210        naturalAdd induction induction)
211      exponent)
212
213-- 256, by doubling: the divisor behind "fits in N bytes".
214def naturalTwoHundredFiftySix =
215  (naturalPowerOfTwo 8)
216
217-- "value < 256^byteCount" WITHOUT ever building 256^byteCount: divide by 256
218-- byteCount times and ask whether anything is left.
219--
220-- A runtime natural costs about 164 bytes and 300 ns PER UNIT of its magnitude
221-- (measured 2026-09-16: 2^20 takes 0.8 s and 195 MB, 2^24 takes 5 s and
222-- 2.75 GB, and 2^32 cannot be built at all -- the image exits 125). So a bound
223-- such as 2^32 must never be materialised, and `naturalLess x (naturalPowerOfTwo
224-- 32)` is not a comparison but an out-of-memory. This is how "fits in a 32-bit
225-- field" is asked instead; it costs about value/256 steps.
226def naturalBelowBytePower =
227  (lambda unrestricted byteCount : Nat . unrestricted value : Nat .
228    naturalIsZero
229      (nat-eliminate
230        (lambda unrestricted current : Nat . Nat)
231        value
232        (lambda unrestricted predecessor : Nat . unrestricted quotient : Nat .
233          naturalDivideUnchecked quotient naturalTwoHundredFiftySix)
234        byteCount))
235
236-- "value <= 256^byteCount", as (value - 1) < 256^byteCount with the saturating
237-- predecessor: 0 qualifies, 256^byteCount itself qualifies, one more does not.
238-- Callers that wrote `naturalLessOrEqual x bound` keep exactly that bound.
239def naturalAtMostBytePower =
240  (lambda unrestricted byteCount : Nat . unrestricted value : Nat .
241    naturalBelowBytePower byteCount (naturalPredecessor value))
242
243-- value < 2^32: it fits a 32-bit word
244def naturalFitsWord32 =
245  (lambda unrestricted value : Nat . naturalBelowBytePower 4 value)
246
247-- Every byte of the accesses offset + stride * i .. + width - 1, for
248-- first <= i < first + count, is at most maximum (an inclusive bound).
249-- Empty ranges have no accesses; nonempty ranges need positive width.
250--
251-- Work backwards from the remaining budget instead of constructing the
252-- endpoint. Saturating subtraction and division cannot overflow, even when
253-- the mathematical index sum or product exceeds the evaluator's Nat range.
254-- In particular, stride zero needs no representable index at all. A zero
255-- divisor yields zero in naturalDivideUnchecked; that quotient is ignored
256-- by the zero-stride branch. No sum or product is evaluated in this check.
257--
258-- This bounds resulting addresses, NOT an index evaluated in a narrow
259-- register before a predicate. Check that range separately with
260-- naturalRangeAtMost. Scalar operands, runtime inputs and a wider address
261-- base also have separate obligations. See #173 for the exchange consumer.
262def naturalAffineAccessAtMost =
263  (lambda unrestricted maximum : Nat . (lambda unrestricted offset : Nat .
264    (lambda unrestricted stride : Nat . (lambda unrestricted first : Nat .
265      (lambda unrestricted count : Nat . (lambda unrestricted width : Nat .
266        (let unrestricted remaining = (naturalSaturatingSubtract maximum offset) in
267        (let unrestricted lastByte = (naturalPredecessor width) in
268        (let unrestricted indexLimit =
269          (naturalDivideUnchecked (naturalSaturatingSubtract remaining lastByte) stride) in
270          (naturalOr (naturalIsZero count)
271            (naturalAnd (naturalNonzero width)
272              (naturalAnd (naturalLessOrEqual offset maximum)
273                (naturalAnd (naturalLessOrEqual lastByte remaining)
274                  (naturalOr (naturalIsZero stride)
275                    (naturalAnd (naturalLessOrEqual first indexLimit)
276                      (naturalLessOrEqual (naturalPredecessor count)
277                        (naturalSaturatingSubtract indexLimit first)))))))))))))))))
278
279-- The affine values themselves, without a memory access width.
280def naturalAffineRangeAtMost =
281  (lambda unrestricted maximum : Nat . (lambda unrestricted offset : Nat .
282    (lambda unrestricted stride : Nat . (lambda unrestricted first : Nat .
283      (lambda unrestricted count : Nat .
284        (naturalAffineAccessAtMost maximum offset stride first count 1))))))
285
286-- All consecutive indices, including lanes that a later predicate excludes.
287def naturalRangeAtMost =
288  (lambda unrestricted maximum : Nat . (lambda unrestricted first : Nat .
289    (lambda unrestricted count : Nat .
290      (naturalAffineRangeAtMost maximum 0 1 first count))))
291
292-- "value < 2^bits" WITHOUT building 2^bits: halve bits times and ask whether
293-- anything is left. The general form of naturalBelowBytePower (a byte is eight
294-- halvings); it is what a limit such as "fits int64" (bits = 63) or "at most
295-- 16 MiB of input" (bits = 24) must use at runtime, since 2^24 alone costs
296-- 2.75 GB to materialise and 2^63 cannot be materialised at all.
297def naturalBelowTwoPower =
298  (lambda unrestricted bits : Nat . unrestricted value : Nat .
299    naturalIsZero
300      (nat-eliminate
301        (lambda unrestricted current : Nat . Nat)
302        value
303        (lambda unrestricted predecessor : Nat . unrestricted quotient : Nat .
304          naturalDivideUnchecked quotient 2)
305        bits))
306
307-- value <= 2^32
308def naturalAtMostTwoPower32 =
309  (lambda unrestricted value : Nat . naturalAtMostBytePower 4 value)
310
311-- How many of f 0, f 1, ..., f (count - 1) are zero: a plain fold over a
312-- closed count, so the checker runs it as a strict loop -- one cell at a
313-- time, each forgotten once counted.  (The first formulation nested each
314-- cell's select inside the previous one; a verdict of 40 cells that each run
315-- a program kept every earlier cell alive: 51 s against 7.6 s, two thirds of
316-- it garbage collection.)
317def naturalFailuresBelow =
318  (lambda unrestricted count : Nat . unrestricted f : (pi unrestricted index : Nat . Nat) .
319    nat-eliminate
320      (lambda unrestricted current : Nat . Nat)
321      0
322      (lambda unrestricted predecessor : Nat . unrestricted induction : Nat .
323        naturalAdd (naturalIsZero (f predecessor)) induction)
324      count)
325
326-- 1 when f 0, f 1, ..., f (count - 1) are all nonzero, else 0: a bounded
327-- universal verdict the checker can compute.  With a statement for every
328-- f (count + b), Std.Equality.stdNaturalAllBelowSound turns it into a
329-- statement for every natural -- a finite region decided by computation, the
330-- rest by an argument over an open offset.
331def naturalAllBelow =
332  (lambda unrestricted count : Nat . unrestricted f : (pi unrestricted index : Nat . Nat) .
333    naturalIsZero (naturalFailuresBelow count f))
334
335-- The decimal digits of a natural, most significant first ("0" for zero):
336-- the text form of a counter, a sequence number or a tick in an AOS-JSON/1
337-- stream (Observe.Value), and of a token cache path's ranges
338-- (Data.TokenCachePath). `fuel` is the caller's bound on the number of
339-- digits LESS ONE: a natural with more than `fuel + 1` digits keeps only its
340-- last `fuel + 1`, so every caller names a bound its values cannot exceed
341-- (a u64 has at most 20 digits).
342def naturalDecimalBuilder =
343  (lambda unrestricted fuel : Nat .
344    nat-eliminate
345      (lambda unrestricted current : Nat . pi unrestricted value : Nat . BytesBuilder)
346      (lambda unrestricted value : Nat .
347        then bytes-builder-chunk bytes nat-to-byte (naturalAdd 48) (naturalModuloUnchecked value) 10)
348      (lambda unrestricted predecessor : Nat .
349        unrestricted induction : (pi unrestricted value : Nat . BytesBuilder) .
350        unrestricted value : Nat .
351        let unrestricted quotient =
352          (naturalDivideUnchecked value 10)
353          in
354          nat-eliminate
355            (lambda unrestricted nonzero : Nat . BytesBuilder)
356            (then bytes-builder-chunk
357              bytes
358              nat-to-byte
359              (naturalAdd 48)
360              (naturalModuloUnchecked value)
361              10)
362            (lambda unrestricted quotientPredecessor : Nat .
363              unrestricted quotientInduction : BytesBuilder .
364              then (bytes-builder-append (induction quotient))
365                bytes-builder-chunk
366                bytes
367                nat-to-byte
368                (naturalAdd 48)
369                (naturalModuloUnchecked value)
370                10)
371            (naturalNonzero quotient))
372      fuel)
373
374def naturalDecimalBytesWithin =
375  (lambda unrestricted fuel : Nat . unrestricted value : Nat .
376    bytes-builder-build (naturalDecimalBuilder fuel value))

The compiler supplied declaration spans and resolved links from this source snapshot. This page does not assert that this file belongs to a checked closure.