From 7c9d82018b0421a9d6f1577ca5b8aa8aa78e557b Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 17:11:04 +0000 Subject: [PATCH 1/6] Uint8ClampedArray and Float16Array Uint8ClampedArray clamps a number written to it into 0..255 and rounds half to even, where Uint8Array wraps. Float16Array keeps IEEE 754 binary16 bits, converted in TypeScript: LLVM lowers an f16 conversion to __truncsfhf2 and __extendhfsf2, which the MSVC runtime does not have. Both are one class, ConvertingTypedArray, with TypedArray's methods over a number element. Co-Authored-By: Claude Opus 5.5 --- src/generics/lib.generics.ts | 421 +++++++++++++++++++++++++++++++++++ tests/typed_array_clamped.ts | 57 +++++ tests/typed_array_float16.ts | 39 ++++ 3 files changed, 517 insertions(+) create mode 100644 tests/typed_array_clamped.ts create mode 100644 tests/typed_array_float16.ts diff --git a/src/generics/lib.generics.ts b/src/generics/lib.generics.ts index 6c508f4..2d7413f 100644 --- a/src/generics/lib.generics.ts +++ b/src/generics/lib.generics.ts @@ -1315,6 +1315,427 @@ type Float32Array = TypedArray; type Float64Array = TypedArray; +// IEEE 754 binary16, the element of Float16Array and of DataView's getFloat16 and setFloat16, and +// what Math.f16round rounds to. Converted here, bit by bit, not through an f16: LLVM lowers that to +// the __truncsfhf2 and __extendhfsf2 helpers, which the MSVC runtime does not have. Generic only so +// that a program that never uses them does not get them (see sleep). +namespace __Float16 { + function bitsOf(x: number): u64 { + let value: f64 = x; + let bits: u64 = 0; + memcpy(Ref(bits), Ref(value), 8); + return bits; + } + + // the nearest binary16, ties to even, as JavaScript rounds: too large is Infinity, too small 0 + function encode(x: number): u16 { + const b = bitsOf(x); + const sign = ((b >> 48) & 0x8000); + const exponent = ((b >> 52) & 0x7FF); + const fraction: u64 = b & 0xFFFFFFFFFFFFF; + if (exponent == 0x7FF) { + return fraction != 0 ? 0x7E00 : sign | 0x7C00; + } + + const e = exponent - 1023 + 15; + if (e >= 31) { + return sign | 0x7C00; + } + + if (e <= 0) { + // a subnormal, or 0: the 53 bits, the leading 1 among them, shifted down to 10 + const shift = 43 - e; + if (shift > 53) { + return sign; + } + + const full: u64 = fraction | 0x10000000000000; + let h = full >> shift; + const rest = full & ((1 << shift) - 1); + const half = 1 << (shift - 1); + if (rest > half || (rest == half && (h & 1) != 0)) h++; + return sign | h; + } + + // a carry out of the fraction goes into the exponent, which is right: up to Infinity + let h: u64 = (e << 10) | (fraction >> 42); + const rest = fraction & 0x3FFFFFFFFFF; + if (rest > 0x20000000000 || (rest == 0x20000000000 && (h & 1) != 0)) h++; + return sign | h; + } + + function decode(bits: u16): number { + const e = (bits >> 10) & 0x1F; + const m = bits & 0x3FF; + let value: number; + if (e == 0) { + value = m * Math.pow(2, -24); + } else if (e == 31) { + value = m != 0 ? Number.NaN : Number.POSITIVE_INFINITY; + } else { + value = (1 + m / 1024) * Math.pow(2, e - 15); + } + + // times -1, not -value: the compiler's unary minus is 0 - value, which makes -0 of 0 + return (bits & 0x8000) != 0 ? value * -1 : value; + } +} + +// A ConvertingTypedArray's element on the way in and out: S, the kept element, says which kind it +// is (see ConvertingTypedArray). Functions here, not static methods: a generic class's static +// generic method cannot be called. +namespace __ConvertedElement { + function encode(value: number): E { + if (sizeof() == 1) { + // JavaScript's ToUint8Clamp + if (!(value > 0)) return 0; + if (value >= 255) return 255; + const floor = Math.floor(value); + const half = floor + 0.5; + if (value > half) return (floor + 1); + if (value < half) return floor; + return (floor % 2 == 0 ? floor : floor + 1); + } + + return __Float16.encode(value); + } + + function decode(element: E): number { + if (sizeof() == 1) { + return element; + } + + return __Float16.decode(element); + } +} + +// The two typed arrays whose element is not a C type: Uint8ClampedArray keeps a byte, and a number +// written to it is clamped into 0..255 and rounded half to even, where Uint8Array wraps it; +// Float16Array keeps the bits of a binary16 (see __Float16). Each element is a `number` to the +// program, as in JavaScript, and is converted on the way in and out. S, the kept element, tells the +// two apart: u8 is Uint8ClampedArray, u16 is Float16Array. Otherwise as TypedArray: a window that +// subarray() shares, a fixed length, and the same methods, with `_with` for `with`. +class ConvertingTypedArray { + private elements: TypedArray; + + constructor(data: number[] = []) { + this.elements = new TypedArray(data.length); + for (let i = 0; i < data.length; i++) { + this.elements[i] = __ConvertedElement.encode(data[i]); + } + } + + // `length` elements, each 0 + constructor(length: int) { + this.elements = new TypedArray(length); + } + + // a copy of another's elements: the two share nothing + constructor(source: ConvertingTypedArray) { + this.elements = new TypedArray(source.elements); + } + + public [index: int]: number; + + // outside the window a read gives 0 and a write does nothing, as TypedArray's + public get(index: int): number { + return __ConvertedElement.decode(this.elements[index]); + } + + public set(index: int, value: number) { + this.elements[index] = __ConvertedElement.encode(value); + } + + public get length() { + return this.elements.length; + } + + public get BYTES_PER_ELEMENT(): int { + return sizeof(); + } + + public get byteLength(): int { + return this.elements.byteLength; + } + + public get byteOffset(): int { + return this.elements.byteOffset; + } + + // one of the same kind around `elements` + private __around(elements: TypedArray): ConvertingTypedArray { + const result = new ConvertingTypedArray(0); + result.elements = elements; + return result; + } + + private __clamp(index: int): int { + const count = this.elements.length; + if (index < 0) { + index = index + count; + return index < 0 ? 0 : index; + } + + return index > count ? count : index; + } + + public at(index: int): number | undefined { + if (index < 0) { + index = index + this.length; + } + + if (index < 0 || index >= this.length) { + return undefined; + } + + return this[index]; + } + + public copyWithin(target: int, start = 0, end = this.length): ConvertingTypedArray { + this.elements.copyWithin(target, start, end); + return this; + } + + @borrows("this") + public entries() { + return this.__entries(); + } + + @borrows("this") + public keys() { + return this.elements.keys(); + } + + @borrows("this") + public values() { + return this.__values(); + } + + @borrows("this") + public [Symbol.iterator]() { + return this.__values(); + } + + @borrows("this") + private *__entries() { + for (let i = 0; i < this.length; i++) { + const v = this[i]; + yield [i, v]; + } + } + + @borrows("this") + private *__values() { + for (let i = 0; i < this.length; i++) { + yield this[i]; + } + } + + public every(func: (v: number, i: number) => boolean) { + for (let i = 0; i < this.length; i++) if (!func(this[i], i)) return false; + return true; + } + + public some(func: (v: number, i: number) => boolean) { + for (let i = 0; i < this.length; i++) if (func(this[i], i)) return true; + return false; + } + + // the value is converted once, as JavaScript does + public fill(value: number, start = 0, end = this.length): ConvertingTypedArray { + this.elements.fill(__ConvertedElement.encode(value), start, end); + return this; + } + + public filter(func: (v: number, i: number) => boolean): ConvertingTypedArray { + const data: number[] = []; + for (let i = 0; i < this.length; i++) { + const v = this[i]; + if (func(v, i)) data.push(v); + } + + return new ConvertingTypedArray(data); + } + + public find(func: (v: number, i: number) => boolean): number | undefined { + for (let i = 0; i < this.length; i++) if (func(this[i], i)) return this[i]; + return undefined; + } + + public findIndex(func: (v: number, i: number) => boolean) { + for (let i = 0; i < this.length; i++) if (func(this[i], i)) return i; + return -1; + } + + public findLast(func: (v: number, i: number) => boolean): number | undefined { + for (let i = this.length - 1; i >= 0; i--) if (func(this[i], i)) return this[i]; + return undefined; + } + + public findLastIndex(func: (v: number, i: number) => boolean) { + for (let i = this.length - 1; i >= 0; i--) if (func(this[i], i)) return i; + return -1; + } + + public forEach(func: (v: number, i: number) => void) { + for (let i = 0; i < this.length; i++) func(this[i], i); + } + + // SameValueZero: NaN is found, where indexOf does not find it + public includes(searchElement: number, fromIndex = 0) { + for (let i = this.__clamp(fromIndex); i < this.length; i++) { + const v = this[i]; + if (v == searchElement || (v != v && searchElement != searchElement)) return true; + } + + return false; + } + + public indexOf(searchElement: number, fromIndex = 0) { + for (let i = this.__clamp(fromIndex); i < this.length; i++) if (this[i] == searchElement) return i; + return -1; + } + + public lastIndexOf(searchElement: number, fromIndex = this.length - 1) { + let i = fromIndex < 0 ? fromIndex + this.length : fromIndex; + if (i >= this.length) { + i = this.length - 1; + } + + for (; i >= 0; i--) if (this[i] == searchElement) return i; + return -1; + } + + public join(separator = ",") { + const parts: string[] = []; + for (let i = 0; i < this.length; i++) { + if (i > 0) { + parts.push(separator + this[i]); + } else { + parts.push("" + this[i]); + } + } + + return "".concat(...parts); + } + + public toString() { + return this.join(); + } + + public toLocaleString() { + return this.join(); + } + + // each result is converted as a write is: a Uint8ClampedArray's map clamps + public map(func: (v: number, i: number) => number): ConvertingTypedArray { + const result = new ConvertingTypedArray(this.length); + for (let i = 0; i < this.length; i++) result[i] = func(this[i], i); + return result; + } + + public reduce(func: (v: V, t: number) => V, initial?: V): V { + if (initial == undefined) { + if (this.length <= 0) { + throw new TypeError("Reduce of empty array with no initial value"); + } + + if (__is(this[0])) { + let result = this[0]; + for (let i = 1; i < this.length; i++) result = func(result, this[i]); + return result; + } + } + else { + let result = initial; + for (let i = 0; i < this.length; i++) result = func(result, this[i]); + return result; + } + } + + public reduceRight(func: (v: V, t: number) => V, initial?: V): V { + if (initial == undefined) { + if (this.length <= 0) { + throw new TypeError("Reduce of empty array with no initial value"); + } + + if (__is(this[0])) { + let result = this[this.length - 1]; + for (let i = this.length - 2; i >= 0; i--) result = func(result, this[i]); + return result; + } + } + else { + let result = initial; + for (let i = this.length - 1; i >= 0; i--) result = func(result, this[i]); + return result; + } + } + + public reverse(): ConvertingTypedArray { + this.elements.reverse(); + return this; + } + + public slice(start = 0, end = this.length): ConvertingTypedArray { + return this.__around(this.elements.slice(start, end)); + } + + // a window onto the same elements: nothing is copied + public subarray(begin = 0, end = this.length): ConvertingTypedArray { + return this.__around(this.elements.subarray(begin, end)); + } + + // By value with no compare function, NaN last; stable. The values are sorted, not the kept + // elements: a binary16's bits do not sort as its value does. + public sort(callbackfn?: (value1: number, value2: number) => int): ConvertingTypedArray { + const data: number[] = []; + data.length = this.length; + for (let i = 0; i < this.length; i++) data[i] = this[i]; + if (callbackfn) { + data.sort(callbackfn); + } else { + data.sort((a: number, b: number) => { + if (a < b) return -1; + if (a > b) return 1; + if (a == b) return 0; + if (a != a) return b != b ? 0 : 1; + return -1; + }); + } + + for (let i = 0; i < this.length; i++) this[i] = data[i]; + return this; + } + + public toReversed(): ConvertingTypedArray { + return this.slice().reverse(); + } + + public toSorted(callbackfn?: (value1: number, value2: number) => int): ConvertingTypedArray { + return this.slice().sort(callbackfn); + } + + // `with`, which is a keyword here + public _with(index: int, value: number): ConvertingTypedArray { + if (index < 0) { + index = index + this.length; + } + + if (index < 0 || index >= this.length) { + throw new RangeError(); + } + + const copy = this.slice(); + copy[index] = value; + return copy; + } +} + +type Uint8ClampedArray = ConvertingTypedArray; + +type Float16Array = ConvertingTypedArray; + // Atomic operations on an integer TypedArray's elements, each sequentially consistent, as in // JavaScript. Each is one LLVM atomic `load`, `store`, `atomicrmw` or `cmpxchg` on the element. The // operation codes are written out, not passed in: the builtins take them only as constants. The diff --git a/tests/typed_array_clamped.ts b/tests/typed_array_clamped.ts new file mode 100644 index 0000000..8568c42 --- /dev/null +++ b/tests/typed_array_clamped.ts @@ -0,0 +1,57 @@ +// Uint8ClampedArray: a number written to it is clamped into 0..255 and rounded half to even, as in +// JavaScript, where Uint8Array wraps it +function main() { + const c = new Uint8ClampedArray(8); + assert(c.length == 8 && c[0] == 0, "8 elements, each 0"); + assert(c.BYTES_PER_ELEMENT == 1 && c.byteLength == 8, "one byte each"); + + c[0] = 300; + assert(c[0] == 255, "300 clamps to 255"); + c[1] = -5; + assert(c[1] == 0, "-5 clamps to 0"); + c[2] = 1.5; + assert(c[2] == 2, "1.5 rounds to 2"); + c[3] = 2.5; + assert(c[3] == 2, "2.5 rounds to even 2"); + c[4] = 2.6; + assert(c[4] == 3, "2.6 rounds to 3"); + c[5] = Number.NaN; + assert(c[5] == 0, "NaN is 0"); + c[6] = Number.POSITIVE_INFINITY; + assert(c[6] == 255, "Infinity is 255"); + c[7] = 254.5; + assert(c[7] == 254, "254.5 rounds to even 254"); + + // where Uint8Array wraps + const u = new Uint8Array(1); + u[0] = 300; + assert(u[0] == 44, "Uint8Array wraps 300 to 44"); + + const given = new Uint8ClampedArray([-1, 128, 1000]); + assert(given.join() == "0,128,255", "from an array, clamped"); + + // a write through a method is clamped too + const filled = new Uint8ClampedArray(3).fill(999); + assert(filled.join() == "255,255,255", "fill clamps"); + const doubled = given.map((v: number, i: number) => v * 2); + assert(doubled.join() == "0,255,255", "map clamps"); + const changed = given._with(0, 77.5); + assert(changed[0] == 78 && given[0] == 0, "with clamps, and copies"); + + // subarray shares the elements, slice copies them + const view = given.subarray(1); + view[0] = -20; + assert(given[1] == 0, "a write through a subarray is seen, clamped"); + const copy = given.slice(); + copy[2] = 1; + assert(given[2] == 255, "a slice is a copy"); + + let sum = 0; + for (const v of given) sum += v; + assert(sum == 255, "iterates its values"); + assert(given.reduce((a: number, v: number) => a + v, 0) == 255, "reduce"); + assert(given.indexOf(255) == 2 && given.includes(0), "indexOf and includes"); + assert(new Uint8ClampedArray([3, 1, 2]).sort().join() == "1,2,3", "sort"); + + console.log("ALL DONE"); +} diff --git a/tests/typed_array_float16.ts b/tests/typed_array_float16.ts new file mode 100644 index 0000000..fa2ead3 --- /dev/null +++ b/tests/typed_array_float16.ts @@ -0,0 +1,39 @@ +// Float16Array: each element is an IEEE 754 binary16, rounded to the nearest, ties to even, as in +// JavaScript; a value too large for one is Infinity +function main() { + const h = new Float16Array(4); + assert(h.length == 4 && h[3] == 0, "4 elements, each 0"); + assert(h.BYTES_PER_ELEMENT == 2 && h.byteLength == 8, "two bytes each"); + + h[0] = 1.5; + assert(h[0] == 1.5, "1.5 is exact"); + h[1] = 0.1; + assert(h[1] == 0.0999755859375, "0.1 rounds to the nearest binary16"); + h[2] = 65504; + assert(h[2] == 65504, "the largest finite binary16"); + h[3] = 65520; + assert(h[3] == Number.POSITIVE_INFINITY, "65520 rounds up to Infinity"); + + const r = new Float16Array([2049, 2051, -2, Number.NaN, Math.pow(2, -24), Math.pow(2, -25)]); + assert(r[0] == 2048, "2049 ties to even 2048"); + assert(r[1] == 2052, "2051 ties to even 2052"); + assert(r[2] == -2, "a negative value"); + assert(r[3] != r[3], "NaN stays NaN"); + assert(r[4] == Math.pow(2, -24), "the smallest subnormal"); + assert(r[5] == 0, "half of it ties to even 0"); + + // -0 keeps its sign (1 / -Infinity is -0) + const z = new Float16Array(1); + z[0] = 1 / Number.NEGATIVE_INFINITY; + assert(1 / z[0] == Number.NEGATIVE_INFINITY, "-0 keeps its sign"); + + // sorted by value, not by its bits: a negative binary16's bits are the larger + const s = new Float16Array([1, -1, 0.5, -0.5]).sort(); + assert(s.join() == "-1,-0.5,0.5,1", "sort by value"); + + const m = new Float16Array([1, 2]).map((v: number, i: number) => v / 3); + assert(m[0] == 0.333251953125, "map rounds each result"); + assert(m.subarray(1).byteOffset == 2, "a subarray's byteOffset"); + + console.log("ALL DONE"); +} From 49ad69771b7c032879a3cdeaa9956159d102f839 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 17:22:00 +0000 Subject: [PATCH 2/6] SharedArrayBuffer and DataView; ArrayBuffer is declared for programs DataView reads and writes every width JavaScript has (Int8 to Float64, Float16, BigInt64) at any byte offset of an ArrayBuffer or SharedArrayBuffer, big-endian unless littleEndian. A view made without a length follows a resizable buffer. A growable SharedArrayBuffer takes maxByteLength bytes up front, so grow() never moves them under another thread. Math.f16round. ArrayBuffer was in lib.ts but not in lib.d.ts, so no program could name it. Declaring it brings it to JavaScript's rules: resizable only with a maxByteLength, resize checks it, byteLength, and transfer(newByteLength) honours the length. A program calls a lib.ts class's methods by vtable slot, taken from lib.d.ts order, so each class lists its declared members first and its private ones after. Under -mm=own a DataView keeps its buffer (@keeps), as Response keeps its headers. Co-Authored-By: Claude Opus 5.5 --- src/generics/lib.generics.ts | 8 +- src/lib.d.ts | 93 +++++++ src/lib.ts | 431 ++++++++++++++++++++++++++++++++- tests/arraybuffer_resize.ts | 58 +++++ tests/dataview.ts | 84 +++++++ tests/dataview_keeps_buffer.ts | 25 ++ tests/shared_array_buffer.ts | 48 ++++ 7 files changed, 732 insertions(+), 15 deletions(-) create mode 100644 tests/arraybuffer_resize.ts create mode 100644 tests/dataview.ts create mode 100644 tests/dataview_keeps_buffer.ts create mode 100644 tests/shared_array_buffer.ts diff --git a/src/generics/lib.generics.ts b/src/generics/lib.generics.ts index 2d7413f..e2098d6 100644 --- a/src/generics/lib.generics.ts +++ b/src/generics/lib.generics.ts @@ -891,8 +891,8 @@ static class Array { // seen through the other. The elements are held through a Shared handle, so under -mm=own each window // holds a count of them and none owns them alone. The length is fixed, as in JavaScript: there is no // push, pop, shift, unshift or splice. Not here: set(array, offset), which the indexer's set(index, -// value) takes the name of, as a class cannot overload a method; `buffer`, as there is no ArrayBuffer -// under it; and the static from, of and BYTES_PER_ELEMENT, as Uint8Array and its kin are type names. +// value) takes the name of, as a class cannot overload a method; `buffer`, as its elements are not +// an ArrayBuffer's bytes (a DataView reads those); and the static from, of and BYTES_PER_ELEMENT, as Uint8Array and its kin are type names. class TypedArray { private store: Shared; private first: int; @@ -1740,8 +1740,8 @@ type Float16Array = ConvertingTypedArray; // JavaScript. Each is one LLVM atomic `load`, `store`, `atomicrmw` or `cmpxchg` on the element. The // operation codes are written out, not passed in: the builtins take them only as constants. The // value is a `number`, as in JavaScript, and wraps to the element's width (300 added to a Uint8Array -// element adds 44). There is no SharedArrayBuffer, so an operation acts on the elements the array -// shares with its subarrays: threads share the array itself (see Thread.spawn). +// element adds 44). A TypedArray cannot view a SharedArrayBuffer, so an operation acts on the elements +// the array shares with its subarrays: threads share the array itself (see Thread.spawn). // `waitAsync` is not here: there is no event loop to resolve its promise. namespace Atomics { // atomicrmw operations: 0 xchg, 1 add, 2 sub, 3 and, 5 or, 6 xor; ordering 7: seq_cst diff --git a/src/lib.d.ts b/src/lib.d.ts index 3fae85d..7520001 100644 --- a/src/lib.d.ts +++ b/src/lib.d.ts @@ -585,6 +585,11 @@ declare namespace Math { * @param x A numeric expression. */ function fround(x: number): number; + /** + * Returns the nearest half precision float representation of a number. + * @param x A numeric expression. + */ + function f16round(x: number): number; /** * Returns the square root of the sum of squares of its arguments. * @param values Values to compute the square root for. @@ -682,6 +687,94 @@ declare namespace Math { function trunc(x: number): number; } +declare enum States { + HasMaxByteLength = 1, + NonResizable = 2, + Detached = 4, + View = 8, +} + +@final +@owned +declare class ArrayBuffer { + private arrayOfView: char[]; + private states: States; + maxByteLength: int; + + constructor(length: int, options?: { maxByteLength?: int }); + + get resizable(): boolean; + get detached(): boolean; + get byteLength(): int; + static isView(arrayBuffer: ArrayBuffer): boolean; + resize(newLength: int): void; + slice(start?: int, end?: int): ArrayBuffer; + transfer(newByteLength?: int): ArrayBuffer; + transferToFixedLength(newByteLength?: int): ArrayBuffer; + @lends("this") + __bytes(): char[]; + [Symbol.dispose](): void; +} + +@final +@owned +declare class SharedArrayBuffer { + private bytes: char[]; + private length: int; + private capacity: int; + private canGrow: boolean; + + constructor(length: int, options?: { maxByteLength?: int }); + + get byteLength(): int; + get growable(): boolean; + get maxByteLength(): int; + grow(newLength: int): void; + slice(start?: int, end?: int): SharedArrayBuffer; + @lends("this") + __bytes(): char[]; +} + +@final +@owned +declare class DataView { + private source: ArrayBuffer | SharedArrayBuffer; + private offset: int; + private fixedLength: int; + private tracksLength: boolean; + + @keeps("buffer") + constructor(buffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: int, byteLength?: int); + + @lends("this") + get buffer(): ArrayBuffer | SharedArrayBuffer; + get byteOffset(): int; + get byteLength(): int; + + getInt8(byteOffset: int): number; + getUint8(byteOffset: int): number; + getInt16(byteOffset: int, littleEndian?: boolean): number; + getUint16(byteOffset: int, littleEndian?: boolean): number; + getInt32(byteOffset: int, littleEndian?: boolean): number; + getUint32(byteOffset: int, littleEndian?: boolean): number; + getFloat16(byteOffset: int, littleEndian?: boolean): number; + getFloat32(byteOffset: int, littleEndian?: boolean): number; + getFloat64(byteOffset: int, littleEndian?: boolean): number; + getBigInt64(byteOffset: int, littleEndian?: boolean): bigint; + getBigUint64(byteOffset: int, littleEndian?: boolean): bigint; + setInt8(byteOffset: int, value: number): void; + setUint8(byteOffset: int, value: number): void; + setInt16(byteOffset: int, value: number, littleEndian?: boolean): void; + setUint16(byteOffset: int, value: number, littleEndian?: boolean): void; + setInt32(byteOffset: int, value: number, littleEndian?: boolean): void; + setUint32(byteOffset: int, value: number, littleEndian?: boolean): void; + setFloat16(byteOffset: int, value: number, littleEndian?: boolean): void; + setFloat32(byteOffset: int, value: number, littleEndian?: boolean): void; + setFloat64(byteOffset: int, value: number, littleEndian?: boolean): void; + setBigInt64(byteOffset: int, value: bigint, littleEndian?: boolean): void; + setBigUint64(byteOffset: int, value: bigint, littleEndian?: boolean): void; +} + @final @owned declare class Headers { diff --git a/src/lib.ts b/src/lib.ts index b381ea8..8114c1f 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -1780,6 +1780,14 @@ export static class Math { return x; } + /** + * Returns the nearest half precision float representation of a number. + * @param x A numeric expression. + */ + f16round(x: number): number { + return __Float16.decode(__Float16.encode(x)); + } + /** * Returns the square root of the sum of squares of its arguments. * @param values Values to compute the square root for. @@ -1967,15 +1975,26 @@ enum States { @final export class ArrayBuffer { - private arrayOfView: char[]; private states: States; public maxByteLength: int; public constructor(length: int, options?: { maxByteLength?: int }) { + if (length < 0) { + throw new RangeError("Invalid array buffer length"); + } + + // resizable only when given a maxByteLength, as in JavaScript if (options != undefined && options.maxByteLength != undefined) { + if (options.maxByteLength < length) { + throw new RangeError("Invalid array buffer max length"); + } + this.maxByteLength = options.maxByteLength; this.states |= States.HasMaxByteLength; + } else { + this.maxByteLength = length; + this.states |= States.NonResizable; } // always an array, empty for no bytes and once detached: never null @@ -1995,16 +2014,35 @@ export class ArrayBuffer { return (this.states & States.Detached) == States.Detached; } + // 0 once detached + public get byteLength(): int { + return this.arrayOfView.length; + } + public static isView(arrayBuffer: ArrayBuffer) { return (arrayBuffer.states & States.View) == States.View; } public resize(newLength: int) { this.expectAttached(); + if (!this.resizable) { + throw new TypeError("ArrayBuffer is not resizable"); + } + + if (newLength < 0 || newLength > this.maxByteLength) { + throw new RangeError("Invalid array buffer length"); + } + + // the bytes past the old length are 0, as in JavaScript: setting the length alone keeps + // what a shrink left there + const oldLength = this.arrayOfView.length; this.arrayOfView.length = newLength; + for (let i = oldLength; i < newLength; i++) { + this.arrayOfView[i] = 0; + } } - public slice(start = 0, end = this.arrayOfView.length) { + public slice(start = 0, end: int = this.arrayOfView.length) { this.expectAttached(); if (start < 0 && -this.arrayOfView.length <= start) start += this.arrayOfView.length; if (start < -this.arrayOfView.length) start = 0; @@ -2019,19 +2057,31 @@ export class ArrayBuffer { if (start >= end) end = start; const newArrayBuffer = new ArrayBuffer(0); - newArrayBuffer.states = this.states | States.NonResizable; - newArrayBuffer.maxByteLength = this.maxByteLength; + newArrayBuffer.states = (this.states & ~States.HasMaxByteLength) | States.NonResizable; newArrayBuffer.arrayOfView = this.copyOf(start, end); + newArrayBuffer.maxByteLength = end - start; return newArrayBuffer; } - // TODO: newByteLength is not used + // the bytes in a buffer of newByteLength, its own length by default: cut short, or 0 past it public transfer(newByteLength?: int) { this.expectAttached(); + const length = newByteLength == undefined ? this.arrayOfView.length : newByteLength; + if (length < 0 || (this.resizable && length > this.maxByteLength)) { + throw new RangeError("Invalid array buffer length"); + } + const newArrayBuffer = new ArrayBuffer(0); newArrayBuffer.states = this.states; - newArrayBuffer.maxByteLength = this.maxByteLength; - newArrayBuffer.arrayOfView = this.copyOf(0, this.arrayOfView.length); + newArrayBuffer.maxByteLength = this.resizable ? this.maxByteLength : length; + const kept = length < this.arrayOfView.length ? length : this.arrayOfView.length; + const bytes = this.copyOf(0, kept); + bytes.length = length; + for (let i = kept; i < length; i++) { + bytes[i] = 0; + } + + newArrayBuffer.arrayOfView = bytes; this.detach(); return newArrayBuffer; @@ -2040,9 +2090,23 @@ export class ArrayBuffer { public transferToFixedLength(newByteLength?: int) { const newArrayBuffer = this.transfer(newByteLength); newArrayBuffer.states |= States.NonResizable; + newArrayBuffer.maxByteLength = newArrayBuffer.arrayOfView.length; return newArrayBuffer; } + // for DataView: the bytes themselves + @lends("this") + public __bytes(): char[] { + return this.arrayOfView; + } + + // the assignment releases the bytes under rc and own, and leaves them to the collector under gc + [Symbol.dispose]() { + if (!this.detached) { + this.arrayOfView = []; + } + } + // The bytes [start, end) in an array of their own. A slice is a copy, as in JavaScript, and a // transfer copies too: the bytes cannot move out of the field into another object under // -mm=own, where a read of a field only borrows it. @@ -2067,12 +2131,357 @@ export class ArrayBuffer { this.states |= States.Detached; this.arrayOfView = []; } +} - // the assignment releases the bytes under rc and own, and leaves them to the collector under gc - [Symbol.dispose]() { - if (!this.detached) { - this.arrayOfView = []; +// A block of bytes that threads share, as in JavaScript. A growable one takes all maxByteLength bytes +// up front, so grow() never moves them while another thread reads: it only says more of them are in +// use. Nothing here is atomic: threads that write the same bytes order their writes themselves (a +// TypedArray cannot view these bytes, so Atomics cannot reach them). +@final +export class SharedArrayBuffer { + private bytes: char[]; + private length: int; + private capacity: int; + private canGrow: boolean; + + public constructor(length: int, options?: { maxByteLength?: int }) { + if (length < 0) { + throw new RangeError("Invalid array buffer length"); + } + + let capacity = length; + let canGrow = false; + if (options != undefined && options.maxByteLength != undefined) { + capacity = options.maxByteLength; + canGrow = true; + if (capacity < length) { + throw new RangeError("Invalid array buffer max length"); + } + } + + let bytes: char[] = []; + if (capacity > 0) { + bytes.length = capacity; + } + + this.bytes = bytes; + this.length = length; + this.capacity = capacity; + this.canGrow = canGrow; + } + + public get byteLength(): int { + return this.length; + } + + public get growable(): boolean { + return this.canGrow; + } + + public get maxByteLength(): int { + return this.capacity; + } + + // the bytes past the old length are 0: they were never written + public grow(newLength: int): void { + if (!this.canGrow) { + throw new TypeError("SharedArrayBuffer is not growable"); + } + + if (newLength < this.length || newLength > this.capacity) { + throw new RangeError("Invalid array buffer length"); + } + + this.length = newLength; + } + + // a copy of the bytes [start, end), in a SharedArrayBuffer of its own that does not grow + public slice(start = 0, end = this.length): SharedArrayBuffer { + const from = SharedArrayBuffer.clamp(start, this.length); + const until = SharedArrayBuffer.clamp(end, this.length); + const count = until > from ? until - from : 0; + const copy = new SharedArrayBuffer(count); + for (let i = 0; i < count; i++) { + copy.bytes[i] = this.bytes[from + i]; + } + + return copy; + } + + // for DataView: the bytes themselves, of which the first byteLength are in use + @lends("this") + public __bytes(): char[] { + return this.bytes; + } + + // a relative index, as JavaScript takes one: a negative one counts from the end + private static clamp(index: int, length: int): int { + if (index < 0) { + index = index + length; + return index < 0 ? 0 : index; + } + + return index > length ? length : index; + } +} + +// A view that reads and writes numbers of any width at any byte offset of an ArrayBuffer or a +// SharedArrayBuffer, big-endian unless littleEndian is true, as in JavaScript. An offset past the +// view's end is a RangeError, and a detached ArrayBuffer a TypeError. Made without a byteLength over +// a buffer that can resize or grow, the view follows the buffer's length. +@final +export class DataView { + private source: ArrayBuffer | SharedArrayBuffer; + private offset: int; + private fixedLength: int; + private tracksLength: boolean; + + // One constructor of a union, not two: lib.d.ts cannot declare an overloaded one. The view keeps + // the buffer: under -mm=own its caller gives the buffer up, and reaches it through `buffer`. + @keeps("buffer") + public constructor(buffer: ArrayBuffer | SharedArrayBuffer, byteOffset = 0, byteLength?: int) { + if (buffer instanceof ArrayBuffer) { + if (buffer.detached) { + throw new TypeError("ArrayBuffer is detached"); + } + + this.init(buffer.byteLength, buffer.resizable, byteOffset, byteLength); + } else { + this.init(buffer.byteLength, buffer.growable, byteOffset, byteLength); + } + + // stored once, after it is measured: under -mm=own the store moves it + this.source = buffer; + } + + @lends("this") + public get buffer(): ArrayBuffer | SharedArrayBuffer { + return this.source; + } + + public get byteOffset(): int { + this.bufferLength(); + return this.offset; + } + + public get byteLength(): int { + const bufferLength = this.bufferLength(); + if (this.tracksLength) { + return bufferLength - this.offset; + } + + if (this.offset + this.fixedLength > bufferLength) { + throw new TypeError("DataView is out of bounds"); + } + + return this.fixedLength; + } + + public getInt8(byteOffset: int): number { + return this.read(byteOffset, 1, false); + } + + public getUint8(byteOffset: int): number { + return this.read(byteOffset, 1, false); + } + + public getInt16(byteOffset: int, littleEndian = false): number { + return this.read(byteOffset, 2, littleEndian); + } + + public getUint16(byteOffset: int, littleEndian = false): number { + return this.read(byteOffset, 2, littleEndian); + } + + public getInt32(byteOffset: int, littleEndian = false): number { + return this.read(byteOffset, 4, littleEndian); + } + + public getUint32(byteOffset: int, littleEndian = false): number { + return this.read(byteOffset, 4, littleEndian); + } + + public getFloat16(byteOffset: int, littleEndian = false): number { + return __Float16.decode(this.read(byteOffset, 2, littleEndian)); + } + + public getFloat32(byteOffset: int, littleEndian = false): number { + return DataView.f32Of(this.read(byteOffset, 4, littleEndian)); + } + + public getFloat64(byteOffset: int, littleEndian = false): number { + return DataView.f64Of(this.read(byteOffset, 8, littleEndian)); + } + + public getBigInt64(byteOffset: int, littleEndian = false): bigint { + return this.read(byteOffset, 8, littleEndian); + } + + // a bigint here is 64 bits and signed: a value of 2^63 or more comes out negative + public getBigUint64(byteOffset: int, littleEndian = false): bigint { + return this.read(byteOffset, 8, littleEndian); + } + + public setInt8(byteOffset: int, value: number): void { + this.write(byteOffset, 1, DataView.wrap(value), false); + } + + public setUint8(byteOffset: int, value: number): void { + this.write(byteOffset, 1, DataView.wrap(value), false); + } + + public setInt16(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 2, DataView.wrap(value), littleEndian); + } + + public setUint16(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 2, DataView.wrap(value), littleEndian); + } + + public setInt32(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 4, DataView.wrap(value), littleEndian); + } + + public setUint32(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 4, DataView.wrap(value), littleEndian); + } + + public setFloat16(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 2, __Float16.encode(value), littleEndian); + } + + public setFloat32(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 4, DataView.f32Bits(value), littleEndian); + } + + public setFloat64(byteOffset: int, value: number, littleEndian = false): void { + this.write(byteOffset, 8, DataView.f64Bits(value), littleEndian); + } + + public setBigInt64(byteOffset: int, value: bigint, littleEndian = false): void { + this.write(byteOffset, 8, value, littleEndian); + } + + public setBigUint64(byteOffset: int, value: bigint, littleEndian = false): void { + this.write(byteOffset, 8, value, littleEndian); + } + + private init(bufferLength: int, followsBuffer: boolean, byteOffset: int, byteLength?: int) { + if (byteOffset < 0 || byteOffset > bufferLength) { + throw new RangeError("Start offset is outside the bounds of the buffer"); } + + this.offset = byteOffset; + if (byteLength == undefined) { + this.fixedLength = bufferLength - byteOffset; + this.tracksLength = followsBuffer; + } else { + if (byteLength < 0 || byteOffset + byteLength > bufferLength) { + throw new RangeError("Invalid DataView length"); + } + + this.fixedLength = byteLength; + this.tracksLength = false; + } + } + + // the buffer's length now: a resizable ArrayBuffer may have shrunk under the view + private bufferLength(): int { + const source = this.source; + if (source instanceof ArrayBuffer) { + if (source.detached) { + throw new TypeError("ArrayBuffer is detached"); + } + + return source.byteLength; + } + + return source.byteLength; + } + + @lends("this") + private bytes(): char[] { + const source = this.source; + if (source instanceof ArrayBuffer) { + return source.__bytes(); + } + + return source.__bytes(); + } + + private check(byteOffset: int, size: int): void { + const length = this.byteLength; + if (byteOffset < 0 || byteOffset + size > length) { + throw new RangeError("Offset is outside the bounds of the DataView"); + } + } + + // `size` bytes at `byteOffset`, as one unsigned integer + private read(byteOffset: int, size: int, littleEndian: boolean): u64 { + this.check(byteOffset, size); + const bytes = this.bytes(); + const at = this.offset + byteOffset; + let value: u64 = 0; + for (let i = 0; i < size; i++) { + const b = bytes[littleEndian ? at + size - 1 - i : at + i]; + value = (value << 8) | b; + } + + return value; + } + + private write(byteOffset: int, size: int, value: u64, littleEndian: boolean): void { + this.check(byteOffset, size); + const bytes = this.bytes(); + const at = this.offset + byteOffset; + for (let i = 0; i < size; i++) { + const b = (value & 0xFF); + bytes[littleEndian ? at + i : at + size - 1 - i] = b; + value = value >> 8; + } + } + + // a number as an integer of the element's width, as JavaScript's ToInt32 and its kin wrap it: + // NaN and the infinities are 0 + private static wrap(value: number): u64 { + if (!isFinite(value)) { + return 0; + } + + const whole = Math.trunc(value); + if (whole < 0) { + return whole; + } + + return whole; + } + + private static f32Of(bits: u64): number { + let b: u32 = bits; + let value: f32 = 0; + memcpy(Ref(value), Ref(b), 4); + return value; + } + + private static f32Bits(x: number): u64 { + let value: f32 = x; + let b: u32 = 0; + memcpy(Ref(b), Ref(value), 4); + return b; + } + + private static f64Of(bits: u64): number { + let b: u64 = bits; + let value: f64 = 0; + memcpy(Ref(value), Ref(b), 8); + return value; + } + + private static f64Bits(x: number): u64 { + let value: f64 = x; + let b: u64 = 0; + memcpy(Ref(b), Ref(value), 8); + return b; } } diff --git a/tests/arraybuffer_resize.ts b/tests/arraybuffer_resize.ts new file mode 100644 index 0000000..bcaf8d4 --- /dev/null +++ b/tests/arraybuffer_resize.ts @@ -0,0 +1,58 @@ +// not own: the program goes on using a buffer after a DataView keeps it, which -mm=own refuses +// ArrayBuffer: resizable only when given a maxByteLength, and a DataView made without a length follows +// a resizable buffer's length, as in JavaScript +function main() { + const fixed = new ArrayBuffer(4); + assert(!fixed.resizable && fixed.maxByteLength == 4, "not resizable without maxByteLength"); + let refused = false; + try { + fixed.resize(2); + } catch (e) { + refused = e instanceof TypeError; + } + + assert(refused, "a fixed buffer refuses resize"); + + const growing = new ArrayBuffer(2, { maxByteLength: 8 }); + assert(growing.resizable && growing.maxByteLength == 8, "resizable with maxByteLength"); + const tracking = new DataView(growing); + const fixedView = new DataView(growing, 0, 2); + tracking.setUint16(0, 0xABCD); + + growing.resize(6); + assert(growing.byteLength == 6, "grown"); + assert(tracking.byteLength == 6 && fixedView.byteLength == 2, "a view without a length follows it"); + assert(tracking.getUint16(0) == 0xABCD, "the bytes stay"); + assert(tracking.getUint32(2) == 0, "the new bytes are 0"); + + let tooLarge = false; + try { + growing.resize(9); + } catch (e) { + tooLarge = e instanceof RangeError; + } + + assert(tooLarge, "past maxByteLength is a RangeError"); + + growing.resize(1); + let outOfBounds = false; + try { + outOfBounds = fixedView.byteLength < 0; + } catch (e) { + outOfBounds = e instanceof TypeError; + } + + assert(outOfBounds, "a fixed view past a shrunk buffer is out of bounds"); + growing.resize(3); + assert(tracking.getUint8(1) == 0 && tracking.getUint8(2) == 0, "bytes a shrink cut off come back 0"); + + const cut = fixed.slice(1, 3); + assert(cut.byteLength == 2 && !cut.resizable, "slice copies a part"); + + const longer = growing.transfer(5); + assert(longer.byteLength == 5 && longer.resizable, "transfer to a new length keeps resizability"); + const shorter = longer.transferToFixedLength(2); + assert(shorter.byteLength == 2 && !shorter.resizable, "transferToFixedLength"); + + console.log("ALL DONE"); +} diff --git a/tests/dataview.ts b/tests/dataview.ts new file mode 100644 index 0000000..ff65acf --- /dev/null +++ b/tests/dataview.ts @@ -0,0 +1,84 @@ +// not own: the program goes on using a buffer after a DataView keeps it, which -mm=own refuses +// DataView: numbers of any width at any byte offset of an ArrayBuffer, big-endian unless asked for +// little-endian, as in JavaScript +function main() { + const buffer = new ArrayBuffer(16); + assert(buffer.byteLength == 16 && !buffer.resizable, "a fixed ArrayBuffer of 16 bytes"); + const view = new DataView(buffer); + assert(view.byteLength == 16 && view.byteOffset == 0, "the whole buffer"); + + view.setUint16(0, 0x1234); + assert(view.getUint8(0) == 0x12 && view.getUint8(1) == 0x34, "big-endian by default"); + view.setUint16(0, 0x1234, true); + assert(view.getUint8(0) == 0x34 && view.getUint8(1) == 0x12, "little-endian when asked"); + assert(view.getUint16(0, true) == 0x1234, "read back little-endian"); + + view.setInt8(2, -1); + assert(view.getInt8(2) == -1 && view.getUint8(2) == 255, "signed and unsigned bytes"); + view.setUint8(2, 300); + assert(view.getUint8(2) == 44, "a byte wraps"); + + view.setInt32(4, -2); + assert(view.getInt32(4) == -2, "Int32"); + assert(view.getUint32(4) == 4294967294, "the same bits as Uint32"); + view.setInt16(4, -300, true); + assert(view.getInt16(4, true) == -300, "Int16"); + + view.setFloat32(8, 1.5); + assert(view.getFloat32(8) == 1.5, "Float32"); + assert(view.getUint32(8) == 0x3FC00000, "Float32's bits, big-endian"); + view.setFloat32(8, 0.1); + assert(view.getFloat32(8) == Math.fround(0.1), "Float32 rounds as fround"); + + view.setFloat64(8, Math.PI, true); + assert(view.getFloat64(8, true) == Math.PI, "Float64"); + view.setFloat64(8, 2); + assert(view.getUint8(8) == 0x40 && view.getUint8(9) == 0, "Float64's bits, big-endian"); + + view.setFloat16(0, 1.5); + assert(view.getUint16(0) == 0x3E00, "Float16's bits"); + assert(view.getFloat16(0) == 1.5, "Float16"); + assert(Math.f16round(0.1) == 0.0999755859375, "Math.f16round"); + + view.setBigInt64(8, -5); + assert(view.getBigInt64(8) == -5, "BigInt64"); + assert(view.getUint8(15) == 0xFB, "BigInt64's low byte, big-endian"); + + // a view of part of the buffer + const part = new DataView(buffer, 4, 8); + assert(part.byteOffset == 4 && part.byteLength == 8, "offset and length"); + part.setUint8(0, 9); + assert(view.getUint8(4) == 9, "a write through it reaches the buffer"); + + let outside = false; + try { + part.getUint32(6); + } catch (e) { + outside = e instanceof RangeError; + } + + assert(outside, "past its end is a RangeError"); + + let badView = false; + try { + new DataView(buffer, 12, 8); + } catch (e) { + badView = e instanceof RangeError; + } + + assert(badView, "a view past the buffer's end is a RangeError"); + + // a detached buffer + const moved = buffer.transfer(); + assert(buffer.detached && moved.byteLength == 16, "transfer detaches"); + let detached = false; + try { + view.getUint8(0); + } catch (e) { + detached = e instanceof TypeError; + } + + assert(detached, "a detached buffer is a TypeError"); + + console.log("ALL DONE"); +} diff --git a/tests/dataview_keeps_buffer.ts b/tests/dataview_keeps_buffer.ts new file mode 100644 index 0000000..0cfb94a --- /dev/null +++ b/tests/dataview_keeps_buffer.ts @@ -0,0 +1,25 @@ +// A DataView keeps the buffer it is given (under -mm=own its caller gives the buffer up) and reaches it +// through `buffer` +function main() { + const view = new DataView(new ArrayBuffer(8), 2); + assert(view.byteOffset == 2 && view.byteLength == 6, "a view from byte 2"); + view.setUint16(0, 0x1234); + assert(view.getUint8(0) == 0x12 && view.getUint8(1) == 0x34, "big-endian"); + view.setFloat32(2, 0.5, true); + assert(view.getFloat32(2, true) == 0.5, "Float32, little-endian"); + let outside = false; + try { + view.setFloat64(0, 1); + } catch (e) { + outside = e instanceof RangeError; + } + + assert(outside, "8 bytes do not fit in 6"); + + const shared = new DataView(new SharedArrayBuffer(4, { maxByteLength: 8 })); + shared.setInt32(0, -7); + assert(shared.getInt32(0) == -7, "over a SharedArrayBuffer"); + assert(shared.byteLength == 4, "4 bytes"); + + console.log("ALL DONE"); +} diff --git a/tests/shared_array_buffer.ts b/tests/shared_array_buffer.ts new file mode 100644 index 0000000..19e1492 --- /dev/null +++ b/tests/shared_array_buffer.ts @@ -0,0 +1,48 @@ +// not own: the program goes on using a buffer after a DataView keeps it, which -mm=own refuses +// SharedArrayBuffer: bytes that threads share; a growable one grows up to its maxByteLength without +// moving its bytes, as in JavaScript +function main() { + const shared = new SharedArrayBuffer(4, { maxByteLength: 16 }); + assert(shared.byteLength == 4 && shared.growable && shared.maxByteLength == 16, "growable"); + + const view = new DataView(shared); + view.setInt32(0, 123456, true); + shared.grow(12); + assert(shared.byteLength == 12 && view.byteLength == 12, "grown, and the view follows"); + assert(view.getInt32(0, true) == 123456 && view.getInt32(8) == 0, "old bytes stay, new ones are 0"); + + let shrink = false; + try { + shared.grow(8); + } catch (e) { + shrink = e instanceof RangeError; + } + + assert(shrink, "it cannot shrink"); + + const fixed = new SharedArrayBuffer(2); + assert(!fixed.growable, "not growable without maxByteLength"); + let refused = false; + try { + fixed.grow(2); + } catch (e) { + refused = e instanceof TypeError; + } + + assert(refused, "a fixed one refuses grow"); + + const copy = shared.slice(0, 4); + assert(copy.byteLength == 4 && !copy.growable, "slice copies"); + new DataView(copy).setInt32(0, 7, true); + assert(view.getInt32(0, true) == 123456, "the copy shares nothing"); + + // another thread sees the same bytes + const handle = Thread.spawn((): int => { + view.setUint8(11, 42); + return 0; + }); + handle.join(); + assert(view.getUint8(11) == 42, "a write by another thread is seen"); + + console.log("ALL DONE"); +} From 339a9ee50c1ef0c47fdd4dfc0f463a458c40b77c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 17:34:46 +0000 Subject: [PATCH 3/6] DisposableStack, SuppressedError and ReferenceError DisposableStack disposes its resources last added first, by `using` or dispose(), with use, adopt, defer, move and disposed. A resource that throws does not stop the rest; two failures make a SuppressedError holding both. A disposed stack takes nothing more (ReferenceError). [Symbol.dispose]() is the method named dispose here, so the class has dispose() alone. Under -mm=own, defer() and adopt() of a copied value compile; use() of an object, which keeps it and gives it back, does not. Co-Authored-By: Claude Opus 5.5 --- src/core/core.d.ts | 12 ++++ src/core/core.ts | 14 +++++ src/generics/lib.generics.ts | 83 ++++++++++++++++++++++++++ tests/disposable_stack.ts | 100 ++++++++++++++++++++++++++++++++ tests/disposable_stack_defer.ts | 23 ++++++++ 5 files changed, 232 insertions(+) create mode 100644 tests/disposable_stack.ts create mode 100644 tests/disposable_stack_defer.ts diff --git a/src/core/core.d.ts b/src/core/core.d.ts index 96054a2..257b6f6 100644 --- a/src/core/core.d.ts +++ b/src/core/core.d.ts @@ -21,6 +21,18 @@ declare class SyntaxError extends Error { constructor(message?: string, filename?: string, line?: int); } +@owned +declare class ReferenceError extends Error { + constructor(message?: string, filename?: string, line?: int); +} + +@owned +declare class SuppressedError extends Error { + public error: any; + public suppressed: any; + constructor(error: any, suppressed: any, message?: string); +} + @owned declare class ErrorEvent { public message: string; diff --git a/src/core/core.ts b/src/core/core.ts index 247a5a4..5206484 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -23,6 +23,20 @@ export class SyntaxError extends Error { } } +export class ReferenceError extends Error { + public constructor(message?: string, filename?: string, line?: int) { + super(message, filename, line); + } +} + +// An error thrown while another was already on its way out, as DisposableStack's dispose() throws +// when more than one resource fails: `error` is the newer, `suppressed` the one it hid. +export class SuppressedError extends Error { + public constructor(public error: any, public suppressed: any, message?: string) { + super(message); + } +} + // What a worker threw, as the thread that made it is told (MDN's ErrorEvent; `filename`, `lineno` // and `colno` are not here). Made from the message alone: the thrown object was the worker's. export class ErrorEvent { diff --git a/src/generics/lib.generics.ts b/src/generics/lib.generics.ts index e2098d6..c56cf13 100644 --- a/src/generics/lib.generics.ts +++ b/src/generics/lib.generics.ts @@ -4005,3 +4005,86 @@ class WeakSet { return this.keys.delete(value); } } + +// Resources disposed together, last added first, as in JavaScript: by `using stack = new +// DisposableStack()` at the end of the block, or by dispose(). A resource that throws does not stop +// the rest; when more than one throws, dispose() throws a SuppressedError that holds the newest +// error and the one it hid. Once disposed, use, adopt, defer and move throw a ReferenceError. +// X only keeps the class out of a program that does not use it (see sleep). Under -mm=own use() of +// an object is refused, as it both keeps the object and gives it back; defer(), and adopt() of a +// value that is copied, are there. +class DisposableStack { + // what disposing each resource calls, in the order they were added: under -mm=own defer() keeps + // its callback here as it is + private resources: (() => void)[] = []; + private isDisposed = false; + + public get disposed(): boolean { + return this.isDisposed; + } + + // `value`, to be disposed with the stack + public use(value: T): T { + this.expectNotDisposed(); + this.resources.push(() => value[Symbol.dispose]()); + return value; + } + + // `value`, given to onDispose when the stack is disposed: for what has no [Symbol.dispose]() + public adopt(value: T, onDispose: (value: T) => void): T { + this.expectNotDisposed(); + this.resources.push(() => onDispose(value)); + return value; + } + + // onDispose, called when the stack is disposed; the stack keeps it + @keeps("onDispose") + public defer(onDispose: () => void): void { + this.expectNotDisposed(); + this.resources.push(onDispose); + } + + // a new stack with all of this one's resources; this one is left disposed, with none + public move(): DisposableStack { + this.expectNotDisposed(); + const moved = new DisposableStack(); + moved.resources = this.resources; + this.resources = []; + this.isDisposed = true; + return moved; + } + + // also [Symbol.dispose](), which is the method named `dispose` here: `using` calls this + public dispose(): void { + if (this.isDisposed) { + return; + } + + this.isDisposed = true; + let failed = false; + let failure: any; + while (this.resources.length > 0) { + const dispose = this.resources.pop(); + try { + dispose(); + } catch (e) { + if (failed) { + failure = new SuppressedError(e, failure, "An error was suppressed during disposal"); + } else { + failure = e; + failed = true; + } + } + } + + if (failed) { + throw failure; + } + } + + private expectNotDisposed(): void { + if (this.isDisposed) { + throw new ReferenceError("DisposableStack already disposed"); + } + } +} diff --git a/tests/disposable_stack.ts b/tests/disposable_stack.ts new file mode 100644 index 0000000..6e3b416 --- /dev/null +++ b/tests/disposable_stack.ts @@ -0,0 +1,100 @@ +// not own: use() and adopt() keep a value and give it back, which -mm=own refuses +// DisposableStack: resources disposed together, last added first, as in JavaScript +let trail = ""; + +class Resource { + constructor(public name: string) { + } + + [Symbol.dispose]() { + trail += this.name; + } +} + +class Failing { + constructor(public name: string) { + } + + [Symbol.dispose]() { + trail += this.name; + throw new TypeError(this.name); + } +} + +function main() { + // by `using`, at the end of the block + { + using stack = new DisposableStack(); + const a = stack.use(new Resource("a")); + assert(a.name == "a", "use gives the value back"); + stack.adopt(7, (n: int) => { trail += n; }); + stack.defer(() => { trail += "c"; }); + assert(!stack.disposed, "not yet disposed"); + } + + assert(trail == "c7a", "last added first"); + + // dispose() once: a second call does nothing + trail = ""; + const stack = new DisposableStack(); + stack.use(new Resource("x")); + stack.dispose(); + stack.dispose(); + assert(trail == "x" && stack.disposed, "disposed once"); + + let refused = false; + try { + stack.defer(() => { }); + } catch (e) { + refused = e instanceof ReferenceError; + } + + assert(refused, "a disposed stack takes nothing more"); + + // move() hands the resources on + trail = ""; + const first = new DisposableStack(); + first.use(new Resource("m")); + const second = first.move(); + assert(first.disposed && !second.disposed, "move leaves the first disposed"); + first.dispose(); + assert(trail == "", "the first has nothing left"); + second.dispose(); + assert(trail == "m", "the second disposes them"); + + // a failure does not stop the rest; one failure is thrown as it is + trail = ""; + const one = new DisposableStack(); + one.use(new Resource("a")); + one.use(new Failing("F")); + one.use(new Resource("b")); + let single = false; + try { + one.dispose(); + } catch (e) { + single = e instanceof TypeError; + } + + assert(single && trail == "bFa", "one failure, thrown as it is, and the rest disposed"); + + // two failures: a SuppressedError of the newer, hiding the older + trail = ""; + const two = new DisposableStack(); + two.use(new Failing("1")); + two.use(new Failing("2")); + let suppressed = false; + try { + two.dispose(); + } catch (e) { + if (e instanceof SuppressedError) { + const newer = e.error; + const older = e.suppressed; + suppressed = newer instanceof TypeError && older instanceof TypeError + && (newer).message == "1" && (older).message == "2"; + } + } + + assert(suppressed && trail == "21", "a SuppressedError holds both"); + + console.log("ALL DONE"); +} diff --git a/tests/disposable_stack_defer.ts b/tests/disposable_stack_defer.ts new file mode 100644 index 0000000..0984f37 --- /dev/null +++ b/tests/disposable_stack_defer.ts @@ -0,0 +1,23 @@ +// DisposableStack.defer and adopt, which -mm=own takes too: callbacks run when the stack is disposed, +// last added first +let trail = ""; + +function main() { + { + using stack = new DisposableStack(); + stack.defer(() => { trail += "1"; }); + stack.defer(() => { trail += "2"; }); + const n = stack.adopt(4, (v: int) => { trail += v; }); + assert(n == 4, "adopt gives the value back"); + } + + assert(trail == "421", "at the end of the block, last first"); + + const stack = new DisposableStack(); + stack.defer(() => { trail += "3"; }); + const moved = stack.move(); + moved.dispose(); + assert(trail == "4213" && stack.disposed && moved.disposed, "move, then dispose"); + + console.log("ALL DONE"); +} From f79f85c37407c5f73e44da45f77e05e2986dd92a Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 17:37:03 +0000 Subject: [PATCH 4/6] FinalizationRegistry on the compiler's WeakRef; tests can say "// not rc" FinalizationRegistry calls its callback with the held value of each target that has gone: freed by the collector (gc), given up by its owner (own), or never (none). There is no event loop, and the collector cannot run TypeScript mid-allocation, so callbacks run at the registry's next use: register(), unregister() or cleanupSome() (the TC39 proposal's). Targets and unregister tokens are held weakly. No runtime change: it is built on WeakRef, so it has WeakRef's models, gc, own and none. tests.ps1 and tests.sh skip a test whose first line starts with "// not rc" under -mm=rc, as they skip "// not own" under -mm=own. Co-Authored-By: Claude Opus 5.5 --- src/generics/lib.generics.ts | 98 +++++++++++++++++++++++++++ tests.ps1 | 15 +++- tests.sh | 15 +++- tests/finalization_registry.ts | 60 ++++++++++++++++ tests/finalization_registry_models.ts | 46 +++++++++++++ 5 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 tests/finalization_registry.ts create mode 100644 tests/finalization_registry_models.ts diff --git a/src/generics/lib.generics.ts b/src/generics/lib.generics.ts index c56cf13..44a19cb 100644 --- a/src/generics/lib.generics.ts +++ b/src/generics/lib.generics.ts @@ -4006,6 +4006,104 @@ class WeakSet { } } +// what a FinalizationRegistry keeps for each registration, beside its held value: the target and the +// unregister token, both weakly +class FinalizationEntry { + constructor(public target: WeakRef, public token: WeakRef | null) { + } +} + +// Calls cleanupCallback with the held value of each registered target that has gone, as in +// JavaScript, through the compiler's WeakRef: under gc, own and none, not rc. A target goes when the +// collector frees it (gc), when its owner gives it up (own), or never (none, which frees nothing). +// There is no event loop to run the callbacks on their own, and the collector cannot run TypeScript +// in the middle of an allocation, so they run when the registry is next used: by register(), +// unregister() or cleanupSome(), and never during one of the program's own statements. JavaScript +// promises no more: a callback may run late, or not at all. +// H is the held value's type and T the targets' class; the unregister token is a T too, often the +// target itself, and is held weakly, as the target is. +class FinalizationRegistry { + // entries[i] is registration i, heldValues[i] its held value: apart, so that under -mm=own a + // held value is moved out to its callback whole, not lent from an entry + private entries: FinalizationEntry[] = []; + private heldValues: H[] = []; + + constructor(private cleanupCallback: (heldValue: H) => void) { + } + + public register(target: T, heldValue: H, unregisterToken?: T): void { + this.cleanupSome(); + const token = unregisterToken != undefined ? new WeakRef(unregisterToken) : null; + this.entries.push(new FinalizationEntry(new WeakRef(target), token)); + this.heldValues.push(heldValue); + } + + // forgets every registration made with this token, so its callback never runs; true if any + public unregister(unregisterToken: T): boolean { + this.cleanupSome(); + let removed = false; + let i = 0; + while (i < this.entries.length) { + if (this.hasToken(i, unregisterToken)) { + this.removeAt(i); + removed = true; + } else { + i++; + } + } + + return removed; + } + + // Calls the callback, or `callback` when given, for each target that has gone (from the TC39 + // proposal; not in every engine). The gone values are taken out first and called after, so a + // callback may register again. + public cleanupSome(callback?: (heldValue: H) => void): void { + const gone: H[] = []; + let i = 0; + while (i < this.entries.length) { + if (this.isGone(i)) { + gone.push(this.removeAt(i)); + } else { + i++; + } + } + + if (callback) { + while (gone.length > 0) callback(gone.shift()); + } else { + while (gone.length > 0) this.cleanupCallback(gone.shift()); + } + } + + // in a method of its own, so that no pointer to a live target is left in the caller's frame, + // where the collector's conservative scan of the stack would find it and keep the target + private isGone(index: int): boolean { + return this.entries[index].target.deref() == undefined; + } + + // whether the entry at `index` was made with this token; a method of its own, so that under + // -mm=own the entry is not borrowed past the test + private hasToken(index: int, unregisterToken: T): boolean { + const token = this.entries[index].token; + return token != null && token.deref() === unregisterToken; + } + + // Registration `index` taken out, its held value given back: each array's element exchanged with + // its last and popped, which moves it (under -mm=own a copy would have two owners). The order of + // the rest does not matter. + private removeAt(index: int): H { + const last = this.entries.length - 1; + if (index != last) { + [this.entries[index], this.entries[last]] = [this.entries[last], this.entries[index]]; + [this.heldValues[index], this.heldValues[last]] = [this.heldValues[last], this.heldValues[index]]; + } + + this.entries.pop(); + return this.heldValues.pop(); + } +} + // Resources disposed together, last added first, as in JavaScript: by `using stack = new // DisposableStack()` at the end of the block, or by dispose(). A resource that throws does not stop // the rest; when more than one throws, dispose() throws a SuppressedError that holds the newest diff --git a/tests.ps1 b/tests.ps1 index 07ca111..1f444b2 100644 --- a/tests.ps1 +++ b/tests.ps1 @@ -2,7 +2,8 @@ # .\tests.ps1 the compiler's default memory model (gc) # .\tests.ps1 -Model rc -mm=rc, against the default library built for it; also $Env:TSLANG_MM # A test whose first line starts with "// gc only" is skipped under any other model, and one whose -# first line starts with "// not own" under -mm=own. One whose first line starts with "// linux only" +# first line starts with "// not own" under -mm=own, and one whose first line starts with "// not rc" +# under -mm=rc. One whose first line starts with "// linux only" # is skipped here, under every model, and runs in tests.sh. param([string]$Model = $Env:TSLANG_MM) @@ -155,6 +156,12 @@ function Test-NotOwn([string]$path) { return (Get-Content $path -TotalCount 1) -match '^// not own' } +# A test of what -mm=rc does not have says so on its first line ("// not rc: ..."), e.g. WeakRef, +# which the compiler gives under gc, own and none. +function Test-NotRc([string]$path) { + return (Get-Content $path -TotalCount 1) -match '^// not rc' +} + # A test that calls what only Linux provides says so on its first line ("// linux only: ..."). function Test-LinuxOnly([string]$path) { return (Get-Content $path -TotalCount 1) -match '^// linux only' @@ -187,6 +194,12 @@ function Tests([string]$config, [string]$mode) { return } + if ($Model -eq "rc" -and (Test-NotRc $_.FullName)) { + $skipped++ + Write-Host "Skipped (not rc)" -ForegroundColor Yellow + return + } + if (Test-LinuxOnly $_.FullName) { $skipped++ Write-Host "Skipped (linux only)" -ForegroundColor Yellow diff --git a/tests.sh b/tests.sh index c2179e8..cefcae8 100755 --- a/tests.sh +++ b/tests.sh @@ -3,7 +3,8 @@ # ./tests.sh the compiler's default memory model (gc) # ./tests.sh rc -mm=rc, against the default library built for it; also TSLANG_MM=rc # A test whose first line starts with "// gc only" is skipped under any other model, and one whose -# first line starts with "// not own" under -mm=own. +# first line starts with "// not own" under -mm=own, and one whose first line starts with "// not rc" +# under -mm=rc. MODEL="${1:-$TSLANG_MM}" # The library paths the environment gives when the script starts. One it does not give is worked @@ -123,6 +124,12 @@ function not_own() { head -n 1 "$1" | grep -q '^// not own' } +# A test of what -mm=rc does not have says so on its first line ("// not rc: ..."), e.g. WeakRef, +# which the compiler gives under gc, own and none. +function not_rc() { + head -n 1 "$1" | grep -q '^// not rc' +} + function tests() { config="$1" mode="$2" @@ -150,6 +157,12 @@ function tests() { continue fi + if [ "$MODEL" = "rc" ] && not_rc "$file"; then + skipped=$((skipped + 1)) + printf "\e[33mSkipped\e[0m (not rc)\n" + continue + fi + start=$(date +%s.%N) test_script "$config" "$mode" "$(basename "$file" .ts)" result=$? diff --git a/tests/finalization_registry.ts b/tests/finalization_registry.ts new file mode 100644 index 0000000..920e738 --- /dev/null +++ b/tests/finalization_registry.ts @@ -0,0 +1,60 @@ +// gc only: this calls GC_gcollect() itself, which the compiler rejects under any other model. +// FinalizationRegistry calls its callback with the held value of a target the collector has freed, +// when the registry is next used. +class Foo { + constructor(public value: int) { + } +} + +let cleaned = ""; + +// in a function of its own, so no pointer to the object stays in main's frame for the collector's +// conservative stack scan to find (see weakref_basic.ts) +function registerDropped(registry: FinalizationRegistry, held: string, withToken: boolean) { + const obj = new Foo(1); + if (withToken) { + registry.register(obj, held, obj); + } else { + registry.register(obj, held); + } +} + +function clearStack(depth: int): int { + const a = depth; + const b = depth + 1; + const c = depth + 2; + const d = depth + 3; + return depth > 0 ? clearStack(depth - 1) + a + b + c + d : 0; +} + +function main() { + const registry = new FinalizationRegistry((held: string) => { cleaned += held; }); + registerDropped(registry, "a", false); + registerDropped(registry, "b", true); + + const kept = new Foo(2); + registry.register(kept, "k", kept); + + // nothing has collected yet + registry.cleanupSome(); + assert(cleaned == "", "no callback before a collection"); + + clearStack(200); + GC_gcollect(); + GC_gcollect(); + + // the callbacks run when the registry is next used, never on their own + assert(cleaned == "", "no callback until the registry is used"); + registry.cleanupSome(); + assert(cleaned.length == 2 && cleaned.indexOf("a") >= 0 && cleaned.indexOf("b") >= 0, + "a callback for each freed target, once"); + registry.cleanupSome(); + assert(cleaned.length == 2, "not again"); + + // a held object is not freed, and unregister forgets it + assert(registry.unregister(kept), "unregister finds the token"); + assert(!registry.unregister(kept), "and has nothing more for it"); + assert(kept.value == 2); + + console.log("ALL DONE"); +} diff --git a/tests/finalization_registry_models.ts b/tests/finalization_registry_models.ts new file mode 100644 index 0000000..90ccbbc --- /dev/null +++ b/tests/finalization_registry_models.ts @@ -0,0 +1,46 @@ +// not rc: FinalizationRegistry is built on WeakRef, which the compiler gives under gc, own and none. +// What every one of those models does alike, and under -mm=own a callback for a target its owner gave +// up, at the registry's next use. +class Foo { + constructor(public value: int) { + } +} + +let cleaned = ""; + +// -mm=own frees an object when its owner gives it up: only there is a dropped target certainly gone +function freesAtOnce() { + return Shared.count(new Shared(0)) >= 0; +} + +function registerDropped(registry: FinalizationRegistry, held: string) { + const obj = new Foo(1); + registry.register(obj, held); +} + +function main() { + const registry = new FinalizationRegistry((held: string) => { cleaned += held; }); + + const kept = new Foo(2); + const other = new Foo(3); + registry.register(kept, "k", kept); + registry.register(other, "o", kept); + registry.cleanupSome(); + assert(cleaned == "", "no callback for a live target"); + + // both registrations made with the token go + assert(registry.unregister(kept), "unregister finds the token"); + assert(!registry.unregister(kept), "and has nothing more for it"); + assert(!registry.unregister(other), "a target that was not a token unregisters nothing"); + + registerDropped(registry, "d"); + let given = ""; + registry.cleanupSome((held: string) => { given += held; }); + if (freesAtOnce()) { + assert(given == "d", "under own, the dropped target's value, to the callback given"); + assert(cleaned == "", "not to the registry's own"); + } + + assert(kept.value == 2 && other.value == 3); + console.log("ALL DONE"); +} From 5b57ed9aabe75cda8ae3cc8e155dd9f41fb0613c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 17:47:30 +0000 Subject: [PATCH 5/6] Temporal: Duration, Instant, PlainDate, PlainTime, PlainDateTime, Now The ISO 8601 calendar's part of Temporal, with from (ISO 8601 text), compare, add, subtract, until, since, equals, toString and toJSON, and _with for with. Spans are kept as seconds plus nanoseconds, exact past the 104 days a number of nanoseconds holds. Not here: ZonedDateTime, PlainYearMonth, PlainMonthDay, time zones other than UTC and the present system offset, other calendars, and options bags. Instant.epochNanoseconds is a 64-bit bigint (years 1677-2262). README lists the classes added on this branch. Co-Authored-By: Claude Opus 5.5 --- README.md | 43 +- src/lib.d.ts | 166 +++++ src/lib.ts | 1006 ++++++++++++++++++++++++++++ tests/temporal_duration_instant.ts | 77 +++ tests/temporal_plain.ts | 69 ++ 5 files changed, 1357 insertions(+), 4 deletions(-) create mode 100644 tests/temporal_duration_instant.ts create mode 100644 tests/temporal_plain.ts diff --git a/README.md b/README.md index c5b8f76..d93f3f8 100644 --- a/README.md +++ b/README.md @@ -127,8 +127,8 @@ $Env:TSLANG_ARCH="x86"; .\tests.ps1 # x86, release/compile and debug/compile onl ``` The default memory model is `gc`. A test whose first line starts with `// gc only` is -skipped under any other model, one starting `// not own` under `-mm=own`, and one starting -`// linux only` by `tests.ps1` (it runs in `tests.sh`). A test that should run under every +skipped under any other model, one starting `// not own` under `-mm=own`, one starting `// not rc` +under `-mm=rc`, and one starting `// linux only` by `tests.ps1` (it runs in `tests.sh`). A test that should run under every model but has a part that can't, branches on `__MEMORY_MODEL__` instead. A test's functions are global symbols, so on Linux one named like a libc function (`read`, @@ -169,8 +169,30 @@ Globals (`src/lib.ts`): `replace`, `replaceAll`, `search`, `slice`, `split`, `startsWith`, `substring`, `toLocaleLowerCase`, `toLocaleUpperCase`, `toLowerCase`, `toUpperCase`, `toWellFormed`, `trim`, `trimStart`, `trimEnd` -- `Math` (static) -- `ArrayBuffer` +- `Math` (static), with `f16round` +- `ArrayBuffer`: resizable only when made with `{ maxByteLength }`; `byteLength`, `resize`, `slice`, + `transfer(newByteLength?)`, `transferToFixedLength`, `detached` +- `SharedArrayBuffer`: `byteLength`, `growable`, `maxByteLength`, `grow`, `slice`. A growable one + takes all `maxByteLength` bytes up front, so `grow` never moves them under another thread. A + typed array cannot view one, so `Atomics` cannot reach its bytes. +- `DataView` over an `ArrayBuffer` or a `SharedArrayBuffer`: `get`/`set` of `Int8`, `Uint8`, + `Int16`, `Uint16`, `Int32`, `Uint32`, `Float16`, `Float32`, `Float64`, `BigInt64`, `BigUint64`, + big-endian unless `littleEndian` is `true`. Made without a length over a resizable buffer, it + follows the buffer's length. A `bigint` is 64 bits and signed here, so `getBigUint64` of 2^63 or + more comes out negative. Under `-mm=own` the view keeps the buffer it is given (reach it through + `buffer`). +- `Error`, `RangeError`, `TypeError`, `SyntaxError`, `ReferenceError`, and `SuppressedError` + (`error`, `suppressed`) +- `Temporal`, the ISO 8601 calendar's part: `Duration`, `Instant`, `PlainDate`, `PlainTime`, + `PlainDateTime` and `Now` (`instant`, `plainDateTimeISO`, `plainDateISO`, `plainTimeISO`), with + `from` (ISO 8601 text), `compare`, `add`, `subtract`, `until`, `since`, `equals`, `toString` and + `toJSON`, and `_with` for `with`, a keyword here. Not here: `ZonedDateTime`, `PlainYearMonth`, + `PlainMonthDay`, time zones other than UTC and the system's present offset, other calendars, and + the options bags: `until` and `since` give their default largest unit, and an overflowing day is + constrained to the month's last. Without a date to count from, a `Duration` with years, months or + weeks cannot be added, compared or totalled (a `RangeError`), and a day is 24 hours. + `Instant.epochNanoseconds` is a 64-bit `bigint`, so it holds the years 1677 to 2262. `Now` reads + the clock to the millisecond. - `Headers`, `Response`, `fetch` — see [docs/fetch.md](docs/fetch.md) - `JSON.parse`, and the `JsonValue` it gives. There are no objects whose fields are found at run time, so a value is read through accessors: `kind`, `isNull`, `asBoolean`, `asNumber`, `asString`, @@ -210,6 +232,9 @@ Generics (`src/generics/lib.generics.ts`): `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array`, `Float32Array`, `Float64Array`). A typed array is made from an array of its elements (`new Uint8Array([1, 2, 3])`) or a length (`new Uint8Array(4096)`, each element 0) +- `Uint8ClampedArray`, which clamps a number written to it into 0..255 and rounds half to even, and + `Float16Array`, of IEEE 754 binary16 elements. Both have `TypedArray`'s methods, with a `number` + element. - `T[]` and `Array` also have `flatMap`, `toSpliced` (`splice` on a copy), and `T[][]` has `flat()`, which takes away one level only: a depth would make the result's type depend on a number - `Map`, and `Map.groupBy(items, keySelector)`, a `Map` of each key to its items, the keys in @@ -289,6 +314,16 @@ Generics (`src/generics/lib.generics.ts`): - `WeakMap`: `get`, `set`, `has`, `delete`. `WeakSet`: `add`, `has`, `delete`. Keys are objects, compared by identity. `-mm=gc` only, as `WeakRef` is. A value is held strongly, so a value that refers to its own key keeps that key alive. +- `FinalizationRegistry`: `register(target, heldValue, unregisterToken?)`, `unregister`, and + `cleanupSome(callback?)` from the TC39 proposal. `H` is the held value's type, `T` the targets' + class (an unregister token is a `T` too). Built on `WeakRef`, so under `-mm=gc`, `own` and `none`, + not `rc`. There is no event loop, so the callback runs at the registry's next use (`register`, + `unregister`, `cleanupSome`), for each target freed by then: under `gc` once the collector has run, + under `own` once its owner has given it up, under `none` never. +- `DisposableStack`: `use`, `adopt`, `defer`, `move`, `dispose`, `disposed`; disposed by `using` + too. Resources go last added first, and one that throws does not stop the rest; two failures make + a `SuppressedError`. Under `-mm=own`, `use` of an object is refused (it keeps the object and gives + it back); `defer` and `adopt` of a copied value work. - `Promise`: `resolve`, `reject`, `all`, `allSettled`, `race`, `any`. The compiler takes `Promise` as `T` (an async function returns its value and `await` gives it back), so these work on values that have already settled and a rejection is a thrown exception. diff --git a/src/lib.d.ts b/src/lib.d.ts index 7520001..2f35271 100644 --- a/src/lib.d.ts +++ b/src/lib.d.ts @@ -879,3 +879,169 @@ declare namespace console { function error(...data: string[]): void; } + +// Temporal's ISO 8601 part: see lib.ts. Each class lists its members in lib.ts's order: a program +// calls them by their place in the class's table. +declare namespace Temporal { + @final + @owned + class Duration { + private fields: number[]; + + constructor(years?: number, months?: number, weeks?: number, days?: number, hours?: number, minutes?: number, + seconds?: number, milliseconds?: number, microseconds?: number, nanoseconds?: number); + + static from(text: string): Duration; + static compare(one: Duration, two: Duration): int; + get years(): number; + get months(): number; + get weeks(): number; + get days(): number; + get hours(): number; + get minutes(): number; + get seconds(): number; + get milliseconds(): number; + get microseconds(): number; + get nanoseconds(): number; + get sign(): int; + get blank(): boolean; + negated(): Duration; + abs(): Duration; + add(other: Duration): Duration; + subtract(other: Duration): Duration; + total(unit: string): number; + toString(): string; + toJSON(): string; + __field(index: int): number; + } + + @final + @owned + class Instant { + private epochSeconds: number; + private nanos: number; + + constructor(epochNanoseconds: bigint); + + static fromEpochMilliseconds(epochMilliseconds: number): Instant; + static fromEpochNanoseconds(epochNanoseconds: bigint): Instant; + static from(text: string): Instant; + static compare(one: Instant, two: Instant): int; + get epochMilliseconds(): number; + get epochNanoseconds(): bigint; + add(duration: Duration): Instant; + subtract(duration: Duration): Instant; + until(other: Instant): Duration; + since(other: Instant): Duration; + equals(other: Instant): boolean; + toString(): string; + toJSON(): string; + } + + @final + @owned + class PlainDate { + private isoYear: int; + private isoMonth: int; + private isoDay: int; + + constructor(year: int, month: int, day: int); + + static from(text: string): PlainDate; + static compare(one: PlainDate, two: PlainDate): int; + get year(): int; + get month(): int; + get day(): int; + get monthCode(): string; + get calendarId(): string; + get dayOfWeek(): int; + get dayOfYear(): int; + get daysInMonth(): int; + get daysInYear(): int; + get daysInWeek(): int; + get monthsInYear(): int; + get inLeapYear(): boolean; + add(duration: Duration): PlainDate; + subtract(duration: Duration): PlainDate; + until(other: PlainDate): Duration; + since(other: PlainDate): Duration; + _with(fields: { year?: int, month?: int, day?: int }): PlainDate; + equals(other: PlainDate): boolean; + toPlainDateTime(time?: PlainTime): PlainDateTime; + toString(): string; + toJSON(): string; + __epochDays(): int; + } + + @final + @owned + class PlainTime { + private parts: int[]; + + constructor(hour?: int, minute?: int, second?: int, millisecond?: int, microsecond?: int, nanosecond?: int); + + static from(text: string): PlainTime; + static compare(one: PlainTime, two: PlainTime): int; + get hour(): int; + get minute(): int; + get second(): int; + get millisecond(): int; + get microsecond(): int; + get nanosecond(): int; + add(duration: Duration): PlainTime; + subtract(duration: Duration): PlainTime; + until(other: PlainTime): Duration; + since(other: PlainTime): Duration; + _with(fields: { hour?: int, minute?: int, second?: int, millisecond?: int, microsecond?: int, nanosecond?: int }): PlainTime; + equals(other: PlainTime): boolean; + toString(): string; + toJSON(): string; + } + + @final + @owned + class PlainDateTime { + private date: PlainDate; + private time: PlainTime; + + constructor(year: int, month: int, day: int, hour?: int, minute?: int, second?: int, millisecond?: int, + microsecond?: int, nanosecond?: int); + + static from(text: string): PlainDateTime; + static compare(one: PlainDateTime, two: PlainDateTime): int; + get year(): int; + get month(): int; + get day(): int; + get hour(): int; + get minute(): int; + get second(): int; + get millisecond(): int; + get microsecond(): int; + get nanosecond(): int; + get monthCode(): string; + get calendarId(): string; + get dayOfWeek(): int; + get dayOfYear(): int; + get daysInMonth(): int; + get daysInYear(): int; + get inLeapYear(): boolean; + add(duration: Duration): PlainDateTime; + subtract(duration: Duration): PlainDateTime; + until(other: PlainDateTime): Duration; + since(other: PlainDateTime): Duration; + _with(fields: { year?: int, month?: int, day?: int, hour?: int, minute?: int, second?: int, + millisecond?: int, microsecond?: int, nanosecond?: int }): PlainDateTime; + equals(other: PlainDateTime): boolean; + toPlainDate(): PlainDate; + toPlainTime(): PlainTime; + toString(): string; + toJSON(): string; + } + + namespace Now { + function instant(): Temporal.Instant; + function plainDateTimeISO(): Temporal.PlainDateTime; + function plainDateISO(): Temporal.PlainDate; + function plainTimeISO(): Temporal.PlainTime; + } +} diff --git a/src/lib.ts b/src/lib.ts index 8114c1f..ace95c9 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -3541,3 +3541,1009 @@ export static class console { stdio_write(fileNo, data, data.length); } } + +// Temporal, the ISO 8601 calendar's part of it: Duration, Instant, PlainDate, PlainTime, +// PlainDateTime and Now. Not here: ZonedDateTime, PlainYearMonth, PlainMonthDay, time zones other +// than UTC and the system's present offset, other calendars, and the options bags (largestUnit, +// smallestUnit, rounding, overflow). Where JavaScript takes options the default is used, and an +// overflowing day is constrained to the month's last. Instant.epochNanoseconds is a 64-bit bigint, so +// an Instant is between the years 1677 and 2262 when it is read that way. +// In each class the members lib.d.ts declares come first, in its order: a program calls them by +// their place in the class's table. +export namespace Temporal { + const NS_PER_SECOND = 1000000000; + const SECONDS_PER_DAY = 86400; + + // the units, largest first, as Duration's fields are + const YEARS = 0; + const MONTHS = 1; + const WEEKS = 2; + const DAYS = 3; + const HOURS = 4; + const MINUTES = 5; + const SECONDS = 6; + + function isLeapYear(year: int): boolean { + return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + } + + function daysInMonthOf(year: int, month: int): int { + if (month == 2) return isLeapYear(year) ? 29 : 28; + if (month == 4 || month == 6 || month == 9 || month == 11) return 30; + return 31; + } + + // the days from 1970-01-01 to the date (H. Hinnant's days_from_civil) + function epochDays(year: int, month: int, day: int): int { + const y = month <= 2 ? year - 1 : year; + const era = Math.floor(y / 400); + const yoe = y - era * 400; + const mp = (month + 9) % 12; + const doy = Math.floor((153 * mp + 2) / 5) + day - 1; + const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy; + return (era * 146097 + doe - 719468); + } + + // the date that many days from 1970-01-01 (civil_from_days) + function dateOfEpochDays(days: int): PlainDate { + const z = days + 719468; + const era = Math.floor(z / 146097); + const doe = z - era * 146097; + const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365); + const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100)); + const mp = Math.floor((5 * doy + 2) / 153); + const day = doy - Math.floor((153 * mp + 2) / 5) + 1; + const month = mp < 10 ? mp + 3 : mp - 9; + const year = yoe + era * 400 + (month <= 2 ? 1 : 0); + return new PlainDate(year, month, day); + } + + function pad(value: number, width: int): string { + let text = "" + value; + while (text.length < width) text = "0" + text; + return text; + } + + function yearText(year: int): string { + if (year >= 0 && year <= 9999) return pad(year, 4); + return (year < 0 ? "-" : "+") + pad(Math.abs(year), 6); + } + + // the nine digits of a fraction of a second, its trailing zeros gone; "" for none + function fractionText(nanoseconds: number): string { + if (nanoseconds == 0) return ""; + let text = pad(nanoseconds, 9); + while (text.endsWith("0")) text = text.substring(0, text.length - 1); + return "." + text; + } + + function timeText(hour: int, minute: int, second: int, nanoseconds: number): string { + return pad(hour, 2) + ":" + pad(minute, 2) + ":" + pad(second, 2) + fractionText(nanoseconds); + } + + function invalid(what: string): RangeError { + return new RangeError("Invalid " + what); + } + + // An ISO 8601 text, read one part at a time: each read throws a RangeError for what it cannot + // read. `at` is where the next part starts. + class IsoReader { + public at = 0; + + constructor(public text: string) { + } + + public get done(): boolean { + return this.at >= this.text.length; + } + + public peek(): int { + return this.at < this.text.length ? this.text.charCodeAt(this.at) : -1; + } + + public take(code: int): boolean { + if (this.peek() == code) { + this.at++; + return true; + } + + return false; + } + + public digits(count: int): int { + let value = 0; + for (let i = 0; i < count; i++) { + const c = this.peek(); + if (c < 48 || c > 57) throw invalid("ISO 8601 string: " + this.text); + value = value * 10 + (c - 48); + this.at++; + } + + return value; + } + + // YYYY-MM-DD, or ±YYYYYY-MM-DD + public date(): int[] { + let year: int; + if (this.peek() == 43 || this.peek() == 45) { + const negative = this.peek() == 45; + this.at++; + year = this.digits(6); + if (negative) year = -year; + } else { + year = this.digits(4); + } + + if (!this.take(45)) throw invalid("ISO 8601 date: " + this.text); + const month = this.digits(2); + if (!this.take(45)) throw invalid("ISO 8601 date: " + this.text); + const day = this.digits(2); + return [year, month, day]; + } + + // HH:MM[:SS[.fffffffff]]: hour, minute, second and the fraction in nanoseconds + public time(): int[] { + const hour = this.digits(2); + if (!this.take(58)) throw invalid("ISO 8601 time: " + this.text); + const minute = this.digits(2); + let second = 0; + let fraction = 0; + if (this.take(58)) { + second = this.digits(2); + if (this.take(46) || this.take(44)) { + let count = 0; + while (count < 9 && this.peek() >= 48 && this.peek() <= 57) { + fraction = fraction * 10 + (this.peek() - 48); + this.at++; + count++; + } + + if (count == 0) throw invalid("ISO 8601 time: " + this.text); + for (; count < 9; count++) fraction = fraction * 10; + } + } + + return [hour, minute, second, fraction]; + } + + // the date, then "T" or a space and the time when there is one + public dateTime(): int[] { + const date = this.date(); + let time = [0, 0, 0, 0]; + if (this.take(84) || this.take(116) || this.take(32)) { + time = this.time(); + } + + return [date[0], date[1], date[2], time[0], time[1], time[2], time[3]]; + } + + // Z, or ±HH:MM: the offset from UTC in seconds + public offset(): int { + if (this.take(90) || this.take(122)) return 0; + const c = this.peek(); + if (c != 43 && c != 45) throw invalid("ISO 8601 offset: " + this.text); + this.at++; + const hours = this.digits(2); + this.take(58); + const minutes = this.digits(2); + const seconds = hours * 3600 + minutes * 60; + return c == 45 ? -seconds : seconds; + } + + public end(): void { + // an annotation, as [u-ca=iso8601], is allowed and ignored + if (this.peek() == 91) { + const close = this.text.indexOf("]", this.at); + if (close >= 0) this.at = close + 1; + } + + if (!this.done) throw invalid("ISO 8601 string: " + this.text); + } + } + + function checkDate(year: int, month: int, day: int): void { + if (month < 1 || month > 12 || day < 1 || day > daysInMonthOf(year, month)) { + throw invalid("date: " + year + "-" + month + "-" + day); + } + } + + function checkTime(hour: int, minute: int, second: int, millisecond: int, microsecond: int, nanosecond: int): void { + if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59 + || millisecond < 0 || millisecond > 999 || microsecond < 0 || microsecond > 999 + || nanosecond < 0 || nanosecond > 999) { + throw invalid("time"); + } + } + + // A span of seconds and the nanoseconds past them, the nanoseconds in [0, 1e9): exact over any + // span a Duration can hold, where nanoseconds alone in a number lose digits past 104 days. + class Span { + constructor(public seconds: number, public nanoseconds: number) { + const carry = Math.floor(this.nanoseconds / NS_PER_SECOND); + this.seconds = this.seconds + carry; + this.nanoseconds = this.nanoseconds - carry * NS_PER_SECOND; + } + + public plus(other: Span): Span { + return new Span(this.seconds + other.seconds, this.nanoseconds + other.nanoseconds); + } + + public minus(other: Span): Span { + return new Span(this.seconds - other.seconds, this.nanoseconds - other.nanoseconds); + } + + public get sign(): int { + if (this.seconds < 0) return -1; + if (this.seconds > 0 || this.nanoseconds > 0) return 1; + return 0; + } + + public compare(other: Span): int { + return this.minus(other).sign; + } + + // as a Duration whose largest unit is `largest` (DAYS to SECONDS), each field with its sign + public toDuration(largest: int): Duration { + const sign = this.sign; + let seconds = this.seconds; + let nanoseconds = this.nanoseconds; + if (sign < 0) { + // the magnitude: -(seconds + nanoseconds / 1e9) + seconds = -seconds; + if (nanoseconds > 0) { + seconds = seconds - 1; + nanoseconds = NS_PER_SECOND - nanoseconds; + } + } + + let days = 0; + let hours = 0; + let minutes = 0; + if (largest <= DAYS) { + days = Math.floor(seconds / SECONDS_PER_DAY); + seconds = seconds - days * SECONDS_PER_DAY; + } + + if (largest <= HOURS) { + hours = Math.floor(seconds / 3600); + seconds = seconds - hours * 3600; + } + + if (largest <= MINUTES) { + minutes = Math.floor(seconds / 60); + seconds = seconds - minutes * 60; + } + + const milliseconds = Math.floor(nanoseconds / 1000000); + const microseconds = Math.floor(nanoseconds / 1000) % 1000; + const rest = nanoseconds % 1000; + return new Duration(0, 0, 0, days * sign, hours * sign, minutes * sign, seconds * sign, + milliseconds * sign, microseconds * sign, rest * sign); + } + } + + function unitOf(name: string): int { + if (name == "year" || name == "years") return YEARS; + if (name == "month" || name == "months") return MONTHS; + if (name == "week" || name == "weeks") return WEEKS; + if (name == "day" || name == "days") return DAYS; + if (name == "hour" || name == "hours") return HOURS; + if (name == "minute" || name == "minutes") return MINUTES; + if (name == "second" || name == "seconds") return SECONDS; + if (name == "millisecond" || name == "milliseconds") return 7; + if (name == "microsecond" || name == "microseconds") return 8; + if (name == "nanosecond" || name == "nanoseconds") return 9; + throw invalid("unit: " + name); + } + + // A length of time in years, months, weeks, days, hours, minutes, seconds, milliseconds, + // microseconds and nanoseconds. Every field is a whole number, and none has a sign the others + // do not. Without a date to count from (JavaScript's relativeTo, not here) a year, a month and a + // week have no length, so add, subtract, compare and total refuse a Duration that has them, and a + // day is 24 hours. + @final + export class Duration { + private fields: number[]; + + public constructor(years: number = 0, months: number = 0, weeks: number = 0, days: number = 0, + hours: number = 0, minutes: number = 0, seconds: number = 0, milliseconds: number = 0, + microseconds: number = 0, nanoseconds: number = 0) { + const fields = [years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds]; + let sign = 0; + for (let i = 0; i < 10; i++) { + const v = fields[i]; + if (!isFinite(v) || Math.trunc(v) != v) { + throw invalid("duration: a field is not a whole number"); + } + + // -0 is 0 + if (v == 0) { + fields[i] = 0; + continue; + } + + const s = v < 0 ? -1 : 1; + if (sign != 0 && s != sign) { + throw invalid("duration: mixed signs"); + } + + sign = s; + } + + this.fields = fields; + } + + // P[nY][nM][nW][nD][T[nH][nM][n[.fffffffff]S]], with a sign before the P for a negative one + public static from(text: string): Duration { + const reader = new IsoReader(text); + let sign = 1; + if (reader.take(45)) { + sign = -1; + } else { + reader.take(43); + } + + if (!reader.take(80) && !reader.take(112)) throw invalid("ISO 8601 duration: " + text); + const fields = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let inTime = false; + let any = false; + let last = -1; + while (!reader.done) { + if (reader.take(84) || reader.take(116)) { + if (inTime) throw invalid("ISO 8601 duration: " + text); + inTime = true; + continue; + } + + let whole = 0; + let digits = 0; + while (reader.peek() >= 48 && reader.peek() <= 57) { + whole = whole * 10 + (reader.peek() - 48); + reader.at++; + digits++; + } + + let fraction = 0; + let fractionDigits = 0; + if (reader.take(46) || reader.take(44)) { + while (reader.peek() >= 48 && reader.peek() <= 57) { + if (fractionDigits < 9) { + fraction = fraction * 10 + (reader.peek() - 48); + fractionDigits++; + } + + reader.at++; + } + } + + if (digits == 0) throw invalid("ISO 8601 duration: " + text); + const designator = reader.peek() | 32; + reader.at++; + let unit = -1; + if (!inTime && designator == 121) unit = YEARS; + else if (!inTime && designator == 109) unit = MONTHS; + else if (!inTime && designator == 119) unit = WEEKS; + else if (!inTime && designator == 100) unit = DAYS; + else if (inTime && designator == 104) unit = HOURS; + else if (inTime && designator == 109) unit = MINUTES; + else if (inTime && designator == 115) unit = SECONDS; + if (unit < 0 || unit <= last) throw invalid("ISO 8601 duration: " + text); + // only seconds take a fraction here + if (fractionDigits > 0 && unit != SECONDS) throw invalid("ISO 8601 duration: " + text); + fields[unit] = whole; + if (unit == SECONDS) { + for (let i = fractionDigits; i < 9; i++) fraction = fraction * 10; + fields[7] = Math.floor(fraction / 1000000); + fields[8] = Math.floor(fraction / 1000) % 1000; + fields[9] = fraction % 1000; + } + + last = unit; + any = true; + } + + if (!any) throw invalid("ISO 8601 duration: " + text); + return new Duration(fields[0] * sign, fields[1] * sign, fields[2] * sign, fields[3] * sign, + fields[4] * sign, fields[5] * sign, fields[6] * sign, fields[7] * sign, fields[8] * sign, + fields[9] * sign); + } + + // by length: a Duration with years, months or weeks has none, and is a RangeError + public static compare(one: Duration, two: Duration): int { + return one.span().compare(two.span()); + } + + public get years(): number { return this.fields[0]; } + public get months(): number { return this.fields[1]; } + public get weeks(): number { return this.fields[2]; } + public get days(): number { return this.fields[3]; } + public get hours(): number { return this.fields[4]; } + public get minutes(): number { return this.fields[5]; } + public get seconds(): number { return this.fields[6]; } + public get milliseconds(): number { return this.fields[7]; } + public get microseconds(): number { return this.fields[8]; } + public get nanoseconds(): number { return this.fields[9]; } + + public get sign(): int { + for (let i = 0; i < 10; i++) { + if (this.fields[i] < 0) return -1; + if (this.fields[i] > 0) return 1; + } + + return 0; + } + + public get blank(): boolean { + return this.sign == 0; + } + + public negated(): Duration { + const f = this.fields; + return new Duration(-f[0], -f[1], -f[2], -f[3], -f[4], -f[5], -f[6], -f[7], -f[8], -f[9]); + } + + // a new Duration either way: under -mm=own one call cannot give back `this` or a new one + public abs(): Duration { + if (this.sign < 0) return this.negated(); + const f = this.fields; + return new Duration(f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]); + } + + // the sum, in the larger of the two largest units + public add(other: Duration): Duration { + const largest = this.largestUnit() < other.largestUnit() ? this.largestUnit() : other.largestUnit(); + return this.span().plus(other.span()).toDuration(largest < DAYS ? DAYS : largest); + } + + public subtract(other: Duration): Duration { + return this.add(other.negated()); + } + + // the length in `unit`, from "day" to "nanosecond", fraction and all + public total(unit: string): number { + const u = unitOf(unit); + if (u < DAYS) throw new RangeError("A year, month or week has no length without a date to count from"); + const span = this.span(); + const perUnit = [SECONDS_PER_DAY, 3600, 60, 1, 0.001, 0.000001, 0.000000001]; + return (span.seconds + span.nanoseconds / NS_PER_SECOND) / perUnit[u - DAYS]; + } + + public toString(): string { + const sign = this.sign; + if (sign == 0) return "PT0S"; + const f = this.abs().fields; + let text: string = sign < 0 ? "-P" : "P"; + if (f[0] != 0) text += f[0] + "Y"; + if (f[1] != 0) text += f[1] + "M"; + if (f[2] != 0) text += f[2] + "W"; + if (f[3] != 0) text += f[3] + "D"; + // the parts of a second go into the seconds, as JavaScript writes them + const subsecond = new Span(f[6], f[7] * 1000000 + f[8] * 1000 + f[9]); + const hasSeconds = subsecond.seconds != 0 || subsecond.nanoseconds != 0; + if (f[4] != 0 || f[5] != 0 || hasSeconds) { + text += "T"; + if (f[4] != 0) text += f[4] + "H"; + if (f[5] != 0) text += f[5] + "M"; + if (hasSeconds) text += subsecond.seconds + fractionText(subsecond.nanoseconds) + "S"; + } + + return text; + } + + public toJSON(): string { + return this.toString(); + } + + // for the classes here: the fields as they are + public __field(index: int): number { + return this.fields[index]; + } + + // years, months and weeks refused; a day is 24 hours + private span(): Span { + const f = this.fields; + if (f[0] != 0 || f[1] != 0 || f[2] != 0) { + throw new RangeError("A year, month or week has no length without a date to count from"); + } + + return new Span(f[3] * SECONDS_PER_DAY + f[4] * 3600 + f[5] * 60 + f[6], f[7] * 1000000 + f[8] * 1000 + f[9]); + } + + // the index of the first field that is not 0; SECONDS when only parts of a second are + private largestUnit(): int { + for (let i = 0; i < 10; i++) { + if (this.fields[i] != 0) return i < SECONDS ? i : SECONDS; + } + + return SECONDS; + } + + } + + // A point in time, to the nanosecond, with no calendar and no time zone: kept as the seconds + // from 1970-01-01T00:00:00Z and the nanoseconds past them. + @final + export class Instant { + private epochSeconds: number; + private nanos: number; + + // nanoseconds from 1970-01-01T00:00:00Z + public constructor(epochNanoseconds: bigint) { + // in 64 bits throughout: a bigint times an int is an int here + const billion: bigint = NS_PER_SECOND; + const rest: bigint = epochNanoseconds % billion; + const whole: bigint = (epochNanoseconds - rest) / billion; + const span = new Span(0, rest); + this.epochSeconds = whole + span.seconds; + this.nanos = span.nanoseconds; + } + + public static fromEpochMilliseconds(epochMilliseconds: number): Instant { + if (!isFinite(epochMilliseconds) || Math.trunc(epochMilliseconds) != epochMilliseconds) { + throw invalid("epoch milliseconds"); + } + + return Instant.ofSpan(new Span(0, (epochMilliseconds % 1000) * 1000000).plus(new Span(Math.trunc(epochMilliseconds / 1000), 0))); + } + + public static fromEpochNanoseconds(epochNanoseconds: bigint): Instant { + return new Instant(epochNanoseconds); + } + + // a date and time with Z or an offset, as 2024-03-15T12:30:00Z or 2024-03-15T14:30+02:00 + public static from(text: string): Instant { + const reader = new IsoReader(text); + const p = reader.dateTime(); + const offset = reader.offset(); + reader.end(); + checkDate(p[0], p[1], p[2]); + checkTime(p[3], p[4], p[5], 0, 0, 0); + const seconds = epochDays(p[0], p[1], p[2]) * SECONDS_PER_DAY + p[3] * 3600 + p[4] * 60 + p[5] - offset; + return Instant.ofSpan(new Span(seconds, p[6])); + } + + public static compare(one: Instant, two: Instant): int { + return one.span().compare(two.span()); + } + + public get epochMilliseconds(): number { + return this.epochSeconds * 1000 + Math.floor(this.nanos / 1000000); + } + + public get epochNanoseconds(): bigint { + const billion: bigint = NS_PER_SECOND; + const seconds: bigint = this.epochSeconds; + const nanos: bigint = this.nanos; + return seconds * billion + nanos; + } + + // hours and smaller only: a day is not always 24 hours, so days and larger are a RangeError + public add(duration: Duration): Instant { + if (duration.__field(YEARS) != 0 || duration.__field(MONTHS) != 0 || duration.__field(WEEKS) != 0 + || duration.__field(DAYS) != 0) { + throw new RangeError("An Instant takes hours and smaller units only"); + } + + return Instant.ofSpan(this.span().plus(Instant.spanOf(duration))); + } + + public subtract(duration: Duration): Instant { + return this.add(duration.negated()); + } + + // from this one to `other`, in seconds and smaller + public until(other: Instant): Duration { + return other.span().minus(this.span()).toDuration(SECONDS); + } + + public since(other: Instant): Duration { + return this.span().minus(other.span()).toDuration(SECONDS); + } + + public equals(other: Instant): boolean { + return this.epochSeconds == other.epochSeconds && this.nanos == other.nanos; + } + + // in UTC, as 2024-03-15T12:30:00.5Z + public toString(): string { + const days = Math.floor(this.epochSeconds / SECONDS_PER_DAY); + const rest = this.epochSeconds - days * SECONDS_PER_DAY; + const date = dateOfEpochDays(days); + return date.toString() + "T" + timeText(Math.floor(rest / 3600), (Math.floor(rest / 60) % 60), (rest % 60), this.nanos) + "Z"; + } + + public toJSON(): string { + return this.toString(); + } + + private span(): Span { + return new Span(this.epochSeconds, this.nanos); + } + + private static ofSpan(span: Span): Instant { + const instant = new Instant(0); + instant.epochSeconds = span.seconds; + instant.nanos = span.nanoseconds; + return instant; + } + + private static spanOf(duration: Duration): Span { + return new Span(duration.__field(HOURS) * 3600 + duration.__field(MINUTES) * 60 + duration.__field(SECONDS), + duration.__field(7) * 1000000 + duration.__field(8) * 1000 + duration.__field(9)); + } + } + + // A date in the ISO 8601 calendar, with no time and no time zone. + @final + export class PlainDate { + private isoYear: int; + private isoMonth: int; + private isoDay: int; + + public constructor(year: int, month: int, day: int) { + checkDate(year, month, day); + this.isoYear = year; + this.isoMonth = month; + this.isoDay = day; + } + + // YYYY-MM-DD; the time of a date and time is ignored + public static from(text: string): PlainDate { + const reader = new IsoReader(text); + const p = reader.dateTime(); + if (reader.peek() == 90 || reader.peek() == 122) throw invalid("PlainDate string: " + text); + reader.end(); + return new PlainDate(p[0], p[1], p[2]); + } + + public static compare(one: PlainDate, two: PlainDate): int { + const d = one.__epochDays() - two.__epochDays(); + return d < 0 ? -1 : d > 0 ? 1 : 0; + } + + public get year(): int { return this.isoYear; } + public get month(): int { return this.isoMonth; } + public get day(): int { return this.isoDay; } + + public get monthCode(): string { + return "M" + pad(this.isoMonth, 2); + } + + public get calendarId(): string { + return "iso8601"; + } + + // 1 for Monday to 7 for Sunday + public get dayOfWeek(): int { + const d = (this.__epochDays() + 3) % 7; + return (d < 0 ? d + 8 : d + 1); + } + + public get dayOfYear(): int { + return this.__epochDays() - epochDays(this.isoYear, 1, 1) + 1; + } + + public get daysInMonth(): int { + return daysInMonthOf(this.isoYear, this.isoMonth); + } + + public get daysInYear(): int { + return isLeapYear(this.isoYear) ? 366 : 365; + } + + public get daysInWeek(): int { + return 7; + } + + public get monthsInYear(): int { + return 12; + } + + public get inLeapYear(): boolean { + return isLeapYear(this.isoYear); + } + + // Years and months first, a day past the month's end moved back to its last, then weeks and + // days; whole days of the time units count too, and the rest of them is dropped. + public add(duration: Duration): PlainDate { + let year = this.isoYear + duration.__field(YEARS); + let month = this.isoMonth + duration.__field(MONTHS); + year = year + Math.floor((month - 1) / 12); + month = ((month - 1) % 12 + 12) % 12 + 1; + let day = this.isoDay; + const last = daysInMonthOf(year, month); + if (day > last) day = last; + const timeSeconds = duration.__field(HOURS) * 3600 + duration.__field(MINUTES) * 60 + duration.__field(SECONDS) + + Math.trunc((duration.__field(7) * 1000000 + duration.__field(8) * 1000 + duration.__field(9)) / NS_PER_SECOND); + const days = duration.__field(WEEKS) * 7 + duration.__field(DAYS) + Math.trunc(timeSeconds / SECONDS_PER_DAY); + return dateOfEpochDays((epochDays(year, month, day) + days)); + } + + public subtract(duration: Duration): PlainDate { + return this.add(duration.negated()); + } + + // from this date to `other`, in days + public until(other: PlainDate): Duration { + return new Duration(0, 0, 0, other.__epochDays() - this.__epochDays()); + } + + public since(other: PlainDate): Duration { + return new Duration(0, 0, 0, this.__epochDays() - other.__epochDays()); + } + + // `with`, which is a keyword here, as Array's is: a copy with the fields given replaced + public _with(fields: { year?: int, month?: int, day?: int }): PlainDate { + const year = fields.year != undefined ? fields.year : this.isoYear; + const month = fields.month != undefined ? fields.month : this.isoMonth; + let day = fields.day != undefined ? fields.day : this.isoDay; + if (month >= 1 && month <= 12 && day > daysInMonthOf(year, month)) day = daysInMonthOf(year, month); + return new PlainDate(year, month, day); + } + + public equals(other: PlainDate): boolean { + return this.isoYear == other.isoYear && this.isoMonth == other.isoMonth && this.isoDay == other.isoDay; + } + + public toPlainDateTime(time?: PlainTime): PlainDateTime { + if (time == undefined) { + return new PlainDateTime(this.isoYear, this.isoMonth, this.isoDay); + } + + return new PlainDateTime(this.isoYear, this.isoMonth, this.isoDay, time.hour, time.minute, time.second, + time.millisecond, time.microsecond, time.nanosecond); + } + + public toString(): string { + return yearText(this.isoYear) + "-" + pad(this.isoMonth, 2) + "-" + pad(this.isoDay, 2); + } + + public toJSON(): string { + return this.toString(); + } + + // for the classes here: the days from 1970-01-01 + public __epochDays(): int { + return epochDays(this.isoYear, this.isoMonth, this.isoDay); + } + } + + // A time of day, to the nanosecond, with no date and no time zone. + @final + export class PlainTime { + private parts: int[]; + + public constructor(hour = 0, minute = 0, second = 0, millisecond = 0, microsecond = 0, nanosecond = 0) { + checkTime(hour, minute, second, millisecond, microsecond, nanosecond); + this.parts = [hour, minute, second, millisecond, microsecond, nanosecond]; + } + + // HH:MM[:SS[.fffffffff]], alone or after a date and "T" + public static from(text: string): PlainTime { + const reader = new IsoReader(text); + let p: int[]; + if (text.length > 2 && text.charCodeAt(2) == 58) { + p = reader.time(); + } else { + const all = reader.dateTime(); + p = [all[3], all[4], all[5], all[6]]; + } + + reader.end(); + return new PlainTime(p[0], p[1], p[2], Math.floor(p[3] / 1000000), (Math.floor(p[3] / 1000) % 1000), p[3] % 1000); + } + + public static compare(one: PlainTime, two: PlainTime): int { + return spanOfTime(one).compare(spanOfTime(two)); + } + + public get hour(): int { return this.parts[0]; } + public get minute(): int { return this.parts[1]; } + public get second(): int { return this.parts[2]; } + public get millisecond(): int { return this.parts[3]; } + public get microsecond(): int { return this.parts[4]; } + public get nanosecond(): int { return this.parts[5]; } + + // around the clock: what passes midnight starts the day again + public add(duration: Duration): PlainTime { + const span = spanOfTime(this).plus(new Span(duration.__field(DAYS) * SECONDS_PER_DAY + duration.__field(HOURS) * 3600 + + duration.__field(MINUTES) * 60 + duration.__field(SECONDS), + duration.__field(7) * 1000000 + duration.__field(8) * 1000 + duration.__field(9))); + const seconds = span.seconds - Math.floor(span.seconds / SECONDS_PER_DAY) * SECONDS_PER_DAY; + return PlainTime.ofSpan(new Span(seconds, span.nanoseconds)); + } + + public subtract(duration: Duration): PlainTime { + return this.add(duration.negated()); + } + + // from this time to `other`, in hours and smaller + public until(other: PlainTime): Duration { + return spanOfTime(other).minus(spanOfTime(this)).toDuration(HOURS); + } + + public since(other: PlainTime): Duration { + return spanOfTime(this).minus(spanOfTime(other)).toDuration(HOURS); + } + + // `with`, a copy with the fields given replaced + public _with(fields: { hour?: int, minute?: int, second?: int, millisecond?: int, microsecond?: int, nanosecond?: int }): PlainTime { + return new PlainTime( + fields.hour != undefined ? fields.hour : this.parts[0], + fields.minute != undefined ? fields.minute : this.parts[1], + fields.second != undefined ? fields.second : this.parts[2], + fields.millisecond != undefined ? fields.millisecond : this.parts[3], + fields.microsecond != undefined ? fields.microsecond : this.parts[4], + fields.nanosecond != undefined ? fields.nanosecond : this.parts[5]); + } + + public equals(other: PlainTime): boolean { + return PlainTime.compare(this, other) == 0; + } + + public toString(): string { + const p = this.parts; + return timeText(p[0], p[1], p[2], p[3] * 1000000 + p[4] * 1000 + p[5]); + } + + public toJSON(): string { + return this.toString(); + } + + private static ofSpan(span: Span): PlainTime { + const s = span.seconds; + const n = span.nanoseconds; + return new PlainTime(Math.floor(s / 3600), (Math.floor(s / 60) % 60), (s % 60), + Math.floor(n / 1000000), (Math.floor(n / 1000) % 1000), (n % 1000)); + } + } + + // the seconds since midnight and the nanoseconds past them + function spanOfTime(time: PlainTime): Span { + return new Span(time.hour * 3600 + time.minute * 60 + time.second, + time.millisecond * 1000000 + time.microsecond * 1000 + time.nanosecond); + } + + // A date and a time of day in the ISO 8601 calendar, with no time zone. + @final + export class PlainDateTime { + private date: PlainDate; + private time: PlainTime; + + public constructor(year: int, month: int, day: int, hour = 0, minute = 0, second = 0, millisecond = 0, + microsecond = 0, nanosecond = 0) { + this.date = new PlainDate(year, month, day); + this.time = new PlainTime(hour, minute, second, millisecond, microsecond, nanosecond); + } + + // YYYY-MM-DD[THH:MM[:SS[.fffffffff]]] + public static from(text: string): PlainDateTime { + const reader = new IsoReader(text); + const p = reader.dateTime(); + if (reader.peek() == 90 || reader.peek() == 122) throw invalid("PlainDateTime string: " + text); + reader.end(); + return new PlainDateTime(p[0], p[1], p[2], p[3], p[4], p[5], Math.floor(p[6] / 1000000), + (Math.floor(p[6] / 1000) % 1000), p[6] % 1000); + } + + public static compare(one: PlainDateTime, two: PlainDateTime): int { + return one.span().compare(two.span()); + } + + public get year(): int { return this.date.year; } + public get month(): int { return this.date.month; } + public get day(): int { return this.date.day; } + public get hour(): int { return this.time.hour; } + public get minute(): int { return this.time.minute; } + public get second(): int { return this.time.second; } + public get millisecond(): int { return this.time.millisecond; } + public get microsecond(): int { return this.time.microsecond; } + public get nanosecond(): int { return this.time.nanosecond; } + public get monthCode(): string { return this.date.monthCode; } + public get calendarId(): string { return "iso8601"; } + public get dayOfWeek(): int { return this.date.dayOfWeek; } + public get dayOfYear(): int { return this.date.dayOfYear; } + public get daysInMonth(): int { return this.date.daysInMonth; } + public get daysInYear(): int { return this.date.daysInYear; } + public get inLeapYear(): boolean { return this.date.inLeapYear; } + + // the time units first, whole days of them carried into the date, then the date's + public add(duration: Duration): PlainDateTime { + const time = spanOfTime(this.time).plus(new Span(duration.__field(HOURS) * 3600 + duration.__field(MINUTES) * 60 + + duration.__field(SECONDS), duration.__field(7) * 1000000 + duration.__field(8) * 1000 + duration.__field(9))); + const carry = Math.floor(time.seconds / SECONDS_PER_DAY); + const date = this.date.add(new Duration(duration.__field(YEARS), duration.__field(MONTHS), duration.__field(WEEKS), + duration.__field(DAYS) + carry)); + return PlainDateTime.of(date, new Span(time.seconds - carry * SECONDS_PER_DAY, time.nanoseconds)); + } + + public subtract(duration: Duration): PlainDateTime { + return this.add(duration.negated()); + } + + // from this one to `other`, in days and smaller + public until(other: PlainDateTime): Duration { + return other.span().minus(this.span()).toDuration(DAYS); + } + + public since(other: PlainDateTime): Duration { + return this.span().minus(other.span()).toDuration(DAYS); + } + + // `with`, a copy with the fields given replaced + public _with(fields: { year?: int, month?: int, day?: int, hour?: int, minute?: int, second?: int, + millisecond?: int, microsecond?: int, nanosecond?: int }): PlainDateTime { + const year = fields.year != undefined ? fields.year : this.date.year; + const month = fields.month != undefined ? fields.month : this.date.month; + let day = fields.day != undefined ? fields.day : this.date.day; + if (month >= 1 && month <= 12 && day > daysInMonthOf(year, month)) day = daysInMonthOf(year, month); + return new PlainDateTime(year, month, day, + fields.hour != undefined ? fields.hour : this.time.hour, + fields.minute != undefined ? fields.minute : this.time.minute, + fields.second != undefined ? fields.second : this.time.second, + fields.millisecond != undefined ? fields.millisecond : this.time.millisecond, + fields.microsecond != undefined ? fields.microsecond : this.time.microsecond, + fields.nanosecond != undefined ? fields.nanosecond : this.time.nanosecond); + } + + public equals(other: PlainDateTime): boolean { + return this.date.equals(other.date) && this.time.equals(other.time); + } + + public toPlainDate(): PlainDate { + return new PlainDate(this.date.year, this.date.month, this.date.day); + } + + public toPlainTime(): PlainTime { + return new PlainTime(this.time.hour, this.time.minute, this.time.second, this.time.millisecond, + this.time.microsecond, this.time.nanosecond); + } + + public toString(): string { + return this.date.toString() + "T" + this.time.toString(); + } + + public toJSON(): string { + return this.toString(); + } + + // the seconds from 1970-01-01T00:00 and the nanoseconds past them + private span(): Span { + const time = spanOfTime(this.time); + return new Span(this.date.__epochDays() * SECONDS_PER_DAY + time.seconds, time.nanoseconds); + } + + private static of(date: PlainDate, time: Span): PlainDateTime { + const s = time.seconds; + const n = time.nanoseconds; + return new PlainDateTime(date.year, date.month, date.day, Math.floor(s / 3600), (Math.floor(s / 60) % 60), + (s % 60), Math.floor(n / 1000000), (Math.floor(n / 1000) % 1000), (n % 1000)); + } + } + + // the present, to the millisecond, as the system's clock gives it; the plain ones at the system's + // present offset from UTC + export namespace Now { + export function instant(): Temporal.Instant { + return Temporal.Instant.fromEpochMilliseconds(Date.now()); + } + + export function plainDateTimeISO(): Temporal.PlainDateTime { + const now = Date.now(); + const local = now - new Date(now).getTimezoneOffset() * 60000; + const days = Math.floor(local / 86400000); + const ms = local - days * 86400000; + const date = new Temporal.PlainDate(1970, 1, 1).add(new Temporal.Duration(0, 0, 0, days)); + return date.toPlainDateTime(new Temporal.PlainTime(Math.floor(ms / 3600000), + (Math.floor(ms / 60000) % 60), (Math.floor(ms / 1000) % 60), (ms % 1000))); + } + + export function plainDateISO(): Temporal.PlainDate { + return plainDateTimeISO().toPlainDate(); + } + + export function plainTimeISO(): Temporal.PlainTime { + return plainDateTimeISO().toPlainTime(); + } + } +} diff --git a/tests/temporal_duration_instant.ts b/tests/temporal_duration_instant.ts new file mode 100644 index 0000000..e097712 --- /dev/null +++ b/tests/temporal_duration_instant.ts @@ -0,0 +1,77 @@ +// Temporal's Duration and Instant, and Now, as in JavaScript +function main() { + const d = Temporal.Duration.from("P1Y2M3W4DT5H6M7.008009010S"); + assert(d.years == 1 && d.months == 2 && d.weeks == 3 && d.days == 4, "the date fields"); + assert(d.hours == 5 && d.minutes == 6 && d.seconds == 7, "the time fields"); + assert(d.milliseconds == 8 && d.microseconds == 9 && d.nanoseconds == 10, "the parts of a second"); + assert(d.toString() == "P1Y2M3W4DT5H6M7.00800901S", "back to text"); + assert(d.sign == 1 && !d.blank, "positive"); + + const neg = d.negated(); + assert(neg.sign == -1 && neg.years == -1 && neg.toString() == "-P1Y2M3W4DT5H6M7.00800901S", "negated"); + assert(neg.abs().toString() == d.toString(), "abs"); + assert(new Temporal.Duration().toString() == "PT0S" && new Temporal.Duration().blank, "blank"); + assert(new Temporal.Duration(0, 0, 0, 0, 0, 0, 0, 1500).toString() == "PT1.5S", "milliseconds into seconds"); + + let mixed = false; + try { + new Temporal.Duration(1, -1); + } catch (e) { + mixed = e instanceof RangeError; + } + + assert(mixed, "mixed signs are a RangeError"); + + // the sum in the larger of the two largest units + const a = Temporal.Duration.from("PT1H30M"); + const b = Temporal.Duration.from("PT45M"); + assert(a.add(b).toString() == "PT2H15M", "hours and minutes"); + assert(Temporal.Duration.from("PT36H").add(b).toString() == "PT36H45M", "hours stay hours"); + assert(Temporal.Duration.from("P1D").add(Temporal.Duration.from("PT25H")).toString() == "P2DT1H", "days take hours"); + assert(a.subtract(Temporal.Duration.from("PT2H")).toString() == "-PT30M", "below 0"); + assert(Temporal.Duration.from("PT1H").total("minutes") == 60, "total"); + assert(Temporal.Duration.from("P1DT12H").total("day") == 1.5, "total in days"); + assert(Temporal.Duration.compare(a, b) == 1, "compare"); + + let noLength = false; + try { + Temporal.Duration.from("P1M").add(a); + } catch (e) { + noLength = e instanceof RangeError; + } + + assert(noLength, "a month has no length without a date"); + + const epoch = Temporal.Instant.fromEpochMilliseconds(0); + assert(epoch.toString() == "1970-01-01T00:00:00Z", "the epoch"); + const i = Temporal.Instant.from("2024-03-15T14:30:00.5+02:00"); + assert(i.toString() == "2024-03-15T12:30:00.5Z", "an offset, in UTC"); + assert(i.epochMilliseconds == 1710505800500, "epochMilliseconds"); + assert(i.epochNanoseconds == 1710505800500000000, "epochNanoseconds"); + assert(Temporal.Instant.fromEpochNanoseconds(i.epochNanoseconds).equals(i), "fromEpochNanoseconds"); + const later = i.add(Temporal.Duration.from("PT1H0.25S")); + assert(later.toString() == "2024-03-15T13:30:00.75Z", "add"); + assert(i.until(later).toString() == "PT3600.25S", "until, in seconds"); + assert(later.since(i).seconds == 3600, "since"); + assert(Temporal.Instant.compare(i, later) == -1, "compare"); + const before = Temporal.Instant.fromEpochMilliseconds(-1); + assert(before.toString() == "1969-12-31T23:59:59.999Z", "before the epoch"); + assert(before.epochNanoseconds == -1000000, "a negative epochNanoseconds"); + + let noDays = false; + try { + i.add(Temporal.Duration.from("P1D")); + } catch (e) { + noDays = e instanceof RangeError; + } + + assert(noDays, "an Instant takes no days"); + + const now = Temporal.Now.instant(); + assert(now.epochMilliseconds > 1700000000000, "now is after 2023"); + const today = Temporal.Now.plainDateISO(); + assert(today.year >= 2024, "today"); + assert(Temporal.Now.plainTimeISO().hour < 24, "a time of day"); + + console.log("ALL DONE"); +} diff --git a/tests/temporal_plain.ts b/tests/temporal_plain.ts new file mode 100644 index 0000000..d8a3b98 --- /dev/null +++ b/tests/temporal_plain.ts @@ -0,0 +1,69 @@ +// Temporal's PlainDate, PlainTime and PlainDateTime, in the ISO 8601 calendar, as in JavaScript +function main() { + const date = new Temporal.PlainDate(2024, 2, 29); + assert(date.year == 2024 && date.month == 2 && date.day == 29, "fields"); + assert(date.inLeapYear && date.daysInMonth == 29 && date.daysInYear == 366, "a leap year"); + assert(date.dayOfWeek == 4 && date.dayOfYear == 60, "Thursday, the 60th day"); + assert(date.monthCode == "M02" && date.calendarId == "iso8601", "monthCode and calendarId"); + assert(date.toString() == "2024-02-29", "toString"); + + let refused = false; + try { + new Temporal.PlainDate(2023, 2, 29); + } catch (e) { + refused = e instanceof RangeError; + } + + assert(refused, "no February 29 in 2023"); + + // a day past the end of the month goes back to its last + assert(date.add(Temporal.Duration.from("P1Y")).toString() == "2025-02-28", "a year on, constrained"); + assert(date.add(new Temporal.Duration(0, 1)).toString() == "2024-03-29", "a month on"); + assert(Temporal.PlainDate.from("2024-01-31").add(Temporal.Duration.from("P1M")).toString() == "2024-02-29", + "January 31 and a month"); + assert(date.add(Temporal.Duration.from("P1W2D")).toString() == "2024-03-09", "weeks and days"); + assert(date.subtract(Temporal.Duration.from("P60D")).toString() == "2023-12-31", "back past the start of a year"); + assert(date.add(Temporal.Duration.from("PT47H")).toString() == "2024-03-01", "whole days of hours"); + + const from = Temporal.PlainDate.from("1970-01-01"); + assert(from.until(date).days == 19782, "until, in days"); + assert(date.since(from).toString() == "P19782D", "since"); + assert(Temporal.PlainDate.compare(from, date) == -1 && date.equals(Temporal.PlainDate.from("2024-02-29")), + "compare and equals"); + assert(date._with({ month: 4, day: 31 }).toString() == "2024-04-30", "with, constrained"); + assert(new Temporal.PlainDate(-44, 3, 15).toString() == "-000044-03-15", "an expanded year"); + assert(Temporal.PlainDate.from("1969-12-31").dayOfWeek == 3, "a Wednesday before 1970"); + + const time = Temporal.PlainTime.from("13:45:30.25"); + assert(time.hour == 13 && time.minute == 45 && time.second == 30 && time.millisecond == 250, "time fields"); + assert(time.toString() == "13:45:30.25", "fraction, its trailing zeros gone"); + assert(new Temporal.PlainTime(9, 5).toString() == "09:05:00", "padded"); + assert(time.add(Temporal.Duration.from("PT11H")).toString() == "00:45:30.25", "around midnight"); + assert(time.subtract(Temporal.Duration.from("PT14H")).toString() == "23:45:30.25", "back around midnight"); + assert(new Temporal.PlainTime(8).until(time).toString() == "PT5H45M30.25S", "until, in hours and smaller"); + assert(time._with({ second: 0, millisecond: 0 }).toString() == "13:45:00", "with"); + + const dt = Temporal.PlainDateTime.from("2024-12-31T23:30"); + assert(dt.year == 2024 && dt.hour == 23 && dt.minute == 30, "date and time fields"); + assert(dt.toString() == "2024-12-31T23:30:00", "toString"); + const next = dt.add(Temporal.Duration.from("PT45M")); + assert(next.toString() == "2025-01-01T00:15:00", "the time carries into the date"); + assert(dt.until(next).toString() == "PT45M", "until"); + assert(Temporal.PlainDateTime.from("2024-01-01T00:00").until(dt).toString() == "P365DT23H30M", "days and smaller"); + assert(dt.subtract(Temporal.Duration.from("P1M")).toString() == "2024-11-30T23:30:00", "a month back, constrained"); + assert(dt.toPlainDate().equals(Temporal.PlainDate.from("2024-12-31")), "toPlainDate"); + assert(dt.toPlainTime().toString() == "23:30:00", "toPlainTime"); + assert(date.toPlainDateTime(time).toString() == "2024-02-29T13:45:30.25", "a date with a time"); + assert(Temporal.PlainDateTime.compare(dt, next) == -1, "compare"); + + let bad = false; + try { + Temporal.PlainDate.from("2024-13-01"); + } catch (e) { + bad = e instanceof RangeError; + } + + assert(bad, "month 13 is a RangeError"); + + console.log("ALL DONE"); +} From 45adee6989f9d6954b60322a2cbd460e7392fdc4 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 18:03:14 +0000 Subject: [PATCH 6/6] lib.d.ts: declare each Temporal class, so a program does not define it again A class inside `declare namespace` without its own `declare` had its ..new and ..instanceOf defined in every program as well as in the library: a debug link failed with duplicate symbols on every test (release dropped them). Co-Authored-By: Claude Opus 5.5 --- src/lib.d.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/lib.d.ts b/src/lib.d.ts index 2f35271..a2fbbb0 100644 --- a/src/lib.d.ts +++ b/src/lib.d.ts @@ -881,11 +881,13 @@ declare namespace console { } // Temporal's ISO 8601 part: see lib.ts. Each class lists its members in lib.ts's order: a program -// calls them by their place in the class's table. +// calls them by their place in the class's table. `declare` on each class too, not only on the +// namespace: without it a program defines the class's ..new and ..instanceOf itself, and a debug link +// finds them twice. declare namespace Temporal { @final @owned - class Duration { + declare class Duration { private fields: number[]; constructor(years?: number, months?: number, weeks?: number, days?: number, hours?: number, minutes?: number, @@ -917,7 +919,7 @@ declare namespace Temporal { @final @owned - class Instant { + declare class Instant { private epochSeconds: number; private nanos: number; @@ -940,7 +942,7 @@ declare namespace Temporal { @final @owned - class PlainDate { + declare class PlainDate { private isoYear: int; private isoMonth: int; private isoDay: int; @@ -975,7 +977,7 @@ declare namespace Temporal { @final @owned - class PlainTime { + declare class PlainTime { private parts: int[]; constructor(hour?: int, minute?: int, second?: int, millisecond?: int, microsecond?: int, nanosecond?: int); @@ -1000,7 +1002,7 @@ declare namespace Temporal { @final @owned - class PlainDateTime { + declare class PlainDateTime { private date: PlainDate; private time: PlainTime; @@ -1038,10 +1040,10 @@ declare namespace Temporal { toJSON(): string; } - namespace Now { - function instant(): Temporal.Instant; - function plainDateTimeISO(): Temporal.PlainDateTime; - function plainDateISO(): Temporal.PlainDate; - function plainTimeISO(): Temporal.PlainTime; + declare namespace Now { + declare function instant(): Temporal.Instant; + declare function plainDateTimeISO(): Temporal.PlainDateTime; + declare function plainDateISO(): Temporal.PlainDate; + declare function plainTimeISO(): Temporal.PlainTime; } }