diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index 67daeb410..1d39cb443 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -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 diff --git a/quest/m2/ts-model/once.md b/quest/m2/ts-model/once.md deleted file mode 100644 index 0d91a0494..000000000 --- a/quest/m2/ts-model/once.md +++ /dev/null @@ -1,23 +0,0 @@ -# [S] A std Once in a static - -## Goal - -rust2-ts translates std's `Once`, read from a static's memory and called through -`call_once` and `call_once_force`, so crossbeam-epoch's own `OnceLock` static -translates, proven by differential tests against native Rust. - -## Plan - -Left by [#255](https://github.com/moq-dev/rust2/pull/255) on 2026-10-29: statics read from memory now translate std's -`OnceLock` and `LazyLock`, but crossbeam-epoch keeps its own `OnceLock` over a bare `Once`, -which has no runtime counterpart. The model's census refuses it at -`crossbeam-epoch-0.9.21/src/default.rs:18`, once as the static's `Once` and once as -`Once::call_once`. - -- An `rt.Once`, a state as wasm32's `no_threads` one is: incomplete, running, or - complete. A `Once` read from memory is incomplete, as const evaluation leaves it, and any - other state is refused. -- `call_once` from within its own function panics as wasm32's does, which `once.ts` can - check beside `OnceLock`'s. - -Public API: the translator's output. diff --git a/quest/m2/ts-model/unsafe-cell.md b/quest/m2/ts-model/unsafe-cell.md new file mode 100644 index 000000000..ae331f50f --- /dev/null +++ b/quest/m2/ts-model/unsafe-cell.md @@ -0,0 +1,23 @@ +# [M] std's UnsafeCell + +## Goal + +rust2-ts translates std's `UnsafeCell`, 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` 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>`: 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`. + +Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index 0afaa8f3e..eca6e8888 100644 --- a/ts/README.md +++ b/ts/README.md @@ -112,6 +112,7 @@ crate translation reaches is refused, and so are two versions of one crate it re | `Cell`, `RefCell`, `RwLock` | `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` | 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`, `OnceLock` | `rt.OnceCell` and `rt.OnceLock`, holding the `Option` 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`, `LazyLock` 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` | `rt.Atomic`, 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`: a class of its own, its coroutine's state machine | diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index 1a1e2ce21..dfe5820d7 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -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]; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 53c3aaa51..eab8e20f0 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -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"; @@ -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); @@ -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. */ diff --git a/ts/fixtures/lang/expected/statics.Slot.ts b/ts/fixtures/lang/expected/statics.Slot.ts new file mode 100644 index 000000000..cc98cc4b0 --- /dev/null +++ b/ts/fixtures/lang/expected/statics.Slot.ts @@ -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; +} + +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 diff --git a/ts/fixtures/lang/expected/statics.ts b/ts/fixtures/lang/expected/statics.ts index eafcd4d9c..842a1daa7 100644 --- a/ts/fixtures/lang/expected/statics.ts +++ b/ts/fixtures/lang/expected/statics.ts @@ -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 = /* @__PURE__ */ new rt.Atomic({ hi: 0xffffffff, lo: 0xfffffffd } as rt.u64); @@ -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 = 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 diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index f722e3c1d..27b8d0760 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -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)), ] } diff --git a/ts/fixtures/lang/src/statics.rs b/ts/fixtures/lang/src/statics.rs index 5cf8db275..95829541d 100644 --- a/ts/fixtures/lang/src/statics.rs +++ b/ts/fixtures/lang/src/statics.rs @@ -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); @@ -245,3 +247,83 @@ pub fn cells(data: &[u8], out: &mut Vec) { } 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) { + 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); + } + } + } +} diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 0f98ee35d..3f149f38e 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -660,6 +660,26 @@ export function onceGetOrInit(cell: OnceCell, f: () => T return value; } +/** `Once`: a `OnceLock` that holds `true` once its function has run. */ +export type Once = OnceLock; + +/** `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`: 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. diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 708c6ef94..e1b4712a5 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -76,6 +76,9 @@ pub enum Std { /// `rt.OnceCell` and `rt.OnceLock`: the `Option` each holds. OnceCell, OnceLock, + /// `rt.Once`, an `rt.OnceLock` of `true`, and `rt.OnceState`, the `Once` it reports on. + Once, + OnceState, /// `rt.LazyCell` and `rt.LazyLock`: the function that makes the value, then the value. LazyCell, LazyLock, @@ -256,6 +259,8 @@ impl Std { ["sync", "atomic", "Ordering"] => Some(Self::AtomicOrdering), ["cell", "once", "OnceCell"] => Some(Self::OnceCell), ["sync", "once_lock", "OnceLock"] => Some(Self::OnceLock), + ["sync", "once", "Once"] => Some(Self::Once), + ["sync", "once", "OnceState"] => Some(Self::OnceState), ["cell", "lazy", "LazyCell"] => Some(Self::LazyCell), ["sync", "lazy_lock", "LazyLock"] => Some(Self::LazyLock), ["cmp", "Reverse"] => Some(Self::Reverse), @@ -645,6 +650,7 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { ("Vec", "retain" | "retain_mut" | "dedup" | "dedup_by" | "dedup_by_key" | "truncate" | "clear") => &[0], // `get_or_init::` drops its function uncalled if the cell is set. ("OnceCell" | "OnceLock", "get_or_init") => &[1], + ("Once", "call_once" | "call_once_force") => &[0], ("Arc" | "Rc", "new_cyclic") => &[1], // `is_sorted_by::` drops its comparator before the last item, as `all` takes it. ("Iterator", "is_sorted_by") => &[1], diff --git a/ts/src/lower/mir/memory.rs b/ts/src/lower/mir/memory.rs index 9277a18b8..2e374f84a 100644 --- a/ts/src/lower/mir/memory.rs +++ b/ts/src/lower/mir/memory.rs @@ -53,6 +53,8 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { } _ => self.unreadable(ty, span), }, + Some(Std::Once) if self.incomplete(val, ty) => crate::lower::task::once_unrun(), + Some(Std::Once) => self.unreadable(ty, span), // Its function, which the first `force` runs. Some(Std::LazyCell) => match self.variant_fields(val, ty) { Some((variant, fields)) if variant == "Uninit" => self.lazy("LazyCell", fields[0], span), diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 0cd69a8f1..fd8236dca 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -1151,6 +1151,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { | library::Std::Atomic | library::Std::OnceCell | library::Std::OnceLock + | library::Std::Once + | library::Std::OnceState | library::Std::LazyCell | library::Std::LazyLock | library::Std::Waker @@ -1467,6 +1469,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { }; Type::Rt(name, args) } + library::Std::Once => Type::Rt("Once", vec![]), + library::Std::OnceState => Type::Rt("OnceState", vec![]), library::Std::LazyCell => Type::Rt("LazyCell", vec![self.ty(args.type_at(0), span)]), library::Std::LazyLock => Type::Rt("LazyLock", vec![self.ty(args.type_at(0), span)]), library::Std::Waker => Type::Rt("Waker", vec![]), diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 5d9a53541..d420589c4 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -277,6 +277,17 @@ pub fn call<'tcx>( ("Atomic", _) => return atomic(b, call, name, args), ("LazyCell" | "LazyLock", "force") => first(args).member("force").call(vec![]), ("OnceCell" | "OnceLock", _) => return once(b, call, name, args), + // A `OnceLock` of `true`, which nothing poisons, as a panic aborts. + ("Once", "new") => once_unrun(), + ("Once", "is_completed") => first(args).member("v").binary("===", Expr::lit("true")), + // With what drops `f`, as `discards` says, uncalled if the `Once` has run. + ("Once", "call_once" | "call_once_force") => { + let Some(droppers) = b.t.droppers([call.args.type_at(0)], call.span) else { + return Ok(Some(Expr::undefined())); + }; + Expr::rt("onceCall", args.into_iter().chain(droppers).collect()) + } + ("OnceState", "is_poisoned") => Expr::rt("onceIsPoisoned", args), ("From", "from") if matches!(self_std, Some(Std::OnceCell | Std::OnceLock)) => { let cell = self_ty.expect("a `From` impl's type"); Expr::New(Box::new(Expr::Rt(once_class(b, cell).into())), args) @@ -516,6 +527,11 @@ pub fn once_new<'tcx>(b: &Body<'_, '_, 'tcx>, cell: Ty<'tcx>) -> Expr { ) } +/// `Once::new()`: an `rt.OnceLock` holding nothing, as no function has run. +pub fn once_unrun() -> Expr { + Expr::New(Box::new(Expr::Rt("OnceLock".into())), vec![Expr::undefined()]) +} + /// The runtime class of `cell`, a `OnceCell` or `OnceLock`. fn once_class<'tcx>(b: &Body<'_, '_, 'tcx>, cell: Ty<'tcx>) -> &'static str { match b.t.std_of(cell) {