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
2 changes: 1 addition & 1 deletion quest/m2/ts-model/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ Public API: the translator's output for moq-net's model.
## Required

- [Shared ownership](/quest/m2/ts-shared.md) - kio's waiters are `Arc`/`Weak` with observable counts, and its atomics and locks are plain values
- [A std Once in a static](/quest/m2/ts-model/once.md) - crossbeam-epoch's own `OnceLock` static translates over an `rt.Once`
- [std's UnsafeCell](/quest/m2/ts-model/unsafe-cell.md) - crossbeam-epoch's own `OnceLock` static translates, its `Once` already does
- [The rest of std the model reaches](/quest/m2/ts-model/std-rest.md) - `Vec` and `VecDeque` capacity
- [hashbrown as the runtime's map](/quest/m2/ts-model/hashbrown.md) - hashlink's `hashbrown` tables translate as `rt.HashMap`, with std's capacity
- [Async in the TypeScript translator](/quest/m2/ts-async.md) - kio's producers and consumers are futures
23 changes: 0 additions & 23 deletions quest/m2/ts-model/once.md

This file was deleted.

23 changes: 23 additions & 0 deletions quest/m2/ts-model/unsafe-cell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# [M] std's UnsafeCell

## Goal

rust2-ts translates std's `UnsafeCell<T>`, its type and its `new`, `get`, `get_mut`, and
`into_inner`, with the pointer `get` gives read and written as raw pointers are, so
crossbeam-epoch's own `OnceLock<Collector>` static translates, proven by differential
tests against native Rust.

## Plan

Left by [#262](https://github.com/moq-dev/rust2/pull/262) on 2026-10-30: std's `Once`
translates, so crossbeam-epoch's `OnceLock` is refused only at its
`UnsafeCell<MaybeUninit<T>>`: the field at `crossbeam-epoch-0.9.21/src/sync/once_lock.rs:11`
and `get` at lines 64 and 77. The model's census refuses std's `UnsafeCell` 10 times, first
in crossbeam-epoch's own wrapper over it at `src/lib.rs:101`, and in foldhash's seed.

- A static's `UnsafeCell` already reads from memory as its contents; its type and calls
are what remain.
- `get` gives a `*mut T`, which is what a `&mut T` is: the object, or an `rt.Place` where
JS copies `T`, as `rt.Cell` is for `Cell<T>`.

Public API: the translator's output.
1 change: 1 addition & 0 deletions ts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ crate translation reaches is refused, and so are two versions of one crate it re
| `Cell<T>`, `RefCell<T>`, `RwLock<T>` | `rt.Cell`, the place holding its value in `v`; `rt.RefCell` for either of the others, its own guard, counting its borrows: borrowing it while that conflicts panics as `RefCell`'s does, and locking it so aborts as wasm32's `RwLock` does |
| `thread_local!`, `LocalKey<T>` | an `rt.LocalKey`, a module's value, which makes its value on first use from the `const` or the expression and never drops it, as wasm32's do; `with` calls its function on that value, `try_with` never fails, the `Cell` and `RefCell` helpers lower from std, and a `RefCell` key's `set` and `with_borrow_mut` borrow it as `borrow_mut` does |
| `OnceCell<T>`, `OnceLock<T>` | `rt.OnceCell` and `rt.OnceLock`, holding the `Option<T>` in `v`; a `OnceLock` initialized from within its own initialization panics, as wasm32's does |
| `Once`, `OnceState` | `rt.Once`, an `rt.OnceLock` that holds `true` once `call_once` or `call_once_force` ran its function, and panics as wasm32's does if run again from within it; `rt.OnceState`, that `Once`, which a panic never poisons, as it aborts |
| `LazyCell<T>`, `LazyLock<T>` in a `static` or `const` | `rt.LazyCell` and `rt.LazyLock`, which run their function on the first `force` or `Deref`, once; forced from within it, either panics as std's does |
| `AtomicU32` and the others of `bool` and integers, `AtomicPtr<T>` | `rt.Atomic<T>`, the `rt.Place` of its value; an `atomic::Ordering` is its discriminant, and one an operation can't take panics as std's does. An `AtomicPtr` compares pointers only to what JS keeps as an object, as raw pointers do |
| `async fn` | a function returning `rt.Future<T>`: a class of its own, its coroutine's state machine |
Expand Down
9 changes: 8 additions & 1 deletion ts/fixtures/lang/caller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,4 +292,11 @@ const locks = [[0, 1, 5, 6, 2, 7, 3, 8, 3, 0, 1], [4, 0, 4, 1], [2, 9, 2, 10, 4,
(bytes) => Uint8Array.of(op("locks::locks"), 0, ...bytes),
);

export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...dyns, ...cells, ...shared, ...locks];
/**
* `statics::onces` scripts: a `Once` forced, called, and forced again, which drops the
* function it never runs, each static's, and each `call_once` and `call_once_force` run
* again from within itself.
*/
const onces = [[1, 0, 1, 7], [0, 6, 1, 2, 3, 4, 5, 11], [2, 14, 8], [9], [3, 15]].map((bytes) => Uint8Array.of(op("statics::onces"), 0, ...bytes));

export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...dyns, ...cells, ...shared, ...locks, ...onces];
8 changes: 5 additions & 3 deletions ts/fixtures/lang/expected/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { refs, toRefs } from "./refs.ts";
import { copies as shapes_copies, order, discriminants, loops, patterns, closures, library, flows } from "./shapes.ts";
import { parts, drains } from "./slices.ts";
import { splits } from "./splits.ts";
import { statics, cells as statics_cells } from "./statics.ts";
import { statics, cells as statics_cells, onces } from "./statics.ts";
import { strs, slices } from "./strs.ts";
import { decodes } from "./utf8.ts";
import { wrappers } from "./wrappers.ts";
Expand Down Expand Up @@ -89,7 +89,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec)
refs(data21, out21);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::counts", (_2121: rt.u8, data22: rt.ByteSlice, out22: rt.ByteVec): void => {
counts(data22, out22);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _327: rt.ByteSlice, out23: rt.ByteVec): void => {
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _330: rt.ByteSlice, out23: rt.ByteVec): void => {
rounding(out23);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["iters::skips", skips] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["wrappers::wrappers", wrappers] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["edits::edits", edits] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["utf8::decodes", decodes] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::floats", floats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["atomics::atomics", atomics] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["keys::overrides", overrides] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["dyns::dyns", (_2123: rt.u8, data23: rt.ByteSlice, out24: rt.ByteVec): void => {
dyns(data23, out24);
Expand Down Expand Up @@ -161,7 +161,9 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec)
random(data56, out57);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::formats", formats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::parses", parses] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["orders::bytes", (_2157: rt.u8, data57: rt.ByteSlice, out58: rt.ByteVec): void => {
orders_bytes(data57, out58);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::parts", parts] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::drains", drains] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]).map(copy$str_forabfnu8au8bmutstdvecVecu8);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::parts", parts] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::drains", drains] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["statics::onces", (_2158: rt.u8, data58: rt.ByteSlice, out59: rt.ByteVec): void => {
onces(data58, out59);
}] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]).map(copy$str_forabfnu8au8bmutstdvecVecu8);
}

