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
1 change: 1 addition & 0 deletions quest/m2/ts-model/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Public API: the translator's output for moq-net's model.
- [Shared ownership](/quest/m2/ts-shared.md) - kio's waiters are `Arc`/`Weak` with observable counts, and its atomics and locks are plain values
- [Translate safe dependencies with the package](/quest/m2/ts-model/crates.md) - kio, moq-clock, moq-pattern, and rangemap translate as one program with moq-net
- [Std gaps the model reaches](/quest/m2/ts-model/std-more.md) - ranges, wrappers, and `Vec`'s editing methods
- [Floats](/quest/m2/ts-model/floats.md) - `f64` translates, so `Bandwidth::scaled` and `Duration::mul_f64` do
- [Std's mutable references to values JS copies](/quest/m2/ts-model/std-places.md) - `as_mut`, `get_or_insert`, `iter_mut`, and the rest give an `rt.Place`
- [The rest of std the model reaches](/quest/m2/ts-model/std-rest.md) - the std calls the census still refuses
- [Well-known crates without config](/quest/m2/ts-model/stock.md) - rust2-ts maps `bytes`, `rand`, and `tracing` itself, so `model.toml` stops binding and ignoring them
Expand Down
35 changes: 35 additions & 0 deletions quest/m2/ts-model/floats.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# [L] Floats

## Goal

[rust2-ts](/ts/README.md) translates `f64`: its arithmetic, comparisons, `as` casts to and
from every integer width, its methods and constants, `str::parse`, its formatting, and
`Duration`'s `f64` methods, proven by differential tests against native Rust. moq-net's
`Bandwidth::scaled`, its probe thresholds, and its `Duration::mul_f64` jitter translate.

## Plan

Decided with the maintainer on 2026-10-27, from
[#135](https://github.com/kixelated/rust2/pull/135):

- `f64` here, since moq-net uses it; [`f32`](/quest/m3/ts-f32.md) follows in m3.
- An `f64` is a JS number. Every operation std specifies exactly matches native bit for
bit, including where JS differs: `round` rounds half away from zero, `max` and `min`
ignore a NaN, a cast to an integer saturates and sends NaN to 0, and a 64- or 128-bit
integer rounds to the nearest `f64` once. `str::parse` follows std's grammar, not
`Number`'s.
- The functions std leaves to the platform's libm (`sin`, `exp`, `ln`, `powf`, `powi`, and
the rest) map to `Math.*`. Their tests compare within a small ULP bound the README
states, not an exact libm port. `mul_add` is specified as one rounding, which `Math`
has no cheap form of, so it is refused with a span until a consumer needs it.
- `to_bits` and `from_bits` go through a `DataView`. JS does not guarantee a NaN's
payload, so the tests cover payloads in Node and Chrome and the README notes it.
- This quest owns float formatting byte for byte as `core::fmt`: `Display`, `Debug`
(which switches to an exponent), a precision, and `{:e}`/`{:E}`.
The other types' format specs already translate.
- `Duration`'s `f64` methods (`as_secs_f64`, `from_secs_f64`, `mul_f64`, `div_f64`,
`div_duration_f64`, and the `try_` forms) port std's integer algorithms, with its
panics and `Err`s at `u64::MAX` seconds, negative values, and NaN.
- Report the model's census before and after.

