@magnusopera/fscript 0.75.0

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.
Files changed (79) hide show
  1. package/README.md +5 -0
  2. package/dist/FScript.Language/Ast.js +234 -0
  3. package/dist/FScript.Language/BuiltinFunctions.js +2039 -0
  4. package/dist/FScript.Language/BuiltinSignatures.js +24 -0
  5. package/dist/FScript.Language/BuiltinTypes.js +13 -0
  6. package/dist/FScript.Language/Error.js +74 -0
  7. package/dist/FScript.Language/Eval.js +2404 -0
  8. package/dist/FScript.Language/IncludeResolver.js +806 -0
  9. package/dist/FScript.Language/Lexer.js +1067 -0
  10. package/dist/FScript.Language/Library.js +28 -0
  11. package/dist/FScript.Language/Parser.js +2368 -0
  12. package/dist/FScript.Language/Pretty.js +115 -0
  13. package/dist/FScript.Language/Span.js +33 -0
  14. package/dist/FScript.Language/Token.js +32 -0
  15. package/dist/FScript.Language/TypeInfer.js +2561 -0
  16. package/dist/FScript.Language/Types.js +205 -0
  17. package/dist/FScript.Language/Value.js +91 -0
  18. package/dist/Library.js +732 -0
  19. package/dist/fable_modules/fable-library-js.5.2.0/Array.js +1347 -0
  20. package/dist/fable_modules/fable-library-js.5.2.0/Async.js +134 -0
  21. package/dist/fable_modules/fable-library-js.5.2.0/AsyncBuilder.js +183 -0
  22. package/dist/fable_modules/fable-library-js.5.2.0/BigInt.js +306 -0
  23. package/dist/fable_modules/fable-library-js.5.2.0/BitConverter.js +138 -0
  24. package/dist/fable_modules/fable-library-js.5.2.0/Boolean.js +22 -0
  25. package/dist/fable_modules/fable-library-js.5.2.0/CHANGELOG.md +234 -0
  26. package/dist/fable_modules/fable-library-js.5.2.0/Char.js +202 -0
  27. package/dist/fable_modules/fable-library-js.5.2.0/Choice.js +184 -0
  28. package/dist/fable_modules/fable-library-js.5.2.0/CollectionUtil.js +182 -0
  29. package/dist/fable_modules/fable-library-js.5.2.0/ConditionalWeakTable.js +21 -0
  30. package/dist/fable_modules/fable-library-js.5.2.0/Date.js +841 -0
  31. package/dist/fable_modules/fable-library-js.5.2.0/DateOffset.js +261 -0
  32. package/dist/fable_modules/fable-library-js.5.2.0/DateOnly.js +124 -0
  33. package/dist/fable_modules/fable-library-js.5.2.0/Decimal.js +238 -0
  34. package/dist/fable_modules/fable-library-js.5.2.0/Double.js +47 -0
  35. package/dist/fable_modules/fable-library-js.5.2.0/Encoding.js +185 -0
  36. package/dist/fable_modules/fable-library-js.5.2.0/Event.js +93 -0
  37. package/dist/fable_modules/fable-library-js.5.2.0/FSharp.Collections.js +45 -0
  38. package/dist/fable_modules/fable-library-js.5.2.0/FSharp.Core.CompilerServices.js +27 -0
  39. package/dist/fable_modules/fable-library-js.5.2.0/FSharp.Core.js +156 -0
  40. package/dist/fable_modules/fable-library-js.5.2.0/Global.js +29 -0
  41. package/dist/fable_modules/fable-library-js.5.2.0/Guid.js +161 -0
  42. package/dist/fable_modules/fable-library-js.5.2.0/Int32.js +135 -0
  43. package/dist/fable_modules/fable-library-js.5.2.0/List.js +1323 -0
  44. package/dist/fable_modules/fable-library-js.5.2.0/Long.js +47 -0
  45. package/dist/fable_modules/fable-library-js.5.2.0/MailboxProcessor.js +94 -0
  46. package/dist/fable_modules/fable-library-js.5.2.0/Map.js +1396 -0
  47. package/dist/fable_modules/fable-library-js.5.2.0/MapUtil.js +130 -0
  48. package/dist/fable_modules/fable-library-js.5.2.0/MutableMap.js +339 -0
  49. package/dist/fable_modules/fable-library-js.5.2.0/MutableSet.js +233 -0
  50. package/dist/fable_modules/fable-library-js.5.2.0/Native.js +14 -0
  51. package/dist/fable_modules/fable-library-js.5.2.0/Numeric.js +75 -0
  52. package/dist/fable_modules/fable-library-js.5.2.0/Observable.js +113 -0
  53. package/dist/fable_modules/fable-library-js.5.2.0/Option.js +104 -0
  54. package/dist/fable_modules/fable-library-js.5.2.0/README.md +3 -0
  55. package/dist/fable_modules/fable-library-js.5.2.0/Random.js +172 -0
  56. package/dist/fable_modules/fable-library-js.5.2.0/Range.js +45 -0
  57. package/dist/fable_modules/fable-library-js.5.2.0/Reflection.js +479 -0
  58. package/dist/fable_modules/fable-library-js.5.2.0/RegExp.js +141 -0
  59. package/dist/fable_modules/fable-library-js.5.2.0/Result.js +165 -0
  60. package/dist/fable_modules/fable-library-js.5.2.0/Seq.js +1417 -0
  61. package/dist/fable_modules/fable-library-js.5.2.0/Seq2.js +111 -0
  62. package/dist/fable_modules/fable-library-js.5.2.0/Set.js +1816 -0
  63. package/dist/fable_modules/fable-library-js.5.2.0/String.js +674 -0
  64. package/dist/fable_modules/fable-library-js.5.2.0/System.Collections.Generic.js +333 -0
  65. package/dist/fable_modules/fable-library-js.5.2.0/System.Text.js +200 -0
  66. package/dist/fable_modules/fable-library-js.5.2.0/System.js +283 -0
  67. package/dist/fable_modules/fable-library-js.5.2.0/TimeOnly.js +122 -0
  68. package/dist/fable_modules/fable-library-js.5.2.0/TimeSpan.js +180 -0
  69. package/dist/fable_modules/fable-library-js.5.2.0/Timer.js +67 -0
  70. package/dist/fable_modules/fable-library-js.5.2.0/Types.js +198 -0
  71. package/dist/fable_modules/fable-library-js.5.2.0/Unicode.13.0.0.js +4 -0
  72. package/dist/fable_modules/fable-library-js.5.2.0/Uri.js +165 -0
  73. package/dist/fable_modules/fable-library-js.5.2.0/Util.js +795 -0
  74. package/dist/fable_modules/fable-library-js.5.2.0/big.d.ts +338 -0
  75. package/dist/fable_modules/fable-library-js.5.2.0/lib/big.js +825 -0
  76. package/dist/fable_modules/fable-library-js.5.2.0/package.json +24 -0
  77. package/dist/fable_modules/fable-library-js.5.2.0/quotation.js +618 -0
  78. package/dist/fable_modules/project_cracked.json +1 -0
  79. package/package.json +36 -0
