From 93915834ecda50cb9916e95258a128a787b6f3cc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:14:09 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m2/ts-ref-shapes.md Quest-Claim: 11a6aeffc6455635 From 45f606e765bb54ac29f96f9007253fdcaf70f186 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:47:30 -0700 Subject: [PATCH 2/2] feat(ts): translate comparisons through references and &mut slice index writes std's PartialEq, PartialOrd, Ord, and Hash impls for references call their referents', so a derived impl on a type holding references now reaches the referent's. A bounds check of a `&mut` slice reads its length through a fake raw pointer, which now reads the slice's, so `live[0] = x` translates. A variant MIR reads without a switch, as a derived `==` reads the other operand of an enum whose variants all hold data, is cast to it for tsc. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-ref-shapes.md | 17 ---- ts/fixtures/lang/expected/keys.Seen.ts | 80 +++++++++++++++ ts/fixtures/lang/expected/keys.Skew.ts | 4 + ts/fixtures/lang/expected/keys.Skewed.ts | 22 ++++ ts/fixtures/lang/expected/keys.ts | 124 ++++++++++++++++++++++- ts/fixtures/lang/expected/shapes.ts | 70 +++++++++++-- ts/fixtures/lang/src/keys.rs | 68 ++++++++++++- ts/fixtures/lang/src/shapes.rs | 29 ++++++ ts/src/lower/body.rs | 3 + ts/src/lower/library.rs | 31 ++++++ ts/src/lower/mir/mod.rs | 58 +++++++---- ts/src/lower/mir/place.rs | 26 ++++- ts/src/lower/mir/rvalue.rs | 3 + ts/src/ts.rs | 17 ++++ 15 files changed, 508 insertions(+), 45 deletions(-) delete mode 100644 quest/m2/ts-ref-shapes.md create mode 100644 ts/fixtures/lang/expected/keys.Seen.ts create mode 100644 ts/fixtures/lang/expected/keys.Skewed.ts diff --git a/quest/m2/README.md b/quest/m2/README.md index 36996ca94..d8214313b 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -37,7 +37,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [str and String methods over char](/quest/m2/ts-str-char.md) - `chars`, `char` patterns, and `String::push` translate, unblocking `ietf/namespace.rs` - [Share a held-back read across a call](/quest/m2/ts-shared-read.md) - `leading-ones` decode recovers what #83's copy fix cost - [Output tsc accepts for writes through Result and Poll compares](/quest/m2/ts-tsc-shapes.md) - two shapes whose output fails `tsc` type-check -- [Translate derived == through references and slice index writes](/quest/m2/ts-ref-shapes.md) - two refused shapes #83's tests hit - [Translate moq-net's model to TypeScript](/quest/m2/ts-model.md) - the driver grows from moq-net's codec to its model, for moq to compare against WASM - [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/uniffi-swift-arm.md) - the nightly UniFFI fixtures move back to arm - [Waiting: ubrn reads UniFFI 0.32](/quest/m2/ubrn-release.md) - the binding benchmark's browser runner pins a ubrn release, not an open PR diff --git a/quest/m2/ts-ref-shapes.md b/quest/m2/ts-ref-shapes.md deleted file mode 100644 index f9bb1f9a0..000000000 --- a/quest/m2/ts-ref-shapes.md +++ /dev/null @@ -1,17 +0,0 @@ -# [S] Translate derived == through references and slice index writes - -## Goal - -rust2-ts translates `<&T as PartialEq>::eq`, which a derived `==` on an enum holding -references reaches, and `live[0] = x` on a `&mut [u8]` parameter, proven by -differential tests against native Rust. - -## Plan - -Found by [#83](https://github.com/kixelated/rust2/pull/83)'s tests on 2026-10-26. -Both are refused with a span today: the first as unsupported, the second as a raw -pointer. - -- Report each one's count in moq-net's census before and after. - -Public API: the translator's output. diff --git a/ts/fixtures/lang/expected/keys.Seen.ts b/ts/fixtures/lang/expected/keys.Seen.ts new file mode 100644 index 000000000..bcdb80b54 --- /dev/null +++ b/ts/fixtures/lang/expected/keys.Seen.ts @@ -0,0 +1,80 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import * as Hop from "./keys.Hop.ts"; +import * as Horizon from "./keys.Horizon.ts"; +import * as Name from "./keys.Name.ts"; + +export function eq$PartialEq(self: Seen, other: Seen): boolean { + if (!({ Hop: 0, Twice: 1, Text: 2, Name: 3, Mut: 4 }[self.tag] === { Hop: 0, Twice: 1, Text: 2, Name: 3, Mut: 4 }[other.tag])) { + return false; + } + if (self.tag === "Hop") { + return rt.eqOption(Hop.eq$PartialEq)(self._0, (other as { tag: "Hop"; _0: Hop.Hop | undefined })._0); + } + if (self.tag === "Twice") { + return Horizon.eq$PartialEq(self._0, (other as { tag: "Twice"; _0: Horizon.Horizon })._0); + } + if (self.tag === "Text") { + return self._0 === (other as { tag: "Text"; _0: string })._0; + } + if (self.tag === "Name") { + return Name.eq$PartialEq(self._0, (other as { tag: "Name"; _0: Name.Name })._0); + } + return Hop.eq$PartialEq(self._0, (other as { tag: "Mut"; _0: Hop.Hop })._0); +} + +export function partialCmp$PartialOrd(self: Seen, other: Seen): rt.Ordering | undefined { + return cmp$Ord(self, other); +} + +export function cmp$Ord(self: Seen, other: Seen): rt.Ordering { + if (self.tag === "Hop") { + if (other.tag === "Hop") { + return rt.cmpOption(Hop.cmp$Ord)(self._0, other._0); + } + } else if (self.tag === "Twice") { + if (other.tag === "Twice") { + return Horizon.cmp$Ord(self._0, other._0); + } + } else if (self.tag === "Text") { + if (other.tag === "Text") { + return rt.cmpStr(self._0, other._0); + } + } else if (self.tag === "Name") { + if (other.tag === "Name") { + return Name.cmp$Ord(self._0, other._0); + } + } else if (other.tag === "Mut") { + return Hop.cmp$Ord(self._0, other._0); + } + return rt.cmp({ Hop: 0, Twice: 1, Text: 2, Name: 3, Mut: 4 }[self.tag], { Hop: 0, Twice: 1, Text: 2, Name: 3, Mut: 4 }[other.tag]); +} + +export function hash$Hash_DefaultHasher(self: Seen, state: rt.Hasher): void { + rt.hashInt({ Hop: 0, Twice: 1, Text: 2, Name: 3, Mut: 4 }[self.tag], state); + if (self.tag === "Hop") { + rt.hashOption(Hop.hash$Hash_DefaultHasher)(self._0, state); + } else if (self.tag === "Twice") { + Horizon.hash$Hash_DefaultHasher(self._0, state); + } else if (self.tag === "Text") { + rt.hashStr(self._0, state); + } else if (self.tag === "Name") { + Name.hash$Hash_DefaultHasher(self._0, state); + } else { + Hop.hash$Hash_DefaultHasher(self._0, state); + } +} + +/** + * Borrows, whose derived impls compare, order, and hash what they point at through + * std's impls for references. + */ +export type Seen = + | { tag: "Hop"; _0: Hop.Hop | undefined } + | { tag: "Twice"; _0: Horizon.Horizon } + | { tag: "Text"; _0: string } + | { tag: "Name"; _0: Name.Name } + | { tag: "Mut"; _0: Hop.Hop }; + +//# sourceMappingURL=keys.Seen.ts.map diff --git a/ts/fixtures/lang/expected/keys.Skew.ts b/ts/fixtures/lang/expected/keys.Skew.ts index 7de96b6c6..b1a2ce539 100644 --- a/ts/fixtures/lang/expected/keys.Skew.ts +++ b/ts/fixtures/lang/expected/keys.Skew.ts @@ -2,6 +2,10 @@ import * as rt from "./rt.ts"; +export function eq$PartialEq(self: Skew, other: Skew): boolean { + return self._0 === other._0; +} + /** * An `Ord` by value whose `PartialOrd` disagrees: reversed, and unordered between odd * values, so a `partial_cmp` that calls `cmp` shows. diff --git a/ts/fixtures/lang/expected/keys.Skewed.ts b/ts/fixtures/lang/expected/keys.Skewed.ts new file mode 100644 index 000000000..ee7fd4a44 --- /dev/null +++ b/ts/fixtures/lang/expected/keys.Skewed.ts @@ -0,0 +1,22 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import * as Skew from "./keys.Skew.ts"; + +export function eq$PartialEq(self: Skewed, other: Skewed): boolean { + return Skew.eq$PartialEq(self._0, other._0); +} + +export function partialCmp$PartialOrd(self: Skewed, other: Skewed): rt.Ordering | undefined { + return Skew.partialCmp$PartialOrd(self._0, other._0); +} + +/** + * A borrow of a `Skew`, whose derived `partial_cmp` reaches its own, not its `cmp`: a + * derived `Ord` beside it would be called instead. + */ +export interface Skewed { + _0: Skew.Skew; +} + +//# sourceMappingURL=keys.Skewed.ts.map diff --git a/ts/fixtures/lang/expected/keys.ts b/ts/fixtures/lang/expected/keys.ts index b5eef3384..22af19ef7 100644 --- a/ts/fixtures/lang/expected/keys.ts +++ b/ts/fixtures/lang/expected/keys.ts @@ -1,15 +1,17 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Horizon } from "./lib.ts"; +import { copy$Hop, copy$Horizon } from "./lib.ts"; import * as Hop from "./keys.Hop.ts"; import * as Horizon from "./keys.Horizon.ts"; import * as Liar from "./keys.Liar.ts"; import * as Name from "./keys.Name.ts"; import * as Never from "./keys.Never.ts"; import * as Picky from "./keys.Picky.ts"; +import * as Seen from "./keys.Seen.ts"; import * as Side from "./keys.Side.ts"; import * as Skew from "./keys.Skew.ts"; +import * as Skewed from "./keys.Skewed.ts"; import * as Touchy from "./keys.Touchy.ts"; import * as Way from "./keys.Way.ts"; @@ -89,6 +91,18 @@ export function hashOf$Arc_str(value: rt.Arc): rt.u64 { return rt.hashFinish(h); } +export function hashOf$Hop(value: Hop.Hop): rt.u64 { + const h: rt.Hasher = rt.hasher(); + Hop.hash$Hash_DefaultHasher(value, h); + return rt.hashFinish(h); +} + +export function hashOf$Hop$2(value: Hop.Hop): rt.u64 { + const h: rt.Hasher = rt.hasher(); + Hop.hash$Hash_DefaultHasher(value, h); + return rt.hashFinish(h); +} + export function hashOf$Name(value: Name.Name): rt.u64 { const h: rt.Hasher = rt.hasher(); Name.hash$Hash_DefaultHasher(value, h); @@ -101,6 +115,12 @@ export function hashOf$Option_Hop(value: Hop.Hop | undefined): rt.u64 { return rt.hashFinish(h); } +export function hashOf$Seen(value: Seen.Seen): rt.u64 { + const h: rt.Hasher = rt.hasher(); + Seen.hash$Hash_DefaultHasher(value, h); + return rt.hashFinish(h); +} + export function order(o: rt.Ordering): rt.u8 { if (o === -1) { return 1; @@ -165,16 +185,116 @@ export function find$u8_u8(keys_: Uint8Array, q: rt.u8): rt.u8 { /** Run one case. */ export function keys(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { - const _4: rt.u8 = rt.u8Rem(kind, 3); + const _4: rt.u8 = rt.u8Rem(kind, 4); if (_4 === 0) { options(data, out); } else if (_4 === 1) { arcs(data, out); + } else if (_4 === 2) { + borrows(data, out); } else { places(data, out); } } +/** One of `Seen`'s variants, by `k`. */ +export function seen(k: rt.u8, hop_: Hop.Hop | undefined, horizon: Horizon.Horizon, name_: Name.Name, mine: Hop.Hop): Seen.Seen { + const _6: rt.u8 = rt.u8Rem(k, 5); + if (_6 === 0) { + return { tag: "Hop", _0: hop_ } as Seen.Seen; + } + if (_6 === 1) { + return { tag: "Twice", _0: horizon } as Seen.Seen; + } + if (_6 === 2) { + const _9: rt.usize = rt.usizeRem(rt.usizeDiv(k as rt.usize, 5), ["", "a", "ab", "", "￿", "𐀀"].length); + if (!(_9 < 6)) { + rt.panic("index out of bounds: the len is " + 6 + " but the index is " + _9); + } + return { tag: "Text", _0: ["", "a", "ab", "", "￿", "𐀀"][_9] } as Seen.Seen; + } + if (_6 === 3) { + return { tag: "Name", _0: name_ } as Seen.Seen; + } + return { tag: "Mut", _0: mine } as Seen.Seen; +} + +/** + * Borrows compared, ordered, and hashed as what they point at, through one reference + * or two, shared or mutable. + */ +export function borrows(data: Uint8Array, out: rt.ByteVec): void { + let _7!: rt.usize; + let m!: Name.Name; + let n!: Name.Name; + let _43!: Name.Name; + let unwind: number = 0; + try { + let iterStart: rt.usize = 1; + const iterEnd: rt.usize = data.length; + while ((_7 = iterStart++) < iterEnd) { + const i: rt.usize = _7; + const _15: rt.usize = rt.usizeSub(i, 1); + rt.idx(data, _15); + const _14: rt.u8 = data[_15]; + rt.idx(data, i); + const _13: [rt.u8, rt.u8] = [_14, data[i]]; + const c: rt.u8 = _14; + const d: rt.u8 = _13[1]; + const _24: [Hop.Hop | undefined, Hop.Hop | undefined] = [hop(c), hop(d)]; + const a: Hop.Hop | undefined = _24[0]; + const b: Hop.Hop | undefined = _24[1]; + const _28: boolean = rt.u8Rem(c, 2) === 0; + const g: Horizon.Horizon = { exclude: a, local: _28 }; + unwind = 0; + const _32: boolean = rt.u8Rem(d, 2) === 0; + const gr: Horizon.Horizon = g; + const hr: Horizon.Horizon = { exclude: b, local: _32 }; + _43 = name(c); + unwind = 55; + const _44: Name.Name = name(d); + unwind = 53; + m = _43; + n = _44; + const _47: [Hop.Hop, Hop.Hop] = [{ _0: rt.u64Rem(c as rt.u64, 3) }, { _0: rt.u64Rem(d as rt.u64, 3) }]; + const x: Hop.Hop = copy$Hop(_47[0]); + const y: Hop.Hop = copy$Hop(_47[1]); + const _58: [Seen.Seen, Seen.Seen] = [seen(c, a, gr, m, x), seen(d, b, hr, n, y)]; + const l: Seen.Seen = _58[0]; + const r: Seen.Seen = _58[1]; + rt.byteVecPush(out, (Seen.eq$PartialEq(l, r) ? 1 : 0) | ((order(Seen.cmp$Ord(l, r)) << 1) & 0xff) | ((partial(Seen.partialCmp$PartialOrd(l, r)) << 3) & 0xff) | (((rt.u64Eq(hashOf$Seen(l), hashOf$Seen(r)) ? 1 : 0) << 5) & 0xff)); + const _102: [Skew.Skew, Skew.Skew] = [{ _0: rt.u8Rem(c, 4) }, { _0: rt.u8Rem(d, 4) }]; + const s: Skew.Skew = _102[0]; + const t: Skew.Skew = _102[1]; + const _111: [Skewed.Skewed, Skewed.Skewed] = [{ _0: s }, { _0: t }]; + const s2: Skewed.Skewed = _111[0]; + const t2: Skewed.Skewed = _111[1]; + const _119: boolean = Skewed.eq$PartialEq(s2, t2); + unwind = 53; + rt.byteVecPush(out, (_119 ? 1 : 0) | ((partial(Skewed.partialCmp$PartialOrd(s2, t2)) << 1) & 0xff)); + rt.byteVecPush(out, (rt.eqOption(Hop.eq$PartialEq)(a, b) ? 1 : 0) | (((Horizon.eq$PartialEq(gr, hr) ? 1 : 0) << 1) & 0xff) | (((Hop.eq$PartialEq(x, y) ? 1 : 0) << 2) & 0xff) | (((Hop.eq$PartialEq(x, y) ? 1 : 0) << 3) & 0xff) | (((Hop.eq$PartialEq(x, y) ? 1 : 0) << 4) & 0xff) | (((rt.u64Eq(hashOf$Hop(x), hashOf$Hop$2(y)) ? 1 : 0) << 5) & 0xff)); + unwind = 54; + rt.drop(n); + unwind = 0; + rt.drop(m); + } + } catch (e) { + b2: { + if (unwind === 0) { + throw e; + } + if (unwind === 53) { + rt.drop(n); + } else if (unwind !== 54) { + rt.drop(_43); + break b2; + } + rt.drop(m); + } + throw e; + } +} + /** `Option`s compared, ordered, and hashed, alone and in keys. */ export function options(data: Uint8Array, out: rt.ByteVec): void { let _10!: rt.usize; diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 77a72187c..bb1f37171 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -347,7 +347,7 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { bump(_124.slot); } arc = new rt.Arc(a); - unwind = 102; + unwind = 117; if (rt.u8Rem(a, 3) === 0) { flow = rt.Ok(Uint8Array.of(a)); } else { @@ -355,13 +355,13 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { } rt.byteVecPush(out, sameArc(flow, arc)); const _143: rt.Mutex = slot; - unwind = 101; + unwind = 116; rt.byteVecPush(out, _143.value); - unwind = 102; + unwind = 117; const _150: rt.Mutex = other; - unwind = 100; + unwind = 115; rt.byteVecPush(out, _150.value); - unwind = 102; + unwind = 117; const source: Held.Held = { at: copy$Point(Point.new(a as rt.i32, 0)) }; const kept: Held.Held = hold(copy$Point(source.at)); source.at.x = 9; @@ -370,10 +370,24 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { const part: rt.i32 = partMovedThenRead(copy$Held(source), source.at); const _172: rt.u8 = kept.at.x & 0xff; rt.byteVecExtendFromSlice(out, Uint8Array.of(_172, read & 0xff, by & 0xff, part & 0xff, source.at.x & 0xff)); - unwind = 102; + unwind = 117; const bytes: Uint8Array = Uint8Array.of(a, 1); rt.byteVecPush(out, unsizedCopy(bytes)); rt.byteVecPush(out, bytes[0]); + const at: rt.usize = rt.optionMapOr(rt.sliceGet(data, 1), 0, (_22: rt.u8): rt.usize => { + return rt.usizeRem(_22 as rt.usize, 3); + }); + rt.byteVecPush(out, writeAt(bytes, at, a)); + rt.byteVecExtendFromSlice(out, bytes); + const points: Point.Point[] = rt.vecFromElem(copy$Point(Point.new(a as rt.i32, 0)), 2, copy$Point); + unwind = 114; + movedAt(points, at); + const at2 = rt.idx(points, 0); + const _206: rt.u8 = points[at2].x & 0xff; + const at3 = rt.idx(points, 1); + const _210: rt.u8 = points[at3].x & 0xff; + const at4 = rt.idx(points, 1); + rt.byteVecExtendFromSlice(out, Uint8Array.of(_206, _210, points[at4].y & 0xff)); unwind = 0; rt.drop(arc); } catch (e) { @@ -385,6 +399,50 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { } } +/** + * `live[at]`, written with `b`, then changed through its first byte, and through a + * reborrow that may move past it: an index past the end panics as native Rust does. + */ +export function writeAt(live: Uint8Array, at: rt.usize, b: rt.u8): rt.u8 { + rt.idx(live, at); + live[at] = b; + rt.idx(live, at); + const _7: rt.u8 = rt.u8WrappingAdd(live[at], 1); + rt.idx(live, 0); + live[0] = live[0] ^ _7; + let rest: Uint8Array = live; + if (rt.u8Rem(b, 2) === 0) { + const _21: Uint8Array = rest; + rest = rt.sliceRange(_21, 1); + } + const _27: rt.usize = rest.length; + if (!(0 < _27)) { + rt.panic("index out of bounds: the len is " + _27 + " but the index is " + 0); + } + const _23: rt.u8 = rt.u8WrappingAdd(rest[0], 3); + const _31: rt.usize = rest.length; + if (!(0 < _31)) { + rt.panic("index out of bounds: the len is " + _31 + " but the index is " + 0); + } + rest[0] = _23; + rt.idx(live, at); + return live[at]; +} + +/** + * `live[at]` moved right by one, and its neighbor by its new `x`: an index past the end + * panics as native Rust does. + */ +export function movedAt(live: Point.Point[], at: rt.usize): void { + rt.idx(live, at); + const _6: rt.i32 = rt.i32Add(live[at].x, 1); + live[at].x = _6; + rt.idx(live, at); + const _7: rt.i32 = live[at].x; + rt.idx(live, 1); + live[1].y = _7; +} + /** `at`, held. */ export function hold(at: Point.Point): Held.Held { return { at }; diff --git a/ts/fixtures/lang/src/keys.rs b/ts/fixtures/lang/src/keys.rs index 1433a3081..89522f6a7 100644 --- a/ts/fixtures/lang/src/keys.rs +++ b/ts/fixtures/lang/src/keys.rs @@ -148,6 +148,22 @@ impl PartialEq for Picky { } } +/// Borrows, whose derived impls compare, order, and hash what they point at through +/// std's impls for references. +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] +enum Seen<'a> { + Hop(&'a Option), + Twice(&'a &'a Horizon), + Text(&'a str), + Name(&'a Name), + Mut(&'a mut Hop), +} + +/// A borrow of a `Skew`, whose derived `partial_cmp` reaches its own, not its `cmp`: a +/// derived `Ord` beside it would be called instead. +#[derive(PartialEq, PartialOrd)] +struct Skewed<'a>(&'a Skew); + /// Strings whose UTF-8 order differs from their UTF-16 order past U+FFFF. const WORDS: [&str; 6] = ["", "a", "ab", "\u{e000}", "\u{ffff}", "\u{10000}"]; @@ -216,13 +232,63 @@ fn find, Q: PartialEq + ?Sized>(keys: &[K], q: &Q) -> u8 { /// Run one case. pub fn keys(kind: u8, data: &[u8], out: &mut Vec) { - match kind % 3 { + match kind % 4 { 0 => options(data, out), 1 => arcs(data, out), + 2 => borrows(data, out), _ => places(data, out), } } +/// One of `Seen`'s variants, by `k`. +fn seen<'a>(k: u8, hop: &'a Option, horizon: &'a &'a Horizon, name: &'a Name, mine: &'a mut Hop) -> Seen<'a> { + match k % 5 { + 0 => Seen::Hop(hop), + 1 => Seen::Twice(horizon), + 2 => Seen::Text(WORDS[k as usize / 5 % WORDS.len()]), + 3 => Seen::Name(name), + _ => Seen::Mut(mine), + } +} + +/// Borrows compared, ordered, and hashed as what they point at, through one reference +/// or two, shared or mutable. +fn borrows(data: &[u8], out: &mut Vec) { + for i in 1..data.len() { + let (c, d) = (data[i - 1], data[i]); + let (a, b) = (hop(c), hop(d)); + let g = Horizon { + exclude: a, + local: c % 2 == 0, + }; + let h = Horizon { + exclude: b, + local: d % 2 == 0, + }; + let (gr, hr) = (&g, &h); + let (m, n) = (name(c), name(d)); + let (mut x, mut y) = (Hop(c as u64 % 3), Hop(d as u64 % 3)); + let (l, r) = (seen(c, &a, &gr, &m, &mut x), seen(d, &b, &hr, &n, &mut y)); + out.push( + (l == r) as u8 + | order(l.cmp(&r)) << 1 + | partial(l.partial_cmp(&r)) << 3 + | ((hash_of(&l) == hash_of(&r)) as u8) << 5, + ); + let (s, t) = (Skew(c % 4), Skew(d % 4)); + let (s, t) = (Skewed(&s), Skewed(&t)); + out.push((s == t) as u8 | partial(s.partial_cmp(&t)) << 1); + out.push( + (&a == &b) as u8 + | ((&gr == &hr) as u8) << 1 + | ((&mut x == &mut y) as u8) << 2 + | ((&x == &mut y) as u8) << 3 + | ((&mut x == &y) as u8) << 4 + | ((hash_of(&&mut x) == hash_of(&y)) as u8) << 5, + ); + } +} + /// `Option`s compared, ordered, and hashed, alone and in keys. fn options(data: &[u8], out: &mut Vec) { let mut hashed: HashMap<(u8, Horizon), u8> = HashMap::new(); diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 2914e447a..9990ff6b0 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -369,6 +369,35 @@ fn shares(data: &[u8], out: &mut Vec) { let mut bytes = [a, 1]; out.push(unsized_copy(&mut bytes)); out.push(bytes[0]); + let at = data.get(1).map_or(0, |&b| b as usize % 3); + out.push(write_at(&mut bytes, at, a)); + out.extend_from_slice(&bytes); + let mut points = vec![Point::new(a as i32, 0); 2]; + moved_at(&mut points, at); + out.extend_from_slice(&[points[0].x as u8, points[1].x as u8, points[1].y as u8]); +} + +/// `live[at]`, written with `b`, then changed through its first byte, and through a +/// reborrow that may move past it: an index past the end panics as native Rust does. +#[inline(never)] +fn write_at(live: &mut [u8], at: usize, b: u8) -> u8 { + live[at] = b; + live[0] ^= live[at].wrapping_add(1); + // Reassigned, so its bounds checks read its length apart from `rt.idx`. + let mut rest = &mut *live; + if b % 2 == 0 { + rest = &mut rest[1..]; + } + rest[0] = rest[0].wrapping_add(3); + live[at] +} + +/// `live[at]` moved right by one, and its neighbor by its new `x`: an index past the end +/// panics as native Rust does. +#[inline(never)] +fn moved_at(live: &mut [Point], at: usize) { + live[at].x += 1; + live[1].y = live[at].x; } /// A `Copy` struct holding another by value. diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 80b0d6956..4ab8c686f 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -122,6 +122,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } return call; } + if let Some(referent) = library::referent(tcx, def_id, gargs, instance) { + return self.call_def(def_id, referent, args, span, out); + } let call = library::Call { def_id, args: gargs, diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index ec30c2e41..9c3ebda37 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -240,6 +240,37 @@ fn is_std(tcx: TyCtxt<'_>, did: DefId) -> bool { matches!(tcx.crate_name(did.krate).as_str(), "core" | "alloc" | "std") } +/// If `instance` is a method of std's `PartialEq`, `PartialOrd`, `Ord`, or `Hash` impl +/// for references, which calls its referents' with the operands dereferenced, the +/// generic arguments of that call. A reference is its referent in JS, so the operands +/// pass as they are. +pub fn referent<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: DefId, + gargs: GenericArgsRef<'tcx>, + instance: Instance<'tcx>, +) -> Option> { + let tr = tcx.trait_of_assoc(def_id)?; + // A method the impl leaves to its trait's default, as `Ord::max` is, is not forwarded. + let imp = tcx.impl_of_assoc(instance.def_id())?; + if !is_std(tcx, imp) { + return None; + } + let operands = match tcx.get_diagnostic_name(tr)?.as_str() { + "PartialEq" | "PartialOrd" => 2, + "Ord" | "Hash" => 1, + _ => return None, + }; + let mut args = gargs.to_vec(); + for arg in &mut args[..operands] { + let ty::Ref(_, pointee, _) = arg.as_type()?.kind() else { + return None; + }; + *arg = (*pointee).into(); + } + Some(tcx.mk_args(&args)) +} + /// Whether `Clone` of `ty`, a `Copy` type, only copies: no `Clone` written by hand runs /// for it or anything in it, as a derived or std `Clone` clones each field. pub fn clone_copies<'tcx>(t: &super::Translator<'_, 'tcx>, ty: Ty<'tcx>) -> bool { diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 80606b4fe..8eca465ac 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -220,6 +220,9 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { /// it: its `rt.Place` or `undefined`, which is only tested, unwrapped, or taken apart /// into a reference that reads and writes through it. place_opts: FxHashSet, + /// The paths a switch lowered so far tests the variant of, which `tsc` narrows in + /// its arms. + switched: FxHashSet, } impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { @@ -274,6 +277,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { halves: FxHashMap::default(), joined: FxHashSet::default(), place_opts: FxHashSet::default(), + switched: FxHashSet::default(), }; fx.analyze(); fx @@ -381,12 +385,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { for (cond, len, index) in bounds { if let Operand::Copy(l) | Operand::Move(l) = len && let Some(l) = l.as_local() - && let Some(Rvalue::UnaryOp(mir::UnOp::PtrMetadata, Operand::Copy(slice) | Operand::Move(slice))) = - self.def_rvalue(l) - && self.stable(*slice) + && let Some(slice) = self.measured(l) + && self.stable(slice) { - self.idx_of.insert(l, *slice); - self.place_use(*slice); + self.idx_of.insert(l, slice); + self.place_use(slice); self.operand_use(index); continue; } @@ -490,7 +493,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { { match &assign.1 { // One that can throw is lowered even unread, so it keeps its reads. - r @ (Rvalue::BinaryOp(..) | Rvalue::UnaryOp(..) | Rvalue::Use(..)) + r @ (Rvalue::BinaryOp(..) + | Rvalue::UnaryOp(..) + | Rvalue::Use(..) + | Rvalue::RawPtr(mir::RawPtrKind::FakeForPtrMetadata, _)) if !rvalue::effect(r, self) => { computed[local].push(r) @@ -509,21 +515,20 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { continue; } for rvalue in std::mem::take(&mut computed[local]) { - let ops: Vec<&Operand<'tcx>> = match rvalue { - Rvalue::BinaryOp(_, ops) => vec![&ops.0, &ops.1], - Rvalue::UnaryOp(_, op) | Rvalue::Use(op, _) => vec![op], + let read: Vec> = match rvalue { + Rvalue::BinaryOp(_, ops) => [&ops.0, &ops.1].into_iter().filter_map(Operand::place).collect(), + Rvalue::UnaryOp(_, op) | Rvalue::Use(op, _) => op.place().into_iter().collect(), + Rvalue::RawPtr(_, p) => vec![*p], _ => unreachable!("collected above"), }; - for op in ops { - if let Operand::Copy(p) | Operand::Move(p) = op { - self.uses[p.local] -= 1; - for elem in p.projection { - if let mir::ProjectionElem::Index(index) = elem { - self.uses[index] -= 1; - } + for p in read { + self.uses[p.local] -= 1; + for elem in p.projection { + if let mir::ProjectionElem::Index(index) = elem { + self.uses[index] -= 1; } - work.push(p.local); } + work.push(p.local); } } } @@ -637,6 +642,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } } + // Only `PtrMetadata` reads a fake borrow, so it borrows nothing. + Rvalue::RawPtr(mir::RawPtrKind::FakeForPtrMetadata, place) => self.place_use(*place), Rvalue::RawPtr(_, place) => { self.place_use(*place); if own(*place) { @@ -1068,6 +1075,20 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// The slice whose length `len` is assigned: by `PtrMetadata` of a reference to it, or + /// of the fake raw pointer to it a bounds check of a `&mut` slice reads. + fn measured(&self, len: Local) -> Option> { + let Some(Rvalue::UnaryOp(mir::UnOp::PtrMetadata, Operand::Copy(slice) | Operand::Move(slice))) = + self.def_rvalue(len) + else { + return None; + }; + match slice.as_local().and_then(|raw| self.def_rvalue(raw)) { + Some(Rvalue::RawPtr(mir::RawPtrKind::FakeForPtrMetadata, place)) => self.stable(*slice).then_some(*place), + _ => Some(*slice), + } + } + /// Whether `place` names the same memory wherever it is read: every local in it is /// assigned at most once. fn stable(&self, place: Place<'tcx>) -> bool { @@ -2074,6 +2095,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { }; let tests: Vec<(Expr, BasicBlock)> = match discr_local.map(|l| self.slots[l].clone()) { Some(Slot::Discr(Some((scrut, ty)))) => { + if !arms.is_empty() { + self.switched.extend(scrut.path_key()); + } let tests: Vec = arms .iter() .map(|&(value, _)| self.variant_test(&scrut, ty, value, span)) diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index e2f4c869b..f7e923b1c 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -113,7 +113,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ProjectionElem::Field(field, _) => { e = self.field(e, ty, pty.variant_index, field, span); } - ProjectionElem::Downcast(..) => {} + ProjectionElem::Downcast(_, variant) => { + if !e.path_key().is_some_and(|key| self.switched.contains(&key)) { + e = self.as_variant(e, ty, variant, span); + } + } ProjectionElem::Index(index) => { let i = self.local_expr(index, span); e = e.index(i); @@ -179,6 +183,26 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { )) } + /// `base`, a `ty`, cast to its `variant`, which MIR reads without a switch where the + /// others can't be, as a derived `==` reads the other operand after comparing + /// discriminants. `tsc` narrows only what a switch tests. + fn as_variant(&mut self, base: Expr, ty: Ty<'tcx>, variant: VariantIdx, span: Span) -> Expr { + let tcx = self.tcx; + let ty::Adt(adt, args) = ty.kind() else { + return base; + }; + if !adt.did().is_local() || !matches!(self.b.t.adt(*adt, span).repr, AdtRepr::Union) { + return base; + } + let def = adt.variant(variant); + let mut fields = vec![("tag".to_string(), crate::ts::Type::StrLit(def.name.to_string()))]; + for (i, field) in def.fields.iter().enumerate() { + let ty = self.b.t.ty(field.ty(tcx, args).skip_norm_wip(), span); + fields.push((crate::lower::field_name(field.name.as_str(), i), ty)); + } + Expr::As(Box::new(base), crate::ts::Type::Object(fields)) + } + /// A field of `base`, a `ty`, in `variant` if it was downcast to one. fn field(&mut self, base: Expr, ty: Ty<'tcx>, variant: Option, field: FieldIdx, span: Span) -> Expr { let tcx = self.tcx; diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 7b9719c28..58354df10 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -45,6 +45,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } self.place_expr(*place, span, out) } + // A bounds check of a `&mut` slice reads its length through a raw pointer that + // only `PtrMetadata` reads, which reads the slice's. + Rvalue::RawPtr(mir::RawPtrKind::FakeForPtrMetadata, place) => self.place_expr(*place, span, out), Rvalue::RawPtr(..) => self.err(span, "raw pointers are not supported"), Rvalue::Reborrow(..) => self.err(span, "reborrowing a type by its `Reborrow` impl is not supported"), Rvalue::ThreadLocalRef(_) => self.err(span, "thread locals are not supported"), diff --git a/ts/src/ts.rs b/ts/src/ts.rs index d88ba77a1..a88c7da5f 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -151,6 +151,23 @@ impl Expr { } } + /// The text of a path of names, the same for two paths that read the same place. + pub fn path_key(&self) -> Option { + match self { + Self::Ident(name) => Some(name.clone()), + Self::This => Some("this".into()), + Self::Member(base, key) => { + let key = match key { + Key::Name(name) => name.clone(), + Key::Field(id) => format!("#{id}"), + }; + Some(format!("{}.{key}", base.path_key()?)) + } + Self::Located(_, e) => e.path_key(), + _ => None, + } + } + /// Whether evaluating this twice is free and gives the same value both times, so a /// pattern may read it more than once: a name, or a member path from one. pub fn is_path(&self) -> bool {