/** Run one case. */
Expand Down
53 changes: 53 additions & 0 deletions ts/fixtures/lang/expected/statics.Slot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Generated by rust2-ts. Do not edit.

import * as rt from "./rt.ts";

/**
* A value a `Once` guards, as crossbeam-epoch keeps its collector: written in
* `call_once`'s function, and read once `is_completed` says it ran.
*/
export interface Slot {
once: rt.Once;
value: rt.Atomic<rt.u32>;
}

function new_(): Slot {
return { once: new rt.OnceLock(undefined), value: new rt.Atomic(0) };
}

export function getOrInit$onces_closure5(self: Slot, f: () => rt.u32): rt.u32 {
if (!((self.once.v === true))) {
const captured = f;
rt.onceCall(self.once, (): void => {
const _32: rt.u32 = captured();
rt.atomicStore(self.value, _32, 0);
});
}
return rt.atomicLoad(self.value, 0);
}

export function getOrInit$onces_closure6(self: Slot, f: () => rt.u32): rt.u32 {
if (!((self.once.v === true))) {
const captured = f;
rt.onceCall(self.once, (): void => {
const _32: rt.u32 = captured();
rt.atomicStore(self.value, _32, 0);
});
}
return rt.atomicLoad(self.value, 0);
}

export function getOrInit$onces_closure7(self: Slot, f: () => rt.u32): rt.u32 {
if (!((self.once.v === true))) {
const captured = f;
rt.onceCall(self.once, (): void => {
const _32: rt.u32 = captured();
rt.atomicStore(self.value, _32, 0);
});
}
return rt.atomicLoad(self.value, 0);
}

export { new_ as new };

//# sourceMappingURL=statics.Slot.ts.map
70 changes: 70 additions & 0 deletions ts/fixtures/lang/expected/statics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { LATER, read } from "./statics/elsewhere.ts";
import type * as Counter from "./statics.Counter.ts";
import type * as Node from "./statics.Node.ts";
import type * as Raw from "./statics.Raw.ts";
import * as Slot from "./statics.Slot.ts";