@@ -0,0 +1,134 @@
1
+ import { OperationCanceledException, Trampoline } from "./AsyncBuilder.js";
2
+ import { CancellationToken } from "./AsyncBuilder.js";
3
+ import { protectedCont, protectedBind, protectedReturn } from "./AsyncBuilder.js";
4
+ import { Choice_makeChoice1Of2, Choice_makeChoice2Of2 } from "./Choice.js";
5
+ import { TimeoutException_$ctor } from "./System.js";
6
+ import { Exception } from "./Util.js";
7
+ function emptyContinuation(_x) {
8
+ // NOP
9
+ }
10
+ // see AsyncBuilder.Delay
11
+ function delay(generator) {
12
+ return protectedCont((ctx) => generator()(ctx));
13
+ }
14
+ // MakeAsync: body:(AsyncActivation<'T> -> AsyncReturn) -> Async<'T>
15
+ export function makeAsync(body) {
16
+ return body;
17
+ }
18
+ // Invoke: computation: Async<'T> -> ctxt:AsyncActivation<'T> -> AsyncReturn
19
+ export function invoke(computation, ctx) {
20
+ return computation(ctx);
21
+ }
22
+ // CallThenInvoke: ctxt:AsyncActivation<'T> -> result1:'U -> part2:('U -> Async<'T>) -> AsyncReturn
23
+ export function callThenInvoke(ctx, result1, part2) {
24
+ return part2(result1)(ctx);
25
+ }
26
+ // Bind: ctxt:AsyncActivation<'T> -> part1:Async<'U> -> part2:('U -> Async<'T>) -> AsyncReturn
27
+ export function bind(ctx, part1, part2) {
28
+ return protectedBind(part1, part2)(ctx);
29
+ }
30
+ export function createCancellationToken(arg) {
31
+ const token = new CancellationToken(typeof arg === "boolean" ? arg : false);
32
+ if (typeof arg === "number") {
33
+ setTimeout(() => { token.cancel(); }, arg);
34
+ }
35
+ return token;
36
+ }
37
+ export function cancel(token) {
38
+ token.cancel();
39
+ }
40
+ export function cancelAfter(token, ms) {
41
+ setTimeout(() => { token.cancel(); }, ms);
42
+ }
43
+ export function isCancellationRequested(token) {
44
+ return token != null && token.isCancelled;
45
+ }
46
+ export function throwIfCancellationRequested(token) {
47
+ if (token != null && token.isCancelled) {
48
+ throw new Exception("Operation is cancelled");
49
+ }
50
+ }
51
+ export function startChild(computation, ms) {
52
+ const promise = startAsPromise(computation);
53
+ let promiseToRun = promise;
54
+ if (ms) {
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
+ });
60
+ }
61
+ // JS Promises are hot, computation has already started
62
+ // but we delay returning the result
63
+ return protectedCont((ctx) => protectedReturn(awaitPromise(promiseToRun))(ctx));
64
+ }
65
+ export function awaitPromise(p) {
66
+ return fromContinuations((conts) => p.then(conts[0]).catch((err) => (err instanceof OperationCanceledException
67
+ ? conts[2] : conts[1])(err)));
68
+ }
69
+ export function cancellationToken() {
70
+ return protectedCont((ctx) => ctx.onSuccess(ctx.cancelToken));
71
+ }
72
+ export const defaultCancellationToken = new CancellationToken();
73
+ export function catchAsync(work) {
74
+ return protectedCont((ctx) => {
75
+ work({
76
+ onSuccess: (x) => ctx.onSuccess(Choice_makeChoice1Of2(x)),
77
+ onError: (ex) => ctx.onSuccess(Choice_makeChoice2Of2(ex)),
78
+ onCancel: ctx.onCancel,
79
+ cancelToken: ctx.cancelToken,
80
+ trampoline: ctx.trampoline,
81
+ });
82
+ });
83
+ }
84
+ export function fromContinuations(f) {
85
+ return protectedCont((ctx) => f([ctx.onSuccess, ctx.onError, ctx.onCancel]));
86
+ }
87
+ export function ignore(computation) {
88
+ return protectedBind(computation, (_x) => protectedReturn(void 0));
89
+ }
90
+ export function parallel(computations) {
91
+ return delay(() => awaitPromise(Promise.all(Array.from(computations, (w) => startAsPromise(w)))));
92
+ }
93
+ export function sequential(computations) {
94
+ function _sequential(computations) {
95
+ let pr = Promise.resolve([]);
96
+ for (const c of computations) {
97
+ pr = pr.then(results => startAsPromise(c).then(r => results.concat([r])));
98
+ }
99
+ return pr;
100
+ }
101
+ return delay(() => awaitPromise(_sequential(computations)));
102
+ }
103
+ export function sleep(millisecondsDueTime) {
104
+ return protectedCont((ctx) => {
105
+ let tokenId;
106
+ const timeoutId = setTimeout(() => {
107
+ ctx.cancelToken.removeListener(tokenId);
108
+ ctx.onSuccess(void 0);
109
+ }, millisecondsDueTime);
110
+ tokenId = ctx.cancelToken.addListener(() => {
111
+ clearTimeout(timeoutId);
112
+ ctx.onCancel(new OperationCanceledException());
113
+ });
114
+ });
115
+ }
116
+ export function start(computation, cancellationToken) {
117
+ return startWithContinuations(computation, emptyContinuation, function (err) { throw err; }, emptyContinuation, cancellationToken);
118
+ }
119
+ export function startImmediate(computation, cancellationToken) {
120
+ return start(computation, cancellationToken);
121
+ }
122
+ export function startWithContinuations(computation, continuation, exceptionContinuation, cancellationContinuation, cancelToken) {
123
+ const trampoline = new Trampoline();
124
+ computation({
125
+ onSuccess: continuation ? continuation : emptyContinuation,
126
+ onError: exceptionContinuation,
127
+ onCancel: cancellationContinuation,
128
+ cancelToken: cancelToken ? cancelToken : defaultCancellationToken,
129
+ trampoline,
130
+ });
131
+ }
132
+ export function startAsPromise(computation, cancellationToken) {
133
+ return new Promise((resolve, reject) => startWithContinuations(computation, resolve, reject, reject, cancellationToken ? cancellationToken : defaultCancellationToken));
134
+ }
@@ -0,0 +1,183 @@
1
+ import { Exception, ensureErrorOrException } from "./Util.js";
2
+ export class CancellationToken {
3
+ constructor(cancelled = false) {
4
+ this._id = 0;
5
+ this._cancelled = cancelled;
6
+ this._listeners = new Map();
7
+ }
8
+ get isCancelled() {
9
+ return this._cancelled;
10
+ }
11
+ cancel() {
12
+ if (!this._cancelled) {
13
+ this._cancelled = true;
14
+ for (const [, listener] of this._listeners) {
15
+ listener();
16
+ }
17
+ }
18
+ }
19
+ addListener(f) {
20
+ const id = this._id;
21
+ this._listeners.set(this._id++, f);
22
+ return id;
23
+ }
24
+ removeListener(id) {
25
+ return this._listeners.delete(id);
26
+ }
27
+ register(f, state) {
28
+ const $ = this;
29
+ const id = this.addListener(state == null ? f : () => f(state));
30
+ return { Dispose() { $.removeListener(id); } };
31
+ }
32
+ Dispose() {
33
+ // Implement IDisposable for compatibility but do nothing
34
+ // According to docs, calling Dispose does not trigger cancellation
35
+ // https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.dispose?view=net-6.0
36
+ }
37
+ }
38
+ export class OperationCanceledException extends Exception {
39
+ constructor(msg) {
40
+ super(msg ?? "The operation was canceled");
41
+ // Object.setPrototypeOf(this, OperationCanceledException.prototype);
42
+ }
43
+ }
44
+ export class Trampoline {
45
+ static get maxTrampolineCallCount() {
46
+ return 2000;
47
+ }
48
+ constructor() {
49
+ this.callCount = 0;
50
+ }
51
+ incrementAndCheck() {
52
+ return this.callCount++ > Trampoline.maxTrampolineCallCount;
53
+ }
54
+ hijack(f) {
55
+ this.callCount = 0;
56
+ setTimeout(f, 0);
57
+ }
58
+ }
59
+ export function protectedCont(f) {
60
+ return (ctx) => {
61
+ if (ctx.cancelToken.isCancelled) {
62
+ ctx.onCancel(new OperationCanceledException());
63
+ }
64
+ else if (ctx.trampoline.incrementAndCheck()) {
65
+ ctx.trampoline.hijack(() => {
66
+ try {
67
+ f(ctx);
68
+ }
69
+ catch (err) {
70
+ ctx.onError(ensureErrorOrException(err));
71
+ }
72
+ });
73
+ }
74
+ else {
75
+ try {
76
+ f(ctx);
77
+ }
78
+ catch (err) {
79
+ ctx.onError(ensureErrorOrException(err));
80
+ }
81
+ }
82
+ };
83
+ }
84
+ export function protectedBind(computation, binder) {
85
+ return protectedCont((ctx) => {
86
+ computation({
87
+ onSuccess: (x) => {
88
+ try {
89
+ binder(x)(ctx);
90
+ }
91
+ catch (err) {
92
+ ctx.onError(ensureErrorOrException(err));
93
+ }
94
+ },
95
+ onError: ctx.onError,
96
+ onCancel: ctx.onCancel,
97
+ cancelToken: ctx.cancelToken,
98
+ trampoline: ctx.trampoline,
99
+ });
100
+ });
101
+ }
102
+ export function protectedReturn(value) {
103
+ return protectedCont((ctx) => ctx.onSuccess(value));
104
+ }
105
+ export class AsyncBuilder {
106
+ Bind(computation, binder) {
107
+ return protectedBind(computation, binder);
108
+ }
109
+ Combine(computation1, computation2) {
110
+ return this.Bind(computation1, () => computation2);
111
+ }
112
+ Delay(generator) {
113
+ return protectedCont((ctx) => generator()(ctx));
114
+ }
115
+ For(sequence, body) {
116
+ const iter = sequence[Symbol.iterator]();
117
+ let cur = iter.next();
118
+ return this.While(() => !cur.done, this.Delay(() => {
119
+ const res = body(cur.value);
120
+ cur = iter.next();
121
+ return res;
122
+ }));
123
+ }
124
+ Return(value) {
125
+ return protectedReturn(value);
126
+ }
127
+ ReturnFrom(computation) {
128
+ return computation;
129
+ }
130
+ TryFinally(computation, compensation) {
131
+ return protectedCont((ctx) => {
132
+ computation({
133
+ onSuccess: (x) => {
134
+ compensation();
135
+ ctx.onSuccess(x);
136
+ },
137
+ onError: (x) => {
138
+ compensation();
139
+ ctx.onError(x);
140
+ },
141
+ onCancel: (x) => {
142
+ compensation();
143
+ ctx.onCancel(x);
144
+ },
145
+ cancelToken: ctx.cancelToken,
146
+ trampoline: ctx.trampoline,
147
+ });
148
+ });
149
+ }
150
+ TryWith(computation, catchHandler) {
151
+ return protectedCont((ctx) => {
152
+ computation({
153
+ onSuccess: ctx.onSuccess,
154
+ onCancel: ctx.onCancel,
155
+ cancelToken: ctx.cancelToken,
156
+ trampoline: ctx.trampoline,
157
+ onError: (ex) => {
158
+ try {
159
+ catchHandler(ex)(ctx);
160
+ }
161
+ catch (err) {
162
+ ctx.onError(ensureErrorOrException(err));
163
+ }
164
+ },
165
+ });
166
+ });
167
+ }
168
+ Using(resource, binder) {
169
+ return this.TryFinally(binder(resource), () => resource.Dispose());
170
+ }
171
+ While(guard, computation) {
172
+ if (guard()) {
173
+ return this.Bind(computation, () => this.While(guard, computation));
174
+ }
175
+ else {
176
+ return this.Return(void 0);
177
+ }
178
+ }
179
+ Zero() {
180
+ return protectedCont((ctx) => ctx.onSuccess(void 0));
181
+ }
182
+ }
183
+ export const singleton = new AsyncBuilder();
@@ -0,0 +1,306 @@
1
+ import { fromParts, truncate } from "./Decimal.js";
2
+ import { Exception, bigintHash } from "./Util.js";
3
+ const isBigEndian = false;
4
+ BigInt.prototype.toJSON = function () {
5
+ return `${this.toString()}`;
6
+ };
7
+ const zero = 0n;
8
+ const one = 1n;
9
+ const two = 2n;
10
+ const minusOne = -1n;
11
+ export function isBigInt(x) {
12
+ return typeof x === "bigint";
13
+ }
14
+ export function hash(x) {
15
+ return bigintHash(x);
16
+ }
17
+ export function equals(x, y) {
18
+ return x === y;
19
+ }
20
+ export function compare(x, y) {
21
+ return x < y ? -1 : x > y ? 1 : 0;
22
+ }
23
+ export function abs(x) { return x < zero ? -x : x; }
24
+ export function sign(x) { return x < zero ? -1 : x > zero ? 1 : 0; }
25
+ export function max(x, y) { return x > y ? x : y; }
26
+ export function min(x, y) { return x < y ? x : y; }
27
+ export function maxMagnitude(x, y) { return abs(x) > abs(y) ? x : y; }
28
+ export function minMagnitude(x, y) { return abs(x) < abs(y) ? x : y; }
29
+ export function clamp(x, min, max) {
30
+ return x < min ? min : x > max ? max : x;
31
+ }
32
+ export function add(x, y) { return x + y; }
33
+ export function subtract(x, y) { return x - y; }
34
+ export function multiply(x, y) { return x * y; }
35
+ export function divide(x, y) { return x / y; }
36
+ export function remainder(x, y) { return x % y; }
37
+ export function negate(x) { return -x; }
38
+ export function op_UnaryNegation(x) { return -x; }
39
+ export function op_LogicalNot(x) { return ~x; }
40
+ export function op_UnaryPlus(x) { return x; }
41
+ export function op_Addition(x, y) { return x + y; }
42
+ export function op_Subtraction(x, y) { return x - y; }
43
+ export function op_Multiply(x, y) { return x * y; }
44
+ export function op_Division(x, y) { return x / y; }
45
+ export function op_Modulus(x, y) { return x % y; }
46
+ export function op_RightShift(x, n) { return x >> BigInt(n); }
47
+ export function op_LeftShift(x, n) { return x << BigInt(n); }
48
+ export function op_BitwiseAnd(x, y) { return x & y; }
49
+ export function op_BitwiseOr(x, y) { return x | y; }
50
+ export function op_ExclusiveOr(x, y) { return x ^ y; }
51
+ export function op_LessThan(x, y) { return x < y; }
52
+ export function op_LessThanOrEqual(x, y) { return x <= y; }
53
+ export function op_GreaterThan(x, y) { return x > y; }
54
+ export function op_GreaterThanOrEqual(x, y) { return x >= y; }
55
+ export function op_Equality(x, y) { return x === y; }
56
+ export function op_Inequality(x, y) { return x !== y; }
57
+ export function get_Zero() { return zero; }
58
+ export function get_One() { return one; }
59
+ export function get_MinusOne() { return minusOne; }
60
+ export function get_IsZero(x) { return x === zero; }
61
+ export function get_IsOne(x) { return x === one; }
62
+ export function get_IsEven(x) { return isEvenInteger(x); }
63
+ export function get_IsPowerOfTwo(x) { return isPow2(x); }
64
+ export function get_Sign(x) { return sign(x); }
65
+ export function isNegative(x) { return x < zero; }
66
+ export function isPositive(x) { return x > zero; }
67
+ export function isEvenInteger(x) { return (x % two) === zero; }
68
+ export function isOddInteger(x) { return (x % two) !== zero; }
69
+ export function isPow2(x) { return (x & (x - one)) === zero; }
70
+ export function fromZero() { return zero; }
71
+ export function fromOne() { return one; }
72
+ export function fromInt8(n) { return BigInt(n); }
73
+ export function fromUInt8(n) { return BigInt(n); }
74
+ export function fromInt16(n) { return BigInt(n); }
75
+ export function fromUInt16(n) { return BigInt(n); }
76
+ export function fromInt32(n) { return BigInt(n); }
77
+ export function fromUInt32(n) { return BigInt(n); }
78
+ export function fromInt64(n) { return n; }
79
+ export function fromUInt64(n) { return n; }
80
+ export function fromInt128(n) { return n; }
81
+ export function fromUInt128(n) { return n; }
82
+ export function fromNativeInt(n) { return n; }
83
+ export function fromUNativeInt(n) { return n; }
84
+ export function fromFloat16(n) { return BigInt(Math.trunc(n)); }
85
+ export function fromFloat32(n) { return BigInt(Math.trunc(n)); }
86
+ export function fromFloat64(n) { return BigInt(Math.trunc(n)); }
87
+ export function fromDecimal(d) { return BigInt(truncate(d).toString()); }
88
+ export function fromBigInt(x) { return x; }
89
+ export function fromBoolean(b) { return BigInt(b); }
90
+ export function fromChar(c) { return BigInt(c.charCodeAt(0)); }
91
+ export function fromString(s) { return BigInt(s); }
92
+ export function fromByteArray(bytes) {
93
+ return fromSignedBytes(bytes, isBigEndian);
94
+ }
95
+ export function toByteArray(value) {
96
+ return toSignedBytes(value, isBigEndian);
97
+ }
98
+ export function toIntN_unchecked(bits, x, signed) {
99
+ return signed ? BigInt.asIntN(bits, x) : BigInt.asUintN(bits, x);
100
+ }
101
+ export function toIntN(bits, x, signed) {
102
+ let higher_bits = abs(x) >> BigInt(bits);
103
+ if (higher_bits !== 0n) {
104
+ const s = signed ? "a signed" : "an unsigned";
105
+ throw new Exception(`Value was either too large or too small for ${s} ${bits}-bit integer.`);
106
+ }
107
+ return signed ? BigInt.asIntN(bits, x) : BigInt.asUintN(bits, x);
108
+ }
109
+ export function toInt8(x) { return Number(toIntN(8, x, true)); }
110
+ export function toUInt8(x) { return Number(toIntN(8, x, false)); }
111
+ export function toInt16(x) { return Number(toIntN(16, x, true)); }
112
+ export function toUInt16(x) { return Number(toIntN(16, x, false)); }
113
+ export function toInt32(x) { return Number(toIntN(32, x, true)); }
114
+ export function toUInt32(x) { return Number(toIntN(32, x, false)); }
115
+ export function toInt64(x) { return toIntN(64, x, true); }
116
+ export function toUInt64(x) { return toIntN(64, x, false); }
117
+ export function toInt128(x) { return toIntN(128, x, true); }
118
+ export function toUInt128(x) { return toIntN(128, x, false); }
119
+ export function toNativeInt(x) { return toIntN(64, x, true); }
120
+ export function toUNativeInt(x) { return toIntN(64, x, false); }
121
+ export function toInt8_unchecked(x) { return Number(toIntN_unchecked(8, x, true)); }
122
+ export function toUInt8_unchecked(x) { return Number(toIntN_unchecked(8, x, false)); }
123
+ export function toInt16_unchecked(x) { return Number(toIntN_unchecked(16, x, true)); }
124
+ export function toUInt16_unchecked(x) { return Number(toIntN_unchecked(16, x, false)); }
125
+ export function toInt32_unchecked(x) { return Number(toIntN_unchecked(32, x, true)); }
126
+ export function toUInt32_unchecked(x) { return Number(toIntN_unchecked(32, x, false)); }
127
+ export function toInt64_unchecked(x) { return toIntN_unchecked(64, x, true); }
128
+ export function toUInt64_unchecked(x) { return toIntN_unchecked(64, x, false); }
129
+ export function toInt128_unchecked(x) { return toIntN_unchecked(128, x, true); }
130
+ export function toUInt128_unchecked(x) { return toIntN_unchecked(128, x, false); }
131
+ export function toNativeInt_unchecked(x) { return toIntN_unchecked(64, x, true); }
132
+ export function toUNativeInt_unchecked(x) { return toIntN_unchecked(64, x, false); }
133
+ export function toFloat16(x) { return Number(x); }
134
+ export function toFloat32(x) { return Number(x); }
135
+ export function toFloat64(x) { return Number(x); }
136
+ export function toDecimal(x) {
137
+ const isNegative = x < zero;
138
+ const bits = abs(x);
139
+ const low = Number(BigInt.asUintN(32, bits));
140
+ const mid = Number(BigInt.asUintN(32, bits >> 32n));
141
+ const high = Number(BigInt.asUintN(32, bits >> 64n));
142
+ const scale = 0;
143
+ return fromParts(low, mid, high, isNegative, scale);
144
+ }
145
+ export function toBigInt(x) { return x; }
146
+ export function toBoolean(x) { return x !== zero; }
147
+ export function toChar(x) {
148
+ return String.fromCharCode(toUInt16(x));
149
+ }
150
+ export function toString(x) { return x.toString(); }
151
+ export function tryParse(s, res) {
152
+ try {
153
+ res.contents = BigInt(s);
154
+ return true;
155
+ }
156
+ catch (err) {
157
+ return false;
158
+ }
159
+ }
160
+ export function parse(s) {
161
+ return BigInt(s);
162
+ }
163
+ export function pow(x, n) {
164
+ return x ** BigInt(n);
165
+ }
166
+ export function modPow(x, e, m) {
167
+ return (x ** e) % m;
168
+ }
169
+ export function divRem(x, y, out) {
170
+ const div = x / y;
171
+ const rem = x % y;
172
+ if (out === void 0) {
173
+ return [div, rem];
174
+ }
175
+ else {
176
+ out.contents = rem;
177
+ return div;
178
+ }
179
+ }
180
+ export function greatestCommonDivisor(x, y) {
181
+ while (y > zero) {
182
+ const q = x / y;
183
+ const r = x - q * y;
184
+ x = y;
185
+ y = r;
186
+ }
187
+ return x;
188
+ }
189
+ export function getBitLength(x) {
190
+ return fromFloat64(x === zero ? 1 : log2(abs(x)) + 1);
191
+ }
192
+ export function log2(x) {
193
+ const n = Number(x);
194
+ if (Number.isFinite(n))
195
+ return Math.log2(n); // fast path
196
+ if (x < zero)
197
+ return Number.NaN;
198
+ let shift = one;
199
+ while (x >= (one << shift)) {
200
+ shift = shift << one;
201
+ }
202
+ let log = zero;
203
+ while (shift > one) {
204
+ shift = shift >> one;
205
+ if (x >= (one << shift)) {
206
+ log = log + shift;
207
+ x = x >> shift;
208
+ }
209
+ }
210
+ return Number(log);
211
+ }
212
+ export function log10(x) {
213
+ return log2(x) * Math.log10(2);
214
+ }
215
+ export function ln(x) {
216
+ return log2(x) * Math.log(2);
217
+ }
218
+ export function log(x, base) {
219
+ return log2(x) / Math.log2(base);
220
+ }
221
+ export function ilog2(x) {
222
+ return BigInt(log2(x));
223
+ }
224
+ // export function copySign
225
+ // export function createChecked
226
+ // export function createSaturating
227
+ // export function createTruncating
228
+ // export function getByteCount
229
+ // export function leadingZeroCount
230
+ // export function popCount
231
+ // export function rotateLeft
232
+ // export function rotateRight
233
+ // export function trailingZeroCount
234
+ // export function tryFormat
235
+ // export function tryWriteBytes
236
+ // -------------------------------------------------
237
+ // Binary serialization
238
+ // -------------------------------------------------
239
+ const hexCodes = new Uint8Array([48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102]);
240
+ function fromHexCode(code) {
241
+ if (48 <= code && code <= 57)
242
+ return code - 48;
243
+ if (97 <= code && code <= 102)
244
+ return code - 97 + 10;
245
+ if (65 <= code && code <= 70)
246
+ return code - 65 + 10;
247
+ throw Error(`Invalid hex code: ${code}`);
248
+ }
249
+ function toSignedBytes(x, isBigEndian) {
250
+ const isNeg = x < 0n;
251
+ if (isNeg) {
252
+ const len = log2(-x);
253
+ const bits = len + (8 - len % 8);
254
+ const pow2 = (1n << BigInt(bits));
255
+ x = x + pow2; // two's complement
256
+ }
257
+ const hex = x.toString(16);
258
+ const len = hex.length;
259
+ const odd = len % 2;
260
+ const first = hex.charCodeAt(0);
261
+ const isLow = 48 <= first && first <= 55; // 0..7
262
+ const start = (isNeg && isLow) || (!isNeg && !isLow) ? 1 : 0;
263
+ const bytes = new Uint8Array(start + (len + odd) / 2);
264
+ const inc = isBigEndian ? 1 : -1;
265
+ let pos = isBigEndian ? 0 : bytes.length - 1;
266
+ if (start > 0) {
267
+ bytes[pos] = isNeg ? 255 : 0;
268
+ pos += inc;
269
+ }
270
+ if (odd > 0) {
271
+ bytes[pos] = fromHexCode(first);
272
+ pos += inc;
273
+ }
274
+ for (let i = odd; i < len; i += 2, pos += inc) {
275
+ const a = fromHexCode(hex.charCodeAt(i));
276
+ const b = fromHexCode(hex.charCodeAt(i + 1));
277
+ bytes[pos] = (a << 4) | b;
278
+ }
279
+ return bytes;
280
+ }
281
+ function fromSignedBytes(bytes, isBigEndian) {
282
+ if (bytes == null) {
283
+ throw new Exception("bytes is null");
284
+ }
285
+ const len = bytes.length;
286
+ const first = isBigEndian ? 0 : len - 1;
287
+ const isNeg = bytes[first] > 127;
288
+ const codes = new Uint16Array(len * 2 + 2);
289
+ codes[0] = 48; // 0
290
+ codes[1] = 120; // x
291
+ const inc = isBigEndian ? 1 : -1;
292
+ let pos = isBigEndian ? 0 : len - 1;
293
+ for (let i = 0; i < bytes.length; i++, pos += inc) {
294
+ const byte = bytes[pos];
295
+ codes[2 * i + 2] = hexCodes[byte >> 4];
296
+ codes[2 * i + 3] = hexCodes[byte & 15];
297
+ }
298
+ const str = String.fromCharCode.apply(null, codes);
299
+ let x = BigInt(str);
300
+ if (isNeg) {
301
+ const bits = len * 8;
302
+ const pow2 = (1n << BigInt(bits));
303
+ x = x - pow2; // two's complement
304
+ }
305
+ return x;
306
+ }