pud.dev 0.0.1 → 0.0.2
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/LICENSE +21 -0
- package/README.md +53 -27
- package/THIRD-PARTY-NOTICES +112 -0
- package/chunk-224av1ab.js +10 -0
- package/chunk-fstxscck.js +3 -0
- package/chunk-h90k6v7w.js +3 -0
- package/chunk-k7a83qqm.js +3 -0
- package/cli.js +37 -0
- package/index.js +2 -0
- package/lean/index.js +880 -0
- package/package.json +28 -19
- package/project-runner.js +2 -0
- package/types/assistant.d.ts +200 -0
- package/types/check.d.ts +55 -0
- package/types/expressions.d.ts +47 -0
- package/types/input-scope.d.ts +4 -0
- package/types/lean/command.d.ts +14 -0
- package/types/lean/index.d.ts +5 -0
- package/types/lean/number.d.ts +4 -0
- package/types/lean/program.d.ts +26 -0
- package/types/lean/replay-predicate.d.ts +5 -0
- package/types/lean/replay.d.ts +6 -0
- package/types/lean/scalar.d.ts +23 -0
- package/types/lean/subject.d.ts +25 -0
- package/types/lean/syntax.d.ts +42 -0
- package/types/module.d.ts +9 -0
- package/types/prover-process.d.ts +7 -0
- package/types/run.d.ts +30 -0
- package/types/source.d.ts +5 -0
- package/types/suite-authoring.d.ts +117 -0
- package/types/suite-check.d.ts +10 -0
- package/types/suite.d.ts +44 -0
- package/CLAUDE.md +0 -106
- package/scripts/pack.ts +0 -67
- package/scripts/setup-lean.ts +0 -88
- package/src/assistant.ts +0 -131
- package/src/check.ts +0 -173
- package/src/cli.ts +0 -70
- package/src/expressions.ts +0 -65
- package/src/input-scope.ts +0 -71
- package/src/lean/command.ts +0 -40
- package/src/lean/index.ts +0 -437
- package/src/lean/iteration.lean +0 -145
- package/src/lean/lean-assets.d.ts +0 -4
- package/src/lean/number.lean +0 -427
- package/src/lean/number.ts +0 -25
- package/src/lean/program.ts +0 -110
- package/src/lean/replay-predicate.ts +0 -95
- package/src/lean/replay.ts +0 -136
- package/src/lean/scalar.lean +0 -183
- package/src/lean/scalar.ts +0 -196
- package/src/lean/subject.ts +0 -443
- package/src/lean/syntax.ts +0 -287
- package/src/module.ts +0 -110
- package/src/project-runner.ts +0 -26
- package/src/prover-process.ts +0 -16
- package/src/reporter.ts +0 -173
- package/src/run.ts +0 -60
- package/src/source.ts +0 -54
- package/src/suite-authoring.ts +0 -135
- package/src/suite-check.ts +0 -157
- package/src/suite.ts +0 -515
- package/src/terminal-progress.ts +0 -145
- package/src/terminal.ts +0 -41
- package/test/authoring.test.ts +0 -151
- package/test/lean.test.ts +0 -394
- package/test/module.test.ts +0 -55
- package/test/number.test.ts +0 -318
- package/test/package.test.ts +0 -170
- package/test/suite.test.ts +0 -257
- package/tsconfig.json +0 -7
- package/tsconfig.pack.json +0 -12
- /package/{src/index.ts → types/index.d.ts} +0 -0
package/lean/index.js
ADDED
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Unsupported2,parseExpression,invalid,parseSourceModule,resolveTypeScriptImport}from"../chunk-224av1ab.js";import{native2}from"../chunk-k7a83qqm.js";import{existsSync,mkdtempSync,rmSync,writeFileSync as writeFileSync2}from"fs";import{tmpdir}from"os";import{join as join3}from"path";import{execFile}from"child_process";import{promisify}from"util";var exec=promisify(execFile);async function runProver(binary,args,options){try{const{stdout,stderr}=await exec(binary,args,{...options,encoding:"utf8"});return{status:0,stdout,stderr}}catch(error){const failure=error;if(typeof failure.code!=="number"||failure.killed||failure.signal)throw error;return{status:failure.code,stdout:failure.stdout??"",stderr:failure.stderr??""}}}import{readFileSync,statSync}from"fs";import{homedir}from"os";import{dirname,join,resolve}from"path";function ancestors(file){const directories=[];for(let dir=dirname(file);;dir=dirname(dir)){directories.push(dir);if(dirname(dir)===dir)return directories}}function leanCommand(subject,options){const directories=ancestors(subject.file);const executable=process.platform==="win32"?"lean.exe":"lean";const override=options.executable??process.env.PUD_LEAN;const local=[...directories,...ancestors(join(process.cwd(),"pud.config.ts"))].map((dir)=>join(dir,".cache","elan")).find((home)=>Bun.which(join(home,"bin",executable)));const localShim=local&&join(local,"bin",executable);const userShim=join(process.env.ELAN_HOME??join(homedir(),".elan"),"bin",executable);const binary=override?/[/\\]/.test(override)?resolve(override):Bun.which(override)??override:localShim??Bun.which("lean")??Bun.which(userShim)??"lean";const env={...process.env};if(local&&binary===localShim)env.ELAN_HOME=local;let toolchain=options.toolchain??env.ELAN_TOOLCHAIN;if(!toolchain){const pin=directories.map((dir)=>join(dir,"lean-toolchain")).find((file)=>statSync(file,{throwIfNoEntry:false})?.isFile());if(pin)toolchain=(subject.readDependency?subject.readDependency(pin):readFileSync(pin,"utf8")).trim()}if(toolchain)env.ELAN_TOOLCHAIN=toolchain;return{binary,env}}var number_default=`import Std
|
|
3
|
+
|
|
4
|
+
namespace Pud
|
|
5
|
+
|
|
6
|
+
-- The magnitude is the unsigned binary64 encoding with the sign bit removed.
|
|
7
|
+
-- Both zeros are representable. Scalar ECMAScript Number has one observable NaN.
|
|
8
|
+
inductive JSNumber where
|
|
9
|
+
| nan
|
|
10
|
+
| num (negative : Bool) (magnitude : Fin (0x7ff0000000000000 + 1))
|
|
11
|
+
deriving DecidableEq, Repr
|
|
12
|
+
|
|
13
|
+
namespace JSNumber
|
|
14
|
+
|
|
15
|
+
private abbrev infBits : Nat := 0x7ff0000000000000
|
|
16
|
+
private abbrev hiddenBit : Nat := 2^52
|
|
17
|
+
private def pack (negative : Bool) (m : Nat) : JSNumber :=
|
|
18
|
+
.num negative \u27E8min m infBits, Nat.lt_succ_of_le (Nat.min_le_right ..)\u27E9
|
|
19
|
+
|
|
20
|
+
def ofBits (word : Nat) : JSNumber :=
|
|
21
|
+
let m := word % 2^63
|
|
22
|
+
if m > infBits then .nan else pack (word.testBit 63) m
|
|
23
|
+
|
|
24
|
+
def toBits : JSNumber \u2192 Nat
|
|
25
|
+
| .nan => 0x7ff8000000000000
|
|
26
|
+
| .num s m => (if s then 2^63 else 0) + m.val
|
|
27
|
+
|
|
28
|
+
def neg : JSNumber \u2192 JSNumber
|
|
29
|
+
| .nan => .nan
|
|
30
|
+
| .num s m => .num (!s) m
|
|
31
|
+
|
|
32
|
+
def isNaN : JSNumber \u2192 Bool
|
|
33
|
+
| .nan => true
|
|
34
|
+
| .num .. => false
|
|
35
|
+
|
|
36
|
+
def isZero : JSNumber \u2192 Bool
|
|
37
|
+
| .nan => false
|
|
38
|
+
| .num _ m => m.val == 0
|
|
39
|
+
|
|
40
|
+
def eq (a b : JSNumber) : Bool :=
|
|
41
|
+
if b.isNaN then false else if b.isZero then a.isZero else decide (a = b)
|
|
42
|
+
|
|
43
|
+
def truthy (x : JSNumber) : Bool := !(x.isNaN || x.isZero)
|
|
44
|
+
|
|
45
|
+
-- The magnitude bits increase with absolute value. This signed key is used only for ordering.
|
|
46
|
+
private def orderKey (negative : Bool) (m : Nat) : Int := if negative then -Int.ofNat m else Int.ofNat m
|
|
47
|
+
|
|
48
|
+
def lt : JSNumber \u2192 JSNumber \u2192 Bool
|
|
49
|
+
| .num s m, .num t n => decide (orderKey s m.val < orderKey t n.val)
|
|
50
|
+
| _, _ => false
|
|
51
|
+
|
|
52
|
+
def le : JSNumber \u2192 JSNumber \u2192 Bool
|
|
53
|
+
| .num s m, .num t n => decide (orderKey s m.val \u2264 orderKey t n.val)
|
|
54
|
+
| _, _ => false
|
|
55
|
+
|
|
56
|
+
-- A finite input has exact absolute value significand(m) * 2^scale(m).
|
|
57
|
+
private def significand (m : Nat) := if m < hiddenBit then m else hiddenBit + m % hiddenBit
|
|
58
|
+
private def scale (m : Nat) : Int := Int.ofNat (max 1 (m / hiddenBit)) - 1075
|
|
59
|
+
|
|
60
|
+
private def roundEven (n d : Nat) : Nat :=
|
|
61
|
+
let q := n / d
|
|
62
|
+
let twice := 2 * (n % d)
|
|
63
|
+
if twice > d || (twice == d && q % 2 == 1) then q + 1 else q
|
|
64
|
+
|
|
65
|
+
-- Exact arithmetic on two binary64 operands uses fewer than 2,100 significant bits.
|
|
66
|
+
-- Binary search keeps these closed calculations reducible in the Lean kernel.
|
|
67
|
+
private def bitLog (n : Nat) : Nat :=
|
|
68
|
+
if n >>> 4096 != 0 then n.log2 else
|
|
69
|
+
[2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1].foldl
|
|
70
|
+
(fun k step => if n >>> (k + step) != 0 then k + step else k) 0
|
|
71
|
+
|
|
72
|
+
-- floor(log2(n/d)), where n and d are positive.
|
|
73
|
+
private def logRatio (n d : Nat) : Int :=
|
|
74
|
+
let k := Int.ofNat (bitLog n) - Int.ofNat (bitLog d)
|
|
75
|
+
if (n <<< (-k).toNat) < (d <<< k.toNat) then k - 1 else k
|
|
76
|
+
|
|
77
|
+
-- Round the exact nonnegative rational (n/d) * 2^k to the nearest binary64.
|
|
78
|
+
-- The smallest unit is one subnormal. A carry at the top exponent yields infinity.
|
|
79
|
+
private def roundedMagnitude (n d : Nat) (k : Int) : Nat :=
|
|
80
|
+
if n = 0 then 0 else
|
|
81
|
+
let unit := max (-1074) (logRatio n d + k - 52)
|
|
82
|
+
let shift := k - unit
|
|
83
|
+
let q := roundEven (n <<< shift.toNat) (d <<< (-shift).toNat)
|
|
84
|
+
if q < hiddenBit then q else
|
|
85
|
+
let carry := q == 2 * hiddenBit
|
|
86
|
+
let exponent := (unit + 1075).toNat + (if carry then 1 else 0)
|
|
87
|
+
let fraction := if carry then 0 else q - hiddenBit
|
|
88
|
+
exponent * hiddenBit + fraction
|
|
89
|
+
|
|
90
|
+
private def fromRatio (s : Bool) (n d : Nat) (k : Int) := pack s (roundedMagnitude n d k)
|
|
91
|
+
|
|
92
|
+
def mul : JSNumber \u2192 JSNumber \u2192 JSNumber
|
|
93
|
+
| .num s a, .num t b =>
|
|
94
|
+
let sign := xor s t
|
|
95
|
+
if a.val == infBits || b.val == infBits then
|
|
96
|
+
if a.val == 0 || b.val == 0 then .nan else pack sign infBits
|
|
97
|
+
else fromRatio sign (significand a * significand b) 1 (scale a + scale b)
|
|
98
|
+
| _, _ => .nan
|
|
99
|
+
|
|
100
|
+
def div : JSNumber \u2192 JSNumber \u2192 JSNumber
|
|
101
|
+
| .num s a, .num t b =>
|
|
102
|
+
let sign := xor s t
|
|
103
|
+
if (a.val == 0 && b.val == 0) || (a.val == infBits && b.val == infBits) then .nan
|
|
104
|
+
else if a.val == infBits || b.val == 0 then pack sign infBits
|
|
105
|
+
else if b.val == infBits then pack sign 0
|
|
106
|
+
else fromRatio sign (significand a) (significand b) (scale a - scale b)
|
|
107
|
+
| _, _ => .nan
|
|
108
|
+
|
|
109
|
+
def add : JSNumber \u2192 JSNumber \u2192 JSNumber
|
|
110
|
+
| .num s a, .num t b =>
|
|
111
|
+
if a.val == infBits then
|
|
112
|
+
if b.val == infBits && s != t then .nan else .num s a
|
|
113
|
+
else if b.val == infBits then .num t b
|
|
114
|
+
else
|
|
115
|
+
let k := min (scale a) (scale b)
|
|
116
|
+
let x := significand a <<< (scale a - k).toNat
|
|
117
|
+
let y := significand b <<< (scale b - k).toNat
|
|
118
|
+
let sum := orderKey s x + orderKey t y
|
|
119
|
+
fromRatio (decide (sum < 0) || (sum == 0 && s && t)) sum.natAbs 1 k
|
|
120
|
+
| _, _ => .nan
|
|
121
|
+
|
|
122
|
+
def sub (a b : JSNumber) := add a (neg b)
|
|
123
|
+
|
|
124
|
+
private inductive IntegralMode where | nearest | down | up | towardZero
|
|
125
|
+
|
|
126
|
+
private abbrev oneBits : Nat := 0x3ff0000000000000
|
|
127
|
+
private abbrev halfBits : Nat := 0x3fe0000000000000
|
|
128
|
+
|
|
129
|
+
private def roundUp (mode : IntegralMode) (negative : Bool) (remainder unit : Nat) : Bool :=
|
|
130
|
+
match mode with
|
|
131
|
+
| .nearest => 2 * remainder > unit || (2 * remainder == unit && !negative)
|
|
132
|
+
| .down => negative && remainder != 0
|
|
133
|
+
| .up => !negative && remainder != 0
|
|
134
|
+
| .towardZero => false
|
|
135
|
+
|
|
136
|
+
private def roundIntegral (mode : IntegralMode) : JSNumber \u2192 JSNumber
|
|
137
|
+
| .nan => .nan
|
|
138
|
+
| .num s m =>
|
|
139
|
+
if m.val < oneBits then
|
|
140
|
+
let up := match mode with
|
|
141
|
+
| .nearest => m.val > halfBits || (m.val == halfBits && !s)
|
|
142
|
+
| .down => s && m.val != 0
|
|
143
|
+
| .up => !s && m.val != 0
|
|
144
|
+
| .towardZero => false
|
|
145
|
+
pack s (if up then oneBits else 0)
|
|
146
|
+
else
|
|
147
|
+
let exponent := m.val / hiddenBit
|
|
148
|
+
if exponent \u2265 1075 then .num s m else
|
|
149
|
+
-- Between 1 and 2^52 the low (1075 - exponent) bits encode the fraction.
|
|
150
|
+
-- oneBits is aligned to every such unit. A carry crosses exponents naturally.
|
|
151
|
+
let unit := 2 ^ (1075 - exponent)
|
|
152
|
+
let offset := m.val - oneBits
|
|
153
|
+
let base := oneBits + offset / unit * unit
|
|
154
|
+
pack s (base + if roundUp mode s (offset % unit) unit then unit else 0)
|
|
155
|
+
|
|
156
|
+
-- Number.isInteger describes the represented value, including integers beyond the safe range.
|
|
157
|
+
def isInteger : JSNumber \u2192 Bool
|
|
158
|
+
| .nan => false
|
|
159
|
+
| .num _ m =>
|
|
160
|
+
if m.val < oneBits then m.val == 0 else
|
|
161
|
+
let exponent := m.val / hiddenBit
|
|
162
|
+
m.val != infBits && (exponent \u2265 1075 || (m.val - oneBits) % (2 ^ (1075 - exponent)) == 0)
|
|
163
|
+
|
|
164
|
+
-- Math.round resolves half ties toward positive infinity and preserves a negative zero.
|
|
165
|
+
def round := roundIntegral .nearest
|
|
166
|
+
def floor := roundIntegral .down
|
|
167
|
+
def ceil := roundIntegral .up
|
|
168
|
+
def trunc := roundIntegral .towardZero
|
|
169
|
+
|
|
170
|
+
-- Compare the fractional magnitude to its midpoint. When the sign is negative,
|
|
171
|
+
-- the integer of smaller magnitude is the upper endpoint on the number line.
|
|
172
|
+
private def lowerIsNearer (negative : Bool) (a b : Nat) : Bool :=
|
|
173
|
+
if negative then decide (b < a) else decide (a < b)
|
|
174
|
+
|
|
175
|
+
-- For a fractional Number, floor and ceil are the two adjacent integers.
|
|
176
|
+
-- Below unit magnitude the ordering of the magnitude bits locates the half.
|
|
177
|
+
-- Above it, compare exact distances in representable steps in this exponent bin.
|
|
178
|
+
-- Both endpoints coincide on integers, signed zeros, infinities and NaN.
|
|
179
|
+
private def nearestTiesUp (x : JSNumber) : JSNumber :=
|
|
180
|
+
match x with
|
|
181
|
+
| .nan => .nan
|
|
182
|
+
| .num s m =>
|
|
183
|
+
let lower := if m.val < oneBits then lowerIsNearer s m.val halfBits else
|
|
184
|
+
let unit := 2 ^ (1075 - m.val / hiddenBit)
|
|
185
|
+
let remainder := (m.val - oneBits) % unit
|
|
186
|
+
lowerIsNearer s remainder (unit - remainder)
|
|
187
|
+
if lower then floor x else ceil x
|
|
188
|
+
|
|
189
|
+
private theorem nearest_step (s : Bool) (r u : Nat) (hr : r < u) :
|
|
190
|
+
(if lowerIsNearer s r (u - r) then roundUp .down s r u else roundUp .up s r u) =
|
|
191
|
+
roundUp .nearest s r u := by
|
|
192
|
+
have below : r < u - r \u2194 2 * r < u := by omega
|
|
193
|
+
have above : u - r < r \u2194 u < 2 * r := by omega
|
|
194
|
+
rcases Nat.lt_trichotomy (2 * r) u with low | tie | high <;> by_cases z : r = 0 <;>
|
|
195
|
+
cases s <;> simp (disch := omega) [lowerIsNearer, roundUp, below, above, *, bne_iff_ne] <;>
|
|
196
|
+
(try simp_all) <;> omega
|
|
197
|
+
|
|
198
|
+
private theorem nearestTiesUp_round (x : JSNumber) : nearestTiesUp x = round x := by
|
|
199
|
+
cases x with
|
|
200
|
+
| nan => rfl
|
|
201
|
+
| num s m =>
|
|
202
|
+
unfold nearestTiesUp
|
|
203
|
+
dsimp only
|
|
204
|
+
by_cases small : m.val < oneBits
|
|
205
|
+
\xB7 simp only [small, \u2193reduceIte, floor, ceil, round, roundIntegral]
|
|
206
|
+
by_cases z : m.val = 0 <;> by_cases tie : m.val = halfBits <;> by_cases above : halfBits < m.val <;>
|
|
207
|
+
cases s <;> simp [lowerIsNearer, *, halfBits] at * <;> (repeat' split) <;> (try simp_all) <;> omega
|
|
208
|
+
\xB7 simp only [small, Bool.false_eq_true, \u2193reduceIte, floor, ceil, round, roundIntegral]
|
|
209
|
+
by_cases large : m.val / hiddenBit \u2265 1075
|
|
210
|
+
\xB7 simp [large]
|
|
211
|
+
\xB7 simp only [large, \u2193reduceIte]
|
|
212
|
+
let u := 2 ^ (1075 - m.val / hiddenBit)
|
|
213
|
+
let r := (m.val - oneBits) % u
|
|
214
|
+
have hr : r < u := Nat.mod_lt _ (Nat.pow_pos (by decide))
|
|
215
|
+
have step := nearest_step s r u hr
|
|
216
|
+
by_cases lower : lowerIsNearer s r (u - r) = true <;>
|
|
217
|
+
simp [lower] at step <;>
|
|
218
|
+
simp only [u, r] at lower step <;> simp [lower, step]
|
|
219
|
+
|
|
220
|
+
-- Reflection exchanges upper and lower ties and preserves the sign of a zero result.
|
|
221
|
+
def nearestInteger (x : JSNumber) (tiesUp : Bool) : JSNumber :=
|
|
222
|
+
if tiesUp then nearestTiesUp x else neg (nearestTiesUp (neg x))
|
|
223
|
+
|
|
224
|
+
theorem nearestInteger_round (x : JSNumber) : nearestInteger x true = round x :=
|
|
225
|
+
nearestTiesUp_round x
|
|
226
|
+
|
|
227
|
+
theorem nearestInteger_round_down (x : JSNumber) : nearestInteger x false = neg (round (neg x)) :=
|
|
228
|
+
congrArg neg (nearestTiesUp_round (neg x))
|
|
229
|
+
|
|
230
|
+
-- A strict-equality premise fixes the input bits for every nonzero, non-NaN literal.
|
|
231
|
+
theorem eq_regular {a b : JSNumber} (hn : b.isNaN = false) (hz : b.isZero = false) :
|
|
232
|
+
eq a b = true \u2194 a = b := by simp [eq, hn, hz]
|
|
233
|
+
|
|
234
|
+
private theorem nonnegative_pack (m : Nat) : le (ofBits 0) (pack false m) = true := by
|
|
235
|
+
change decide ((0 : Int) \u2264 Int.ofNat (min m infBits)) = true
|
|
236
|
+
simp
|
|
237
|
+
|
|
238
|
+
private theorem nonnegative_ratio (n d : Nat) (k : Int) : le (ofBits 0) (fromRatio false n d k) = true := by
|
|
239
|
+
exact nonnegative_pack _
|
|
240
|
+
|
|
241
|
+
theorem nonnegative_round {x : JSNumber} (hx : le (ofBits 0) x = true) :
|
|
242
|
+
le (ofBits 0) (round x) = true := by
|
|
243
|
+
cases x with
|
|
244
|
+
| nan => contradiction
|
|
245
|
+
| num s m =>
|
|
246
|
+
cases s
|
|
247
|
+
case false =>
|
|
248
|
+
simp only [round, roundIntegral]
|
|
249
|
+
split
|
|
250
|
+
\xB7 apply nonnegative_pack
|
|
251
|
+
\xB7 split
|
|
252
|
+
\xB7 exact hx
|
|
253
|
+
\xB7 apply nonnegative_pack
|
|
254
|
+
case true =>
|
|
255
|
+
change decide ((0 : Int) \u2264 -(m.val : Int)) = true at hx
|
|
256
|
+
simp only [decide_eq_true_eq] at hx
|
|
257
|
+
have hm : m.val = 0 := by omega
|
|
258
|
+
have zero : m = \u27E80, by decide\u27E9 := Fin.ext hm
|
|
259
|
+
subst m; decide
|
|
260
|
+
|
|
261
|
+
-- Scaling a nonnegative Number by a strictly positive, finite constant preserves its sign,
|
|
262
|
+
-- including -0 and overflow to +Infinity.
|
|
263
|
+
theorem nonnegative_mul {x c : JSNumber} (hc : lt (ofBits 0) c = true) (hf : lt c (ofBits infBits) = true)
|
|
264
|
+
(hx : le (ofBits 0) x = true) : le (ofBits 0) (mul x c) = true := by
|
|
265
|
+
cases c with
|
|
266
|
+
| nan => change false = true at hc; cases hc
|
|
267
|
+
| num t b =>
|
|
268
|
+
cases t
|
|
269
|
+
case true =>
|
|
270
|
+
change decide ((0 : Int) < -(b.val : Int)) = true at hc
|
|
271
|
+
simp only [decide_eq_true_eq] at hc
|
|
272
|
+
omega
|
|
273
|
+
case false =>
|
|
274
|
+
change decide ((0 : Int) < (b.val : Int)) = true at hc
|
|
275
|
+
change decide ((b.val : Int) < (infBits : Int)) = true at hf
|
|
276
|
+
simp only [decide_eq_true_eq] at hc hf
|
|
277
|
+
have hb : b.val \u2260 0 := by omega
|
|
278
|
+
have hi : b.val \u2260 infBits := by omega
|
|
279
|
+
cases x with
|
|
280
|
+
| nan => change false = true at hx; cases hx
|
|
281
|
+
| num s a =>
|
|
282
|
+
cases s
|
|
283
|
+
case false =>
|
|
284
|
+
by_cases h : a.val = infBits
|
|
285
|
+
\xB7 simp [mul, h, hb, nonnegative_pack]
|
|
286
|
+
\xB7 simp [mul, h, hi, nonnegative_ratio]
|
|
287
|
+
case true =>
|
|
288
|
+
change decide ((0 : Int) \u2264 -(a.val : Int)) = true at hx
|
|
289
|
+
simp only [decide_eq_true_eq] at hx
|
|
290
|
+
have ha : a.val = 0 := by omega
|
|
291
|
+
simp [mul, ha, hi, significand, fromRatio, roundedMagnitude]
|
|
292
|
+
decide
|
|
293
|
+
|
|
294
|
+
-- These rewrites operate on arbitrary operands. Structural equality includes NaN and signed zero.
|
|
295
|
+
theorem mul_comm (x y : JSNumber) : mul x y = mul y x := by
|
|
296
|
+
cases x <;> cases y <;> first | rfl | simp only [mul, Bool.xor_comm, Bool.or_comm, Nat.mul_comm, Int.add_comm]
|
|
297
|
+
|
|
298
|
+
theorem mul_neg (x y : JSNumber) : mul (neg x) y = neg (mul x y) := by
|
|
299
|
+
cases x with
|
|
300
|
+
| nan => rfl
|
|
301
|
+
| num s a =>
|
|
302
|
+
cases y with
|
|
303
|
+
| nan => rfl
|
|
304
|
+
| num t b => cases s <;> cases t <;> simp only [neg, mul] <;> repeat' first | rfl | split
|
|
305
|
+
|
|
306
|
+
theorem div_neg (x y : JSNumber) : div (neg x) y = neg (div x y) := by
|
|
307
|
+
cases x with
|
|
308
|
+
| nan => rfl
|
|
309
|
+
| num s a =>
|
|
310
|
+
cases y with
|
|
311
|
+
| nan => rfl
|
|
312
|
+
| num t b => cases s <;> cases t <;> simp only [neg, div] <;> repeat' first | rfl | split
|
|
313
|
+
|
|
314
|
+
theorem eq_self (x : JSNumber) : eq x x = !x.isNaN := by cases x <;> simp [eq, isNaN]
|
|
315
|
+
|
|
316
|
+
theorem isNaN_neg (x : JSNumber) : isNaN (neg x) = isNaN x := by cases x <;> rfl
|
|
317
|
+
|
|
318
|
+
def finiteNonzero : JSNumber \u2192 Bool
|
|
319
|
+
| .nan => false
|
|
320
|
+
| .num _ m => m.val != 0 && m.val != infBits
|
|
321
|
+
|
|
322
|
+
theorem isNaN_mul_right (x c : JSNumber) (hc : finiteNonzero c = true) : isNaN (mul x c) = isNaN x := by
|
|
323
|
+
cases c with
|
|
324
|
+
| nan => contradiction
|
|
325
|
+
| num t b =>
|
|
326
|
+
simp [finiteNonzero] at hc
|
|
327
|
+
cases x with
|
|
328
|
+
| nan => rfl
|
|
329
|
+
| num s a => by_cases h : a.val = infBits <;> simp [mul, hc.1, hc.2, h, isNaN, fromRatio, pack]
|
|
330
|
+
|
|
331
|
+
theorem isNaN_mul_left (c x : JSNumber) (hc : finiteNonzero c = true) : isNaN (mul c x) = isNaN x := by
|
|
332
|
+
rw [mul_comm, isNaN_mul_right x c hc]
|
|
333
|
+
|
|
334
|
+
theorem isNaN_div_right (x c : JSNumber) (hc : finiteNonzero c = true) : isNaN (div x c) = isNaN x := by
|
|
335
|
+
cases c with
|
|
336
|
+
| nan => contradiction
|
|
337
|
+
| num t b =>
|
|
338
|
+
simp [finiteNonzero] at hc
|
|
339
|
+
cases x with
|
|
340
|
+
| nan => rfl
|
|
341
|
+
| num s a => by_cases h : a.val = infBits <;> simp [div, hc.1, hc.2, h, isNaN, fromRatio, pack]
|
|
342
|
+
|
|
343
|
+
private theorem integral_fixed (mode : IntegralMode) {x : JSNumber} (hx : isInteger x = true) : eq (roundIntegral mode x) x = true := by
|
|
344
|
+
cases x with
|
|
345
|
+
| nan => contradiction
|
|
346
|
+
| num s m =>
|
|
347
|
+
suffices fixed : roundIntegral mode (.num s m) = .num s m by rw [fixed, eq_self]; rfl
|
|
348
|
+
by_cases small : m.val < oneBits
|
|
349
|
+
\xB7 change (if m.val < oneBits then m.val == 0 else _) = true at hx
|
|
350
|
+
have zero : m = \u27E80, by decide\u27E9 := Fin.ext (by simpa [small] using hx)
|
|
351
|
+
subst m
|
|
352
|
+
cases mode <;> cases s <;> decide
|
|
353
|
+
\xB7 by_cases large : m.val / hiddenBit \u2265 1075
|
|
354
|
+
\xB7 simp [round, roundIntegral, small, large]
|
|
355
|
+
\xB7 have aligned : (m.val - oneBits) % (2 ^ (1075 - m.val / hiddenBit)) = 0 := by
|
|
356
|
+
simp [isInteger, small, large] at hx
|
|
357
|
+
exact hx.2
|
|
358
|
+
have restored := Nat.div_add_mod (m.val - oneBits) (2 ^ (1075 - m.val / hiddenBit))
|
|
359
|
+
rw [aligned, Nat.add_zero, Nat.mul_comm] at restored
|
|
360
|
+
have unit : (0 : Nat) \u2260 2 ^ (1075 - m.val / hiddenBit) := Nat.ne_of_lt (Nat.pow_pos (by decide))
|
|
361
|
+
cases mode <;> simp [roundIntegral, small, large, roundUp, aligned, restored, pack, unit,
|
|
362
|
+
Nat.add_sub_of_le (Nat.le_of_not_gt small), Nat.min_eq_left (Nat.le_of_lt_succ m.isLt)]
|
|
363
|
+
|
|
364
|
+
theorem round_integer {x : JSNumber} (h : isInteger x = true) : eq (round x) x = true := integral_fixed .nearest h
|
|
365
|
+
theorem floor_integer {x : JSNumber} (h : isInteger x = true) : eq (floor x) x = true := integral_fixed .down h
|
|
366
|
+
theorem ceil_integer {x : JSNumber} (h : isInteger x = true) : eq (ceil x) x = true := integral_fixed .up h
|
|
367
|
+
theorem trunc_integer {x : JSNumber} (h : isInteger x = true) : eq (trunc x) x = true := integral_fixed .towardZero h
|
|
368
|
+
|
|
369
|
+
-- JavaScript comparison sees -0 as zero; its reciprocal exposes the sign after underflow.
|
|
370
|
+
private theorem negative_or_reciprocal (m : Fin (infBits + 1)) :
|
|
371
|
+
lt (.num true m) (ofBits 0) = true \u2228 lt (div (ofBits oneBits) (.num true m)) (ofBits 0) = true := by
|
|
372
|
+
by_cases h : m.val = 0
|
|
373
|
+
\xB7 have hm : m = \u27E80, by decide\u27E9 := Fin.ext h
|
|
374
|
+
subst m
|
|
375
|
+
right; decide
|
|
376
|
+
\xB7 left
|
|
377
|
+
change decide (-(m.val : Int) < 0) = true
|
|
378
|
+
simp only [decide_eq_true_eq]
|
|
379
|
+
omega
|
|
380
|
+
|
|
381
|
+
theorem negative_div {x c : JSNumber} (hc : finiteNonzero c = true) (hp : lt (ofBits 0) c = true)
|
|
382
|
+
(hx : lt x (ofBits 0) = true) :
|
|
383
|
+
lt (div x c) (ofBits 0) = true \u2228 lt (div (ofBits oneBits) (div x c)) (ofBits 0) = true := by
|
|
384
|
+
cases c with
|
|
385
|
+
| nan => contradiction
|
|
386
|
+
| num t b =>
|
|
387
|
+
cases t
|
|
388
|
+
case true =>
|
|
389
|
+
change decide ((0 : Int) < -(b.val : Int)) = true at hp
|
|
390
|
+
simp only [decide_eq_true_eq] at hp
|
|
391
|
+
omega
|
|
392
|
+
case false =>
|
|
393
|
+
simp [finiteNonzero] at hc
|
|
394
|
+
cases x with
|
|
395
|
+
| nan => contradiction
|
|
396
|
+
| num s a =>
|
|
397
|
+
cases s
|
|
398
|
+
case false =>
|
|
399
|
+
change decide ((a.val : Int) < 0) = true at hx
|
|
400
|
+
simp only [decide_eq_true_eq] at hx
|
|
401
|
+
omega
|
|
402
|
+
case true =>
|
|
403
|
+
have result : \u2203 m, div (.num true a) (.num false b) = .num true m := by
|
|
404
|
+
by_cases h : a.val = infBits <;>
|
|
405
|
+
simp [div, h, hc.1, hc.2, fromRatio, pack]
|
|
406
|
+
obtain \u27E8m, hm\u27E9 := result
|
|
407
|
+
rw [hm]
|
|
408
|
+
exact negative_or_reciprocal m
|
|
409
|
+
|
|
410
|
+
private theorem integral_nonzero (s : Bool) (a b : Nat) : isZero (pack s (oneBits + a + b)) = false := by
|
|
411
|
+
change (min (oneBits + a + b) infBits == 0) = false
|
|
412
|
+
simp [Nat.min_def, oneBits, infBits]
|
|
413
|
+
split <;> omega
|
|
414
|
+
|
|
415
|
+
-- Math.round's zero cell is closed at -0.5 and open at +0.5, including both input zeros.
|
|
416
|
+
theorem round_eq_zero (x : JSNumber) :
|
|
417
|
+
eq (round x) (ofBits 0) = true \u2194
|
|
418
|
+
le (neg (ofBits halfBits)) x = true \u2227 lt x (ofBits halfBits) = true := by
|
|
419
|
+
cases x with
|
|
420
|
+
| nan => decide
|
|
421
|
+
| num s m =>
|
|
422
|
+
change isZero (roundIntegral .nearest (.num s m)) = true \u2194
|
|
423
|
+
decide (-(halfBits : Int) \u2264 orderKey s m.val) = true \u2227 decide (orderKey s m.val < (halfBits : Int)) = true
|
|
424
|
+
cases s <;> simp only [roundIntegral, orderKey, Bool.false_eq_true, \u2193reduceIte, decide_eq_true_eq] <;>
|
|
425
|
+
split <;> (repeat' split) <;> (try simp only [integral_nonzero]) <;> simp_all [pack, isZero, halfBits, oneBits, infBits] <;> omega
|
|
426
|
+
|
|
427
|
+
end JSNumber
|
|
428
|
+
end Pud
|
|
429
|
+
`;var numberSemantics=number_default.replace(/^import Std\s*/,"").trimEnd();function numberLiteral(value){const bytes=new DataView(new ArrayBuffer(8));bytes.setFloat64(0,value);return{sort:"number",code:`(JSNumber.ofBits 0x${bytes.getBigUint64(0).toString(16)})`}}var arithmetic={"+":"add","-":"sub","*":"mul","/":"div"};var comparisons={"===":"eq","!==":"eq","<":"lt","<=":"le",">":"lt",">=":"le"};function numberBinary(op,lhs,rhs){if(Object.hasOwn(arithmetic,op)){return{sort:"number",code:`(JSNumber.${arithmetic[op]} ${lhs} ${rhs})`}}if(Object.hasOwn(comparisons,op)){const args=op===">"||op===">="?`${rhs} ${lhs}`:`${lhs} ${rhs}`;const comparison=`(JSNumber.${comparisons[op]} ${args})`;return{sort:"boolean",code:op==="!=="?`(!${comparison})`:comparison}}}var bmpIdentifierStart=/[\p{ID_Start}\u0558\u058b\u058c\u088f\u0c5c\u0cdc\u208f\u209d-\u209f\ua7ce\ua7cf\ua7d2\ua7d4\ua7dd\ua7e2\ua7f1\uab6c\uab6d]/u;var bmpIdentifier=/[\p{ID_Continue}\u0558\u058b\u058c\u088f\u0c5c\u0cdc\u208f\u209d-\u209f\ua7ce\ua7cf\ua7d2\ua7d4\ua7dd\ua7e2\ua7f1\uab6c\uab6d\u05c8\u05c9\u0b53\u0b54\u1acf-\u1af0]/u;var supplementaryIdentifierStartCodes=[1979,4,385,25,1388,2,18,21,3100,0,678,43,22,0,1662,0,6,10,209,310,18458,24,3,24,287,4,6146,7,1239,4,47,23,96,114,14,913,15,50,8017,5,64,0,9534,0,2169,5,7,86,15,6,55,50,1729,30,2,2,2,1,2,6,3,4,10,1,53307,5,223,0,5764,11,21763,4297,39815,11327];var supplementaryIdentifierCodes=[3787,4,33,11,3173,7,633,9,7,0,45879,1,296,2,9,1,3,0,33,1,5218,0,3,0,8,1,6,0];function isInSupplementarySet(code,set){let pos=65536;for(let i=0,length=set.length;i<length;i+=2){pos+=set[i];if(pos>code)return false;pos+=set[i+1];if(pos>=code)return true}return false}function isIdentifierStart(code){if(code<65)return code===36;if(code<=90)return true;if(code<97)return code===95;if(code<=122)return true;if(code<=65535){return code>=170&&bmpIdentifierStart.test(String.fromCharCode(code))}return!isNaN(code)&&code<=1114111&&(bmpIdentifierStart.test(String.fromCodePoint(code))||isInSupplementarySet(code,supplementaryIdentifierStartCodes))}function isIdentifierChar(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<=90)return true;if(code<97)return code===95;if(code<=122)return true;if(code<=65535){return code>=170&&bmpIdentifier.test(String.fromCharCode(code))}return!isNaN(code)&&code<=1114111&&(bmpIdentifier.test(String.fromCodePoint(code))||isInSupplementarySet(code,supplementaryIdentifierStartCodes)||isInSupplementarySet(code,supplementaryIdentifierCodes))}function isIdentifierName(name){let isFirst=true;for(let i=0;i<name.length;i++){let cp=name.charCodeAt(i);if((cp&64512)===55296&&i+1<name.length){const trail=name.charCodeAt(++i);if((trail&64512)===56320){cp=65536+((cp&1023)<<10)+(trail&1023)}}if(isFirst){isFirst=false;if(!isIdentifierStart(cp)){return false}}else if(!isIdentifierChar(cp)){return false}}return!isFirst}var reservedWords={keyword:["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"],strict:["implements","interface","let","package","private","protected","public","static","yield"],strictBind:["eval","arguments"]};var keywords=new Set(reservedWords.keyword);var reservedWordsStrictSet=new Set(reservedWords.strict);var reservedWordsStrictBindSet=new Set(reservedWords.strictBind);function isReservedWord(word,inModule){return inModule&&word==="await"||word==="enum"}function isStrictReservedWord(word,inModule){return isReservedWord(word,inModule)||reservedWordsStrictSet.has(word)}function isKeyword(word){return keywords.has(word)}var _isDigit=function isDigit(code){return code>=48&&code<=57};var forbiddenNumericSeparatorSiblings={decBinOct:new Set([46,66,69,79,95,98,101,111,43,45]),hex:new Set([46,88,95,120])};var isAllowedNumericSeparatorSibling={bin:(ch)=>ch===48||ch===49,oct:(ch)=>ch>=48&&ch<=55,dec:(ch)=>ch>=48&&ch<=57,hex:(ch)=>ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102};function readStringContents(type,input,pos,lineStart,curLine,errors){const initialPos=pos;const initialLineStart=lineStart;const initialCurLine=curLine;let out="";let firstInvalidLoc=null;let chunkStart=pos;const{length}=input;for(;;){if(pos>=length){errors.unterminated(initialPos,initialLineStart,initialCurLine);out+=input.slice(chunkStart,pos);break}const ch=input.charCodeAt(pos);if(isStringEnd(type,ch,input,pos)){out+=input.slice(chunkStart,pos);break}if(ch===92){out+=input.slice(chunkStart,pos);const res=readEscapedChar(input,pos,lineStart,curLine,type==="template",errors);if(res.ch===null&&!firstInvalidLoc){firstInvalidLoc={pos,lineStart,curLine}}else{out+=res.ch}({pos,lineStart,curLine}=res);chunkStart=pos}else if(ch===8232||ch===8233){++pos;++curLine;lineStart=pos}else if(ch===10||ch===13){if(type==="template"){out+=input.slice(chunkStart,pos)+`
|
|
430
|
+
`;++pos;if(ch===13&&input.charCodeAt(pos)===10){++pos}++curLine;chunkStart=lineStart=pos}else{errors.unterminated(initialPos,initialLineStart,initialCurLine)}}else{++pos}}return{pos,str:out,firstInvalidLoc,lineStart,curLine}}function isStringEnd(type,ch,input,pos){if(type==="template"){return ch===96||ch===36&&input.charCodeAt(pos+1)===123}return ch===(type==="double"?34:39)}function readEscapedChar(input,pos,lineStart,curLine,inTemplate,errors){const throwOnInvalid=!inTemplate;pos++;const res=(ch)=>({pos,ch,lineStart,curLine});const ch=input.charCodeAt(pos++);switch(ch){case 110:return res(`
|
|
431
|
+
`);case 114:return res("\r");case 120:{let code;({code,pos}=readHexChar(input,pos,lineStart,curLine,2,false,throwOnInvalid,errors));return res(code===null?null:String.fromCharCode(code))}case 117:{let code;({code,pos}=readCodePoint(input,pos,lineStart,curLine,throwOnInvalid,errors));return res(code===null?null:String.fromCodePoint(code))}case 116:return res("\t");case 98:return res("\b");case 118:return res("\v");case 102:return res("\f");case 13:if(input.charCodeAt(pos)===10){++pos}case 10:lineStart=pos;++curLine;case 8232:case 8233:return res("");case 56:case 57:if(inTemplate){return res(null)}else{errors.strictNumericEscape(pos-1,lineStart,curLine)}default:if(ch>=48&&ch<=55){const startPos=pos-1;const match=/^[0-7]+/.exec(input.slice(startPos,pos+2));let octalStr=match[0];let octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}pos+=octalStr.length-1;const next=input.charCodeAt(pos);if(octalStr!=="0"||next===56||next===57){if(inTemplate){return res(null)}else{errors.strictNumericEscape(startPos,lineStart,curLine)}}return res(String.fromCharCode(octal))}return res(String.fromCharCode(ch))}}function readHexChar(input,pos,lineStart,curLine,len,forceLen,throwOnInvalid,errors){const initialPos=pos;let n;({n,pos}=readInt(input,pos,lineStart,curLine,16,len,forceLen,false,errors,!throwOnInvalid));if(n===null){if(throwOnInvalid){errors.invalidEscapeSequence(initialPos,lineStart,curLine)}else{pos=initialPos-1}}return{code:n,pos}}function readInt(input,pos,lineStart,curLine,radix,len,forceLen,allowNumSeparator,errors,bailOnError){const start=pos;const forbiddenSiblings=radix===16?forbiddenNumericSeparatorSiblings.hex:forbiddenNumericSeparatorSiblings.decBinOct;const isAllowedSibling=radix===16?isAllowedNumericSeparatorSibling.hex:radix===10?isAllowedNumericSeparatorSibling.dec:radix===8?isAllowedNumericSeparatorSibling.oct:isAllowedNumericSeparatorSibling.bin;let invalid=false;let total=0;for(let i=0,e=len==null?Infinity:len;i<e;++i){const code=input.charCodeAt(pos);let val;if(code===95&&allowNumSeparator!=="bail"){const prev=input.charCodeAt(pos-1);const next=input.charCodeAt(pos+1);if(!allowNumSeparator){if(bailOnError)return{n:null,pos};errors.numericSeparatorInEscapeSequence(pos,lineStart,curLine)}else if(Number.isNaN(next)||!isAllowedSibling(next)||forbiddenSiblings.has(prev)){if(bailOnError)return{n:null,pos};errors.unexpectedNumericSeparator(pos,lineStart,curLine)}++pos;continue}if(code>=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(_isDigit(code)){val=code-48}else{val=Infinity}if(val>=radix){if(val<=9){if(bailOnError)return{n:null,pos};errors.invalidDigit(pos,lineStart,curLine,radix);val=0}else if(forceLen){val=0;invalid=true}else{break}}++pos;total=total*radix+val}if(pos===start||len!=null&&pos-start!==len||invalid){return{n:null,pos}}return{n:total,pos}}function readCodePoint(input,pos,lineStart,curLine,throwOnInvalid,errors){const ch=input.charCodeAt(pos);let code;if(ch===123){++pos;({code,pos}=readHexChar(input,pos,lineStart,curLine,input.indexOf("}",pos)-pos,true,throwOnInvalid,errors));++pos;if(code!==null&&code>1114111){if(throwOnInvalid){errors.invalidCodePoint(pos,lineStart,curLine)}return{code:null,pos}}}else{({code,pos}=readHexChar(input,pos,lineStart,curLine,4,false,throwOnInvalid,errors))}return{code,pos}}function shallowEqual(actual,expected){const keys=Object.keys(expected);for(const key of keys){if(actual[key]!==expected[key]){return false}}return true}function isType$1(type,node,opts){return node?.type===type&&(opts==null||shallowEqual(node,opts))}var warnings=new Set;function deprecationWarning(oldName,newName,prefix="",cacheKey=oldName){if(warnings.has(cacheKey))return;warnings.add(cacheKey);const{internal,trace}=captureShortStackTrace(1,2);if(internal){return}console.warn(`${prefix}\`${oldName}\` has been deprecated, please migrate to \`${newName}\`
|
|
432
|
+
${trace}`)}function captureShortStackTrace(skip,length){const{stackTraceLimit,prepareStackTrace}=Error;let stackTrace;Error.stackTraceLimit=1+skip+length;Error.prepareStackTrace=function(err,stack){stackTrace=stack};new Error().stack;Error.stackTraceLimit=stackTraceLimit;Error.prepareStackTrace=prepareStackTrace;if(!stackTrace)return{internal:false,trace:""};const shortStackTrace=stackTrace.slice(1+skip,1+skip+length);return{internal:/[\\/]@babel[\\/]/.test(shortStackTrace[1].getFileName()),trace:shortStackTrace.map((frame)=>` at ${frame}`).join(`
|
|
433
|
+
`)}}function isAssignmentExpression(node,opts){return isType$1("AssignmentExpression",node,opts)}function isFile(node,opts){return isType$1("File",node,opts)}function isFunctionDeclaration(node,opts){return isType$1("FunctionDeclaration",node,opts)}function isFunctionExpression(node,opts){return isType$1("FunctionExpression",node,opts)}function isIdentifier(node,opts){return isType$1("Identifier",node,opts)}function isStringLiteral(node,opts){return isType$1("StringLiteral",node,opts)}function isMemberExpression(node,opts){return isType$1("MemberExpression",node,opts)}function isThisExpression(node,opts){return isType$1("ThisExpression",node,opts)}function isUnaryExpression(node,opts){return isType$1("UnaryExpression",node,opts)}function isUpdateExpression(node,opts){return isType$1("UpdateExpression",node,opts)}function isClassExpression(node,opts){return isType$1("ClassExpression",node,opts)}function isExportAllDeclaration(node,opts){return isType$1("ExportAllDeclaration",node,opts)}function isMetaProperty(node,opts){return isType$1("MetaProperty",node,opts)}function isSuper(node,opts){return isType$1("Super",node,opts)}function isPrivateName(node,opts){return isType$1("PrivateName",node,opts)}function isDeclaration(node,opts){if(!node)return false;switch(node.type){case"FunctionDeclaration":case"VariableDeclaration":case"ClassDeclaration":case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":case"ImportDeclaration":case"DeclareClass":case"DeclareFunction":case"DeclareInterface":case"DeclareModule":case"DeclareModuleExports":case"DeclareTypeAlias":case"DeclareOpaqueType":case"DeclareVariable":case"DeclareExportDeclaration":case"DeclareExportAllDeclaration":case"InterfaceDeclaration":case"OpaqueType":case"TypeAlias":case"EnumDeclaration":case"StructDeclaration":case"TSDeclareFunction":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":case"TSImportEqualsDeclaration":break;case"Placeholder":if(node.expectedNode==="Declaration")break;default:return false}return opts==null||shallowEqual(node,opts)}function isExportDeclaration(node,opts){if(!node)return false;switch(node.type){case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":break;default:return false}return opts==null||shallowEqual(node,opts)}function isMemberExpressionLike(node){return isMemberExpression(node)||isMetaProperty(node)}function matchesPattern(member,match,allowPartial){if(!isMemberExpressionLike(member))return false;const parts=Array.isArray(match)?match:match.split(".");const nodes=[];let node;for(node=member;isMemberExpressionLike(node);node=node.object??node.meta){nodes.push(node.property)}nodes.push(node);if(nodes.length<parts.length)return false;if(!allowPartial&&nodes.length>parts.length)return false;for(let i=0,j=nodes.length-1;i<parts.length;i++,j--){const node=nodes[j];let value;if(isIdentifier(node)){value=node.name}else if(isStringLiteral(node)){value=node.value}else if(isThisExpression(node)){value="this"}else if(isSuper(node)){value="super"}else if(isPrivateName(node)){value="#"+node.id.name}else{return false}if(parts[i]!==value)return false}return true}function buildMatchMemberExpression(match,allowPartial){const parts=match.split(".");return(member)=>matchesPattern(member,parts,allowPartial)}var isReactComponent=buildMatchMemberExpression("React.Component");function isType(nodeType,targetType){if(nodeType===targetType)return true;if(nodeType==null)return false;if(ALIAS_KEYS[targetType])return false;const aliases=FLIPPED_ALIAS_KEYS[targetType];if(aliases?.includes(nodeType))return true;return false}function isPlaceholderType(placeholderType,targetType){if(placeholderType===targetType)return true;const aliases=PLACEHOLDERS_ALIAS[placeholderType];if(aliases?.includes(targetType))return true;return false}function is(type,node,opts){if(!node)return false;const matches=isType(node.type,type);if(!matches){if(!opts&&node.type==="Placeholder"&&type in FLIPPED_ALIAS_KEYS){return isPlaceholderType(node.expectedNode,type)}return false}if(opts===undefined){return true}else{return shallowEqual(node,opts)}}function isValidIdentifier(name,reserved=true){if(typeof name!=="string")return false;if(reserved){if(isKeyword(name)||isStrictReservedWord(name,true)){return false}}return isIdentifierName(name)}var COMMENT_KEYS=["leadingComments","trailingComments","innerComments"];var LOGICAL_OPERATORS=["||","&&","??"];var UPDATE_OPERATORS=["++","--"];var BOOLEAN_NUMBER_BINARY_OPERATORS=[">","<",">=","<="];var EQUALITY_BINARY_OPERATORS=["==","===","!=","!=="];var COMPARISON_BINARY_OPERATORS=[...EQUALITY_BINARY_OPERATORS,"in","instanceof"];var BOOLEAN_BINARY_OPERATORS=[...COMPARISON_BINARY_OPERATORS,...BOOLEAN_NUMBER_BINARY_OPERATORS];var NUMBER_BINARY_OPERATORS=["-","/","%","*","**","&","|",">>",">>>","<<","^"];var BINARY_OPERATORS=["+",...NUMBER_BINARY_OPERATORS,...BOOLEAN_BINARY_OPERATORS,"|>"];var ASSIGNMENT_OPERATORS=["=","+=",...NUMBER_BINARY_OPERATORS.map((op)=>op+"="),...LOGICAL_OPERATORS.map((op)=>op+"=")];var BOOLEAN_UNARY_OPERATORS=["delete","!"];var NUMBER_UNARY_OPERATORS=["+","-","~"];var STRING_UNARY_OPERATORS=["typeof"];var UNARY_OPERATORS=["void","throw",...BOOLEAN_UNARY_OPERATORS,...NUMBER_UNARY_OPERATORS,...STRING_UNARY_OPERATORS];var VISITOR_KEYS={};var ALIAS_KEYS={};var FLIPPED_ALIAS_KEYS={};var NODE_FIELDS$1={};var BUILDER_KEYS={};var DEPRECATED_KEYS={};var NODE_PARENT_VALIDATIONS={};var NODE_UNION_SHAPES__PRIVATE={};function getType(val){if(Array.isArray(val)){return"array"}else if(val===null){return"null"}else{return typeof val}}function combine(fn,...validators){return Object.assign(fn,...validators)}function validate$2(validate){return{validate}}function validateType(...typeNames){return validate$2(assertNodeType(...typeNames))}function validateOptional(validate){return{validate,optional:true}}function validateDefault(validate,defaultValue){return{validate,default:defaultValue,optional:false}}function validateOptionalType(...typeNames){return{validate:assertNodeType(...typeNames),optional:true}}function arrayOf(elementType){return chain(assertValueType("array"),assertEach(elementType))}function arrayOfType(...typeNames){return arrayOf(assertNodeType(...typeNames))}function validateArrayOfType(...typeNames){return validate$2(arrayOfType(...typeNames))}function assertEach(callback){const childValidator=validateChild;function validator(node,key,val){if(!Array.isArray(val))return;let i=0;const subKey={toString(){return`${key}[${i}]`}};for(;i<val.length;i++){const v=val[i];callback(node,subKey,v);childValidator(node,subKey,v)}}validator.each=callback;return validator}function assertOneOf(...values){function validate(node,key,val){if(!values.includes(val)){throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`)}}validate.oneOf=values;return validate}var allExpandedTypes=[];function assertNodeType(...types){const expandedTypes=new Set;allExpandedTypes.push({types,set:expandedTypes});function validate(node,key,val){const valType=val?.type;if(valType!=null){if(expandedTypes.has(valType)){validateChild(node,key,val);return}if(valType==="Placeholder"){for(const type of types){if(is(type,val)){validateChild(node,key,val);return}}}}throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(valType)}`)}validate.oneOfNodeTypes=types;return validate}function assertNodeOrValueType(...types){function validate(node,key,val){const primitiveType=getType(val);for(const type of types){if(primitiveType===type||is(type,val)){validateChild(node,key,val);return}}throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val?.type)}`)}validate.oneOfNodeOrValueTypes=types;return validate}function assertValueType(type){function validate(node,key,val){if(getType(val)===type){return}throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`)}validate.type=type;return validate}function assertShape(shape){const keys=Object.keys(shape);function validate(node,key,val){const errors=[];for(const property of keys){try{validateField(node,property,val[property],shape[property])}catch(error){if(error instanceof TypeError){errors.push(error.message);continue}throw error}}if(errors.length){throw new TypeError(`Property ${key} of ${node.type} expected to have the following:
|
|
434
|
+
${errors.join(`
|
|
435
|
+
`)}`)}}validate.shapeOf=shape;return validate}function assertOptionalChainStart(){function validate(node){let current=node;while(node){const{type}=current;if(type==="OptionalCallExpression"){if(current.optional)return;current=current.callee;continue}if(type==="OptionalMemberExpression"){if(current.optional)return;current=current.object;continue}break}throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${current?.type}`)}return validate}function chain(...fns){function validate(...args){for(const fn of fns){fn(...args)}}validate.chainOf=fns;if(fns.length>=2&&"type"in fns[0]&&fns[0].type==="array"&&!("each"in fns[1])){throw new Error(`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`)}return validate}var validTypeOpts=new Set(["aliases","builder","deprecatedAlias","fields","inherits","visitor","validate","unionShape"]);var validFieldKeys=new Set(["default","optional","deprecated","validate"]);var store={};function defineAliasedType(...aliases){return(type,opts={})=>{let defined=opts.aliases;if(!defined){if(opts.inherits)defined=store[opts.inherits].aliases?.slice();defined??=[];opts.aliases=defined}const additional=aliases.filter((a)=>!defined.includes(a));defined.unshift(...additional);defineType$5(type,opts)}}function defineType$5(type,opts={}){const inherits=opts.inherits&&store[opts.inherits]||{};const visitor=opts.visitor||inherits.visitor||[];const aliases=opts.aliases||inherits.aliases||[];const builder=opts.builder||inherits.builder||opts.visitor||[];let fields=opts.fields;if(!fields){fields={};if(inherits.fields){const keys=Object.getOwnPropertyNames(inherits.fields);for(const key of keys){const field=inherits.fields[key];const def=field.default;if(Array.isArray(def)?def.length>0:def&&typeof def==="object"){throw new Error("field defaults can only be primitives or empty arrays currently")}fields[key]={default:Array.isArray(def)?[]:def,optional:field.optional,deprecated:field.deprecated,validate:field.validate}}}}for(const k of Object.keys(opts)){if(!validTypeOpts.has(k)){throw new Error(`Unknown type option "${k}" on ${type}`)}}if(opts.deprecatedAlias){DEPRECATED_KEYS[opts.deprecatedAlias]=type}for(const key of visitor.concat(builder)){fields[key]=fields[key]||{}}for(const key of Object.keys(fields)){const field=fields[key];if(field.default===null){field.optional??=true}if(field.default===undefined){field.default=null;field.optional??=false}else if(!field.validate&&field.default!=null){field.validate=assertValueType(getType(field.default))}for(const k of Object.keys(field)){if(!validFieldKeys.has(k)){throw new Error(`Unknown field key "${k}" on ${type}.${key}`)}}}VISITOR_KEYS[type]=opts.visitor=visitor;BUILDER_KEYS[type]=opts.builder=builder;NODE_FIELDS$1[type]=opts.fields=fields;ALIAS_KEYS[type]=opts.aliases=aliases;aliases.forEach((alias)=>{FLIPPED_ALIAS_KEYS[alias]=FLIPPED_ALIAS_KEYS[alias]||[];FLIPPED_ALIAS_KEYS[alias].push(type)});if(opts.validate){NODE_PARENT_VALIDATIONS[type]=opts.validate}if(opts.unionShape){NODE_UNION_SHAPES__PRIVATE[type]=opts.unionShape}store[type]=opts}var utils=Object.defineProperty({__proto__:null,ALIAS_KEYS,BUILDER_KEYS,DEPRECATED_KEYS,FLIPPED_ALIAS_KEYS,NODE_FIELDS:NODE_FIELDS$1,NODE_PARENT_VALIDATIONS,NODE_UNION_SHAPES__PRIVATE,VISITOR_KEYS,allExpandedTypes,arrayOf,arrayOfType,assertEach,assertNodeOrValueType,assertNodeType,assertOneOf,assertOptionalChainStart,assertShape,assertValueType,chain,combine,default:defineType$5,defineAliasedType,validate:validate$2,validateArrayOfType,validateDefault,validateOptional,validateOptionalType,validateType},Symbol.toStringTag,{value:"Module"});var classMethodOrPropertyUnionShapeCommon=(allowPrivateName=false)=>({unionShape:{discriminator:"computed",shapes:[{name:"computed",value:[true],properties:{key:{validate:assertNodeType("Expression")}}},{name:"nonComputed",value:[false],properties:{key:{validate:allowPrivateName?assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","PrivateName"):assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral")}}}]}});var memberExpressionUnionShapeCommon={unionShape:{discriminator:"computed",shapes:[{name:"computed",value:[true],properties:{property:{validate:assertNodeType("Expression")}}},{name:"nonComputed",value:[false],properties:{property:{validate:assertNodeType("Identifier","PrivateName")}}}]}};var defineType$4=defineAliasedType("Standardized");defineType$4("ArrayExpression",{fields:{elements:{validate:arrayOf(assertNodeOrValueType("null","Expression","SpreadElement")),default:undefined}},visitor:["elements"],aliases:["Expression"]});defineType$4("AssignmentExpression",{fields:{operator:{validate:combine(function(){const identifier=assertOneOf(...ASSIGNMENT_OPERATORS);const pattern=assertOneOf("=");return function(node,key,val){const validator=is("Pattern",node.left)?pattern:identifier;validator(node,key,val)}}(),{oneOf:ASSIGNMENT_OPERATORS})},left:{validate:assertNodeType("Identifier","MemberExpression","OptionalMemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")},right:{validate:assertNodeType("Expression")}},builder:["operator","left","right"],visitor:["left","right"],aliases:["Expression"]});defineType$4("BinaryExpression",{builder:["operator","left","right"],fields:{operator:{validate:assertOneOf(...BINARY_OPERATORS)},left:{validate:function(){const expression=assertNodeType("Expression");const inOp=assertNodeType("Expression","PrivateName");const validator=combine(function(node,key,val){const validator=node.operator==="in"?inOp:expression;validator(node,key,val)},{oneOfNodeTypes:["Expression","PrivateName"]});return validator}()},right:{validate:assertNodeType("Expression")}},unionShape:{discriminator:"operator",shapes:[{name:"in",value:["in"],properties:{left:{validate:assertNodeType("Expression","PrivateName")}}},{name:"notIn",value:BINARY_OPERATORS.filter((op)=>op!=="in"),properties:{left:{validate:assertNodeType("Expression")}}}]},visitor:["left","right"],aliases:["Binary","Expression"]});defineType$4("InterpreterDirective",{builder:["value"],fields:{value:{validate:assertValueType("string")}}});defineType$4("Directive",{visitor:["value"],fields:{value:{validate:assertNodeType("DirectiveLiteral")}}});defineType$4("DirectiveLiteral",{builder:["value"],fields:{value:{validate:assertValueType("string")}}});defineType$4("BlockStatement",{builder:["body","directives"],visitor:["directives","body"],fields:{directives:{validate:arrayOfType("Directive"),default:[]},body:validateArrayOfType("Statement")},aliases:["Scopable","BlockParent","Block","Statement"]});defineType$4("BreakStatement",{visitor:["label"],fields:{label:{validate:assertNodeType("Identifier"),optional:true}},aliases:["Statement","Terminatorless","CompletionStatement"]});defineType$4("CallExpression",{visitor:["callee","typeArguments","arguments"],builder:["callee","arguments"],aliases:["Expression"],fields:{callee:{validate:assertNodeType("Expression","Super","Import","V8IntrinsicIdentifier")},arguments:validateArrayOfType("Expression","SpreadElement","ArgumentPlaceholder"),typeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true}}});defineType$4("CatchClause",{visitor:["param","body"],fields:{param:{validate:assertNodeType("Identifier","ArrayPattern","ObjectPattern"),optional:true},body:{validate:assertNodeType("BlockStatement")}},aliases:["Scopable","BlockParent"]});defineType$4("ConditionalExpression",{visitor:["test","consequent","alternate"],fields:{test:{validate:assertNodeType("Expression")},consequent:{validate:assertNodeType("Expression")},alternate:{validate:assertNodeType("Expression")}},aliases:["Expression","Conditional"]});defineType$4("ContinueStatement",{visitor:["label"],fields:{label:{validate:assertNodeType("Identifier"),optional:true}},aliases:["Statement","Terminatorless","CompletionStatement"]});defineType$4("DebuggerStatement",{aliases:["Statement"]});defineType$4("DoWhileStatement",{builder:["test","body"],visitor:["body","test"],fields:{test:{validate:assertNodeType("Expression")},body:{validate:assertNodeType("Statement")}},aliases:["Statement","BlockParent","Loop","While","Scopable"]});defineType$4("EmptyStatement",{aliases:["Statement"]});defineType$4("ExpressionStatement",{visitor:["expression"],fields:{expression:{validate:assertNodeType("Expression")}},aliases:["Statement","ExpressionWrapper"]});defineType$4("File",{builder:["program","comments","tokens"],visitor:["program"],fields:{program:{validate:assertNodeType("Program")},comments:{validate:assertEach(assertNodeType("CommentBlock","CommentLine")),optional:true},tokens:{validate:assertEach(Object.assign(()=>{},{type:"any"})),optional:true}}});defineType$4("ForInStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:assertNodeType("VariableDeclaration","Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")},right:{validate:assertNodeType("Expression")},body:{validate:assertNodeType("Statement")}}});defineType$4("ForStatement",{visitor:["init","test","update","body"],aliases:["Scopable","Statement","For","BlockParent","Loop"],fields:{init:{validate:assertNodeType("VariableDeclaration","Expression"),optional:true},test:{validate:assertNodeType("Expression"),optional:true},update:{validate:assertNodeType("Expression"),optional:true},body:{validate:assertNodeType("Statement")}}});var functionCommon=()=>({params:validateArrayOfType("FunctionParameter"),generator:{default:false},async:{default:false}});var functionTypeAnnotationCommon=()=>({returnType:{validate:assertNodeType("TypeAnnotation","TSTypeAnnotation"),optional:true},typeParameters:{validate:assertNodeType("TypeParameterDeclaration","TSTypeParameterDeclaration"),optional:true}});var functionDeclarationCommon=()=>({...functionCommon(),declare:{validate:assertValueType("boolean"),optional:true},id:{validate:assertNodeType("Identifier"),optional:true}});defineType$4("FunctionDeclaration",{builder:["id","params","body","generator","async"],visitor:["id","typeParameters","params","predicate","returnType","body"],fields:{...functionDeclarationCommon(),...functionTypeAnnotationCommon(),body:{validate:assertNodeType("BlockStatement")},predicate:{validate:assertNodeType("FlowPredicate"),optional:true}},aliases:["Scopable","Function","BlockParent","FunctionParent","Statement","Pureish","Declaration"],validate:function(){const identifier=assertNodeType("Identifier");return function(parent,key,node){if(!is("ExportDefaultDeclaration",parent)){identifier(node,"id",node.id)}}}()});defineType$4("FunctionExpression",{inherits:"FunctionDeclaration",aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{...functionCommon(),...functionTypeAnnotationCommon(),id:{validate:assertNodeType("Identifier"),optional:true},body:{validate:assertNodeType("BlockStatement")},predicate:{validate:assertNodeType("FlowPredicate"),optional:true}}});var patternLikeCommon=()=>({typeAnnotation:{validate:assertNodeType("TypeAnnotation","TSTypeAnnotation"),optional:true},optional:{validate:assertValueType("boolean"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true}});defineType$4("Identifier",{builder:["name"],visitor:["typeAnnotation","decorators"],aliases:["Expression","FunctionParameter","PatternLike","LVal","TSEntityName"],fields:{...patternLikeCommon(),name:{validate:chain(assertValueType("string"),combine(function(node,key,val){if(!isValidIdentifier(val,false)){throw new TypeError(`"${val}" is not a valid identifier name`)}},{type:"string"}))}},validate:function(parent,key,node){const match=/\.(\w+)$/.exec(key.toString());if(!match)return;const[,parentKey]=match;const nonComp={computed:false};if(parentKey==="property"){if(is("MemberExpression",parent,nonComp))return;if(is("OptionalMemberExpression",parent,nonComp))return}else if(parentKey==="key"){if(is("Property",parent,nonComp))return;if(is("Method",parent,nonComp))return}else if(parentKey==="exported"){if(is("ExportSpecifier",parent))return}else if(parentKey==="imported"){if(is("ImportSpecifier",parent,{imported:node}))return}else if(parentKey==="meta"){if(is("MetaProperty",parent,{meta:node}))return}if((isKeyword(node.name)||isReservedWord(node.name,false))&&node.name!=="this"){throw new TypeError(`"${node.name}" is not a valid identifier`)}}});defineType$4("IfStatement",{visitor:["test","consequent","alternate"],aliases:["Statement","Conditional"],fields:{test:{validate:assertNodeType("Expression")},consequent:{validate:assertNodeType("Statement")},alternate:{optional:true,validate:assertNodeType("Statement")}}});defineType$4("LabeledStatement",{visitor:["label","body"],aliases:["Statement"],fields:{label:{validate:assertNodeType("Identifier")},body:{validate:assertNodeType("Statement")}}});defineType$4("StringLiteral",{builder:["value"],fields:{value:{validate:assertValueType("string")}},aliases:["Expression","Pureish","Literal","Immutable"]});defineType$4("NumericLiteral",{builder:["value"],deprecatedAlias:"NumberLiteral",fields:{value:{validate:chain(assertValueType("number"),combine(function(node,key,val){if(1/val<0||!Number.isFinite(val)){const error=new Error("NumericLiterals must be non-negative finite numbers. "+`You can use t.valueToNode(${val}) instead.`);if(!new Error().stack.includes("regenerator")){throw error}}},{type:"number"}))}},aliases:["Expression","Pureish","Literal","Immutable"]});defineType$4("NullLiteral",{aliases:["Expression","Pureish","Literal","Immutable"]});defineType$4("BooleanLiteral",{builder:["value"],fields:{value:{validate:assertValueType("boolean")}},aliases:["Expression","Pureish","Literal","Immutable"]});defineType$4("RegExpLiteral",{builder:["pattern","flags"],deprecatedAlias:"RegexLiteral",aliases:["Expression","Pureish","Literal"],fields:{pattern:{validate:assertValueType("string")},flags:{validate:chain(assertValueType("string"),combine(function(node,key,val){const invalid=/[^dgimsuvy]/.exec(val);if(invalid){throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`)}},{type:"string"})),default:""}}});defineType$4("LogicalExpression",{builder:["operator","left","right"],visitor:["left","right"],aliases:["Binary","Expression"],fields:{operator:{validate:assertOneOf(...LOGICAL_OPERATORS)},left:{validate:assertNodeType("Expression")},right:{validate:assertNodeType("Expression")}}});defineType$4("MemberExpression",{builder:["object","property","computed"],visitor:["object","property"],aliases:["Expression","LVal","PatternLike"],...memberExpressionUnionShapeCommon,fields:{object:{validate:assertNodeType("Expression","Super")},property:{validate:function(){const normal=assertNodeType("Identifier","PrivateName");const computed=assertNodeType("Expression");const validator=combine(function(node,key,val){const validator=node.computed?computed:normal;validator(node,key,val)},{oneOfNodeTypes:["Expression","Identifier","PrivateName"]});return validator}()},computed:{default:false}}});defineType$4("NewExpression",{inherits:"CallExpression",fields:{callee:{validate:assertNodeType("Expression","V8IntrinsicIdentifier")},arguments:validateArrayOfType("Expression","SpreadElement","ArgumentPlaceholder"),typeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true}}});defineType$4("Program",{visitor:["directives","body"],builder:["body","directives","sourceType","interpreter"],fields:{sourceType:{validate:assertOneOf("script","module"),default:"script"},interpreter:{validate:assertNodeType("InterpreterDirective"),default:null,optional:true},directives:{validate:arrayOfType("Directive"),default:[]},body:validateArrayOfType("Statement")},aliases:["Scopable","BlockParent","Block"]});defineType$4("ObjectExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:validateArrayOfType("ObjectMethod","ObjectProperty","SpreadElement")}});defineType$4("ObjectMethod",{builder:["kind","key","params","body","computed","generator","async"],visitor:["decorators","key","typeParameters","params","returnType","body"],...classMethodOrPropertyUnionShapeCommon(),fields:{...functionCommon(),...functionTypeAnnotationCommon(),kind:{validate:assertOneOf("method","get","set")},computed:{default:false},key:{validate:function(){const normal=assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral");const computed=assertNodeType("Expression");const validator=combine(function(node,key,val){const validator=node.computed?computed:normal;validator(node,key,val)},{oneOfNodeTypes:["Expression","Identifier","StringLiteral","NumericLiteral","BigIntLiteral"]});return validator}()},decorators:{validate:arrayOfType("Decorator"),optional:true},body:{validate:assertNodeType("BlockStatement")}},aliases:["UserWhitespacable","Function","Scopable","BlockParent","FunctionParent","Method","ObjectMember"]});defineType$4("ObjectProperty",{builder:["key","value","computed","shorthand"],...classMethodOrPropertyUnionShapeCommon(true),fields:{computed:{default:false},key:{validate:function(){const normal=assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","PrivateName");const computed=assertNodeType("Expression");const validator=combine(function(node,key,val){const validator=node.computed?computed:normal;validator(node,key,val)},{oneOfNodeTypes:["Expression","Identifier","StringLiteral","NumericLiteral","BigIntLiteral","PrivateName"]});return validator}()},value:{validate:assertNodeType("Expression","PatternLike")},shorthand:{validate:chain(assertValueType("boolean"),combine(function(node,key,shorthand){if(!shorthand)return;if(node.computed){throw new TypeError("Property shorthand of ObjectProperty cannot be true if computed is true")}if(!is("Identifier",node.key)){throw new TypeError("Property shorthand of ObjectProperty cannot be true if key is not an Identifier")}},{type:"boolean"})),default:false},decorators:{validate:arrayOfType("Decorator"),optional:true}},visitor:["decorators","key","value"],aliases:["UserWhitespacable","Property","ObjectMember"],validate:function(){const pattern=assertNodeType("Identifier","Pattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","TSTypeAssertion");const expression=assertNodeType("Expression");return function(parent,key,node){const validator=is("ObjectPattern",parent)?pattern:expression;validator(node,"value",node.value)}}()});defineType$4("RestElement",{visitor:["argument","typeAnnotation"],builder:["argument"],aliases:["FunctionParameter","PatternLike"],deprecatedAlias:"RestProperty",fields:{...patternLikeCommon(),argument:{validate:assertNodeType("Identifier","ArrayPattern","ObjectPattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")}},validate:function(parent,key){const match=/(\w+)\[(\d+)\]/.exec(key.toString());if(!match)throw new Error("Internal Babel error: malformed key.");const[,listKey,index]=match;if(parent[listKey].length>+index+1){throw new TypeError(`RestElement must be last element of ${listKey}`)}}});defineType$4("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:assertNodeType("Expression"),optional:true}}});defineType$4("SequenceExpression",{visitor:["expressions"],fields:{expressions:validateArrayOfType("Expression")},aliases:["Expression"]});defineType$4("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:assertNodeType("Expression")}}});defineType$4("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:assertNodeType("Expression"),optional:true},consequent:validateArrayOfType("Statement")}});defineType$4("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:assertNodeType("Expression")},cases:validateArrayOfType("SwitchCase")}});defineType$4("ThisExpression",{aliases:["Expression","TSEntityName"]});defineType$4("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:assertNodeType("Expression")}}});defineType$4("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{block:{validate:chain(assertNodeType("BlockStatement"),combine(function(node){if(!node.handler&&!node.finalizer){throw new TypeError("TryStatement expects either a handler or finalizer, or both")}},{oneOfNodeTypes:["BlockStatement"]}))},handler:{optional:true,validate:assertNodeType("CatchClause")},finalizer:{optional:true,validate:assertNodeType("BlockStatement")}}});defineType$4("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:true},argument:{validate:assertNodeType("Expression")},operator:{validate:assertOneOf(...UNARY_OPERATORS)}},visitor:["argument"],aliases:["UnaryLike","Expression"]});defineType$4("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:false},argument:{validate:assertNodeType("Identifier","MemberExpression")},operator:{validate:assertOneOf(...UPDATE_OPERATORS)}},visitor:["argument"],aliases:["Expression"]});defineType$4("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{declare:{validate:assertValueType("boolean"),optional:true},kind:{validate:assertOneOf("var","let","const","using","await using")},declarations:validateArrayOfType("VariableDeclarator")},validate:(()=>{const withoutInit=assertNodeType("Identifier","Placeholder");const constOrLetOrVar=assertNodeType("Identifier","ArrayPattern","ObjectPattern","Placeholder");const usingOrAwaitUsing=assertNodeType("Identifier","VoidPattern","Placeholder");return function(parent,key,node){const{kind,declarations}=node;const parentIsForX=is("ForXStatement",parent,{left:node});if(parentIsForX){if(declarations.length!==1){throw new TypeError(`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`)}}for(const decl of declarations){if(kind==="const"||kind==="let"||kind==="var"){if(!parentIsForX&&!decl.init){withoutInit(decl,"id",decl.id)}else{constOrLetOrVar(decl,"id",decl.id)}}else{usingOrAwaitUsing(decl,"id",decl.id)}}}})()});defineType$4("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:assertNodeType("Identifier","ArrayPattern","ObjectPattern","VoidPattern")},definite:{optional:true,validate:assertValueType("boolean")},init:{optional:true,validate:assertNodeType("Expression")}}});defineType$4("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:assertNodeType("Expression")},body:{validate:assertNodeType("Statement")}}});defineType$4("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{validate:assertNodeType("Expression")},body:{validate:assertNodeType("Statement")}}});defineType$4("AssignmentPattern",{visitor:["left","right","decorators"],builder:["left","right"],aliases:["FunctionParameter","Pattern","PatternLike"],fields:{...patternLikeCommon(),left:{validate:assertNodeType("Identifier","ObjectPattern","ArrayPattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")},right:{validate:assertNodeType("Expression")}}});defineType$4("ArrayPattern",{visitor:["elements","typeAnnotation"],builder:["elements"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:{...patternLikeCommon(),elements:{validate:chain(assertValueType("array"),assertEach(assertNodeOrValueType("null","PatternLike")))}}});defineType$4("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["typeParameters","params","predicate","returnType","body"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{...functionCommon(),generator:{default:null,optional:true,validate:combine((node,key,val)=>{if(val){throw new TypeError("ArrowFunctionExpression cannot be a generator")}},{type:"boolean"})},...functionTypeAnnotationCommon(),expression:{optional:true,validate:assertValueType("boolean")},body:{validate:assertNodeType("BlockStatement","Expression")},predicate:{validate:assertNodeType("FlowPredicate"),optional:true}}});defineType$4("ClassBody",{visitor:["body"],fields:{body:validateArrayOfType("ClassMethod","ClassPrivateMethod","ClassProperty","ClassPrivateProperty","ClassAccessorProperty","TSDeclareMethod","TSIndexSignature","StaticBlock")}});defineType$4("ClassExpression",{builder:["id","superClass","body","decorators"],visitor:["decorators","id","typeParameters","superClass","superTypeArguments","mixins","implements","body"],aliases:["Scopable","Class","Expression"],fields:{id:{validate:assertNodeType("Identifier"),optional:true},typeParameters:{validate:assertNodeType("TypeParameterDeclaration","TSTypeParameterDeclaration"),optional:true},body:{validate:assertNodeType("ClassBody")},superClass:{optional:true,validate:assertNodeType("Expression")},superTypeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true},implements:{validate:arrayOfType("TSClassImplements","ClassImplements"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true},mixins:{validate:assertNodeType("InterfaceExtends"),optional:true}}});defineType$4("ClassDeclaration",{inherits:"ClassExpression",aliases:["Scopable","Class","Statement","Declaration"],fields:{id:{validate:assertNodeType("Identifier"),optional:true},typeParameters:{validate:assertNodeType("TypeParameterDeclaration","TSTypeParameterDeclaration"),optional:true},body:{validate:assertNodeType("ClassBody")},superClass:{optional:true,validate:assertNodeType("Expression")},superTypeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true},implements:{validate:arrayOfType("TSClassImplements","ClassImplements"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true},mixins:{validate:assertNodeType("InterfaceExtends"),optional:true},declare:{validate:assertValueType("boolean"),optional:true},abstract:{validate:assertValueType("boolean"),optional:true}},validate:function(){const identifier=assertNodeType("Identifier");return function(parent,key,node){if(!is("ExportDefaultDeclaration",parent)){identifier(node,"id",node.id)}}}()});var importAttributes={attributes:{optional:true,validate:arrayOfType("ImportAttribute")}};defineType$4("ExportAllDeclaration",{visitor:["source","attributes"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:{source:{validate:assertNodeType("StringLiteral")},exportKind:validateOptional(assertOneOf("type","value")),...importAttributes}});defineType$4("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:{declaration:validateType("FunctionDeclaration","ClassDeclaration","Expression","StructDeclaration","TSDeclareFunction","TSInterfaceDeclaration","EnumDeclaration"),exportKind:validateOptional(assertOneOf("value"))}});defineType$4("ExportNamedDeclaration",{builder:["declaration","specifiers","source","attributes"],visitor:["declaration","specifiers","source","attributes"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:{declaration:{optional:true,validate:chain(assertNodeType("Declaration"),combine(function(node,key,val){if(val&&node.specifiers.length){throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration")}if(val&&node.source){throw new TypeError("Cannot export a declaration from a source")}},{oneOfNodeTypes:["VariableDeclaration","FunctionDeclaration","ClassDeclaration","StructDeclaration","TSDeclareFunction","TSEnumDeclaration","TSImportEqualsDeclaration","TSInterfaceDeclaration","TSModuleDeclaration","TSTypeAliasDeclaration","EnumDeclaration","InterfaceDeclaration","OpaqueType","TypeAlias"]}))},...importAttributes,phase:{default:null,validate:assertOneOf("defer")},specifiers:{default:[],validate:arrayOf(function(){const sourced=assertNodeType("ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier");const sourceless=assertNodeType("ExportSpecifier");return combine(function(node,key,val){const validator=node.source?sourced:sourceless;validator(node,key,val)},{oneOfNodeTypes:["ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"]})}())},source:{validate:assertNodeType("StringLiteral"),optional:true},exportKind:validateOptional(assertOneOf("type","value"))}});defineType$4("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:assertNodeType("Identifier","StringLiteral")},exported:{validate:assertNodeType("Identifier","StringLiteral")},exportKind:{validate:assertOneOf("type","value"),optional:true}}});defineType$4("ForOfStatement",{visitor:["left","right","body"],builder:["left","right","body","await"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:function(){const declaration=assertNodeType("VariableDeclaration");const lval=assertNodeType("Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression");return combine(function(node,key,val){if(is("VariableDeclaration",val)){declaration(node,key,val)}else{lval(node,key,val)}},{oneOfNodeTypes:["VariableDeclaration","Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"]})}()},right:{validate:assertNodeType("Expression")},body:{validate:assertNodeType("Statement")},await:{default:false}}});defineType$4("ImportDeclaration",{builder:["specifiers","source","attributes"],visitor:["specifiers","source","attributes"],aliases:["Statement","Declaration","ImportOrExportDeclaration"],fields:{...importAttributes,module:{optional:true,validate:assertValueType("boolean")},phase:{default:null,validate:assertOneOf("source","defer")},specifiers:validateArrayOfType("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier"),source:{validate:assertNodeType("StringLiteral")},importKind:{validate:assertOneOf("type","typeof","value"),optional:true}}});defineType$4("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:assertNodeType("Identifier")}}});defineType$4("ImportNamespaceSpecifier",{visitor:["exportsFilter","local"],builder:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:assertNodeType("Identifier")},exportsFilter:{optional:true,validate:arrayOfType("Identifier","StringLiteral")}}});defineType$4("ImportSpecifier",{visitor:["imported","local"],builder:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:assertNodeType("Identifier")},imported:{validate:assertNodeType("Identifier","StringLiteral")},importKind:{validate:assertOneOf("type","typeof","value"),optional:true}}});defineType$4("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:chain(assertNodeType("Identifier"),combine(function(node,key,val){let property;switch(val.name){case"function":property="sent";break;case"new":property="target";break;case"import":property="meta";break}if(!is("Identifier",node.property,{name:property})){throw new TypeError("Unrecognised MetaProperty")}},{oneOfNodeTypes:["Identifier"]}))},property:{validate:assertNodeType("Identifier")}}});var classMethodOrPropertyCommon=()=>({abstract:{validate:assertValueType("boolean"),default:false,optional:true},accessibility:{validate:assertOneOf("public","private","protected"),optional:true},static:{default:false},override:{optional:true,validate:assertValueType("boolean"),default:false},computed:{default:false},optional:{validate:assertValueType("boolean"),optional:true},key:{validate:chain(function(){const normal=assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral");const computed=assertNodeType("Expression","PrivateName");return function(node,key,val){const validator=node.computed?computed:normal;validator(node,key,val)}}(),assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression","PrivateName"))}});var classMethodOrDeclareMethodCommon=(allowDecorators=true)=>({...functionCommon(),...classMethodOrPropertyCommon(),params:validateArrayOfType("FunctionParameter","TSParameterProperty"),kind:{validate:assertOneOf("get","set","method","constructor"),default:"method"},access:{validate:chain(assertValueType("string"),assertOneOf("public","private","protected")),optional:true},...allowDecorators?{decorators:{validate:arrayOfType("Decorator"),optional:true}}:{}});defineType$4("ClassMethod",{aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static","generator","async"],visitor:["decorators","key","typeParameters","params","returnType","body"],...classMethodOrPropertyUnionShapeCommon(),fields:{...classMethodOrDeclareMethodCommon(),...functionTypeAnnotationCommon(),body:{validate:assertNodeType("BlockStatement")}}});defineType$4("ObjectPattern",{visitor:["decorators","properties","typeAnnotation"],builder:["properties"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:{...patternLikeCommon(),properties:validateArrayOfType("RestElement","ObjectProperty")}});defineType$4("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],deprecatedAlias:"SpreadProperty",fields:{argument:{validate:assertNodeType("Expression")}}});defineType$4("Super");defineType$4("TaggedTemplateExpression",{visitor:["tag","typeArguments","quasi"],builder:["tag","quasi"],aliases:["Expression"],fields:{tag:{validate:assertNodeType("Expression")},quasi:{validate:assertNodeType("TemplateLiteral")},typeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true}}});defineType$4("TemplateElement",{builder:["value","tail"],fields:{value:{validate:chain(assertShape({raw:{validate:assertValueType("string")},cooked:{validate:assertValueType("string"),optional:true}}),function templateElementCookedValidator(node){const raw=node.value.raw;let unterminatedCalled=false;const error=()=>{throw new Error("Internal @babel/types error.")};const{str,firstInvalidLoc}=readStringContents("template",raw,0,0,0,{unterminated(){unterminatedCalled=true},strictNumericEscape:error,invalidEscapeSequence:error,numericSeparatorInEscapeSequence:error,unexpectedNumericSeparator:error,invalidDigit:error,invalidCodePoint:error});if(!unterminatedCalled)throw new Error("Invalid raw");node.value.cooked=firstInvalidLoc?null:str})},tail:{default:false}}});defineType$4("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:validateArrayOfType("TemplateElement"),expressions:{validate:chain(assertValueType("array"),assertEach(assertNodeType("Expression","TSType")),function(node,key,val){if(node.quasis.length!==val.length+1){throw new TypeError(`Number of ${node.type} quasis should be exactly one more than the number of expressions.
|
|
436
|
+
Expected ${val.length+1} quasis but got ${node.quasis.length}`)}})}}});defineType$4("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:chain(assertValueType("boolean"),combine(function(node,key,val){if(val&&!node.argument){throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument")}},{type:"boolean"})),default:false},argument:{optional:true,validate:assertNodeType("Expression")}}});defineType$4("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:assertNodeType("Expression")}}});defineType$4("ImportExpression",{visitor:["source","options"],aliases:["Expression"],fields:{phase:{default:null,validate:assertOneOf("source","defer")},sync:{optional:true,validate:assertValueType("boolean")},source:{validate:assertNodeType("Expression")},options:{validate:assertNodeType("Expression"),optional:true}}});defineType$4("Import");defineType$4("BigIntLiteral",{builder:["value"],fields:{value:{validate:assertValueType("bigint")}},aliases:["Expression","Pureish","Literal","Immutable"]});defineType$4("ExportNamespaceSpecifier",{visitor:["exportsFilter","exported"],builder:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:assertNodeType("Identifier","StringLiteral")},exportsFilter:{optional:true,validate:arrayOfType("Identifier","StringLiteral")}}});defineType$4("OptionalMemberExpression",{builder:["object","property","computed","optional"],visitor:["object","property"],aliases:["Expression"],...memberExpressionUnionShapeCommon,fields:{object:{validate:assertNodeType("Expression")},property:{validate:function(){const normal=assertNodeType("Identifier","PrivateName");const computed=assertNodeType("Expression");return combine(function(node,key,val){const validator=node.computed?computed:normal;validator(node,key,val)},{oneOfNodeTypes:["Expression","PrivateName"]})}()},computed:{default:false},optional:{validate:chain(assertValueType("boolean"),assertOptionalChainStart())}}});defineType$4("OptionalCallExpression",{visitor:["callee","typeArguments","arguments"],builder:["callee","arguments","optional"],aliases:["Expression"],fields:{callee:{validate:assertNodeType("Expression")},arguments:validateArrayOfType("Expression","SpreadElement","ArgumentPlaceholder"),optional:{validate:chain(assertValueType("boolean"),assertOptionalChainStart())},typeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true}}});defineType$4("ClassProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property"],...classMethodOrPropertyUnionShapeCommon(),fields:{...classMethodOrPropertyCommon(),value:{validate:assertNodeType("Expression"),optional:true},definite:{validate:assertValueType("boolean"),optional:true},typeAnnotation:{validate:assertNodeType("TypeAnnotation","TSTypeAnnotation"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true},readonly:{validate:assertValueType("boolean"),optional:true},declare:{validate:assertValueType("boolean"),optional:true},variance:{validate:assertNodeType("Variance"),optional:true}}});defineType$4("ClassPrivateProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","decorators","static"],aliases:["Property","Private"],fields:{key:{validate:assertNodeType("PrivateName")},value:{validate:assertNodeType("Expression"),optional:true},typeAnnotation:{validate:assertNodeType("TypeAnnotation","TSTypeAnnotation"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true},static:{validate:assertValueType("boolean"),default:false},readonly:{validate:assertValueType("boolean"),optional:true},optional:{validate:assertValueType("boolean"),optional:true},definite:{validate:assertValueType("boolean"),optional:true},variance:{validate:assertNodeType("Variance"),optional:true}}});defineType$4("ClassPrivateMethod",{builder:["kind","key","params","body","static"],visitor:["decorators","key","typeParameters","params","returnType","body"],aliases:["Function","Scopable","BlockParent","FunctionParent","Method","Private"],fields:{...classMethodOrDeclareMethodCommon(),...functionTypeAnnotationCommon(),kind:{validate:assertOneOf("get","set","method"),default:"method"},key:{validate:assertNodeType("PrivateName")},body:{validate:assertNodeType("BlockStatement")}}});defineType$4("PrivateName",{visitor:["id"],aliases:["Private"],fields:{id:{validate:assertNodeType("Identifier")}}});defineType$4("StaticBlock",{visitor:["body"],fields:{body:validateArrayOfType("Statement")},aliases:["Scopable","BlockParent","FunctionParent"]});defineType$4("ImportAttribute",{visitor:["key","value"],fields:{key:{validate:assertNodeType("Identifier","StringLiteral")},value:{validate:assertNodeType("StringLiteral")}}});var defineType$3=defineAliasedType("Flow");var defineInterfaceishType=(name)=>{const isDeclareClass=name==="DeclareClass";defineType$3(name,{builder:["id","typeParameters","extends","body"],visitor:["id","typeParameters","extends",...isDeclareClass?["mixins","implements"]:[],"body"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier"),typeParameters:validateOptionalType("TypeParameterDeclaration"),extends:validateOptional(arrayOfType("InterfaceExtends")),...isDeclareClass?{mixins:validateOptional(arrayOfType("InterfaceExtends")),implements:validateOptional(arrayOfType("ClassImplements"))}:{},body:validateType("ObjectTypeAnnotation")}})};defineType$3("AnyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["FlowType"],fields:{elementType:validateType("FlowType")}});defineType$3("BooleanTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("BooleanLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:validate$2(assertValueType("boolean"))}});defineType$3("NullLiteralTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("ClassImplements",{visitor:["id","typeParameters"],fields:{id:validateType("Identifier"),typeParameters:validateOptionalType("TypeParameterInstantiation")}});defineInterfaceishType("DeclareClass");defineType$3("DeclareFunction",{builder:["id"],visitor:["id","predicate"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier"),predicate:validateOptionalType("FlowPredicate")}});defineInterfaceishType("DeclareInterface");defineType$3("DeclareModule",{builder:["id","body","kind"],visitor:["id","body"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier","StringLiteral"),body:validateType("BlockStatement"),kind:validateOptional(assertOneOf("CommonJS","ES"))}});defineType$3("DeclareModuleExports",{visitor:["typeAnnotation"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{typeAnnotation:validateType("TypeAnnotation")}});defineType$3("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier"),typeParameters:validateOptionalType("TypeParameterDeclaration"),right:validateType("FlowType")}});defineType$3("DeclareOpaqueType",{visitor:["id","typeParameters","supertype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier"),typeParameters:validateOptionalType("TypeParameterDeclaration"),supertype:validateOptionalType("FlowType"),impltype:validateOptionalType("FlowType")}});defineType$3("DeclareVariable",{visitor:["id"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier")}});defineType$3("DeclareExportDeclaration",{visitor:["declaration","specifiers","source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{declaration:validateOptionalType("Flow"),specifiers:validateOptional(arrayOfType("ExportSpecifier","ExportNamespaceSpecifier")),source:validateOptionalType("StringLiteral"),default:validateOptional(assertValueType("boolean")),...importAttributes}});defineType$3("DeclareExportAllDeclaration",{visitor:["source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{source:validateType("StringLiteral"),exportKind:validateOptional(assertOneOf("type","value")),...importAttributes}});defineType$3("DeclaredPredicate",{visitor:["value"],aliases:["FlowPredicate"],fields:{value:validateType("Expression")}});defineType$3("ExistsTypeAnnotation",{aliases:["FlowType"]});defineType$3("FunctionTypeAnnotation",{builder:["typeParameters","params","rest","returnType"],visitor:["typeParameters","this","params","rest","returnType"],aliases:["FlowType"],fields:{typeParameters:validateOptionalType("TypeParameterDeclaration"),params:validateArrayOfType("FunctionTypeParam"),rest:validateOptionalType("FunctionTypeParam"),this:validateOptionalType("FunctionTypeParam"),returnType:validateType("FlowType")}});defineType$3("FunctionTypeParam",{visitor:["name","typeAnnotation"],fields:{name:validateOptionalType("Identifier"),typeAnnotation:validateType("FlowType"),optional:validateOptional(assertValueType("boolean"))}});defineType$3("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["FlowType"],fields:{id:validateType("Identifier","QualifiedTypeIdentifier"),typeParameters:validateOptionalType("TypeParameterInstantiation")}});defineType$3("InferredPredicate",{aliases:["FlowPredicate"]});defineType$3("InterfaceExtends",{visitor:["id","typeParameters"],fields:{id:validateType("Identifier","QualifiedTypeIdentifier"),typeParameters:validateOptionalType("TypeParameterInstantiation")}});defineInterfaceishType("InterfaceDeclaration");defineType$3("InterfaceTypeAnnotation",{visitor:["extends","body"],aliases:["FlowType"],fields:{extends:validateOptional(arrayOfType("InterfaceExtends")),body:validateType("ObjectTypeAnnotation")}});defineType$3("IntersectionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:validate$2(arrayOfType("FlowType"))}});defineType$3("MixedTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("EmptyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["FlowType"],fields:{typeAnnotation:validateType("FlowType")}});defineType$3("NumberLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:validate$2(assertValueType("number"))}});defineType$3("BigIntLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:validate$2(assertValueType("bigint"))}});defineType$3("NumberTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties","internalSlots"],aliases:["FlowType"],builder:["properties","indexers","callProperties","internalSlots","exact"],fields:{properties:validate$2(arrayOfType("ObjectTypeProperty","ObjectTypeSpreadProperty")),indexers:{validate:arrayOfType("ObjectTypeIndexer"),optional:false,default:[]},callProperties:{validate:arrayOfType("ObjectTypeCallProperty"),optional:false,default:[]},internalSlots:{validate:arrayOfType("ObjectTypeInternalSlot"),optional:false,default:[]},exact:{validate:assertValueType("boolean"),default:false},inexact:validateOptional(assertValueType("boolean"))}});defineType$3("ObjectTypeInternalSlot",{visitor:["id","value"],builder:["id","value","optional","static","method"],aliases:["UserWhitespacable"],fields:{id:validateType("Identifier"),value:validateType("FlowType"),optional:validate$2(assertValueType("boolean")),static:validate$2(assertValueType("boolean")),method:validate$2(assertValueType("boolean"))}});defineType$3("ObjectTypeCallProperty",{visitor:["value"],aliases:["UserWhitespacable"],fields:{value:validateType("FlowType"),static:validateDefault(assertValueType("boolean"),false)}});defineType$3("ObjectTypeIndexer",{visitor:["variance","id","key","value"],builder:["id","key","value","variance"],aliases:["UserWhitespacable"],fields:{id:validateOptionalType("Identifier"),key:validateType("FlowType"),value:validateType("FlowType"),static:validateDefault(assertValueType("boolean"),false),variance:validateOptionalType("Variance")}});defineType$3("ObjectTypeProperty",{visitor:["key","value","variance"],aliases:["UserWhitespacable"],fields:{key:validateType("Identifier","StringLiteral","NumericLiteral"),value:validateType("FlowType"),kind:{validate:assertOneOf("init","get","set"),default:"init",optional:false},static:validateDefault(assertValueType("boolean"),false),proto:validateDefault(assertValueType("boolean"),false),optional:validateDefault(assertValueType("boolean"),false),variance:validateOptionalType("Variance"),method:validateDefault(assertValueType("boolean"),false)}});defineType$3("ObjectTypeSpreadProperty",{visitor:["argument"],aliases:["UserWhitespacable"],fields:{argument:validateType("FlowType")}});defineType$3("OpaqueType",{visitor:["id","typeParameters","supertype","impltype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier"),typeParameters:validateOptionalType("TypeParameterDeclaration"),supertype:validateOptionalType("FlowType"),impltype:validateType("FlowType")}});defineType$3("QualifiedTypeIdentifier",{visitor:["qualification","id"],builder:["id","qualification"],fields:{id:validateType("Identifier"),qualification:validateType("Identifier","QualifiedTypeIdentifier")}});defineType$3("StringLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:validate$2(assertValueType("string"))}});defineType$3("StringTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("SymbolTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("ThisTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("TupleTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:validate$2(arrayOfType("FlowType"))}});defineType$3("TypeofTypeAnnotation",{visitor:["argument"],aliases:["FlowType"],fields:{argument:validateType("FlowType","Identifier")}});defineType$3("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:validateType("Identifier"),typeParameters:validateOptionalType("TypeParameterDeclaration"),right:validateType("FlowType")}});defineType$3("TypeAnnotation",{visitor:["typeAnnotation"],fields:{typeAnnotation:validateType("FlowType","Identifier")}});defineType$3("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["ExpressionWrapper","Expression"],fields:{expression:validateType("Expression"),typeAnnotation:validateType("TypeAnnotation")}});defineType$3("TypeParameter",{builder:["name","bound","default","variance"],visitor:["bound","default","variance"],fields:{name:validate$2(assertValueType("string")),bound:validateOptionalType("TypeAnnotation"),default:validateOptionalType("FlowType"),variance:validateOptionalType("Variance")}});defineType$3("TypeParameterDeclaration",{visitor:["params"],fields:{params:validate$2(arrayOfType("TypeParameter"))}});defineType$3("TypeParameterInstantiation",{visitor:["params"],fields:{params:validate$2(arrayOfType("FlowType"))}});defineType$3("UnionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:validate$2(arrayOfType("FlowType"))}});defineType$3("Variance",{builder:["kind"],fields:{kind:validate$2(assertOneOf("minus","plus"))}});defineType$3("VoidTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]});defineType$3("EnumDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:{id:validateType("Identifier"),body:validateType("EnumBooleanBody","EnumNumberBody","EnumStringBody","EnumSymbolBody")}});var enumBodyBase={explicitType:validateDefault(assertValueType("boolean"),false),hasUnknownMembers:validateDefault(assertValueType("boolean"),false)};defineType$3("EnumBooleanBody",{aliases:["EnumBody"],visitor:["members"],fields:{...enumBodyBase,members:validateArrayOfType("EnumBooleanMember")}});defineType$3("EnumNumberBody",{aliases:["EnumBody"],visitor:["members"],fields:{...enumBodyBase,members:validateArrayOfType("EnumNumberMember")}});defineType$3("EnumStringBody",{aliases:["EnumBody"],visitor:["members"],fields:{...enumBodyBase,members:validateArrayOfType("EnumStringMember","EnumDefaultedMember")}});defineType$3("EnumSymbolBody",{aliases:["EnumBody"],visitor:["members"],fields:{members:validateArrayOfType("EnumDefaultedMember"),hasUnknownMembers:validateDefault(assertValueType("boolean"),false)}});defineType$3("EnumBooleanMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:validateType("Identifier"),init:validateType("BooleanLiteral")}});defineType$3("EnumNumberMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:validateType("Identifier"),init:validateType("NumericLiteral")}});defineType$3("EnumStringMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:validateType("Identifier"),init:validateType("StringLiteral")}});defineType$3("EnumDefaultedMember",{aliases:["EnumMember"],visitor:["id"],fields:{id:validateType("Identifier")}});defineType$3("IndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:validateType("FlowType"),indexType:validateType("FlowType")}});defineType$3("OptionalIndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:validateType("FlowType"),indexType:validateType("FlowType"),optional:validateDefault(assertValueType("boolean"),false)}});var defineType$2=defineAliasedType("JSX");defineType$2("JSXAttribute",{visitor:["name","value"],aliases:["Immutable"],fields:{name:{validate:assertNodeType("JSXIdentifier","JSXNamespacedName")},value:{optional:true,validate:assertNodeType("JSXElement","JSXFragment","StringLiteral","JSXExpressionContainer")}}});defineType$2("JSXClosingElement",{visitor:["name"],aliases:["Immutable"],fields:{name:{validate:assertNodeType("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")}}});defineType$2("JSXElement",{builder:["openingElement","closingElement","children"],visitor:["openingElement","children","closingElement"],aliases:["Immutable","Expression"],fields:{openingElement:{validate:assertNodeType("JSXOpeningElement")},closingElement:{optional:true,validate:assertNodeType("JSXClosingElement")},children:validateArrayOfType("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")}});defineType$2("JSXEmptyExpression",{});defineType$2("JSXExpressionContainer",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:assertNodeType("Expression","JSXEmptyExpression")}}});defineType$2("JSXSpreadChild",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:assertNodeType("Expression")}}});defineType$2("JSXIdentifier",{builder:["name"],fields:{name:{validate:assertValueType("string")}}});defineType$2("JSXMemberExpression",{visitor:["object","property"],fields:{object:{validate:assertNodeType("JSXMemberExpression","JSXIdentifier")},property:{validate:assertNodeType("JSXIdentifier")}}});defineType$2("JSXNamespacedName",{visitor:["namespace","name"],fields:{namespace:{validate:assertNodeType("JSXIdentifier")},name:{validate:assertNodeType("JSXIdentifier")}}});defineType$2("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","typeArguments","attributes"],aliases:["Immutable"],fields:{name:{validate:assertNodeType("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")},selfClosing:{default:false},attributes:validateArrayOfType("JSXAttribute","JSXSpreadAttribute"),typeArguments:{validate:assertNodeType("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:true}}});defineType$2("JSXSpreadAttribute",{visitor:["argument"],fields:{argument:{validate:assertNodeType("Expression")}}});defineType$2("JSXText",{aliases:["Immutable"],builder:["value"],fields:{value:{validate:assertValueType("string")}}});defineType$2("JSXFragment",{builder:["openingFragment","closingFragment","children"],visitor:["openingFragment","children","closingFragment"],aliases:["Immutable","Expression"],fields:{openingFragment:{validate:assertNodeType("JSXOpeningFragment")},closingFragment:{validate:assertNodeType("JSXClosingFragment")},children:validateArrayOfType("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")}});defineType$2("JSXOpeningFragment",{aliases:["Immutable"]});defineType$2("JSXClosingFragment",{aliases:["Immutable"]});var PLACEHOLDERS=["Identifier","StringLiteral","Expression","Statement","Declaration","BlockStatement","ClassBody","Pattern"];var PLACEHOLDERS_ALIAS={Declaration:["Statement"],Pattern:["PatternLike","LVal"]};for(const type of PLACEHOLDERS){const alias=ALIAS_KEYS[type];if(alias?.length)PLACEHOLDERS_ALIAS[type]=alias}var PLACEHOLDERS_FLIPPED_ALIAS={};Object.keys(PLACEHOLDERS_ALIAS).forEach((type)=>{PLACEHOLDERS_ALIAS[type].forEach((alias)=>{if(!Object.hasOwn(PLACEHOLDERS_FLIPPED_ALIAS,alias)){PLACEHOLDERS_FLIPPED_ALIAS[alias]=[]}PLACEHOLDERS_FLIPPED_ALIAS[alias].push(type)})});var defineType$1=defineAliasedType("Miscellaneous");defineType$1("Placeholder",{visitor:[],builder:["expectedNode","name"],fields:{name:{validate:assertNodeType("Identifier")},expectedNode:{validate:assertOneOf(...PLACEHOLDERS)},...patternLikeCommon()}});defineType$1("V8IntrinsicIdentifier",{builder:["name"],fields:{name:{validate:assertValueType("string")}}});defineType$5("ArgumentPlaceholder",{});defineType$5("BindExpression",{visitor:["object","callee"],aliases:["Expression"],fields:{object:{validate:assertNodeOrValueType("null","Expression")},callee:{validate:assertNodeType("Expression")}}});defineType$5("ClassAccessorProperty",{visitor:["decorators","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property","Accessor"],...classMethodOrPropertyUnionShapeCommon(true),fields:{...classMethodOrPropertyCommon(),key:{validate:chain(function(){const normal=assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","PrivateName");const computed=assertNodeType("Expression");return function(node,key,val){const validator=node.computed?computed:normal;validator(node,key,val)}}(),assertNodeType("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression","PrivateName"))},value:{validate:assertNodeType("Expression"),optional:true},definite:{validate:assertValueType("boolean"),optional:true},typeAnnotation:{validate:assertNodeType("TypeAnnotation","TSTypeAnnotation"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true},readonly:{validate:assertValueType("boolean"),optional:true},declare:{validate:assertValueType("boolean"),optional:true},variance:{validate:assertNodeType("Variance"),optional:true}}});defineType$5("Decorator",{visitor:["expression"],fields:{expression:{validate:assertNodeType("Expression")}}});defineType$5("DoExpression",{visitor:["body"],builder:["body","async"],aliases:["Expression"],fields:{body:{validate:assertNodeType("BlockStatement")},async:{validate:assertValueType("boolean"),default:false}}});defineType$5("ExportDefaultSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:assertNodeType("Identifier")}}});defineType$5("ModuleExpression",{visitor:["body"],fields:{body:{validate:assertNodeType("Program")}},aliases:["Expression"]});defineType$5("TopicReference",{aliases:["Expression"]});defineType$5("VoidPattern",{aliases:["Pattern","PatternLike","FunctionParameter"]});defineType$5("StructDeclaration",{visitor:["id","superClass","body"],aliases:["Scopable","Statement","Declaration"],fields:{id:{validate:assertNodeType("Identifier"),optional:true},body:{validate:assertNodeType("StructBody")},superClass:{optional:true,validate:assertNodeType("Expression")}}});defineType$5("StructBody",{visitor:["body"],fields:{body:validateArrayOfType("ClassMethod","ClassPrivateMethod","ClassProperty","ClassPrivateProperty","StaticBlock","ClassAccessorProperty")}});var defineType=defineAliasedType("TypeScript");var bool=assertValueType("boolean");var tSFunctionTypeAnnotationCommon=()=>({returnType:{validate:assertNodeType("TSTypeAnnotation"),optional:true},typeParameters:{validate:assertNodeType("TSTypeParameterDeclaration"),optional:true}});defineType("TSParameterProperty",{aliases:[],builder:["parameter"],visitor:["decorators","parameter"],fields:{accessibility:{validate:assertOneOf("public","private","protected"),optional:true},readonly:{validate:assertValueType("boolean"),optional:true},parameter:{validate:assertNodeType("Identifier","AssignmentPattern")},override:{validate:assertValueType("boolean"),optional:true},decorators:{validate:arrayOfType("Decorator"),optional:true}}});defineType("TSDeclareFunction",{aliases:["Statement","Declaration"],visitor:["id","typeParameters","params","returnType"],fields:{...functionDeclarationCommon(),...tSFunctionTypeAnnotationCommon()}});defineType("TSDeclareMethod",{visitor:["key","typeParameters","params","returnType"],...classMethodOrPropertyUnionShapeCommon(true),fields:{...classMethodOrDeclareMethodCommon(false),...tSFunctionTypeAnnotationCommon()}});defineType("TSQualifiedName",{aliases:["TSEntityName"],visitor:["left","right"],fields:{left:validateType("TSEntityName"),right:validateType("Identifier")}});var signatureDeclarationCommon=()=>({typeParameters:validateOptionalType("TSTypeParameterDeclaration"),params:validateArrayOfType("ArrayPattern","Identifier","ObjectPattern","RestElement"),returnType:validateOptionalType("TSTypeAnnotation")});var callConstructSignatureDeclaration={aliases:["TSTypeElement"],visitor:["typeParameters","params","returnType"],fields:signatureDeclarationCommon()};defineType("TSCallSignatureDeclaration",callConstructSignatureDeclaration);defineType("TSConstructSignatureDeclaration",callConstructSignatureDeclaration);var namedTypeElementCommon=()=>({key:validateType("Expression"),computed:{default:false},optional:validateOptional(bool)});defineType("TSPropertySignature",{aliases:["TSTypeElement"],visitor:["key","typeAnnotation"],fields:{...namedTypeElementCommon(),readonly:validateOptional(bool),typeAnnotation:validateOptionalType("TSTypeAnnotation"),kind:{optional:true,validate:assertOneOf("get","set")}}});defineType("TSMethodSignature",{aliases:["TSTypeElement"],visitor:["key","typeParameters","params","returnType"],fields:{...signatureDeclarationCommon(),...namedTypeElementCommon(),kind:{validate:assertOneOf("method","get","set"),default:"method"}}});defineType("TSIndexSignature",{aliases:["TSTypeElement"],visitor:["parameters","typeAnnotation"],fields:{readonly:validateOptional(bool),static:validateOptional(bool),parameters:validateArrayOfType("Identifier"),typeAnnotation:validateOptionalType("TSTypeAnnotation")}});var tsKeywordTypes=["TSAnyKeyword","TSBooleanKeyword","TSBigIntKeyword","TSIntrinsicKeyword","TSNeverKeyword","TSNullKeyword","TSNumberKeyword","TSObjectKeyword","TSStringKeyword","TSSymbolKeyword","TSUndefinedKeyword","TSUnknownKeyword","TSVoidKeyword"];for(const type of tsKeywordTypes){defineType(type,{aliases:["TSType","TSBaseType"],visitor:[],fields:{}})}defineType("TSThisType",{aliases:["TSType","TSBaseType"],visitor:[],fields:{}});var fnOrCtrBase={aliases:["TSType"],visitor:["typeParameters","params","returnType"]};defineType("TSFunctionType",{...fnOrCtrBase,fields:signatureDeclarationCommon()});defineType("TSConstructorType",{...fnOrCtrBase,fields:{...signatureDeclarationCommon(),abstract:validateOptional(bool)}});defineType("TSTypeReference",{aliases:["TSType"],visitor:["typeName","typeArguments"],fields:{typeName:validateType("TSEntityName"),typeArguments:validateOptionalType("TSTypeParameterInstantiation")}});defineType("TSTypePredicate",{aliases:["TSType"],visitor:["parameterName","typeAnnotation"],builder:["parameterName","typeAnnotation","asserts"],fields:{parameterName:validateType("Identifier","TSThisType"),typeAnnotation:validateOptionalType("TSTypeAnnotation"),asserts:validateOptional(bool)}});defineType("TSTypeQuery",{aliases:["TSType"],visitor:["exprName","typeArguments"],fields:{exprName:validateType("TSEntityName","TSImportType"),typeArguments:validateOptionalType("TSTypeParameterInstantiation")}});defineType("TSTypeLiteral",{aliases:["TSType"],visitor:["members"],fields:{members:validateArrayOfType("TSTypeElement")}});defineType("TSArrayType",{aliases:["TSType"],visitor:["elementType"],fields:{elementType:validateType("TSType")}});defineType("TSTupleType",{aliases:["TSType"],visitor:["elementTypes"],fields:{elementTypes:validateArrayOfType("TSType","TSNamedTupleMember")}});defineType("TSOptionalType",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{typeAnnotation:validateType("TSType")}});defineType("TSRestType",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{typeAnnotation:validateType("TSType")}});defineType("TSNamedTupleMember",{aliases:["TSType"],visitor:["label","elementType"],builder:["label","elementType","optional"],fields:{label:validateType("Identifier"),optional:{validate:bool,default:false},elementType:validateType("TSType")}});var unionOrIntersection={aliases:["TSType"],visitor:["types"],fields:{types:validateArrayOfType("TSType")}};defineType("TSUnionType",unionOrIntersection);defineType("TSIntersectionType",unionOrIntersection);defineType("TSConditionalType",{aliases:["TSType"],visitor:["checkType","extendsType","trueType","falseType"],fields:{checkType:validateType("TSType"),extendsType:validateType("TSType"),trueType:validateType("TSType"),falseType:validateType("TSType")}});defineType("TSInferType",{aliases:["TSType"],visitor:["typeParameter"],fields:{typeParameter:validateType("TSTypeParameter")}});defineType("TSParenthesizedType",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{typeAnnotation:validateType("TSType")}});defineType("TSTypeOperator",{aliases:["TSType"],visitor:["typeAnnotation"],builder:["typeAnnotation","operator"],fields:{operator:{validate:assertOneOf("keyof","readonly","unique"),default:undefined},typeAnnotation:validateType("TSType")}});defineType("TSIndexedAccessType",{aliases:["TSType"],visitor:["objectType","indexType"],fields:{objectType:validateType("TSType"),indexType:validateType("TSType")}});defineType("TSMappedType",{aliases:["TSType"],visitor:["key","constraint","nameType","typeAnnotation"],builder:["key","constraint","nameType","typeAnnotation"],fields:{key:validateType("Identifier"),constraint:validateType("TSType"),readonly:validateOptional(assertOneOf(true,false,"+","-")),optional:validateOptional(assertOneOf(true,false,"+","-")),typeAnnotation:validateOptionalType("TSType"),nameType:validateOptionalType("TSType")}});defineType("TSTemplateLiteralType",{aliases:["TSType","TSBaseType"],visitor:["quasis","types"],fields:{quasis:validateArrayOfType("TemplateElement"),types:{validate:chain(assertValueType("array"),assertEach(assertNodeType("TSType")),function(node,key,val){if(node.quasis.length!==val.length+1){throw new TypeError(`Number of ${node.type} quasis should be exactly one more than the number of types.
|
|
437
|
+
Expected ${val.length+1} quasis but got ${node.quasis.length}`)}})}}});defineType("TSLiteralType",{aliases:["TSType","TSBaseType"],visitor:["literal"],fields:{literal:{validate:function(){const unaryExpression=assertNodeType("NumericLiteral","BigIntLiteral");const unaryOperator=assertOneOf("-");const literal=assertNodeType("NumericLiteral","StringLiteral","BooleanLiteral","BigIntLiteral","TemplateLiteral");const validator=combine(function validator(parent,key,node){if(is("UnaryExpression",node)){unaryOperator(node,"operator",node.operator);unaryExpression(node,"argument",node.argument)}else{literal(parent,key,node)}},{oneOfNodeTypes:["NumericLiteral","StringLiteral","BooleanLiteral","BigIntLiteral","TemplateLiteral","UnaryExpression"]});return validator}()}}});defineType("TSClassImplements",{aliases:["TSType"],visitor:["expression","typeArguments"],fields:{expression:validateType("Expression"),typeArguments:validateOptionalType("TSTypeParameterInstantiation")}});defineType("TSInterfaceHeritage",{aliases:["TSType"],visitor:["expression","typeArguments"],fields:{expression:validateType("Expression"),typeArguments:validateOptionalType("TSTypeParameterInstantiation")}});defineType("TSInterfaceDeclaration",{aliases:["Statement","Declaration"],visitor:["id","typeParameters","extends","body"],fields:{declare:validateOptional(bool),id:validateType("Identifier"),typeParameters:validateOptionalType("TSTypeParameterDeclaration"),extends:validateOptional(arrayOfType("TSInterfaceHeritage")),body:validateType("TSInterfaceBody")}});defineType("TSInterfaceBody",{visitor:["body"],fields:{body:validateArrayOfType("TSTypeElement")}});defineType("TSTypeAliasDeclaration",{aliases:["Statement","Declaration"],visitor:["id","typeParameters","typeAnnotation"],fields:{declare:validateOptional(bool),id:validateType("Identifier"),typeParameters:validateOptionalType("TSTypeParameterDeclaration"),typeAnnotation:validateType("TSType")}});defineType("TSInstantiationExpression",{aliases:["Expression"],visitor:["expression","typeArguments"],fields:{expression:validateType("Expression"),typeArguments:validateOptionalType("TSTypeParameterInstantiation")}});var TSTypeExpression={aliases:["Expression","LVal","PatternLike"],visitor:["expression","typeAnnotation"],fields:{expression:validateType("Expression"),typeAnnotation:validateType("TSType")}};defineType("TSAsExpression",TSTypeExpression);defineType("TSSatisfiesExpression",TSTypeExpression);defineType("TSTypeAssertion",{aliases:["Expression","LVal","PatternLike"],visitor:["typeAnnotation","expression"],fields:{typeAnnotation:validateType("TSType"),expression:validateType("Expression")}});defineType("TSEnumBody",{visitor:["members"],fields:{members:validateArrayOfType("TSEnumMember")}});defineType("TSEnumDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:{declare:validateOptional(bool),const:validateOptional(bool),id:validateType("Identifier"),body:validateType("TSEnumBody")}});defineType("TSEnumMember",{visitor:["id","initializer"],fields:{id:validateType("Identifier","StringLiteral"),initializer:validateOptionalType("Expression")}});defineType("TSModuleDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:{kind:{validate:assertOneOf("global","namespace","module"),default:"namespace"},declare:validateOptional(bool),id:{validate:chain(assertNodeType("TSEntityName","StringLiteral"),combine(function(node,key,val){if(node.kind==="namespace"&&is("StringLiteral",val)){throw new TypeError(`TSModuleDeclaration of kind 'namespace' cannot have a StringLiteral id.`)}},{oneOfNodeTypes:["TSEntityName","StringLiteral"]}))},body:validateType("TSModuleBlock")}});defineType("TSModuleBlock",{aliases:["Scopable","Block","BlockParent","FunctionParent"],visitor:["body"],fields:{body:validateArrayOfType("Statement")}});defineType("TSImportType",{aliases:["TSType"],builder:["source","qualifier","typeArguments"],visitor:["source","options","qualifier","typeArguments"],fields:{source:validateType("StringLiteral"),qualifier:validateOptionalType("TSEntityName"),typeArguments:validateOptionalType("TSTypeParameterInstantiation"),options:{validate:assertNodeType("ObjectExpression"),optional:true}}});defineType("TSImportEqualsDeclaration",{aliases:["Statement","Declaration"],visitor:["id","moduleReference"],fields:{id:validateType("Identifier"),moduleReference:validateType("TSEntityName","TSExternalModuleReference"),importKind:{validate:assertOneOf("type","value"),optional:true}}});defineType("TSExternalModuleReference",{visitor:["expression"],fields:{expression:validateType("StringLiteral")}});defineType("TSNonNullExpression",{aliases:["Expression","LVal","PatternLike"],visitor:["expression"],fields:{expression:validateType("Expression")}});defineType("TSExportAssignment",{aliases:["Statement"],visitor:["expression"],fields:{expression:validateType("Expression")}});defineType("TSNamespaceExportDeclaration",{aliases:["Statement"],visitor:["id"],fields:{id:validateType("Identifier")}});defineType("TSTypeAnnotation",{visitor:["typeAnnotation"],fields:{typeAnnotation:{validate:assertNodeType("TSType")}}});defineType("TSTypeParameterInstantiation",{visitor:["params"],fields:{params:validateArrayOfType("TSType")}});defineType("TSTypeParameterDeclaration",{visitor:["params"],fields:{params:validateArrayOfType("TSTypeParameter")}});defineType("TSTypeParameter",{builder:["constraint","default","name"],visitor:["name","constraint","default"],fields:{name:{validate:assertNodeType("Identifier")},in:{validate:assertValueType("boolean"),optional:true},out:{validate:assertValueType("boolean"),optional:true},const:{validate:assertValueType("boolean"),optional:true},constraint:{validate:assertNodeType("TSType"),optional:true},default:{validate:assertNodeType("TSType"),optional:true}}});var DEPRECATED_ALIASES={ModuleDeclaration:"ImportOrExportDeclaration"};Object.keys(DEPRECATED_ALIASES).forEach((deprecatedAlias)=>{FLIPPED_ALIAS_KEYS[deprecatedAlias]=FLIPPED_ALIAS_KEYS[DEPRECATED_ALIASES[deprecatedAlias]]});for(const{types,set}of allExpandedTypes){for(const type of types){const aliases=FLIPPED_ALIAS_KEYS[type];if(aliases){aliases.forEach(set.add,set)}else{set.add(type)}}}var TYPES=[].concat(Object.keys(VISITOR_KEYS),Object.keys(FLIPPED_ALIAS_KEYS),Object.keys(DEPRECATED_KEYS));function validate$1(node,key,val){if(!node)return;const fields=NODE_FIELDS$1[node.type];if(!fields)return;const field=fields[key];validateField(node,key,val,field);validateChild(node,key,val)}function validateInternal(field,node,key,val,maybeNode){if(!field?.validate)return;if(field.optional&&val==null)return;field.validate(node,key,val);if(maybeNode){const type=val.type;if(type==null)return;NODE_PARENT_VALIDATIONS[type]?.(node,key,val)}}function validateField(node,key,val,field){if(!field?.validate)return;if(field.optional&&val==null)return;field.validate(node,key,val)}function validateChild(node,key,val){const type=val?.type;if(type==null)return;NODE_PARENT_VALIDATIONS[type]?.(node,key,val)}var _validate=Object.defineProperty({__proto__:null,default:validate$1,validateChild,validateField,validateInternal},Symbol.toStringTag,{value:"Module"});var{validateInternal:validate}=_validate;var{NODE_FIELDS}=utils;function arrayExpression(elements){const node={type:"ArrayExpression",elements};const defs=NODE_FIELDS.ArrayExpression;validate(defs.elements,node,"elements",elements,1);return node}function assignmentExpression(operator,left,right){const node={type:"AssignmentExpression",operator,left,right};const defs=NODE_FIELDS.AssignmentExpression;validate(defs.operator,node,"operator",operator);validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);return node}function binaryExpression(operator,left,right){const node={type:"BinaryExpression",operator,left,right};const defs=NODE_FIELDS.BinaryExpression;validate(defs.operator,node,"operator",operator);validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);return node}function interpreterDirective(value){const node={type:"InterpreterDirective",value};const defs=NODE_FIELDS.InterpreterDirective;validate(defs.value,node,"value",value);return node}function directive(value){const node={type:"Directive",value};const defs=NODE_FIELDS.Directive;validate(defs.value,node,"value",value,1);return node}function directiveLiteral(value){const node={type:"DirectiveLiteral",value};const defs=NODE_FIELDS.DirectiveLiteral;validate(defs.value,node,"value",value);return node}function blockStatement(body,directives=[]){const node={type:"BlockStatement",body,directives};const defs=NODE_FIELDS.BlockStatement;validate(defs.body,node,"body",body,1);validate(defs.directives,node,"directives",directives,1);return node}function breakStatement(label=null){const node={type:"BreakStatement",label};const defs=NODE_FIELDS.BreakStatement;validate(defs.label,node,"label",label,1);return node}function callExpression(callee,_arguments){const node={type:"CallExpression",callee,arguments:_arguments};const defs=NODE_FIELDS.CallExpression;validate(defs.callee,node,"callee",callee,1);validate(defs.arguments,node,"arguments",_arguments,1);return node}function catchClause(param=null,body){const node={type:"CatchClause",param,body};const defs=NODE_FIELDS.CatchClause;validate(defs.param,node,"param",param,1);validate(defs.body,node,"body",body,1);return node}function conditionalExpression(test,consequent,alternate){const node={type:"ConditionalExpression",test,consequent,alternate};const defs=NODE_FIELDS.ConditionalExpression;validate(defs.test,node,"test",test,1);validate(defs.consequent,node,"consequent",consequent,1);validate(defs.alternate,node,"alternate",alternate,1);return node}function continueStatement(label=null){const node={type:"ContinueStatement",label};const defs=NODE_FIELDS.ContinueStatement;validate(defs.label,node,"label",label,1);return node}function debuggerStatement(){return{type:"DebuggerStatement"}}function doWhileStatement(test,body){const node={type:"DoWhileStatement",test,body};const defs=NODE_FIELDS.DoWhileStatement;validate(defs.test,node,"test",test,1);validate(defs.body,node,"body",body,1);return node}function emptyStatement(){return{type:"EmptyStatement"}}function expressionStatement(expression){const node={type:"ExpressionStatement",expression};const defs=NODE_FIELDS.ExpressionStatement;validate(defs.expression,node,"expression",expression,1);return node}function file(program,comments=null,tokens=null){const node={type:"File",program,comments,tokens};const defs=NODE_FIELDS.File;validate(defs.program,node,"program",program,1);validate(defs.comments,node,"comments",comments,1);validate(defs.tokens,node,"tokens",tokens);return node}function forInStatement(left,right,body){const node={type:"ForInStatement",left,right,body};const defs=NODE_FIELDS.ForInStatement;validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);validate(defs.body,node,"body",body,1);return node}function forStatement(init=null,test=null,update=null,body){const node={type:"ForStatement",init,test,update,body};const defs=NODE_FIELDS.ForStatement;validate(defs.init,node,"init",init,1);validate(defs.test,node,"test",test,1);validate(defs.update,node,"update",update,1);validate(defs.body,node,"body",body,1);return node}function functionDeclaration(id=null,params,body,generator=false,async=false){const node={type:"FunctionDeclaration",id,params,body,generator,async};const defs=NODE_FIELDS.FunctionDeclaration;validate(defs.id,node,"id",id,1);validate(defs.params,node,"params",params,1);validate(defs.body,node,"body",body,1);validate(defs.generator,node,"generator",generator);validate(defs.async,node,"async",async);return node}function functionExpression(id=null,params,body,generator=false,async=false){const node={type:"FunctionExpression",id,params,body,generator,async};const defs=NODE_FIELDS.FunctionExpression;validate(defs.id,node,"id",id,1);validate(defs.params,node,"params",params,1);validate(defs.body,node,"body",body,1);validate(defs.generator,node,"generator",generator);validate(defs.async,node,"async",async);return node}function identifier(name){const node={type:"Identifier",name};const defs=NODE_FIELDS.Identifier;validate(defs.name,node,"name",name);return node}function ifStatement(test,consequent,alternate=null){const node={type:"IfStatement",test,consequent,alternate};const defs=NODE_FIELDS.IfStatement;validate(defs.test,node,"test",test,1);validate(defs.consequent,node,"consequent",consequent,1);validate(defs.alternate,node,"alternate",alternate,1);return node}function labeledStatement(label,body){const node={type:"LabeledStatement",label,body};const defs=NODE_FIELDS.LabeledStatement;validate(defs.label,node,"label",label,1);validate(defs.body,node,"body",body,1);return node}function stringLiteral(value){const node={type:"StringLiteral",value};const defs=NODE_FIELDS.StringLiteral;validate(defs.value,node,"value",value);return node}function numericLiteral(value){const node={type:"NumericLiteral",value};const defs=NODE_FIELDS.NumericLiteral;validate(defs.value,node,"value",value);return node}function nullLiteral(){return{type:"NullLiteral"}}function booleanLiteral(value){const node={type:"BooleanLiteral",value};const defs=NODE_FIELDS.BooleanLiteral;validate(defs.value,node,"value",value);return node}function regExpLiteral(pattern,flags=""){const node={type:"RegExpLiteral",pattern,flags};const defs=NODE_FIELDS.RegExpLiteral;validate(defs.pattern,node,"pattern",pattern);validate(defs.flags,node,"flags",flags);return node}function logicalExpression(operator,left,right){const node={type:"LogicalExpression",operator,left,right};const defs=NODE_FIELDS.LogicalExpression;validate(defs.operator,node,"operator",operator);validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);return node}function memberExpression(object,property,computed=false){const node={type:"MemberExpression",object,property,computed};const defs=NODE_FIELDS.MemberExpression;validate(defs.object,node,"object",object,1);validate(defs.property,node,"property",property,1);validate(defs.computed,node,"computed",computed);return node}function newExpression(callee,_arguments){const node={type:"NewExpression",callee,arguments:_arguments};const defs=NODE_FIELDS.NewExpression;validate(defs.callee,node,"callee",callee,1);validate(defs.arguments,node,"arguments",_arguments,1);return node}function program(body,directives=[],sourceType="script",interpreter=null){const node={type:"Program",body,directives,sourceType,interpreter};const defs=NODE_FIELDS.Program;validate(defs.body,node,"body",body,1);validate(defs.directives,node,"directives",directives,1);validate(defs.sourceType,node,"sourceType",sourceType);validate(defs.interpreter,node,"interpreter",interpreter,1);return node}function objectExpression(properties){const node={type:"ObjectExpression",properties};const defs=NODE_FIELDS.ObjectExpression;validate(defs.properties,node,"properties",properties,1);return node}function objectMethod(kind,key,params,body,computed=false,generator=false,async=false){const node={type:"ObjectMethod",kind,key,params,body,computed,generator,async};const defs=NODE_FIELDS.ObjectMethod;validate(defs.kind,node,"kind",kind);validate(defs.key,node,"key",key,1);validate(defs.params,node,"params",params,1);validate(defs.body,node,"body",body,1);validate(defs.computed,node,"computed",computed);validate(defs.generator,node,"generator",generator);validate(defs.async,node,"async",async);return node}function objectProperty(key,value,computed=false,shorthand=false){const node={type:"ObjectProperty",key,value,computed,shorthand};const defs=NODE_FIELDS.ObjectProperty;validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);validate(defs.computed,node,"computed",computed);validate(defs.shorthand,node,"shorthand",shorthand);return node}function restElement(argument){const node={type:"RestElement",argument};const defs=NODE_FIELDS.RestElement;validate(defs.argument,node,"argument",argument,1);return node}function returnStatement(argument=null){const node={type:"ReturnStatement",argument};const defs=NODE_FIELDS.ReturnStatement;validate(defs.argument,node,"argument",argument,1);return node}function sequenceExpression(expressions){const node={type:"SequenceExpression",expressions};const defs=NODE_FIELDS.SequenceExpression;validate(defs.expressions,node,"expressions",expressions,1);return node}function parenthesizedExpression(expression){const node={type:"ParenthesizedExpression",expression};const defs=NODE_FIELDS.ParenthesizedExpression;validate(defs.expression,node,"expression",expression,1);return node}function switchCase(test=null,consequent){const node={type:"SwitchCase",test,consequent};const defs=NODE_FIELDS.SwitchCase;validate(defs.test,node,"test",test,1);validate(defs.consequent,node,"consequent",consequent,1);return node}function switchStatement(discriminant,cases){const node={type:"SwitchStatement",discriminant,cases};const defs=NODE_FIELDS.SwitchStatement;validate(defs.discriminant,node,"discriminant",discriminant,1);validate(defs.cases,node,"cases",cases,1);return node}function thisExpression(){return{type:"ThisExpression"}}function throwStatement(argument){const node={type:"ThrowStatement",argument};const defs=NODE_FIELDS.ThrowStatement;validate(defs.argument,node,"argument",argument,1);return node}function tryStatement(block,handler=null,finalizer=null){const node={type:"TryStatement",block,handler,finalizer};const defs=NODE_FIELDS.TryStatement;validate(defs.block,node,"block",block,1);validate(defs.handler,node,"handler",handler,1);validate(defs.finalizer,node,"finalizer",finalizer,1);return node}function unaryExpression(operator,argument,prefix=true){const node={type:"UnaryExpression",operator,argument,prefix};const defs=NODE_FIELDS.UnaryExpression;validate(defs.operator,node,"operator",operator);validate(defs.argument,node,"argument",argument,1);validate(defs.prefix,node,"prefix",prefix);return node}function updateExpression(operator,argument,prefix=false){const node={type:"UpdateExpression",operator,argument,prefix};const defs=NODE_FIELDS.UpdateExpression;validate(defs.operator,node,"operator",operator);validate(defs.argument,node,"argument",argument,1);validate(defs.prefix,node,"prefix",prefix);return node}function variableDeclaration(kind,declarations){const node={type:"VariableDeclaration",kind,declarations};const defs=NODE_FIELDS.VariableDeclaration;validate(defs.kind,node,"kind",kind);validate(defs.declarations,node,"declarations",declarations,1);return node}function variableDeclarator(id,init=null){const node={type:"VariableDeclarator",id,init};const defs=NODE_FIELDS.VariableDeclarator;validate(defs.id,node,"id",id,1);validate(defs.init,node,"init",init,1);return node}function whileStatement(test,body){const node={type:"WhileStatement",test,body};const defs=NODE_FIELDS.WhileStatement;validate(defs.test,node,"test",test,1);validate(defs.body,node,"body",body,1);return node}function withStatement(object,body){const node={type:"WithStatement",object,body};const defs=NODE_FIELDS.WithStatement;validate(defs.object,node,"object",object,1);validate(defs.body,node,"body",body,1);return node}function assignmentPattern(left,right){const node={type:"AssignmentPattern",left,right};const defs=NODE_FIELDS.AssignmentPattern;validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);return node}function arrayPattern(elements){const node={type:"ArrayPattern",elements};const defs=NODE_FIELDS.ArrayPattern;validate(defs.elements,node,"elements",elements,1);return node}function arrowFunctionExpression(params,body,async=false){const node={type:"ArrowFunctionExpression",params,body,async};const defs=NODE_FIELDS.ArrowFunctionExpression;validate(defs.params,node,"params",params,1);validate(defs.body,node,"body",body,1);validate(defs.async,node,"async",async);return node}function classBody(body){const node={type:"ClassBody",body};const defs=NODE_FIELDS.ClassBody;validate(defs.body,node,"body",body,1);return node}function classExpression(id=null,superClass=null,body,decorators=null){const node={type:"ClassExpression",id,superClass,body,decorators};const defs=NODE_FIELDS.ClassExpression;validate(defs.id,node,"id",id,1);validate(defs.superClass,node,"superClass",superClass,1);validate(defs.body,node,"body",body,1);validate(defs.decorators,node,"decorators",decorators,1);return node}function classDeclaration(id=null,superClass=null,body,decorators=null){const node={type:"ClassDeclaration",id,superClass,body,decorators};const defs=NODE_FIELDS.ClassDeclaration;validate(defs.id,node,"id",id,1);validate(defs.superClass,node,"superClass",superClass,1);validate(defs.body,node,"body",body,1);validate(defs.decorators,node,"decorators",decorators,1);return node}function exportAllDeclaration(source,attributes=null){const node={type:"ExportAllDeclaration",source,attributes};const defs=NODE_FIELDS.ExportAllDeclaration;validate(defs.source,node,"source",source,1);validate(defs.attributes,node,"attributes",attributes,1);return node}function exportDefaultDeclaration(declaration){const node={type:"ExportDefaultDeclaration",declaration};const defs=NODE_FIELDS.ExportDefaultDeclaration;validate(defs.declaration,node,"declaration",declaration,1);return node}function exportNamedDeclaration(declaration=null,specifiers=[],source=null,attributes=null){const node={type:"ExportNamedDeclaration",declaration,specifiers,source,attributes};const defs=NODE_FIELDS.ExportNamedDeclaration;validate(defs.declaration,node,"declaration",declaration,1);validate(defs.specifiers,node,"specifiers",specifiers,1);validate(defs.source,node,"source",source,1);validate(defs.attributes,node,"attributes",attributes,1);return node}function exportSpecifier(local,exported){const node={type:"ExportSpecifier",local,exported};const defs=NODE_FIELDS.ExportSpecifier;validate(defs.local,node,"local",local,1);validate(defs.exported,node,"exported",exported,1);return node}function forOfStatement(left,right,body,_await=false){const node={type:"ForOfStatement",left,right,body,await:_await};const defs=NODE_FIELDS.ForOfStatement;validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);validate(defs.body,node,"body",body,1);validate(defs.await,node,"await",_await);return node}function importDeclaration(specifiers,source,attributes=null){const node={type:"ImportDeclaration",specifiers,source,attributes};const defs=NODE_FIELDS.ImportDeclaration;validate(defs.specifiers,node,"specifiers",specifiers,1);validate(defs.source,node,"source",source,1);validate(defs.attributes,node,"attributes",attributes,1);return node}function importDefaultSpecifier(local){const node={type:"ImportDefaultSpecifier",local};const defs=NODE_FIELDS.ImportDefaultSpecifier;validate(defs.local,node,"local",local,1);return node}function importNamespaceSpecifier(local){const node={type:"ImportNamespaceSpecifier",local};const defs=NODE_FIELDS.ImportNamespaceSpecifier;validate(defs.local,node,"local",local,1);return node}function importSpecifier(local,imported){const node={type:"ImportSpecifier",local,imported};const defs=NODE_FIELDS.ImportSpecifier;validate(defs.local,node,"local",local,1);validate(defs.imported,node,"imported",imported,1);return node}function metaProperty(meta,property){const node={type:"MetaProperty",meta,property};const defs=NODE_FIELDS.MetaProperty;validate(defs.meta,node,"meta",meta,1);validate(defs.property,node,"property",property,1);return node}function classMethod(kind="method",key,params,body,computed=false,_static=false,generator=false,async=false){const node={type:"ClassMethod",kind,key,params,body,computed,static:_static,generator,async};const defs=NODE_FIELDS.ClassMethod;validate(defs.kind,node,"kind",kind);validate(defs.key,node,"key",key,1);validate(defs.params,node,"params",params,1);validate(defs.body,node,"body",body,1);validate(defs.computed,node,"computed",computed);validate(defs.static,node,"static",_static);validate(defs.generator,node,"generator",generator);validate(defs.async,node,"async",async);return node}function objectPattern(properties){const node={type:"ObjectPattern",properties};const defs=NODE_FIELDS.ObjectPattern;validate(defs.properties,node,"properties",properties,1);return node}function spreadElement(argument){const node={type:"SpreadElement",argument};const defs=NODE_FIELDS.SpreadElement;validate(defs.argument,node,"argument",argument,1);return node}function _super(){return{type:"Super"}}function taggedTemplateExpression(tag,quasi){const node={type:"TaggedTemplateExpression",tag,quasi};const defs=NODE_FIELDS.TaggedTemplateExpression;validate(defs.tag,node,"tag",tag,1);validate(defs.quasi,node,"quasi",quasi,1);return node}function templateElement(value,tail=false){const node={type:"TemplateElement",value,tail};const defs=NODE_FIELDS.TemplateElement;validate(defs.value,node,"value",value);validate(defs.tail,node,"tail",tail);return node}function templateLiteral(quasis,expressions){const node={type:"TemplateLiteral",quasis,expressions};const defs=NODE_FIELDS.TemplateLiteral;validate(defs.quasis,node,"quasis",quasis,1);validate(defs.expressions,node,"expressions",expressions,1);return node}function yieldExpression(argument=null,delegate=false){const node={type:"YieldExpression",argument,delegate};const defs=NODE_FIELDS.YieldExpression;validate(defs.argument,node,"argument",argument,1);validate(defs.delegate,node,"delegate",delegate);return node}function awaitExpression(argument){const node={type:"AwaitExpression",argument};const defs=NODE_FIELDS.AwaitExpression;validate(defs.argument,node,"argument",argument,1);return node}function importExpression(source,options=null){const node={type:"ImportExpression",source,options};const defs=NODE_FIELDS.ImportExpression;validate(defs.source,node,"source",source,1);validate(defs.options,node,"options",options,1);return node}function _import(){return{type:"Import"}}function bigIntLiteral(value){const node={type:"BigIntLiteral",value};const defs=NODE_FIELDS.BigIntLiteral;validate(defs.value,node,"value",value);return node}function exportNamespaceSpecifier(exported){const node={type:"ExportNamespaceSpecifier",exported};const defs=NODE_FIELDS.ExportNamespaceSpecifier;validate(defs.exported,node,"exported",exported,1);return node}function optionalMemberExpression(object,property,computed=false,optional){const node={type:"OptionalMemberExpression",object,property,computed,optional};const defs=NODE_FIELDS.OptionalMemberExpression;validate(defs.object,node,"object",object,1);validate(defs.property,node,"property",property,1);validate(defs.computed,node,"computed",computed);validate(defs.optional,node,"optional",optional);return node}function optionalCallExpression(callee,_arguments,optional){const node={type:"OptionalCallExpression",callee,arguments:_arguments,optional};const defs=NODE_FIELDS.OptionalCallExpression;validate(defs.callee,node,"callee",callee,1);validate(defs.arguments,node,"arguments",_arguments,1);validate(defs.optional,node,"optional",optional);return node}function classProperty(key,value=null,typeAnnotation=null,decorators=null,computed=false,_static=false){const node={type:"ClassProperty",key,value,typeAnnotation,decorators,computed,static:_static};const defs=NODE_FIELDS.ClassProperty;validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);validate(defs.decorators,node,"decorators",decorators,1);validate(defs.computed,node,"computed",computed);validate(defs.static,node,"static",_static);return node}function classPrivateProperty(key,value=null,decorators=null,_static=false){const node={type:"ClassPrivateProperty",key,value,decorators,static:_static};const defs=NODE_FIELDS.ClassPrivateProperty;validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);validate(defs.decorators,node,"decorators",decorators,1);validate(defs.static,node,"static",_static);return node}function classPrivateMethod(kind="method",key,params,body,_static=false){const node={type:"ClassPrivateMethod",kind,key,params,body,static:_static,async:false,computed:false,generator:false};const defs=NODE_FIELDS.ClassPrivateMethod;validate(defs.kind,node,"kind",kind);validate(defs.key,node,"key",key,1);validate(defs.params,node,"params",params,1);validate(defs.body,node,"body",body,1);validate(defs.static,node,"static",_static);return node}function privateName(id){const node={type:"PrivateName",id};const defs=NODE_FIELDS.PrivateName;validate(defs.id,node,"id",id,1);return node}function staticBlock(body){const node={type:"StaticBlock",body};const defs=NODE_FIELDS.StaticBlock;validate(defs.body,node,"body",body,1);return node}function importAttribute(key,value){const node={type:"ImportAttribute",key,value};const defs=NODE_FIELDS.ImportAttribute;validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);return node}function anyTypeAnnotation(){return{type:"AnyTypeAnnotation"}}function arrayTypeAnnotation(elementType){const node={type:"ArrayTypeAnnotation",elementType};const defs=NODE_FIELDS.ArrayTypeAnnotation;validate(defs.elementType,node,"elementType",elementType,1);return node}function booleanTypeAnnotation(){return{type:"BooleanTypeAnnotation"}}function booleanLiteralTypeAnnotation(value){const node={type:"BooleanLiteralTypeAnnotation",value};const defs=NODE_FIELDS.BooleanLiteralTypeAnnotation;validate(defs.value,node,"value",value);return node}function nullLiteralTypeAnnotation(){return{type:"NullLiteralTypeAnnotation"}}function classImplements(id,typeParameters=null){const node={type:"ClassImplements",id,typeParameters};const defs=NODE_FIELDS.ClassImplements;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);return node}function declareClass(id,typeParameters=null,_extends=null,body){const node={type:"DeclareClass",id,typeParameters,extends:_extends,body};const defs=NODE_FIELDS.DeclareClass;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.extends,node,"extends",_extends,1);validate(defs.body,node,"body",body,1);return node}function declareFunction(id){const node={type:"DeclareFunction",id};const defs=NODE_FIELDS.DeclareFunction;validate(defs.id,node,"id",id,1);return node}function declareInterface(id,typeParameters=null,_extends=null,body){const node={type:"DeclareInterface",id,typeParameters,extends:_extends,body};const defs=NODE_FIELDS.DeclareInterface;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.extends,node,"extends",_extends,1);validate(defs.body,node,"body",body,1);return node}function declareModule(id,body,kind=null){const node={type:"DeclareModule",id,body,kind};const defs=NODE_FIELDS.DeclareModule;validate(defs.id,node,"id",id,1);validate(defs.body,node,"body",body,1);validate(defs.kind,node,"kind",kind);return node}function declareModuleExports(typeAnnotation){const node={type:"DeclareModuleExports",typeAnnotation};const defs=NODE_FIELDS.DeclareModuleExports;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function declareTypeAlias(id,typeParameters=null,right){const node={type:"DeclareTypeAlias",id,typeParameters,right};const defs=NODE_FIELDS.DeclareTypeAlias;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.right,node,"right",right,1);return node}function declareOpaqueType(id,typeParameters=null,supertype=null){const node={type:"DeclareOpaqueType",id,typeParameters,supertype};const defs=NODE_FIELDS.DeclareOpaqueType;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.supertype,node,"supertype",supertype,1);return node}function declareVariable(id){const node={type:"DeclareVariable",id};const defs=NODE_FIELDS.DeclareVariable;validate(defs.id,node,"id",id,1);return node}function declareExportDeclaration(declaration=null,specifiers=null,source=null,attributes=null){const node={type:"DeclareExportDeclaration",declaration,specifiers,source,attributes};const defs=NODE_FIELDS.DeclareExportDeclaration;validate(defs.declaration,node,"declaration",declaration,1);validate(defs.specifiers,node,"specifiers",specifiers,1);validate(defs.source,node,"source",source,1);validate(defs.attributes,node,"attributes",attributes,1);return node}function declareExportAllDeclaration(source,attributes=null){const node={type:"DeclareExportAllDeclaration",source,attributes};const defs=NODE_FIELDS.DeclareExportAllDeclaration;validate(defs.source,node,"source",source,1);validate(defs.attributes,node,"attributes",attributes,1);return node}function declaredPredicate(value){const node={type:"DeclaredPredicate",value};const defs=NODE_FIELDS.DeclaredPredicate;validate(defs.value,node,"value",value,1);return node}function existsTypeAnnotation(){return{type:"ExistsTypeAnnotation"}}function functionTypeAnnotation(typeParameters=null,params,rest=null,returnType){const node={type:"FunctionTypeAnnotation",typeParameters,params,rest,returnType};const defs=NODE_FIELDS.FunctionTypeAnnotation;validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.rest,node,"rest",rest,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function functionTypeParam(name=null,typeAnnotation){const node={type:"FunctionTypeParam",name,typeAnnotation};const defs=NODE_FIELDS.FunctionTypeParam;validate(defs.name,node,"name",name,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function genericTypeAnnotation(id,typeParameters=null){const node={type:"GenericTypeAnnotation",id,typeParameters};const defs=NODE_FIELDS.GenericTypeAnnotation;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);return node}function inferredPredicate(){return{type:"InferredPredicate"}}function interfaceExtends(id,typeParameters=null){const node={type:"InterfaceExtends",id,typeParameters};const defs=NODE_FIELDS.InterfaceExtends;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);return node}function interfaceDeclaration(id,typeParameters=null,_extends=null,body){const node={type:"InterfaceDeclaration",id,typeParameters,extends:_extends,body};const defs=NODE_FIELDS.InterfaceDeclaration;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.extends,node,"extends",_extends,1);validate(defs.body,node,"body",body,1);return node}function interfaceTypeAnnotation(_extends=null,body){const node={type:"InterfaceTypeAnnotation",extends:_extends,body};const defs=NODE_FIELDS.InterfaceTypeAnnotation;validate(defs.extends,node,"extends",_extends,1);validate(defs.body,node,"body",body,1);return node}function intersectionTypeAnnotation(types){const node={type:"IntersectionTypeAnnotation",types};const defs=NODE_FIELDS.IntersectionTypeAnnotation;validate(defs.types,node,"types",types,1);return node}function mixedTypeAnnotation(){return{type:"MixedTypeAnnotation"}}function emptyTypeAnnotation(){return{type:"EmptyTypeAnnotation"}}function nullableTypeAnnotation(typeAnnotation){const node={type:"NullableTypeAnnotation",typeAnnotation};const defs=NODE_FIELDS.NullableTypeAnnotation;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function numberLiteralTypeAnnotation(value){const node={type:"NumberLiteralTypeAnnotation",value};const defs=NODE_FIELDS.NumberLiteralTypeAnnotation;validate(defs.value,node,"value",value);return node}function bigIntLiteralTypeAnnotation(value){const node={type:"BigIntLiteralTypeAnnotation",value};const defs=NODE_FIELDS.BigIntLiteralTypeAnnotation;validate(defs.value,node,"value",value);return node}function numberTypeAnnotation(){return{type:"NumberTypeAnnotation"}}function objectTypeAnnotation(properties,indexers=[],callProperties=[],internalSlots=[],exact=false){const node={type:"ObjectTypeAnnotation",properties,indexers,callProperties,internalSlots,exact};const defs=NODE_FIELDS.ObjectTypeAnnotation;validate(defs.properties,node,"properties",properties,1);validate(defs.indexers,node,"indexers",indexers,1);validate(defs.callProperties,node,"callProperties",callProperties,1);validate(defs.internalSlots,node,"internalSlots",internalSlots,1);validate(defs.exact,node,"exact",exact);return node}function objectTypeInternalSlot(id,value,optional,_static,method){const node={type:"ObjectTypeInternalSlot",id,value,optional,static:_static,method};const defs=NODE_FIELDS.ObjectTypeInternalSlot;validate(defs.id,node,"id",id,1);validate(defs.value,node,"value",value,1);validate(defs.optional,node,"optional",optional);validate(defs.static,node,"static",_static);validate(defs.method,node,"method",method);return node}function objectTypeCallProperty(value){const node={type:"ObjectTypeCallProperty",value,static:false};const defs=NODE_FIELDS.ObjectTypeCallProperty;validate(defs.value,node,"value",value,1);return node}function objectTypeIndexer(id=null,key,value,variance=null){const node={type:"ObjectTypeIndexer",id,key,value,variance,static:false};const defs=NODE_FIELDS.ObjectTypeIndexer;validate(defs.id,node,"id",id,1);validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);validate(defs.variance,node,"variance",variance,1);return node}function objectTypeProperty(key,value,variance=null){const node={type:"ObjectTypeProperty",key,value,variance,kind:"init",method:false,optional:false,proto:false,static:false};const defs=NODE_FIELDS.ObjectTypeProperty;validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);validate(defs.variance,node,"variance",variance,1);return node}function objectTypeSpreadProperty(argument){const node={type:"ObjectTypeSpreadProperty",argument};const defs=NODE_FIELDS.ObjectTypeSpreadProperty;validate(defs.argument,node,"argument",argument,1);return node}function opaqueType(id,typeParameters=null,supertype=null,impltype){const node={type:"OpaqueType",id,typeParameters,supertype,impltype};const defs=NODE_FIELDS.OpaqueType;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.supertype,node,"supertype",supertype,1);validate(defs.impltype,node,"impltype",impltype,1);return node}function qualifiedTypeIdentifier(id,qualification){const node={type:"QualifiedTypeIdentifier",id,qualification};const defs=NODE_FIELDS.QualifiedTypeIdentifier;validate(defs.id,node,"id",id,1);validate(defs.qualification,node,"qualification",qualification,1);return node}function stringLiteralTypeAnnotation(value){const node={type:"StringLiteralTypeAnnotation",value};const defs=NODE_FIELDS.StringLiteralTypeAnnotation;validate(defs.value,node,"value",value);return node}function stringTypeAnnotation(){return{type:"StringTypeAnnotation"}}function symbolTypeAnnotation(){return{type:"SymbolTypeAnnotation"}}function thisTypeAnnotation(){return{type:"ThisTypeAnnotation"}}function tupleTypeAnnotation(types){const node={type:"TupleTypeAnnotation",types};const defs=NODE_FIELDS.TupleTypeAnnotation;validate(defs.types,node,"types",types,1);return node}function typeofTypeAnnotation(argument){const node={type:"TypeofTypeAnnotation",argument};const defs=NODE_FIELDS.TypeofTypeAnnotation;validate(defs.argument,node,"argument",argument,1);return node}function typeAlias(id,typeParameters=null,right){const node={type:"TypeAlias",id,typeParameters,right};const defs=NODE_FIELDS.TypeAlias;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.right,node,"right",right,1);return node}function typeAnnotation(typeAnnotation){const node={type:"TypeAnnotation",typeAnnotation};const defs=NODE_FIELDS.TypeAnnotation;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function typeCastExpression(expression,typeAnnotation){const node={type:"TypeCastExpression",expression,typeAnnotation};const defs=NODE_FIELDS.TypeCastExpression;validate(defs.expression,node,"expression",expression,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function typeParameter(name,bound=null,_default=null,variance=null){const node={type:"TypeParameter",name,bound,default:_default,variance};const defs=NODE_FIELDS.TypeParameter;validate(defs.name,node,"name",name);validate(defs.bound,node,"bound",bound,1);validate(defs.default,node,"default",_default,1);validate(defs.variance,node,"variance",variance,1);return node}function typeParameterDeclaration(params){const node={type:"TypeParameterDeclaration",params};const defs=NODE_FIELDS.TypeParameterDeclaration;validate(defs.params,node,"params",params,1);return node}function typeParameterInstantiation(params){const node={type:"TypeParameterInstantiation",params};const defs=NODE_FIELDS.TypeParameterInstantiation;validate(defs.params,node,"params",params,1);return node}function unionTypeAnnotation(types){const node={type:"UnionTypeAnnotation",types};const defs=NODE_FIELDS.UnionTypeAnnotation;validate(defs.types,node,"types",types,1);return node}function variance(kind){const node={type:"Variance",kind};const defs=NODE_FIELDS.Variance;validate(defs.kind,node,"kind",kind);return node}function voidTypeAnnotation(){return{type:"VoidTypeAnnotation"}}function enumDeclaration(id,body){const node={type:"EnumDeclaration",id,body};const defs=NODE_FIELDS.EnumDeclaration;validate(defs.id,node,"id",id,1);validate(defs.body,node,"body",body,1);return node}function enumBooleanBody(members){const node={type:"EnumBooleanBody",members,explicitType:false,hasUnknownMembers:false};const defs=NODE_FIELDS.EnumBooleanBody;validate(defs.members,node,"members",members,1);return node}function enumNumberBody(members){const node={type:"EnumNumberBody",members,explicitType:false,hasUnknownMembers:false};const defs=NODE_FIELDS.EnumNumberBody;validate(defs.members,node,"members",members,1);return node}function enumStringBody(members){const node={type:"EnumStringBody",members,explicitType:false,hasUnknownMembers:false};const defs=NODE_FIELDS.EnumStringBody;validate(defs.members,node,"members",members,1);return node}function enumSymbolBody(members){const node={type:"EnumSymbolBody",members,hasUnknownMembers:false};const defs=NODE_FIELDS.EnumSymbolBody;validate(defs.members,node,"members",members,1);return node}function enumBooleanMember(id,init){const node={type:"EnumBooleanMember",id,init};const defs=NODE_FIELDS.EnumBooleanMember;validate(defs.id,node,"id",id,1);validate(defs.init,node,"init",init,1);return node}function enumNumberMember(id,init){const node={type:"EnumNumberMember",id,init};const defs=NODE_FIELDS.EnumNumberMember;validate(defs.id,node,"id",id,1);validate(defs.init,node,"init",init,1);return node}function enumStringMember(id,init){const node={type:"EnumStringMember",id,init};const defs=NODE_FIELDS.EnumStringMember;validate(defs.id,node,"id",id,1);validate(defs.init,node,"init",init,1);return node}function enumDefaultedMember(id){const node={type:"EnumDefaultedMember",id};const defs=NODE_FIELDS.EnumDefaultedMember;validate(defs.id,node,"id",id,1);return node}function indexedAccessType(objectType,indexType){const node={type:"IndexedAccessType",objectType,indexType};const defs=NODE_FIELDS.IndexedAccessType;validate(defs.objectType,node,"objectType",objectType,1);validate(defs.indexType,node,"indexType",indexType,1);return node}function optionalIndexedAccessType(objectType,indexType){const node={type:"OptionalIndexedAccessType",objectType,indexType,optional:false};const defs=NODE_FIELDS.OptionalIndexedAccessType;validate(defs.objectType,node,"objectType",objectType,1);validate(defs.indexType,node,"indexType",indexType,1);return node}function jsxAttribute(name,value=null){const node={type:"JSXAttribute",name,value};const defs=NODE_FIELDS.JSXAttribute;validate(defs.name,node,"name",name,1);validate(defs.value,node,"value",value,1);return node}function jsxClosingElement(name){const node={type:"JSXClosingElement",name};const defs=NODE_FIELDS.JSXClosingElement;validate(defs.name,node,"name",name,1);return node}function jsxElement(openingElement,closingElement=null,children){const node={type:"JSXElement",openingElement,closingElement,children};const defs=NODE_FIELDS.JSXElement;validate(defs.openingElement,node,"openingElement",openingElement,1);validate(defs.closingElement,node,"closingElement",closingElement,1);validate(defs.children,node,"children",children,1);return node}function jsxEmptyExpression(){return{type:"JSXEmptyExpression"}}function jsxExpressionContainer(expression){const node={type:"JSXExpressionContainer",expression};const defs=NODE_FIELDS.JSXExpressionContainer;validate(defs.expression,node,"expression",expression,1);return node}function jsxSpreadChild(expression){const node={type:"JSXSpreadChild",expression};const defs=NODE_FIELDS.JSXSpreadChild;validate(defs.expression,node,"expression",expression,1);return node}function jsxIdentifier(name){const node={type:"JSXIdentifier",name};const defs=NODE_FIELDS.JSXIdentifier;validate(defs.name,node,"name",name);return node}function jsxMemberExpression(object,property){const node={type:"JSXMemberExpression",object,property};const defs=NODE_FIELDS.JSXMemberExpression;validate(defs.object,node,"object",object,1);validate(defs.property,node,"property",property,1);return node}function jsxNamespacedName(namespace,name){const node={type:"JSXNamespacedName",namespace,name};const defs=NODE_FIELDS.JSXNamespacedName;validate(defs.namespace,node,"namespace",namespace,1);validate(defs.name,node,"name",name,1);return node}function jsxOpeningElement(name,attributes,selfClosing=false){const node={type:"JSXOpeningElement",name,attributes,selfClosing};const defs=NODE_FIELDS.JSXOpeningElement;validate(defs.name,node,"name",name,1);validate(defs.attributes,node,"attributes",attributes,1);validate(defs.selfClosing,node,"selfClosing",selfClosing);return node}function jsxSpreadAttribute(argument){const node={type:"JSXSpreadAttribute",argument};const defs=NODE_FIELDS.JSXSpreadAttribute;validate(defs.argument,node,"argument",argument,1);return node}function jsxText(value){const node={type:"JSXText",value};const defs=NODE_FIELDS.JSXText;validate(defs.value,node,"value",value);return node}function jsxFragment(openingFragment,closingFragment,children){const node={type:"JSXFragment",openingFragment,closingFragment,children};const defs=NODE_FIELDS.JSXFragment;validate(defs.openingFragment,node,"openingFragment",openingFragment,1);validate(defs.closingFragment,node,"closingFragment",closingFragment,1);validate(defs.children,node,"children",children,1);return node}function jsxOpeningFragment(){return{type:"JSXOpeningFragment"}}function jsxClosingFragment(){return{type:"JSXClosingFragment"}}function placeholder(expectedNode,name){const node={type:"Placeholder",expectedNode,name};const defs=NODE_FIELDS.Placeholder;validate(defs.expectedNode,node,"expectedNode",expectedNode);validate(defs.name,node,"name",name,1);return node}function v8IntrinsicIdentifier(name){const node={type:"V8IntrinsicIdentifier",name};const defs=NODE_FIELDS.V8IntrinsicIdentifier;validate(defs.name,node,"name",name);return node}function argumentPlaceholder(){return{type:"ArgumentPlaceholder"}}function bindExpression(object,callee){const node={type:"BindExpression",object,callee};const defs=NODE_FIELDS.BindExpression;validate(defs.object,node,"object",object,1);validate(defs.callee,node,"callee",callee,1);return node}function classAccessorProperty(key,value=null,typeAnnotation=null,decorators=null,computed=false,_static=false){const node={type:"ClassAccessorProperty",key,value,typeAnnotation,decorators,computed,static:_static};const defs=NODE_FIELDS.ClassAccessorProperty;validate(defs.key,node,"key",key,1);validate(defs.value,node,"value",value,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);validate(defs.decorators,node,"decorators",decorators,1);validate(defs.computed,node,"computed",computed);validate(defs.static,node,"static",_static);return node}function decorator(expression){const node={type:"Decorator",expression};const defs=NODE_FIELDS.Decorator;validate(defs.expression,node,"expression",expression,1);return node}function doExpression(body,async=false){const node={type:"DoExpression",body,async};const defs=NODE_FIELDS.DoExpression;validate(defs.body,node,"body",body,1);validate(defs.async,node,"async",async);return node}function exportDefaultSpecifier(exported){const node={type:"ExportDefaultSpecifier",exported};const defs=NODE_FIELDS.ExportDefaultSpecifier;validate(defs.exported,node,"exported",exported,1);return node}function moduleExpression(body){const node={type:"ModuleExpression",body};const defs=NODE_FIELDS.ModuleExpression;validate(defs.body,node,"body",body,1);return node}function topicReference(){return{type:"TopicReference"}}function voidPattern(){return{type:"VoidPattern"}}function structDeclaration(id=null,superClass=null,body){const node={type:"StructDeclaration",id,superClass,body};const defs=NODE_FIELDS.StructDeclaration;validate(defs.id,node,"id",id,1);validate(defs.superClass,node,"superClass",superClass,1);validate(defs.body,node,"body",body,1);return node}function structBody(body){const node={type:"StructBody",body};const defs=NODE_FIELDS.StructBody;validate(defs.body,node,"body",body,1);return node}function tsParameterProperty(parameter){const node={type:"TSParameterProperty",parameter};const defs=NODE_FIELDS.TSParameterProperty;validate(defs.parameter,node,"parameter",parameter,1);return node}function tsDeclareFunction(id=null,typeParameters=null,params,returnType=null){const node={type:"TSDeclareFunction",id,typeParameters,params,returnType,async:false,generator:false};const defs=NODE_FIELDS.TSDeclareFunction;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsDeclareMethod(key,typeParameters=null,params,returnType=null){const node={type:"TSDeclareMethod",key,typeParameters,params,returnType,async:false,computed:false,generator:false,kind:"method",static:false};const defs=NODE_FIELDS.TSDeclareMethod;validate(defs.key,node,"key",key,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsQualifiedName(left,right){const node={type:"TSQualifiedName",left,right};const defs=NODE_FIELDS.TSQualifiedName;validate(defs.left,node,"left",left,1);validate(defs.right,node,"right",right,1);return node}function tsCallSignatureDeclaration(typeParameters=null,params,returnType=null){const node={type:"TSCallSignatureDeclaration",typeParameters,params,returnType};const defs=NODE_FIELDS.TSCallSignatureDeclaration;validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsConstructSignatureDeclaration(typeParameters=null,params,returnType=null){const node={type:"TSConstructSignatureDeclaration",typeParameters,params,returnType};const defs=NODE_FIELDS.TSConstructSignatureDeclaration;validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsPropertySignature(key,typeAnnotation=null){const node={type:"TSPropertySignature",key,typeAnnotation,computed:false};const defs=NODE_FIELDS.TSPropertySignature;validate(defs.key,node,"key",key,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsMethodSignature(key,typeParameters=null,params,returnType=null){const node={type:"TSMethodSignature",key,typeParameters,params,returnType,computed:false,kind:"method"};const defs=NODE_FIELDS.TSMethodSignature;validate(defs.key,node,"key",key,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsIndexSignature(parameters,typeAnnotation=null){const node={type:"TSIndexSignature",parameters,typeAnnotation};const defs=NODE_FIELDS.TSIndexSignature;validate(defs.parameters,node,"parameters",parameters,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsAnyKeyword(){return{type:"TSAnyKeyword"}}function tsBooleanKeyword(){return{type:"TSBooleanKeyword"}}function tsBigIntKeyword(){return{type:"TSBigIntKeyword"}}function tsIntrinsicKeyword(){return{type:"TSIntrinsicKeyword"}}function tsNeverKeyword(){return{type:"TSNeverKeyword"}}function tsNullKeyword(){return{type:"TSNullKeyword"}}function tsNumberKeyword(){return{type:"TSNumberKeyword"}}function tsObjectKeyword(){return{type:"TSObjectKeyword"}}function tsStringKeyword(){return{type:"TSStringKeyword"}}function tsSymbolKeyword(){return{type:"TSSymbolKeyword"}}function tsUndefinedKeyword(){return{type:"TSUndefinedKeyword"}}function tsUnknownKeyword(){return{type:"TSUnknownKeyword"}}function tsVoidKeyword(){return{type:"TSVoidKeyword"}}function tsThisType(){return{type:"TSThisType"}}function tsFunctionType(typeParameters=null,params,returnType=null){const node={type:"TSFunctionType",typeParameters,params,returnType};const defs=NODE_FIELDS.TSFunctionType;validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsConstructorType(typeParameters=null,params,returnType=null){const node={type:"TSConstructorType",typeParameters,params,returnType};const defs=NODE_FIELDS.TSConstructorType;validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.params,node,"params",params,1);validate(defs.returnType,node,"returnType",returnType,1);return node}function tsTypeReference(typeName,typeArguments=null){const node={type:"TSTypeReference",typeName,typeArguments};const defs=NODE_FIELDS.TSTypeReference;validate(defs.typeName,node,"typeName",typeName,1);validate(defs.typeArguments,node,"typeArguments",typeArguments,1);return node}function tsTypePredicate(parameterName,typeAnnotation=null,asserts=null){const node={type:"TSTypePredicate",parameterName,typeAnnotation,asserts};const defs=NODE_FIELDS.TSTypePredicate;validate(defs.parameterName,node,"parameterName",parameterName,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);validate(defs.asserts,node,"asserts",asserts);return node}function tsTypeQuery(exprName,typeArguments=null){const node={type:"TSTypeQuery",exprName,typeArguments};const defs=NODE_FIELDS.TSTypeQuery;validate(defs.exprName,node,"exprName",exprName,1);validate(defs.typeArguments,node,"typeArguments",typeArguments,1);return node}function tsTypeLiteral(members){const node={type:"TSTypeLiteral",members};const defs=NODE_FIELDS.TSTypeLiteral;validate(defs.members,node,"members",members,1);return node}function tsArrayType(elementType){const node={type:"TSArrayType",elementType};const defs=NODE_FIELDS.TSArrayType;validate(defs.elementType,node,"elementType",elementType,1);return node}function tsTupleType(elementTypes){const node={type:"TSTupleType",elementTypes};const defs=NODE_FIELDS.TSTupleType;validate(defs.elementTypes,node,"elementTypes",elementTypes,1);return node}function tsOptionalType(typeAnnotation){const node={type:"TSOptionalType",typeAnnotation};const defs=NODE_FIELDS.TSOptionalType;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsRestType(typeAnnotation){const node={type:"TSRestType",typeAnnotation};const defs=NODE_FIELDS.TSRestType;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsNamedTupleMember(label,elementType,optional=false){const node={type:"TSNamedTupleMember",label,elementType,optional};const defs=NODE_FIELDS.TSNamedTupleMember;validate(defs.label,node,"label",label,1);validate(defs.elementType,node,"elementType",elementType,1);validate(defs.optional,node,"optional",optional);return node}function tsUnionType(types){const node={type:"TSUnionType",types};const defs=NODE_FIELDS.TSUnionType;validate(defs.types,node,"types",types,1);return node}function tsIntersectionType(types){const node={type:"TSIntersectionType",types};const defs=NODE_FIELDS.TSIntersectionType;validate(defs.types,node,"types",types,1);return node}function tsConditionalType(checkType,extendsType,trueType,falseType){const node={type:"TSConditionalType",checkType,extendsType,trueType,falseType};const defs=NODE_FIELDS.TSConditionalType;validate(defs.checkType,node,"checkType",checkType,1);validate(defs.extendsType,node,"extendsType",extendsType,1);validate(defs.trueType,node,"trueType",trueType,1);validate(defs.falseType,node,"falseType",falseType,1);return node}function tsInferType(typeParameter){const node={type:"TSInferType",typeParameter};const defs=NODE_FIELDS.TSInferType;validate(defs.typeParameter,node,"typeParameter",typeParameter,1);return node}function tsParenthesizedType(typeAnnotation){const node={type:"TSParenthesizedType",typeAnnotation};const defs=NODE_FIELDS.TSParenthesizedType;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsTypeOperator(typeAnnotation,operator){const node={type:"TSTypeOperator",typeAnnotation,operator};const defs=NODE_FIELDS.TSTypeOperator;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);validate(defs.operator,node,"operator",operator);return node}function tsIndexedAccessType(objectType,indexType){const node={type:"TSIndexedAccessType",objectType,indexType};const defs=NODE_FIELDS.TSIndexedAccessType;validate(defs.objectType,node,"objectType",objectType,1);validate(defs.indexType,node,"indexType",indexType,1);return node}function tsMappedType(key,constraint,nameType=null,typeAnnotation=null){const node={type:"TSMappedType",key,constraint,nameType,typeAnnotation};const defs=NODE_FIELDS.TSMappedType;validate(defs.key,node,"key",key,1);validate(defs.constraint,node,"constraint",constraint,1);validate(defs.nameType,node,"nameType",nameType,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsTemplateLiteralType(quasis,types){const node={type:"TSTemplateLiteralType",quasis,types};const defs=NODE_FIELDS.TSTemplateLiteralType;validate(defs.quasis,node,"quasis",quasis,1);validate(defs.types,node,"types",types,1);return node}function tsLiteralType(literal){const node={type:"TSLiteralType",literal};const defs=NODE_FIELDS.TSLiteralType;validate(defs.literal,node,"literal",literal,1);return node}function tsClassImplements(expression,typeArguments=null){const node={type:"TSClassImplements",expression,typeArguments};const defs=NODE_FIELDS.TSClassImplements;validate(defs.expression,node,"expression",expression,1);validate(defs.typeArguments,node,"typeArguments",typeArguments,1);return node}function tsInterfaceHeritage(expression,typeArguments=null){const node={type:"TSInterfaceHeritage",expression,typeArguments};const defs=NODE_FIELDS.TSInterfaceHeritage;validate(defs.expression,node,"expression",expression,1);validate(defs.typeArguments,node,"typeArguments",typeArguments,1);return node}function tsInterfaceDeclaration(id,typeParameters=null,_extends=null,body){const node={type:"TSInterfaceDeclaration",id,typeParameters,extends:_extends,body};const defs=NODE_FIELDS.TSInterfaceDeclaration;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.extends,node,"extends",_extends,1);validate(defs.body,node,"body",body,1);return node}function tsInterfaceBody(body){const node={type:"TSInterfaceBody",body};const defs=NODE_FIELDS.TSInterfaceBody;validate(defs.body,node,"body",body,1);return node}function tsTypeAliasDeclaration(id,typeParameters=null,typeAnnotation){const node={type:"TSTypeAliasDeclaration",id,typeParameters,typeAnnotation};const defs=NODE_FIELDS.TSTypeAliasDeclaration;validate(defs.id,node,"id",id,1);validate(defs.typeParameters,node,"typeParameters",typeParameters,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsInstantiationExpression(expression,typeArguments=null){const node={type:"TSInstantiationExpression",expression,typeArguments};const defs=NODE_FIELDS.TSInstantiationExpression;validate(defs.expression,node,"expression",expression,1);validate(defs.typeArguments,node,"typeArguments",typeArguments,1);return node}function tsAsExpression(expression,typeAnnotation){const node={type:"TSAsExpression",expression,typeAnnotation};const defs=NODE_FIELDS.TSAsExpression;validate(defs.expression,node,"expression",expression,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsSatisfiesExpression(expression,typeAnnotation){const node={type:"TSSatisfiesExpression",expression,typeAnnotation};const defs=NODE_FIELDS.TSSatisfiesExpression;validate(defs.expression,node,"expression",expression,1);validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsTypeAssertion(typeAnnotation,expression){const node={type:"TSTypeAssertion",typeAnnotation,expression};const defs=NODE_FIELDS.TSTypeAssertion;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);validate(defs.expression,node,"expression",expression,1);return node}function tsEnumBody(members){const node={type:"TSEnumBody",members};const defs=NODE_FIELDS.TSEnumBody;validate(defs.members,node,"members",members,1);return node}function tsEnumDeclaration(id,body){const node={type:"TSEnumDeclaration",id,body};const defs=NODE_FIELDS.TSEnumDeclaration;validate(defs.id,node,"id",id,1);validate(defs.body,node,"body",body,1);return node}function tsEnumMember(id,initializer=null){const node={type:"TSEnumMember",id,initializer};const defs=NODE_FIELDS.TSEnumMember;validate(defs.id,node,"id",id,1);validate(defs.initializer,node,"initializer",initializer,1);return node}function tsModuleDeclaration(id,body){const node={type:"TSModuleDeclaration",id,body,kind:"namespace"};const defs=NODE_FIELDS.TSModuleDeclaration;validate(defs.id,node,"id",id,1);validate(defs.body,node,"body",body,1);return node}function tsModuleBlock(body){const node={type:"TSModuleBlock",body};const defs=NODE_FIELDS.TSModuleBlock;validate(defs.body,node,"body",body,1);return node}function tsImportType(source,qualifier=null,typeArguments=null){const node={type:"TSImportType",source,qualifier,typeArguments};const defs=NODE_FIELDS.TSImportType;validate(defs.source,node,"source",source,1);validate(defs.qualifier,node,"qualifier",qualifier,1);validate(defs.typeArguments,node,"typeArguments",typeArguments,1);return node}function tsImportEqualsDeclaration(id,moduleReference){const node={type:"TSImportEqualsDeclaration",id,moduleReference};const defs=NODE_FIELDS.TSImportEqualsDeclaration;validate(defs.id,node,"id",id,1);validate(defs.moduleReference,node,"moduleReference",moduleReference,1);return node}function tsExternalModuleReference(expression){const node={type:"TSExternalModuleReference",expression};const defs=NODE_FIELDS.TSExternalModuleReference;validate(defs.expression,node,"expression",expression,1);return node}function tsNonNullExpression(expression){const node={type:"TSNonNullExpression",expression};const defs=NODE_FIELDS.TSNonNullExpression;validate(defs.expression,node,"expression",expression,1);return node}function tsExportAssignment(expression){const node={type:"TSExportAssignment",expression};const defs=NODE_FIELDS.TSExportAssignment;validate(defs.expression,node,"expression",expression,1);return node}function tsNamespaceExportDeclaration(id){const node={type:"TSNamespaceExportDeclaration",id};const defs=NODE_FIELDS.TSNamespaceExportDeclaration;validate(defs.id,node,"id",id,1);return node}function tsTypeAnnotation(typeAnnotation){const node={type:"TSTypeAnnotation",typeAnnotation};const defs=NODE_FIELDS.TSTypeAnnotation;validate(defs.typeAnnotation,node,"typeAnnotation",typeAnnotation,1);return node}function tsTypeParameterInstantiation(params){const node={type:"TSTypeParameterInstantiation",params};const defs=NODE_FIELDS.TSTypeParameterInstantiation;validate(defs.params,node,"params",params,1);return node}function tsTypeParameterDeclaration(params){const node={type:"TSTypeParameterDeclaration",params};const defs=NODE_FIELDS.TSTypeParameterDeclaration;validate(defs.params,node,"params",params,1);return node}function tsTypeParameter(constraint=null,_default=null,name){const node={type:"TSTypeParameter",constraint,default:_default,name};const defs=NODE_FIELDS.TSTypeParameter;validate(defs.constraint,node,"constraint",constraint,1);validate(defs.default,node,"default",_default,1);validate(defs.name,node,"name",name,1);return node}function NumberLiteral(value){deprecationWarning("NumberLiteral","NumericLiteral","The node type ");return numericLiteral(value)}function RegexLiteral(pattern,flags=""){deprecationWarning("RegexLiteral","RegExpLiteral","The node type ");return regExpLiteral(pattern,flags)}function RestProperty(argument){deprecationWarning("RestProperty","RestElement","The node type ");return restElement(argument)}function SpreadProperty(argument){deprecationWarning("SpreadProperty","SpreadElement","The node type ");return spreadElement(argument)}var b=Object.defineProperty({__proto__:null,anyTypeAnnotation,argumentPlaceholder,arrayExpression,arrayPattern,arrayTypeAnnotation,arrowFunctionExpression,assignmentExpression,assignmentPattern,awaitExpression,bigIntLiteral,bigIntLiteralTypeAnnotation,binaryExpression,bindExpression,blockStatement,booleanLiteral,booleanLiteralTypeAnnotation,booleanTypeAnnotation,breakStatement,callExpression,catchClause,classAccessorProperty,classBody,classDeclaration,classExpression,classImplements,classMethod,classPrivateMethod,classPrivateProperty,classProperty,conditionalExpression,continueStatement,debuggerStatement,declareClass,declareExportAllDeclaration,declareExportDeclaration,declareFunction,declareInterface,declareModule,declareModuleExports,declareOpaqueType,declareTypeAlias,declareVariable,declaredPredicate,decorator,directive,directiveLiteral,doExpression,doWhileStatement,emptyStatement,emptyTypeAnnotation,enumBooleanBody,enumBooleanMember,enumDeclaration,enumDefaultedMember,enumNumberBody,enumNumberMember,enumStringBody,enumStringMember,enumSymbolBody,existsTypeAnnotation,exportAllDeclaration,exportDefaultDeclaration,exportDefaultSpecifier,exportNamedDeclaration,exportNamespaceSpecifier,exportSpecifier,expressionStatement,file,forInStatement,forOfStatement,forStatement,functionDeclaration,functionExpression,functionTypeAnnotation,functionTypeParam,genericTypeAnnotation,identifier,ifStatement,import:_import,importAttribute,importDeclaration,importDefaultSpecifier,importExpression,importNamespaceSpecifier,importSpecifier,indexedAccessType,inferredPredicate,interfaceDeclaration,interfaceExtends,interfaceTypeAnnotation,interpreterDirective,intersectionTypeAnnotation,jsxAttribute,jsxClosingElement,jsxClosingFragment,jsxElement,jsxEmptyExpression,jsxExpressionContainer,jsxFragment,jsxIdentifier,jsxMemberExpression,jsxNamespacedName,jsxOpeningElement,jsxOpeningFragment,jsxSpreadAttribute,jsxSpreadChild,jsxText,labeledStatement,logicalExpression,memberExpression,metaProperty,mixedTypeAnnotation,moduleExpression,newExpression,nullLiteral,nullLiteralTypeAnnotation,nullableTypeAnnotation,numberLiteral:NumberLiteral,numberLiteralTypeAnnotation,numberTypeAnnotation,numericLiteral,objectExpression,objectMethod,objectPattern,objectProperty,objectTypeAnnotation,objectTypeCallProperty,objectTypeIndexer,objectTypeInternalSlot,objectTypeProperty,objectTypeSpreadProperty,opaqueType,optionalCallExpression,optionalIndexedAccessType,optionalMemberExpression,parenthesizedExpression,placeholder,privateName,program,qualifiedTypeIdentifier,regExpLiteral,regexLiteral:RegexLiteral,restElement,restProperty:RestProperty,returnStatement,sequenceExpression,spreadElement,spreadProperty:SpreadProperty,staticBlock,stringLiteral,stringLiteralTypeAnnotation,stringTypeAnnotation,structBody,structDeclaration,super:_super,switchCase,switchStatement,symbolTypeAnnotation,taggedTemplateExpression,templateElement,templateLiteral,thisExpression,thisTypeAnnotation,throwStatement,topicReference,tryStatement,tsAnyKeyword,tsArrayType,tsAsExpression,tsBigIntKeyword,tsBooleanKeyword,tsCallSignatureDeclaration,tsClassImplements,tsConditionalType,tsConstructSignatureDeclaration,tsConstructorType,tsDeclareFunction,tsDeclareMethod,tsEnumBody,tsEnumDeclaration,tsEnumMember,tsExportAssignment,tsExternalModuleReference,tsFunctionType,tsImportEqualsDeclaration,tsImportType,tsIndexSignature,tsIndexedAccessType,tsInferType,tsInstantiationExpression,tsInterfaceBody,tsInterfaceDeclaration,tsInterfaceHeritage,tsIntersectionType,tsIntrinsicKeyword,tsLiteralType,tsMappedType,tsMethodSignature,tsModuleBlock,tsModuleDeclaration,tsNamedTupleMember,tsNamespaceExportDeclaration,tsNeverKeyword,tsNonNullExpression,tsNullKeyword,tsNumberKeyword,tsObjectKeyword,tsOptionalType,tsParameterProperty,tsParenthesizedType,tsPropertySignature,tsQualifiedName,tsRestType,tsSatisfiesExpression,tsStringKeyword,tsSymbolKeyword,tsTemplateLiteralType,tsThisType,tsTupleType,tsTypeAliasDeclaration,tsTypeAnnotation,tsTypeAssertion,tsTypeLiteral,tsTypeOperator,tsTypeParameter,tsTypeParameterDeclaration,tsTypeParameterInstantiation,tsTypePredicate,tsTypeQuery,tsTypeReference,tsUndefinedKeyword,tsUnionType,tsUnknownKeyword,tsVoidKeyword,tupleTypeAnnotation,typeAlias,typeAnnotation,typeCastExpression,typeParameter,typeParameterDeclaration,typeParameterInstantiation,typeofTypeAnnotation,unaryExpression,unionTypeAnnotation,updateExpression,v8IntrinsicIdentifier,variableDeclaration,variableDeclarator,variance,voidPattern,voidTypeAnnotation,whileStatement,withStatement,yieldExpression},Symbol.toStringTag,{value:"Module"});function alias(lowercase){return function(){deprecationWarning(lowercase.replace(/^(?:ts|jsx|[a-z])/,(x)=>x.toUpperCase()),lowercase,"Usage of builders starting with an uppercase letter such as ","uppercase builders");return b[lowercase](...arguments)}}var ArrayExpression=alias("arrayExpression");var AssignmentExpression=alias("assignmentExpression");var BinaryExpression=alias("binaryExpression");var InterpreterDirective=alias("interpreterDirective");var Directive=alias("directive");var DirectiveLiteral=alias("directiveLiteral");var BlockStatement=alias("blockStatement");var BreakStatement=alias("breakStatement");var CallExpression=alias("callExpression");var CatchClause=alias("catchClause");var ConditionalExpression=alias("conditionalExpression");var ContinueStatement=alias("continueStatement");var DebuggerStatement=alias("debuggerStatement");var DoWhileStatement=alias("doWhileStatement");var EmptyStatement=alias("emptyStatement");var ExpressionStatement=alias("expressionStatement");var File=alias("file");var ForInStatement=alias("forInStatement");var ForStatement=alias("forStatement");var FunctionDeclaration=alias("functionDeclaration");var FunctionExpression=alias("functionExpression");var Identifier=alias("identifier");var IfStatement=alias("ifStatement");var LabeledStatement=alias("labeledStatement");var StringLiteral=alias("stringLiteral");var NumericLiteral=alias("numericLiteral");var NullLiteral=alias("nullLiteral");var BooleanLiteral=alias("booleanLiteral");var RegExpLiteral=alias("regExpLiteral");var LogicalExpression=alias("logicalExpression");var MemberExpression=alias("memberExpression");var NewExpression=alias("newExpression");var Program=alias("program");var ObjectExpression=alias("objectExpression");var ObjectMethod=alias("objectMethod");var ObjectProperty=alias("objectProperty");var RestElement=alias("restElement");var ReturnStatement=alias("returnStatement");var SequenceExpression=alias("sequenceExpression");var ParenthesizedExpression=alias("parenthesizedExpression");var SwitchCase=alias("switchCase");var SwitchStatement=alias("switchStatement");var ThisExpression=alias("thisExpression");var ThrowStatement=alias("throwStatement");var TryStatement=alias("tryStatement");var UnaryExpression=alias("unaryExpression");var UpdateExpression=alias("updateExpression");var VariableDeclaration=alias("variableDeclaration");var VariableDeclarator=alias("variableDeclarator");var WhileStatement=alias("whileStatement");var WithStatement=alias("withStatement");var AssignmentPattern=alias("assignmentPattern");var ArrayPattern=alias("arrayPattern");var ArrowFunctionExpression=alias("arrowFunctionExpression");var ClassBody=alias("classBody");var ClassExpression=alias("classExpression");var ClassDeclaration=alias("classDeclaration");var ExportAllDeclaration=alias("exportAllDeclaration");var ExportDefaultDeclaration=alias("exportDefaultDeclaration");var ExportNamedDeclaration=alias("exportNamedDeclaration");var ExportSpecifier=alias("exportSpecifier");var ForOfStatement=alias("forOfStatement");var ImportDeclaration=alias("importDeclaration");var ImportDefaultSpecifier=alias("importDefaultSpecifier");var ImportNamespaceSpecifier=alias("importNamespaceSpecifier");var ImportSpecifier=alias("importSpecifier");var MetaProperty=alias("metaProperty");var ClassMethod=alias("classMethod");var ObjectPattern=alias("objectPattern");var SpreadElement=alias("spreadElement");var Super=alias("super");var TaggedTemplateExpression=alias("taggedTemplateExpression");var TemplateElement=alias("templateElement");var TemplateLiteral=alias("templateLiteral");var YieldExpression=alias("yieldExpression");var AwaitExpression=alias("awaitExpression");var ImportExpression=alias("importExpression");var Import=alias("import");var BigIntLiteral=alias("bigIntLiteral");var ExportNamespaceSpecifier=alias("exportNamespaceSpecifier");var OptionalMemberExpression=alias("optionalMemberExpression");var OptionalCallExpression=alias("optionalCallExpression");var ClassProperty=alias("classProperty");var ClassPrivateProperty=alias("classPrivateProperty");var ClassPrivateMethod=alias("classPrivateMethod");var PrivateName=alias("privateName");var StaticBlock=alias("staticBlock");var ImportAttribute=alias("importAttribute");var AnyTypeAnnotation=alias("anyTypeAnnotation");var ArrayTypeAnnotation=alias("arrayTypeAnnotation");var BooleanTypeAnnotation=alias("booleanTypeAnnotation");var BooleanLiteralTypeAnnotation=alias("booleanLiteralTypeAnnotation");var NullLiteralTypeAnnotation=alias("nullLiteralTypeAnnotation");var ClassImplements=alias("classImplements");var DeclareClass=alias("declareClass");var DeclareFunction=alias("declareFunction");var DeclareInterface=alias("declareInterface");var DeclareModule=alias("declareModule");var DeclareModuleExports=alias("declareModuleExports");var DeclareTypeAlias=alias("declareTypeAlias");var DeclareOpaqueType=alias("declareOpaqueType");var DeclareVariable=alias("declareVariable");var DeclareExportDeclaration=alias("declareExportDeclaration");var DeclareExportAllDeclaration=alias("declareExportAllDeclaration");var DeclaredPredicate=alias("declaredPredicate");var ExistsTypeAnnotation=alias("existsTypeAnnotation");var FunctionTypeAnnotation=alias("functionTypeAnnotation");var FunctionTypeParam=alias("functionTypeParam");var GenericTypeAnnotation=alias("genericTypeAnnotation");var InferredPredicate=alias("inferredPredicate");var InterfaceExtends=alias("interfaceExtends");var InterfaceDeclaration=alias("interfaceDeclaration");var InterfaceTypeAnnotation=alias("interfaceTypeAnnotation");var IntersectionTypeAnnotation=alias("intersectionTypeAnnotation");var MixedTypeAnnotation=alias("mixedTypeAnnotation");var EmptyTypeAnnotation=alias("emptyTypeAnnotation");var NullableTypeAnnotation=alias("nullableTypeAnnotation");var NumberLiteralTypeAnnotation=alias("numberLiteralTypeAnnotation");var BigIntLiteralTypeAnnotation=alias("bigIntLiteralTypeAnnotation");var NumberTypeAnnotation=alias("numberTypeAnnotation");var ObjectTypeAnnotation=alias("objectTypeAnnotation");var ObjectTypeInternalSlot=alias("objectTypeInternalSlot");var ObjectTypeCallProperty=alias("objectTypeCallProperty");var ObjectTypeIndexer=alias("objectTypeIndexer");var ObjectTypeProperty=alias("objectTypeProperty");var ObjectTypeSpreadProperty=alias("objectTypeSpreadProperty");var OpaqueType=alias("opaqueType");var QualifiedTypeIdentifier=alias("qualifiedTypeIdentifier");var StringLiteralTypeAnnotation=alias("stringLiteralTypeAnnotation");var StringTypeAnnotation=alias("stringTypeAnnotation");var SymbolTypeAnnotation=alias("symbolTypeAnnotation");var ThisTypeAnnotation=alias("thisTypeAnnotation");var TupleTypeAnnotation=alias("tupleTypeAnnotation");var TypeofTypeAnnotation=alias("typeofTypeAnnotation");var TypeAlias=alias("typeAlias");var TypeAnnotation=alias("typeAnnotation");var TypeCastExpression=alias("typeCastExpression");var TypeParameter=alias("typeParameter");var TypeParameterDeclaration=alias("typeParameterDeclaration");var TypeParameterInstantiation=alias("typeParameterInstantiation");var UnionTypeAnnotation=alias("unionTypeAnnotation");var Variance=alias("variance");var VoidTypeAnnotation=alias("voidTypeAnnotation");var EnumDeclaration=alias("enumDeclaration");var EnumBooleanBody=alias("enumBooleanBody");var EnumNumberBody=alias("enumNumberBody");var EnumStringBody=alias("enumStringBody");var EnumSymbolBody=alias("enumSymbolBody");var EnumBooleanMember=alias("enumBooleanMember");var EnumNumberMember=alias("enumNumberMember");var EnumStringMember=alias("enumStringMember");var EnumDefaultedMember=alias("enumDefaultedMember");var IndexedAccessType=alias("indexedAccessType");var OptionalIndexedAccessType=alias("optionalIndexedAccessType");var JSXAttribute=alias("jsxAttribute");var JSXClosingElement=alias("jsxClosingElement");var JSXElement=alias("jsxElement");var JSXEmptyExpression=alias("jsxEmptyExpression");var JSXExpressionContainer=alias("jsxExpressionContainer");var JSXSpreadChild=alias("jsxSpreadChild");var JSXIdentifier=alias("jsxIdentifier");var JSXMemberExpression=alias("jsxMemberExpression");var JSXNamespacedName=alias("jsxNamespacedName");var JSXOpeningElement=alias("jsxOpeningElement");var JSXSpreadAttribute=alias("jsxSpreadAttribute");var JSXText=alias("jsxText");var JSXFragment=alias("jsxFragment");var JSXOpeningFragment=alias("jsxOpeningFragment");var JSXClosingFragment=alias("jsxClosingFragment");var Placeholder=alias("placeholder");var V8IntrinsicIdentifier=alias("v8IntrinsicIdentifier");var ArgumentPlaceholder=alias("argumentPlaceholder");var BindExpression=alias("bindExpression");var ClassAccessorProperty=alias("classAccessorProperty");var Decorator=alias("decorator");var DoExpression=alias("doExpression");var ExportDefaultSpecifier=alias("exportDefaultSpecifier");var ModuleExpression=alias("moduleExpression");var TopicReference=alias("topicReference");var VoidPattern=alias("voidPattern");var StructDeclaration=alias("structDeclaration");var StructBody=alias("structBody");var TSParameterProperty=alias("tsParameterProperty");var TSDeclareFunction=alias("tsDeclareFunction");var TSDeclareMethod=alias("tsDeclareMethod");var TSQualifiedName=alias("tsQualifiedName");var TSCallSignatureDeclaration=alias("tsCallSignatureDeclaration");var TSConstructSignatureDeclaration=alias("tsConstructSignatureDeclaration");var TSPropertySignature=alias("tsPropertySignature");var TSMethodSignature=alias("tsMethodSignature");var TSIndexSignature=alias("tsIndexSignature");var TSAnyKeyword=alias("tsAnyKeyword");var TSBooleanKeyword=alias("tsBooleanKeyword");var TSBigIntKeyword=alias("tsBigIntKeyword");var TSIntrinsicKeyword=alias("tsIntrinsicKeyword");var TSNeverKeyword=alias("tsNeverKeyword");var TSNullKeyword=alias("tsNullKeyword");var TSNumberKeyword=alias("tsNumberKeyword");var TSObjectKeyword=alias("tsObjectKeyword");var TSStringKeyword=alias("tsStringKeyword");var TSSymbolKeyword=alias("tsSymbolKeyword");var TSUndefinedKeyword=alias("tsUndefinedKeyword");var TSUnknownKeyword=alias("tsUnknownKeyword");var TSVoidKeyword=alias("tsVoidKeyword");var TSThisType=alias("tsThisType");var TSFunctionType=alias("tsFunctionType");var TSConstructorType=alias("tsConstructorType");var TSTypeReference=alias("tsTypeReference");var TSTypePredicate=alias("tsTypePredicate");var TSTypeQuery=alias("tsTypeQuery");var TSTypeLiteral=alias("tsTypeLiteral");var TSArrayType=alias("tsArrayType");var TSTupleType=alias("tsTupleType");var TSOptionalType=alias("tsOptionalType");var TSRestType=alias("tsRestType");var TSNamedTupleMember=alias("tsNamedTupleMember");var TSUnionType=alias("tsUnionType");var TSIntersectionType=alias("tsIntersectionType");var TSConditionalType=alias("tsConditionalType");var TSInferType=alias("tsInferType");var TSParenthesizedType=alias("tsParenthesizedType");var TSTypeOperator=alias("tsTypeOperator");var TSIndexedAccessType=alias("tsIndexedAccessType");var TSMappedType=alias("tsMappedType");var TSTemplateLiteralType=alias("tsTemplateLiteralType");var TSLiteralType=alias("tsLiteralType");var TSClassImplements=alias("tsClassImplements");var TSInterfaceHeritage=alias("tsInterfaceHeritage");var TSInterfaceDeclaration=alias("tsInterfaceDeclaration");var TSInterfaceBody=alias("tsInterfaceBody");var TSTypeAliasDeclaration=alias("tsTypeAliasDeclaration");var TSInstantiationExpression=alias("tsInstantiationExpression");var TSAsExpression=alias("tsAsExpression");var TSSatisfiesExpression=alias("tsSatisfiesExpression");var TSTypeAssertion=alias("tsTypeAssertion");var TSEnumBody=alias("tsEnumBody");var TSEnumDeclaration=alias("tsEnumDeclaration");var TSEnumMember=alias("tsEnumMember");var TSModuleDeclaration=alias("tsModuleDeclaration");var TSModuleBlock=alias("tsModuleBlock");var TSImportType=alias("tsImportType");var TSImportEqualsDeclaration=alias("tsImportEqualsDeclaration");var TSExternalModuleReference=alias("tsExternalModuleReference");var TSNonNullExpression=alias("tsNonNullExpression");var TSExportAssignment=alias("tsExportAssignment");var TSNamespaceExportDeclaration=alias("tsNamespaceExportDeclaration");var TSTypeAnnotation=alias("tsTypeAnnotation");var TSTypeParameterInstantiation=alias("tsTypeParameterInstantiation");var TSTypeParameterDeclaration=alias("tsTypeParameterDeclaration");var TSTypeParameter=alias("tsTypeParameter");var{hasOwn}=Object;function cloneIfNode(obj,deep,withoutLoc,commentsCache){if(obj&&typeof obj.type==="string"){return cloneNodeInternal(obj,deep,withoutLoc,commentsCache)}return obj}function cloneIfNodeOrArray(obj,deep,withoutLoc,commentsCache){if(Array.isArray(obj)){return obj.map((node)=>cloneIfNode(node,deep,withoutLoc,commentsCache))}return cloneIfNode(obj,deep,withoutLoc,commentsCache)}function cloneNode(node,deep=true,withoutLoc=false){if(!node)return node;return cloneNodeInternal(node,deep,withoutLoc,new Map)}function cloneNodeInternal(node,deep=true,withoutLoc=false,commentsCache){if(!node)return node;const{type}=node;const newNode={type:node.type};if(isIdentifier(node)){newNode.name=node.name;if(hasOwn(node,"optional")&&typeof node.optional==="boolean"){newNode.optional=node.optional}if(hasOwn(node,"typeAnnotation")){newNode.typeAnnotation=deep?cloneIfNodeOrArray(node.typeAnnotation,true,withoutLoc,commentsCache):node.typeAnnotation}if(hasOwn(node,"decorators")){newNode.decorators=deep?cloneIfNodeOrArray(node.decorators,true,withoutLoc,commentsCache):node.decorators}}else if(!hasOwn(NODE_FIELDS$1,type)){throw new Error(`Unknown node type: "${type}"`)}else{for(const field of Object.keys(NODE_FIELDS$1[type])){if(hasOwn(node,field)){if(deep){newNode[field]=isFile(node)&&field==="comments"?maybeCloneComments(node.comments,deep,withoutLoc,commentsCache):cloneIfNodeOrArray(node[field],true,withoutLoc,commentsCache)}else{newNode[field]=node[field]}}}}if(hasOwn(node,"loc")){if(withoutLoc){newNode.loc=null}else{newNode.loc=node.loc}}if(hasOwn(node,"leadingComments")){newNode.leadingComments=maybeCloneComments(node.leadingComments,deep,withoutLoc,commentsCache)}if(hasOwn(node,"innerComments")){newNode.innerComments=maybeCloneComments(node.innerComments,deep,withoutLoc,commentsCache)}if(hasOwn(node,"trailingComments")){newNode.trailingComments=maybeCloneComments(node.trailingComments,deep,withoutLoc,commentsCache)}if(hasOwn(node,"extra")){newNode.extra={...node.extra}}return newNode}function maybeCloneComments(comments,deep,withoutLoc,commentsCache){if(!comments||!deep){return comments}return comments.map((comment)=>{const cache=commentsCache.get(comment);if(cache)return cache;const{type,value,loc}=comment;const ret={type,value,loc};if(withoutLoc){ret.loc=undefined}commentsCache.set(comment,ret);return ret})}var STANDARDIZED_TYPES=FLIPPED_ALIAS_KEYS["Standardized"];var EXPRESSION_TYPES=FLIPPED_ALIAS_KEYS["Expression"];var BINARY_TYPES=FLIPPED_ALIAS_KEYS["Binary"];var SCOPABLE_TYPES=FLIPPED_ALIAS_KEYS["Scopable"];var BLOCKPARENT_TYPES=FLIPPED_ALIAS_KEYS["BlockParent"];var BLOCK_TYPES=FLIPPED_ALIAS_KEYS["Block"];var STATEMENT_TYPES=FLIPPED_ALIAS_KEYS["Statement"];var TERMINATORLESS_TYPES=FLIPPED_ALIAS_KEYS["Terminatorless"];var COMPLETIONSTATEMENT_TYPES=FLIPPED_ALIAS_KEYS["CompletionStatement"];var CONDITIONAL_TYPES=FLIPPED_ALIAS_KEYS["Conditional"];var LOOP_TYPES=FLIPPED_ALIAS_KEYS["Loop"];var WHILE_TYPES=FLIPPED_ALIAS_KEYS["While"];var EXPRESSIONWRAPPER_TYPES=FLIPPED_ALIAS_KEYS["ExpressionWrapper"];var FOR_TYPES=FLIPPED_ALIAS_KEYS["For"];var FORXSTATEMENT_TYPES=FLIPPED_ALIAS_KEYS["ForXStatement"];var FUNCTION_TYPES=FLIPPED_ALIAS_KEYS["Function"];var FUNCTIONPARENT_TYPES=FLIPPED_ALIAS_KEYS["FunctionParent"];var PUREISH_TYPES=FLIPPED_ALIAS_KEYS["Pureish"];var DECLARATION_TYPES=FLIPPED_ALIAS_KEYS["Declaration"];var FUNCTIONPARAMETER_TYPES=FLIPPED_ALIAS_KEYS["FunctionParameter"];var PATTERNLIKE_TYPES=FLIPPED_ALIAS_KEYS["PatternLike"];var LVAL_TYPES=FLIPPED_ALIAS_KEYS["LVal"];var TSENTITYNAME_TYPES=FLIPPED_ALIAS_KEYS["TSEntityName"];var LITERAL_TYPES=FLIPPED_ALIAS_KEYS["Literal"];var IMMUTABLE_TYPES=FLIPPED_ALIAS_KEYS["Immutable"];var USERWHITESPACABLE_TYPES=FLIPPED_ALIAS_KEYS["UserWhitespacable"];var METHOD_TYPES=FLIPPED_ALIAS_KEYS["Method"];var OBJECTMEMBER_TYPES=FLIPPED_ALIAS_KEYS["ObjectMember"];var PROPERTY_TYPES=FLIPPED_ALIAS_KEYS["Property"];var UNARYLIKE_TYPES=FLIPPED_ALIAS_KEYS["UnaryLike"];var PATTERN_TYPES=FLIPPED_ALIAS_KEYS["Pattern"];var CLASS_TYPES=FLIPPED_ALIAS_KEYS["Class"];var IMPORTOREXPORTDECLARATION_TYPES=FLIPPED_ALIAS_KEYS["ImportOrExportDeclaration"];var EXPORTDECLARATION_TYPES=FLIPPED_ALIAS_KEYS["ExportDeclaration"];var MODULESPECIFIER_TYPES=FLIPPED_ALIAS_KEYS["ModuleSpecifier"];var PRIVATE_TYPES=FLIPPED_ALIAS_KEYS["Private"];var FLOW_TYPES=FLIPPED_ALIAS_KEYS["Flow"];var FLOWTYPE_TYPES=FLIPPED_ALIAS_KEYS["FlowType"];var FLOWBASEANNOTATION_TYPES=FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"];var FLOWDECLARATION_TYPES=FLIPPED_ALIAS_KEYS["FlowDeclaration"];var FLOWPREDICATE_TYPES=FLIPPED_ALIAS_KEYS["FlowPredicate"];var ENUMBODY_TYPES=FLIPPED_ALIAS_KEYS["EnumBody"];var ENUMMEMBER_TYPES=FLIPPED_ALIAS_KEYS["EnumMember"];var JSX_TYPES=FLIPPED_ALIAS_KEYS["JSX"];var MISCELLANEOUS_TYPES=FLIPPED_ALIAS_KEYS["Miscellaneous"];var ACCESSOR_TYPES=FLIPPED_ALIAS_KEYS["Accessor"];var TYPESCRIPT_TYPES=FLIPPED_ALIAS_KEYS["TypeScript"];var TSTYPEELEMENT_TYPES=FLIPPED_ALIAS_KEYS["TSTypeElement"];var TSTYPE_TYPES=FLIPPED_ALIAS_KEYS["TSType"];var TSBASETYPE_TYPES=FLIPPED_ALIAS_KEYS["TSBaseType"];var _skip=Symbol();var _stop=Symbol();function traverseFast(node,enter,opts){if(!node)return false;const keys=VISITOR_KEYS[node.type];if(!keys)return false;opts=opts||{};const ret=enter(node,opts);if(ret!==undefined){switch(ret){case _skip:return false;case _stop:return true}}for(const key of keys){const subNode=node[key];if(!subNode)continue;if(Array.isArray(subNode)){for(const node of subNode){if(traverseFast(node,enter,opts))return true}}else{if(traverseFast(subNode,enter,opts))return true}}return false}traverseFast.skip=_skip;traverseFast.stop=_stop;var CLEAR_KEYS=["tokens","start","end","loc","raw","rawValue"];var CLEAR_KEYS_PLUS_COMMENTS=[...COMMENT_KEYS,"comments",...CLEAR_KEYS];function removeProperties(node,opts={}){const map=opts.preserveComments?CLEAR_KEYS:CLEAR_KEYS_PLUS_COMMENTS;for(const key of map){if(node[key]!=null)node[key]=undefined}for(const key of Object.keys(node)){if(key.startsWith("_")&&node[key]!=null)node[key]=undefined}const symbols=Object.getOwnPropertySymbols(node);for(const sym of symbols){node[sym]=null}}function removePropertiesDeep(tree,opts){traverseFast(tree,removeProperties,opts);return tree}function toKeyAlias(node,key=node.key){let alias;if(node.kind==="method"){return toKeyAlias.increment()+""}else if(isIdentifier(key)){alias=key.name}else if(isStringLiteral(key)){alias=JSON.stringify(key.value)}else{alias=JSON.stringify(removePropertiesDeep(cloneNode(key)))}if(node.computed){alias=`[${alias}]`}if(node.static){alias=`static:${alias}`}return alias}toKeyAlias.uid=0;toKeyAlias.increment=function(){if(toKeyAlias.uid>=Number.MAX_SAFE_INTEGER){return toKeyAlias.uid=0}else{return toKeyAlias.uid++}};var objectToString=Function.call.bind(Object.prototype.toString);function getBindingIdentifiers(node,duplicates,outerOnly,newBindingsOnly){const search=[].concat(node);const ids=Object.create(null);while(search.length){const id=search.shift();if(!id)continue;if(newBindingsOnly&&(isAssignmentExpression(id)||isUnaryExpression(id)||isUpdateExpression(id))){continue}if(isIdentifier(id)){if(duplicates){const _ids=ids[id.name]=ids[id.name]||[];_ids.push(id)}else{ids[id.name]=id}continue}if(isExportDeclaration(id)&&!isExportAllDeclaration(id)){if(isDeclaration(id.declaration)){search.push(id.declaration)}continue}if(outerOnly){if(isFunctionDeclaration(id)){search.push(id.id);continue}if(isFunctionExpression(id)||isClassExpression(id)){continue}}const keys=getBindingIdentifiers.keys[id.type];if(keys){for(let i=0;i<keys.length;i++){const key=keys[i];const nodes=id[key];if(nodes){if(Array.isArray(nodes)){search.push(...nodes)}else{search.push(nodes)}}}}}return ids}var keys={DeclareClass:["id"],DeclareFunction:["id"],DeclareModule:["id"],DeclareVariable:["id"],DeclareInterface:["id"],DeclareTypeAlias:["id"],DeclareOpaqueType:["id"],InterfaceDeclaration:["id"],TypeAlias:["id"],OpaqueType:["id"],CatchClause:["param"],LabeledStatement:["label"],UnaryExpression:["argument"],AssignmentExpression:["left"],ImportSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportDefaultSpecifier:["local"],ImportDeclaration:["specifiers"],TSImportEqualsDeclaration:["id"],ExportSpecifier:["exported"],ExportNamespaceSpecifier:["exported"],ExportDefaultSpecifier:["exported"],FunctionDeclaration:["id","params"],FunctionExpression:["id","params"],ArrowFunctionExpression:["params"],ObjectMethod:["params"],ClassMethod:["params"],ClassPrivateMethod:["params"],ForInStatement:["left"],ForOfStatement:["left"],ClassDeclaration:["id"],ClassExpression:["id"],RestElement:["argument"],UpdateExpression:["argument"],ObjectProperty:["value"],AssignmentPattern:["left"],ArrayPattern:["elements"],ObjectPattern:["properties"],VariableDeclaration:["declarations"],VariableDeclarator:["id"]};getBindingIdentifiers.keys=keys;function getOuterBindingIdentifiers(node,duplicates){return getBindingIdentifiers(node,duplicates,true)}var RESERVED_WORDS_ES3_ONLY=new Set(["abstract","boolean","byte","char","double","enum","final","float","goto","implements","int","interface","long","native","package","private","protected","public","short","static","synchronized","throws","transient","volatile"]);function literalInitializer(node){if(!node)return false;switch(node.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":case"BigIntLiteral":case"NullLiteral":return true;case"TemplateLiteral":return node.expressions.length===0;case"UnaryExpression":return node.operator==="-"&&(node.argument.type==="BigIntLiteral"||node.argument.type==="NumericLiteral");case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return literalInitializer(node.expression);default:return false}}function writesBinding(target,name){switch(target.type){case"Identifier":return target.name===name;case"MemberExpression":case"OptionalMemberExpression":case"VariableDeclaration":return false;case"ObjectPattern":return target.properties.some((p)=>writesBinding(p.type==="RestElement"?p.argument:p.value,name));case"ArrayPattern":return target.elements.some((item)=>item!==null&&writesBinding(item,name));case"RestElement":return writesBinding(target.argument,name);case"AssignmentPattern":return writesBinding(target.left,name);case"ParenthesizedExpression":case"TSAsExpression":case"TSInstantiationExpression":case"TSNonNullExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return writesBinding(target.expression,name);default:return true}}function checkSibling(file,fn,subject){const hasLocalParameter=fn.params.some((p)=>p.type==="Identifier"&&p.name===subject);traverseFast(fn,(node)=>{if(node.type==="Identifier"&&node.name==="eval"){invalid(file,node,"Cannot verify a function alongside code that may evaluate dynamic JavaScript.")}const target=node.type==="UpdateExpression"?node.argument:node.type==="AssignmentExpression"||node.type==="ForOfStatement"||node.type==="ForInStatement"?node.left:undefined;if(target&&!hasLocalParameter&&writesBinding(target,subject)){invalid(file,target,`Another function may reassign the verified binding '${subject}'.`)}})}function selectSubject(program,file,name,options){let fn;for(const stmt of program.body){if(stmt.type==="ImportDeclaration"&&stmt.importKind==="type")continue;if((stmt.type==="ExportNamedDeclaration"||stmt.type==="ExportAllDeclaration")&&stmt.exportKind==="type")continue;const exported=stmt.type==="ExportNamedDeclaration";const selectable=exported||options?.allowLocalFunctions;const decl=exported?stmt.declaration:stmt;if(decl?.type==="FunctionDeclaration"){if(selectable&&decl.id?.name===name)fn=decl;else checkSibling(file,decl,name);continue}if(decl?.type==="TSInterfaceDeclaration"||decl?.type==="TSTypeAliasDeclaration")continue;if(decl?.type==="VariableDeclaration"&&decl.kind==="const"&&!decl.declare){for(const d of decl.declarations){if(d.id.type==="Identifier"&&literalInitializer(d.init))continue;if(d.id.type!=="Identifier"||!options?.allowArrowFunctions||d.init?.type!=="ArrowFunctionExpression"){invalid(file,d,"Subject modules may contain only named functions, type-only declarations, or constants with supported initializers.")}if(selectable&&d.id.name===name){if(d.id.typeAnnotation)invalid(file,d.id,"Declare parameter and return types on the arrow function itself.");fn=d.init}else checkSibling(file,d.init,name)}continue}invalid(file,stmt,"Subject modules may contain only named functions, type-only declarations, or constants with supported initializers.")}if(!fn){if(options?.allowLocalFunctions)return invalid(file,undefined,`Expected a directly declared function named '${name}'.`);throw new Error(`${file}: No named function export '${name}'.`)}return fn}import{dirname as dirname2}from"path";var iteration_default=`import Std
|
|
438
|
+
|
|
439
|
+
namespace Pud
|
|
440
|
+
|
|
441
|
+
set_option autoImplicit false
|
|
442
|
+
|
|
443
|
+
def countdownWhile {m : Type \u2192 Type} [Monad m] {\u03C3 : Type}
|
|
444
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
445
|
+
(step : Int \u2192 \u03C3 \u2192 m \u03C3) (state : \u03C3) : m (Int \xD7 \u03C3) :=
|
|
446
|
+
if _above : counter > limit then do
|
|
447
|
+
let next \u2190 step counter state
|
|
448
|
+
countdownWhile (counter - decrement) limit decrement positive step next
|
|
449
|
+
else pure (counter, state)
|
|
450
|
+
termination_by (counter - limit).toNat
|
|
451
|
+
decreasing_by omega
|
|
452
|
+
|
|
453
|
+
@[simp] theorem countdownWhile_stop {m : Type \u2192 Type} [Monad m] {\u03C3 : Type}
|
|
454
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
455
|
+
(step : Int \u2192 \u03C3 \u2192 m \u03C3) (state : \u03C3) (stopped : counter \u2264 limit) :
|
|
456
|
+
countdownWhile counter limit decrement positive step state = pure (counter, state) := by
|
|
457
|
+
rw [countdownWhile]
|
|
458
|
+
simp [Int.not_lt.mpr stopped]
|
|
459
|
+
|
|
460
|
+
-- A false guard finishes with the current state. A throw finishes before the
|
|
461
|
+
-- counter update. A successful body updates the counter and runs the next step.
|
|
462
|
+
inductive CountdownRuns {\u03B5 \u03C3 : Type} (limit decrement : Int)
|
|
463
|
+
(step : Int \u2192 \u03C3 \u2192 Except \u03B5 \u03C3) : Int \u2192 \u03C3 \u2192 Except \u03B5 (Int \xD7 \u03C3) \u2192 Prop where
|
|
464
|
+
| stopped {counter state} : counter \u2264 limit \u2192
|
|
465
|
+
CountdownRuns limit decrement step counter state (.ok (counter, state))
|
|
466
|
+
| thrown {counter state error} : counter > limit \u2192 step counter state = .error error \u2192
|
|
467
|
+
CountdownRuns limit decrement step counter state (.error error)
|
|
468
|
+
| continued {counter state next outcome} : counter > limit \u2192 step counter state = .ok next \u2192
|
|
469
|
+
CountdownRuns limit decrement step (counter - decrement) next outcome \u2192
|
|
470
|
+
CountdownRuns limit decrement step counter state outcome
|
|
471
|
+
|
|
472
|
+
theorem countdownWhile_except_runs {\u03B5 \u03C3 : Type}
|
|
473
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
474
|
+
(step : Int \u2192 \u03C3 \u2192 Except \u03B5 \u03C3) (state : \u03C3) :
|
|
475
|
+
CountdownRuns limit decrement step counter state (countdownWhile counter limit decrement positive step state) := by
|
|
476
|
+
by_cases above : counter > limit
|
|
477
|
+
\xB7 rw [countdownWhile]
|
|
478
|
+
simp only [dif_pos above]
|
|
479
|
+
cases currentStep : step counter state with
|
|
480
|
+
| error error => exact .thrown above currentStep
|
|
481
|
+
| ok next =>
|
|
482
|
+
exact .continued above currentStep
|
|
483
|
+
(countdownWhile_except_runs (counter - decrement) limit decrement positive step next)
|
|
484
|
+
\xB7 rw [countdownWhile_stop _ _ _ _ _ _ (Int.le_of_not_gt above)]
|
|
485
|
+
exact .stopped (Int.le_of_not_gt above)
|
|
486
|
+
termination_by (counter - limit).toNat
|
|
487
|
+
decreasing_by omega
|
|
488
|
+
|
|
489
|
+
theorem countdownWhile_pure_runs {\u03C3 : Type}
|
|
490
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
491
|
+
(step : Int \u2192 \u03C3 \u2192 \u03C3) (state : \u03C3) :
|
|
492
|
+
CountdownRuns (\u03B5 := Unit) limit decrement (fun n s => .ok (step n s)) counter state
|
|
493
|
+
(.ok (countdownWhile (m := Id) counter limit decrement positive step state)) := by
|
|
494
|
+
by_cases above : counter > limit
|
|
495
|
+
\xB7 rw [countdownWhile]
|
|
496
|
+
simp only [dif_pos above]
|
|
497
|
+
exact .continued above rfl (countdownWhile_pure_runs (counter - decrement) limit decrement positive step (step counter state))
|
|
498
|
+
\xB7 rw [countdownWhile_stop _ _ _ _ _ _ (Int.le_of_not_gt above)]
|
|
499
|
+
exact .stopped (Int.le_of_not_gt above)
|
|
500
|
+
termination_by (counter - limit).toNat
|
|
501
|
+
decreasing_by omega
|
|
502
|
+
|
|
503
|
+
theorem CountdownRuns.deterministic {\u03B5 \u03C3 : Type} {limit decrement : Int}
|
|
504
|
+
{step : Int \u2192 \u03C3 \u2192 Except \u03B5 \u03C3} {counter : Int} {state : \u03C3} {first second : Except \u03B5 (Int \xD7 \u03C3)}
|
|
505
|
+
(h\u2081 : CountdownRuns limit decrement step counter state first)
|
|
506
|
+
(h\u2082 : CountdownRuns limit decrement step counter state second) : first = second := by
|
|
507
|
+
induction h\u2081 generalizing second with
|
|
508
|
+
| stopped below => cases h\u2082 <;> first | rfl | omega
|
|
509
|
+
| thrown above error => cases h\u2082 <;> first | (simp_all; done) | omega
|
|
510
|
+
| continued above ok _ ih =>
|
|
511
|
+
cases h\u2082 with
|
|
512
|
+
| stopped _ => omega
|
|
513
|
+
| thrown _ error => rw [ok] at error; contradiction
|
|
514
|
+
| continued _ other rest =>
|
|
515
|
+
have same := Except.ok.inj (ok.symm.trans other)
|
|
516
|
+
cases same
|
|
517
|
+
exact ih rest
|
|
518
|
+
|
|
519
|
+
theorem countdownWhile_except_correct {\u03B5 \u03C3 : Type} (counter limit decrement : Int)
|
|
520
|
+
(positive : 0 < decrement) (step : Int \u2192 \u03C3 \u2192 Except \u03B5 \u03C3) (state : \u03C3) (outcome : Except \u03B5 (Int \xD7 \u03C3)) :
|
|
521
|
+
CountdownRuns limit decrement step counter state outcome \u2194
|
|
522
|
+
countdownWhile counter limit decrement positive step state = outcome := by
|
|
523
|
+
have run := countdownWhile_except_runs counter limit decrement positive step state
|
|
524
|
+
constructor
|
|
525
|
+
\xB7 exact run.deterministic
|
|
526
|
+
\xB7 intro equal
|
|
527
|
+
rw [\u2190 equal]
|
|
528
|
+
exact run
|
|
529
|
+
|
|
530
|
+
theorem countdownWhile_pure_correct {\u03C3 : Type} (counter limit decrement : Int)
|
|
531
|
+
(positive : 0 < decrement) (step : Int \u2192 \u03C3 \u2192 \u03C3) (state : \u03C3) (outcome : Int \xD7 \u03C3) :
|
|
532
|
+
CountdownRuns (\u03B5 := Unit) limit decrement (fun n s => .ok (step n s)) counter state (.ok outcome) \u2194
|
|
533
|
+
countdownWhile (m := Id) counter limit decrement positive step state = outcome := by
|
|
534
|
+
have run := countdownWhile_pure_runs counter limit decrement positive step state
|
|
535
|
+
constructor
|
|
536
|
+
\xB7 intro other
|
|
537
|
+
exact Except.ok.inj (run.deterministic other)
|
|
538
|
+
\xB7 intro equal
|
|
539
|
+
rw [\u2190 equal]
|
|
540
|
+
exact run
|
|
541
|
+
|
|
542
|
+
-- The scalar-accumulator optimization consumes the dense array in order,
|
|
543
|
+
-- committing exactly one state update before proceeding to the tail.
|
|
544
|
+
inductive DenseForOfRuns {\u03B1 \u03C3 : Type} (step : \u03C3 \u2192 \u03B1 \u2192 \u03C3) : List \u03B1 \u2192 \u03C3 \u2192 \u03C3 \u2192 Prop where
|
|
545
|
+
| done (state) : DenseForOfRuns step [] state state
|
|
546
|
+
| next (value : \u03B1) {rest state final} : DenseForOfRuns step rest (step state value) final \u2192
|
|
547
|
+
DenseForOfRuns step (value :: rest) state final
|
|
548
|
+
|
|
549
|
+
theorem denseForOf_foldl {\u03B1 \u03C3 : Type} (step : \u03C3 \u2192 \u03B1 \u2192 \u03C3) (values : List \u03B1) (state : \u03C3) :
|
|
550
|
+
DenseForOfRuns step values state (values.foldl step state) := by
|
|
551
|
+
induction values generalizing state with
|
|
552
|
+
| nil => exact .done state
|
|
553
|
+
| cons head rest ih => exact .next head (ih (step state head))
|
|
554
|
+
|
|
555
|
+
theorem DenseForOfRuns.deterministic {\u03B1 \u03C3 : Type} {step : \u03C3 \u2192 \u03B1 \u2192 \u03C3} {values : List \u03B1}
|
|
556
|
+
{state first second : \u03C3} (h\u2081 : DenseForOfRuns step values state first)
|
|
557
|
+
(h\u2082 : DenseForOfRuns step values state second) : first = second := by
|
|
558
|
+
induction h\u2081 generalizing second with
|
|
559
|
+
| done => cases h\u2082; rfl
|
|
560
|
+
| next _ _ ih => cases h\u2082; apply ih; assumption
|
|
561
|
+
|
|
562
|
+
theorem denseForOf_correct {\u03B1 \u03C3 : Type} (step : \u03C3 \u2192 \u03B1 \u2192 \u03C3) (values : List \u03B1) (state outcome : \u03C3) :
|
|
563
|
+
DenseForOfRuns step values state outcome \u2194 values.foldl step state = outcome := by
|
|
564
|
+
have run := denseForOf_foldl step values state
|
|
565
|
+
constructor
|
|
566
|
+
\xB7 exact run.deterministic
|
|
567
|
+
\xB7 intro equal
|
|
568
|
+
rw [\u2190 equal]
|
|
569
|
+
exact run
|
|
570
|
+
|
|
571
|
+
theorem forIn_foldl_of_step_eq {\u03B1 \u03C3 : Type} (values : List \u03B1) (initial : \u03C3)
|
|
572
|
+
(body : \u03B1 \u2192 \u03C3 \u2192 Id (ForInStep \u03C3)) (step : \u03C3 \u2192 \u03B1 \u2192 \u03C3)
|
|
573
|
+
(agrees : \u2200 item state, body item state = .yield (step state item)) :
|
|
574
|
+
forIn (m := Id) values initial body = values.foldl step initial := by
|
|
575
|
+
induction values generalizing initial with
|
|
576
|
+
| nil => rfl
|
|
577
|
+
| cons head tail ih =>
|
|
578
|
+
rw [List.forIn_cons, List.foldl_cons, agrees]
|
|
579
|
+
exact ih (step initial head)
|
|
580
|
+
|
|
581
|
+
end Pud
|
|
582
|
+
`;var scalar_default=`import Std
|
|
583
|
+
|
|
584
|
+
namespace Pud.Scalar
|
|
585
|
+
|
|
586
|
+
inductive Kind where
|
|
587
|
+
| integer
|
|
588
|
+
| boolean
|
|
589
|
+
|
|
590
|
+
abbrev Value : Kind \u2192 Type
|
|
591
|
+
| .integer => Int
|
|
592
|
+
| .boolean => Bool
|
|
593
|
+
|
|
594
|
+
inductive Unary : Kind \u2192 Kind \u2192 Type where
|
|
595
|
+
| neg : Unary .integer .integer
|
|
596
|
+
| not : Unary .boolean .boolean
|
|
597
|
+
| truthy : Unary .integer .boolean
|
|
598
|
+
| shift (count : Nat) : Unary .integer .integer
|
|
599
|
+
| mask (bits : Nat) : Unary .integer .integer
|
|
600
|
+
|
|
601
|
+
def Unary.apply : Unary i o \u2192 Value i \u2192 Value o
|
|
602
|
+
| .neg, value => -value
|
|
603
|
+
| .not, value => !value
|
|
604
|
+
| .truthy, value => decide (value \u2260 0)
|
|
605
|
+
| .shift count, value => value * (2 : Int) ^ count
|
|
606
|
+
| .mask bits, value => value % (2 : Int) ^ bits
|
|
607
|
+
|
|
608
|
+
-- A mask of low bits selects from the finite two's-complement encoding.
|
|
609
|
+
def lowBits (value : Int) (bits : Nat) : Int :=
|
|
610
|
+
Int.ofNat ((value % (2 : Int) ^ bits).toNat &&& ((2 : Nat) ^ bits - 1))
|
|
611
|
+
|
|
612
|
+
theorem lowBits_preservation (value : Int) (bits : Nat) :
|
|
613
|
+
lowBits value bits = value % (2 : Int) ^ bits := by
|
|
614
|
+
have positive : 0 < (2 : Int) ^ bits := Int.pow_pos (by decide)
|
|
615
|
+
have nonneg := Int.emod_nonneg value (Int.ne_of_gt positive)
|
|
616
|
+
have below := Int.emod_lt_of_pos value positive
|
|
617
|
+
have bound : (value % (2 : Int) ^ bits).toNat < (2 : Nat) ^ bits := by
|
|
618
|
+
apply (Int.toNat_lt nonneg).mpr
|
|
619
|
+
rw [Int.natCast_pow]
|
|
620
|
+
exact below
|
|
621
|
+
simp [lowBits, Nat.mod_eq_of_lt bound, Int.toNat_of_nonneg nonneg]
|
|
622
|
+
|
|
623
|
+
def Unary.evaluate : Unary i o \u2192 Value i \u2192 Value o
|
|
624
|
+
| .mask bits, value => lowBits value bits
|
|
625
|
+
| op, value => op.apply value
|
|
626
|
+
|
|
627
|
+
theorem Unary.preservation (op : Unary i o) (value : Value i) :
|
|
628
|
+
op.evaluate value = op.apply value := by
|
|
629
|
+
cases op <;> simp [Unary.evaluate, Unary.apply, lowBits_preservation]
|
|
630
|
+
|
|
631
|
+
inductive Binary (\u03B5 : Type) : Kind \u2192 Kind \u2192 Type where
|
|
632
|
+
| add : Binary \u03B5 .integer .integer
|
|
633
|
+
| sub : Binary \u03B5 .integer .integer
|
|
634
|
+
| mul : Binary \u03B5 .integer .integer
|
|
635
|
+
| divide (zero : \u03B5) : Binary \u03B5 .integer .integer
|
|
636
|
+
| remainder (zero : \u03B5) : Binary \u03B5 .integer .integer
|
|
637
|
+
| lt : Binary \u03B5 .integer .boolean
|
|
638
|
+
| lte : Binary \u03B5 .integer .boolean
|
|
639
|
+
| gt : Binary \u03B5 .integer .boolean
|
|
640
|
+
| gte : Binary \u03B5 .integer .boolean
|
|
641
|
+
| equalInt : Binary \u03B5 .integer .boolean
|
|
642
|
+
| equalBool : Binary \u03B5 .boolean .boolean
|
|
643
|
+
|
|
644
|
+
def Binary.lower : Binary \u03B5 i o \u2192 Value i \u2192 Value i \u2192 Except \u03B5 (Value o)
|
|
645
|
+
| .add, lhs, rhs => .ok (lhs + rhs)
|
|
646
|
+
| .sub, lhs, rhs => .ok (lhs - rhs)
|
|
647
|
+
| .mul, lhs, rhs => .ok (lhs * rhs)
|
|
648
|
+
| .divide zero, lhs, rhs => if rhs = 0 then .error zero else .ok (Int.tdiv lhs rhs)
|
|
649
|
+
| .remainder zero, lhs, rhs => if rhs = 0 then .error zero else .ok (Int.tmod lhs rhs)
|
|
650
|
+
| .lt, lhs, rhs => .ok (decide (lhs < rhs))
|
|
651
|
+
| .lte, lhs, rhs => .ok (decide (lhs \u2264 rhs))
|
|
652
|
+
| .gt, lhs, rhs => .ok (decide (lhs > rhs))
|
|
653
|
+
| .gte, lhs, rhs => .ok (decide (lhs \u2265 rhs))
|
|
654
|
+
| .equalInt, lhs, rhs => .ok (decide (lhs = rhs))
|
|
655
|
+
| .equalBool, lhs, rhs => .ok (decide (lhs = rhs))
|
|
656
|
+
|
|
657
|
+
-- ECMAScript BigInt division truncates the exact quotient toward zero.
|
|
658
|
+
def quotient (lhs rhs : Int) : Int :=
|
|
659
|
+
let magnitude : Int := Int.ofNat (lhs.natAbs / rhs.natAbs)
|
|
660
|
+
if (lhs < 0) \u2194 (rhs < 0) then magnitude else -magnitude
|
|
661
|
+
|
|
662
|
+
theorem quotient_eq_tdiv (lhs rhs : Int) : quotient lhs rhs = lhs.tdiv rhs := by
|
|
663
|
+
cases lhs <;> cases rhs <;> simp [quotient, Int.tdiv, Int.natAbs, Int.not_lt.mpr (Int.ofNat_nonneg _)]
|
|
664
|
+
|
|
665
|
+
-- ECMAScript BigInt remainder subtracts the divisor times the truncated quotient.
|
|
666
|
+
theorem remainder_eq_tmod (lhs rhs : Int) :
|
|
667
|
+
lhs - rhs * lhs.tdiv rhs = lhs.tmod rhs := by
|
|
668
|
+
have := Int.tmod_add_tdiv lhs rhs
|
|
669
|
+
omega
|
|
670
|
+
|
|
671
|
+
def Binary.evaluate : Binary \u03B5 i o \u2192 Value i \u2192 Value i \u2192 Except \u03B5 (Value o)
|
|
672
|
+
| .divide zero, lhs, rhs => if rhs = 0 then .error zero else .ok (quotient lhs rhs)
|
|
673
|
+
| .remainder zero, lhs, rhs => if rhs = 0 then .error zero else .ok (lhs - rhs * quotient lhs rhs)
|
|
674
|
+
| op, lhs, rhs => op.lower lhs rhs
|
|
675
|
+
|
|
676
|
+
theorem Binary.preservation (op : Binary \u03B5 i o) (lhs rhs : Value i) :
|
|
677
|
+
op.evaluate lhs rhs = op.lower lhs rhs := by
|
|
678
|
+
cases op <;> simp [Binary.evaluate, Binary.lower, quotient_eq_tdiv, remainder_eq_tmod]
|
|
679
|
+
|
|
680
|
+
inductive Expr (\u03B5 : Type) : Kind \u2192 Type where
|
|
681
|
+
| integer (value : Int) : Expr \u03B5 .integer
|
|
682
|
+
| boolean (value : Bool) : Expr \u03B5 .boolean
|
|
683
|
+
| unary (op : Unary i o) (arg : Expr \u03B5 i) : Expr \u03B5 o
|
|
684
|
+
| binary (op : Binary \u03B5 i o) (lhs rhs : Expr \u03B5 i) : Expr \u03B5 o
|
|
685
|
+
| choose (test : Expr \u03B5 .boolean) (yes no : Expr \u03B5 o) : Expr \u03B5 o
|
|
686
|
+
| and (lhs rhs : Expr \u03B5 .boolean) : Expr \u03B5 .boolean
|
|
687
|
+
| or (lhs rhs : Expr \u03B5 .boolean) : Expr \u03B5 .boolean
|
|
688
|
+
| bind (arg : Expr \u03B5 i) (next : Value i \u2192 Expr \u03B5 o) : Expr \u03B5 o
|
|
689
|
+
| thrown (error : \u03B5) : Expr \u03B5 o
|
|
690
|
+
| handle (attempt recovery : Expr \u03B5 o) : Expr \u03B5 o
|
|
691
|
+
|
|
692
|
+
-- Explicit evaluation order and abrupt completion on the source side.
|
|
693
|
+
def evaluate : Expr \u03B5 o \u2192 Except \u03B5 (Value o)
|
|
694
|
+
| .integer value => .ok value
|
|
695
|
+
| .boolean value => .ok value
|
|
696
|
+
| .unary op arg =>
|
|
697
|
+
match evaluate arg with
|
|
698
|
+
| .error error => .error error
|
|
699
|
+
| .ok value => .ok (op.evaluate value)
|
|
700
|
+
| .binary op lhs rhs =>
|
|
701
|
+
match evaluate lhs with
|
|
702
|
+
| .error error => .error error
|
|
703
|
+
| .ok left =>
|
|
704
|
+
match evaluate rhs with
|
|
705
|
+
| .error error => .error error
|
|
706
|
+
| .ok right => op.evaluate left right
|
|
707
|
+
| .choose test yes no =>
|
|
708
|
+
match evaluate test with
|
|
709
|
+
| .error error => .error error
|
|
710
|
+
| .ok value => if value then evaluate yes else evaluate no
|
|
711
|
+
| .and lhs rhs =>
|
|
712
|
+
match evaluate lhs with
|
|
713
|
+
| .error error => .error error
|
|
714
|
+
| .ok value => if value then evaluate rhs else .ok false
|
|
715
|
+
| .or lhs rhs =>
|
|
716
|
+
match evaluate lhs with
|
|
717
|
+
| .error error => .error error
|
|
718
|
+
| .ok value => if value then .ok true else evaluate rhs
|
|
719
|
+
| .bind arg next =>
|
|
720
|
+
match evaluate arg with
|
|
721
|
+
| .error error => .error error
|
|
722
|
+
| .ok value => evaluate (next value)
|
|
723
|
+
| .thrown error => .error error
|
|
724
|
+
| .handle attempt recovery =>
|
|
725
|
+
match evaluate attempt with
|
|
726
|
+
| .ok value => .ok value
|
|
727
|
+
| .error _ => evaluate recovery
|
|
728
|
+
|
|
729
|
+
-- Target denotation using the primitives and Except sequencing of the emitter.
|
|
730
|
+
def lower : Expr \u03B5 o \u2192 Except \u03B5 (Value o)
|
|
731
|
+
| .integer value => .ok value
|
|
732
|
+
| .boolean value => .ok value
|
|
733
|
+
| .unary op arg => (lower arg).bind fun value => .ok (op.apply value)
|
|
734
|
+
| .binary op lhs rhs => (lower lhs).bind fun left => (lower rhs).bind fun right => op.lower left right
|
|
735
|
+
| .choose test yes no => (lower test).bind fun value => if value then lower yes else lower no
|
|
736
|
+
| .and lhs rhs => (lower lhs).bind fun value => if value then lower rhs else .ok false
|
|
737
|
+
| .or lhs rhs => (lower lhs).bind fun value => if value then .ok true else lower rhs
|
|
738
|
+
| .bind arg next => (lower arg).bind fun value => lower (next value)
|
|
739
|
+
| .thrown error => .error error
|
|
740
|
+
| .handle attempt recovery =>
|
|
741
|
+
match lower attempt with
|
|
742
|
+
| .ok value => .ok value
|
|
743
|
+
| .error _ => lower recovery
|
|
744
|
+
|
|
745
|
+
@[simp] theorem bind_ok {\u03B5 \u03B1 \u03B2 : Type} (value : \u03B1) (next : \u03B1 \u2192 Except \u03B5 \u03B2) :
|
|
746
|
+
(Except.ok value).bind next = next value := rfl
|
|
747
|
+
|
|
748
|
+
@[simp] theorem bind_error {\u03B5 \u03B1 \u03B2 : Type} (error : \u03B5) (next : \u03B1 \u2192 Except \u03B5 \u03B2) :
|
|
749
|
+
(Except.error error : Except \u03B5 \u03B1).bind next = .error error := rfl
|
|
750
|
+
|
|
751
|
+
@[simp] theorem bind_return {\u03B5 \u03B1 : Type} (value : Except \u03B5 \u03B1) :
|
|
752
|
+
value.bind Except.ok = value := by cases value <;> rfl
|
|
753
|
+
|
|
754
|
+
@[simp] theorem bind_if {\u03B5 \u03B1 \u03B2 : Type} (test : Prop) [Decidable test]
|
|
755
|
+
(yes no : Except \u03B5 \u03B1) (next : \u03B1 \u2192 Except \u03B5 \u03B2) :
|
|
756
|
+
(if test then yes else no).bind next = if test then yes.bind next else no.bind next := by
|
|
757
|
+
by_cases h : test <;> simp [h]
|
|
758
|
+
|
|
759
|
+
theorem preservation (expression : Expr \u03B5 o) :
|
|
760
|
+
evaluate expression = lower expression := by
|
|
761
|
+
induction expression <;> simp [evaluate, lower, Except.bind, Unary.preservation, Binary.preservation, *]
|
|
762
|
+
all_goals (repeat' (split <;> try simp_all))
|
|
763
|
+
|
|
764
|
+
end Pud.Scalar
|
|
765
|
+
`;var integer=(value)=>({kind:"integer",sort:"integer",value:value.toString()});var bool2=(value)=>({kind:"boolean",sort:"boolean",value});var ref=(sort,...path)=>({kind:"reference",sort,path});function unary(op,arg){const sort=op==="!"?"boolean":"integer";if(arg.sort!==sort)throw new Error(`${op} expects ${sort==="integer"?"bigint":sort} operands.`);return{kind:"unary",sort,op,arg}}function binary(op,left,right){const input=op==="==="||op==="!=="?left.sort:op==="&&"||op==="||"?"boolean":"integer";if(left.sort!==input||right.sort!==input)throw new Error(`${op} expects ${input==="integer"?"bigint":input} operands.`);const sort=op==="+"||op==="-"||op==="*"?"integer":"boolean";return{kind:"binary",sort,op,left,right}}function choose(test,yes,no){if(test.sort!=="boolean"||yes.sort!==no.sort)throw new Error("A conditional needs a boolean test and two branches of the same type.");return{kind:"choose",sort:yes.sort,test,yes,no}}var operators=new Set(["+","-","*","<","<=",">",">=","===","!==","&&","||"]);function readExpression(file,node,resolve){const read=(n)=>readExpression(file,n,resolve);const existing=resolve(node);if(existing)return existing;try{switch(node.type){case"BooleanLiteral":return bool2(node.value);case"BigIntLiteral":return integer(BigInt(node.value));case"UnaryExpression":if(node.operator==="-"||node.operator==="!")return unary(node.operator,read(node.argument));break;case"BinaryExpression":case"LogicalExpression":if(operators.has(node.operator))return binary(node.operator,read(node.left),read(node.right));break;case"ConditionalExpression":return choose(read(node.test),read(node.consequent),read(node.alternate))}}catch(error){if(error instanceof Unsupported2)throw error;return invalid(file,node,error.message)}return invalid(file,node,`Unsupported TypeScript: ${node.type}${"operator"in node?` (${node.operator})`:""}.`)}var leanTypes={integer:"Int",number:"JSNumber",boolean:"Bool",integers:"List Int",items:"List Item",textOrItems:"Option (List Item)"};var errorKinds={Error:"error",RangeError:"rangeError",TypeError:"typeError"};function isScalar(sort){return sort==="integer"||sort==="number"||sort==="boolean"}function truthy(value,code){if(value.sort==="number")return`(JSNumber.truthy ${code})`;return value.sort==="integer"?`(decide (${code} \u2260 (0 : Int)))`:code}function nameOf(file,node){if(node?.type!=="Identifier"||node.name==="this"||node.optional||node.decorators?.length){return invalid(file,node??undefined,"Expected a named binding.")}return node.name}function arrayElement(type){if(type.type==="TSTypeOperator"&&type.operator==="readonly"&&type.typeAnnotation.type==="TSArrayType"){return type.typeAnnotation.elementType}}function tsSort(file,annotation,at,registerItem){function isOpaqueItem(element){if(!registerItem||element?.type!=="TSTypeReference"||element.typeName.type!=="Identifier"||element.typeArguments)return false;registerItem(element.typeName.name,element);return true}if(annotation?.type==="TSTypeAnnotation"){const type=annotation.typeAnnotation;if(type.type==="TSBigIntKeyword")return"integer";if(type.type==="TSNumberKeyword")return"number";if(type.type==="TSBooleanKeyword")return"boolean";const element=arrayElement(type);if(element?.type==="TSBigIntKeyword")return"integers";if(isOpaqueItem(element))return"items";if(type.type==="TSUnionType"&&type.types.length===2&&type.types.some((branch)=>branch.type==="TSStringKeyword")){const array=type.types.find((branch)=>branch.type!=="TSStringKeyword");if(array&&isOpaqueItem(arrayElement(array)))return"textOrItems"}}return invalid(file,at,"Expected bigint, number, boolean, a supported readonly array, or a string-or-record-array union.")}var comparisons2={"<":"<","<=":"\u2264",">":">",">=":"\u2265","===":"=","!==":"\u2260"};function emit(expr){switch(expr.kind){case"integer":return`(${expr.value} : Int)`;case"boolean":return String(expr.value);case"reference":return expr.path[0];case"unary":return`(${expr.op}${emit(expr.arg)})`;case"choose":return`(if ${emit(expr.test)} then ${emit(expr.yes)} else ${emit(expr.no)})`;case"binary":{const lhs=emit(expr.left),rhs=emit(expr.right);if(expr.op in comparisons2){return`(decide (${lhs} ${comparisons2[expr.op]} ${rhs}))`}return`(${lhs} ${expr.op} ${rhs})`}default:throw new Error(`Unexpected expression in Lean lowering: ${expr.kind}`)}}function readSpecCall(file,node,helpers,read){if(node.type!=="CallExpression"||node.typeArguments||node.callee.type!=="MemberExpression"||node.callee.computed||node.callee.object.type!=="Identifier"||!helpers?.has(node.callee.object.name)||node.callee.property.type!=="Identifier")return;const name=node.callee.property.name;if(name==="sum"||name==="length"){const[input]=node.arguments;if(node.arguments.length!==1||!input)invalid(file,node,`Pass one array to pud.${name}().`);const value=read(input);if(name==="sum"){return{sort:"integer",code:`(List.sum ${ofSort(file,input,value,"integers")})`}}if(value.sort!=="integers"&&value.sort!=="items")invalid(file,input,"Pass a supported array to pud.length().");return{sort:"integer",code:`(Int.ofNat (List.length ${value.code}))`}}if(name==="modulo"){const[input,divisor]=node.arguments;if(node.arguments.length!==2||!input||divisor?.type!=="BigIntLiteral"||BigInt(divisor.value)<=0n){invalid(file,node,"Pass a bigint and a positive literal divisor to pud.modulo().")}return{sort:"integer",code:`(${ofSort(file,input,read(input),"integer")} % (${BigInt(divisor.value)} : Int))`}}if(name==="quotient"){const[input,divisor]=node.arguments;if(node.arguments.length!==2||!input||!divisor)invalid(file,node,"Pass two bigints to pud.quotient().");const lhs=ofSort(file,input,read(input),"integer"),rhs=ofSort(file,divisor,read(divisor),"integer");return{sort:"integer",code:`(Int.tdiv ${lhs} ${rhs})`}}}function asOutcome(value){return value.fallible?value.code:`(Except.ok (${value.code}))`}function sequence(values,fresh,finish){const steps=[];const operands=values.map((value)=>{if(!value.fallible)return value.code;const name=fresh();steps.push(`let ${name} \u2190 ${value.code};`);return name});const result=finish(operands);if(!steps.length)return result;return{sort:result.sort,fallible:true,code:`(do ${steps.join(" ")} ${asOutcome(result)})`}}function invoke(callee,args,fresh){return sequence(args,fresh,(values)=>({sort:callee.result,fallible:callee.fallible,code:values.length?`(${callee.code} ${values.join(" ")})`:callee.code}))}function bigintLiteral(node){if(node.type==="BigIntLiteral")return BigInt(node.value);if(node.type==="UnaryExpression"&&node.operator==="-"&&node.argument.type==="BigIntLiteral"){return-BigInt(node.argument.value)}}function readValue(file,node,scope,helpers,executable,numberGlobal=executable?.numberGlobal){if(node.type==="Identifier")return scope.get(node.name)??invalid(file,node,`Unknown binding '${node.name}'.`);if(node.type==="NumericLiteral")return numberLiteral(node.value);const read=(child)=>readValue(file,child,scope,helpers,executable,numberGlobal);const fresh=()=>executable?.fresh()??invalid(file,node,"A specification expression must be total.");if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&!node.callee.computed&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Number"&&node.callee.property.type==="Identifier"&&(node.callee.property.name==="isInteger"||node.callee.property.name==="isNaN")){const method=node.callee.property.name;if(!numberGlobal||scope.has("Number"))invalid(file,node,`Number.${method} requires the unshadowed Number built-in.`);const[arg]=node.arguments;if(node.typeArguments||node.arguments.length!==1||!arg)invalid(file,node,`Pass one number to Number.${method}.`);const value=read(arg);ofSort(file,arg,value,"number");return sequence([value],fresh,([x])=>({sort:"boolean",code:`(JSNumber.${method} ${x})`}))}const spec=readSpecCall(file,node,helpers,read);if(spec)return spec;if(node.type==="CallExpression"&&executable)return executable.call(node,read);const operands=node.type==="BinaryExpression"?[node.left,node.right]:node.type==="UnaryExpression"?[node.argument]:[];const values=operands.map(read);if(node.type==="BinaryExpression"){const op=node.operator;const left=values[0],right=values[1];if(left.sort==="number"||right.sort==="number"){ofSort(file,node.left,left,"number");ofSort(file,node.right,right,"number");return sequence(values,fresh,([a,b])=>numberBinary(op,a,b)??invalid(file,node,`Unsupported number operator '${op}'.`))}if(op==="/"||op==="%"){const divisor=bigintLiteral(node.right);if(!executable&&(divisor===undefined||divisor===0n)){invalid(file,node.right,"A specification division or remainder needs a nonzero bigint literal divisor.")}ofSort(file,node.left,left,"integer");ofSort(file,node.right,right,"integer");const operation=op==="%"?"Int.tmod":"Int.tdiv";return sequence([left,right],fresh,([lhs,rhs])=>divisor!==undefined&&divisor!==0n?{sort:"integer",code:`(${operation} ${lhs} ${rhs})`}:{sort:"integer",fallible:true,code:`(if ${rhs} = 0 then Except.error .rangeError else Except.ok (${operation} ${lhs} ${rhs}))`})}if(op==="<<"||op==="&"){const literal=node.right.type==="BigIntLiteral"?BigInt(node.right.value):undefined;if(literal===undefined||op==="&"&&(literal&literal+1n)!==0n){invalid(file,node.right,op==="<<"?"Bigint left shift needs a nonnegative literal count.":"Bigint bitwise AND needs a literal mask with only consecutive low bits set.")}ofSort(file,node.left,left,"integer");return sequence([left],fresh,([lhs])=>({sort:"integer",code:op==="<<"?`(${lhs} * (2 : Int) ^ (${literal} : Nat))`:`(${lhs} % (${literal+1n} : Int))`}))}}if(node.type==="UnaryExpression"&&values[0]?.sort==="number"){return sequence(values,fresh,([x])=>{if(node.operator==="-")return{sort:"number",code:`(JSNumber.neg ${x})`};if(node.operator==="+")return{sort:"number",code:x};if(node.operator==="!")return{sort:"boolean",code:`(!(JSNumber.truthy ${x}))`};return invalid(file,node,`Unsupported number operator '${node.operator}'.`)})}const conditional=(test,yes,no)=>{if(test.sort!=="number")ofSort(file,node,test,"boolean");if(yes.sort!==no.sort)invalid(file,node,"A conditional needs two branches of the same type.");const branchesThrow=yes.fallible||no.fallible;const premise=executable?.recursive?`_${fresh()} : `:"";return sequence([test],fresh,([code])=>({sort:yes.sort,fallible:branchesThrow,code:`(if ${premise}${truthy(test,code)} then ${branchesThrow?asOutcome(yes):yes.code} else ${branchesThrow?asOutcome(no):no.code})`}))};if(node.type==="ConditionalExpression")return conditional(read(node.test),read(node.consequent),read(node.alternate));if(node.type==="LogicalExpression"&&(node.operator==="&&"||node.operator==="||")){const left=read(node.left),right=read(node.right);ofSort(file,node.left,left,"boolean");ofSort(file,node.right,right,"boolean");if(left.fallible||right.fallible||executable?.recursive){const short={sort:"boolean",code:node.operator==="&&"?"false":"true"};return node.operator==="&&"?conditional(left,right,short):conditional(left,short,right)}return{sort:"boolean",code:`(${left.code} ${node.operator} ${right.code})`}}return sequence(values,fresh,(codes)=>{const expr=readExpression(file,node,(child)=>{const i=operands.indexOf(child);if(i===-1)return;const value=values[i];if(value.sort!=="integer"&&value.sort!=="boolean")invalid(file,child,"Use arrays and unions as whole values.");return ref(value.sort,codes[i])});if(expr.sort==="string")return invalid(file,node,"Use bigint or boolean for scalar values in the Lean adapter.");return{sort:expr.sort,code:emit(expr)}})}function ofSort(file,at,value,expected){if(value.sort!==expected)invalid(file,at,`Expected ${leanTypes[expected]}, got ${leanTypes[value.sort]}.`);return value.code}function readProposition(file,node,scope,helpers,numberGlobal){const read=(child)=>readValue(file,child,scope,helpers,undefined,numberGlobal);const predicate=(child)=>readProposition(file,child,scope,helpers,numberGlobal);if(node.type==="LogicalExpression"&&(node.operator==="&&"||node.operator==="||")){return`(${predicate(node.left)} ${node.operator==="&&"?"\u2227":"\u2228"} ${predicate(node.right)})`}if(node.type==="UnaryExpression"&&node.operator==="!"){const value=read(node.argument);if(value.sort==="number")return`(JSNumber.truthy ${value.code} = false)`;return`(\xAC ${predicate(node.argument)})`}if(node.type==="BinaryExpression"&&Object.hasOwn(comparisons2,node.operator)){const left=read(node.left);if(left.sort==="number"){const right=ofSort(file,node.right,read(node.right),"number");return`(${numberBinary(node.operator,left.code,right).code} = true)`}const sort=node.operator==="==="||node.operator==="!=="?left.sort:"integer";if(!isScalar(sort))invalid(file,node,"Use equality on bigint or boolean values.");const lhs=ofSort(file,node.left,left,sort);const rhs=ofSort(file,node.right,read(node.right),sort);return`(${lhs} ${comparisons2[node.operator]} ${rhs})`}return`(${ofSort(file,node,read(node),"boolean")} = true)`}var scalarSemantics=scalar_default.replace(/^import Std\s*/,"").trimEnd();var iterationSemantics=iteration_default.replace(/^import Std\s*/,"").trimEnd();var integerOperators={"+":"add","-":"sub","*":"mul","<":"lt","<=":"lte",">":"gt",">=":"gte"};function scalarValue(sort,value){return sort==="integer"||sort==="boolean"?{sort,code:`(.${sort} ${value})`}:undefined}function scalarCall(subject,args,fresh){if(!subject.sourceExpression||args.some((arg)=>arg===undefined))return;const sort=subject.result;if(sort!=="integer"&&sort!=="boolean")return;const names=args.map(fresh);const call=`(${[subject.code+"Source",...names].join(" ")})`;return{sort,code:args.reduceRight((body,arg,index)=>`(.bind ${arg.code} (fun ${names[index]} => ${body}))`,call)}}class OutsideScalarSemantics extends Error{}function outside(){throw new OutsideScalarSemantics}function scalarSource(fn,parameters,result,callees){if(result!=="integer"&&result!=="boolean")return;const scope=new Map;for(const param of parameters){const value=scalarValue(param.sort,param.code);if(!value)return;scope.set(param.name,{sort:value.sort,code:param.code})}let next=0;const fresh=()=>`_js${next++}`;const unary=(op,value,sort)=>({sort,code:`(.unary .${op} ${value.code})`});const conditional=(test,yes,no)=>`(.choose ${test.sort==="integer"?unary("truthy",test,"boolean").code:test.code} ${yes} ${no})`;const extend=(env,name,value)=>new Map([...env,[name,value]]);function expression(node,env){switch(node.type){case"Identifier":{const value=env.get(node.name)??outside();return scalarValue(value.sort,value.code)}case"BigIntLiteral":return scalarValue("integer",`(${BigInt(node.value)} : Int)`);case"BooleanLiteral":return scalarValue("boolean",String(node.value));case"UnaryExpression":{const arg=expression(node.argument,env);if(node.operator==="-")return unary("neg",arg,"integer");if(node.operator==="!")return unary("not",arg,"boolean");return outside()}case"LogicalExpression":{if(node.operator!=="&&"&&node.operator!=="||")return outside();const lhs=expression(node.left,env),rhs=expression(node.right,env);return{sort:"boolean",code:`(.${node.operator==="&&"?"and":"or"} ${lhs.code} ${rhs.code})`}}case"ConditionalExpression":{const yes=expression(node.consequent,env),no=expression(node.alternate,env);return{sort:yes.sort,code:conditional(expression(node.test,env),yes.code,no.code)}}case"BinaryExpression":{const lhs=expression(node.left,env),op=node.operator;if(op==="<<"){if(node.right.type!=="BigIntLiteral")return outside();return{sort:"integer",code:`(.unary (.shift ${BigInt(node.right.value)}) ${lhs.code})`}}if(op==="&"){if(node.right.type!=="BigIntLiteral")return outside();const mask=BigInt(node.right.value);if((mask&mask+1n)!==0n)return outside();const bits=mask===0n?0:mask.toString(2).length;return{sort:"integer",code:`(.unary (.mask ${bits}) ${lhs.code})`}}const rhs=expression(node.right,env);if(op==="/"||op==="%"){const operator=op==="/"?"divide":"remainder";return{sort:"integer",code:`(.binary (.${operator} .rangeError) ${lhs.code} ${rhs.code})`}}if(op==="==="||op==="!=="){const equality=lhs.sort==="integer"?"equalInt":"equalBool";const equal={sort:"boolean",code:`(.binary .${equality} ${lhs.code} ${rhs.code})`};return op==="==="?equal:unary("not",equal,"boolean")}if(!Object.hasOwn(integerOperators,op))return outside();const operator=integerOperators[op];const sort=op==="+"||op==="-"||op==="*"?"integer":"boolean";return{sort,code:`(.binary .${operator} ${lhs.code} ${rhs.code})`}}case"CallExpression":{if(node.callee.type!=="Identifier")return outside();const callee=callees.get(node.callee.name)??outside();return scalarCall(callee,node.arguments.map((arg)=>expression(arg,env)),fresh)??outside()}default:return outside()}}const type=(value)=>value.sort==="integer"?"Int":"Bool";function bind(name,value,env,resume){const local=fresh();return`(.bind ${value.code} (fun ${local} => ${resume(extend(env,name,{sort:value.sort,code:local}))}))`}function declarations(nodes,env,resume){const[node,...rest]=nodes;if(!node)return resume(env);if(node.id.type!=="Identifier"||!node.init)return outside();return bind(node.id.name,expression(node.init,env),env,(scope)=>declarations(rest,scope,resume))}function statements(nodes,env,resume){const[node,...rest]=nodes;if(!node)return resume(env);const continueWith=(scope)=>statements(rest,scope,resume);switch(node.type){case"ReturnStatement":return node.argument?expression(node.argument,env).code:outside();case"EmptyStatement":return continueWith(env);case"VariableDeclaration":return declarations(node.declarations,env,continueWith);case"ExpressionStatement":{const assignment=node.expression;if(assignment.type!=="AssignmentExpression"||assignment.left.type!=="Identifier")return outside();const name=assignment.left.name;const rhs=expression(assignment.right,env);if(assignment.operator==="=")return bind(name,rhs,env,continueWith);if(assignment.operator!=="+="&&assignment.operator!=="-=")return outside();const lhs=expression(assignment.left,env);const op=assignment.operator==="+="?"add":"sub";return bind(name,{sort:"integer",code:`(.binary .${op} ${lhs.code} ${rhs.code})`},env,continueWith)}case"ThrowStatement":{const thrown=node.argument;if(thrown.type!=="NewExpression"||thrown.callee.type!=="Identifier"||!Object.hasOwn(errorKinds,thrown.callee.name))return outside();return`(.thrown .${errorKinds[thrown.callee.name]})`}case"IfStatement":{const captured=[...env].map(([name,value])=>[name,{sort:value.sort,code:fresh()}]);const continuation=fresh();let used=false;const resumeBranch=(scope)=>{used=true;return`(${[continuation,...captured.map(([name])=>scope.get(name).code)].join(" ")})`};const yes=statements(branch(node.consequent),env,resumeBranch);const no=statements(branch(node.alternate),env,resumeBranch);const choice=conditional(expression(node.test,env),yes,no);if(!used)return choice;const args=captured.map(([,value])=>`(${value.code} : ${type(value)})`);const tail=continueWith(new Map(captured));return`(let ${continuation}${args.length?" "+args.join(" "):""} := ${tail}; ${choice})`}case"TryStatement":{const[attempt]=node.block.body;if(node.block.body.length!==1||attempt?.type!=="ReturnStatement"||!attempt.argument||!node.handler||node.handler.param||node.finalizer)return outside();const recover=statements(node.handler.body.body,env,(next)=>continueWith(new Map([...env].map(([name])=>[name,next.get(name)]))));return`(.handle ${expression(attempt.argument,env).code} ${recover})`}default:return outside()}}function branch(node){return node?.type==="BlockStatement"?node.body:node?[node]:[]}try{if(fn.type==="BlockStatement")return statements(fn.body,scope,outside);return expression(fn,scope).code}catch(error){if(!(error instanceof OutsideScalarSemantics))throw error}}var roundingMethods=new Set(["round","floor","ceil","trunc"]);function exits(node){switch(node?.type){case"ReturnStatement":case"ThrowStatement":return true;case"BlockStatement":return exits(node.body.at(-1));case"IfStatement":return exits(node.consequent)&&exits(node.alternate??undefined);case"TryStatement":return!!node.handler&&exits(node.block)&&exits(node.handler.body);default:return false}}function tuple(parts){return parts.length===1?parts[0]:`(${parts.join(", ")})`}function singleStatement(node){return node.type==="BlockStatement"&&node.body.length===1?node.body[0]:node}function localUpdate(node){const statement=singleStatement(node);if(statement.type==="ExpressionStatement"&&statement.expression.type==="AssignmentExpression"&&statement.expression.left.type==="Identifier")return statement.expression}function lowerFunction(file,program,fn,symbol,code,resolveCall){if(fn.async||fn.generator||fn.typeParameters)invalid(file,fn,"Expected a synchronous, non-generic function.");const interfaces=new Set(program.body.flatMap((statement)=>{const node=statement.type==="ExportNamedDeclaration"?statement.declaration:statement;return node?.type==="TSInterfaceDeclaration"&&!node.typeParameters?[node.id.name]:[]}));let itemType;function sort(annotation,at){return tsSort(file,annotation,at,(name,node)=>{if(!interfaces.has(name)||itemType&&itemType!==name){invalid(file,node,"Use one locally declared interface as the opaque array element type.")}itemType=name})}const inferBody=!fn.returnType&&fn.type==="ArrowFunctionExpression"&&fn.body.type!=="BlockStatement"?fn.body:undefined;const annotatedResult=inferBody?undefined:sort(fn.returnType,fn);const params=fn.params.map((node,i)=>({name:nameOf(file,node),sort:sort(node.type==="Identifier"?node.typeAnnotation:undefined,node),code:`p${i}`}));const scope=new Map(params.map((p)=>[p.name,p]));const moduleNames=new Set(program.body.flatMap((node)=>Object.keys(getOuterBindingIdentifiers(node))));const localNames=new Set(scope.keys());let recursive=false;traverseFast(fn.body,(node)=>{if(node.type==="VariableDeclarator")for(const name of Object.keys(getOuterBindingIdentifiers(node.id)))localNames.add(name);if(node.type==="CallExpression"&&node.callee.type==="Identifier"&&node.callee.name===symbol)recursive=true});const signature=[itemType&&"{Item : Type}",...params.map((p)=>`(${p.code} : ${leanTypes[p.sort]})`)].filter(Boolean);let nextLocal=0;const fresh=()=>`v${nextLocal++}`;const lines=[];let arrayGuard;let fallible=false;let countdown=false;let fold=false;const loopConformance=[];const callTargets=new Map;const executable={fresh,recursive,numberGlobal:!localNames.has("Number")&&!moduleNames.has("Number"),call(node,read){const member=node.callee;if(member.type==="MemberExpression"&&!member.computed&&member.object.type==="Identifier"&&member.object.name==="Math"&&member.property.type==="Identifier"&&roundingMethods.has(member.property.name)){const method=member.property.name;if(localNames.has("Math")||moduleNames.has("Math"))invalid(file,member,`Math.${method} requires the unshadowed Math built-in.`);const[arg]=node.arguments;if(node.typeArguments||node.arguments.length!==1||!arg)invalid(file,node,`Pass one number to Math.${method}.`);const value=read(arg);ofSort(file,arg,value,"number");return sequence([value],fresh,([x])=>({sort:"number",code:`(JSNumber.${method} ${x})`}))}if(node.typeArguments||node.callee.type!=="Identifier"||localNames.has(node.callee.name)){invalid(file,node,"Call a directly declared function without shadowing its name.")}const linked=node.callee.name===symbol?undefined:resolveCall(node.callee.name,node);const callee=linked??{params,result:annotatedResult??invalid(file,node,"Annotate a recursive function's return type."),itemType,code,fallible:false};if(callee.itemType||node.arguments.length!==callee.params.length){invalid(file,node,"Call a supported function with its exact argument count and types.")}if(linked)callTargets.set(node.callee.name,linked);const args=node.arguments.map((arg,index)=>{const value=read(arg);ofSort(file,arg,value,callee.params[index].sort);return value});return invoke(callee,args,fresh)}};const read=(node,bindings)=>readValue(file,node,bindings,undefined,executable);const inferred=inferBody&&read(inferBody,scope);const result=annotatedResult??inferred.sort;if(result==="textOrItems")invalid(file,fn,"Return a scalar or a supported readonly array.");function returned(node,bindings){if(node.type==="ArrayExpression"&&!node.elements.length&&!isScalar(result))return{sort:result,code:"[]"};const value=read(node,bindings);ofSort(file,node,value,result);return value}function assignment(node,bindings){const name=nameOf(file,node.left);const binding=bindings.get(name);if(!binding?.mutable||!isScalar(binding.sort))invalid(file,node.left,"Only scalar let bindings can be assigned.");const rhs=read(node.right,bindings);ofSort(file,node.right,rhs,binding.sort);if(node.operator==="=")return{name,binding,rhs};if(binding.sort==="integer"&&(node.operator==="+="||node.operator==="-=")){return{name,binding,rhs:sequence([rhs],fresh,([value])=>({sort:"integer",code:`(${binding.code} ${node.operator[0]} ${value})`}))}}return invalid(file,node,`Unsupported assignment '${node.operator}'.`)}function line(indent,code){lines.push(" ".repeat(indent)+code)}function force(value,indent){if(!value.fallible)return value.code;fallible=true;const name=fresh();line(indent,`let ${name} \u2190 ${value.code}`);return name}function certifyGuardedUpdate(node,bindings,item,itemCode){if(recursive||arrayGuard===node.test)return;const yes=localUpdate(node.consequent);const no=node.alternate&&localUpdate(node.alternate);if(yes?.left.type!=="Identifier"||node.alternate&&!no)return;const target=yes.left.name;const accumulator=bindings.get(target);if(!accumulator?.mutable||!isScalar(accumulator.sort)||no&&(no.left.type!=="Identifier"||no.left.name!==target))return;const state=fresh();const scope=new Map(bindings);scope.set(target,{...accumulator,code:state});const test=read(node.test,scope);const updated=assignment(yes,scope).rhs;const otherwise=no?assignment(no,scope).rhs:{sort:accumulator.sort,code:state};if(test.fallible||updated.fallible||otherwise.fallible)return;const guard=truthy(test,test.code);function delta(update){if(accumulator?.sort!=="integer")return;const{operator,right}=update;if(operator==="+="||operator==="-=")return{operator:operator[0],code:read(right,scope).code};if(operator==="="&&right.type==="BinaryExpression"&&(right.operator==="+"||right.operator==="-")&&right.left.type==="Identifier"&&right.left.name===target){return{operator:right.operator,code:read(right.right,scope).code}}}let step=`(if ${guard} then ${updated.code} else ${otherwise.code})`;const taken=delta(yes),skipped=no&&delta(no);if(taken&&(!no||skipped?.operator===taken.operator)){step=`(${state} ${taken.operator} (if ${guard} then ${taken.code} else ${skipped?.code??"(0 : Int)"}))`}const used=new Set;for(const expression of[node.test,yes.right,no?.right]){if(expression)traverseFast(expression,(child)=>{if(child.type==="Identifier")used.add(child.name)})}const captured=[...bindings].filter(([name])=>name!==target&&name!==item&&used.has(name));const parameters=captured.map(([,value])=>`(${value.code} : ${leanTypes[value.sort]})`);if(captured.some(([,value])=>value.sort==="items"||value.sort==="textOrItems"))parameters.unshift("{Item : Type}");const name=`${code}Loop${loopConformance.length}Conforms`;loopConformance.push({name,definition:`theorem ${[name,...parameters].join(" ")}
|
|
766
|
+
(values : List Int) (initial : ${leanTypes[accumulator.sort]}) :
|
|
767
|
+
forIn (m := Id) values initial (fun ${itemCode} ${state} =>
|
|
768
|
+
if ${guard} then ForInStep.yield (${updated.code}) else ForInStep.yield (${otherwise.code})) =
|
|
769
|
+
values.foldl (fun ${state} ${itemCode} => ${step}) initial := by
|
|
770
|
+
apply forIn_foldl_of_step_eq
|
|
771
|
+
intro ${itemCode} ${state}
|
|
772
|
+
by_cases h : (${guard}) = true <;> simp only [h, Bool.false_eq_true, if_true, if_false, Int.add_zero, Int.sub_zero]`})}function emitArrayGuard(node,bindings,indent,inLoop){const test=node.test;if(test.type!=="CallExpression"||test.callee.type!=="MemberExpression"||test.callee.computed||test.callee.object.type!=="Identifier"||test.callee.object.name!=="Array"||test.callee.property.type!=="Identifier"||test.callee.property.name!=="isArray")return false;if(test.typeArguments||test.arguments.length!==1)invalid(file,test,"Pass one named union value to Array.isArray.");const name=nameOf(file,test.arguments[0]);const value=bindings.get(name);if(value?.sort!=="textOrItems")invalid(file,test,"Array.isArray expects a string-or-record-array binding.");arrayGuard=test;const narrowed=new Map(bindings),code=fresh();narrowed.set(name,{sort:"items",code});line(indent,`match ${value.code} with`);line(indent,`| some ${code} =>`);branch(node.consequent,narrowed,indent+2,inLoop);line(indent,"| none =>");if(node.alternate)branch(node.alternate,bindings,indent+2,inLoop);else line(indent+2,"pure ()");return true}function emitWhile(node,bindings,indent){const{test,body}=node;const counter=test.type==="BinaryExpression"&&(test.operator===">"||test.operator===">=")&&test.left.type==="Identifier"?test.left.name:undefined;if(!counter||test.type!=="BinaryExpression"||body.type!=="BlockStatement"){invalid(file,node,"Use a braced while loop guarded by a decreasing bigint counter and a literal lower bound.")}const binding=bindings.get(counter);const bound=bigintLiteral(test.right);const last=body.body.at(-1);const assignment=last?.type==="ExpressionStatement"&&last.expression.type==="AssignmentExpression"?last.expression:undefined;const amount=assignment?.operator==="-="&&assignment.left.type==="Identifier"&&assignment.left.name===counter?bigintLiteral(assignment.right):undefined;if(binding?.sort!=="integer"||!binding.mutable||bound===undefined||amount===undefined||amount<=0n){invalid(file,node,"A while loop needs a mutable bigint counter and a final counter -= positiveLiteral update.")}const statements=body.body.slice(0,-1);for(const child of statements)traverseFast(child,(part)=>{if(part.type==="ReturnStatement"||part.type==="BreakStatement"||part.type==="ContinueStatement"){invalid(file,part,"Use a while body that reaches its counter update on every continuing path.")}});countdown=true;const limit=test.operator===">="?bound-1n:bound;const state=[...bindings].filter(([name,value])=>name!==counter&&value.mutable);const stateValues=state.map(([,value])=>value.code);const nextCounter=fresh();const nextState=state.map(fresh);const counterArg=fresh(),stateArg=fresh();const loopScope=new Map(bindings);loopScope.set(counter,{...binding,code:counterArg,mutable:false});line(indent,`let (${nextCounter}, ${state.length?tuple(nextState):"_"}) \u2190 countdownWhile ${binding.code} (${limit} : Int) (${amount} : Int) (by decide)`);line(indent+2,`(fun ${counterArg} ${stateArg} => do`);const stateInputs=state.map(fresh);if(state.length)line(indent+4,`let ${tuple(stateInputs)} := ${stateArg}`);for(const[index,[name,value]]of state.entries()){const code=fresh();line(indent+4,`let mut ${code} := ${stateInputs[index]}`);loopScope.set(name,{...value,code})}for(const child of statements)statement(child,loopScope,indent+4,false);line(indent+4,`return ${tuple(state.map(([name])=>loopScope.get(name).code))}) ${tuple(stateValues)}`);line(indent,`${binding.code} := ${nextCounter}`);for(const[index,original]of stateValues.entries())line(indent,`${original} := ${nextState[index]}`)}function statement(node,bindings,indent,inLoop){switch(node.type){case"EmptyStatement":return;case"ReturnStatement":{if(!node.argument)invalid(file,node,"Return a value.");line(indent,`return ${force(returned(node.argument,bindings),indent)}`);return}case"ThrowStatement":{const value=node.argument;if(value.type!=="NewExpression"||value.callee.type!=="Identifier"||value.typeArguments||!Object.hasOwn(errorKinds,value.callee.name)||moduleNames.has(value.callee.name)||localNames.has(value.callee.name)||value.arguments.length>1||value.arguments[0]&&value.arguments[0].type!=="StringLiteral"){invalid(file,value,"Throw an unshadowed Error, RangeError, or TypeError with an optional string literal.")}fallible=true;line(indent,`throw ErrorKind.${errorKinds[value.callee.name]}`);return}case"TryStatement":{const[attempt]=node.block.body;if(!node.handler||node.handler.param||node.finalizer||node.block.body.length!==1||attempt?.type!=="ReturnStatement"||!attempt.argument){invalid(file,node,"Use try { return expression } with an unbound catch and no finally.")}const value=returned(attempt.argument,bindings);const success=fresh();line(indent,`match (${asOutcome(value)} : Except ErrorKind (${leanTypes[result]})) with`);line(indent,`| .ok ${success} => return ${success}`);line(indent,"| .error _ =>");branch(node.handler.body,bindings,indent+2,inLoop);return}case"BreakStatement":case"ContinueStatement":{if(!inLoop||node.label)invalid(file,node,"Loop control must be unlabelled and inside a for-of loop.");line(indent,node.type==="BreakStatement"?"break":"continue");return}case"VariableDeclaration":{if(node.kind!=="const"&&node.kind!=="let")invalid(file,node,"Expected a const or let declaration.");for(const decl of node.declarations){const name=nameOf(file,decl.id);if(!decl.init||bindings.has(name))invalid(file,decl,"Expected a new, initialized binding.");const value=read(decl.init,bindings);if(!isScalar(value.sort))invalid(file,decl,"Keep array and union inputs as named parameters.");if(decl.id.type==="Identifier"&&decl.id.typeAnnotation){ofSort(file,decl,value,tsSort(file,decl.id.typeAnnotation,decl))}const code=fresh(),mutable=node.kind==="let";const rhs=force(value,indent);bindings.set(name,{sort:value.sort,code,mutable});line(indent,`let ${mutable?"mut ":""}${code} := ${rhs}`)}return}case"ExpressionStatement":{if(node.expression.type!=="AssignmentExpression")invalid(file,node,"Expected a local assignment.");const{binding,rhs}=assignment(node.expression,bindings);line(indent,`${binding.code} := ${force(rhs,indent)}`);return}case"IfStatement":{if(emitArrayGuard(node,bindings,indent,inLoop))return;const value=read(node.test,bindings);if(value.sort!=="integer"&&value.sort!=="number")ofSort(file,node.test,value,"boolean");const test=truthy(value,force(value,indent));line(indent,`if ${recursive?`_${fresh()} : `:""}${test} then`);branch(node.consequent,bindings,indent+2,inLoop);if(node.alternate){line(indent,"else");branch(node.alternate,bindings,indent+2,inLoop)}return}case"WhileStatement":emitWhile(node,bindings,indent);return;case"ForOfStatement":{const decl=node.left.type==="VariableDeclaration"&&node.left.kind==="const"&&node.left.declarations.length===1?node.left.declarations[0]:undefined;if(node.await||!decl||decl.init)invalid(file,node,"Expected a synchronous for (const item of values) loop.");const iterable=read(node.right,bindings);ofSort(file,node.right,iterable,"integers");const item=nameOf(file,decl.id),values=force(iterable,indent);if(bindings.has(item))invalid(file,decl,"The loop item must have a new name.");const loopScope=new Map(bindings),itemCode=fresh();loopScope.set(item,{sort:"integer",code:itemCode});const update=localUpdate(node.body);if(update?.left.type==="Identifier"){const target=update.left.name,accumulator=bindings.get(target);if(accumulator?.mutable&&accumulator.sort==="integer"){const stateCode=fresh();const{rhs}=assignment(update,new Map([...loopScope,[target,{...accumulator,code:stateCode}]]));if(!rhs.fallible){fold=true;const step=`(fun (${stateCode} ${itemCode} : Int) => ${rhs.code})`;line(indent,`${accumulator.code} := List.foldl ${step} ${accumulator.code} ${values}`);return}}}line(indent,`for ${itemCode} in ${values} do`);branch(node.body,loopScope,indent+2,true);const inner=singleStatement(node.body);if(inner.type==="IfStatement")certifyGuardedUpdate(inner,loopScope,item,itemCode);return}default:invalid(file,node,`Unsupported statement '${node.type}' before the final return.`)}}function branch(node,bindings,indent,inLoop){const inner=new Map(bindings);const statements=node.type==="BlockStatement"?node.body:[node];emitStatements(statements,inner,indent,inLoop);const last=statements.at(-1);if(!exits(last)&&last?.type!=="BreakStatement"&&last?.type!=="ContinueStatement")line(indent,"pure ()")}function emitStatements(statements,bindings,indent,inLoop){for(const[i,node]of statements.entries()){if(recursive&&node.type==="IfStatement"&&!node.alternate&&exits(node.consequent)&&i<statements.length-1){statement({...node,alternate:{type:"BlockStatement",body:statements.slice(i+1),directives:[]}},bindings,indent,inLoop);return}statement(node,bindings,indent,inLoop)}}let body;if(fn.body.type==="BlockStatement"){if(!exits(fn.body))invalid(file,fn.body,"The final statement must return a value or throw on every path.");emitStatements(fn.body.body,scope,2,false);body=`${fallible?" do":" Id.run do"}
|
|
773
|
+
${lines.join(`
|
|
774
|
+
`)}`}else{const value=inferred??returned(fn.body,scope);fallible=!!value.fallible;body=`
|
|
775
|
+
${value.code}`}if(arrayGuard&&(moduleNames.has("Array")||localNames.has("Array"))){invalid(file,arrayGuard,"Array.isArray requires an unshadowed Array built-in.")}const resultType=fallible?`Except ErrorKind (${leanTypes[result]})`:leanTypes[result];let termination="";if(recursive){const measure=params.find((param)=>param.sort==="integer");if(!measure||fallible||countdown||itemType){invalid(file,fn,"Direct recursion needs a pure body and a decreasing bigint parameter.")}termination=`
|
|
776
|
+
termination_by ${measure.code}.toNat
|
|
777
|
+
decreasing_by all_goals (simp_wf; try simp_all; omega)`}const definition=`def ${[code,...signature].join(" ")} : ${resultType} :=${body}${termination}`;return{file,name:symbol,code,params,result,itemType,definition,fallible,countdown,fold,loopConformance:fallible?[]:loopConformance,recursive,callees:new Set(callTargets.values()),sourceExpression:scalarSource(fn.body,params,result,callTargets)}}function lowerProgram(source){const modules=new Map;const loading=new Set;const functions=new Map;const compiling=new Map;let nextFunction=0;function load(file,contents){if(loading.has(file))invalid(file,undefined,"Cyclic runtime imports are outside the Lean model.");const cached=modules.get(file);if(cached)return cached;loading.add(file);try{const program=parseSourceModule(file,contents);const module={file,source:contents,program,declarations:{...program,body:[]},imports:new Map,resolvedImports:[]};for(const node of program.body){if(node.type!=="ImportDeclaration"||node.importKind==="type"){module.declarations.body.push(node);continue}if(!source.readModule||node.attributes?.length||node.phase||!node.specifiers.length||!node.specifiers.some((spec)=>spec.type==="ImportSpecifier"&&spec.importKind!=="type")){invalid(file,node,"Use named TypeScript function imports from modules with inert initialization.")}const resolveAgain=()=>resolveTypeScriptImport(file,node.source,dirname2(file));const dependency=source.readModule(resolveAgain(),resolveAgain);const owner=load(dependency.canonical,dependency.source);module.resolvedImports.push({start:node.source.start,end:node.source.end,file:owner.file});for(const spec of node.specifiers){if(spec.type!=="ImportSpecifier"||spec.imported.type!=="Identifier"){invalid(file,spec,"Use a named function import.")}if(spec.importKind==="type")continue;const name=spec.imported.name;selectSubject(owner.declarations,owner.file,name,{allowArrowFunctions:true});module.imports.set(spec.local.name,{owner,name})}}modules.set(file,module);functions.set(module,new Map);compiling.set(module,new Set);return module}finally{loading.delete(file)}}function link(module,name,exported=false){const done=functions.get(module);const cached=done.get(name);if(cached){if(exported)selectSubject(module.declarations,module.file,name,{allowArrowFunctions:true});return cached}const pending=compiling.get(module);if(pending.has(name))invalid(module.file,undefined,"Mutually recursive calls are outside the Lean model.");pending.add(name);try{const fn=selectSubject(module.declarations,module.file,name,{allowArrowFunctions:true,allowLocalFunctions:!exported});const code=exported&&module===owner&&name===source.name?"impl":`fn${nextFunction++}`;const subject=lowerFunction(module.file,module.program,fn,name,code,(callee,at)=>{const imported=module.imports.get(callee);if(imported)return link(imported.owner,imported.name,true);if(pending.has(callee))invalid(module.file,at,"Mutually recursive calls are outside the Lean model.");return link(module,callee)});done.set(name,subject);return subject}finally{pending.delete(name)}}const owner=load(source.file,source.source);const root=link(owner,source.name,true);return{root,modules,resolve(file,name){if(file===owner.file)return link(owner,name,true);if(!source.readModule)invalid(file,undefined,"Linking another export needs a source snapshot.");const dependency=source.readModule(file);return link(load(dependency.canonical,dependency.source),name,true)}}}function definitions(roots){const ordered=new Set;function add(subject){if(ordered.has(subject))return;for(const callee of subject.callees)add(callee);ordered.add(subject)}for(const root of roots)add(root);return[...ordered]}import{mkdirSync,writeFileSync}from"fs";import{join as join2}from"path";var comparisons3={eq:"===",gt:">",gte:">=",lt:"<",lte:"<="};var binary2=new Set(["+","-","*","/","%","&","<<","===","!==","<",">","<=",">=","&&","||"]);function operand(expression,parameters,locals){function read(node){switch(node.type){case"Identifier":return locals.get(node.name)??parameters.get(expression.bindings.get(node.name)??"");case"NumericLiteral":return String(node.value);case"BigIntLiteral":return BigInt(node.value).toString()+"n";case"BooleanLiteral":return String(node.value);case"CallExpression":{const method=node.callee;if(!expression.numberGlobal||locals.has("Number")||expression.bindings.has("Number")||method.type!=="MemberExpression"||method.computed||method.object.type!=="Identifier"||method.object.name!=="Number"||method.property.type!=="Identifier"||!["isInteger","isNaN"].includes(method.property.name)||node.arguments.length!==1)return;const arg=read(node.arguments[0]);return arg&&"Number."+method.property.name+"("+arg+")"}case"UnaryExpression":{const arg=read(node.argument);if(arg&&["-","+","!"].includes(node.operator))return"("+node.operator+arg+")";return}case"BinaryExpression":case"LogicalExpression":{const left=read(node.left),right=read(node.right);if(left&&right&&binary2.has(node.operator))return"("+left+" "+node.operator+" "+right+")";return}case"ConditionalExpression":{const test=read(node.test),yes=read(node.consequent),no=read(node.alternate);if(test&&yes&&no)return"("+test+" ? "+yes+" : "+no+")";return}}}return read(parseExpression(expression.source,{plugins:["typescript"]}))}function predicate(spec,parameters,locals){switch(spec.kind){case"boolean":return operand(spec.expression,parameters,locals);case"not":{const value=predicate(spec.operand,parameters,locals);return value&&"!("+value+")"}case"binary":{const left=predicate(spec.left,parameters,locals),right=predicate(spec.right,parameters,locals);if(!left||!right)return;if(spec.operator==="implies")return"(!("+left+") || "+right+")";const operator={iff:"===",and:"&&",or:"||"}[spec.operator];return"("+left+" "+operator+" "+right+")"}case"quantifier":return}}function replayConstraints(constraints,parameters){const clauses=[];const empty=new Map;for(const constraint of constraints){let clause;if(constraint.kind==="condition")clause=operand(constraint.expression,parameters,empty);else if(constraint.kind==="proposition")clause=predicate(constraint.predicate,parameters,empty);else{const target=constraint.target.kind==="result"?"received":constraint.target.kind==="parameter"?parameters.get(constraint.target.name):undefined;if(!target)return;if(constraint.kind==="sameValue"){const rhs=operand(constraint.value,parameters,empty);if(rhs)clause=`Object.is(${target}, ${rhs})`}else if(constraint.kind==="nearestInteger"){const rhs=operand(constraint.value,parameters,empty);if(rhs)clause=`Object.is(${target}, nearestInteger(${rhs}, ${constraint.ties==="up"}))`}else if(constraint.kind==="comparison"){const rhs=operand(constraint.value,parameters,empty);if(rhs)clause="("+target+" "+comparisons3[constraint.operator]+" "+rhs+")"}else if(constraint.kind==="refinement"){clause=predicate(constraint.predicate,parameters,new Map([[constraint.variable,target]]))}}if(!clause)return;clauses.push(clause)}return clauses.join(" && ")||"true"}var samples={integer:[0n,1n,-1n,2n,9007199254740993n],number:[0,-0,...[1,0.5,0.25,0.125,1/16,1/1024,Number.EPSILON,Number.MIN_VALUE,2**-1022,Number.MAX_SAFE_INTEGER,Number.MAX_VALUE,Infinity].flatMap((x)=>[x,-x]),NaN],boolean:[false,true],integers:[[],[1n],[0n],[2n],[-1n,2n],[1n,1n],[9007199254740993n]]};function inputsFor(program){const numbers=new Set,integers=new Set;for(const module of program.modules.values())traverseFast(module.program,(node)=>{if(node.type==="NumericLiteral"&&numbers.size<32){numbers.add(node.value).add(-node.value)}else if(node.type==="BigIntLiteral"&&integers.size<32){const value=BigInt(node.value);integers.add(value).add(-value)}});let inputs=[[]];for(const{sort}of program.root.params){const base=samples[sort];if(!base)return[];const literals=sort==="number"?numbers:sort==="integer"?integers:[];const domain=[...base,...[...literals].filter((value)=>!base.includes(value))];inputs=inputs.flatMap((input)=>domain.map((value)=>[...input,value])).slice(0,128)}return inputs}function literal(value){if(typeof value==="bigint")return`${value}n`;if(typeof value==="number")return Object.is(value,-0)?"-0":String(value);if(typeof value==="boolean")return String(value);return`[${value.map(literal).join(", ")}]`}async function replayClaim(program,claim,directory){if(claim.kind==="throw")return;const{params,name}=program.root;const observed=claim.observation??{kind:"call",callee:"subject",args:params.map((parameter)=>({kind:"parameter",name:parameter.name}))};const parameters=new Map(params.map((parameter,index)=>[parameter.name,`args[${index}]`]));const modules=new Map;function call(node){const subject=node.callee==="subject"?program.root:program.resolve(node.callee.file,node.callee.name);modules.set(subject.file,modules.get(subject.file)??`module${modules.size}`);const args=node.args.map((arg)=>arg.kind==="parameter"?parameters.get(arg.name):call(arg));return`${modules.get(subject.file)}[${JSON.stringify(subject.name)}](${args.join(", ")})`}const premises=replayConstraints(claim.premises,parameters);const assertions=replayConstraints(claim.assertions,parameters);if(!premises||!assertions)return;const actual=call(observed);const reference=claim.kind==="equal"?call(claim.reference):undefined;const inputs=inputsFor(program);if(!inputs.length)return;const resultSort=(observed.callee==="subject"?program.root:program.resolve(observed.callee.file,observed.callee.name)).result;const candidates=samples[resultSort]?.map(literal).join(", ")??"";const ambiguityCheck=claim.exactResult?`
|
|
778
|
+
const neighbors = typeof received === "bigint" ? [received + 1n, received - 1n] :
|
|
779
|
+
typeof received === "number" ? [received + 1, received - 1, -received] : [!received];
|
|
780
|
+
const alternative = [...neighbors, ${candidates}].find(value => !Object.is(received, value) && accepts(value));
|
|
781
|
+
if (alternative !== undefined) {
|
|
782
|
+
process.stdout.write(JSON.stringify({ index, received: display(received), alternative: display(alternative) }));
|
|
783
|
+
break;
|
|
784
|
+
}`:"";const files=new Map([...program.modules.keys()].map((file,index)=>[file,`subject-${index}.ts`]));mkdirSync(directory);for(const[file,snapshot]of program.modules){const rewritten=[...snapshot.resolvedImports].reverse().reduce((contents,entry)=>contents.slice(0,entry.start)+JSON.stringify(`./${files.get(entry.file)}`)+contents.slice(entry.end),snapshot.source);writeFileSync(join2(directory,files.get(file)),rewritten)}const imports=[...modules].map(([file,alias])=>`import * as ${alias} from "./${files.get(file)}";`);writeFileSync(join2(directory,"replay.ts"),`${imports.join(`
|
|
785
|
+
`)}
|
|
786
|
+
const inputs = [${inputs.map((values)=>`[${values.map(literal).join(", ")}]`).join(`,
|
|
787
|
+
`)}];
|
|
788
|
+
const display = value => typeof value === "bigint" ? String(value) + "n" : Object.is(value, -0) ? "-0" : String(value);
|
|
789
|
+
function nearestInteger(x, tiesUp) {
|
|
790
|
+
const lower = Math.floor(x), upper = Math.ceil(x);
|
|
791
|
+
if (lower === upper) return lower;
|
|
792
|
+
const midpoint = lower + 0.5;
|
|
793
|
+
return (tiesUp ? x < midpoint : x <= midpoint) ? lower : upper;
|
|
794
|
+
}
|
|
795
|
+
for (const [index, args] of inputs.entries()) {
|
|
796
|
+
if (!(${premises})) continue;
|
|
797
|
+
let received;
|
|
798
|
+
try { received = ${actual}; } catch { continue; }
|
|
799
|
+
${reference?`let expected;
|
|
800
|
+
try { expected = ${reference}; } catch { continue; }
|
|
801
|
+
if (received === expected) continue;
|
|
802
|
+
process.stdout.write(JSON.stringify({ index, expected: display(expected), received: display(received) }));`:`const accepts = received => ${assertions};
|
|
803
|
+
if (accepts(received)) {${ambiguityCheck}
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
process.stdout.write(JSON.stringify({ index, received: display(received) }));`}
|
|
807
|
+
break;
|
|
808
|
+
}
|
|
809
|
+
`);const run=await runProver(process.execPath,["--no-env-file","run","replay.ts"],{cwd:directory,timeout:3000,maxBuffer:64*1024});if(run.status!==0)throw new Error(run.stderr.trim()||`Bun exited with status ${run.status}.`);if(!run.stdout)return;const{index,expected,received,alternative}=JSON.parse(run.stdout);const witness=inputs[index];if(!witness||reference&&typeof expected!=="string"||typeof received!=="string")throw new Error("Bun returned an invalid witness.");return{summary:alternative!==undefined?`The result rule permits both ${received} and ${alternative} for the same input.`:expected===undefined?`${name} returned ${received}, violating the result assertion in Bun.`:received==="NaN"&&expected==="NaN"?"Both calls returned NaN, which fails JavaScript strict equality.":`${name} returned a different value from the reference in Bun.`,input:Object.fromEntries(params.map((parameter,i)=>[parameter.name,literal(witness[i])])),result:received,...alternative!==undefined&&{alternative},...expected!==undefined&&{difference:{subject:name,expected,received}}}}var lean=native2("lean");var trustedAxioms=new Set(["propext","Quot.sound","Classical.choice"]);var operators2={eq:"=",gt:">",gte:"\u2265",lt:"<",lte:"\u2264"};var jsOperators={eq:"===",gt:">",gte:">=",lt:"<",lte:"<="};var modeledErrors=Object.keys(errorKinds);var errors=`inductive ErrorKind where
|
|
810
|
+
${Object.values(errorKinds).map((kind)=>` | ${kind}`).join(`
|
|
811
|
+
`)}
|
|
812
|
+
deriving DecidableEq, Repr`;var autoProof=(unfold,recursive,numbers,fallible)=>`by
|
|
813
|
+
simp only [claim]
|
|
814
|
+
intros
|
|
815
|
+
first
|
|
816
|
+
| rfl${fallible?`
|
|
817
|
+
| solve | simp (disch := omega) [${unfold}, pure, Except.pure, bind, Except.bind, if_neg, if_pos]`:""}${numbers?`
|
|
818
|
+
| solve | simp (disch := assumption) only [${unfold}, pure, JSNumber.round_integer, JSNumber.floor_integer,
|
|
819
|
+
JSNumber.ceil_integer, JSNumber.trunc_integer, JSNumber.round_eq_zero, JSNumber.mul_comm,
|
|
820
|
+
JSNumber.nearestInteger_round, JSNumber.nearestInteger_round_down]
|
|
821
|
+
| solve
|
|
822
|
+
| simp (disch := decide) only [${unfold}, JSNumber.mul_neg, JSNumber.div_neg, JSNumber.mul_comm,
|
|
823
|
+
JSNumber.round_eq_zero, JSNumber.eq_self, JSNumber.isNaN_neg, JSNumber.isNaN_mul_right,
|
|
824
|
+
JSNumber.isNaN_mul_left, JSNumber.isNaN_div_right, Bool.not_eq_true'] at * <;> assumption
|
|
825
|
+
| simp only [${unfold}] at *
|
|
826
|
+
try apply JSNumber.nonnegative_round
|
|
827
|
+
first | apply JSNumber.nonnegative_mul <;> first | assumption | decide
|
|
828
|
+
| apply JSNumber.negative_div <;> first | assumption | decide
|
|
829
|
+
| simp only [${unfold}] at *
|
|
830
|
+
try simp (disch := decide) only [JSNumber.eq_regular] at *
|
|
831
|
+
subst_vars
|
|
832
|
+
decide +kernel`:""}
|
|
833
|
+
| try simp_all [${unfold}, Int.add_nonneg, Int.tmod_eq_emod_of_nonneg, Int.tdiv_eq_ediv_of_nonneg]
|
|
834
|
+
all_goals (repeat' (split <;> try simp_all))
|
|
835
|
+
all_goals ((try simp (disch := omega) [Int.tmod_eq_emod_of_nonneg, Int.tdiv_eq_ediv_of_nonneg] at *) <;> (first | rfl | omega))${recursive.length?`
|
|
836
|
+
| solve | simp_all (config := { maxSteps := 500 }) [${unfold}, ${recursive.join(", ")}]`:""}
|
|
837
|
+
| try simp_all [${unfold}]
|
|
838
|
+
all_goals (repeat' (first | split | constructor))
|
|
839
|
+
all_goals ((try simp_all) <;> omega)`;function proofType(sort,itemType){switch(sort){case"integer":case"number":case"boolean":return{kind:sort};case"integers":return{kind:"array",item:{kind:"integer"}};case"items":return{kind:"array",item:{kind:"opaque",name:itemType}};case"textOrItems":return{kind:"textOrArray",item:{kind:"opaque",name:itemType}}}}var emptyScope=new Map;var logicalOperators={and:"\u2227",or:"\u2228",implies:"\u2192",iff:"\u2194"};function readOperand(expression,parameters,locals,read){const{file,source,line,column,offset,bindings,schemaBindings}=expression;const scope=new Map([...bindings].map(([name,parameter])=>[name,parameters.get(parameter)]));for(const[name,value]of locals)scope.set(name,value);try{const node=parseExpression(source,{plugins:["typescript"],startLine:line,startColumn:column,startIndex:offset});return read(file,node,scope,schemaBindings,expression.numberGlobal)}catch(error){if(error instanceof Unsupported2)throw error;throw new Unsupported2(`${file}:${line}:${column+1}: ${error.message}`)}}function indent(code){return code.split(`
|
|
840
|
+
`).map((line)=>` ${line}`).join(`
|
|
841
|
+
`)}function observe(program,observation){const{root}=program;const roots=new Set([root]);const parameters=new Map(root.params.map((param)=>[param.name,param]));let next=0;const fresh=()=>`callArg${next++}`;function call(node){const subject=node.callee==="subject"?root:program.resolve(node.callee.file,node.callee.name);if(subject.itemType||subject.params.length!==node.args.length){throw new Unsupported2("Pass the full signature of each function in a composed call.")}roots.add(subject);const args=node.args.map((arg,index)=>{const param=arg.kind==="parameter"?parameters.get(arg.name):undefined;const operand=arg.kind==="call"?call(arg):param&&{value:param,source:scalarValue(param.sort,param.code)};if(operand?.value.sort!==subject.params[index].sort){throw new Unsupported2("Each argument in a composed call must match the callee's declared type.")}return operand});return{value:invoke(subject,args.map((arg)=>arg.value),fresh),source:scalarCall(subject,args.map((arg)=>arg.source),fresh)}}const args=[root.itemType&&"(Item := Item)",...root.params.map((param)=>param.code)].filter(Boolean);const observed=observation?call(observation):{value:{sort:root.result,code:[root.code,...args].join(" "),fallible:root.fallible},source:root.sourceExpression&&(root.result==="integer"||root.result==="boolean")?{sort:root.result,code:`(${[`${root.code}Source`,...args].join(" ")})`}:undefined};return{...observed,linked:definitions([...roots])}}function loweringProof(observed,binders){if(!observed.source)return;const proved=observed.linked.filter((subject)=>subject.sourceExpression);function normalize(rewrite){const rules=[...rewrite,"Scalar.lower","Scalar.Binary.lower","Scalar.Unary.apply","Id.run","bind","pure","Except.pure"];return`first
|
|
842
|
+
| rfl
|
|
843
|
+
| simp [${rules.join(", ")}]
|
|
844
|
+
all_goals (repeat' (split <;> try simp_all))
|
|
845
|
+
all_goals (first | rfl | simp_all | omega)`}const sourceDefinitions=proved.map((subject)=>{const source=subject.code+"Source";const params=subject.params.map((p)=>` (${p.code} : ${leanTypes[p.sort]})`).join("");const args=subject.params.map((p)=>" "+p.code).join("");const invocation={sort:subject.result,code:subject.code+args,fallible:subject.fallible};return`def ${source}${params} : Scalar.Expr ErrorKind .${subject.result} :=
|
|
846
|
+
${subject.sourceExpression}
|
|
847
|
+
|
|
848
|
+
theorem ${subject.code}Lowering${params} :
|
|
849
|
+
Scalar.lower (${source}${args}) = ${asOutcome(invocation)} := by
|
|
850
|
+
${indent(normalize([source,subject.code,...[...subject.callees].map((callee)=>callee.code+"Lowering")]))}`});return[...sourceDefinitions,`def loweringClaim : Prop :=
|
|
851
|
+
${binders?`\u2200 ${binders},
|
|
852
|
+
`:""}Scalar.evaluate ${observed.source.code} = ${asOutcome(observed.value)}
|
|
853
|
+
|
|
854
|
+
theorem loweringCertificate : loweringClaim := by
|
|
855
|
+
simp only [loweringClaim]
|
|
856
|
+
intros
|
|
857
|
+
rw [Scalar.preservation]
|
|
858
|
+
${indent(normalize(proved.map((subject)=>subject.code+"Lowering")))}`].join(`
|
|
859
|
+
|
|
860
|
+
`)}function checkedClaim(input){const{kind:tag,assertions,exactResult,expectedError,reference,...common}=input;const kind=tag??(expectedError!==undefined?"throw":reference!==undefined?"equal":"return");const returns=Boolean(assertions.length||exactResult);if(kind==="return"&&returns&&reference===undefined&&expectedError===undefined){return{...common,kind,assertions,exactResult}}if(kind==="equal"&&reference&&!returns&&expectedError===undefined){return{...common,kind,reference,assertions:[]}}if(kind==="throw"&&expectedError&&Object.hasOwn(errorKinds,expectedError)&&!returns&&reference===undefined){return{...common,kind,expectedError,assertions:[]}}throw new Unsupported2("State a return predicate, equality between calls, or one modeled exception.")}function generate(program,input,imports){const claim=checkedClaim(input);const{params,itemType}=program.root;const observed=observe(program,claim.observation);const execution=observed.value;if(claim.exactResult&&!isScalar(execution.sort)){throw new Unsupported2("Use an exact result schema for a scalar return value.")}const reference=claim.kind==="equal"?observe(program,claim.reference):undefined;if(reference&&(!isScalar(execution.sort)||reference.value.sort!==execution.sort||reference.value.fallible||execution.fallible)){throw new Unsupported2("Use toEqual() with two nonthrowing calls returning the same scalar type.")}const linked=reference?definitions([...observed.linked,...reference.linked]):observed.linked;const parameters=new Map(params.map((p)=>[p.name,p]));const result={sort:execution.sort,code:"result"};let nextBinder=0;function operand(expression,locals,expected){return readOperand(expression,parameters,locals,(file,node,scope,helpers,numberGlobal)=>{const value=readValue(file,node,scope,helpers,undefined,numberGlobal);return expected?ofSort(file,node,value,expected):value.code})}function term(proof,locals){if(proof.assistant!=="lean")throw new Unsupported2(`This proof term requires ${proof.assistant}.`);const args=proof.args.map((arg)=>operand(arg,locals));if(proof.kind==="reference")return[proof.name,...args].join(" ");return`(${proof.parts.map((part,i)=>i?`(${args[i-1]})${part}`:part).join("")})`}function predicate(spec,locals){switch(spec.kind){case"boolean":return readOperand(spec.expression,parameters,locals,readProposition);case"not":return`(\xAC ${predicate(spec.operand,locals)})`;case"binary":return`(${predicate(spec.left,locals)} ${logicalOperators[spec.operator]} ${predicate(spec.right,locals)})`;case"quantifier":{const{domain}=spec;const value={sort:domain.kind==="schema"?domain.type:"integer",code:`q${nextBinder++}`};const restrictions=domain.kind==="schema"?domain.constraints.map((clause)=>renderConstraint(clause,locals,value)):[`(${value.code} \u2208 ${operand(domain.expression,locals,"integers")})`];const body=predicate(spec.predicate,new Map([...locals,[spec.variable,value]]));const binder=`(${value.code} : ${leanTypes[value.sort]})`;const connective=spec.quantifier==="forall"?"\u2192":"\u2227";const symbol=spec.quantifier==="forall"?"\u2200":"\u2203";const guarded=restrictions.length?`(${restrictions.join(" \u2227 ")}) ${connective} ${body}`:body;return`(${symbol} ${binder}, ${guarded})`}}}function renderConstraint(constraint,locals,quantified){if(constraint.kind==="condition")return`(${operand(constraint.expression,locals,"boolean")} = true)`;if(constraint.kind==="proposition")return predicate(constraint.predicate,locals);const target=constraint.target;const value=target.kind==="result"?result:target.kind==="quantified"?quantified:parameters.get(target.name);if(!value)throw new Unsupported2("The property constraint has no corresponding value.");if(constraint.kind==="refinement")return predicate(constraint.predicate,new Map([...locals,[constraint.variable,value]]));if(constraint.kind==="native")return`((${term(constraint.term,locals)} ${value.code}) : Prop)`;const rhs=operand(constraint.value,locals,value.sort);if(constraint.kind==="sameValue"){if(value.sort!=="number")throw new Unsupported2("Use sameValue() with a JavaScript number.");return`(${value.code} = ${rhs})`}if(constraint.kind==="nearestInteger"){if(value.sort!=="number")throw new Unsupported2("Use nearestIntegerTo() with a JavaScript number.");return`(${value.code} = JSNumber.nearestInteger (${rhs}) ${constraint.ties==="up"})`}if(value.sort==="number")return`(${numberBinary(jsOperators[constraint.operator],value.code,rhs).code} = true)`;return`(${value.code} ${operators2[constraint.operator]} ${rhs})`}const render=(constraint)=>renderConstraint(constraint,emptyScope);const binders=[itemType&&"(Item : Type)",...params.map((param)=>`(${param.code} : ${leanTypes[param.sort]})`)].filter(Boolean).join(" ");const premises=claim.premises.map((p)=>`${render(p)} \u2192`);const assertions=claim.assertions.map(render).join(` \u2227
|
|
861
|
+
`)||"True";const binding=claim.exactResult?"actual":"result";const postcondition=claim.exactResult?`\u2200 (result : ${leanTypes[execution.sort]}), (${assertions}) \u2194 result = actual`:assertions;function goal(outcome){if(claim.kind==="throw")return outcome.fallible?`(${outcome.code}) = .error ErrorKind.${errorKinds[claim.expectedError]}`:"False";if(reference)return outcome.sort==="number"?`JSNumber.eq (${outcome.code}) (${reference.value.code}) = true`:`(${outcome.code}) = (${reference.value.code})`;return outcome.fallible?`match (${outcome.code}) with
|
|
862
|
+
| .ok ${binding} =>
|
|
863
|
+
${indent(postcondition)}
|
|
864
|
+
| .error _ => False`:`let ${binding} := ${outcome.code}
|
|
865
|
+
${postcondition}`}function proposition(outcome){return[binders&&`\u2200 ${binders},`,...premises,goal(outcome)].filter(Boolean).join(`
|
|
866
|
+
`)}const simplify=[...linked.filter((subject)=>!subject.recursive).map((subject)=>subject.code),"Id.run"].join(", ");const recursive=linked.filter((subject)=>subject.recursive).map((subject)=>subject.code);const countdown=linked.some((subject)=>subject.countdown);const fold=linked.some((subject)=>subject.fold);const loopConformance=linked.flatMap((subject)=>subject.loopConformance);if(countdown)recursive.push("countdownWhile");const certificate=reference?undefined:loweringProof(observed,binders);const sourceClaim=certificate&&observed.source&&proposition({sort:observed.source.sort,code:`Scalar.evaluate ${observed.source.code}`,fallible:true});const claimText=proposition(execution);const usesNumbers=linked.some((subject)=>subject.definition.includes("JSNumber"))||claimText.includes("JSNumber");let proof=claim.proof?term(claim.proof,emptyScope):autoProof(simplify,recursive,usesNumbers,!!execution.fallible);if(claim.proof?.kind==="reference"&&loopConformance.length){const rewrites=loopConformance.map(({name})=>name).join(", ");proof=`by
|
|
867
|
+
first
|
|
868
|
+
| exact (${proof})
|
|
869
|
+
| simpa only [claim, ${simplify}, bind, pure, ${rewrites}] using (${proof})`}const unit=["import Std",...imports.map((module)=>`import ${module}`),"",...usesNumbers?[numberSemantics,""]:[],...certificate?[scalarSemantics,""]:[],...countdown||fold||loopConformance.length?[iterationSemantics,""]:[],"namespace Pud","","set_option autoImplicit false","",errors,"",linked.map((subject)=>subject.definition).join(`
|
|
870
|
+
|
|
871
|
+
`),"",...loopConformance.flatMap(({definition})=>[definition,""]),...certificate?[certificate,""]:[],"def claim : Prop :=",indent(claimText),"",...sourceClaim?["def sourceClaim : Prop :=",indent(sourceClaim),""]:[],"theorem checked : claim :=",indent(proof),"",...sourceClaim?[`theorem sourceChecked : sourceClaim := by
|
|
872
|
+
have preservation := loweringCertificate
|
|
873
|
+
unfold loweringClaim at preservation
|
|
874
|
+
simpa [sourceClaim, claim, preservation] using checked`,""]:[],"end Pud",""].join(`
|
|
875
|
+
`);const iterationTheorems=[...countdown?["Pud.countdownWhile_except_correct","Pud.countdownWhile_pure_correct"]:[],...fold?["Pud.denseForOf_correct"]:[],...loopConformance.map(({name})=>`Pud.${name}`)];return{unit,claim,certifiedLowering:!!certificate,iterationTheorems}}class RejectedProof extends Error{}function leanAt(dir,command){return async(module,source,compile=false)=>{const file=`${module}.lean`;const artifact=`${module}.olean`;writeFileSync2(join3(dir,file),source);const run=await runProver(command.binary,compile?["-o",artifact,file]:[file],{cwd:dir,env:{...command.env,LEAN_PATH:dir},timeout:30000,maxBuffer:1024*1024}).catch((error)=>{if(error.code==="ENOENT")throw new Error("Install Lean with Elan or set PUD_LEAN to a working Lean executable.");if(error.signal)throw new Error(`Lean was interrupted by ${error.signal} while checking ${file}.`);throw error});if(run.status!==0)throw new RejectedProof([run.stdout,run.stderr].filter(Boolean).join(`
|
|
876
|
+
`).trim()||`Lean rejected ${file}.`);if(compile&&!existsSync(join3(dir,artifact)))throw new Error(`Lean did not produce ${artifact}.`);return run.stdout.trim()}}async function audit(module,run,certificate){const{certifiedLowering,iterationTheorems}=certificate;const certificates=["pudAuditCertificate",...certifiedLowering?["pudLoweringAuditCertificate","pudSourceAuditCertificate"]:[],...iterationTheorems];const report=await run("PudAudit",[`import ${module}`,"set_option autoImplicit false","theorem pudAuditCertificate : Pud.claim := Pud.checked",...certifiedLowering?["theorem pudLoweringAuditCertificate : Pud.loweringClaim := Pud.loweringCertificate","theorem pudSourceAuditCertificate : Pud.sourceClaim := Pud.sourceChecked"]:[],...certificates.map((name)=>`#print axioms ${name}`),""].join(`
|
|
877
|
+
`));const lines=report.split(`
|
|
878
|
+
`);const approved=certificates.every((name,index)=>{const line=lines[index];if(line===`'${name}' does not depend on any axioms`)return true;const prefix=`'${name}' depends on axioms: [`;return line?.startsWith(prefix)&&line.endsWith("]")&&line.slice(prefix.length,-1).split(",").every((axiom)=>trustedAxioms.has(axiom.trim()))});if(lines.length!==certificates.length||!approved){throw new RejectedProof(`Lean did not certify the expected claim with approved axioms.
|
|
879
|
+
${report}`)}}function moduleNames(modules){return modules.map(({file},i)=>{if(!file.endsWith(".lean"))throw new Unsupported2(`Expected a .lean support module. Received ${file}.`);return`PudSupport${i}`})}async function verify(program,source,options,claims,modules,onClaim){const imports=moduleNames(modules);const units=claims.map((claim)=>{try{return generate(program,claim,imports)}catch(error){if(!(error instanceof Unsupported2))throw error;return{outcome:{status:"unsupported",detail:error.message}}}});if(units.every((entry)=>("outcome"in entry)))return units.map((entry)=>entry.outcome);const dir=mkdtempSync(join3(tmpdir(),"pud-lean-"));try{const run=leanAt(dir,leanCommand(source,options));for(const[i,module]of modules.entries()){try{await run(imports[i],module.source,true)}catch(error){throw new Error(`${module.file}
|
|
880
|
+
${error.message}`)}}const outcomes=[];for(const[i,entry]of units.entries()){if("outcome"in entry){outcomes.push(entry.outcome);onClaim?.(i,"finished",entry.outcome.status);continue}onClaim?.(i,"running");let outcome;try{const module=`PudClaim${i}`;await run(module,entry.unit,true);await audit(module,run,entry);outcome={status:"proved"}}catch(error){const detail=error.message;outcome=error instanceof RejectedProof&&entry.claim.exactResult?{status:"unproved",detail:"Lean could not prove that the rule accepts exactly the returned value for each admitted input.",diagnostic:detail}:{status:error instanceof RejectedProof?"unproved":"error",detail};if(error instanceof RejectedProof&&options.replay){try{const counterexample=await replayClaim(program,entry.claim,join3(dir,`replay-${i}`));if(counterexample)outcome={status:"disproved",counterexample}}catch(replayError){outcome={status:"error",detail:`Bun replay failed. ${replayError.message}`,diagnostic:detail}}}}outcomes.push(outcome);onClaim?.(i,"finished",outcome.status)}return outcomes}finally{rmSync(dir,{recursive:true,force:true})}}function leanAdapter(options={}){return{id:"lean",prepare(source){const program=lowerProgram(source);const subject=program.root;return{parameters:subject.params.map((p)=>({name:p.name,type:proofType(p.sort,subject.itemType)})),result:proofType(subject.result,subject.itemType),inspectCall(call){return proofType(observe(program,call).value.sort,undefined)},callEquality:true,exactResults:true,errors:modeledErrors,emit(claim,modules){return generate(program,claim,moduleNames(modules)).unit},verify(claims,modules,onClaim){return verify(program,source,options,claims,modules,onClaim)}}}}}export{lean,leanAdapter};
|