export const COUNT: rt.Atomic<rt.u64> = /* @__PURE__ */ new rt.Atomic({ hi: 0xffffffff, lo: 0xfffffffd } as rt.u64);

Expand Down Expand Up @@ -225,4 +226,73 @@ export function cells(data: rt.ByteSlice, out: rt.ByteVec): void {
rt.atomicStore(COUNTER.hits, 4294967295 - 1, 0);
}

export const COLLECTOR: Slot.Slot = /* @__PURE__ */ { once: new rt.OnceLock(undefined), value: new rt.Atomic(0) };

export const STARTED: rt.Once = /* @__PURE__ */ new rt.OnceLock(undefined);

/**
* Each byte an operation on a `Once`, its own or a static's; each puts what it saw. One
* whose function runs again from within it panics, as wasm32's does, if its byte is odd.
*/
export function onces(data: rt.ByteSlice, out: rt.ByteVec): void {
const once: rt.Once = new rt.OnceLock(undefined);
const owned: rt.Arc<undefined> = new rt.Arc(undefined);
for (const op of rt.byteSliceView(data)) {
const n: rt.u8 = rt.u8Div(op, 6);
const _14: rt.u8 = rt.u8Rem(op, 6);
if (_14 === 0) {
rt.byteVecPush(out, once.v === true ? 1 : 0);
rt.onceCall(once, (): void => {
rt.byteVecPush(out, n);
});
rt.byteVecPush(out, once.v === true ? 1 : 0);
} else if (_14 === 1) {
const captured = rt.arcClone(owned);
rt.onceCall(once, rt.closure((state: rt.OnceState): void => {
rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(rt.onceIsPoisoned(state) ? 1 : 0, once.v === true ? 1 : 0, n)));
captured[Symbol.dispose]();
}, (): void => {
captured[Symbol.dispose]();
}), rt.drop);
rt.byteVecPush(out, owned.strong & 0xff);
} else if (_14 === 2) {
const fresh: rt.Once = new rt.OnceLock(undefined);
rt.onceCall(fresh, (): void => {
rt.byteVecPush(out, fresh.v === true ? 1 : 0);
if (rt.u8Rem(n, 2) === 1) {
rt.onceCall(fresh, (): void => {
rt.byteVecPush(out, 238);
});
}
});
rt.byteVecPush(out, fresh.v === true ? 1 : 0);
} else if (_14 === 3) {
if (!(rt.u8Rem(n, 2) === 1)) {
rt.onceCall(STARTED, (): void => {});
rt.byteVecPush(out, STARTED.v === true ? 1 : 0);
} else {
const fresh2: rt.Once = new rt.OnceLock(undefined);
rt.onceCall(fresh2, (_23: rt.OnceState): void => {
rt.onceCall(fresh2, (_24: rt.OnceState): void => {
rt.byteVecPush(out, 238);
});
});
}
} else if (_14 === 4) {
rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(Slot.getOrInit$onces_closure5(COLLECTOR, (): rt.u32 => {
return 16909060;
})).reverse()));
} else {
const slot: Slot.Slot = Slot.new();
rt.byteVecPush(out, Slot.getOrInit$onces_closure6(slot, (): rt.u32 => {
return n as rt.u32;
}) & 0xff);
rt.byteVecPush(out, Slot.getOrInit$onces_closure7(slot, (): rt.u32 => {
return 238;
}) & 0xff);
}
}
owned[Symbol.dispose]();
}

//# sourceMappingURL=statics.ts.map
1 change: 1 addition & 0 deletions ts/fixtures/lang/src/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ fn cases() -> Vec<(&'static str, Case)> {
("orders::bytes", |_, data, out| orders::bytes(data, out)),
("slices::parts", slices::parts),
("slices::drains", slices::drains),
("statics::onces", |_, data, out| statics::onces(data, out)),
]
}

Expand Down
94 changes: 88 additions & 6 deletions ts/fixtures/lang/src/statics.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
//! `static` atomics, each one value every use shares: of every kind, at module level and
//! in a function, as kio's `waiter` keeps its ids, starting from a value of the type's
//! extremes. Statics of any type, read from the memory rustc evaluated: a struct holding
//! an atomic, an `AtomicPtr` as parking_lot keeps its table in, std's `OnceLock` and
//! `LazyLock`, and one pointing at a static of a module that reads it back; and `const`s
//! holding cells, each use of which is a value of its own, as lock_api's `RawMutex::INIT`
//! is. Each case leaves every static as it found it, or reads only what it holds whatever
//! ran before, so a fresh instance and a reused one agree.
//! an atomic, an `AtomicPtr` as parking_lot keeps its table in, std's `OnceLock`,
//! `LazyLock`, and `Once`, one in a struct as crossbeam-epoch keeps its collector, and one
//! pointing at a static of a module that reads it back; and `const`s holding cells, each
//! use of which is a value of its own, as lock_api's `RawMutex::INIT` is. Each case leaves
//! every static as it found it, or reads only what it holds whatever ran before, so a fresh
//! instance and a reused one agree.