Public API: the translator's output.
2 changes: 1 addition & 1 deletion quest/m3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ generic std gap is planned here even when moq never calls it.
- [Retrial Cranelift on moq's tests](/quest/m3/cranelift-unwind.md) - waits on upstream: moq's tests pass under Cranelift, so its CI can weigh it again
- [Relink without rebuilding](/quest/m3/relink.md) - measure upstream's skip of dependency-only rebuilds on moq's edits once it reaches nightly
- [Unsafe code the translator can model](/quest/m3/ts-unsafe.md) - a dependency using only `unsafe` the translator can model translates from source
- [The rest of Duration](/quest/m3/ts-duration.md) - compound assignment, float conversions, and `Sum` on a `Duration` translate
- [f32](/quest/m3/ts-f32.md) - `f32` and `Duration`'s `f32` methods translate as `f64` does
- [Trait objects](/quest/m3/ts-dyn.md) - `dyn Trait` and `Box<dyn Future>` translate, so a consumer neither rewrites nor binds them
- [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library
- [Fold matches across tests that aren't variant switches](/quest/m3/ts-fold-guards.md) - a match an `if` or guard decided drops its dead arms
Expand Down
24 changes: 0 additions & 24 deletions quest/m3/ts-duration.md

This file was deleted.

24 changes: 24 additions & 0 deletions quest/m3/ts-f32.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# [M] f32

## Goal

[rust2-ts](/ts/README.md) translates `f32` as it translates `f64`, including casts between
them, its formatting, and `Duration`'s `f32` methods, proven by differential tests against
native Rust.

## Plan

Decided with the maintainer on 2026-10-27: rust2 aims to support all of std, so this is
planned without a moq consumer. The decisions of [floats](/quest/m2/ts-model/floats.md)
carry over.

- An `f32` is a JS number rounded with `Math.fround` after every operation. A 64- or
128-bit integer rounds to `f32` once, never through `f64`, which would round twice.
- Formatting prints the shortest digits that round-trip as an `f32`, as `core::fmt` does,
which JS's number formatting cannot give.

Public API: the translator's output.

## Required

- [Floats](/quest/m2/ts-model/floats.md) - `f64` translates, with the formatting and casts `f32` builds on
2 changes: 1 addition & 1 deletion ts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ they need.
Until they translate, an item that needs one, such as a boxed future, binds to
hand-written TS ([bindings](#bindings)).

These fail translation: floats, statics, async closures, a closure that owns a value
These fail translation: floats ([Floats](/quest/m2/ts-model/floats.md)), statics, async closures, a closure that owns a value
that drops given to std's iterators or collections, and values that drop in some
iterators ([Drop](/quest/m2/ts-drop.md)), a `Cow` of other than `str`,
a collection holding a type that can be `undefined`, as `()` and `Option` can, a std
Expand Down
18 changes: 16 additions & 2 deletions ts/fixtures/lang/caller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,29 @@ function duration(secs: bigint, nanos: number): number[] {

/**
* `durations` where seconds leave a safe integer or reach `u64::MAX`, nanoseconds carry,
* and a factor makes the nanoseconds' product or a quotient's remainder pass 2^53.
* a sum carries them past it, and a factor makes the nanoseconds' product or a
* quotient's remainder pass 2^53.
*/
const edges = [0n, 1n, (1n << 53n) - 1n, 1n << 53n, (1n << 64n) - 1n].flatMap((secs) => [0, 1, 999_999_999].map((nanos) => duration(secs, nanos)));
const factors = [0, 1, 3, 1000, 9_007_199, 1_000_000_000, 0xffffffff].map((n) => [n >>> 24, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]);
const durations = [
...[0n, 1n, 1n << 32n, (1n << 53n) - 1n, 1n << 53n, (1n << 64n) - 2n, (1n << 64n) - 1n].flatMap((secs) =>
[0, 1, 999_999_999, 1_000_000_000, 0xffffffff].flatMap((nanos) => [0, 1].map((kind) => Uint8Array.of(47, kind, ...duration(secs, nanos)))),
),
...edges.flatMap((a) => edges.flatMap((b) => factors.flatMap((n) => [2, 3, 4, 5, 6, 7, 8, 9].map((kind) => Uint8Array.of(47, kind, ...a, ...b, ...n))))),
...edges.flatMap((a) => edges.flatMap((b) => factors.flatMap((n) => [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13].map((kind) => Uint8Array.of(47, kind, ...a, ...b, ...n))))),
// Each side of where minutes, hours, and a `u128` of nanoseconds pass `u64::MAX` seconds.
...[2n ** 64n / 60n, 2n ** 64n / 3600n].flatMap((units) => [units, units + 1n].map((n) => wide(n << 64n))),
...[(7n << 64n) + 999_999_999n, 2n ** 64n * 1_000_000_000n - 1n, 2n ** 64n * 1_000_000_000n, 2n ** 128n - 1n].map((n) => wide(n)),
];

/** `durations`' larger units, of a `u128` whose high half is also its `u64`. */
function wide(n: bigint): Uint8Array {
const bytes = new Uint8Array(18);
bytes.set([47, 12]);
const view = new DataView(bytes.buffer);
view.setBigUint64(2, n >> 64n);
view.setBigUint64(10, n & 0xffff_ffff_ffff_ffffn);
return bytes;
}

export const cases: Uint8Array[] = [...loops, ...durations];
10 changes: 10 additions & 0 deletions ts/fixtures/lang/expected/durations.Twice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Generated by rust2-ts. Do not edit.

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

/** The crate's own `+=` onto a `Duration`, which adds twice. */
export interface Twice {
_0: rt.Duration;
}

//# sourceMappingURL=durations.Twice.ts.map
84 changes: 70 additions & 14 deletions ts/fixtures/lang/expected/durations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import * as rt from "./rt.ts";
import { copy$Window } from "./lib.ts";
import type * as Twice from "./durations.Twice.ts";
import * as Window from "./durations.Window.ts";
import { put } from "./fmt.ts";

Expand Down Expand Up @@ -46,6 +47,16 @@ export function putOpt(out: rt.ByteVec, d: rt.Duration | undefined): void {
}
}

export function addAssign$AddAssign_Twice_Duration(self: rt.Place<rt.Duration>, by: Twice.Twice): void {
self.v = rt.durationAdd(self.v, by._0);
self.v = rt.durationAdd(self.v, by._0);
}

/** `-=` through a `&mut`, which is an `rt.Place`. */
export function shrink(d: rt.Place<rt.Duration>, by: rt.Duration): void {
d.v = rt.durationSub(d.v, by);
}

export function durations(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void {
const _6: [rt.Duration, rt.ByteSlice] = duration(data);
const a: rt.Duration = _6[0];
Expand All @@ -55,7 +66,7 @@ export function durations(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi
const k: rt.usize = rt.min(_9[1].length, rt.byteSliceFrom(word).length);
rt.byteSliceCopyFromSlice(rt.byteSliceRange(rt.byteSliceFrom(word), 0, k), rt.byteSliceRange(_9[1], 0, k));
const n: rt.u32 = rt.u32FromBeBytes(word);
const _24: rt.u8 = rt.u8Rem(kind, 10);
const _24: rt.u8 = rt.u8Rem(kind, 14);
if (_24 === 0) {
const _28: [rt.u64, rt.u32, rt.ByteSlice] = take(data);
putDuration(out, rt.durationNew(_28[0], _28[1]));
Expand Down Expand Up @@ -157,28 +168,73 @@ export function durations(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi
const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.durationDebug(part, f)];
put(out, rt.fmtFormat([rt.fmtSpec({ precision: 0 }, args6[0]), " ", rt.fmtSpec({ precision: 1 }, args6[0]), " ", rt.fmtSpec({ precision: 2 }, args6[0])]));
}
} else if (_24 === 10) {
let c2: rt.Duration = a;
c2 = rt.durationAdd(c2, b);
putDuration(out, c2);
const w: Window.Window = { start: c2, len: b };
w.start = rt.durationSub(w.start, b);
putDuration(out, w.start);
if (w.len !== undefined) {
const _283: rt.Duration = rt.ordMin(a, b, rt.durationCmp);
w.len = rt.durationSub(w.len, _283);
}
putOpt(out, w.len);
const v: rt.Duration[] = [a, b];
v[1] = rt.durationAdd(v[1], a);
putDuration(out, v[1]);
shrink(rt.place(() => v[0], (value) => v[0] = value), b);
putDuration(out, v[0]);
let d5: rt.Duration = a;
const _306: Twice.Twice = { _0: b };
addAssign$AddAssign_Twice_Duration(rt.place(() => d5, (value2) => d5 = value2), _306);
putDuration(out, d5);
} else if (_24 === 11) {
let c3: rt.Duration = a;
c3 = rt.durationMul(c3, n);
putDuration(out, c3);
const v2: rt.Duration[] = [a];
const at = rt.idx(v2, 0);
v2[at] = rt.durationDiv(v2[at], n);
putDuration(out, v2[rt.idx(v2, 0)]);
} else if (_24 === 12) {
const units2: rt.u64 = take(data)[0];
const wide: Uint8Array = rt.bytes(16);
const k2: rt.usize = rt.min(data.length, rt.byteSliceFrom(wide).length);
rt.byteSliceCopyFromSlice(rt.byteSliceRange(rt.byteSliceFrom(wide), 0, k2), rt.byteSliceRange(data, 0, k2));
putDuration(out, rt.durationFromMins(units2));
putDuration(out, rt.durationFromHours(units2));
putDuration(out, rt.durationFromNanosU128(rt.u128FromBeBytes(wide)));
} else if (_24 === 13) {
const _346: rt.Duration = rt.durationNew(0, rt.u32Rem(n, 1000000000));
const parts: rt.Duration[] = [a, b, _346];
putDuration(out, rt.durationSum(rt.iterSlice(parts)));
putDuration(out, rt.durationSum(rt.iterSlice([b, a])));
putDuration(out, rt.durationSum(rt.iterFilter(rt.iterSlice(parts), (d7: rt.Duration): boolean => {
return !rt.durationIsZero(d7);
})));
} else {
const iter5: rt.Iter<rt.Duration> = rt.iterSlice([{ secs: 0, nanos: 0 }, { secs: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, nanos: 999999999 }, { secs: 0, nanos: 999 }]);
while (true) {
const _269: rt.Duration | rt.Done = iter5.next();
if (_269 === rt.DONE) {
const _367: rt.Duration | rt.Done = iter5.next();
if (_367 === rt.DONE) {
break;
}
putDuration(out, _269);
putDuration(out, _367);
}
putDuration(out, { secs: 1, nanos: 500000000 });
putDuration(out, { secs: 0, nanos: 0 });
putOpt(out, rt.durationCheckedAdd({ secs: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, nanos: 999999999 }, rt.durationFromNanos(1)));
const _281: rt.Duration | undefined = rt.thenSome(rt.durationCmp(b, { secs: 1, nanos: 500000000 }) === 1, b);
const w: Window.Window = { start: a, len: _281 };
const _290: Window.Window = Window.default$Default();
rt.byteVecPush(out, Window.eq$PartialEq(w, _290) ? 1 : 0);
rt.byteVecPush(out, Window.cmp$Ord(w, { start: b, len: undefined }) < 0 ? 1 : 0);
const _302: Window.Window = copy$Window(Window.default$Default());
const _300: rt.Iter<Window.Window> = rt.iterSlice([copy$Window(w), copy$Window(w), _302]);
rt.byteVecPush(out, rt.hashLen(rt.hashExtendKeys(rt.hashNew(rt.hashing(Window.hash$Hash_DefaultHasher, Window.eq$PartialEq)) as rt.HashSet<Window.Window>, _300)) & 0xff);
const _315: Window.Window = Window.default$Default();
const args8: rt.Fmt[] = [(f: rt.Formatter) => Window.fmt$Debug(w, f), (f: rt.Formatter) => Window.fmt$Debug(_315, f)];
const _379: rt.Duration | undefined = rt.thenSome(rt.durationCmp(b, { secs: 1, nanos: 500000000 }) === 1, b);
const w2: Window.Window = { start: a, len: _379 };
const _388: Window.Window = Window.default$Default();
rt.byteVecPush(out, Window.eq$PartialEq(w2, _388) ? 1 : 0);
rt.byteVecPush(out, Window.cmp$Ord(w2, { start: b, len: undefined }) < 0 ? 1 : 0);
const _400: Window.Window = copy$Window(Window.default$Default());
const _398: rt.Iter<Window.Window> = rt.iterSlice([copy$Window(w2), copy$Window(w2), _400]);
rt.byteVecPush(out, rt.hashLen(rt.hashExtendKeys(rt.hashNew(rt.hashing(Window.hash$Hash_DefaultHasher, Window.eq$PartialEq)) as rt.HashSet<Window.Window>, _398)) & 0xff);
const _413: Window.Window = Window.default$Default();
const args8: rt.Fmt[] = [(f: rt.Formatter) => Window.fmt$Debug(w2, f), (f: rt.Formatter) => Window.fmt$Debug(_413, f)];
put(out, rt.fmtFormat([args8[0], "|", rt.fmtSpec({ alternate: true }, args8[1])]));
}
}
Expand Down
71 changes: 68 additions & 3 deletions ts/fixtures/lang/src/durations.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! `Duration`: made from each unit and read back in each, added, subtracted, scaled, and
//! divided with std's checks and panics, compared, ordered, hashed, held in a field and
//! as a key, printed, and made by constants. Seconds past 2^53 and up to `u64::MAX` take
//! divided with std's checks and panics, in place through each kind of place, summed,
//! compared, ordered, hashed, held in a field and as a key, printed, and made by constants. Seconds past 2^53 and up to `u64::MAX` take
//! the runtime past its numbers; `caller.ts` names those cases.

use std::cmp::Ordering;
Expand Down Expand Up @@ -50,14 +50,29 @@ fn put_opt(out: &mut Vec<u8>, d: Option<Duration>) {
}
}

/// The crate's own `+=` onto a `Duration`, which adds twice.
struct Twice(Duration);

impl std::ops::AddAssign<Twice> for Duration {
fn add_assign(&mut self, by: Twice) {
*self += by.0;
*self += by.0;
}
}

/// `-=` through a `&mut`, which is an `rt.Place`.
fn shrink(d: &mut Duration, by: Duration) {
*d -= by;
}

pub fn durations(kind: u8, data: &[u8], out: &mut Vec<u8>) {
let (a, rest) = duration(data);
let (b, rest) = duration(rest);
let mut word = [0u8; 4];
let k = rest.len().min(word.len());
word[..k].copy_from_slice(&rest[..k]);
let n = u32::from_be_bytes(word);
match kind % 10 {
match kind % 14 {
0 => {
// `new`, which carries nanoseconds past a second and panics past `u64::MAX`.
let (secs, nanos, _) = take(data);
Expand Down Expand Up @@ -156,6 +171,56 @@ pub fn durations(kind: u8, data: &[u8], out: &mut Vec<u8>) {
put(out, &format!("{d:.0?} {d:.1?} {d:.2?}"));
}
}
10 => {
// `+=` and `-=` on a local, a field, what an `Option`'s `&mut` borrows, an
// element, and through a `&mut`, each panicking as `+` and `-` do, and the
// crate's own `+=`.
let mut c = a;
c += b;
put_duration(out, c);
let mut w = Window { start: c, len: Some(b) };
w.start -= b;
put_duration(out, w.start);
if let Some(len) = &mut w.len {
*len -= a.min(b);
}
put_opt(out, w.len);
let mut v = [a, b];
v[1] += a;
put_duration(out, v[1]);
shrink(&mut v[0], b);
put_duration(out, v[0]);
let mut d = a;
d += Twice(b);
put_duration(out, d);
}
11 => {
// `*=` and `/=` by a `u32`, the last by zero panicking.
let mut c = a;
c *= n;
put_duration(out, c);
let mut v = vec![a];
v[0] /= n;
put_duration(out, v[0]);
}
12 => {
// Each larger unit, panicking past `u64::MAX` seconds, minutes before hours.
let (units, _, _) = take(data);
let mut wide = [0u8; 16];
let k = data.len().min(wide.len());
wide[..k].copy_from_slice(&data[..k]);
put_duration(out, Duration::from_mins(units));
put_duration(out, Duration::from_hours(units));
put_duration(out, Duration::from_nanos_u128(u128::from_be_bytes(wide)));
}
13 => {
// `Sum` of values and of references, whose nanoseconds carry at the end, past
// `u64::MAX` seconds a panic.
let parts = [a, b, Duration::new(0, n % 1_000_000_000)];
put_duration(out, parts.iter().sum());
put_duration(out, [b, a].into_iter().sum::<Duration>());
put_duration(out, parts.iter().filter(|d| !d.is_zero()).copied().sum());
}
_ => {
// Constants, `Default`, and a field.
for d in LIMITS {
Expand Down
Loading