From 4c39a334f775b6dd6e1f7964b393d675f6a3be90 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:12:53 -0700 Subject: [PATCH 1/6] chore(quest): claim quest/m3/ts-duration.md Quest-Claim: f957c8e279f937fe From 524b4e1dfe13c4b7894266a1a1c0ebd012c62410 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:55:15 -0700 Subject: [PATCH 2/6] feat(ts): translate Duration's compound assignment, larger units, and Sum `+=`, `-=`, `*=`, and `/=` on a `Duration` assign a new value to the place the `&mut` borrows, as `String::push` does. `from_mins`, `from_hours`, `from_nanos_u128`, and `Iterator::sum` map to runtime functions with std's panics, `Sum` carrying nanoseconds as std's does. The float methods stay in the quest: they wait on floats, which rust2-ts refuses everywhere. Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 2 +- quest/m3/ts-duration.md | 24 ++++----- ts/fixtures/lang/caller.ts | 18 ++++++- ts/fixtures/lang/expected/durations.ts | 74 +++++++++++++++++++++----- ts/fixtures/lang/src/durations.rs | 57 ++++++++++++++++++-- ts/fixtures/reject/census.md | 29 +++++----- ts/fixtures/reject/expected.txt | 10 ++-- ts/fixtures/reject/src/lib.rs | 6 --- ts/runtime/rt/time.ts | 48 ++++++++++++++++- ts/src/lower/iter.rs | 5 ++ ts/src/lower/mir/call.rs | 16 ++++++ ts/src/lower/time.rs | 3 ++ 12 files changed, 230 insertions(+), 62 deletions(-) diff --git a/quest/m3/README.md b/quest/m3/README.md index 5a8e4f81c..6b926799e 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -16,6 +16,6 @@ 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 +- [Duration's float methods](/quest/m3/ts-duration.md) - `as_secs_f64`, `from_secs_f64`, and the other float methods on a `Duration` translate, once floats do - [The rest of format specs](/quest/m3/ts-fmt-specs.md) - precision, argument widths, `+`, and the other radixes format as `core::fmt` does - [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 diff --git a/quest/m3/ts-duration.md b/quest/m3/ts-duration.md index 99361c53b..4e9665698 100644 --- a/quest/m3/ts-duration.md +++ b/quest/m3/ts-duration.md @@ -1,24 +1,20 @@ -# [M] The rest of Duration +# [M] Duration's float methods ## Goal -rust2-ts translates the rest of `std::time::Duration`'s API that -[#125](https://github.com/kixelated/rust2/pull/125) refuses, with std's results, rounding, -and panics, proven by differential tests against native Rust: compound assignment -(`+=`, `-=`, `*=`, `/=`) on a place, the float methods (`as_secs_f64`, `from_secs_f64`, -`mul_f64`, `div_duration_f64`, and their `f32` and `try_` forms), `from_mins`, -`from_hours`, `from_nanos_u128`, and `Sum`. +rust2-ts translates `std::time::Duration`'s float methods (`as_secs_f64`, +`from_secs_f64`, `mul_f64`, `div_f64`, `div_duration_f64`, and their `f32` and `try_` +forms) with std's results, rounding, and panics, proven by differential tests against +native Rust. ## Plan Decided with the maintainer on 2026-10-27: rust2 aims to support all of std, so generic -gaps are planned without a moq consumer. Nothing in moq-net, moq-clock, or kio uses these -on a `Duration` itself today; moq-clock's `Instant += Duration` is its own `AddAssign`, -which translates from source with [crates](/quest/m2/ts-model/crates.md). +gaps are planned without a moq consumer. Nothing in moq-net, moq-clock, or kio uses these. -- `rt.Duration` is immutable, so compound assignment assigns a new value to the place, as - `String::push` does for a JS string. -- The float conversions must match std's rounding exactly, including at `u64::MAX` - seconds and for values a `f64` cannot hold, which std rejects with a panic or an `Err`. +- Blocked on floats: rust2-ts refuses `f32` and `f64` wherever they appear, so no value + these methods take or return translates yet. Floats need their own quest first. +- The conversions must match std's rounding exactly, including at `u64::MAX` seconds and + for values a `f64` cannot hold, which std rejects with a panic or an `Err`. Public API: the translator's output. diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index 48ff8bae3..6d81f0c79 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -38,7 +38,8 @@ 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]); @@ -46,7 +47,20 @@ 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]; diff --git a/ts/fixtures/lang/expected/durations.ts b/ts/fixtures/lang/expected/durations.ts index 518e0bd49..39abfbc69 100644 --- a/ts/fixtures/lang/expected/durations.ts +++ b/ts/fixtures/lang/expected/durations.ts @@ -46,6 +46,11 @@ export function putOpt(out: rt.ByteVec, d: rt.Duration | undefined): void { } } +/** `-=` through a `&mut`, which is an `rt.Place`. */ +export function shrink(d: rt.Place, 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]; @@ -55,7 +60,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])); @@ -144,28 +149,69 @@ export function durations(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi const d2: rt.Duration = rt.durationFromNanos(rt.u32Rem(n, 1000000) as rt.u64); const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.durationDebug(a, f), (f: rt.Formatter) => rt.durationDebug(c, f), (f: rt.Formatter) => rt.durationDebug(d2, f), (f: rt.Formatter) => rt.fmtOption(_212, f, rt.durationDebug)]; put(out, rt.fmtFormat([args2[0], "|", args2[1], "|", args2[2], "|", rt.fmtSpec({ align: ">", width: 16 }, args2[1]), "|", rt.fmtSpec({ fill: "*", align: "^", width: 14 }, args2[2]), "|", rt.fmtSpec({ align: "<", width: 12 }, args2[1]), "|", rt.fmtSpec({ zero: true, width: 8 }, args2[0]), "|", args2[3]])); + } 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 _239: rt.Duration = rt.ordMin(a, b, rt.durationCmp); + w.len = rt.durationSub(w.len, _239); + } + 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]); + } 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 _296: rt.Duration = rt.durationNew(0, rt.u32Rem(n, 1000000000)); + const parts: rt.Duration[] = [a, b, _296]; + putDuration(out, rt.durationSum(rt.iterSlice(parts))); + putDuration(out, rt.durationSum(rt.iterSlice([b, a]))); + putDuration(out, rt.durationSum(rt.iterFilter(rt.iterSlice(parts), (d4: rt.Duration): boolean => { + return !rt.durationIsZero(d4); + }))); } else { const iter4: rt.Iter = rt.iterSlice([{ secs: 0, nanos: 0 }, { secs: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, nanos: 999999999 }, { secs: 0, nanos: 999 }]); while (true) { - const _225: rt.Duration | rt.Done = iter4.next(); - if (_225 === rt.DONE) { + const _317: rt.Duration | rt.Done = iter4.next(); + if (_317 === rt.DONE) { break; } - putDuration(out, _225); + putDuration(out, _317); } 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 _237: rt.Duration | undefined = rt.thenSome(rt.durationCmp(b, { secs: 1, nanos: 500000000 }) === 1, b); - const w: Window.Window = { start: a, len: _237 }; - const _246: Window.Window = Window.default$Default(); - rt.byteVecPush(out, Window.eq$PartialEq(w, _246) ? 1 : 0); - rt.byteVecPush(out, Window.cmp$Ord(w, { start: b, len: undefined }) < 0 ? 1 : 0); - const _258: Window.Window = copy$Window(Window.default$Default()); - const _256: rt.Iter = rt.iterSlice([copy$Window(w), copy$Window(w), _258]); - rt.byteVecPush(out, rt.hashLen(rt.hashExtendKeys(rt.hashNew(rt.hashing(Window.hash$Hash_DefaultHasher, Window.eq$PartialEq)) as rt.HashSet, _256)) & 0xff); - const _271: Window.Window = Window.default$Default(); - const args4: rt.Fmt[] = [(f: rt.Formatter) => Window.fmt$Debug(w, f), (f: rt.Formatter) => Window.fmt$Debug(_271, f)]; + const _329: rt.Duration | undefined = rt.thenSome(rt.durationCmp(b, { secs: 1, nanos: 500000000 }) === 1, b); + const w2: Window.Window = { start: a, len: _329 }; + const _338: Window.Window = Window.default$Default(); + rt.byteVecPush(out, Window.eq$PartialEq(w2, _338) ? 1 : 0); + rt.byteVecPush(out, Window.cmp$Ord(w2, { start: b, len: undefined }) < 0 ? 1 : 0); + const _350: Window.Window = copy$Window(Window.default$Default()); + const _348: rt.Iter = rt.iterSlice([copy$Window(w2), copy$Window(w2), _350]); + rt.byteVecPush(out, rt.hashLen(rt.hashExtendKeys(rt.hashNew(rt.hashing(Window.hash$Hash_DefaultHasher, Window.eq$PartialEq)) as rt.HashSet, _348)) & 0xff); + const _363: Window.Window = Window.default$Default(); + const args4: rt.Fmt[] = [(f: rt.Formatter) => Window.fmt$Debug(w2, f), (f: rt.Formatter) => Window.fmt$Debug(_363, f)]; put(out, rt.fmtFormat([args4[0], "|", rt.fmtSpec({ alternate: true }, args4[1])])); } } diff --git a/ts/fixtures/lang/src/durations.rs b/ts/fixtures/lang/src/durations.rs index 7c36867ea..eeb60cf92 100644 --- a/ts/fixtures/lang/src/durations.rs +++ b/ts/fixtures/lang/src/durations.rs @@ -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; @@ -50,6 +50,11 @@ fn put_opt(out: &mut Vec, d: Option) { } } +/// `-=` 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) { let (a, rest) = duration(data); let (b, rest) = duration(rest); @@ -57,7 +62,7 @@ pub fn durations(kind: u8, data: &[u8], out: &mut Vec) { 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); @@ -136,6 +141,52 @@ pub fn durations(kind: u8, data: &[u8], out: &mut Vec) { &format!("{a:?}|{c:?}|{d:?}|{c:>16?}|{d:*^14?}|{c:<12?}|{a:08?}|{:?}", Some(b)), ); } + 10 => { + // `+=` and `-=` on a local, a field, what an `Option`'s `&mut` borrows, an + // element, and through a `&mut`, each panicking as `+` and `-` do. + 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]); + } + 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::()); + put_duration(out, parts.iter().filter(|d| !d.is_zero()).copied().sum()); + } _ => { // Constants, `Default`, and a field. for d in LIMITS { diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 846a14f13..a1261f74f 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,14 +1,14 @@ # Census of `reject-fixture` -- Refusals: 86 -- Function instances: 73 +- Refusals: 85 +- Function instances: 72 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct | Count | Construct | First | | ---: | --- | --- | -| 10 | unsupported call to `_` | fixtures/reject/src/lib.rs:28:4 | +| 9 | unsupported call to `_` | fixtures/reject/src/lib.rs:28:4 | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:23:15 | | 5 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:45:11 | | 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:397:2 | @@ -41,7 +41,7 @@ | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:88:2 | | 1 | a copy of a closure that changes what it captured | fixtures/reject/src/lib.rs:275:14 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | fixtures/reject/src/lib.rs:244:13 | -| 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:446:12 | +| 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:440:12 | | 1 | a precision, as in `{:.2}`, is not supported | fixtures/reject/src/lib.rs:67:3 | | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:100:1 | | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | @@ -91,7 +91,7 @@ The type or module each refused type or path belongs to. | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:11:16 | | 1 | `from_fn` | fixtures/reject/src/lib.rs:390:13 | | 1 | `into_keys` | fixtures/reject/src/lib.rs:51:13 | -| 1 | `std::collections::hash_map::Entry` | fixtures/reject/src/lib.rs:436:15 | +| 1 | `std::collections::hash_map::Entry` | fixtures/reject/src/lib.rs:430:15 | | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:185:51 | | 1 | `std::iter::Flatten` | fixtures/reject/src/lib.rs:234:26 | | 1 | `std::iter::IntoIterator` | fixtures/reject/src/lib.rs:17:2 | @@ -103,7 +103,6 @@ The type or module each refused type or path belongs to. | 1 | `std::str` | fixtures/reject/src/lib.rs:370:4 | | 1 | `std::string::String` | fixtures/reject/src/lib.rs:82:10 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:134:2 | -| 1 | `std::time::Duration` | fixtures/reject/src/lib.rs:423:2 | | 1 | `successors` | fixtures/reject/src/lib.rs:389:15 | | 1 | `u32` | fixtures/reject/src/lib.rs:244:13 | | 1 | `u64` | fixtures/reject/src/lib.rs:104:2 | @@ -127,9 +126,9 @@ The type or module each refused type or path belongs to. | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::count` | fixtures/reject/src/lib.rs:265:38 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::filter` | fixtures/reject/src/lib.rs:265:16 | | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:341:2 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::collections::hash_map::Entry::and_modify` | fixtures/reject/src/lib.rs:436:15 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::collections::hash_map::Entry::and_modify` | fixtures/reject/src/lib.rs:430:15 | | 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::iter::IntoIterator::into_iter` | fixtures/reject/src/lib.rs:17:2 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::slice::last_mut` | fixtures/reject/src/lib.rs:429:21 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::slice::last_mut` | fixtures/reject/src/lib.rs:423:21 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:317:9 | | 1 | `fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet | `std::iter::Flatten` | fixtures/reject/src/lib.rs:234:26 | | 1 | a `_` cast from `_` to `_` | `IntToFloat`, `u64`, `f64` | fixtures/reject/src/lib.rs:104:2 | @@ -163,10 +162,9 @@ The type or module each refused type or path belongs to. | 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `successors::successors` | fixtures/reject/src/lib.rs:389:15 | | 1 | replacing the value behind a reference to `_` | `[u16; 1]` | fixtures/reject/src/lib.rs:258:22 | | 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:409:2 | -| 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:453:2 | +| 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:447:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:139:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:82:10 | -| 1 | unsupported call to `_` | `::add_assign` | fixtures/reject/src/lib.rs:423:2 | | 1 | unsupported call to `_` | `std::mem::size_of_val` | fixtures/reject/src/lib.rs:44:29 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:193:8 | | 1 | unsupported call to `_` | `std::slice::copy_within` | fixtures/reject/src/lib.rs:359:4 | @@ -176,7 +174,7 @@ The type or module each refused type or path belongs to. ## Spans -
unsupported call to `_` (10) +
unsupported call to `_` (9) - fixtures/reject/src/lib.rs:28:4: unsupported call to `std::slice::::sort` - fixtures/reject/src/lib.rs:44:29: unsupported call to `std::mem::size_of_val::` @@ -186,8 +184,7 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:359:4: unsupported call to `core::slice::::copy_within::>` - fixtures/reject/src/lib.rs:370:4: unsupported call to `core::str::::split::<[char; 2]>` - fixtures/reject/src/lib.rs:409:2: unsupported call to ` as std::ops::Deref>::deref` -- fixtures/reject/src/lib.rs:423:2: unsupported call to `::add_assign` -- fixtures/reject/src/lib.rs:453:2: unsupported call to ` as std::cmp::PartialEq>::eq` +- fixtures/reject/src/lib.rs:447:2: unsupported call to ` as std::cmp::PartialEq>::eq`
@@ -242,8 +239,8 @@ The type or module each refused type or path belongs to.
`_` with a mutable reference to a value JS copies, which its mapping would copy (3) - fixtures/reject/src/lib.rs:17:2: `std::iter::IntoIterator::into_iter` with a mutable reference to a value JS copies, which its mapping would copy -- fixtures/reject/src/lib.rs:429:21: `core::slice::::last_mut` with a mutable reference to a value JS copies, which its mapping would copy -- fixtures/reject/src/lib.rs:436:15: `std::collections::hash_map::Entry::<'a, K, V, A>::and_modify` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:423:21: `core::slice::::last_mut` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:430:15: `std::collections::hash_map::Entry::<'a, K, V, A>::and_modify` with a mutable reference to a value JS copies, which its mapping would copy
@@ -415,7 +412,7 @@ The type or module each refused type or path belongs to.
a mutable reference into a `Result`'s payload, passed on or kept (1) -- fixtures/reject/src/lib.rs:446:12: a mutable reference into a `Result`'s payload, passed on or kept +- fixtures/reject/src/lib.rs:440:12: a mutable reference into a `Result`'s payload, passed on or kept
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 6a5d50716..f96b9248b 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -1,4 +1,5 @@ a root must not be generic at fixtures/reject/src/lib.rs:102:1 +no item `duration_assign` in the crate no item `missing` in the crate a printable type must implement `Display` or `Debug` at fixtures/reject/src/lib.rs:100:1 unsupported type `f64` at fixtures/reject/src/lib.rs:7:14 @@ -74,11 +75,10 @@ dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:390:62 an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:391:13 -unsupported call to `::add_assign` at fixtures/reject/src/lib.rs:423:2 -`core::slice::::last_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:429:21 -`std::collections::hash_map::Entry::<'a, K, V, A>::and_modify` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:436:15 -a mutable reference into a `Result`'s payload, passed on or kept at fixtures/reject/src/lib.rs:446:12 -unsupported call to ` as std::cmp::PartialEq>::eq` at fixtures/reject/src/lib.rs:453:2 +`core::slice::::last_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:423:21 +`std::collections::hash_map::Entry::<'a, K, V, A>::and_modify` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:430:15 +a mutable reference into a `Result`'s payload, passed on or kept at fixtures/reject/src/lib.rs:440:12 +unsupported call to ` as std::cmp::PartialEq>::eq` at fixtures/reject/src/lib.rs:447:2 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:152:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:172:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:206:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 68cdbd1e6..6bf162125 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -418,12 +418,6 @@ pub fn cow_made(a: &std::sync::Arc) -> usize { std::sync::Arc::strong_count(a) } -/// `AddAssign` for a `Duration`, which has no mapping. -pub fn duration_assign(mut d: std::time::Duration, by: std::time::Duration) -> std::time::Duration { - d += by; - d -} - /// std makes a `&mut` to a value JS copies, which its mapping has as the value. pub fn last_bumped(v: &mut Vec) { if let Some(x) = v.last_mut() { diff --git a/ts/runtime/rt/time.ts b/ts/runtime/rt/time.ts index 22d7876ae..4f54ab40b 100644 --- a/ts/runtime/rt/time.ts +++ b/ts/runtime/rt/time.ts @@ -7,7 +7,8 @@ import { type FmtResult, type Formatter, fmtPad, panic } from "../rt.ts"; import { cmp, type Hasher, hashInt, type Ordering } from "./collections.ts"; -import { type u32, type u64, type u128, u64CheckedAdd, u64CheckedMul, u64CheckedSub, u64Div, u64Eq, u64Rem, u128Add, u128Cast, u128Mul } from "./int.ts"; +import { type u32, type u64, type u128, u64CheckedAdd, u64CheckedMul, u64CheckedSub, u64Div, u64Eq, u64Rem, u64TryFrom, u128Add, u128Cast, u128Div, u128Mul, u128Rem } from "./int.ts"; +import { type Iter, iterFold } from "./iter.ts"; /** `core::time::Duration`: whole seconds, and the nanoseconds past them, below 10^9. */ export interface Duration { @@ -51,6 +52,23 @@ export function durationFromNanos(nanos: u64): Duration { return { secs: u64Div(nanos, NANOS_PER_SEC), nanos: u64Rem(nanos, NANOS_PER_SEC) as number }; } +/** `Duration::from_mins`, panicking past `u64::MAX` seconds. */ +export function durationFromMins(mins: u64): Duration { + return { secs: u64CheckedMul(mins, 60 as u64) ?? panic("overflow in Duration::from_mins"), nanos: 0 }; +} + +/** `Duration::from_hours`, panicking past `u64::MAX` seconds. */ +export function durationFromHours(hours: u64): Duration { + return { secs: u64CheckedMul(hours, 3600 as u64) ?? panic("overflow in Duration::from_hours"), nanos: 0 }; +} + +/** `Duration::from_nanos_u128`, panicking past `u64::MAX` seconds. */ +export function durationFromNanosU128(nanos: u128): Duration { + const secs = u64TryFrom(u128Div(nanos, NANOS_PER_SEC)); + if (!secs.ok) panic("overflow in `Duration::from_nanos_u128`"); + return { secs: secs.value, nanos: u128Rem(nanos, NANOS_PER_SEC) as number }; +} + /** `Duration::is_zero`. */ export function durationIsZero(d: Duration): boolean { return d.secs === 0 && d.nanos === 0; @@ -201,6 +219,34 @@ export function durationDiv(d: Duration, n: u32): Duration { return durationCheckedDiv(d, n) ?? panic("divisor should not be zero"); } +/** + * `Sum`, as std sums: the seconds as it goes, and the nanoseconds in a `u64` that carries + * into them only when it would overflow and at the end, each overflow past `u64::MAX` + * seconds a panic. + */ +export function durationSum(it: Iter, dropIt?: (it: Iter) => void): Duration { + const overflow = "sum over duration iterator should not overflow u64::MAX"; + let secs = 0 as u64; + let nanos = 0 as u64; + iterFold( + it, + undefined, + (_, d) => { + secs = u64CheckedAdd(secs, d.secs) ?? panic(overflow); + const sum = u64CheckedAdd(nanos, d.nanos as u64); + if (sum !== undefined) { + nanos = sum; + } else { + secs = u64CheckedAdd(secs, u64Div(nanos, NANOS_PER_SEC)) ?? panic(overflow); + nanos = (u64Rem(nanos, NANOS_PER_SEC) as number) + d.nanos; + } + }, + dropIt, + ); + secs = u64CheckedAdd(secs, u64Div(nanos, NANOS_PER_SEC)) ?? panic(overflow); + return { secs, nanos: u64Rem(nanos, NANOS_PER_SEC) as number }; +} + /** `PartialEq::eq`. */ export function durationEq(a: Duration, b: Duration): boolean { return a.nanos === b.nanos && u64Eq(a.secs, b.secs); diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index 1931aa134..ba634cc8a 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -400,6 +400,11 @@ pub fn call<'tcx>( let dropper = iter_dropper(b, self_ty, span); method(&camel, tail(rest, vec![dropper])) } + // `Duration`'s carries its nanoseconds and panics as std's does, not as `+` would. + "sum" if b.t.std_of(targ(1)?) == Some(Std::Duration) => { + let dropper = iter_dropper(b, self_ty, span); + Some(Expr::rt("durationSum", tail(vec![recv.clone()], vec![dropper]))) + } "sum" | "product" => { let int = Int::of(targ(1)?)?; let (op, unit) = match name { diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index a2d742383..b7a3cd0d2 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -444,6 +444,22 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.set_borrowed(&place, pushed, span, out); done(Expr::undefined(), false) } + // A `Duration` never changes once made, so what the `&mut` borrows gets a new one. + ("AddAssign" | "SubAssign" | "MulAssign" | "DivAssign", _) + if targ(0).is_some_and(|t| self.b.t.std_of(t) == Some(Std::Duration)) => + { + let f = match owner.as_str() { + "AddAssign" => "durationAdd", + "SubAssign" => "durationSub", + "MulAssign" => "durationMul", + _ => "durationDiv", + }; + let place = self.borrowed_place(&args[0].node, span, out)?; + let by = self.operand(&args[1].node, span, out); + let value = Expr::rt(f, vec![place.0.clone(), by]); + self.set_borrowed(&place, value, span, out); + done(Expr::undefined(), false) + } // A `Cow` is the `String` it would hold, so the `&mut` borrows the same place. ("Cow", "to_mut") if targ(0).is_some_and(|t| t.is_str()) => { let (place, borrowed) = self.borrowed_place(&args[0].node, span, out)?; diff --git a/ts/src/lower/time.rs b/ts/src/lower/time.rs index 91ca39d85..f396aae50 100644 --- a/ts/src/lower/time.rs +++ b/ts/src/lower/time.rs @@ -35,6 +35,9 @@ pub fn call<'tcx>( "from_millis" => "durationFromMillis", "from_micros" => "durationFromMicros", "from_nanos" => "durationFromNanos", + "from_nanos_u128" => "durationFromNanosU128", + "from_mins" => "durationFromMins", + "from_hours" => "durationFromHours", "is_zero" => "durationIsZero", "as_secs" => "durationAsSecs", "subsec_millis" => "durationSubsecMillis", From bad072449f19efb20060d004bf7148419414fab9 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:09:18 -0700 Subject: [PATCH 3/6] chore(quest): plan floats, folding in Duration's float methods f64 joins the ts-model epic, since moq-net's Bandwidth::scaled and Duration::mul_f64 jitter use it; f32 follows in m3. Each carries Duration's float methods of its width, so ts-duration is done. Co-Authored-By: Claude Opus 5.5 --- quest/m2/ts-model/README.md | 1 + quest/m2/ts-model/floats.md | 35 +++++++++++++++++++++++++++++++++++ quest/m3/README.md | 2 +- quest/m3/ts-duration.md | 20 -------------------- quest/m3/ts-f32.md | 24 ++++++++++++++++++++++++ ts/README.md | 2 +- 6 files changed, 62 insertions(+), 22 deletions(-) create mode 100644 quest/m2/ts-model/floats.md delete mode 100644 quest/m3/ts-duration.md create mode 100644 quest/m3/ts-f32.md diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index db75e7f54..e91630c94 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -49,4 +49,5 @@ Public API: the translator's output for moq-net's model. - [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 - [Options of values that can be undefined](/quest/m2/ts-model/nested-option.md) - `Option>` and `Option<()>` keep `None` apart from `Some(None)` +- [Floats](/quest/m2/ts-model/floats.md) - `f64` translates, so `Bandwidth::scaled` and `Duration::mul_f64` do - [Async in the TypeScript translator](/quest/m2/ts-async.md) - kio's producers and consumers are futures diff --git a/quest/m2/ts-model/floats.md b/quest/m2/ts-model/floats.md new file mode 100644 index 000000000..547387973 --- /dev/null +++ b/quest/m2/ts-model/floats.md @@ -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}`. + [Format specs](/quest/m3/ts-fmt-specs.md) covers the other types. +- `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. diff --git a/quest/m3/README.md b/quest/m3/README.md index 6b926799e..bb4da0d58 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -16,6 +16,6 @@ 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 -- [Duration's float methods](/quest/m3/ts-duration.md) - `as_secs_f64`, `from_secs_f64`, and the other float methods on a `Duration` translate, once floats do +- [f32](/quest/m3/ts-f32.md) - `f32` and `Duration`'s `f32` methods translate as `f64` does - [The rest of format specs](/quest/m3/ts-fmt-specs.md) - precision, argument widths, `+`, and the other radixes format as `core::fmt` does - [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 diff --git a/quest/m3/ts-duration.md b/quest/m3/ts-duration.md deleted file mode 100644 index 4e9665698..000000000 --- a/quest/m3/ts-duration.md +++ /dev/null @@ -1,20 +0,0 @@ -# [M] Duration's float methods - -## Goal - -rust2-ts translates `std::time::Duration`'s float methods (`as_secs_f64`, -`from_secs_f64`, `mul_f64`, `div_f64`, `div_duration_f64`, and their `f32` and `try_` -forms) with std's results, rounding, and panics, proven by differential tests against -native Rust. - -## Plan - -Decided with the maintainer on 2026-10-27: rust2 aims to support all of std, so generic -gaps are planned without a moq consumer. Nothing in moq-net, moq-clock, or kio uses these. - -- Blocked on floats: rust2-ts refuses `f32` and `f64` wherever they appear, so no value - these methods take or return translates yet. Floats need their own quest first. -- The conversions must match std's rounding exactly, including at `u64::MAX` seconds and - for values a `f64` cannot hold, which std rejects with a panic or an `Err`. - -Public API: the translator's output. diff --git a/quest/m3/ts-f32.md b/quest/m3/ts-f32.md new file mode 100644 index 000000000..02de5f77e --- /dev/null +++ b/quest/m3/ts-f32.md @@ -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 diff --git a/ts/README.md b/ts/README.md index 03c6410ae..8951ff16e 100644 --- a/ts/README.md +++ b/ts/README.md @@ -421,7 +421,7 @@ to hand-written TS ([bindings](#bindings)). ## Not yet -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 collection's `capacity`, looking up a key by From 31aa321cdfcf2c2c9b0a64ea2197e383a38ee85d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:34:16 -0700 Subject: [PATCH 4/6] fix(ts): map only std's own Sum and Product, and drop a stale reject root Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/reject/expected.txt | 3 ++- ts/fixtures/reject/src/lib.rs | 19 +++++++++++++++++++ ts/fixtures/reject/ts.toml | 2 +- ts/src/lower/iter.rs | 2 ++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index f96b9248b..2ed28b9f3 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -1,5 +1,4 @@ a root must not be generic at fixtures/reject/src/lib.rs:102:1 -no item `duration_assign` in the crate no item `missing` in the crate a printable type must implement `Display` or `Debug` at fixtures/reject/src/lib.rs:100:1 unsupported type `f64` at fixtures/reject/src/lib.rs:7:14 @@ -75,6 +74,8 @@ dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:390:62 an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:391:13 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:466:17 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:466:38 `core::slice::::last_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:423:21 `std::collections::hash_map::Entry::<'a, K, V, A>::and_modify` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:430:15 a mutable reference into a `Result`'s payload, passed on or kept at fixtures/reject/src/lib.rs:440:12 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 6bf162125..1d313867e 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -446,3 +446,22 @@ pub fn ok_passed(r: &mut Result) { pub fn places_equal(a: &mut u32, b: &mut u32) -> bool { Some(a) == Some(b) } + +pub struct Part(pub u64); + +impl std::iter::Sum for std::time::Duration { + fn sum>(parts: I) -> Self { + std::time::Duration::from_secs(parts.map(|p| p.0 * 2).sum()) + } +} + +impl std::iter::Sum for u64 { + fn sum>(parts: I) -> Self { + parts.map(|p| p.0 * 2).sum() + } +} + +/// A `Sum` of the crate's into a std type, which std's `Sum` mapping would bypass. +pub fn parts_summed(a: Vec, b: Vec) -> (std::time::Duration, u64) { + (a.into_iter().sum(), b.into_iter().sum()) +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 5765d60e8..7cc5ee1cb 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -50,7 +50,7 @@ roots = [ "split_chars", "called_closure", "owning_lazy", - "duration_assign", + "parts_summed", "last_bumped", "modified", "ok_passed", diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index ba634cc8a..241998b5e 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -400,6 +400,8 @@ pub fn call<'tcx>( let dropper = iter_dropper(b, self_ty, span); method(&camel, tail(rest, vec![dropper])) } + // std's `Sum` and `Product` are of the type or a reference to it: another is the crate's. + "sum" | "product" if item.peel_refs() != targ(1)? => None, // `Duration`'s carries its nanoseconds and panics as std's does, not as `+` would. "sum" if b.t.std_of(targ(1)?) == Some(Std::Duration) => { let dropper = iter_dropper(b, self_ty, span); From 3599402c2cb15c7a77734cf8716fa9e7e2b05db6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:45:54 -0700 Subject: [PATCH 5/6] test(ts): count the Sum refusals in the reject census Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/reject/census.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index a1261f74f..4581e9526 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,14 +1,14 @@ # Census of `reject-fixture` -- Refusals: 85 -- Function instances: 72 -- Generic functions no instance reached, lowered over their type parameters: 2 +- Refusals: 87 +- Function instances: 75 +- Generic functions no instance reached, lowered over their type parameters: 4 ## By construct | Count | Construct | First | | ---: | --- | --- | -| 9 | unsupported call to `_` | fixtures/reject/src/lib.rs:28:4 | +| 11 | unsupported call to `_` | fixtures/reject/src/lib.rs:28:4 | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:23:15 | | 5 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:45:11 | | 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:397:2 | @@ -79,6 +79,7 @@ The type or module each refused type or path belongs to. | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:193:8 | | 2 | `std::option::Option` | fixtures/reject/src/lib.rs:286:6 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:129:2 | +| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:466:17 | | 2 | `std::vec::Vec` | fixtures/reject/src/lib.rs:291:52 | | 2 | `u8` | fixtures/reject/src/lib.rs:88:2 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:172:1 | @@ -119,6 +120,7 @@ The type or module each refused type or path belongs to. | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:129:2 | | 2 | dropping `_`, which is not supported yet | `std::iter::Take` | fixtures/reject/src/lib.rs:389:79 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:93:2 | +| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:466:17 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | `std::collections::HashMap`, `std::option::Option` | fixtures/reject/src/lib.rs:286:6 | | 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:408:18 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:309:6 | @@ -174,7 +176,7 @@ The type or module each refused type or path belongs to. ## Spans -
unsupported call to `_` (9) +
unsupported call to `_` (11) - fixtures/reject/src/lib.rs:28:4: unsupported call to `std::slice::::sort` - fixtures/reject/src/lib.rs:44:29: unsupported call to `std::mem::size_of_val::` @@ -185,6 +187,8 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:370:4: unsupported call to `core::str::::split::<[char; 2]>` - fixtures/reject/src/lib.rs:409:2: unsupported call to ` as std::ops::Deref>::deref` - fixtures/reject/src/lib.rs:447:2: unsupported call to ` as std::cmp::PartialEq>::eq` +- fixtures/reject/src/lib.rs:466:17: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:466:38: unsupported call to ` as std::iter::Iterator>::sum::`
From 6e2f96b8874ed8b7df235198918656a44c21a397 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:54:52 -0700 Subject: [PATCH 6/6] fix(ts): map only std's own compound assignment on a Duration Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/lang/expected/durations.Twice.ts | 10 +++++ ts/fixtures/lang/expected/durations.ts | 42 ++++++++++++-------- ts/fixtures/lang/src/durations.rs | 16 +++++++- ts/src/lower/mir/call.rs | 7 +++- 4 files changed, 57 insertions(+), 18 deletions(-) create mode 100644 ts/fixtures/lang/expected/durations.Twice.ts diff --git a/ts/fixtures/lang/expected/durations.Twice.ts b/ts/fixtures/lang/expected/durations.Twice.ts new file mode 100644 index 000000000..802c244cc --- /dev/null +++ b/ts/fixtures/lang/expected/durations.Twice.ts @@ -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 diff --git a/ts/fixtures/lang/expected/durations.ts b/ts/fixtures/lang/expected/durations.ts index 39abfbc69..5db85a190 100644 --- a/ts/fixtures/lang/expected/durations.ts +++ b/ts/fixtures/lang/expected/durations.ts @@ -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"; @@ -46,6 +47,11 @@ export function putOpt(out: rt.ByteVec, d: rt.Duration | undefined): void { } } +export function addAssign$AddAssign_Twice_Duration(self: rt.Place, 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, by: rt.Duration): void { d.v = rt.durationSub(d.v, by); @@ -166,6 +172,10 @@ export function durations(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi putDuration(out, v[1]); shrink(rt.place(() => v[0], (value) => v[0] = value), b); putDuration(out, v[0]); + let d3: rt.Duration = a; + const _262: Twice.Twice = { _0: b }; + addAssign$AddAssign_Twice_Duration(rt.place(() => d3, (value2) => d3 = value2), _262); + putDuration(out, d3); } else if (_24 === 11) { let c3: rt.Duration = a; c3 = rt.durationMul(c3, n); @@ -183,35 +193,35 @@ export function durations(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi putDuration(out, rt.durationFromHours(units2)); putDuration(out, rt.durationFromNanosU128(rt.u128FromBeBytes(wide))); } else if (_24 === 13) { - const _296: rt.Duration = rt.durationNew(0, rt.u32Rem(n, 1000000000)); - const parts: rt.Duration[] = [a, b, _296]; + const _302: rt.Duration = rt.durationNew(0, rt.u32Rem(n, 1000000000)); + const parts: rt.Duration[] = [a, b, _302]; putDuration(out, rt.durationSum(rt.iterSlice(parts))); putDuration(out, rt.durationSum(rt.iterSlice([b, a]))); - putDuration(out, rt.durationSum(rt.iterFilter(rt.iterSlice(parts), (d4: rt.Duration): boolean => { - return !rt.durationIsZero(d4); + putDuration(out, rt.durationSum(rt.iterFilter(rt.iterSlice(parts), (d5: rt.Duration): boolean => { + return !rt.durationIsZero(d5); }))); } else { const iter4: rt.Iter = rt.iterSlice([{ secs: 0, nanos: 0 }, { secs: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, nanos: 999999999 }, { secs: 0, nanos: 999 }]); while (true) { - const _317: rt.Duration | rt.Done = iter4.next(); - if (_317 === rt.DONE) { + const _323: rt.Duration | rt.Done = iter4.next(); + if (_323 === rt.DONE) { break; } - putDuration(out, _317); + putDuration(out, _323); } 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 _329: rt.Duration | undefined = rt.thenSome(rt.durationCmp(b, { secs: 1, nanos: 500000000 }) === 1, b); - const w2: Window.Window = { start: a, len: _329 }; - const _338: Window.Window = Window.default$Default(); - rt.byteVecPush(out, Window.eq$PartialEq(w2, _338) ? 1 : 0); + const _335: rt.Duration | undefined = rt.thenSome(rt.durationCmp(b, { secs: 1, nanos: 500000000 }) === 1, b); + const w2: Window.Window = { start: a, len: _335 }; + const _344: Window.Window = Window.default$Default(); + rt.byteVecPush(out, Window.eq$PartialEq(w2, _344) ? 1 : 0); rt.byteVecPush(out, Window.cmp$Ord(w2, { start: b, len: undefined }) < 0 ? 1 : 0); - const _350: Window.Window = copy$Window(Window.default$Default()); - const _348: rt.Iter = rt.iterSlice([copy$Window(w2), copy$Window(w2), _350]); - rt.byteVecPush(out, rt.hashLen(rt.hashExtendKeys(rt.hashNew(rt.hashing(Window.hash$Hash_DefaultHasher, Window.eq$PartialEq)) as rt.HashSet, _348)) & 0xff); - const _363: Window.Window = Window.default$Default(); - const args4: rt.Fmt[] = [(f: rt.Formatter) => Window.fmt$Debug(w2, f), (f: rt.Formatter) => Window.fmt$Debug(_363, f)]; + const _356: Window.Window = copy$Window(Window.default$Default()); + const _354: rt.Iter = rt.iterSlice([copy$Window(w2), copy$Window(w2), _356]); + rt.byteVecPush(out, rt.hashLen(rt.hashExtendKeys(rt.hashNew(rt.hashing(Window.hash$Hash_DefaultHasher, Window.eq$PartialEq)) as rt.HashSet, _354)) & 0xff); + const _369: Window.Window = Window.default$Default(); + const args4: rt.Fmt[] = [(f: rt.Formatter) => Window.fmt$Debug(w2, f), (f: rt.Formatter) => Window.fmt$Debug(_369, f)]; put(out, rt.fmtFormat([args4[0], "|", rt.fmtSpec({ alternate: true }, args4[1])])); } } diff --git a/ts/fixtures/lang/src/durations.rs b/ts/fixtures/lang/src/durations.rs index eeb60cf92..f4baa8285 100644 --- a/ts/fixtures/lang/src/durations.rs +++ b/ts/fixtures/lang/src/durations.rs @@ -50,6 +50,16 @@ fn put_opt(out: &mut Vec, d: Option) { } } +/// The crate's own `+=` onto a `Duration`, which adds twice. +struct Twice(Duration); + +impl std::ops::AddAssign 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; @@ -143,7 +153,8 @@ pub fn durations(kind: u8, data: &[u8], out: &mut Vec) { } 10 => { // `+=` and `-=` on a local, a field, what an `Option`'s `&mut` borrows, an - // element, and through a `&mut`, each panicking as `+` and `-` do. + // 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); @@ -159,6 +170,9 @@ pub fn durations(kind: u8, data: &[u8], out: &mut Vec) { 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. diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index b7a3cd0d2..b34880a8f 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -445,8 +445,13 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { done(Expr::undefined(), false) } // A `Duration` never changes once made, so what the `&mut` borrows gets a new one. + // std's impls take a `Duration` or a `u32`: another is the crate's. ("AddAssign" | "SubAssign" | "MulAssign" | "DivAssign", _) - if targ(0).is_some_and(|t| self.b.t.std_of(t) == Some(Std::Duration)) => + if targ(0).is_some_and(|t| self.b.t.std_of(t) == Some(Std::Duration)) + && targ(1).is_some_and(|t| match owner.as_str() { + "AddAssign" | "SubAssign" => self.b.t.std_of(t) == Some(Std::Duration), + _ => t == tcx.types.u32, + }) => { let f = match owner.as_str() { "AddAssign" => "durationAdd",