From ee34df3f7854301912beb71b1e347362d83d4cd8 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:01:34 -0700 Subject: [PATCH 1/2] quest: operands in order around indexing Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 + quest/m2/ts-index-order.md | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 quest/m2/ts-index-order.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 1e9b2c2e6..085b7010a 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -24,6 +24,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [MIR's codec as fast as THIR's](/quest/m2/ts-mir-codec.md) - the codec from MIR no slower than from THIR in any engine - [Lower bodies from MIR](/quest/m2/ts-mir.md) - the MIR spike's prototype becomes the only lowering, and the THIR one goes - [Struct update on a std range](/quest/m2/ts-range-update.md) - `Range { start, ..r }` reads its base, or is refused with a span, instead of dropping it or panicking the driver +- [Operands in order around indexing](/quest/m2/ts-index-order.md) - an index or `copy_within`'s `dest` with statements runs after the value it indexes or copies within - [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split - [Wide-integer fast paths](/quest/m2/ts-wide-fast.md) - a fused `from_halves` and an unboxed limb product, kept only if measured faster - [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-index-order.md b/quest/m2/ts-index-order.md new file mode 100644 index 000000000..5d0dc9de3 --- /dev/null +++ b/quest/m2/ts-index-order.md @@ -0,0 +1,19 @@ +# [XS] Operands evaluate in order around indexing + +## Goal + +[rust2-ts](/ts/README.md)'s THIR lowering evaluates the value being indexed, or the +slice `copy_within` reads, before an index or `dest` that needs statements of its own, +as Rust does: `f()[{ ... }]` runs `f()` first. Proven differentially under both +lowerings. + +## Plan + +Found in [#49](https://github.com/kixelated/rust2/pull/49). Each is an operand lowered +to an expression, then a later operand's statements emitted before that expression is +read. `range_bounds` already saves the sliced value first, and `Body::declared` and +`Body::operands` hold the pattern for fields and arguments. Look for other ad-hoc +sequences of the same shape and fix them together. MIR's operands are already locals, +so it may need no change: prove it with the same case. + +Public API: none. From a69c1d686b738271d8bfe013482a125d59f17038 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:07:02 -0700 Subject: [PATCH 2/2] fix(ts): operands evaluate in order around indexing A vector indexed by an integer, the slice `copy_within` reads, a function pointer, and a compound assignment's value now evaluate before a later operand's statements, as Rust evaluates them: `f()[{ ... }]` runs `f()` first. Without an end, `copy_within` reads its slice once. `Body::after` holds the pattern that `operands` and `range_bounds` already shared. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-index-order.md | 19 -------- ts/fixtures/lang/expected/shapes.ts | 62 ++++++++++++++++++++++++ ts/fixtures/lang/src/shapes.rs | 75 +++++++++++++++++++++++++++++ ts/src/lower/body.rs | 35 +++++++++----- ts/src/lower/library.rs | 45 ++++++++++------- 6 files changed, 186 insertions(+), 51 deletions(-) delete mode 100644 quest/m2/ts-index-order.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 085b7010a..1e9b2c2e6 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -24,7 +24,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [MIR's codec as fast as THIR's](/quest/m2/ts-mir-codec.md) - the codec from MIR no slower than from THIR in any engine - [Lower bodies from MIR](/quest/m2/ts-mir.md) - the MIR spike's prototype becomes the only lowering, and the THIR one goes - [Struct update on a std range](/quest/m2/ts-range-update.md) - `Range { start, ..r }` reads its base, or is refused with a span, instead of dropping it or panicking the driver -- [Operands in order around indexing](/quest/m2/ts-index-order.md) - an index or `copy_within`'s `dest` with statements runs after the value it indexes or copies within - [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split - [Wide-integer fast paths](/quest/m2/ts-wide-fast.md) - a fused `from_halves` and an unboxed limb product, kept only if measured faster - [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-index-order.md b/quest/m2/ts-index-order.md deleted file mode 100644 index 5d0dc9de3..000000000 --- a/quest/m2/ts-index-order.md +++ /dev/null @@ -1,19 +0,0 @@ -# [XS] Operands evaluate in order around indexing - -## Goal - -[rust2-ts](/ts/README.md)'s THIR lowering evaluates the value being indexed, or the -slice `copy_within` reads, before an index or `dest` that needs statements of its own, -as Rust does: `f()[{ ... }]` runs `f()` first. Proven differentially under both -lowerings. - -## Plan - -Found in [#49](https://github.com/kixelated/rust2/pull/49). Each is an operand lowered -to an expression, then a later operand's statements emitted before that expression is -read. `range_bounds` already saves the sliced value first, and `Body::declared` and -`Body::operands` hold the pattern for fields and arguments. Look for other ad-hoc -sequences of the same shape and fix them together. MIR's operands are already locals, -so it may need no change: prove it with the same case. - -Public API: none. diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 41a9a3700..bdc0d6f52 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -205,6 +205,68 @@ export function order(data: Uint8Array, out: rt.ByteVec): void { const slice = rt.slice.range(arg3, rt.usize.div(rt.min(mark(out, 15), len), 2), field10); const text = rt.fmt.format([(f: rt.Formatter) => Shape.fmt$Debug(rect, f), " ", (f: rt.Formatter) => Shape.fmt$Debug(line, f), " ", (f: rt.Formatter) => Pair.fmt$Debug(pair, f), " ", (f: rt.Formatter) => Point.fmt$Debug(read, f), " ", (f: rt.Formatter) => Moved.fmt$Debug(updated, f), " ", (f: rt.Formatter) => Shape.fmt$Debug(taken, f), " ", (f: rt.Formatter) => rt.usize.display(range.start, f), " ", (f: rt.Formatter) => rt.usize.display(range.end, f), " ", (f: rt.Formatter) => rt.usize.display(sum, f), " ", (f: rt.Formatter) => rt.fmt.list(slice, f, rt.u8.display)]); out.extendFromSlice(rt.string.asBytes(text)); + indexed(data, out); +} + +/** + * Indexing, calls, and assignments whose later operands need statements of their own + * evaluate what comes before those first: each logs as it runs, or changes what an + * earlier operand read. + */ +export function indexed(data: Uint8Array, out: rt.ByteVec): void { + const at = (i: rt.usize): rt.u8 => { + return rt.option.unwrapOr(rt.slice.get(data, i), 0); + }; + const arg = listed(out, at(0)).view(); + out.push(0xe1); + const first = rt.at(arg, 1); + let bytes: Uint8Array = Uint8Array.of(at(1), at(2), at(3), 4); + const arg2 = loggedMut(bytes, out); + out.push(0xe3); + const arg3 = arg2; + out.push(0xe4); + rt.slice.copyWithin(arg3, 1, 3, 0); + const slice = loggedMut(bytes, out); + const arg4 = slice; + const arg5 = slice.length; + out.push(0xe5); + rt.slice.copyWithin(arg4, 2, arg5, 1); + const slice2 = loggedMut(bytes, out); + rt.slice.copyWithin(slice2, 3, slice2.length, 0); + const value = logged(bytes, out); + out.push(0xe6); + const second = rt.at(value, 1); + let f: (a0: rt.u8) => rt.u8 = halve; + const arg6 = f; + f = twice; + const called = arg6(at(4)); + let n: rt.u8 = at(5); + let slots: Uint8Array = rt.bytes(2); + const value2 = n; + n = rt.u8.wrappingAdd(n, 1); + slots[rt.idx(slots, 0)] = rt.u8.add(slots[rt.idx(slots, 0)], value2); + out.extendFromSlice(Uint8Array.of(first, second, called, f(1), slots[0], n)); + out.extendFromSlice(bytes); +} + +/** A vector of `b`, logging that it was made. */ +export function listed(out: rt.ByteVec, b: rt.u8): rt.ByteVec { + out.push(0xe0); + return rt.slice.toByteVec(Uint8Array.of(b, b ^ 1)); +} + +/** `s`, logging that it was read. */ +export function loggedMut(s: Uint8Array, out: rt.ByteVec): Uint8Array { + out.push(0xe2); + return s; +} + +export function halve(b: rt.u8): rt.u8 { + return rt.u8.div(b, 2); +} + +export function twice(b: rt.u8): rt.u8 { + return rt.u8.wrappingAdd(b, b); } /** `data`, logging that it was read. */ diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index e7d293edf..bdbea9e32 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -314,6 +314,81 @@ pub fn order(data: &[u8], out: &mut Vec) { range.start, range.end ); out.extend_from_slice(text.as_bytes()); + indexed(data, out); +} + +/// Indexing, calls, and assignments whose later operands need statements of their own +/// evaluate what comes before those first: each logs as it runs, or changes what an +/// earlier operand read. +fn indexed(data: &[u8], out: &mut Vec) { + let at = |i: usize| data.get(i).copied().unwrap_or(0); + // The vector, then the index. + let first = listed(out, at(0))[{ + out.push(0xe1); + 1 + }]; + // The slice, the range, then `dest`. + let mut bytes = [at(1), at(2), at(3), 4]; + logged_mut(&mut bytes, out).copy_within( + { + out.push(0xe3); + 1 + }..3, + { + out.push(0xe4); + 0 + }, + ); + logged_mut(&mut bytes, out).copy_within(2.., { + out.push(0xe5); + 1 + }); + // Without an end, the slice is read once for its length too. + logged_mut(&mut bytes, out).copy_within(3.., 0); + // A slice, then its index. + let second = logged(&bytes, out)[{ + out.push(0xe6); + 1 + }]; + // A function pointer is read before its argument, which changes it. + let mut f: fn(u8) -> u8 = halve; + let called = f({ + f = twice; + at(4) + }); + // A compound assignment's value is read before its place's index, which changes it. + let mut n = at(5); + let mut slots = [0u8; 2]; + slots[{ + n = n.wrapping_add(1); + 0 + }] += n; + out.extend_from_slice(&[first, second, called, f(1), slots[0], n]); + out.extend_from_slice(&bytes); +} + +/// A vector of `b`, logging that it was made. +#[inline(never)] +fn listed(out: &mut Vec, b: u8) -> Vec { + out.push(0xe0); + [b, b ^ 1].to_vec() +} + +/// `s`, logging that it was read. +#[inline(never)] +fn logged_mut<'a>(s: &'a mut [u8], out: &mut Vec) -> &'a mut [u8] { + out.push(0xe2); + s +} + +#[inline(never)] +fn halve(b: u8) -> u8 { + b / 2 +} + +#[inline(never)] +fn twice(b: u8) -> u8 { + b.wrapping_add(b) } /// `data`, logging that it was read. diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index af233e977..d79adef1f 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1876,11 +1876,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { span: Span, out: &mut Vec, ) { + // The value evaluates first, so it is saved before the place reads it again or + // runs statements of its own. let mut value = self.operand(rhs, out); - if !value.is_path() { + let mut pre = Vec::new(); + let target = self.place(lhs, &mut pre); + if (!pre.is_empty() || !value.is_path()) && !value.is_constant() { value = self.spill(value, "value", out); } - let target = self.place(lhs, out); + out.extend(pre); if !target.is_path() && !matches!(target, Expr::Index(..)) { self.t.err(span, "a compound assignment to a computed place"); return; @@ -1926,20 +1930,24 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ); } holds |= self.t.drops(self.ty_of(id)); - if !pre.is_empty() { - for earlier in values.iter_mut() { - if !earlier.is_constant() { - let saved = std::mem::replace(earlier, Expr::undefined()); - *earlier = self.spill(saved, "arg", out); - } - } - } - out.extend(pre); + self.after(&mut values, pre, out); values.push(value); } values } + /// Emit `pre`, the statements of an operand that evaluates after `earlier`, saving + /// `earlier` first if there are any, so they cannot change it. + pub fn after(&mut self, earlier: &mut [Expr], pre: Vec, out: &mut Vec) { + if !pre.is_empty() { + for value in earlier.iter_mut().filter(|v| !v.is_constant()) { + let saved = std::mem::replace(value, Expr::undefined()); + *value = self.spill(saved, "arg", out); + } + } + out.extend(pre); + } + /// Whether `id` names a place, rather than making a temporary value. pub fn is_place(&self, id: ExprId) -> bool { match &self.thir[id].kind { @@ -2853,8 +2861,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.call_def(def_id, gargs.skip_binder(), Args::Thir(args), span, out) } ty::FnPtr(..) => { - let f = self.operand(fun, out); - let values = self.operands(args, out); + let ids: Vec = std::iter::once(fun).chain(args.iter().copied()).collect(); + let mut values = self.operands(&ids, out); + let f = values.remove(0); f.call(values) } _ => self.err(span, format!("a call through `{fn_ty}`")), diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 2ed2340ca..81120b411 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -561,9 +561,19 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, let mut s = [b.operand(ids[0], out)]; let (start, end) = range_bounds(b, &mut s, ids[1], out)?; let [s] = s; - let end = end.unwrap_or_else(|| s.clone().member("length")); - let dest = b.operand(ids[2], out); - Expr::Rt("slice").member("copyWithin").call(vec![s, start, end, dest]) + let (s, end) = match end { + Some(end) => (s, end), + None => { + let s = path(b, s, "slice", out); + (s.clone(), s.member("length")) + } + }; + let mut pre = Vec::new(); + let dest = b.operand(ids[2], &mut pre); + let mut values = vec![s, start, end]; + b.after(&mut values, pre, out); + values.push(dest); + Expr::Rt("slice").member("copyWithin").call(values) } ("slice", "to_vec") => { let elem = targ(gargs, 0); @@ -670,15 +680,20 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, _ => base, }; match Int::of(index_ty) { - Some(_) if name == "index" => { - let i = b.operand(ids[1], out); - Expr::rt("at", vec![base, i]) - } Some(_) => { - let base = path(b, base, "slice", out); - let i = b.operand(ids[1], out); - let i = path(b, i, "index", out); - base.clone().index(Expr::rt("idx", vec![base, i])) + let mut pre = Vec::new(); + let i = b.operand(ids[1], &mut pre); + let mut base = [base]; + b.after(&mut base, pre, out); + let [base] = base; + match name.as_str() { + "index" => Expr::rt("at", vec![base, i]), + _ => { + let base = path(b, base, "slice", out); + let i = path(b, i, "index", out); + base.clone().index(Expr::rt("idx", vec![base, i])) + } + } } None => { if name == "index_mut" && !is_u8(elem_ty) { @@ -996,13 +1011,7 @@ fn range_bounds<'tcx>( let values = b.operands(&ids, &mut pre); let values = range.fields.iter().map(|f| f.name.index()).zip(values).collect(); let mut values: Vec = b.declared(values, &mut pre).into_iter().map(|(_, v)| v).collect(); - if !pre.is_empty() { - for value in earlier.iter_mut().filter(|v| !v.is_constant()) { - let saved = std::mem::replace(value, Expr::undefined()); - *value = b.spill(saved, "arg", out); - } - } - out.extend(pre); + b.after(earlier, pre, out); match name.as_str() { "Range" => { let end = values.pop()?;