Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,17 @@ Generics (`src/generics/lib.generics.ts`):
`BigUint64Array`, `Float32Array`, `Float64Array`)
- `Map<K, V>`
- `Set<V>`
- `Atomics`: `add`, `sub`, `and`, `or`, `xor`, `exchange`, `compareExchange`, `load`,
`store`, `isLockFree` over the integer typed arrays (no `wait`/`notify`)
- `Promise`: `resolve`, `reject`, `all`, `allSettled`, `race`, `any`. The compiler takes
`Promise<T>` 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.
There is no `then`/`catch`/`finally`.

Errors (`src/core/core.d.ts`):

- `Error`
- `RangeError`

Not yet implemented: `Promise`, `JSON.parse`/`JSON.stringify`, `Symbol` (beyond the
Not yet implemented: a `Promise` object (`then`/`catch`/`finally`), `JSON.parse`/`JSON.stringify`, `Symbol` (beyond the
well-known symbols used internally), `WeakMap`/`WeakSet`.
74 changes: 66 additions & 8 deletions src/generics/lib.generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -749,10 +749,10 @@ type Float32Array = TypedArray<f32>;
type Float64Array = TypedArray<f64>;

// Atomic operations on an integer TypedArray's elements, each sequentially consistent, as in
// JavaScript. Each is one LLVM `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`,
// not a `T`, so the array alone decides T - a literal `1` would otherwise make it s32 and reject a
// Uint16Array. There is no SharedArrayBuffer and a TypedArray is not a view over a buffer, so an
// 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 and a TypedArray is not a view over a buffer, so an
// operation acts on the array's own elements. `wait`, `waitAsync` and `notify` are not here: there
// is no other thread to wait for yet.
namespace Atomics {
Expand Down Expand Up @@ -787,16 +787,14 @@ namespace Atomics {
return cmpxchg(typedArray.__elementRef(index), <T>expectedValue, <T>replacementValue, 7, 7)[0];
}

// an `or` with 0 reads the element and leaves it as it was
function load<T>(typedArray: TypedArray<T>, index: int): T {
const zero: T = 0;
return atomicrmw(5, typedArray.__elementRef(index), zero, 7);
return atomicload(typedArray.__elementRef(index), 7);
}

// returns the value stored, as JavaScript does, not the one it replaced
function store<T>(typedArray: TypedArray<T>, index: int, value: number): T {
const stored = <T>value;
atomicrmw(0, typedArray.__elementRef(index), stored, 7);
atomicstore(typedArray.__elementRef(index), stored, 7);
return stored;
}

Expand All @@ -807,6 +805,66 @@ namespace Atomics {
}
}

// The compiler takes `Promise<T>` as T: an async function returns its value, and `await` gives the
// value back once the expression has run. So a promise here is the value itself, already settled,
// and these are the functions over such values. A rejected promise is a thrown exception. There is
// no `then`: a value has no methods. Each is generic, as `isLockFree` is above.
namespace Promise {
function resolve<T>(value: T): T {
return value;
}

// throws the reason: what awaiting a rejected promise does. The reason keeps its own type, so a
// `catch (e: Error)` catches an Error.
function reject<T = never, R = Error>(reason: R): T {
throw reason;
}

// the values, in order: every one has already settled. A new array, as in JavaScript: under
// -mm=own the result then owns its elements and can leave an `await`, which the argument cannot.
function all<T>(values: T[]): T[] {
const results: T[] = [];
for (const value of values) {
results.push(value);
}

return results;
}

// the first value: it settled first
function race<T>(values: T[]): T {
if (values.length == 0) {
throw new Error("Promise.race of no values never settles");
}

return values[0];
}

// the first value: none of them was rejected
function any<T>(values: T[]): T {
if (values.length == 0) {
throw new Error("All promises were rejected");
}

return values[0];
}

// every value as fulfilled: a rejection would have thrown before the array was built
function allSettled<T>(values: T[]): PromiseFulfilledResult<T>[] {
const results: PromiseFulfilledResult<T>[] = [];
for (const value of values) {
results.push({ status: "fulfilled", value: value });
}

return results;
}
}

interface PromiseFulfilledResult<T> {
status: string;
value: T;
}

enum InsertionBehavior {
None,
OverwriteExisting,
Expand Down
21 changes: 12 additions & 9 deletions tests/atomics.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
// Atomics over the integer TypedArrays. Each operation returns the value the element had before it,
// except store, which returns the value stored. The array alone decides the element type: a plain
// literal value does not make it s32. Each array is declared with its type: `new Uint8Array([250])`
// alone builds an array of s32.
// literal value does not make it s32, and a value wraps to the element's width as in JavaScript.

function main() {
const ta: Int32Array = new Int32Array([5, 10, 0]);
const ta = new Int32Array([5, 10, 0]);

assert(Atomics.add(ta, 0, 3) == 5 && ta[0] == 8, "add");
assert(Atomics.sub(ta, 1, 4) == 10 && ta[1] == 6, "sub");
Expand All @@ -20,19 +19,23 @@ function main() {
assert(Atomics.compareExchange(ta, 0, 8, 200) == 100 && ta[0] == 100, "compareExchange miss");

// narrower and wider elements wrap at their own width
const u8: Uint8Array = new Uint8Array([250]);
const u8 = new Uint8Array([250]);
assert(Atomics.add(u8, 0, 10) == 250 && u8[0] == 4, "Uint8Array wraps");
assert(Atomics.add(u8, 0, 300) == 4 && u8[0] == 48, "a value wraps to the element width");
assert(Atomics.sub(u8, 0, -1) == 48 && u8[0] == 49, "a negative value wraps too");
assert(Atomics.load(u8, 0) == 49, "load of a narrow element");
assert(Atomics.store(u8, 0, 7) == 7 && u8[0] == 7, "store to a narrow element");

const u16: Uint16Array = new Uint16Array([65535]);
const u16 = new Uint16Array([65535]);
assert(Atomics.add(u16, 0, 2) == 65535 && u16[0] == 1, "Uint16Array wraps");

const s8: Int8Array = new Int8Array([127]);
const s8 = new Int8Array([127]);
assert(Atomics.add(s8, 0, 1) == 127 && s8[0] == -128, "Int8Array wraps");

const big: BigInt64Array = new BigInt64Array([4000000000]);
const big = new BigInt64Array([4000000000]);
assert(Atomics.add(big, 0, 1) == 4000000000 && big[0] == 4000000001, "BigInt64Array is 64 bits");

const counters: Int32Array = new Int32Array([0, 0, 0, 0]);
const counters = new Int32Array([0, 0, 0, 0]);
for (let i = 0; i < 1000; i++) {
Atomics.add(counters, i % 4, 1);
}
Expand All @@ -42,7 +45,7 @@ function main() {
assert(Atomics.isLockFree(4) && Atomics.isLockFree(8) && !Atomics.isLockFree(3), "isLockFree");

// a Float64Array still builds: no atomic operation is made for its elements
const f: Float64Array = new Float64Array([1.5]);
const f = new Float64Array([1.5]);
assert(f[0] == 1.5, "Float64Array unaffected");

print("ALL DONE");
Expand Down
35 changes: 35 additions & 0 deletions tests/promise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Promise<T> is T: an async function returns its value and `await` gives it back. The Promise
// functions take and return such values, already settled. Promise.reject is in promise_reject.ts.

async function twice(n: int): Promise<int> {
return n * 2;
}

function main() {
const one: Promise<int> = Promise.resolve(1);
assert(one == 1, "resolve");

const both = Promise.all([twice(2), twice(5)]);
assert(both.length == 2 && both[0] == 4 && both[1] == 10, "all");

const awaited = await Promise.all([twice(3), twice(4)]);
assert(awaited[0] == 6 && awaited[1] == 8, "await all");

assert(Promise.race([twice(7), twice(8)]) == 14, "race");
assert(Promise.any(["a", "b"]) == "a", "any");

const settled = Promise.allSettled([1, 2]);
assert(settled.length == 2 && settled[0].status == "fulfilled" && settled[1].value == 2, "allSettled");

let raceCaught = false;
try {
const none: int[] = [];
Promise.race(none);
} catch (e: Error) {
raceCaught = true;
}

assert(raceCaught, "race of no values");

print("ALL DONE");
}
30 changes: 30 additions & 0 deletions tests/promise_reject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// A rejected promise is a thrown exception: Promise.reject throws its reason, with its own class.
// The string Promise.resolve returns borrows its argument; under -mm=own the await gives back a copy.

async function greet(name: string): Promise<string> {
return "hello " + name;
}

function main() {
assert(await Promise.resolve(greet("you")) == "hello you", "await resolve");

let caught = false;
try {
Promise.reject<int>(new Error("no"));
} catch (e: Error) {
caught = e.message == "no";
}

assert(caught, "reject throws its reason");

let caughtRange = false;
try {
Promise.reject(new RangeError("range"));
} catch (e: RangeError) {
caughtRange = e.message == "range";
}

assert(caughtRange, "reject keeps the reason's class");

print("ALL DONE");
}