@fable-org/fable-library-js 2.0.0-rc.5 → 2.0.0-rc.6

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/Array.js CHANGED
@@ -3,8 +3,9 @@ import { Helpers_allocateArrayFromCons } from "./Native.js";
3
3
  import { setItem as setItem_1, item as item_2 } from "./Array.js";
4
4
  import { value as value_2, map as map_1, defaultArg, some } from "./Option.js";
5
5
  import { min as min_1, max as max_1 } from "./Double.js";
6
- import { SR_indexOutOfBounds } from "./Global.js";
6
+ import { SR_notEnoughElements, SR_inputMustBeNonNegative, SR_inputSequenceEmpty, SR_Arg_ArgumentOutOfRangeException, SR_indexOutOfBounds } from "./Global.js";
7
7
  import { Operators_IsNull } from "./FSharp.Core.js";
8
+ import { nonSeeded } from "./Random.js";
8
9
  function indexNotFound() {
9
10
  throw new Exception("An index satisfying the predicate was not found in the collection.");
10
11
  }
@@ -1173,6 +1174,105 @@ export function insertManyAt(index, ys, xs, cons) {
1173
1174
  }
1174
1175
  return target;
1175
1176
  }
1177
+ export function randomShuffleInPlaceBy(randomizer, xs) {
1178
+ const len = xs.length | 0;
1179
+ for (let i = len - 1; i >= 1; i--) {
1180
+ const r = randomizer();
1181
+ if ((r < 0) ? true : (r >= 1)) {
1182
+ throw new Exception((SR_Arg_ArgumentOutOfRangeException + "\\nParameter name: ") + "randomizer");
1183
+ }
1184
+ const j = ~~(r * (i + 1)) | 0;
1185
+ const tmp = item_2(i, xs);
1186
+ setItem_1(xs, i, item_2(j, xs));
1187
+ setItem_1(xs, j, tmp);
1188
+ }
1189
+ }
1190
+ export function randomShuffleInPlaceWith(random, xs) {
1191
+ randomShuffleInPlaceBy(() => random.NextDouble(), xs);
1192
+ }
1193
+ export function randomShuffleInPlace(xs) {
1194
+ randomShuffleInPlaceWith(nonSeeded(), xs);
1195
+ }
1196
+ export function randomShuffleBy(randomizer, xs) {
1197
+ const arr = copy(xs);
1198
+ randomShuffleInPlaceBy(randomizer, arr);
1199
+ return arr;
1200
+ }
1201
+ export function randomShuffleWith(random, xs) {
1202
+ return randomShuffleBy(() => random.NextDouble(), xs);
1203
+ }
1204
+ export function randomShuffle(xs) {
1205
+ return randomShuffleWith(nonSeeded(), xs);
1206
+ }
1207
+ export function randomChoiceBy(randomizer, xs) {
1208
+ if (isEmpty(xs)) {
1209
+ throw new Exception((SR_inputSequenceEmpty + "\\nParameter name: ") + "source");
1210
+ }
1211
+ const len = xs.length | 0;
1212
+ const r = randomizer();
1213
+ if ((r < 0) ? true : (r >= 1)) {
1214
+ throw new Exception((SR_Arg_ArgumentOutOfRangeException + "\\nParameter name: ") + "randomizer");
1215
+ }
1216
+ return item_2(~~(r * len), xs);
1217
+ }
1218
+ export function randomChoiceWith(random, xs) {
1219
+ return randomChoiceBy(() => random.NextDouble(), xs);
1220
+ }
1221
+ export function randomChoice(xs) {
1222
+ return randomChoiceWith(nonSeeded(), xs);
1223
+ }
1224
+ export function randomChoicesBy(randomizer, count, xs, cons) {
1225
+ if (count < 0) {
1226
+ throw new Exception((SR_inputMustBeNonNegative + "\\nParameter name: ") + "count");
1227
+ }
1228
+ if ((count > 0) && isEmpty(xs)) {
1229
+ throw new Exception((SR_inputSequenceEmpty + "\\nParameter name: ") + "source");
1230
+ }
1231
+ const len = xs.length | 0;
1232
+ return initialize(count, (_arg) => {
1233
+ const r = randomizer();
1234
+ if ((r < 0) ? true : (r >= 1)) {
1235
+ throw new Exception((SR_Arg_ArgumentOutOfRangeException + "\\nParameter name: ") + "randomizer");
1236
+ }
1237
+ return item_2(~~(r * len), xs);
1238
+ }, cons);
1239
+ }
1240
+ export function randomChoicesWith(random, count, xs, cons) {
1241
+ return randomChoicesBy(() => random.NextDouble(), count, xs, cons);
1242
+ }
1243
+ export function randomChoices(count, xs, cons) {
1244
+ return randomChoicesWith(nonSeeded(), count, xs, cons);
1245
+ }
1246
+ export function randomSampleBy(randomizer, count, xs) {
1247
+ if (count < 0) {
1248
+ throw new Exception((SR_inputMustBeNonNegative + "\\nParameter name: ") + "count");
1249
+ }
1250
+ const arr = copy(xs);
1251
+ const len = arr.length | 0;
1252
+ if ((len === 0) && (count > 0)) {
1253
+ throw new Exception((SR_inputSequenceEmpty + "\\nParameter name: ") + "source");
1254
+ }
1255
+ if (count > len) {
1256
+ throw new Exception((SR_notEnoughElements + "\\nParameter name: ") + "count");
1257
+ }
1258
+ for (let i = 0; i <= (count - 1); i++) {
1259
+ const r = randomizer();
1260
+ if ((r < 0) ? true : (r >= 1)) {
1261
+ throw new Exception((SR_Arg_ArgumentOutOfRangeException + "\\nParameter name: ") + "randomizer");
1262
+ }
1263
+ const j = (i + ~~(r * (len - i))) | 0;
1264
+ const tmp = item_2(i, arr);
1265
+ setItem_1(arr, i, item_2(j, arr));
1266
+ setItem_1(arr, j, tmp);
1267
+ }
1268
+ return getSubArray(arr, 0, count);
1269
+ }
1270
+ export function randomSampleWith(random, count, xs) {
1271
+ return randomSampleBy(() => random.NextDouble(), count, xs);
1272
+ }
1273
+ export function randomSample(count, xs) {
1274
+ return randomSampleWith(nonSeeded(), count, xs);
1275
+ }
1176
1276
  export function removeAt(index, xs) {
1177
1277
  if ((index < 0) ? true : (index >= xs.length)) {
1178
1278
  throw new Exception((SR_indexOutOfBounds + "\\nParameter name: ") + "index");
package/Async.js CHANGED
@@ -48,28 +48,19 @@ export function throwIfCancellationRequested(token) {
48
48
  throw new Exception("Operation is cancelled");
49
49
  }
50
50
  }
51
- function throwAfter(millisecondsDueTime) {
52
- return protectedCont((ctx) => {
53
- let tokenId;
54
- const timeoutId = setTimeout(() => {
55
- ctx.cancelToken.removeListener(tokenId);
56
- ctx.onError(TimeoutException_$ctor());
57
- }, millisecondsDueTime);
58
- tokenId = ctx.cancelToken.addListener(() => {
59
- clearTimeout(timeoutId);
60
- ctx.onCancel(new OperationCanceledException());
61
- });
62
- });
63
- }
64
51
  export function startChild(computation, ms) {
52
+ const promise = startAsPromise(computation);
53
+ let promiseToRun = promise;
65
54
  if (ms) {
66
- const computationWithTimeout = protectedBind(parallel2(computation, throwAfter(ms)), xs => protectedReturn(xs[0]));
67
- return startChild(computationWithTimeout);
55
+ // Race the computation against a timeout: whichever settles first wins.
56
+ promiseToRun = new Promise((resolve, reject) => {
57
+ const timeoutId = setTimeout(() => reject(TimeoutException_$ctor()), ms);
58
+ promise.then(value => { clearTimeout(timeoutId); resolve(value); }, error => { clearTimeout(timeoutId); reject(error); });
59
+ });
68
60
  }
69
- const promise = startAsPromise(computation);
70
61
  // JS Promises are hot, computation has already started
71
62
  // but we delay returning the result
72
- return protectedCont((ctx) => protectedReturn(awaitPromise(promise))(ctx));
63
+ return protectedCont((ctx) => protectedReturn(awaitPromise(promiseToRun))(ctx));
73
64
  }
74
65
  export function awaitPromise(p) {
75
66
  return fromContinuations((conts) => p.then(conts[0]).catch((err) => (err instanceof OperationCanceledException
@@ -99,9 +90,6 @@ export function ignore(computation) {
99
90
  export function parallel(computations) {
100
91
  return delay(() => awaitPromise(Promise.all(Array.from(computations, (w) => startAsPromise(w)))));
101
92
  }
102
- function parallel2(a, b) {
103
- return delay(() => awaitPromise(Promise.all([startAsPromise(a), startAsPromise(b)])));
104
- }
105
93
  export function sequential(computations) {
106
94
  function _sequential(computations) {
107
95
  let pr = Promise.resolve([]);
package/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 2.0.0-rc.6 - 2026-04-07
11
+
12
+ ### Fixed
13
+
14
+ * [JS/TS] Fix `Async.StartChild` with timeout always timing out even when the computation finishes before the deadline (fixes #4481) (by @MangelMaxime)
15
+
10
16
  ## 2.0.0-rc.5 - 2026-03-31
11
17
 
12
18
  ### Fixed
package/Guid.js CHANGED
@@ -56,15 +56,33 @@ export function tryParse(str, defValue) {
56
56
  return false;
57
57
  }
58
58
  }
59
- // From https://gist.github.com/LeverOne/1308368
60
59
  export function newGuid() {
61
- let b = "";
62
- for (let a = 0; a++ < 36;) {
63
- b += a * 51 & 52
64
- ? (a ^ 15 ? 8 ^ Math.random() * (a ^ 20 ? 16 : 4) : 4).toString(16)
65
- : "-";
66
- }
67
- return b;
60
+ const bytes = new Uint8Array(16);
61
+ crypto.getRandomValues(bytes);
62
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
63
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
64
+ const hex = Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
65
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
66
+ }
67
+ // RFC 9562 UUID v7
68
+ export function createVersion7(timestamp) {
69
+ const ms = timestamp != null ? timestamp.getTime() : Date.now();
70
+ // 48-bit timestamp as hex
71
+ const msHex = Math.floor(ms).toString(16).padStart(12, "0");
72
+ // random bits
73
+ const bytes = new Uint8Array(10);
74
+ crypto.getRandomValues(bytes);
75
+ const view = new DataView(bytes.buffer);
76
+ const randA = view.getUint16(0) & 0x0fff; // 12 bits
77
+ const randB1 = view.getUint16(2) & 0x3fff; // 14 bits
78
+ const randB2 = view.getUint32(4); // 32 bits
79
+ const randB3 = view.getUint16(8); // 16 bits
80
+ const timeLow = msHex.slice(0, 8);
81
+ const timeMid = msHex.slice(8, 12);
82
+ const ver = (0x7000 | randA).toString(16).padStart(4, "0");
83
+ const variantAndRandB = (0x8000 | randB1).toString(16).padStart(4, "0");
84
+ const node = randB2.toString(16).padStart(8, "0") + randB3.toString(16).padStart(4, "0");
85
+ return `${timeLow}-${timeMid}-${ver}-${variantAndRandB}-${node}`;
68
86
  }
69
87
  // Maps for number <-> hex string conversion
70
88
  let _convertMapsInitialized = false;
package/List.js CHANGED
@@ -5,7 +5,8 @@ import { Record } from "./Types.js";
5
5
  import { class_type, record_type, option_type } from "./Reflection.js";
6
6
  import { SR_inputSequenceTooLong, SR_inputSequenceEmpty, SR_inputMustBeNonNegative, SR_notEnoughElements, SR_differentLengths, SR_keyNotFoundAlt, SR_indexOutOfBounds, SR_inputWasEmpty } from "./Global.js";
7
7
  import { KeyNotFoundException_$ctor_Z721C83C5 } from "./System.Collections.Generic.js";
8
- import { transpose as transpose_1, splitInto as splitInto_1, windowed as windowed_1, pairwise as pairwise_1, chunkBySize as chunkBySize_1, map as map_1, permute as permute_1, tryFindIndexBack as tryFindIndexBack_1, tryFindBack as tryFindBack_1, scanBack as scanBack_1, item as item_1, foldBack2 as foldBack2_1, foldBack as foldBack_1, setItem, fill } from "./Array.js";
8
+ import { randomSampleBy as randomSampleBy_1, randomChoicesBy as randomChoicesBy_1, randomChoiceBy as randomChoiceBy_1, randomShuffleInPlaceBy, transpose as transpose_1, splitInto as splitInto_1, windowed as windowed_1, pairwise as pairwise_1, chunkBySize as chunkBySize_1, map as map_1, permute as permute_1, tryFindIndexBack as tryFindIndexBack_1, tryFindBack as tryFindBack_1, scanBack as scanBack_1, item as item_1, foldBack2 as foldBack2_1, foldBack as foldBack_1, setItem, fill } from "./Array.js";
9
+ import { nonSeeded } from "./Random.js";
9
10
  export class FSharpList extends Record {
10
11
  constructor(head, tail) {
11
12
  super();
@@ -1282,3 +1283,41 @@ export function updateAt(index, y, xs) {
1282
1283
  }
1283
1284
  return ys;
1284
1285
  }
1286
+ export function randomShuffleBy(randomizer, xs) {
1287
+ const arr = toArray(xs);
1288
+ randomShuffleInPlaceBy(randomizer, arr);
1289
+ return ofArray(arr);
1290
+ }
1291
+ export function randomShuffleWith(random, xs) {
1292
+ return randomShuffleBy(() => random.NextDouble(), xs);
1293
+ }
1294
+ export function randomShuffle(xs) {
1295
+ return randomShuffleWith(nonSeeded(), xs);
1296
+ }
1297
+ export function randomChoiceBy(randomizer, xs) {
1298
+ return randomChoiceBy_1(randomizer, toArray(xs));
1299
+ }
1300
+ export function randomChoiceWith(random, xs) {
1301
+ return randomChoiceBy(() => random.NextDouble(), xs);
1302
+ }
1303
+ export function randomChoice(xs) {
1304
+ return randomChoiceWith(nonSeeded(), xs);
1305
+ }
1306
+ export function randomChoicesBy(randomizer, count, xs) {
1307
+ return ofArray(randomChoicesBy_1(randomizer, count, toArray(xs)));
1308
+ }
1309
+ export function randomChoicesWith(random, count, xs) {
1310
+ return randomChoicesBy(() => random.NextDouble(), count, xs);
1311
+ }
1312
+ export function randomChoices(count, xs) {
1313
+ return randomChoicesWith(nonSeeded(), count, xs);
1314
+ }
1315
+ export function randomSampleBy(randomizer, count, xs) {
1316
+ return ofArray(randomSampleBy_1(randomizer, count, toArray(xs)));
1317
+ }
1318
+ export function randomSampleWith(random, count, xs) {
1319
+ return randomSampleBy(() => random.NextDouble(), count, xs);
1320
+ }
1321
+ export function randomSample(count, xs) {
1322
+ return randomSampleWith(nonSeeded(), count, xs);
1323
+ }
package/Seq.js CHANGED
@@ -5,9 +5,10 @@ import { class_type } from "./Reflection.js";
5
5
  import { some, value as value_1 } from "./Option.js";
6
6
  import { KeyNotFoundException_$ctor_Z721C83C5 } from "./System.Collections.Generic.js";
7
7
  import { Operators_Lock, Operators_NullArgCheck } from "./FSharp.Core.js";
8
- import { chunkBySize as chunkBySize_1, permute as permute_1, transpose as transpose_1, map as map_1, windowed as windowed_1, splitInto as splitInto_1, pairwise as pairwise_1, scanBack as scanBack_1, reverse as reverse_1, mapFoldBack as mapFoldBack_1, mapFold as mapFold_1, item as item_1, tryItem as tryItem_1, tryHead as tryHead_1, foldBack2 as foldBack2_1, foldBack as foldBack_1, tryFindIndexBack as tryFindIndexBack_1, tryFindBack as tryFindBack_1, singleton as singleton_1 } from "./Array.js";
8
+ import { randomSampleBy as randomSampleBy_1, randomChoicesBy as randomChoicesBy_1, randomChoice as randomChoice_1, randomChoiceWith as randomChoiceWith_1, randomChoiceBy as randomChoiceBy_1, randomShuffleInPlaceBy, chunkBySize as chunkBySize_1, permute as permute_1, transpose as transpose_1, map as map_1, windowed as windowed_1, splitInto as splitInto_1, pairwise as pairwise_1, scanBack as scanBack_1, reverse as reverse_1, mapFoldBack as mapFoldBack_1, mapFold as mapFold_1, item as item_1, tryItem as tryItem_1, tryHead as tryHead_1, foldBack2 as foldBack2_1, foldBack as foldBack_1, tryFindIndexBack as tryFindIndexBack_1, tryFindBack as tryFindBack_1, singleton as singleton_1 } from "./Array.js";
9
9
  import { length as length_1, tryItem as tryItem_2, isEmpty as isEmpty_1, tryHead as tryHead_2, ofSeq as ofSeq_1, ofArray as ofArray_1, toArray as toArray_1, FSharpList } from "./List.js";
10
10
  import { SR_indexOutOfBounds } from "./Global.js";
11
+ import { nonSeeded } from "./Random.js";
11
12
  export const SR_enumerationAlreadyFinished = "Enumeration already finished.";
12
13
  export const SR_enumerationNotStarted = "Enumeration has not started. Call MoveNext.";
13
14
  export const SR_inputSequenceEmpty = "The input sequence was empty.";
@@ -1368,3 +1369,41 @@ export function updateAt(index, y, xs) {
1368
1369
  disposeSafe(e_1);
1369
1370
  });
1370
1371
  }
1372
+ export function randomShuffleBy(randomizer, xs) {
1373
+ const arr = toArray(xs);
1374
+ randomShuffleInPlaceBy(randomizer, arr);
1375
+ return ofArray(arr);
1376
+ }
1377
+ export function randomShuffleWith(random, xs) {
1378
+ return randomShuffleBy(() => random.NextDouble(), xs);
1379
+ }
1380
+ export function randomShuffle(xs) {
1381
+ return randomShuffleWith(nonSeeded(), xs);
1382
+ }
1383
+ export function randomChoiceBy(randomizer, xs) {
1384
+ return randomChoiceBy_1(randomizer, toArray(xs));
1385
+ }
1386
+ export function randomChoiceWith(random, xs) {
1387
+ return randomChoiceWith_1(random, toArray(xs));
1388
+ }
1389
+ export function randomChoice(xs) {
1390
+ return randomChoice_1(toArray(xs));
1391
+ }
1392
+ export function randomChoicesBy(randomizer, count, xs) {
1393
+ return ofArray(randomChoicesBy_1(randomizer, count, toArray(xs)));
1394
+ }
1395
+ export function randomChoicesWith(random, count, xs) {
1396
+ return randomChoicesBy(() => random.NextDouble(), count, xs);
1397
+ }
1398
+ export function randomChoices(count, xs) {
1399
+ return randomChoicesWith(nonSeeded(), count, xs);
1400
+ }
1401
+ export function randomSampleBy(randomizer, count, xs) {
1402
+ return ofArray(randomSampleBy_1(randomizer, count, toArray(xs)));
1403
+ }
1404
+ export function randomSampleWith(random, count, xs) {
1405
+ return randomSampleBy(() => random.NextDouble(), count, xs);
1406
+ }
1407
+ export function randomSample(count, xs) {
1408
+ return randomSampleWith(nonSeeded(), count, xs);
1409
+ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "private": false,
4
4
  "type": "module",
5
5
  "name": "@fable-org/fable-library-js",
6
- "version": "2.0.0-rc.5",
6
+ "version": "2.0.0-rc.6",
7
7
  "description": "Core library used by F# projects compiled with fable.io",
8
8
  "author": "Fable Contributors",
9
9
  "license": "MIT",
package/quotation.js ADDED
@@ -0,0 +1,618 @@
1
+ /**
2
+ * F# Quotation runtime support for Fable JS/TS target.
3
+ *
4
+ * Provides class-based representations of F# quotation AST nodes
5
+ * and pattern matching helpers compatible with Fable's option convention
6
+ * (undefined = no match, value/tuple = match).
7
+ */
8
+ // ===================================================================
9
+ // Var: represents an F# quotation variable
10
+ // ===================================================================
11
+ export class Var {
12
+ constructor(name, type_, isMutable) {
13
+ this.Name = name;
14
+ this.Type = type_;
15
+ this.IsMutable = isMutable;
16
+ }
17
+ }
18
+ export function mkQuotVar(name, type_, isMutable = false) {
19
+ return new Var(name, type_, isMutable);
20
+ }
21
+ export function varGetName(v) { return v.Name; }
22
+ export function varGetType(v) { return v.Type; }
23
+ export function varGetIsMutable(v) { return v.IsMutable; }
24
+ // ===================================================================
25
+ // Expr nodes: tagged classes for each quotation expression kind
26
+ // ===================================================================
27
+ export class ExprValue {
28
+ constructor(value, type) {
29
+ this.tag = "Value";
30
+ this.value = value;
31
+ this.type = type;
32
+ }
33
+ toJSON() { return ["Value", this.value, this.type]; }
34
+ }
35
+ export class ExprVarExpr {
36
+ constructor(var_) {
37
+ this.tag = "Var";
38
+ this.var_ = var_;
39
+ }
40
+ toJSON() { return ["Var", this.var_]; }
41
+ }
42
+ export class ExprLambda {
43
+ constructor(var_, body) {
44
+ this.tag = "Lambda";
45
+ this.var_ = var_;
46
+ this.body = body;
47
+ }
48
+ toJSON() { return ["Lambda", this.var_, this.body]; }
49
+ }
50
+ export class ExprApplication {
51
+ constructor(func, arg) {
52
+ this.tag = "Application";
53
+ this.func = func;
54
+ this.arg = arg;
55
+ }
56
+ toJSON() { return ["Application", this.func, this.arg]; }
57
+ }
58
+ export class ExprLet {
59
+ constructor(var_, value, body) {
60
+ this.tag = "Let";
61
+ this.var_ = var_;
62
+ this.value = value;
63
+ this.body = body;
64
+ }
65
+ toJSON() { return ["Let", this.var_, this.value, this.body]; }
66
+ }
67
+ export class ExprIfThenElse {
68
+ constructor(guard, thenExpr, elseExpr) {
69
+ this.tag = "IfThenElse";
70
+ this.guard = guard;
71
+ this.thenExpr = thenExpr;
72
+ this.elseExpr = elseExpr;
73
+ }
74
+ toJSON() { return ["IfThenElse", this.guard, this.thenExpr, this.elseExpr]; }
75
+ }
76
+ export class ExprCall {
77
+ constructor(instance, method, args) {
78
+ this.tag = "Call";
79
+ this.instance = instance;
80
+ this.method = method;
81
+ this.args = args;
82
+ }
83
+ toJSON() { return ["Call", this.instance, this.method, this.args]; }
84
+ }
85
+ export class ExprSequential {
86
+ constructor(first, second) {
87
+ this.tag = "Sequential";
88
+ this.first = first;
89
+ this.second = second;
90
+ }
91
+ toJSON() { return ["Sequential", this.first, this.second]; }
92
+ }
93
+ export class ExprNewTuple {
94
+ constructor(elements) {
95
+ this.tag = "NewTuple";
96
+ this.elements = elements;
97
+ }
98
+ toJSON() { return ["NewTuple", this.elements]; }
99
+ }
100
+ export class ExprNewUnion {
101
+ constructor(typeName, unionTag, fields) {
102
+ this.tag = "NewUnion";
103
+ this.typeName = typeName;
104
+ this.unionTag = unionTag;
105
+ this.fields = fields;
106
+ }
107
+ toJSON() { return ["NewUnion", this.typeName, this.unionTag, this.fields]; }
108
+ }
109
+ export class ExprNewRecord {
110
+ constructor(fieldNames, values) {
111
+ this.tag = "NewRecord";
112
+ this.fieldNames = fieldNames;
113
+ this.values = values;
114
+ }
115
+ toJSON() { return ["NewRecord", this.fieldNames, this.values]; }
116
+ }
117
+ export class ExprNewList {
118
+ constructor(head, tail) {
119
+ this.tag = "NewList";
120
+ this.head = head;
121
+ this.tail = tail;
122
+ }
123
+ toJSON() { return ["NewList", this.head, this.tail]; }
124
+ }
125
+ export class ExprTupleGet {
126
+ constructor(expr, index) {
127
+ this.tag = "TupleGet";
128
+ this.expr = expr;
129
+ this.index = index;
130
+ }
131
+ toJSON() { return ["TupleGet", this.expr, this.index]; }
132
+ }
133
+ export class ExprUnionTag {
134
+ constructor(expr) {
135
+ this.tag = "UnionTag";
136
+ this.expr = expr;
137
+ }
138
+ toJSON() { return ["UnionTag", this.expr]; }
139
+ }
140
+ export class ExprUnionField {
141
+ constructor(expr, fieldIndex) {
142
+ this.tag = "UnionField";
143
+ this.expr = expr;
144
+ this.fieldIndex = fieldIndex;
145
+ }
146
+ toJSON() { return ["UnionField", this.expr, this.fieldIndex]; }
147
+ }
148
+ export class ExprFieldGet {
149
+ constructor(expr, fieldName) {
150
+ this.tag = "FieldGet";
151
+ this.expr = expr;
152
+ this.fieldName = fieldName;
153
+ }
154
+ toJSON() { return ["FieldGet", this.expr, this.fieldName]; }
155
+ }
156
+ export class ExprFieldSet {
157
+ constructor(expr, fieldName, value) {
158
+ this.tag = "FieldSet";
159
+ this.expr = expr;
160
+ this.fieldName = fieldName;
161
+ this.value = value;
162
+ }
163
+ toJSON() { return ["FieldSet", this.expr, this.fieldName, this.value]; }
164
+ }
165
+ export class ExprVarSet {
166
+ constructor(target, value) {
167
+ this.tag = "VarSet";
168
+ this.target = target;
169
+ this.value = value;
170
+ }
171
+ toJSON() { return ["VarSet", this.target, this.value]; }
172
+ }
173
+ // ===================================================================
174
+ // Constructors (called by QuotationEmitter.fs)
175
+ // ===================================================================
176
+ export function mkValue(value, type) {
177
+ return new ExprValue(value, type);
178
+ }
179
+ export function mkVar(v) {
180
+ return new ExprVarExpr(v);
181
+ }
182
+ export function mkLambda(v, body) {
183
+ return new ExprLambda(v, body);
184
+ }
185
+ export function mkApplication(func, arg) {
186
+ return new ExprApplication(func, arg);
187
+ }
188
+ export function mkLet(v, value, body) {
189
+ return new ExprLet(v, value, body);
190
+ }
191
+ export function mkIfThenElse(guard, thenExpr, elseExpr) {
192
+ return new ExprIfThenElse(guard, thenExpr, elseExpr);
193
+ }
194
+ export function mkCall(instance, method, args) {
195
+ return new ExprCall(instance, method, args);
196
+ }
197
+ export function mkSequential(first, second) {
198
+ return new ExprSequential(first, second);
199
+ }
200
+ export function mkNewTuple(elements) {
201
+ return new ExprNewTuple(elements);
202
+ }
203
+ export function mkTupleGet(expr, index) {
204
+ return new ExprTupleGet(expr, index);
205
+ }
206
+ export function mkUnionTag(expr) {
207
+ return new ExprUnionTag(expr);
208
+ }
209
+ export function mkUnionField(expr, fieldIndex) {
210
+ return new ExprUnionField(expr, fieldIndex);
211
+ }
212
+ export function mkFieldGet(expr, fieldName) {
213
+ return new ExprFieldGet(expr, fieldName);
214
+ }
215
+ export function mkFieldSet(expr, fieldName, value) {
216
+ return new ExprFieldSet(expr, fieldName, value);
217
+ }
218
+ export function mkVarSet(target, value) {
219
+ return new ExprVarSet(target, value);
220
+ }
221
+ export function mkNewUnion(typeName, tag, fields) {
222
+ return new ExprNewUnion(typeName, tag, fields);
223
+ }
224
+ export function mkNewRecord(fieldNames, values) {
225
+ return new ExprNewRecord(fieldNames, values);
226
+ }
227
+ export function mkNewList(head, tail) {
228
+ return new ExprNewList(head, tail);
229
+ }
230
+ // ===================================================================
231
+ // Accessors
232
+ // ===================================================================
233
+ export function getType(expr) {
234
+ if (expr instanceof ExprValue)
235
+ return expr.type;
236
+ if (expr instanceof ExprLambda)
237
+ return expr.var_.Type;
238
+ return "obj";
239
+ }
240
+ // ===================================================================
241
+ // Pattern match helpers
242
+ // Returns undefined (no match) or a value/tuple (match), following
243
+ // Fable's option convention for active patterns.
244
+ // ===================================================================
245
+ export function isValue(expr) {
246
+ if (expr instanceof ExprValue)
247
+ return [expr.value, expr.type];
248
+ return undefined;
249
+ }
250
+ export function isVar(expr) {
251
+ if (expr instanceof ExprVarExpr)
252
+ return expr.var_;
253
+ return undefined;
254
+ }
255
+ export function isLambda(expr) {
256
+ if (expr instanceof ExprLambda)
257
+ return [expr.var_, expr.body];
258
+ return undefined;
259
+ }
260
+ export function isApplication(expr) {
261
+ if (expr instanceof ExprApplication)
262
+ return [expr.func, expr.arg];
263
+ return undefined;
264
+ }
265
+ export function isLet(expr) {
266
+ if (expr instanceof ExprLet)
267
+ return [expr.var_, expr.value, expr.body];
268
+ return undefined;
269
+ }
270
+ export function isIfThenElse(expr) {
271
+ if (expr instanceof ExprIfThenElse)
272
+ return [expr.guard, expr.thenExpr, expr.elseExpr];
273
+ return undefined;
274
+ }
275
+ export function isCall(expr) {
276
+ if (expr instanceof ExprCall)
277
+ return [expr.instance, expr.method, expr.args];
278
+ return undefined;
279
+ }
280
+ export function isSequential(expr) {
281
+ if (expr instanceof ExprSequential)
282
+ return [expr.first, expr.second];
283
+ return undefined;
284
+ }
285
+ export function isNewTuple(expr) {
286
+ if (expr instanceof ExprNewTuple)
287
+ return expr.elements;
288
+ return undefined;
289
+ }
290
+ export function isNewUnionCase(expr) {
291
+ if (expr instanceof ExprNewUnion)
292
+ return [expr.typeName, expr.fields];
293
+ return undefined;
294
+ }
295
+ export function isNewRecord(expr) {
296
+ if (expr instanceof ExprNewRecord)
297
+ return [expr.fieldNames, expr.values];
298
+ return undefined;
299
+ }
300
+ export function isTupleGet(expr) {
301
+ if (expr instanceof ExprTupleGet)
302
+ return [expr.expr, expr.index];
303
+ return undefined;
304
+ }
305
+ export function isFieldGet(expr) {
306
+ if (expr instanceof ExprFieldGet)
307
+ return [expr.expr, expr.fieldName];
308
+ return undefined;
309
+ }
310
+ // ===================================================================
311
+ // Evaluation
312
+ // ===================================================================
313
+ const OPERATORS = {
314
+ "op_Addition": (a, b) => a + b,
315
+ "op_Subtraction": (a, b) => a - b,
316
+ "op_Multiply": (a, b) => a * b,
317
+ "op_Division": (a, b) => a / b,
318
+ "op_Modulus": (a, b) => a % b,
319
+ "op_Exponentiation": (a, b) => a ** b,
320
+ "op_UnaryNegation": (a) => -a,
321
+ "op_UnaryPlus": (a) => +a,
322
+ "op_LogicalNot": (a) => !a,
323
+ "op_BitwiseOr": (a, b) => a | b,
324
+ "op_BitwiseAnd": (a, b) => a & b,
325
+ "op_ExclusiveOr": (a, b) => a ^ b,
326
+ "op_LeftShift": (a, b) => a << b,
327
+ "op_RightShift": (a, b) => a >> b,
328
+ "op_Equality": (a, b) => a === b,
329
+ "op_Inequality": (a, b) => a !== b,
330
+ "op_LessThan": (a, b) => a < b,
331
+ "op_LessThanOrEqual": (a, b) => a <= b,
332
+ "op_GreaterThan": (a, b) => a > b,
333
+ "op_GreaterThanOrEqual": (a, b) => a >= b,
334
+ "op_BooleanAnd": (a, b) => a && b,
335
+ "op_BooleanOr": (a, b) => a || b,
336
+ };
337
+ export function evaluate(expr, env) {
338
+ if (env == null)
339
+ env = new Map();
340
+ if (expr instanceof ExprValue)
341
+ return expr.value;
342
+ if (expr instanceof ExprVarExpr) {
343
+ if (env.has(expr.var_.Name))
344
+ return env.get(expr.var_.Name);
345
+ throw new Error(`Unbound variable: ${expr.var_.Name}`);
346
+ }
347
+ if (expr instanceof ExprLambda) {
348
+ const capturedEnv = new Map(env);
349
+ return (arg) => {
350
+ const newEnv = new Map(capturedEnv);
351
+ newEnv.set(expr.var_.Name, arg);
352
+ return evaluate(expr.body, newEnv);
353
+ };
354
+ }
355
+ if (expr instanceof ExprApplication) {
356
+ return evaluate(expr.func, env)(evaluate(expr.arg, env));
357
+ }
358
+ if (expr instanceof ExprLet) {
359
+ const newEnv = new Map(env);
360
+ newEnv.set(expr.var_.Name, evaluate(expr.value, env));
361
+ return evaluate(expr.body, newEnv);
362
+ }
363
+ if (expr instanceof ExprIfThenElse) {
364
+ return evaluate(expr.guard, env) ? evaluate(expr.thenExpr, env) : evaluate(expr.elseExpr, env);
365
+ }
366
+ if (expr instanceof ExprSequential) {
367
+ evaluate(expr.first, env);
368
+ return evaluate(expr.second, env);
369
+ }
370
+ if (expr instanceof ExprNewTuple) {
371
+ return expr.elements.map(e => evaluate(e, env));
372
+ }
373
+ if (expr instanceof ExprCall) {
374
+ const evaluatedArgs = expr.args.map((a) => evaluate(a, env));
375
+ if (expr.method in OPERATORS)
376
+ return OPERATORS[expr.method](...evaluatedArgs);
377
+ throw new Error(`Unknown method: ${expr.method}`);
378
+ }
379
+ if (expr instanceof ExprTupleGet) {
380
+ return evaluate(expr.expr, env)[expr.index];
381
+ }
382
+ if (expr instanceof ExprNewUnion) {
383
+ return [expr.unionTag, ...expr.fields.map((f) => evaluate(f, env))];
384
+ }
385
+ if (expr instanceof ExprNewRecord) {
386
+ const result = {};
387
+ for (let i = 0; i < expr.fieldNames.length; i++) {
388
+ result[expr.fieldNames[i]] = evaluate(expr.values[i], env);
389
+ }
390
+ return result;
391
+ }
392
+ if (expr instanceof ExprNewList) {
393
+ return [evaluate(expr.head, env), ...evaluate(expr.tail, env)];
394
+ }
395
+ if (expr instanceof ExprVarSet) {
396
+ if (expr.target instanceof ExprVarExpr) {
397
+ env.set(expr.target.var_.Name, evaluate(expr.value, env));
398
+ return undefined;
399
+ }
400
+ throw new Error("VarSet target must be a variable");
401
+ }
402
+ if (expr instanceof ExprFieldGet) {
403
+ const obj = evaluate(expr.expr, env);
404
+ return obj[expr.fieldName];
405
+ }
406
+ throw new Error(`Cannot evaluate expression: ${expr.tag}`);
407
+ }
408
+ // ===================================================================
409
+ // FSharpExpr instance methods
410
+ // ===================================================================
411
+ const OP_SYMBOLS = {
412
+ "op_Addition": "+",
413
+ "op_Subtraction": "-",
414
+ "op_Multiply": "*",
415
+ "op_Division": "/",
416
+ "op_Modulus": "%",
417
+ "op_Exponentiation": "**",
418
+ "op_Equality": "=",
419
+ "op_Inequality": "<>",
420
+ "op_LessThan": "<",
421
+ "op_LessThanOrEqual": "<=",
422
+ "op_GreaterThan": ">",
423
+ "op_GreaterThanOrEqual": ">=",
424
+ "op_BooleanAnd": "&&",
425
+ "op_BooleanOr": "||",
426
+ "op_UnaryNegation": "-",
427
+ "op_LogicalNot": "not",
428
+ };
429
+ export function exprToString(expr) {
430
+ if (expr instanceof ExprValue) {
431
+ if (expr.type === "string")
432
+ return `"${expr.value}"`;
433
+ if (expr.type === "unit")
434
+ return "()";
435
+ if (expr.type === "bool")
436
+ return expr.value ? "true" : "false";
437
+ return String(expr.value);
438
+ }
439
+ if (expr instanceof ExprVarExpr)
440
+ return expr.var_.Name;
441
+ if (expr instanceof ExprLambda)
442
+ return `fun ${expr.var_.Name} -> ${exprToString(expr.body)}`;
443
+ if (expr instanceof ExprApplication)
444
+ return `${exprToString(expr.func)} ${exprToString(expr.arg)}`;
445
+ if (expr instanceof ExprLet)
446
+ return `let ${expr.var_.Name} = ${exprToString(expr.value)} in ${exprToString(expr.body)}`;
447
+ if (expr instanceof ExprIfThenElse)
448
+ return `if ${exprToString(expr.guard)} then ${exprToString(expr.thenExpr)} else ${exprToString(expr.elseExpr)}`;
449
+ if (expr instanceof ExprCall) {
450
+ if (expr.method in OP_SYMBOLS && expr.args.length === 2) {
451
+ return `(${exprToString(expr.args[0])} ${OP_SYMBOLS[expr.method]} ${exprToString(expr.args[1])})`;
452
+ }
453
+ if (expr.method in OP_SYMBOLS && expr.args.length === 1) {
454
+ return `${OP_SYMBOLS[expr.method]}${exprToString(expr.args[0])}`;
455
+ }
456
+ return `${expr.method}(${expr.args.map(exprToString).join(", ")})`;
457
+ }
458
+ if (expr instanceof ExprSequential)
459
+ return `${exprToString(expr.first)}; ${exprToString(expr.second)}`;
460
+ if (expr instanceof ExprNewTuple)
461
+ return `(${expr.elements.map(exprToString).join(", ")})`;
462
+ if (expr instanceof ExprTupleGet)
463
+ return `Item${expr.index + 1}(${exprToString(expr.expr)})`;
464
+ if (expr instanceof ExprFieldGet)
465
+ return `${exprToString(expr.expr)}.${expr.fieldName}`;
466
+ return `<${expr.tag}>`;
467
+ }
468
+ export function getFreeVars(expr) {
469
+ const free = [];
470
+ const seen = new Set();
471
+ function walk(e, bound) {
472
+ if (e instanceof ExprVarExpr) {
473
+ if (!bound.has(e.var_.Name) && !seen.has(e.var_.Name)) {
474
+ free.push(e.var_);
475
+ seen.add(e.var_.Name);
476
+ }
477
+ }
478
+ else if (e instanceof ExprLambda) {
479
+ walk(e.body, new Set([...bound, e.var_.Name]));
480
+ }
481
+ else if (e instanceof ExprLet) {
482
+ walk(e.value, bound);
483
+ walk(e.body, new Set([...bound, e.var_.Name]));
484
+ }
485
+ else if (e instanceof ExprApplication) {
486
+ walk(e.func, bound);
487
+ walk(e.arg, bound);
488
+ }
489
+ else if (e instanceof ExprIfThenElse) {
490
+ walk(e.guard, bound);
491
+ walk(e.thenExpr, bound);
492
+ walk(e.elseExpr, bound);
493
+ }
494
+ else if (e instanceof ExprCall) {
495
+ for (const a of e.args)
496
+ walk(a, bound);
497
+ }
498
+ else if (e instanceof ExprSequential) {
499
+ walk(e.first, bound);
500
+ walk(e.second, bound);
501
+ }
502
+ else if (e instanceof ExprNewTuple) {
503
+ for (const el of e.elements)
504
+ walk(el, bound);
505
+ }
506
+ else if (e instanceof ExprTupleGet) {
507
+ walk(e.expr, bound);
508
+ }
509
+ else if (e instanceof ExprNewUnion) {
510
+ for (const f of e.fields)
511
+ walk(f, bound);
512
+ }
513
+ else if (e instanceof ExprNewRecord) {
514
+ for (const v of e.values)
515
+ walk(v, bound);
516
+ }
517
+ else if (e instanceof ExprNewList) {
518
+ walk(e.head, bound);
519
+ walk(e.tail, bound);
520
+ }
521
+ else if (e instanceof ExprUnionTag) {
522
+ walk(e.expr, bound);
523
+ }
524
+ else if (e instanceof ExprUnionField) {
525
+ walk(e.expr, bound);
526
+ }
527
+ else if (e instanceof ExprFieldGet) {
528
+ walk(e.expr, bound);
529
+ }
530
+ else if (e instanceof ExprFieldSet) {
531
+ walk(e.expr, bound);
532
+ walk(e.value, bound);
533
+ }
534
+ else if (e instanceof ExprVarSet) {
535
+ walk(e.target, bound);
536
+ walk(e.value, bound);
537
+ }
538
+ }
539
+ walk(expr, new Set());
540
+ return free;
541
+ }
542
+ export function substitute(expr, fn) {
543
+ function sub(e) {
544
+ if (e instanceof ExprVarExpr) {
545
+ const result = fn(e.var_);
546
+ return result !== undefined ? result : e;
547
+ }
548
+ if (e instanceof ExprLambda)
549
+ return new ExprLambda(e.var_, sub(e.body));
550
+ if (e instanceof ExprLet)
551
+ return new ExprLet(e.var_, sub(e.value), sub(e.body));
552
+ if (e instanceof ExprApplication)
553
+ return new ExprApplication(sub(e.func), sub(e.arg));
554
+ if (e instanceof ExprIfThenElse)
555
+ return new ExprIfThenElse(sub(e.guard), sub(e.thenExpr), sub(e.elseExpr));
556
+ if (e instanceof ExprCall) {
557
+ const newInst = e.instance != null ? sub(e.instance) : e.instance;
558
+ return new ExprCall(newInst, e.method, e.args.map(sub));
559
+ }
560
+ if (e instanceof ExprSequential)
561
+ return new ExprSequential(sub(e.first), sub(e.second));
562
+ if (e instanceof ExprNewTuple)
563
+ return new ExprNewTuple(e.elements.map(sub));
564
+ if (e instanceof ExprTupleGet)
565
+ return new ExprTupleGet(sub(e.expr), e.index);
566
+ if (e instanceof ExprNewUnion)
567
+ return new ExprNewUnion(e.typeName, e.unionTag, e.fields.map(sub));
568
+ if (e instanceof ExprNewRecord)
569
+ return new ExprNewRecord(e.fieldNames, e.values.map(sub));
570
+ if (e instanceof ExprNewList)
571
+ return new ExprNewList(sub(e.head), sub(e.tail));
572
+ if (e instanceof ExprUnionTag)
573
+ return new ExprUnionTag(sub(e.expr));
574
+ if (e instanceof ExprUnionField)
575
+ return new ExprUnionField(sub(e.expr), e.fieldIndex);
576
+ if (e instanceof ExprFieldGet)
577
+ return new ExprFieldGet(sub(e.expr), e.fieldName);
578
+ if (e instanceof ExprFieldSet)
579
+ return new ExprFieldSet(sub(e.expr), e.fieldName, sub(e.value));
580
+ if (e instanceof ExprVarSet)
581
+ return new ExprVarSet(sub(e.target), sub(e.value));
582
+ return e;
583
+ }
584
+ return sub(expr);
585
+ }
586
+ // ===================================================================
587
+ // JSON deserialization
588
+ // Reconstructs Expr/Var from the toJSON() array format.
589
+ // ===================================================================
590
+ function varFromJSON(json) {
591
+ return new Var(json.Name, json.Type, json.IsMutable);
592
+ }
593
+ export function exprFromJSON(json) {
594
+ if (!Array.isArray(json))
595
+ return new ExprValue(json, typeof json);
596
+ const [tag, ...fields] = json;
597
+ switch (tag) {
598
+ case "Value": return new ExprValue(fields[0], fields[1]);
599
+ case "Var": return new ExprVarExpr(varFromJSON(fields[0]));
600
+ case "Lambda": return new ExprLambda(varFromJSON(fields[0]), exprFromJSON(fields[1]));
601
+ case "Application": return new ExprApplication(exprFromJSON(fields[0]), exprFromJSON(fields[1]));
602
+ case "Let": return new ExprLet(varFromJSON(fields[0]), exprFromJSON(fields[1]), exprFromJSON(fields[2]));
603
+ case "IfThenElse": return new ExprIfThenElse(exprFromJSON(fields[0]), exprFromJSON(fields[1]), exprFromJSON(fields[2]));
604
+ case "Call": return new ExprCall(fields[0] != null ? exprFromJSON(fields[0]) : null, fields[1], fields[2].map(exprFromJSON));
605
+ case "Sequential": return new ExprSequential(exprFromJSON(fields[0]), exprFromJSON(fields[1]));
606
+ case "NewTuple": return new ExprNewTuple(fields[0].map(exprFromJSON));
607
+ case "TupleGet": return new ExprTupleGet(exprFromJSON(fields[0]), fields[1]);
608
+ case "NewUnion": return new ExprNewUnion(fields[0], fields[1], fields[2].map(exprFromJSON));
609
+ case "UnionTag": return new ExprUnionTag(exprFromJSON(fields[0]));
610
+ case "UnionField": return new ExprUnionField(exprFromJSON(fields[0]), fields[1]);
611
+ case "NewRecord": return new ExprNewRecord(fields[0], fields[1].map(exprFromJSON));
612
+ case "FieldGet": return new ExprFieldGet(exprFromJSON(fields[0]), fields[1]);
613
+ case "FieldSet": return new ExprFieldSet(exprFromJSON(fields[0]), fields[1], exprFromJSON(fields[2]));
614
+ case "VarSet": return new ExprVarSet(exprFromJSON(fields[0]), exprFromJSON(fields[1]));
615
+ case "NewList": return new ExprNewList(exprFromJSON(fields[0]), exprFromJSON(fields[1]));
616
+ default: return new ExprValue(json, "unknown");
617
+ }
618
+ }