From 61cb486a60e471e2f4229e99faef299080c2809c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:36:04 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m2/ts-swap-parts.md Quest-Claim: f7fd94ad57eeb7d3 From e00ca14681749555863983c2f5b35e7e69a67bd5 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:28:13 -0700 Subject: [PATCH 2/2] fix(ts): read a tuple's parts as they were when it was made A reference part of a tuple read later was its operand's path, even when that path is a variable assigned another first, so `(a, b) = (b, a)` in a loop lowered to `a = b; b = a;`. Whether a part rereads the same is now judged from MIR: a copy of a reference by where it is copied from, a borrow by what it borrows. Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 - quest/m2/ts-swap-parts.md | 24 ---- .../expected/coding/decode.DecodeError.ts | 4 +- ts/fixtures/lang/expected/fmt.ts | 12 +- ts/fixtures/lang/expected/shapes.ts | 66 +++++++---- ts/fixtures/lang/expected/splits.ts | 86 +++++++++------ ts/fixtures/lang/src/shapes.rs | 14 +++ ts/fixtures/lang/src/splits.rs | 8 ++ ts/fixtures/task/expected/drops.ts | 4 +- ts/src/lower/mir/mod.rs | 104 +++++++++++++++--- ts/src/lower/mir/place.rs | 4 +- ts/src/lower/mir/rvalue.rs | 2 +- 12 files changed, 223 insertions(+), 106 deletions(-) delete mode 100644 quest/m2/ts-swap-parts.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 572d2f664..79d9541f1 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -26,7 +26,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export/README ## Required -- [A tuple's parts read after their variables change](/quest/m2/ts-swap-parts.md) - `(a, b) = (b, a)` swaps instead of copying one into both - [Fixture cases by name](/quest/m2/ts-harness-names.md) - adding a harness case never renumbers another - [Byte slices without objects](/quest/m2/ts-byte-views/README.md) - reading through a translated cursor allocates no object per read - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it diff --git a/quest/m2/ts-swap-parts.md b/quest/m2/ts-swap-parts.md deleted file mode 100644 index 02e12e874..000000000 --- a/quest/m2/ts-swap-parts.md +++ /dev/null @@ -1,24 +0,0 @@ -# [S] A tuple's parts read after their variables change - -## Goal - -rust2-ts translates a tuple built from variables and read after one of them is -reassigned with the value it held when built, so `(a, b) = (b, a)` on two `&[u8]` in a -loop swaps them instead of translating to `a = b; b = a;`, proven by a differential test -against native Rust. - -## Plan - -Found by [#130](https://github.com/kixelated/rust2/pull/130) on 2026-10-27: a swap in its -`splits` fixture gave 74 differences in about 344k cases, so the committed fixture leaves -the pattern out. The cause is on main: the `var_parts` arm of `place_expr` in -`ts/src/lower/mir/place.rs` reads a once-built tuple's field as the operand it was built -from, even when that operand is a variable reassigned before the read. - -Decided with the maintainer on 2026-10-27: a silent miscompile, so it ranks first in m2. - -- Fix it where the parts are recorded or read, for every operand kind, not only byte - slices; check the other readers of `var_parts`. -- Put the swap back in the lang fixture, inside a loop. - -Public API: the translator's output. diff --git a/ts/fixtures/codec/expected/coding/decode.DecodeError.ts b/ts/fixtures/codec/expected/coding/decode.DecodeError.ts index 140a7aa7e..2dab66fbd 100644 --- a/ts/fixtures/codec/expected/coding/decode.DecodeError.ts +++ b/ts/fixtures/codec/expected/coding/decode.DecodeError.ts @@ -35,7 +35,9 @@ export function fmt$Display(self: DecodeError, __formatter: rt.Formatter): rt.Re return rt.fmtWriteStr(__formatter, "expected end"); } if (self.tag === "MessageTooLarge") { - const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(self.size, f), (f: rt.Formatter) => rt.usizeDisplay(self.max, f)]; + const _26: rt.usize = self.size; + const _28: rt.usize = self.max; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_26, f), (f: rt.Formatter) => rt.usizeDisplay(_28, f)]; return rt.fmtWriteFmt(__formatter, ["message too large: ", args4[0], " bytes exceeds ", args4[1], " byte limit"]); } if (self.tag === "ExpectedData") { diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 75e14999c..e14b75c5a 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -422,8 +422,8 @@ export function panics(kind: rt.u8, rest: rt.ByteSlice, out: rt.ByteVec): void { const _129: rt.u8 = rt.optionExpect(missing, rt.fmtFormat(["missing ", args10[0]])); put(out, rt.fmtToString((f: rt.Formatter) => rt.u8Display(_129, f))); } else if (_7 === 11) { - const part7 = { _0: n }; - const args12: rt.Fmt[] = [(f: rt.Formatter) => Fails.fmt$Display(part7, f)]; + const part5 = { _0: n }; + const args12: rt.Fmt[] = [(f: rt.Formatter) => Fails.fmt$Display(part5, f)]; put(out, rt.fmtFormat([args12[0]])); } else if (_7 === 12) { const _157: Fails.Fails = { _0: n }; @@ -444,8 +444,8 @@ export function panics(kind: rt.u8, rest: rt.ByteSlice, out: rt.ByteVec): void { } else if (_7 === 15) { const buf: Uint8Array = rt.bytes(3); rt.byteSliceCopyFromSlice(rt.byteSliceFrom(buf), rt.byteSliceRange(rest, 0, rt.min(rest.length, 4))); - const part6 = rt.byteSliceFrom(buf); - const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(part6), f, rt.u8Display)]; + const arg3 = rt.byteSliceFrom(buf); + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arg3), f, rt.u8Display)]; put(out, rt.fmtFormat([args18[0]])); } else if (_7 === 16) { const _221: rt.Result = rt.stringFromUtf8(rt.byteSliceToByteVec(rest)); @@ -462,8 +462,8 @@ export function panics(kind: rt.u8, rest: rt.ByteSlice, out: rt.ByteVec): void { const part3 = rt.u8Rem(rt.u8Div(n, 6), 6) as rt.usize; const dest: rt.usize = rt.usizeRem(unwrapOr$Option_u8(rt.byteSliceGet(rest, 1), 0) as rt.usize, 4); rt.byteSliceCopyWithin(rt.byteSliceFrom(buf2), part2, part3, dest); - const part4 = rt.byteSliceFrom(buf2); - const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(part4), f, rt.u8Display)]; + const arg2 = rt.byteSliceFrom(buf2); + const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arg2), f, rt.u8Display)]; put(out, rt.fmtFormat([args20[0]])); } else if (_7 === 18) { const _271: rt.usize = rt.u8Rem(n, 8) as rt.usize; diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 3288bdbff..8e7307f24 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -95,9 +95,9 @@ export function shape(data: rt.ByteSlice): Shape.Shape { /** `Copy` aggregates: a copy changes apart from its original. */ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { - let _211!: Uint8Array; + let _265!: Uint8Array; let poll!: rt.Poll; - let _246!: rt.u8; + let _300!: rt.u8; const p: Point.Point = Point.new(unwrapOr$Option_u8(rt.byteSliceFirst(data), 0) as rt.i32, 7); const q: Point.Point = copy$Point(p); q.x = rt.i32Add(q.x, 100); @@ -143,6 +143,34 @@ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { const both: [rt.u32, rt.u32] = [n, n]; n = 9; rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u32ToBeBytes(rt.u32Add(rt.u32Add(both[0], both[1]), n)))); + let s: string = "ab"; + let t: string = "cde"; + let x: Point.Point = p; + let y: Point.Point = q; + const _120: [rt.u8, rt.u8] = [data.length & 0xff, 1]; + let i: rt.u8 = _120[0]; + let j: rt.u8 = 1; + const _125: rt.usize = rt.usizeRem(data.length, 3); + let iterStart: rt.usize = 0; + const iterEnd: rt.usize = _125; + while (iterStart++ < iterEnd) { + const _135: string = t; + const _136: string = s; + s = _135; + t = _136; + const _140: Point.Point = y; + const _141: Point.Point = x; + x = _140; + y = _141; + const _144: [rt.u8, rt.u8] = [j, i]; + const _142: rt.u8 = _144[0]; + const _143: rt.u8 = _144[1]; + i = _142; + j = _143; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(s)); + rt.byteVecPush(out, (x.x & 0xff) ^ i); + } + rt.byteVecPush(out, (rt.stringLen(t) & 0xff) ^ (y.y & 0xff) ^ j); const word: Uint8Array = Uint8Array.of(0, 0, 0, data.length & 0xff); const converted: rt.u32 = rt.u32FromBeBytes(word); word[0] = 9; @@ -182,24 +210,24 @@ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { shape_.width = 6; } } - const _202: Shape.Shape = copy$Shape(shape_); - const iter2: rt.Iter = rt.iterSlice([copy$Shape(before), _202]); + const _256: Shape.Shape = copy$Shape(shape_); + const iter3: rt.Iter = rt.iterSlice([copy$Shape(before), _256]); while (true) { - const _204: Shape.Shape | rt.Done = iter2.next(); - if (_204 === rt.DONE) { + const _258: Shape.Shape | rt.Done = iter3.next(); + if (_258 === rt.DONE) { break; } - const shape2: Shape.Shape = _204; + const shape2: Shape.Shape = _258; if (shape2.tag === "Dot") { - _211 = rt.bytes(3); + _265 = rt.bytes(3); } else if (shape2.tag === "Line") { const from: Point.Point = shape2._0; - _211 = Uint8Array.of(1, from.x & 0xff, from.y & 0xff); + _265 = Uint8Array.of(1, from.x & 0xff, from.y & 0xff); } else { const corner: Point.Point = shape2.corner; - _211 = Uint8Array.of(corner.x & 0xff, corner.y & 0xff, shape2.width & 0xff); + _265 = Uint8Array.of(corner.x & 0xff, corner.y & 0xff, shape2.width & 0xff); } - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(_211)); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(_265)); } if (rt.usizeRem(data.length, 2) === 0) { poll = rt.Pending as rt.Poll; @@ -211,20 +239,20 @@ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { const bytes: rt.ByteSlice = rt.byteSliceFrom(poll); bytes.data[bytes.start] = 9; } - const _239: rt.Poll = copy$Poll_u8s(poll); - const iter3: rt.Iter> = rt.iterSlice([copy$Poll_u8s(polled_), _239]); + const _293: rt.Poll = copy$Poll_u8s(poll); + const iter4: rt.Iter> = rt.iterSlice([copy$Poll_u8s(polled_), _293]); while (true) { - const _241: rt.Poll | rt.Done = iter3.next(); - if (_241 === rt.DONE) { + const _295: rt.Poll | rt.Done = iter4.next(); + if (_295 === rt.DONE) { break; } - const poll2: rt.Poll = _241; + const poll2: rt.Poll = _295; if (poll2 !== rt.Pending) { - _246 = poll2[0]; + _300 = poll2[0]; } else { - _246 = 255; + _300 = 255; } - rt.byteVecPush(out, _246); + rt.byteVecPush(out, _300); } shares(data, out); unwritten(data, out); diff --git a/ts/fixtures/lang/expected/splits.ts b/ts/fixtures/lang/expected/splits.ts index 8f52357aa..17a353e13 100644 --- a/ts/fixtures/lang/expected/splits.ts +++ b/ts/fixtures/lang/expected/splits.ts @@ -58,7 +58,7 @@ export function code(out: rt.ByteVec, n: rt.u8): rt.u8 { export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { let _58!: rt.u8; - let _139!: rt.u8; + let _169!: rt.u8; let err!: Short.Short; const _4: rt.u8 = rt.u8Rem(kind, 8); if (_4 === 0) { @@ -86,12 +86,12 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, sum); rt.byteVecExtendFromSlice(out, new rt.ByteSlice(restData, restStart, restLen)); } else if (_4 === 1) { - const mid3: number = rt.u8Rem(unwrapOr$Option_u8(rt.byteSliceFirst(data), 0), 8) as rt.usize; - if (mid3 > data.length) { + const mid4: number = rt.u8Rem(unwrapOr$Option_u8(rt.byteSliceFirst(data), 0), 8) as rt.usize; + if (mid4 > data.length) { rt.panic("mid > len"); } - rt.byteVecPush(out, mid3 & 0xff); - rt.byteVecExtendFromSlice(out, new rt.ByteSlice(data.data, data.start + mid3, data.length - mid3)); + rt.byteVecPush(out, mid4 & 0xff); + rt.byteVecExtendFromSlice(out, new rt.ByteSlice(data.data, data.start + mid4, data.length - mid4)); } else if (_4 === 2) { const _33: rt.Result<[rt.u8, rt.u16, rt.ByteSlice], Short.Short> = header(data); if (_33.ok) { @@ -106,17 +106,17 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, 241 ^ (_33.error._0 & 0xff)); } } else if (_4 === 3) { - const mid2: number = rt.usizeDiv(data.length, 2); - if (mid2 > data.length) { + const mid3: number = rt.usizeDiv(data.length, 2); + if (mid3 > data.length) { rt.panic("mid > len"); } - const head: rt.ByteSlice = new rt.ByteSlice(data.data, data.start, mid2); + const head: rt.ByteSlice = new rt.ByteSlice(data.data, data.start, mid3); let iterStart: rt.u8 = 0; const iterEnd: rt.u8 = 3; while ((_58 = iterStart++) < iterEnd) { rt.byteVecPush(out, opaque(head) ^ _58); } - rt.byteVecPush(out, opaque(new rt.ByteSlice(data.data, data.start + mid2, data.length - mid2))); + rt.byteVecPush(out, opaque(new rt.ByteSlice(data.data, data.start + mid3, data.length - mid3))); } else if (_4 === 4) { const mid: number = rt.usizeDiv(data.length, 3); if (mid > data.length) { @@ -147,20 +147,38 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } rt.byteVecPush(out, pair_0Len & 0xff); if (!((pair_1Len === 0))) { - const _194Len: number = pair_1Len; - if (0 >= _194Len) { - rt.panic("index out of bounds: the len is " + _194Len + " but the index is " + 0); + const _224Len: number = pair_1Len; + if (0 >= _224Len) { + rt.panic("index out of bounds: the len is " + _224Len + " but the index is " + 0); } rt.byteVecPush(out, pair_1Data[pair_1Start]); } rt.byteVecExtendFromSlice(out, new rt.ByteSlice(pair_0Data, pair_0Start, pair_0Len)); + const mid2: number = rt.usizeDiv(data.length, 2); + if (mid2 > data.length) { + rt.panic("mid > len"); + } + let a3: rt.ByteSlice = new rt.ByteSlice(data.data, data.start, mid2); + let b4: rt.ByteSlice = new rt.ByteSlice(data.data, data.start + mid2, data.length - mid2); + const _101: rt.usize = rt.usizeRem(data.length, 3); + let iterStart3: rt.usize = 0; + const iterEnd3: rt.usize = _101; + while (iterStart3++ < iterEnd3) { + const _111: rt.ByteSlice = b4; + const _112: rt.ByteSlice = a3; + a3 = _111; + b4 = _112; + rt.byteVecPush(out, opaque(a3)); + } + rt.byteVecPush(out, a3.length & 0xff); + rt.byteVecPush(out, opaque(b4)); } else if (_4 === 5) { let rest2: rt.ByteSlice = data; while (true) { - const _94: [rt.u8, rt.u8, rt.ByteSlice] | undefined = two(rest2); - if (_94 !== undefined) { - rt.byteVecPush(out, _94[0] ^ _94[1]); - rest2 = _94[2]; + const _124: [rt.u8, rt.u8, rt.ByteSlice] | undefined = two(rest2); + if (_124 !== undefined) { + rt.byteVecPush(out, _124[0] ^ _124[1]); + rest2 = _124[2]; } else { break; } @@ -170,8 +188,8 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const split: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitFirstChunk(data, 4); b5: { if (split !== undefined) { - const _197: rt.ByteSlice = split[0]; - if ((_197.data[_197.start] & 1) === 0) { + const _227: rt.ByteSlice = split[0]; + if ((_227.data[_227.start] & 1) === 0) { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u32ToBeBytes(rt.u32WrappingAdd(((split[0].data[split[0].start] << 24) | (split[0].data[split[0].start + 1] << 16) | (split[0].data[split[0].start + 2] << 8) | split[0].data[split[0].start + 3]) >>> 0, 3)))); rt.byteVecPush(out, split[1].length & 0xff); break b5; @@ -181,18 +199,18 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { return _2[0].data[_2[0].start + 3] ^ (_2[1].length & 0xff); })); } - const _129: rt.Result<[rt.ByteSlice, rt.ByteSlice], Short.Short> = take(data, 3); - if (_129.ok) { - rt.byteVecPush(out, opaque(_129.value[0])); - rt.byteVecPush(out, _129.value[1].length & 0xff); + const _159: rt.Result<[rt.ByteSlice, rt.ByteSlice], Short.Short> = take(data, 3); + if (_159.ok) { + rt.byteVecPush(out, opaque(_159.value[0])); + rt.byteVecPush(out, _159.value[1].length & 0xff); } else { - const e: Short.Short = _129.error; + const e: Short.Short = _159.error; if (e.tag === "Empty") { - _139 = 0; + _169 = 0; } else { - _139 = e._0 & 0xff; + _169 = e._0 & 0xff; } - rt.byteVecPush(out, _139); + rt.byteVecPush(out, _169); } } else { const first2: rt.u8 = code(out, 7); @@ -207,21 +225,21 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } else { err = { tag: "Need", _0: data.length } as Short.Short; } - const _1602: Short.Short = err; + const _1902: Short.Short = err; if (data.length !== 0) { rt.byteVecPush(out, data.data[data.start]); - } else if (_1602.tag === "Empty") { + } else if (_1902.tag === "Empty") { rt.byteVecPush(out, 224); } else { - rt.byteVecPush(out, 225 ^ (_1602._0 & 0xff)); + rt.byteVecPush(out, 225 ^ (_1902._0 & 0xff)); } - const _170: rt.Result = second(data, rt.byteSliceFirst(data)); - if (_170.ok) { - rt.byteVecPush(out, _170.value); - } else if (_170.error === undefined) { + const _200: rt.Result = second(data, rt.byteSliceFirst(data)); + if (_200.ok) { + rt.byteVecPush(out, _200.value); + } else if (_200.error === undefined) { rt.byteVecPush(out, 170); } else { - rt.byteVecPush(out, _170.error ^ 85); + rt.byteVecPush(out, _200.error ^ 85); } if (2 <= data.length) { rt.byteVecPush(out, data.data[data.start + 1] ^ ((data.length - 2) & 0xff)); diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 60bcc47e3..bc56bca64 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -193,6 +193,20 @@ pub fn copies(data: &[u8], out: &mut Vec) { n = 9; out.extend_from_slice(&(both.0 + both.1 + n).to_be_bytes()); + // So does a tuple of references, though the variables they came from are assigned + // others: a swap in a loop. + let (mut s, mut t) = ("ab", "cde"); + let (mut x, mut y) = (&p, &q); + let (mut i, mut j) = (data.len() as u8, 1u8); + for _ in 0..data.len() % 3 { + (s, t) = (t, s); + (x, y) = (y, x); + (i, j) = (j, i); + out.extend_from_slice(s.as_bytes()); + out.push(x.x as u8 ^ i); + } + out.push(t.len() as u8 ^ y.y as u8 ^ j); + // A value computed from a call keeps that call before a later one, though it is read // after. // A conversion reads its bytes before they change. diff --git a/ts/fixtures/lang/src/splits.rs b/ts/fixtures/lang/src/splits.rs index 8ea337d68..02d7709e8 100644 --- a/ts/fixtures/lang/src/splits.rs +++ b/ts/fixtures/lang/src/splits.rs @@ -95,6 +95,14 @@ pub fn splits(kind: u8, data: &[u8], out: &mut Vec) { out.push(pair.1[0]); } out.extend_from_slice(pair.0); + // Two variables swapped through a tuple, which reads each before either changes. + let (mut a, mut b) = data.split_at(data.len() / 2); + for _ in 0..data.len() % 3 { + (a, b) = (b, a); + out.push(opaque(a)); + } + out.push(a.len() as u8); + out.push(opaque(b)); } 5 => { let mut rest = data; diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 3f3c53038..72c049577 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -2151,7 +2151,9 @@ export function arcs(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind = 94; _193 = true; _194 = false; - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, max.value), (f: rt.Formatter) => rt.fmtPad(f, min.value)]; + const _92: string = max.value; + const _96: string = min.value; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _92), (f: rt.Formatter) => rt.fmtPad(f, _96)]; Log.note(log, rt.fmtFormat(["max ", args2[0], " min ", args2[1]])); count("name", name); count("other", other); diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index d1bd3c203..9e5934bc0 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -185,6 +185,8 @@ struct Pending { copy: bool, /// Whether it is an aggregate's part, with no variable of its own until emitted. decl: bool, + /// Whether reading it again, wherever and however often, reads the same. + rereads: bool, } pub struct Fx<'m, 'b, 'a, 'tcx> { @@ -1650,6 +1652,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// The value held back for `local`, if it is. + fn held(&self, local: Local) -> Option<&Pending> { + let name = self.var(local)?; + self.pending.iter().find(|p| p.name == name) + } + /// Whether `local` can be held back as a pending temporary: one assignment, one read. fn foldable(&self, local: Local) -> bool { matches!(self.slots[local], Slot::Var(_)) @@ -1670,21 +1678,61 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { && !self.mutated[local] } - /// Whether the operand `e` reads the same wherever and however often it is read: a - /// path, with what it folds in that is held back a constant, a name nothing changes, or - /// a reference to a path, which borrow checking keeps as it is. - fn rereadable(&self, e: &Expr) -> bool { - let mut names = Vec::new(); - reads_of(e, &mut names); - e.is_path() - && self.pending.iter().filter(|p| names.contains(&p.name)).all(|p| { - p.value.is_constant() - || self.stable_name(&p.value) - || p.value.is_path() - && self - .local_named(&p.name) - .is_some_and(|local| self.mir.local_decls[local].ty.is_ref()) - }) + /// Whether reading `place` again, wherever and however often, reads what it reads now: + /// a place nothing changes, a value held back that rereads the same, or a reference + /// read as what it is assigned. + fn rereads(&self, place: Place<'tcx>) -> bool { + match (self.held(place.local), &self.slots[place.local]) { + (Some(p), _) => place.projection.is_empty() && p.rereads, + (None, Slot::Alias(_)) => { + place.projection.is_empty() + && self + .def_rvalue(place.local) + .is_some_and(|rvalue| self.rvalue_rereads(rvalue)) + } + _ => { + self.stable(place) + && !self.mutated[place.local] + && place + .projection + .iter() + .all(|e| !matches!(e, mir::ProjectionElem::Deref)) + } + } + } + + /// Whether `rvalue`, read again, reads what it reads now: a constant, a copy of a place + /// that rereads the same, or a borrow, which borrow checking keeps as it is, unless the + /// path to it goes through a reference that can be replaced first. A copy of a + /// reference is read from where it is copied, which can be assigned another. + fn rvalue_rereads(&self, rvalue: &Rvalue<'tcx>) -> bool { + match rvalue { + Rvalue::Use(Operand::Constant(_), _) => true, + Rvalue::Use(Operand::Copy(from) | Operand::Move(from), _) | Rvalue::CopyForDeref(from) => { + self.rereads(*from) + } + Rvalue::Ref(_, _, from) => { + let fixed = |l: Local| self.defs[l] <= 1 && (!self.is_arg(l) || self.defs[l] == 0); + let root = Place::from(from.local); + from.projection.iter().all(|e| match e { + mir::ProjectionElem::Index(index) => fixed(index), + _ => true, + }) && match from + .projection + .iter() + .rposition(|e| matches!(e, mir::ProjectionElem::Deref)) + { + // The borrow keeps a variable as it is, but not a value held back. + None => match self.slots[from.local] { + Slot::Var(_) if self.held(from.local).is_none() => true, + _ => self.rereads(root), + }, + Some(0) => self.rereads(root), + Some(_) => false, + } + } + _ => false, + } } // Emission @@ -1867,7 +1915,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } /// Hold back `value`, the assignment of `local`, to fold into what reads it. - fn hold(&mut self, local: Local, value: Expr, effect: bool, memory: bool, parts: Option>) { + fn hold( + &mut self, + local: Local, + value: Expr, + effect: bool, + memory: bool, + parts: Option>, + rereads: bool, + ) { let name = self.var(local).expect("a pending local is a variable").to_string(); self.order += 1; let mut reads = Vec::new(); @@ -1883,6 +1939,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { reads, copy, decl: false, + rereads, }); } @@ -1902,6 +1959,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { reads, copy: false, decl: false, + rereads: false, }); } @@ -1955,6 +2013,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { reads, copy: false, decl: true, + rereads: false, }, ); held += 1; @@ -2031,6 +2090,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return; } if self.foldable(local) { + // A borrow rereads the same by what it borrows, judged before what that + // reads that is held back folds into it; anything else only as a constant + // or a name that stays put. + let borrow = self + .def_rvalue(local) + .is_some_and(|rvalue| matches!(rvalue, Rvalue::Ref(..)) && self.rvalue_rereads(rvalue)); // What it reads that is held back folds into it first, so nothing held // back reads another, and its effects and reads go with it. let mut reads = Vec::new(); @@ -2044,7 +2109,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let value = folded.pop().unwrap(); let parts = parts.and_then(|rereadable| Some(parts_of(&value)?.into_iter().zip(rereadable).collect())); - self.hold(local, value, effect, memory, parts); + let mut bare = &value; + while let Expr::Located(_, e) = bare { + bare = e; + } + let rereads = borrow || value.is_constant() || self.stable_name(bare); + self.hold(local, value, effect, memory, parts, rereads); return; } self.assigned[local] = true; diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 2ce916c83..84c3d6b02 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -108,8 +108,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { part } // A field of an aggregate made once and never changed is its operand: a - // reference, held in a path when the aggregate is made, which borrow checking - // keeps as it was, or a name that stays put. + // reference, held in a path when the aggregate is made unless it reads the same + // later, or a name that stays put. (_, _) if let Some(parts) = self.var_parts.get(&place.local) && let Some(ProjectionElem::Field(field, field_ty)) = projection.peek() diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 1459962f4..f277f3ead 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -308,7 +308,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { for op in ops.iter() { let v = self.operand(op, span, out); let is_ref = op.ty(&self.mir.local_decls, self.tcx).is_ref(); - let reread = is_ref && self.rereadable(&v); + let reread = is_ref && v.is_path() && op.place().is_none_or(|place| self.rereads(place)); let v = match parts_read && is_ref && !reread { true => self.path(v, "part", out), false => v,