use std::cell::LazyCell;
use std::mem::MaybeUninit;
use std::ptr;
use std::rc::Rc;
use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, SeqCst};
use std::sync::atomic::{AtomicBool, AtomicI8, AtomicI64, AtomicPtr, AtomicU8, AtomicU32, AtomicU64, AtomicUsize};
use std::sync::{LazyLock, OnceLock};
use std::sync::{LazyLock, Once, OnceLock};

static COUNT: AtomicU64 = AtomicU64::new(u64::MAX - 2);
static SIGNED: AtomicI8 = AtomicI8::new(-128);
Expand Down Expand Up @@ -245,3 +247,83 @@ pub fn cells(data: &[u8], out: &mut Vec<u8>) {
}
COUNTER.hits.store(u32::MAX - 1, Relaxed);
}

/// A value a `Once` guards, as crossbeam-epoch keeps its collector: written in
/// `call_once`'s function, and read once `is_completed` says it ran.
struct Slot {
once: Once,
value: AtomicU32,
}

impl Slot {
const fn new() -> Self {
Self {
once: Once::new(),
value: AtomicU32::new(0),
}
}

fn get_or_init(&self, f: impl FnOnce() -> u32) -> u32 {
if !self.once.is_completed() {
self.once.call_once(|| self.value.store(f(), Relaxed));
}
self.value.load(Relaxed)
}
}

/// Filled by the first call that gets here, with the value every call gives.
static COLLECTOR: Slot = Slot::new();

/// Run by the first call that gets here.
static STARTED: Once = Once::new();

/// Each byte an operation on a `Once`, its own or a static's; each puts what it saw. One
/// whose function runs again from within it panics, as wasm32's does, if its byte is odd.
pub fn onces(data: &[u8], out: &mut Vec<u8>) {
let once = Once::new();
// Owned by each function `call_once` drops uncalled.
let owned = Rc::new(());
for &op in data {
let n = op / 6;
match op % 6 {
0 => {
out.push(u8::from(once.is_completed()));
once.call_once(|| out.push(n));
out.push(u8::from(once.is_completed()));
}
1 => {
let held = Rc::clone(&owned);
once.call_once_force(|state| {
out.extend([u8::from(state.is_poisoned()), u8::from(once.is_completed()), n]);
drop(held);
});
out.push(Rc::strong_count(&owned) as u8);
}
2 => {
let fresh = Once::new();
fresh.call_once(|| {
out.push(u8::from(fresh.is_completed()));
if n % 2 == 1 {
fresh.call_once(|| out.push(0xee));
}
});
out.push(u8::from(fresh.is_completed()));
}
3 if n % 2 == 1 => {
let fresh = Once::new();
fresh.call_once_force(|_| fresh.call_once_force(|_| out.push(0xee)));
}
3 => {
STARTED.call_once(|| {});
out.push(u8::from(STARTED.is_completed()));
}
4 => out.extend(COLLECTOR.get_or_init(|| 0x0102_0304).to_le_bytes()),
_ => {
// The first function given runs, and the second never does.
let slot = Slot::new();
out.push(slot.get_or_init(|| u32::from(n)) as u8);
out.push(slot.get_or_init(|| 0xee) as u8);
}
}
}
}
20 changes: 20 additions & 0 deletions ts/runtime/rt/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,26 @@ export function onceGetOrInit<T>(cell: OnceCell<T, None | undefined>, f: () => T
return value;
}

/** `Once`: a `OnceLock` that holds `true` once its function has run. */
export type Once = OnceLock<true>;

/** `OnceState`: the `Once` running the function given it, which nothing poisons, as a panic aborts. */
export type OnceState = Once;

/**
* `Once::call_once` and `call_once_force`: runs `f` if `once` has not run one, or else
* drops it by `dropF`. Run again from within `f`, it panics as `recursive` does.
*/
export function onceCall(once: Once, f: (state: OnceState) => void, dropF?: (f: (state: OnceState) => void) => void): void {
if (once.v) dropF?.(f);
else onceGetOrInit(once, () => (f(once), true));
}

/** `OnceState::is_poisoned`: never, as a panic aborts rather than poison a `Once`. */
export function onceIsPoisoned(_state: OnceState): boolean {
return false;
}

/**
* `LazyCell<T>`: the function that makes its value until the first `force` runs it, once,
* and then that value. Forced from within that function, it panics as std's does.
Expand Down
Loading