pud.dev 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +106 -0
- package/README.md +117 -2
- package/package.json +24 -4
- package/scripts/pack.ts +67 -0
- package/scripts/setup-lean.ts +88 -0
- package/src/assistant.ts +131 -0
- package/src/check.ts +173 -0
- package/src/cli.ts +70 -0
- package/src/expressions.ts +65 -0
- package/src/index.ts +4 -0
- package/src/input-scope.ts +71 -0
- package/src/lean/command.ts +40 -0
- package/src/lean/index.ts +437 -0
- package/src/lean/iteration.lean +145 -0
- package/src/lean/lean-assets.d.ts +4 -0
- package/src/lean/number.lean +427 -0
- package/src/lean/number.ts +25 -0
- package/src/lean/program.ts +110 -0
- package/src/lean/replay-predicate.ts +95 -0
- package/src/lean/replay.ts +136 -0
- package/src/lean/scalar.lean +183 -0
- package/src/lean/scalar.ts +196 -0
- package/src/lean/subject.ts +443 -0
- package/src/lean/syntax.ts +287 -0
- package/src/module.ts +110 -0
- package/src/project-runner.ts +26 -0
- package/src/prover-process.ts +16 -0
- package/src/reporter.ts +173 -0
- package/src/run.ts +60 -0
- package/src/source.ts +54 -0
- package/src/suite-authoring.ts +135 -0
- package/src/suite-check.ts +157 -0
- package/src/suite.ts +515 -0
- package/src/terminal-progress.ts +145 -0
- package/src/terminal.ts +41 -0
- package/test/authoring.test.ts +151 -0
- package/test/lean.test.ts +394 -0
- package/test/module.test.ts +55 -0
- package/test/number.test.ts +318 -0
- package/test/package.test.ts +170 -0
- package/test/suite.test.ts +257 -0
- package/tsconfig.json +7 -0
- package/tsconfig.pack.json +12 -0
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import Std
|
|
2
|
+
|
|
3
|
+
namespace Pud
|
|
4
|
+
|
|
5
|
+
-- The magnitude is the unsigned binary64 encoding with the sign bit removed.
|
|
6
|
+
-- Both zeros are representable. Scalar ECMAScript Number has one observable NaN.
|
|
7
|
+
inductive JSNumber where
|
|
8
|
+
| nan
|
|
9
|
+
| num (negative : Bool) (magnitude : Fin (0x7ff0000000000000 + 1))
|
|
10
|
+
deriving DecidableEq, Repr
|
|
11
|
+
|
|
12
|
+
namespace JSNumber
|
|
13
|
+
|
|
14
|
+
private abbrev infBits : Nat := 0x7ff0000000000000
|
|
15
|
+
private abbrev hiddenBit : Nat := 2^52
|
|
16
|
+
private def pack (negative : Bool) (m : Nat) : JSNumber :=
|
|
17
|
+
.num negative ⟨min m infBits, Nat.lt_succ_of_le (Nat.min_le_right ..)⟩
|
|
18
|
+
|
|
19
|
+
def ofBits (word : Nat) : JSNumber :=
|
|
20
|
+
let m := word % 2^63
|
|
21
|
+
if m > infBits then .nan else pack (word.testBit 63) m
|
|
22
|
+
|
|
23
|
+
def toBits : JSNumber → Nat
|
|
24
|
+
| .nan => 0x7ff8000000000000
|
|
25
|
+
| .num s m => (if s then 2^63 else 0) + m.val
|
|
26
|
+
|
|
27
|
+
def neg : JSNumber → JSNumber
|
|
28
|
+
| .nan => .nan
|
|
29
|
+
| .num s m => .num (!s) m
|
|
30
|
+
|
|
31
|
+
def isNaN : JSNumber → Bool
|
|
32
|
+
| .nan => true
|
|
33
|
+
| .num .. => false
|
|
34
|
+
|
|
35
|
+
def isZero : JSNumber → Bool
|
|
36
|
+
| .nan => false
|
|
37
|
+
| .num _ m => m.val == 0
|
|
38
|
+
|
|
39
|
+
def eq (a b : JSNumber) : Bool :=
|
|
40
|
+
if b.isNaN then false else if b.isZero then a.isZero else decide (a = b)
|
|
41
|
+
|
|
42
|
+
def truthy (x : JSNumber) : Bool := !(x.isNaN || x.isZero)
|
|
43
|
+
|
|
44
|
+
-- The magnitude bits increase with absolute value. This signed key is used only for ordering.
|
|
45
|
+
private def orderKey (negative : Bool) (m : Nat) : Int := if negative then -Int.ofNat m else Int.ofNat m
|
|
46
|
+
|
|
47
|
+
def lt : JSNumber → JSNumber → Bool
|
|
48
|
+
| .num s m, .num t n => decide (orderKey s m.val < orderKey t n.val)
|
|
49
|
+
| _, _ => false
|
|
50
|
+
|
|
51
|
+
def le : JSNumber → JSNumber → Bool
|
|
52
|
+
| .num s m, .num t n => decide (orderKey s m.val ≤ orderKey t n.val)
|
|
53
|
+
| _, _ => false
|
|
54
|
+
|
|
55
|
+
-- A finite input has exact absolute value significand(m) * 2^scale(m).
|
|
56
|
+
private def significand (m : Nat) := if m < hiddenBit then m else hiddenBit + m % hiddenBit
|
|
57
|
+
private def scale (m : Nat) : Int := Int.ofNat (max 1 (m / hiddenBit)) - 1075
|
|
58
|
+
|
|
59
|
+
private def roundEven (n d : Nat) : Nat :=
|
|
60
|
+
let q := n / d
|
|
61
|
+
let twice := 2 * (n % d)
|
|
62
|
+
if twice > d || (twice == d && q % 2 == 1) then q + 1 else q
|
|
63
|
+
|
|
64
|
+
-- Exact arithmetic on two binary64 operands uses fewer than 2,100 significant bits.
|
|
65
|
+
-- Binary search keeps these closed calculations reducible in the Lean kernel.
|
|
66
|
+
private def bitLog (n : Nat) : Nat :=
|
|
67
|
+
if n >>> 4096 != 0 then n.log2 else
|
|
68
|
+
[2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1].foldl
|
|
69
|
+
(fun k step => if n >>> (k + step) != 0 then k + step else k) 0
|
|
70
|
+
|
|
71
|
+
-- floor(log2(n/d)), where n and d are positive.
|
|
72
|
+
private def logRatio (n d : Nat) : Int :=
|
|
73
|
+
let k := Int.ofNat (bitLog n) - Int.ofNat (bitLog d)
|
|
74
|
+
if (n <<< (-k).toNat) < (d <<< k.toNat) then k - 1 else k
|
|
75
|
+
|
|
76
|
+
-- Round the exact nonnegative rational (n/d) * 2^k to the nearest binary64.
|
|
77
|
+
-- The smallest unit is one subnormal. A carry at the top exponent yields infinity.
|
|
78
|
+
private def roundedMagnitude (n d : Nat) (k : Int) : Nat :=
|
|
79
|
+
if n = 0 then 0 else
|
|
80
|
+
let unit := max (-1074) (logRatio n d + k - 52)
|
|
81
|
+
let shift := k - unit
|
|
82
|
+
let q := roundEven (n <<< shift.toNat) (d <<< (-shift).toNat)
|
|
83
|
+
if q < hiddenBit then q else
|
|
84
|
+
let carry := q == 2 * hiddenBit
|
|
85
|
+
let exponent := (unit + 1075).toNat + (if carry then 1 else 0)
|
|
86
|
+
let fraction := if carry then 0 else q - hiddenBit
|
|
87
|
+
exponent * hiddenBit + fraction
|
|
88
|
+
|
|
89
|
+
private def fromRatio (s : Bool) (n d : Nat) (k : Int) := pack s (roundedMagnitude n d k)
|
|
90
|
+
|
|
91
|
+
def mul : JSNumber → JSNumber → JSNumber
|
|
92
|
+
| .num s a, .num t b =>
|
|
93
|
+
let sign := xor s t
|
|
94
|
+
if a.val == infBits || b.val == infBits then
|
|
95
|
+
if a.val == 0 || b.val == 0 then .nan else pack sign infBits
|
|
96
|
+
else fromRatio sign (significand a * significand b) 1 (scale a + scale b)
|
|
97
|
+
| _, _ => .nan
|
|
98
|
+
|
|
99
|
+
def div : JSNumber → JSNumber → JSNumber
|
|
100
|
+
| .num s a, .num t b =>
|
|
101
|
+
let sign := xor s t
|
|
102
|
+
if (a.val == 0 && b.val == 0) || (a.val == infBits && b.val == infBits) then .nan
|
|
103
|
+
else if a.val == infBits || b.val == 0 then pack sign infBits
|
|
104
|
+
else if b.val == infBits then pack sign 0
|
|
105
|
+
else fromRatio sign (significand a) (significand b) (scale a - scale b)
|
|
106
|
+
| _, _ => .nan
|
|
107
|
+
|
|
108
|
+
def add : JSNumber → JSNumber → JSNumber
|
|
109
|
+
| .num s a, .num t b =>
|
|
110
|
+
if a.val == infBits then
|
|
111
|
+
if b.val == infBits && s != t then .nan else .num s a
|
|
112
|
+
else if b.val == infBits then .num t b
|
|
113
|
+
else
|
|
114
|
+
let k := min (scale a) (scale b)
|
|
115
|
+
let x := significand a <<< (scale a - k).toNat
|
|
116
|
+
let y := significand b <<< (scale b - k).toNat
|
|
117
|
+
let sum := orderKey s x + orderKey t y
|
|
118
|
+
fromRatio (decide (sum < 0) || (sum == 0 && s && t)) sum.natAbs 1 k
|
|
119
|
+
| _, _ => .nan
|
|
120
|
+
|
|
121
|
+
def sub (a b : JSNumber) := add a (neg b)
|
|
122
|
+
|
|
123
|
+
private inductive IntegralMode where | nearest | down | up | towardZero
|
|
124
|
+
|
|
125
|
+
private abbrev oneBits : Nat := 0x3ff0000000000000
|
|
126
|
+
private abbrev halfBits : Nat := 0x3fe0000000000000
|
|
127
|
+
|
|
128
|
+
private def roundUp (mode : IntegralMode) (negative : Bool) (remainder unit : Nat) : Bool :=
|
|
129
|
+
match mode with
|
|
130
|
+
| .nearest => 2 * remainder > unit || (2 * remainder == unit && !negative)
|
|
131
|
+
| .down => negative && remainder != 0
|
|
132
|
+
| .up => !negative && remainder != 0
|
|
133
|
+
| .towardZero => false
|
|
134
|
+
|
|
135
|
+
private def roundIntegral (mode : IntegralMode) : JSNumber → JSNumber
|
|
136
|
+
| .nan => .nan
|
|
137
|
+
| .num s m =>
|
|
138
|
+
if m.val < oneBits then
|
|
139
|
+
let up := match mode with
|
|
140
|
+
| .nearest => m.val > halfBits || (m.val == halfBits && !s)
|
|
141
|
+
| .down => s && m.val != 0
|
|
142
|
+
| .up => !s && m.val != 0
|
|
143
|
+
| .towardZero => false
|
|
144
|
+
pack s (if up then oneBits else 0)
|
|
145
|
+
else
|
|
146
|
+
let exponent := m.val / hiddenBit
|
|
147
|
+
if exponent ≥ 1075 then .num s m else
|
|
148
|
+
-- Between 1 and 2^52 the low (1075 - exponent) bits encode the fraction.
|
|
149
|
+
-- oneBits is aligned to every such unit. A carry crosses exponents naturally.
|
|
150
|
+
let unit := 2 ^ (1075 - exponent)
|
|
151
|
+
let offset := m.val - oneBits
|
|
152
|
+
let base := oneBits + offset / unit * unit
|
|
153
|
+
pack s (base + if roundUp mode s (offset % unit) unit then unit else 0)
|
|
154
|
+
|
|
155
|
+
-- Number.isInteger describes the represented value, including integers beyond the safe range.
|
|
156
|
+
def isInteger : JSNumber → Bool
|
|
157
|
+
| .nan => false
|
|
158
|
+
| .num _ m =>
|
|
159
|
+
if m.val < oneBits then m.val == 0 else
|
|
160
|
+
let exponent := m.val / hiddenBit
|
|
161
|
+
m.val != infBits && (exponent ≥ 1075 || (m.val - oneBits) % (2 ^ (1075 - exponent)) == 0)
|
|
162
|
+
|
|
163
|
+
-- Math.round resolves half ties toward positive infinity and preserves a negative zero.
|
|
164
|
+
def round := roundIntegral .nearest
|
|
165
|
+
def floor := roundIntegral .down
|
|
166
|
+
def ceil := roundIntegral .up
|
|
167
|
+
def trunc := roundIntegral .towardZero
|
|
168
|
+
|
|
169
|
+
-- Compare the fractional magnitude to its midpoint. When the sign is negative,
|
|
170
|
+
-- the integer of smaller magnitude is the upper endpoint on the number line.
|
|
171
|
+
private def lowerIsNearer (negative : Bool) (a b : Nat) : Bool :=
|
|
172
|
+
if negative then decide (b < a) else decide (a < b)
|
|
173
|
+
|
|
174
|
+
-- For a fractional Number, floor and ceil are the two adjacent integers.
|
|
175
|
+
-- Below unit magnitude the ordering of the magnitude bits locates the half.
|
|
176
|
+
-- Above it, compare exact distances in representable steps in this exponent bin.
|
|
177
|
+
-- Both endpoints coincide on integers, signed zeros, infinities and NaN.
|
|
178
|
+
private def nearestTiesUp (x : JSNumber) : JSNumber :=
|
|
179
|
+
match x with
|
|
180
|
+
| .nan => .nan
|
|
181
|
+
| .num s m =>
|
|
182
|
+
let lower := if m.val < oneBits then lowerIsNearer s m.val halfBits else
|
|
183
|
+
let unit := 2 ^ (1075 - m.val / hiddenBit)
|
|
184
|
+
let remainder := (m.val - oneBits) % unit
|
|
185
|
+
lowerIsNearer s remainder (unit - remainder)
|
|
186
|
+
if lower then floor x else ceil x
|
|
187
|
+
|
|
188
|
+
private theorem nearest_step (s : Bool) (r u : Nat) (hr : r < u) :
|
|
189
|
+
(if lowerIsNearer s r (u - r) then roundUp .down s r u else roundUp .up s r u) =
|
|
190
|
+
roundUp .nearest s r u := by
|
|
191
|
+
have below : r < u - r ↔ 2 * r < u := by omega
|
|
192
|
+
have above : u - r < r ↔ u < 2 * r := by omega
|
|
193
|
+
rcases Nat.lt_trichotomy (2 * r) u with low | tie | high <;> by_cases z : r = 0 <;>
|
|
194
|
+
cases s <;> simp (disch := omega) [lowerIsNearer, roundUp, below, above, *, bne_iff_ne] <;>
|
|
195
|
+
(try simp_all) <;> omega
|
|
196
|
+
|
|
197
|
+
private theorem nearestTiesUp_round (x : JSNumber) : nearestTiesUp x = round x := by
|
|
198
|
+
cases x with
|
|
199
|
+
| nan => rfl
|
|
200
|
+
| num s m =>
|
|
201
|
+
unfold nearestTiesUp
|
|
202
|
+
dsimp only
|
|
203
|
+
by_cases small : m.val < oneBits
|
|
204
|
+
· simp only [small, ↓reduceIte, floor, ceil, round, roundIntegral]
|
|
205
|
+
by_cases z : m.val = 0 <;> by_cases tie : m.val = halfBits <;> by_cases above : halfBits < m.val <;>
|
|
206
|
+
cases s <;> simp [lowerIsNearer, *, halfBits] at * <;> (repeat' split) <;> (try simp_all) <;> omega
|
|
207
|
+
· simp only [small, Bool.false_eq_true, ↓reduceIte, floor, ceil, round, roundIntegral]
|
|
208
|
+
by_cases large : m.val / hiddenBit ≥ 1075
|
|
209
|
+
· simp [large]
|
|
210
|
+
· simp only [large, ↓reduceIte]
|
|
211
|
+
let u := 2 ^ (1075 - m.val / hiddenBit)
|
|
212
|
+
let r := (m.val - oneBits) % u
|
|
213
|
+
have hr : r < u := Nat.mod_lt _ (Nat.pow_pos (by decide))
|
|
214
|
+
have step := nearest_step s r u hr
|
|
215
|
+
by_cases lower : lowerIsNearer s r (u - r) = true <;>
|
|
216
|
+
simp [lower] at step <;>
|
|
217
|
+
simp only [u, r] at lower step <;> simp [lower, step]
|
|
218
|
+
|
|
219
|
+
-- Reflection exchanges upper and lower ties and preserves the sign of a zero result.
|
|
220
|
+
def nearestInteger (x : JSNumber) (tiesUp : Bool) : JSNumber :=
|
|
221
|
+
if tiesUp then nearestTiesUp x else neg (nearestTiesUp (neg x))
|
|
222
|
+
|
|
223
|
+
theorem nearestInteger_round (x : JSNumber) : nearestInteger x true = round x :=
|
|
224
|
+
nearestTiesUp_round x
|
|
225
|
+
|
|
226
|
+
theorem nearestInteger_round_down (x : JSNumber) : nearestInteger x false = neg (round (neg x)) :=
|
|
227
|
+
congrArg neg (nearestTiesUp_round (neg x))
|
|
228
|
+
|
|
229
|
+
-- A strict-equality premise fixes the input bits for every nonzero, non-NaN literal.
|
|
230
|
+
theorem eq_regular {a b : JSNumber} (hn : b.isNaN = false) (hz : b.isZero = false) :
|
|
231
|
+
eq a b = true ↔ a = b := by simp [eq, hn, hz]
|
|
232
|
+
|
|
233
|
+
private theorem nonnegative_pack (m : Nat) : le (ofBits 0) (pack false m) = true := by
|
|
234
|
+
change decide ((0 : Int) ≤ Int.ofNat (min m infBits)) = true
|
|
235
|
+
simp
|
|
236
|
+
|
|
237
|
+
private theorem nonnegative_ratio (n d : Nat) (k : Int) : le (ofBits 0) (fromRatio false n d k) = true := by
|
|
238
|
+
exact nonnegative_pack _
|
|
239
|
+
|
|
240
|
+
theorem nonnegative_round {x : JSNumber} (hx : le (ofBits 0) x = true) :
|
|
241
|
+
le (ofBits 0) (round x) = true := by
|
|
242
|
+
cases x with
|
|
243
|
+
| nan => contradiction
|
|
244
|
+
| num s m =>
|
|
245
|
+
cases s
|
|
246
|
+
case false =>
|
|
247
|
+
simp only [round, roundIntegral]
|
|
248
|
+
split
|
|
249
|
+
· apply nonnegative_pack
|
|
250
|
+
· split
|
|
251
|
+
· exact hx
|
|
252
|
+
· apply nonnegative_pack
|
|
253
|
+
case true =>
|
|
254
|
+
change decide ((0 : Int) ≤ -(m.val : Int)) = true at hx
|
|
255
|
+
simp only [decide_eq_true_eq] at hx
|
|
256
|
+
have hm : m.val = 0 := by omega
|
|
257
|
+
have zero : m = ⟨0, by decide⟩ := Fin.ext hm
|
|
258
|
+
subst m; decide
|
|
259
|
+
|
|
260
|
+
-- Scaling a nonnegative Number by a strictly positive, finite constant preserves its sign,
|
|
261
|
+
-- including -0 and overflow to +Infinity.
|
|
262
|
+
theorem nonnegative_mul {x c : JSNumber} (hc : lt (ofBits 0) c = true) (hf : lt c (ofBits infBits) = true)
|
|
263
|
+
(hx : le (ofBits 0) x = true) : le (ofBits 0) (mul x c) = true := by
|
|
264
|
+
cases c with
|
|
265
|
+
| nan => change false = true at hc; cases hc
|
|
266
|
+
| num t b =>
|
|
267
|
+
cases t
|
|
268
|
+
case true =>
|
|
269
|
+
change decide ((0 : Int) < -(b.val : Int)) = true at hc
|
|
270
|
+
simp only [decide_eq_true_eq] at hc
|
|
271
|
+
omega
|
|
272
|
+
case false =>
|
|
273
|
+
change decide ((0 : Int) < (b.val : Int)) = true at hc
|
|
274
|
+
change decide ((b.val : Int) < (infBits : Int)) = true at hf
|
|
275
|
+
simp only [decide_eq_true_eq] at hc hf
|
|
276
|
+
have hb : b.val ≠ 0 := by omega
|
|
277
|
+
have hi : b.val ≠ infBits := by omega
|
|
278
|
+
cases x with
|
|
279
|
+
| nan => change false = true at hx; cases hx
|
|
280
|
+
| num s a =>
|
|
281
|
+
cases s
|
|
282
|
+
case false =>
|
|
283
|
+
by_cases h : a.val = infBits
|
|
284
|
+
· simp [mul, h, hb, nonnegative_pack]
|
|
285
|
+
· simp [mul, h, hi, nonnegative_ratio]
|
|
286
|
+
case true =>
|
|
287
|
+
change decide ((0 : Int) ≤ -(a.val : Int)) = true at hx
|
|
288
|
+
simp only [decide_eq_true_eq] at hx
|
|
289
|
+
have ha : a.val = 0 := by omega
|
|
290
|
+
simp [mul, ha, hi, significand, fromRatio, roundedMagnitude]
|
|
291
|
+
decide
|
|
292
|
+
|
|
293
|
+
-- These rewrites operate on arbitrary operands. Structural equality includes NaN and signed zero.
|
|
294
|
+
theorem mul_comm (x y : JSNumber) : mul x y = mul y x := by
|
|
295
|
+
cases x <;> cases y <;> first | rfl | simp only [mul, Bool.xor_comm, Bool.or_comm, Nat.mul_comm, Int.add_comm]
|
|
296
|
+
|
|
297
|
+
theorem mul_neg (x y : JSNumber) : mul (neg x) y = neg (mul x y) := by
|
|
298
|
+
cases x with
|
|
299
|
+
| nan => rfl
|
|
300
|
+
| num s a =>
|
|
301
|
+
cases y with
|
|
302
|
+
| nan => rfl
|
|
303
|
+
| num t b => cases s <;> cases t <;> simp only [neg, mul] <;> repeat' first | rfl | split
|
|
304
|
+
|
|
305
|
+
theorem div_neg (x y : JSNumber) : div (neg x) y = neg (div x y) := by
|
|
306
|
+
cases x with
|
|
307
|
+
| nan => rfl
|
|
308
|
+
| num s a =>
|
|
309
|
+
cases y with
|
|
310
|
+
| nan => rfl
|
|
311
|
+
| num t b => cases s <;> cases t <;> simp only [neg, div] <;> repeat' first | rfl | split
|
|
312
|
+
|
|
313
|
+
theorem eq_self (x : JSNumber) : eq x x = !x.isNaN := by cases x <;> simp [eq, isNaN]
|
|
314
|
+
|
|
315
|
+
theorem isNaN_neg (x : JSNumber) : isNaN (neg x) = isNaN x := by cases x <;> rfl
|
|
316
|
+
|
|
317
|
+
def finiteNonzero : JSNumber → Bool
|
|
318
|
+
| .nan => false
|
|
319
|
+
| .num _ m => m.val != 0 && m.val != infBits
|
|
320
|
+
|
|
321
|
+
theorem isNaN_mul_right (x c : JSNumber) (hc : finiteNonzero c = true) : isNaN (mul x c) = isNaN x := by
|
|
322
|
+
cases c with
|
|
323
|
+
| nan => contradiction
|
|
324
|
+
| num t b =>
|
|
325
|
+
simp [finiteNonzero] at hc
|
|
326
|
+
cases x with
|
|
327
|
+
| nan => rfl
|
|
328
|
+
| num s a => by_cases h : a.val = infBits <;> simp [mul, hc.1, hc.2, h, isNaN, fromRatio, pack]
|
|
329
|
+
|
|
330
|
+
theorem isNaN_mul_left (c x : JSNumber) (hc : finiteNonzero c = true) : isNaN (mul c x) = isNaN x := by
|
|
331
|
+
rw [mul_comm, isNaN_mul_right x c hc]
|
|
332
|
+
|
|
333
|
+
theorem isNaN_div_right (x c : JSNumber) (hc : finiteNonzero c = true) : isNaN (div x c) = isNaN x := by
|
|
334
|
+
cases c with
|
|
335
|
+
| nan => contradiction
|
|
336
|
+
| num t b =>
|
|
337
|
+
simp [finiteNonzero] at hc
|
|
338
|
+
cases x with
|
|
339
|
+
| nan => rfl
|
|
340
|
+
| num s a => by_cases h : a.val = infBits <;> simp [div, hc.1, hc.2, h, isNaN, fromRatio, pack]
|
|
341
|
+
|
|
342
|
+
private theorem integral_fixed (mode : IntegralMode) {x : JSNumber} (hx : isInteger x = true) : eq (roundIntegral mode x) x = true := by
|
|
343
|
+
cases x with
|
|
344
|
+
| nan => contradiction
|
|
345
|
+
| num s m =>
|
|
346
|
+
suffices fixed : roundIntegral mode (.num s m) = .num s m by rw [fixed, eq_self]; rfl
|
|
347
|
+
by_cases small : m.val < oneBits
|
|
348
|
+
· change (if m.val < oneBits then m.val == 0 else _) = true at hx
|
|
349
|
+
have zero : m = ⟨0, by decide⟩ := Fin.ext (by simpa [small] using hx)
|
|
350
|
+
subst m
|
|
351
|
+
cases mode <;> cases s <;> decide
|
|
352
|
+
· by_cases large : m.val / hiddenBit ≥ 1075
|
|
353
|
+
· simp [round, roundIntegral, small, large]
|
|
354
|
+
· have aligned : (m.val - oneBits) % (2 ^ (1075 - m.val / hiddenBit)) = 0 := by
|
|
355
|
+
simp [isInteger, small, large] at hx
|
|
356
|
+
exact hx.2
|
|
357
|
+
have restored := Nat.div_add_mod (m.val - oneBits) (2 ^ (1075 - m.val / hiddenBit))
|
|
358
|
+
rw [aligned, Nat.add_zero, Nat.mul_comm] at restored
|
|
359
|
+
have unit : (0 : Nat) ≠ 2 ^ (1075 - m.val / hiddenBit) := Nat.ne_of_lt (Nat.pow_pos (by decide))
|
|
360
|
+
cases mode <;> simp [roundIntegral, small, large, roundUp, aligned, restored, pack, unit,
|
|
361
|
+
Nat.add_sub_of_le (Nat.le_of_not_gt small), Nat.min_eq_left (Nat.le_of_lt_succ m.isLt)]
|
|
362
|
+
|
|
363
|
+
theorem round_integer {x : JSNumber} (h : isInteger x = true) : eq (round x) x = true := integral_fixed .nearest h
|
|
364
|
+
theorem floor_integer {x : JSNumber} (h : isInteger x = true) : eq (floor x) x = true := integral_fixed .down h
|
|
365
|
+
theorem ceil_integer {x : JSNumber} (h : isInteger x = true) : eq (ceil x) x = true := integral_fixed .up h
|
|
366
|
+
theorem trunc_integer {x : JSNumber} (h : isInteger x = true) : eq (trunc x) x = true := integral_fixed .towardZero h
|
|
367
|
+
|
|
368
|
+
-- JavaScript comparison sees -0 as zero; its reciprocal exposes the sign after underflow.
|
|
369
|
+
private theorem negative_or_reciprocal (m : Fin (infBits + 1)) :
|
|
370
|
+
lt (.num true m) (ofBits 0) = true ∨ lt (div (ofBits oneBits) (.num true m)) (ofBits 0) = true := by
|
|
371
|
+
by_cases h : m.val = 0
|
|
372
|
+
· have hm : m = ⟨0, by decide⟩ := Fin.ext h
|
|
373
|
+
subst m
|
|
374
|
+
right; decide
|
|
375
|
+
· left
|
|
376
|
+
change decide (-(m.val : Int) < 0) = true
|
|
377
|
+
simp only [decide_eq_true_eq]
|
|
378
|
+
omega
|
|
379
|
+
|
|
380
|
+
theorem negative_div {x c : JSNumber} (hc : finiteNonzero c = true) (hp : lt (ofBits 0) c = true)
|
|
381
|
+
(hx : lt x (ofBits 0) = true) :
|
|
382
|
+
lt (div x c) (ofBits 0) = true ∨ lt (div (ofBits oneBits) (div x c)) (ofBits 0) = true := by
|
|
383
|
+
cases c with
|
|
384
|
+
| nan => contradiction
|
|
385
|
+
| num t b =>
|
|
386
|
+
cases t
|
|
387
|
+
case true =>
|
|
388
|
+
change decide ((0 : Int) < -(b.val : Int)) = true at hp
|
|
389
|
+
simp only [decide_eq_true_eq] at hp
|
|
390
|
+
omega
|
|
391
|
+
case false =>
|
|
392
|
+
simp [finiteNonzero] at hc
|
|
393
|
+
cases x with
|
|
394
|
+
| nan => contradiction
|
|
395
|
+
| num s a =>
|
|
396
|
+
cases s
|
|
397
|
+
case false =>
|
|
398
|
+
change decide ((a.val : Int) < 0) = true at hx
|
|
399
|
+
simp only [decide_eq_true_eq] at hx
|
|
400
|
+
omega
|
|
401
|
+
case true =>
|
|
402
|
+
have result : ∃ m, div (.num true a) (.num false b) = .num true m := by
|
|
403
|
+
by_cases h : a.val = infBits <;>
|
|
404
|
+
simp [div, h, hc.1, hc.2, fromRatio, pack]
|
|
405
|
+
obtain ⟨m, hm⟩ := result
|
|
406
|
+
rw [hm]
|
|
407
|
+
exact negative_or_reciprocal m
|
|
408
|
+
|
|
409
|
+
private theorem integral_nonzero (s : Bool) (a b : Nat) : isZero (pack s (oneBits + a + b)) = false := by
|
|
410
|
+
change (min (oneBits + a + b) infBits == 0) = false
|
|
411
|
+
simp [Nat.min_def, oneBits, infBits]
|
|
412
|
+
split <;> omega
|
|
413
|
+
|
|
414
|
+
-- Math.round's zero cell is closed at -0.5 and open at +0.5, including both input zeros.
|
|
415
|
+
theorem round_eq_zero (x : JSNumber) :
|
|
416
|
+
eq (round x) (ofBits 0) = true ↔
|
|
417
|
+
le (neg (ofBits halfBits)) x = true ∧ lt x (ofBits halfBits) = true := by
|
|
418
|
+
cases x with
|
|
419
|
+
| nan => decide
|
|
420
|
+
| num s m =>
|
|
421
|
+
change isZero (roundIntegral .nearest (.num s m)) = true ↔
|
|
422
|
+
decide (-(halfBits : Int) ≤ orderKey s m.val) = true ∧ decide (orderKey s m.val < (halfBits : Int)) = true
|
|
423
|
+
cases s <;> simp only [roundIntegral, orderKey, Bool.false_eq_true, ↓reduceIte, decide_eq_true_eq] <;>
|
|
424
|
+
split <;> (repeat' split) <;> (try simp only [integral_nonzero]) <;> simp_all [pack, isZero, halfBits, oneBits, infBits] <;> omega
|
|
425
|
+
|
|
426
|
+
end JSNumber
|
|
427
|
+
end Pud
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/// <reference path="./lean-assets.d.ts" />
|
|
2
|
+
import model from "./number.lean" with { type: "text" };
|
|
3
|
+
import type { Value } from "./syntax.ts";
|
|
4
|
+
|
|
5
|
+
export const numberSemantics = model.replace(/^import Std\s*/, "").trimEnd();
|
|
6
|
+
|
|
7
|
+
export function numberLiteral(value: number): Value {
|
|
8
|
+
const bytes = new DataView(new ArrayBuffer(8));
|
|
9
|
+
bytes.setFloat64(0, value);
|
|
10
|
+
return { sort: "number", code: `(JSNumber.ofBits 0x${bytes.getBigUint64(0).toString(16)})` };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const arithmetic = { "+": "add", "-": "sub", "*": "mul", "/": "div" } as const;
|
|
14
|
+
const comparisons = { "===": "eq", "!==": "eq", "<": "lt", "<=": "le", ">": "lt", ">=": "le" } as const;
|
|
15
|
+
|
|
16
|
+
export function numberBinary(op: string, lhs: string, rhs: string): Value | undefined {
|
|
17
|
+
if (Object.hasOwn(arithmetic, op)) {
|
|
18
|
+
return { sort: "number", code: `(JSNumber.${arithmetic[op as keyof typeof arithmetic]} ${lhs} ${rhs})` };
|
|
19
|
+
}
|
|
20
|
+
if (Object.hasOwn(comparisons, op)) {
|
|
21
|
+
const args = op === ">" || op === ">=" ? `${rhs} ${lhs}` : `${lhs} ${rhs}`;
|
|
22
|
+
const comparison = `(JSNumber.${comparisons[op as keyof typeof comparisons]} ${args})`;
|
|
23
|
+
return { sort: "boolean", code: op === "!==" ? `(!${comparison})` : comparison };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { Node, Program } from "@babel/types";
|
|
2
|
+
import type { SubjectSource } from "../assistant.ts";
|
|
3
|
+
import { selectSubject } from "../module.ts";
|
|
4
|
+
import { invalid, parseSourceModule, resolveTypeScriptImport } from "../source.ts";
|
|
5
|
+
import { dirname } from "node:path";
|
|
6
|
+
import { lowerFunction, type Subject } from "./subject.ts";
|
|
7
|
+
|
|
8
|
+
interface Module {
|
|
9
|
+
file: string;
|
|
10
|
+
source: string;
|
|
11
|
+
program: Program;
|
|
12
|
+
declarations: Program;
|
|
13
|
+
imports: Map<string, { owner: Module; name: string }>;
|
|
14
|
+
resolvedImports: { start: number; end: number; file: string }[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Link source functions only after validating module initialization and binding identities. */
|
|
18
|
+
export function lowerProgram(source: SubjectSource) {
|
|
19
|
+
const modules = new Map<string, Module>();
|
|
20
|
+
const loading = new Set<string>();
|
|
21
|
+
const functions = new Map<Module, Map<string, Subject>>();
|
|
22
|
+
const compiling = new Map<Module, Set<string>>();
|
|
23
|
+
let nextFunction = 0;
|
|
24
|
+
|
|
25
|
+
function load(file: string, contents: string): Module {
|
|
26
|
+
if (loading.has(file)) invalid(file, undefined, "Cyclic runtime imports are outside the Lean model.");
|
|
27
|
+
const cached = modules.get(file);
|
|
28
|
+
if (cached) return cached;
|
|
29
|
+
loading.add(file);
|
|
30
|
+
try {
|
|
31
|
+
const program = parseSourceModule(file, contents);
|
|
32
|
+
const module: Module = { file, source: contents, program, declarations: { ...program, body: [] }, imports: new Map(), resolvedImports: [] };
|
|
33
|
+
for (const node of program.body) {
|
|
34
|
+
if (node.type !== "ImportDeclaration" || node.importKind === "type") {
|
|
35
|
+
module.declarations.body.push(node);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (!source.readModule || node.attributes?.length || node.phase || !node.specifiers.length ||
|
|
39
|
+
!node.specifiers.some(spec => spec.type === "ImportSpecifier" && spec.importKind !== "type")) {
|
|
40
|
+
invalid(file, node, "Use named TypeScript function imports from modules with inert initialization.");
|
|
41
|
+
}
|
|
42
|
+
const resolveAgain = () => resolveTypeScriptImport(file, node.source, dirname(file));
|
|
43
|
+
const dependency = source.readModule(resolveAgain(), resolveAgain);
|
|
44
|
+
const owner = load(dependency.canonical, dependency.source);
|
|
45
|
+
module.resolvedImports.push({ start: node.source.start!, end: node.source.end!, file: owner.file });
|
|
46
|
+
for (const spec of node.specifiers) {
|
|
47
|
+
if (spec.type !== "ImportSpecifier" || spec.imported.type !== "Identifier") {
|
|
48
|
+
invalid(file, spec, "Use a named function import.");
|
|
49
|
+
}
|
|
50
|
+
if (spec.importKind === "type") continue;
|
|
51
|
+
const name = spec.imported.name;
|
|
52
|
+
selectSubject(owner.declarations, owner.file, name, { allowArrowFunctions: true });
|
|
53
|
+
module.imports.set(spec.local.name, { owner, name });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
modules.set(file, module);
|
|
57
|
+
functions.set(module, new Map());
|
|
58
|
+
compiling.set(module, new Set());
|
|
59
|
+
return module;
|
|
60
|
+
} finally { loading.delete(file); }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function link(module: Module, name: string, exported = false): Subject {
|
|
64
|
+
const done = functions.get(module)!;
|
|
65
|
+
const cached = done.get(name);
|
|
66
|
+
if (cached) {
|
|
67
|
+
if (exported) selectSubject(module.declarations, module.file, name, { allowArrowFunctions: true });
|
|
68
|
+
return cached;
|
|
69
|
+
}
|
|
70
|
+
const pending = compiling.get(module)!;
|
|
71
|
+
if (pending.has(name)) invalid(module.file, undefined, "Mutually recursive calls are outside the Lean model.");
|
|
72
|
+
pending.add(name);
|
|
73
|
+
try {
|
|
74
|
+
const fn = selectSubject(module.declarations, module.file, name, { allowArrowFunctions: true, allowLocalFunctions: !exported });
|
|
75
|
+
const code = exported && module === owner && name === source.name ? "impl" : `fn${nextFunction++}`;
|
|
76
|
+
const subject = lowerFunction(module.file, module.program, fn, name, code, (callee: string, at: Node) => {
|
|
77
|
+
const imported = module.imports.get(callee);
|
|
78
|
+
if (imported) return link(imported.owner, imported.name, true);
|
|
79
|
+
if (pending.has(callee)) invalid(module.file, at, "Mutually recursive calls are outside the Lean model.");
|
|
80
|
+
return link(module, callee);
|
|
81
|
+
});
|
|
82
|
+
done.set(name, subject);
|
|
83
|
+
return subject;
|
|
84
|
+
} finally { pending.delete(name); }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const owner = load(source.file, source.source);
|
|
88
|
+
const root = link(owner, source.name, true);
|
|
89
|
+
return {
|
|
90
|
+
root,
|
|
91
|
+
modules,
|
|
92
|
+
resolve(file: string, name: string) {
|
|
93
|
+
if (file === owner.file) return link(owner, name, true);
|
|
94
|
+
if (!source.readModule) invalid(file, undefined, "Linking another export needs a source snapshot.");
|
|
95
|
+
const dependency = source.readModule(file);
|
|
96
|
+
return link(load(dependency.canonical, dependency.source), name, true);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function definitions(roots: readonly Subject[]) {
|
|
102
|
+
const ordered = new Set<Subject>();
|
|
103
|
+
function add(subject: Subject) {
|
|
104
|
+
if (ordered.has(subject)) return;
|
|
105
|
+
for (const callee of subject.callees) add(callee);
|
|
106
|
+
ordered.add(subject);
|
|
107
|
+
}
|
|
108
|
+
for (const root of roots) add(root);
|
|
109
|
+
return [...ordered];
|
|
110
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { parseExpression } from "@babel/parser";
|
|
2
|
+
import type { Node } from "@babel/types";
|
|
3
|
+
import type { ProofConstraint, ProofExpression, ProofPredicate } from "../assistant.ts";
|
|
4
|
+
|
|
5
|
+
const comparisons = { eq: "===", gt: ">", gte: ">=", lt: "<", lte: "<=" } as const;
|
|
6
|
+
const binary = new Set(["+", "-", "*", "/", "%", "&", "<<", "===", "!==", "<", ">", "<=", ">=", "&&", "||"]);
|
|
7
|
+
type Scope = ReadonlyMap<string, string>;
|
|
8
|
+
|
|
9
|
+
/** Render only admitted scalar expressions. Sidecar statements and native proof terms never run in Bun. */
|
|
10
|
+
function operand(expression: ProofExpression, parameters: Scope, locals: Scope): string | undefined {
|
|
11
|
+
function read(node: Node): string | undefined {
|
|
12
|
+
switch (node.type) {
|
|
13
|
+
case "Identifier": return locals.get(node.name) ?? parameters.get(expression.bindings.get(node.name) ?? "");
|
|
14
|
+
case "NumericLiteral": return String(node.value);
|
|
15
|
+
case "BigIntLiteral": return BigInt(node.value).toString() + "n";
|
|
16
|
+
case "BooleanLiteral": return String(node.value);
|
|
17
|
+
case "CallExpression": {
|
|
18
|
+
const method = node.callee;
|
|
19
|
+
if (!expression.numberGlobal || locals.has("Number") || expression.bindings.has("Number") ||
|
|
20
|
+
method.type !== "MemberExpression" || method.computed || method.object.type !== "Identifier" ||
|
|
21
|
+
method.object.name !== "Number" || method.property.type !== "Identifier" ||
|
|
22
|
+
!["isInteger", "isNaN"].includes(method.property.name) || node.arguments.length !== 1) return;
|
|
23
|
+
const arg = read(node.arguments[0]!);
|
|
24
|
+
return arg && "Number." + method.property.name + "(" + arg + ")";
|
|
25
|
+
}
|
|
26
|
+
case "UnaryExpression": {
|
|
27
|
+
const arg = read(node.argument);
|
|
28
|
+
if (arg && ["-", "+", "!"].includes(node.operator)) return "(" + node.operator + arg + ")";
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
case "BinaryExpression":
|
|
32
|
+
case "LogicalExpression": {
|
|
33
|
+
const left = read(node.left), right = read(node.right);
|
|
34
|
+
if (left && right && binary.has(node.operator)) return "(" + left + " " + node.operator + " " + right + ")";
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
case "ConditionalExpression": {
|
|
38
|
+
const test = read(node.test), yes = read(node.consequent), no = read(node.alternate);
|
|
39
|
+
if (test && yes && no) return "(" + test + " ? " + yes + " : " + no + ")";
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return read(parseExpression(expression.source, { plugins: ["typescript"] }));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function predicate(spec: ProofPredicate, parameters: Scope, locals: Scope): string | undefined {
|
|
48
|
+
switch (spec.kind) {
|
|
49
|
+
case "boolean": return operand(spec.expression, parameters, locals);
|
|
50
|
+
case "not": {
|
|
51
|
+
const value = predicate(spec.operand, parameters, locals);
|
|
52
|
+
return value && "!(" + value + ")";
|
|
53
|
+
}
|
|
54
|
+
case "binary": {
|
|
55
|
+
const left = predicate(spec.left, parameters, locals), right = predicate(spec.right, parameters, locals);
|
|
56
|
+
if (!left || !right) return;
|
|
57
|
+
if (spec.operator === "implies") return "(!(" + left + ") || " + right + ")";
|
|
58
|
+
const operator = { iff: "===", and: "&&", or: "||" }[spec.operator];
|
|
59
|
+
return "(" + left + " " + operator + " " + right + ")";
|
|
60
|
+
}
|
|
61
|
+
// A finite sample cannot decide a quantified assertion.
|
|
62
|
+
case "quantifier": return;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** An unavailable premise or assertion disables this replay, so every reported witness is in-domain. */
|
|
67
|
+
export function replayConstraints(constraints: readonly ProofConstraint[], parameters: Scope): string | undefined {
|
|
68
|
+
const clauses: string[] = [];
|
|
69
|
+
const empty: Scope = new Map();
|
|
70
|
+
for (const constraint of constraints) {
|
|
71
|
+
let clause: string | undefined;
|
|
72
|
+
if (constraint.kind === "condition") clause = operand(constraint.expression, parameters, empty);
|
|
73
|
+
else if (constraint.kind === "proposition") clause = predicate(constraint.predicate, parameters, empty);
|
|
74
|
+
else {
|
|
75
|
+
const target = constraint.target.kind === "result" ? "received" :
|
|
76
|
+
constraint.target.kind === "parameter" ? parameters.get(constraint.target.name) : undefined;
|
|
77
|
+
if (!target) return;
|
|
78
|
+
if (constraint.kind === "sameValue") {
|
|
79
|
+
const rhs = operand(constraint.value, parameters, empty);
|
|
80
|
+
if (rhs) clause = `Object.is(${target}, ${rhs})`;
|
|
81
|
+
} else if (constraint.kind === "nearestInteger") {
|
|
82
|
+
const rhs = operand(constraint.value, parameters, empty);
|
|
83
|
+
if (rhs) clause = `Object.is(${target}, nearestInteger(${rhs}, ${constraint.ties === "up"}))`;
|
|
84
|
+
} else if (constraint.kind === "comparison") {
|
|
85
|
+
const rhs = operand(constraint.value, parameters, empty);
|
|
86
|
+
if (rhs) clause = "(" + target + " " + comparisons[constraint.operator] + " " + rhs + ")";
|
|
87
|
+
} else if (constraint.kind === "refinement") {
|
|
88
|
+
clause = predicate(constraint.predicate, parameters, new Map([[constraint.variable, target]]));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (!clause) return;
|
|
92
|
+
clauses.push(clause);
|
|
93
|
+
}
|
|
94
|
+
return clauses.join(" && ") || "true";
|
|
95
|
+
}
|