From ddd0d32044a9170b449ceea77c84724039f407f2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:42:21 -0700 Subject: [PATCH 01/11] chore(quest): claim quest/m3/ts-str-places.md Quest-Claim: 1397ae1d553c85e9 From 7ddc45ec5c564fe329464a5193a49ce49afa0c6d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:17:51 -0700 Subject: [PATCH 02/11] feat(ts): translate a &mut str to a String wherever it is, and to a part of one Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 3 +- quest/m3/ts-box-places.md | 16 ++++ quest/m3/ts-str-get.md | 17 ++++ quest/m3/ts-str-places.md | 18 ---- ts/README.md | 9 +- ts/fixtures/lang/caller.ts | 4 + ts/fixtures/lang/expected/ascii.ts | 137 ++++++++++++++++++++++++++- ts/fixtures/lang/expected/harness.ts | 4 +- ts/fixtures/lang/src/ascii.rs | 124 +++++++++++++++++++++++- ts/fixtures/lang/src/harness.rs | 1 + ts/fixtures/reject/expected.txt | 5 +- ts/fixtures/reject/src/lib.rs | 18 ++-- ts/fixtures/reject/ts.toml | 4 +- ts/runtime/rt/str.ts | 69 ++++++++++++-- ts/src/lower/library.rs | 8 +- ts/src/lower/mir/call.rs | 90 +++++++++++++----- 16 files changed, 457 insertions(+), 70 deletions(-) create mode 100644 quest/m3/ts-box-places.md create mode 100644 quest/m3/ts-str-get.md delete mode 100644 quest/m3/ts-str-places.md diff --git a/quest/m3/README.md b/quest/m3/README.md index 00acc0b53..c6882b824 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -32,7 +32,8 @@ generic std gap is planned here even when moq never calls it. - [LinkedList](/quest/m3/ts-linked-list.md) - `LinkedList` and its methods translate - [std's sorts call their tests in std's order](/quest/m3/ts-sort-order.md) - `slice::sort` and a B-tree's `collect` call `lt` or `cmp` as std's driftsort does past 16 elements - [A B-tree's searches call Ord as std's do](/quest/m3/ts-btree-search-order.md) - a B-tree's lookups and inserts call a key's own `Ord` in std's order and number -- [A &mut str to any String](/quest/m3/ts-str-places.md) - `make_ascii_*` of a `String` a tuple, an array, or a `Vec` holds, and of a part of one, translate +- [A &mut into a Box of a value JS copies](/quest/m3/ts-box-places.md) - a write through `&mut *b` of a `Box`, a `Box`, or a `Box` reaches the box's place +- [A str's checked and inclusive parts](/quest/m3/ts-str-get.md) - `str::get` and indexing a `str` by `a..=b` or `..=b` translate - [The rest of a boxed slice's impls](/quest/m3/ts-boxed-slice-rest.md) - `clone_from`, `AsRef`, `AsMut`, `TryFrom` into a boxed array, and `Box` into bytes translate for boxed slices - [A crate's own Extend in a tuple](/quest/m3/ts-tuple-own-extend.md) - `collect` and `extend` into a tuple holding a crate's `Extend` type translate - [A reversed zip's per-pair cost](/quest/m3/ts-zip-rev-overhead.md) - a reversed by-index zip costs per pair what a forward one does, or the gap is explained diff --git a/quest/m3/ts-box-places.md b/quest/m3/ts-box-places.md new file mode 100644 index 000000000..68b2d7dba --- /dev/null +++ b/quest/m3/ts-box-places.md @@ -0,0 +1,16 @@ +# [S] A &mut into a Box of a value JS copies + +## Goal + +[rust2-ts](/ts/README.md) translates a `&mut` to what a `Box` holds, where JS copies it (a +number, a `String`, or a `str`), as a write to the local or field holding the box. Today +`*(&mut *b) += 1` of a `Box`, `push` on a `Box`, and `make_ascii_uppercase` +on a `Box` translate to `b.v` of a value with no `v`, which `tsc` rejects. Proven by +differential tests against native Rust. + +## Plan + +Found translating `&mut str`'s places. A `Box` is its `T`, so a `&mut` through it is +the box's own place, as `String::as_mut_str` borrows the `String`'s. + +Public API: the translator's output. diff --git a/quest/m3/ts-str-get.md b/quest/m3/ts-str-get.md new file mode 100644 index 000000000..fd5f4b5f9 --- /dev/null +++ b/quest/m3/ts-str-get.md @@ -0,0 +1,17 @@ +# [S] A str's checked and inclusive parts + +## Goal + +[rust2-ts](/ts/README.md) translates `str::get`, and indexing a `str` or a `String` by an +inclusive range (`&s[a..=b]`, `&s[..=b]`, and their `&mut` and `get_mut` forms), with +std's `None` and panics. Today each refuses: `get` as an unsupported call, and the +inclusive ranges at `Index::index` or `IndexMut::index_mut`. Proven by differential tests +against native Rust. + +## Plan + +Found translating `&mut str`'s places, whose `get_mut` and `&mut s[a..b]` take the other +ranges. The runtime's `strSlice` and `strGetMut` check offsets already; an inclusive end +past `usize::MAX` panics as std's does. No consumer calls them yet; planned as part of std. + +Public API: the translator's output. diff --git a/quest/m3/ts-str-places.md b/quest/m3/ts-str-places.md deleted file mode 100644 index b4c064fc8..000000000 --- a/quest/m3/ts-str-places.md +++ /dev/null @@ -1,18 +0,0 @@ -# [S] A &mut str to any String - -## Goal - -[rust2-ts](/ts/README.md) translates a `&mut str` to a `String` wherever the `String` is, -and to a part of one, so `make_ascii_uppercase` and `make_ascii_lowercase` reach every place -std's do. Today they write a local's, a field's, or one behind a `&mut String`; a `String` -a tuple, an array, or a `Vec` holds refuses at `DerefMut` as "no path", and `&mut s[a..b]` -and `String::as_mut_str` refuse as a `&mut` their mapping would copy. Proven by -differential tests against native Rust. - -## Plan - -Found translating the ASCII methods. A JS string can't change in place, so a `&mut str` is -an `rt.Place` of the whole `String`; a part of one needs the place and its UTF-8 -byte range, written back as a new string. No consumer calls them yet; planned as part of std. - -Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index 780b98d82..7ddab2a95 100644 --- a/ts/README.md +++ b/ts/README.md @@ -171,8 +171,7 @@ the width and sign, which computes on the value's `bigint`. The stable ASCII methods of `u8` and `char`, and of `[u8]` and `str`, so of a `Vec` and a `String`, are std's. A `u8` and a `char` share each runtime function, `rt.isAsciiDigit(c)`. `make_ascii_uppercase` and `make_ascii_lowercase` of a byte, a char, or a string write -the other case where the `&mut` borrows it; of a part of a `String`, or of a `String` -that a tuple, an array, or a `Vec` holds, they are refused. `escape_ascii`'s iterators read from either +the other case where the `&mut` borrows it, a part of a `String` included. `escape_ascii`'s iterators read from either end, size themselves as std's do, and write what they have left by `Display`, unpadded. An `f64` is a JS number, so its operators are JS's, which round as Rust's do. Where @@ -284,7 +283,11 @@ returns, from `rfind` or `match_indices`, counts UTF-8 bytes, as Rust's does, an one `&s[a..b]` takes, which reads the string up to it and panics as std does inside a char. A JS string can't change in place, so `String`'s edits, `push_str`, `truncate`, `insert`, `retain`, `replace_range`, and the rest, assign the edited one to the local or -field the `&mut` borrows, taking and checking byte offsets as std does. `extend` and +field the `&mut` borrows, taking and checking byte offsets as std does. A `&mut str` is +the `rt.Place` of its `String` wherever that is, and a part of one, from `&mut s[a..b]`, +`get_mut`, or `split_at_mut`, is `rt.strPart(p, a, b)`, a place of its own that writes the +whole string anew, checking its offsets as `&s[a..b]` does. `as_bytes_mut`, +`get_unchecked_mut`, and `str::from_utf8_mut` are refused. `extend` and `collect` read their iterator by `for_each`, as std's do, and of chars first reserve its size hint's lower bound, which panics past `isize::MAX`. A `drain` holds the `&mut`'s place and writes the string without the drained text as it drops, so one that diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index c04f92d48..b4485c5cc 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -721,6 +721,10 @@ const asciiCases = [ // Text of every char `ascii.rs` tries, each once. ...[0, 1, 2, 3].map((kind) => Uint8Array.of(op("ascii::slices"), kind, ...Array.from({ length: 41 }, (_, i) => i))), Uint8Array.of(op("ascii::chars"), 0, ...[0xd7ff, 0xd800, 0xdfff, 0xe000, 0x1f600, 0x10ffff, 0x110000].flatMap((n) => [n >>> 24, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff])), + // `parts` of each kind at every pair of byte offsets up to two past the end of its + // 14 bytes of text, and of no text. + ...Array.from({ length: 8 * 17 * 17 }, (_, i) => Uint8Array.of(op("ascii::parts"), i % 8, Math.floor(i / 8) % 17, Math.floor(i / 8 / 17))), + ...Array.from({ length: 8 * 3 * 3 }, (_, i) => Uint8Array.of(op("ascii::parts"), 0x10 | (i % 8), Math.floor(i / 8) % 3, Math.floor(i / 24))), ]; export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...singlesCases, ...singlesFormats, ...singlesParsed, ...dyns, ...cells, ...shared, ...locks, ...onces, ...bounds, ...unsafeCells, ...edits, ...subslices, ...consumers, ...closures, ...elements, ...ranges, ...reducers, ...sliceEdits, ...drains, ...iters, ...hinted, ...peekedOthers, ...hints, ...reserves, ...setOps, ...zeros, ...writes, ...floatsMulAdds, ...singlesMulAdds, ...unlikeEqs, ...ownNes, ...rangeFroms, ...compares, ...unlikeCompares, ...rangeMethods, ...wraps(), ...refOrders, ...saturates(), ...methods(), ...separated, ...asciiCases]; diff --git a/ts/fixtures/lang/expected/ascii.ts b/ts/fixtures/lang/expected/ascii.ts index dbfa7d13f..b45562229 100644 --- a/ts/fixtures/lang/expected/ascii.ts +++ b/ts/fixtures/lang/expected/ascii.ts @@ -2,7 +2,7 @@ import * as rt from "./rt.ts"; import type * as ascii_Held from "./ascii.Held.ts"; -import { isSomeAnd$09tpccf, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$0l7j3f6 as option_unwrapOr$0l7j3f6, mapOr$02k4ito as option_mapOr$02k4ito, mapOr$0jad0p1 as option_mapOr$0jad0p1 } from "./core/option.ts"; +import { isSomeAnd$09tpccf, unwrapOr$1iemzn8 as option_unwrapOr$1iemzn8, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$0l7j3f6 as option_unwrapOr$0l7j3f6, mapOr$1t0muvr as option_mapOr$1t0muvr, mapOr$02k4ito as option_mapOr$02k4ito, mapOr$0jad0p1 as option_mapOr$0jad0p1, asDeref$0w8at8i as option_asDeref$0w8at8i } from "./core/option.ts"; import { put as fmt_put } from "./fmt.ts"; /** Each test of `b`, a bit apiece. */ @@ -327,4 +327,139 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } } +/** `s[a..b]`'s case changed through the `&mut str` it is given. */ +export function upperPart(s: rt.Place, a: rt.usize, b: rt.usize): void { + const _5: rt.Place = rt.strPart(s, a, b); + _5.v = rt.strToAsciiUppercase(_5.v); +} + +/** + * A part `get_mut` or `split_at_mut_checked` may give, upper-cased and put, or 0xfe if + * it gave none. + */ +export function putUpper(out: rt.ByteVec, part: rt.Place | undefined): void { + if (part === undefined) { + rt.byteVecPush(out, 254); + } else { + part.v = rt.strToAsciiUppercase(part.v); + fmt_put(out, part.v); + } +} + +/** + * Case changed through a `&mut str` to a `String` where a local, a tuple, an array, a + * `Vec`, or an `Option` holds it, and to parts of one at byte offsets `data` picks up to + * two past the end, the `String` put after each change. A part off a char boundary, + * backwards, or out of bounds panics as std's does; a checked one gives `None`. + */ +export function parts(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + let text!: string; + if ((kind & 16) === 0) { + text = "aÉbࠀc😀dZ"; + } else { + text = ""; + } + const _7: string = text; + const at: (a0: rt.usize) => rt.usize = (i: rt.usize): rt.usize => { + return option_mapOr$1t0muvr(rt.byteSliceGet(data, i), 0, (_2: rt.u8): rt.usize => { + return rt.usizeRem(_2 as rt.usize, rt.usizeAdd(rt.stringLen(_7), 3)); + }); + }; + const _10: [rt.usize, rt.usize] = [at(0), at(1)]; + const a: rt.usize = _10[0]; + const b: rt.usize = _10[1]; + let s: string = text; + const pair: [rt.u8, string] = [7, text]; + const array: string[] = ["q", text]; + const v: string[] = [text, text]; + const _32: rt.u8 = rt.u8Rem(kind, 8); + if (_32 === 0) { + s = rt.strToAsciiUppercase(s); + fmt_put(out, s); + const _41: rt.Place = rt.strPart(rt.place(() => s, (value15) => s = value15), a, b); + _41.v = rt.strToAsciiLowercase(_41.v); + fmt_put(out, s); + } else if (_32 === 1) { + pair[1] = rt.strToAsciiUppercase(pair[1]); + fmt_put(out, pair[1]); + const _54: rt.Place = rt.strPart(rt.place(() => pair[1], (value14) => pair[1] = value14), a); + _54.v = rt.strToAsciiLowercase(_54.v); + fmt_put(out, pair[1]); + rt.byteVecPush(out, pair[0]); + } else if (_32 === 2) { + array[1] = rt.strToAsciiUppercase(array[1]); + fmt_put(out, array[1]); + const _73: rt.Place = rt.strPart(rt.place(() => array[1], (value13) => array[1] = value13), 0, b); + _73.v = rt.strToAsciiLowercase(_73.v); + fmt_put(out, array[1]); + fmt_put(out, array[0]); + } else if (_32 === 3) { + const iter: rt.Iter> = rt.iterSliceMut(v); + while (true) { + const _93: rt.Place | rt.Done = iter.next(); + if (_93 === rt.DONE) { + break; + } + _93.v = rt.strToAsciiUppercase(_93.v); + } + const at6 = rt.idx(v, 0); + const _100: rt.Place = rt.strPart(rt.place(() => v[at6], (value11) => v[at6] = value11), 0); + _100.v = rt.strToAsciiLowercase(_100.v); + const at7 = rt.idx(v, 1); + const _105: rt.Place = rt.strPart(rt.place(() => v[at7], (value12) => v[at7] = value12), a, b); + _105.v = rt.strToAsciiLowercase(_105.v); + fmt_put(out, v[rt.idx(v, 0)]); + fmt_put(out, v[rt.idx(v, 1)]); + } else if (_32 === 4) { + const _119: [rt.Place, rt.Place] = rt.strSplitAtMut(rt.place(() => s, (value10) => s = value10), a); + _119[0].v = rt.strToAsciiUppercase(_119[0].v); + _119[1].v = rt.strToAsciiUppercase(_119[1].v); + _119[0].v = rt.strToAsciiLowercase(_119[0].v); + fmt_put(out, _119[0].v); + fmt_put(out, _119[1].v); + const _131: [rt.Place, rt.Place] = rt.strSplitAtMut(_119[1], rt.usizeSaturatingSub(b, a)); + _131[1].v = rt.strToAsciiLowercase(_131[1].v); + fmt_put(out, _131[0].v); + fmt_put(out, _131[1].v); + fmt_put(out, s); + } else if (_32 === 5) { + putUpper(out, rt.strGetMut(rt.place(() => s, (value7) => s = value7), a, b)); + putUpper(out, rt.strGetMut(rt.place(() => pair[1], (value8) => pair[1] = value8), a)); + const at4 = rt.idx(v, 1); + putUpper(out, rt.strGetMut(rt.place(() => v[at4], (value9) => v[at4] = value9), 0, b)); + fmt_put(out, s); + fmt_put(out, pair[1]); + fmt_put(out, v[rt.idx(v, 1)]); + } else if (_32 === 6) { + const _168: [rt.Place, rt.Place] | undefined = rt.strSplitAtMutChecked(rt.place(() => array[1], (value5) => array[1] = value5), a); + if (_168 === undefined) { + rt.byteVecPush(out, 253); + } else { + _168[1].v = rt.strToAsciiUppercase(_168[1].v); + putUpper(out, rt.strGetMut(_168[0], rt.min(b, rt.stringLen(_168[0].v)))); + } + fmt_put(out, array[1]); + let held: string | undefined = text; + const _191: rt.Place | undefined = held === undefined ? undefined : rt.place(() => held as string, (value6) => held = value6); + if (_191 !== undefined) { + _191.v = rt.strToAsciiUppercase(_191.v); + } + fmt_put(out, option_unwrapOr$1iemzn8(option_asDeref$0w8at8i(held), "-")); + } else { + const at2 = rt.idx(v, 1); + upperPart(rt.strPart(rt.place(() => v[at2], (value) => v[at2] = value), a), 0, rt.usizeSaturatingSub(b, a)); + fmt_put(out, v[rt.idx(v, 1)]); + upperPart(rt.place(() => s, (value2) => s = value2), a, b); + fmt_put(out, rt.strPart(rt.place(() => s, (value3) => s = value3), 0, a).v); + fmt_put(out, rt.strPart(rt.place(() => s, (value4) => s = value4), a).v); + const leaked: rt.Place = { v: pair[1] }; + const _234: rt.Place = rt.strPart(leaked, rt.min(b, a)); + _234.v = rt.strToAsciiUppercase(_234.v); + fmt_put(out, leaked.v); + const empty: rt.Place = { v: "" }; + empty.v = rt.strToAsciiUppercase(empty.v); + fmt_put(out, empty.v); + } +} + //# sourceMappingURL=ascii.ts.map diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index f4eed50f1..2107a2261 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -2,7 +2,7 @@ import * as rt from "./rt.ts"; import { fromFns, maps, lent as arrays_lent, asSlices, given } from "./arrays.ts"; -import { bytes as ascii_bytes, chars as ascii_chars, slices as ascii_slices } from "./ascii.ts"; +import { bytes as ascii_bytes, chars as ascii_chars, slices as ascii_slices, parts as ascii_parts } from "./ascii.ts"; import { atomics } from "./atomics.ts"; import { borrows as borrows_borrows } from "./borrows.ts"; import { bounds as bounds_bounds } from "./bounds.ts"; @@ -233,7 +233,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) loaded(data84, out85); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["orders::btrees", btrees as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["lengths::lengths", lengths as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::option_items", (_2185: rt.u8, data85: rt.ByteSlice, out86: rt.ByteVec): undefined => { optionItems(data85, out86); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["ascii::parts", ascii_parts as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; } /** Run one case. */ diff --git a/ts/fixtures/lang/src/ascii.rs b/ts/fixtures/lang/src/ascii.rs index 476b888c4..63de112b8 100644 --- a/ts/fixtures/lang/src/ascii.rs +++ b/ts/fixtures/lang/src/ascii.rs @@ -1,9 +1,11 @@ //! The ASCII methods of `u8`, `char`, byte slices, and `str`: their tests, case maps, and //! case-insensitive equality, each case changed in place through a `&mut` to where the //! value is, slices trimmed, and what `escape_ascii` yields from either end and writes. -//! Every byte is tried, and the chars at each edge of ASCII and past it. +//! Every byte is tried, and the chars at each edge of ASCII and past it. A `String`'s case +//! also changes through a `&mut str` to it wherever it is, and to parts of it. use std::ascii; +use std::borrow::BorrowMut; use std::fmt::Write; use crate::fmt::put; @@ -318,3 +320,123 @@ pub fn slices(kind: u8, data: &[u8], out: &mut Vec) { } } } + +/// ASCII letters between chars of each wider UTF-8 length, so a case change shows at +/// each side of every part. +const MIXED: &str = "a\u{c9}b\u{800}c\u{1f600}dZ"; + +/// `s[a..b]`'s case changed through the `&mut str` it is given. +fn upper_part(s: &mut str, a: usize, b: usize) { + s[a..b].make_ascii_uppercase(); +} + +/// A part `get_mut` or `split_at_mut_checked` may give, upper-cased and put, or 0xfe if +/// it gave none. +fn put_upper(out: &mut Vec, part: Option<&mut str>) { + match part { + Some(part) => { + part.make_ascii_uppercase(); + put(out, part); + } + None => out.push(0xfe), + } +} + +/// Case changed through a `&mut str` to a `String` where a local, a tuple, an array, a +/// `Vec`, or an `Option` holds it, and to parts of one at byte offsets `data` picks up to +/// two past the end, the `String` put after each change. A part off a char boundary, +/// backwards, or out of bounds panics as std's does; a checked one gives `None`. +pub fn parts(kind: u8, data: &[u8], out: &mut Vec) { + let text = match kind & 0x10 { + 0 => MIXED, + _ => "", + }; + let at = |i: usize| data.get(i).map_or(0, |&b| usize::from(b) % (text.len() + 3)); + let (a, b) = (at(0), at(1)); + let mut s = text.to_string(); + let mut pair = (7u8, text.to_string()); + let mut array = [String::from("q"), text.to_string()]; + let mut v = vec![text.to_string(), text.to_string()]; + match kind % 8 { + 0 => { + s.as_mut_str().make_ascii_uppercase(); + put(out, &s); + s[a..b].make_ascii_lowercase(); + put(out, &s); + } + 1 => { + pair.1.make_ascii_uppercase(); + put(out, &pair.1); + pair.1[a..].make_ascii_lowercase(); + put(out, &pair.1); + out.push(pair.0); + } + 2 => { + array[1].make_ascii_uppercase(); + put(out, &array[1]); + array[1][..b].make_ascii_lowercase(); + put(out, &array[1]); + put(out, &array[0]); + } + 3 => { + for t in v.iter_mut() { + t.make_ascii_uppercase(); + } + AsMut::::as_mut(&mut v[0])[..].make_ascii_lowercase(); + v[1][a..b].make_ascii_lowercase(); + put(out, &v[0]); + put(out, &v[1]); + } + 4 => { + // Two parts at once, each written after the other's write. + let (x, y) = s.split_at_mut(a); + x.make_ascii_uppercase(); + y.make_ascii_uppercase(); + x.make_ascii_lowercase(); + put(out, x); + put(out, y); + let (y0, y1) = y.split_at_mut(b.saturating_sub(a)); + y1.make_ascii_lowercase(); + put(out, y0); + put(out, y1); + put(out, &s); + } + 5 => { + put_upper(out, s.get_mut(a..b)); + put_upper(out, pair.1.get_mut(a..)); + put_upper(out, v[1].get_mut(..b)); + put(out, &s); + put(out, &pair.1); + put(out, &v[1]); + } + 6 => { + match BorrowMut::::borrow_mut(&mut array[1]).split_at_mut_checked(a) { + Some((x, y)) => { + y.make_ascii_uppercase(); + put_upper(out, x.get_mut(b.min(x.len())..)); + } + None => out.push(0xfd), + } + put(out, &array[1]); + let mut held = Some(text.to_string()); + if let Some(t) = held.as_mut() { + t.make_ascii_uppercase(); + } + put(out, held.as_deref().unwrap_or("-")); + } + _ => { + // A part of a part, through a `&mut str` given. + upper_part(&mut v[1][a..], 0, b.saturating_sub(a)); + put(out, &v[1]); + upper_part(&mut s, a, b); + put(out, &String::from(&mut s[..a])); + put(out, &(&mut s[a..]).to_string()); + let leaked = pair.1.leak(); + leaked[b.min(a)..].make_ascii_uppercase(); + put(out, leaked); + let empty: &mut str = Default::default(); + empty.make_ascii_uppercase(); + put(out, empty); + } + } +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 5294a25a4..6407edec6 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -256,6 +256,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("orders::btrees", orders::btrees), ("lengths::lengths", lengths::lengths), ("iters::option_items", |_, data, out| iters::option_items(data, out)), + ("ascii::parts", ascii::parts), ] } diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 3b8f475ca..614b37a53 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -160,8 +160,9 @@ a raw pointer to `ByRefTake` in `(u16, ByRefTake)`, which the crate may put anot a raw pointer to `ByKeySet` in `(u16, ByKeySet)`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:1622:51 a raw pointer to `ByKeyReplace` in `(u16, ByKeyReplace)`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:1630:55 a raw pointer to `ByKeyTake` in `(u16, ByKeyTake)`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:1637:52 -`std::ops::DerefMut::deref_mut` of a value JS copies, which is no path at fixtures/reject/src/lib.rs:1646:2 -`std::ops::IndexMut::index_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:1652:3 +unsupported call to `core::str::::as_bytes_mut` at fixtures/reject/src/lib.rs:1645:13 +`core::str::::get_unchecked_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:1646:13 +`std::str::from_utf8_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:1651:20 unsupported call to `std::ptr::copy::<[u8; 4]>` at fixtures/reject/src/lib.rs:1826:3 unsupported call to `std::ptr::copy_nonoverlapping::<[u8; 4]>` at fixtures/reject/src/lib.rs:1827:3 unsupported call to `std::ptr::addr_eq::<[u8; 4], [u8; 4]>` at fixtures/reject/src/lib.rs:1828:14 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 6b2c9db5f..1de7cb55a 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -1640,17 +1640,17 @@ pub fn key_taken(n: u16) -> u16 { unsafe { *part } } -/// A `String`'s case changed where a tuple holds it, through a `&mut str` to an element -/// JS copies, which is no path to write it back to. -pub fn ascii_in_tuple(mut pair: (u8, String)) -> String { - pair.1.make_ascii_uppercase(); - pair.1 +/// A `str`'s UTF-8 written as bytes, or a part of it unchecked. +pub fn str_bytes_mut(s: &mut str) { + unsafe { s.as_bytes_mut()[0] = b'a' }; + unsafe { s.get_unchecked_mut(..1) }.make_ascii_uppercase(); } -/// Part of a `String` changed in place, which a JS string can't be. -pub fn ascii_part(mut s: String) -> String { - s[1..].make_ascii_uppercase(); - s +/// Bytes written through a `&mut str` to them, which no JS string is. +pub fn str_from_bytes_mut(bytes: &mut [u8]) { + if let Ok(text) = std::str::from_utf8_mut(bytes) { + text.make_ascii_uppercase(); + } } pub struct Owned(pub u32, pub u32); diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index bffbafa0e..9b207cff6 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -147,8 +147,8 @@ roots = [ "key_set", "key_replaced", "key_taken", - "ascii_in_tuple", - "ascii_part", + "str_bytes_mut", + "str_from_bytes_mut", "byte_pointer_ops", "byte_pointer_parts", "byte_pointer_rebound", diff --git a/ts/runtime/rt/str.ts b/ts/runtime/rt/str.ts index 709dc1a53..5d4b8b87e 100644 --- a/ts/runtime/rt/str.ts +++ b/ts/runtime/rt/str.ts @@ -60,14 +60,71 @@ function unitAt(s: string, i: number, from: number, to: number): number { /** `&s[start..end]` by UTF-8 byte offsets, with `end` defaulting to the length. */ export function strSlice(s: string, start: number, end?: number): string { + return s.slice(...units(s, start, end)); +} + +/** + * The code units of `s` from byte `start` to byte `end`, or to the end, or `undefined` if + * either is out of bounds or inside a char, or they are backwards. + */ +function unitsChecked(s: string, start: number, end?: number): [number, number] | undefined { const from = unitAt(s, 0, 0, start); - if (end === undefined) { - if (from < 0) sliceFailed(s, start, stringLen(s)); - return s.slice(from); + if (from < 0) return undefined; + const to = end === undefined ? s.length : unitAt(s, from, start, end); + return to < 0 ? undefined : [from, to]; +} + +/** `unitsChecked`, panicking as std's indexing does where it gives `undefined`. */ +function units(s: string, start: number, end?: number): [number, number] { + return unitsChecked(s, start, end) ?? sliceFailed(s, start, end ?? stringLen(s)); +} + +/** + * `&mut p[from..to]` by code units: a part of the string at `p`, whose writes splice the + * string anew. A write through a `&mut str` keeps each char's length, so the units hold. + */ +class StrPart implements Place { + readonly #whole: Place; + readonly #from: number; + readonly #to: number; + + constructor(whole: Place, [from, to]: [number, number]) { + this.#whole = whole; + this.#from = from; + this.#to = to; + } + + get v(): string { + return this.#whole.v.slice(this.#from, this.#to); } - const to = from < 0 ? -1 : unitAt(s, from, start, end); - if (to < 0) sliceFailed(s, start, end); - return s.slice(from, to); + + set v(value: string) { + const s = this.#whole.v; + this.#whole.v = s.slice(0, this.#from) + value + s.slice(this.#to); + } +} + +/** `&mut p[start..end]` by UTF-8 byte offsets, with `end` defaulting to the length. */ +export function strPart(p: Place, start: number, end?: number): Place { + return new StrPart(p, units(p.v, start, end)); +} + +/** `str::get_mut` by a range's UTF-8 byte offsets, with `end` defaulting to the length. */ +export function strGetMut(p: Place, start: number, end?: number): Place | undefined { + const at = unitsChecked(p.v, start, end); + return at && new StrPart(p, at); +} + +/** `str::split_at_mut`. */ +export function strSplitAtMut(p: Place, mid: number): [Place, Place] { + const [, at] = units(p.v, 0, mid); + return [new StrPart(p, [0, at]), new StrPart(p, [at, p.v.length])]; +} + +/** `str::split_at_mut_checked`. */ +export function strSplitAtMutChecked(p: Place, mid: number): [Place, Place] | undefined { + const at = unitsChecked(p.v, 0, mid); + return at && [new StrPart(p, at), new StrPart(p, [at[1], p.v.length])]; } /** std's panic for a slice of `s` that is out of bounds, backwards, or inside a char. */ diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 101b84c37..396e4d79f 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -1290,9 +1290,13 @@ fn mapping<'tcx>( // `Some` of a value is the value. let some = matches!(to.kind(), ty::Adt(adt, args) if Std::of(tcx, adt.did()) == Some(Std::Option) && args.type_at(0) == targ(gargs, 1)); - if to == from || some || (string(tcx, to) && string(tcx, from.peel_refs())) { + if to == from || some { return Some(value); } + // A `&mut str` is the `rt.Place` of its text. + if string(tcx, to) && string(tcx, from.peel_refs()) { + return Some(b.t.pointee_value(targ(gargs, 1), value)); + } // A `Vec` is owned, and a reference to a slice, an array, or a `Vec` borrows its slice. if let Some(elem) = cow_slice(tcx, to) { let owned = b.t.std_of(targ(gargs, 1)) == Some(Std::Vec); @@ -2154,7 +2158,7 @@ fn mapping<'tcx>( return Some(b.err(span, cow_variant(cow))); } ("ToString", "to_string") | ("ToOwned", "to_owned") if matches!(self_ty()?.peel_refs().kind(), ty::Str) => { - args.pop()? + b.t.pointee_value(self_ty()?, args.pop()?) } // Panics, which format their message as std does. diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 524522eda..0e128098b 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -639,24 +639,39 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { 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)?; - if let Some(local) = dest.as_local() - && self.defs[local] == 1 - && matches!(self.slots[local], Slot::Var(_)) - { - self.slots[local] = Slot::Alias(Some(place)); - self.reborrows.extend(borrowed.map(|b| (local, b))); - return Some(None); - } - match borrowed { - Some(borrowed) => { - let target = self.stable_target(borrowed, place, span, out); - done(self.place_of(target, None), true) - } - None => done(place, true), - } + // A `Cow` is the `String` it would hold, and a `String` is its `str`, so the + // `&mut` borrows the same place. + ("Cow", "to_mut") if targ(0).is_some_and(|t| t.is_str()) => self.same_place(args, dest, span, out), + ("String", "as_mut_str") => self.same_place(args, dest, span, out), + ("DerefMut", "deref_mut") | ("AsMut", "as_mut") | ("BorrowMut", "borrow_mut") + if targ(0).is_some_and(|t| t.is_str() || self.b.t.std_of(t) == Some(Std::String)) + && dest.ty(&self.mir.local_decls, tcx).ty.builtin_deref(true).is_some_and(|t| t.is_str()) => + { + self.same_place(args, dest, span, out) + } + // A place nothing else holds: the `String` leaked, or `Default`'s empty `str`. + ("String", "leak") => { + let leaked = self.operand(&args[0].node, span, out); + done(Expr::Object(vec![(crate::ts::Key::Name("v".into()), leaked)]), true) + } + ("Default", "default") + if targ(0).is_some_and(|t| t.ref_mutability() == Some(ty::Mutability::Mut) && t.peel_refs().is_str()) => + { + done(Expr::Object(vec![(crate::ts::Key::Name("v".into()), Expr::Str(String::new()))]), false) + } + // A part of a `str` is a place of its own, which splices the whole anew. + ("str", "get_mut") => { + let whole = self.operand(&args[0].node, span, out); + let (start, end) = self.range_bounds(&args[1].node, targ(0)?, span, out)?; + done(Expr::rt("strGetMut", [whole, start].into_iter().chain(end).collect()), true) + } + ("str", "split_at_mut" | "split_at_mut_checked") => { + let values = self.operands(false, &[], args, dest.ty(&self.mir.local_decls, tcx).ty, span, out); + let f = match name.as_str() { + "split_at_mut" => "strSplitAtMut", + _ => "strSplitAtMutChecked", + }; + done(Expr::rt(f, values), true) } // A `Wrapping` or a `Saturating` is its integer, so what the `&mut` borrows gets the // wrapped or saturated result. @@ -1065,6 +1080,33 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// The place the `&mut` receiver borrows, as the `&mut` the call returns: an alias of it + /// where the destination is read only as one. + fn same_place( + &mut self, + args: &[Spanned>], + dest: Place<'tcx>, + span: Span, + out: &mut Vec, + ) -> Option> { + let (place, borrowed) = self.borrowed_place(&args[0].node, span, out)?; + if let Some(local) = dest.as_local() + && self.defs[local] == 1 + && matches!(self.slots[local], Slot::Var(_)) + { + self.slots[local] = Slot::Alias(Some(place)); + self.reborrows.extend(borrowed.map(|b| (local, b))); + return Some(None); + } + match borrowed { + Some(borrowed) => { + let target = self.stable_target(borrowed, place, span, out); + Some(Some((self.place_of(target, None), true))) + } + None => Some(Some((place, true))), + } + } + /// A `fmt::Write` method of a `String`, a `Formatter`, or the crate's own writer, or of /// std's impl for a `&mut W`, which calls `W`'s. A provided method of the crate's impl /// writes through its `write_str`. `None` for any other writer. @@ -1396,16 +1438,18 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ) -> Option> { let container = gargs.type_at(0); let index_ty = gargs.type_at(1); - // A string slices by UTF-8 byte offsets, which a JS string doesn't index by. + // A string slices by UTF-8 byte offsets, which a JS string doesn't index by, and a + // part a `&mut` borrows is a place of its own, which splices the whole anew. if container.is_str() || self.b.t.std_of(container) == Some(Std::String) { - if name == "index_mut" { - return None; - } let base = self.operand(&args[0].node, span, out); let (start, end) = self.range_bounds(&args[1].node, index_ty, span, out)?; + let f = match name { + "index_mut" => "strPart", + _ => "strSlice", + }; let mut values = vec![self.path(base, "s", out), start]; values.extend(end); - return Some(Some((Expr::rt("strSlice", values), true))); + return Some(Some((Expr::rt(f, values), true))); } let elem_ty = elem(self.tcx, container)?; let bytes = matches!(elem_ty.kind(), ty::Uint(ty::UintTy::U8)); From 406260c5a3631d9bfb5c3595000a04dbe1c41788 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:24:10 -0700 Subject: [PATCH 03/11] style(ts): format the &mut str intercepts Co-Authored-By: Claude Opus 5.5 --- ts/src/lower/mir/call.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 0e128098b..b464de068 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -645,7 +645,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ("String", "as_mut_str") => self.same_place(args, dest, span, out), ("DerefMut", "deref_mut") | ("AsMut", "as_mut") | ("BorrowMut", "borrow_mut") if targ(0).is_some_and(|t| t.is_str() || self.b.t.std_of(t) == Some(Std::String)) - && dest.ty(&self.mir.local_decls, tcx).ty.builtin_deref(true).is_some_and(|t| t.is_str()) => + && dest.ty(&self.mir.local_decls, tcx).ty.peel_refs().is_str() => { self.same_place(args, dest, span, out) } @@ -655,15 +655,23 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { done(Expr::Object(vec![(crate::ts::Key::Name("v".into()), leaked)]), true) } ("Default", "default") - if targ(0).is_some_and(|t| t.ref_mutability() == Some(ty::Mutability::Mut) && t.peel_refs().is_str()) => + if targ(0) + .and_then(|t| self.b.t.place_pointee(t)) + .is_some_and(|t| t.is_str()) => { - done(Expr::Object(vec![(crate::ts::Key::Name("v".into()), Expr::Str(String::new()))]), false) + done( + Expr::Object(vec![(crate::ts::Key::Name("v".into()), Expr::Str(String::new()))]), + false, + ) } // A part of a `str` is a place of its own, which splices the whole anew. ("str", "get_mut") => { let whole = self.operand(&args[0].node, span, out); let (start, end) = self.range_bounds(&args[1].node, targ(0)?, span, out)?; - done(Expr::rt("strGetMut", [whole, start].into_iter().chain(end).collect()), true) + done( + Expr::rt("strGetMut", [whole, start].into_iter().chain(end).collect()), + true, + ) } ("str", "split_at_mut" | "split_at_mut_checked") => { let values = self.operands(false, &[], args, dest.ty(&self.mir.local_decls, tcx).ty, span, out); From 75938725f4bcc7f6a7753bf1f5506623677129bc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:37:13 -0700 Subject: [PATCH 04/11] test(ts): update the reject census for the str refusals Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/reject/census.md | 42 ++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 53ad641a2..d0ebdc0e6 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,6 +1,6 @@ # Census of `reject-fixture` -- Refusals: 198 +- Refusals: 199 - Function instances: 240 - Generic functions no instance reached, lowered over their type parameters: 11 @@ -9,12 +9,12 @@ | Count | Construct | First | | ---: | --- | --- | | 45 | a raw pointer to `_` in `_`, which the crate may put another object in place of | fixtures/reject/src/lib.rs:617:10 | -| 25 | unsupported call to `_` | fixtures/reject/src/lib.rs:167:8 | +| 26 | unsupported call to `_` | fixtures/reject/src/lib.rs:167:8 | | 19 | a raw pointer to `_` in a variable assigned again while it may point there | fixtures/reject/src/lib.rs:625:10 | | 14 | a reference to `_`, through which a raw pointer may be made, in a variable assigned again while that pointer may point there | fixtures/reject/src/lib.rs:1346:33 | | 5 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | fixtures/reject/src/lib.rs:688:10 | +| 4 | `_` with a mutable reference to a value JS copies, which its mapping would copy | fixtures/reject/src/lib.rs:523:12 | | 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:338:2 | -| 3 | `_` with a mutable reference to a value JS copies, which its mapping would copy | fixtures/reject/src/lib.rs:523:12 | | 3 | a copy of a closure that changes what it captured | fixtures/reject/src/lib.rs:231:14 | | 3 | an assignment through a reference to `_` | fixtures/reject/src/lib.rs:90:2 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:98:2 | @@ -41,7 +41,6 @@ | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | fixtures/reject/src/lib.rs:504:2 | | 1 | `_` of `_` by `_`, which is not supported yet | fixtures/reject/src/lib.rs:260:6 | | 1 | `_` of `_`, which is not supported yet | fixtures/reject/src/lib.rs:547:4 | -| 1 | `_` of a value JS copies, which is no path | fixtures/reject/src/lib.rs:1646:2 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:268:9 | | 1 | `_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported | fixtures/reject/src/lib.rs:390:6 | | 1 | `collect` of `_`, which sorts by `_`'s own `Ord`, of entries that drop, which is not supported yet | fixtures/reject/src/lib.rs:964:22 | @@ -95,6 +94,7 @@ The type or module each refused type or path belongs to. | 4 | `Iterator` | fixtures/reject/src/lib.rs:37:4 | | 4 | `[u8; 4]` | fixtures/reject/src/lib.rs:483:26 | | 4 | `std::pin::Pin` | fixtures/reject/src/lib.rs:98:2 | +| 4 | `std::str` | fixtures/reject/src/lib.rs:441:4 | | 3 | `*const [u8; 4]` | fixtures/reject/src/lib.rs:1829:33 | | 3 | `std::ptr` | fixtures/reject/src/lib.rs:1826:3 | | 3 | `std::vec::Vec` | fixtures/reject/src/lib.rs:317:16 | @@ -212,14 +212,11 @@ The type or module each refused type or path belongs to. | 1 | `std::net::AddrParseError` | fixtures/reject/src/lib.rs:440:32 | | 1 | `std::net::Ipv4Addr` | fixtures/reject/src/lib.rs:440:32 | | 1 | `std::num` | fixtures/reject/src/lib.rs:1286:4 | -| 1 | `std::ops::DerefMut` | fixtures/reject/src/lib.rs:1646:2 | -| 1 | `std::ops::IndexMut` | fixtures/reject/src/lib.rs:1652:3 | | 1 | `std::ops::RangeFrom` | fixtures/reject/src/lib.rs:993:32 | | 1 | `std::ops::RangeTo` | fixtures/reject/src/lib.rs:993:11 | | 1 | `std::ptr::mut_ptr` | fixtures/reject/src/lib.rs:1829:56 | | 1 | `std::slice::IterMut` | fixtures/reject/src/lib.rs:775:15 | | 1 | `std::std::Layout` | fixtures/reject/src/lib.rs:574:15 | -| 1 | `std::str` | fixtures/reject/src/lib.rs:441:4 | | 1 | `std::sync::Mutex` | fixtures/reject/src/lib.rs:523:12 | | 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:457:40 | | 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:84:34 | @@ -261,9 +258,9 @@ The type or module each refused type or path belongs to. | 1 | `_` of `_`, which is not supported yet | `std::any::Any::type_id`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:547:4 | | 1 | `_` of `_`, whose `clone_from` is its own, which is not supported yet | `slice::clone_from_slice`, `Reused` | fixtures/reject/src/lib.rs:293:4 | | 1 | `_` of `_`, whose `clone_from` is its own, which is not supported yet | `slice::fill`, `Reused` | fixtures/reject/src/lib.rs:21:4 | -| 1 | `_` of a value JS copies, which is no path | `std::ops::DerefMut::deref_mut` | fixtures/reject/src/lib.rs:1646:2 | | 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::iter::once` | fixtures/reject/src/lib.rs:1244:22 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::ops::IndexMut::index_mut` | fixtures/reject/src/lib.rs:1652:3 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::str::from_utf8_mut` | fixtures/reject/src/lib.rs:1651:20 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::str::get_unchecked_mut` | fixtures/reject/src/lib.rs:1646:13 | | 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::sync::Mutex::get_mut` | fixtures/reject/src/lib.rs:523:12 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:268:9 | | 1 | `_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported | `BytesMut::capacity` | fixtures/reject/src/lib.rs:390:6 | @@ -384,6 +381,7 @@ The type or module each refused type or path belongs to. | 1 | unsupported call to `_` | `std::std::Layout::new` | fixtures/reject/src/lib.rs:574:15 | | 1 | unsupported call to `_` | `std::std::alloc` | fixtures/reject/src/lib.rs:576:11 | | 1 | unsupported call to `_` | `std::std::dealloc` | fixtures/reject/src/lib.rs:579:3 | +| 1 | unsupported call to `_` | `std::str::as_bytes_mut` | fixtures/reject/src/lib.rs:1645:13 | | 1 | unsupported call to `_` | `std::str::parse` | fixtures/reject/src/lib.rs:441:4 | | 1 | unsupported type `_` from another crate | `std::net::AddrParseError` | fixtures/reject/src/lib.rs:440:32 | | 1 | unsupported type `_` from another crate | `std::net::Ipv4Addr` | fixtures/reject/src/lib.rs:440:32 | @@ -440,7 +438,7 @@ The type or module each refused type or path belongs to. -
unsupported call to `_` (25) +
unsupported call to `_` (26) - fixtures/reject/src/lib.rs:167:8: unsupported call to `std::ops::Range::::contains::` - fixtures/reject/src/lib.rs:308:10: unsupported call to `::hash::` @@ -460,6 +458,7 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:993:32: unsupported call to ` as std::ops::RangeBounds>::contains::` - fixtures/reject/src/lib.rs:998:9: unsupported call to `std::ops::Range::<&mut u8>::is_empty` - fixtures/reject/src/lib.rs:1286:4: unsupported call to `core::num::::is_ascii_octdigit` +- fixtures/reject/src/lib.rs:1645:13: unsupported call to `core::str::::as_bytes_mut` - fixtures/reject/src/lib.rs:1826:3: unsupported call to `std::ptr::copy::<[u8; 4]>` - fixtures/reject/src/lib.rs:1827:3: unsupported call to `std::ptr::copy_nonoverlapping::<[u8; 4]>` - fixtures/reject/src/lib.rs:1828:14: unsupported call to `std::ptr::addr_eq::<[u8; 4], [u8; 4]>` @@ -523,6 +522,15 @@ 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 (4) + +- fixtures/reject/src/lib.rs:523:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:1244:22: `std::iter::once` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:1646:13: `core::str::::get_unchecked_mut` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:1651:20: `std::str::from_utf8_mut` with a mutable reference to a value JS copies, which its mapping would copy + +
+
a variant of `_`, which is not supported: either is the same JS string (4) - fixtures/reject/src/lib.rs:338:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string @@ -532,14 +540,6 @@ 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:523:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy -- fixtures/reject/src/lib.rs:1244:22: `std::iter::once` with a mutable reference to a value JS copies, which its mapping would copy -- fixtures/reject/src/lib.rs:1652:3: `std::ops::IndexMut::index_mut` with a mutable reference to a value JS copies, which its mapping would copy - -
-
a copy of a closure that changes what it captured (3) - fixtures/reject/src/lib.rs:231:14: a copy of a closure that changes what it captured @@ -717,12 +717,6 @@ The type or module each refused type or path belongs to.
-
`_` of a value JS copies, which is no path (1) - -- fixtures/reject/src/lib.rs:1646:2: `std::ops::DerefMut::deref_mut` of a value JS copies, which is no path - -
-
`_`, which is not supported yet (1) - fixtures/reject/src/lib.rs:268:9: `Hasher::write`, which is not supported yet From 20991d5c28510fb9179aec060ecb9c14c37ec3a4 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:15:31 -0700 Subject: [PATCH 05/11] chore: claim quest/m3/ts-box-places Co-Authored-By: Claude Opus 5.5 From e892b35b9c3e1f3128c102a274893c37dd70676d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:24:34 -0700 Subject: [PATCH 06/11] fix(ts): a &mut into a Box is the place holding the box Co-Authored-By: Claude Opus 5.5 --- ts/src/lower/mir/call.rs | 17 ++++++++++---- ts/src/lower/mir/mod.rs | 13 +++++++++++ ts/src/lower/mir/place.rs | 49 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 72 insertions(+), 7 deletions(-) diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index a5842b943..9efd00024 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -656,6 +656,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { { self.same_place(args, dest, span, out) } + // A box is what it holds, so the `&mut` borrows the place holding the box. + ("DerefMut", "deref_mut") | ("AsMut", "as_mut") | ("BorrowMut", "borrow_mut") + if targ(0).and_then(|t| t.boxed_ty()).is_some_and(|t| self.b.t.needs_place(t)) => + { + self.same_place(args, dest, span, out) + } // A place nothing else holds: the `String` leaked, or `Default`'s empty `str`. ("String", "leak") => { let leaked = self.operand(&args[0].node, span, out); @@ -725,8 +731,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let base = self.read_as(dest, "taken"); done(self.swap_out(place, option, none, base, span, out), base.is_some()) } - // The place of the payload, if any: `as_mut`'s, or what `iter_mut` yields. - ("Option", "as_mut" | "iter_mut") if self.b.t.needs_place(targ(0)?) => { + // The place of the payload, if any: `as_mut`'s, or what `iter_mut` yields. A box's is + // what it holds, which `as_deref_mut` lends. + ("Option", "as_mut" | "iter_mut" | "as_deref_mut") + if self.b.t.needs_place(targ(0)?) && (name != "as_deref_mut" || targ(0)?.is_box()) => + { let (target, payload) = self.payload_place(&args[0].node, targ(0)?, span, out)?; let Some(payload) = payload else { return done(target, true); @@ -735,8 +744,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let place = self.make_place(payload, target, span, out); let lent = Expr::Cond(Box::new(none), Box::new(Expr::undefined()), Box::new(place)); match name.as_str() { - "as_mut" => done(lent, true), - _ => done(Expr::rt("iterOption", vec![lent]), true), + "iter_mut" => done(Expr::rt("iterOption", vec![lent]), true), + _ => done(lent, true), } } ("Option", "get_or_insert" | "get_or_insert_with" | "get_or_insert_default" | "insert") => { diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 0e9c971e2..88f6ce99b 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -921,6 +921,19 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return ty.is_bool() || ty.is_char() || crate::lower::num::Int::of(ty).is_some_and(|i| !i.big()); } match (mir.local_decls[local].ty.kind(), rvalue) { + // A box's pointer to a value JS copies, or a copy of such a box that a `**b` reads + // it through, is the place holding the box, where a copy would be another value. + // Rust makes each for the one read or write it is made beside, while the box stays. + (ty::RawPtr(pointee, _), Rvalue::Cast(mir::CastKind::BoxDerefTransmute, ..)) + if self.b.t.needs_place(*pointee) => + { + true + } + (ty::Adt(adt, args), Rvalue::Use(Operand::Copy(_), _) | Rvalue::CopyForDeref(_)) + if adt.is_box() && self.b.t.needs_place(args.type_at(0)) => + { + true + } // A borrow: borrow checking keeps the place as it is but through the borrow, // unless the path to it goes through a reference held in a field or element, // which can be replaced while the borrow lives. diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 7b64dfbc7..de3a91df1 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -862,8 +862,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { matches!(self.slots[local], Slot::Alias(_)) && match self.def_rvalue(local) { // A reborrow of what an alias of a borrowed place points at borrows that place. + // A box's pointer is the box, so what it points at is the place holding the box. Some(mir::Rvalue::Ref(_, _, p)) => match p.projection.as_slice() { - [ProjectionElem::Deref] => self.points_at_place(p.local), + [ProjectionElem::Deref] => self.points_at_place(p.local) || self.box_pointer(p.local), [.., ProjectionElem::Deref] => false, _ => true, }, @@ -909,18 +910,58 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { /// The type of `place` if it is a variant's payload, whose JS path is its whole enum, /// as `Some`'s is the `Option`. pub(super) fn payload_ty(&mut self, place: Place<'tcx>, span: Span) -> Option { + let place = self.through_aliases(place); let downcast = place.iter_projections().any(|(base, e)| { matches!(e, ProjectionElem::Downcast(..)) && base.ty(&self.mir.local_decls, self.tcx).ty.is_enum() }); downcast.then(|| self.b.t.ty(place.ty(&self.mir.local_decls, self.tcx).ty, span)) } + /// `place` with each alias it starts from replaced by the place the alias stands for, + /// as its JS path is: a borrowed place for what an alias of one points at, the box for a + /// copy of it, and what the box holds for what a box's pointer points at. + pub(super) fn through_aliases(&self, mut place: Place<'tcx>) -> Place<'tcx> { + let tcx = self.tcx; + loop { + if !matches!(self.slots[place.local], Slot::Alias(_)) { + return place; + } + let (base, rest) = match (self.def_rvalue(place.local), place.projection.as_slice()) { + (Some(mir::Rvalue::Ref(_, _, p)), [ProjectionElem::Deref, rest @ ..]) if self.alias_of_place(place.local) => { + (*p, rest) + } + (Some(mir::Rvalue::Cast(mir::CastKind::BoxDerefTransmute, op, _)), [ProjectionElem::Deref, rest @ ..]) + if let Some(p) = op.place() + && let [inner @ .., ProjectionElem::Field(..)] = p.projection.as_slice() => + { + let boxed = Place { + local: p.local, + projection: tcx.mk_place_elems(inner), + }; + (tcx.mk_place_deref(boxed), rest) + } + (Some(mir::Rvalue::Use(Operand::Copy(p), _) | mir::Rvalue::CopyForDeref(p)), rest) + if self.mir.local_decls[place.local].ty.is_box() => + { + (*p, rest) + } + _ => return place, + }; + let mut projection = base.projection.to_vec(); + projection.extend_from_slice(rest); + place = Place { + local: base.local, + projection: tcx.mk_place_elems(&projection), + }; + } + } + /// `target`, the JS path of the borrowed `place`, with the objects and index it goes /// through held where they are now, as the borrow fixes them, for an `rt.Place` that /// reads and writes it later. pub(super) fn stable_target(&mut self, place: Place<'tcx>, target: Expr, span: Span, out: &mut Vec) -> Expr { // A store into a `Result`'s value makes the `Result` again, which a path can't. - for (base, elem) in place.iter_projections() { + for (base, elem) in self.through_aliases(place).iter_projections() { if let ProjectionElem::Downcast(..) = elem && let Some(std @ (Std::Result | Std::ControlFlow)) = self.b.t.std_of(base.ty(&self.mir.local_decls, self.tcx).ty) @@ -1041,7 +1082,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { projection: self.tcx.mk_place_elems(rest), }; let base_ty = base.ty(&self.mir.local_decls, self.tcx).ty; - if self.b.t.place_pointee(base_ty).is_none() || base.as_local().is_some_and(|l| self.alias_of_place(l)) { + if self.b.t.place_pointee(base_ty).is_none() + || base.as_local().is_some_and(|l| self.alias_of_place(l) || self.box_pointer(l)) + { return None; } Some(self.place_expr(base, span, out)) From 9218473ce1e6873c08e86563faf4caf784d7faa9 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:00:25 -0700 Subject: [PATCH 07/11] test(ts): writes reaching what a box holds, against native Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 1 - quest/m3/ts-box-places.md | 16 -- ts/README.md | 2 +- ts/fixtures/lang/expected/boxes.Owner.ts | 12 ++ ts/fixtures/lang/expected/boxes.ts | 208 ++++++++++++++++++++++- ts/fixtures/lang/expected/core/bool.ts | 7 + ts/fixtures/lang/expected/core/option.ts | 6 + ts/fixtures/lang/expected/harness.ts | 4 +- ts/fixtures/lang/src/boxes.rs | 156 ++++++++++++++++- ts/fixtures/lang/src/harness.rs | 1 + ts/src/lower/library.rs | 2 + ts/src/lower/mir/call.rs | 5 +- 12 files changed, 397 insertions(+), 23 deletions(-) delete mode 100644 quest/m3/ts-box-places.md create mode 100644 ts/fixtures/lang/expected/boxes.Owner.ts diff --git a/quest/m3/README.md b/quest/m3/README.md index adde5a3a5..026efa49e 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -32,7 +32,6 @@ generic std gap is planned here even when moq never calls it. - [ptr::replace whose result nothing reads](/quest/m3/ts-ptr-replace-unread.md) - `ptr::replace` with its result discarded type-checks - [std's sorts call their tests in std's order](/quest/m3/ts-sort-order.md) - `slice::sort` and a B-tree's `collect` call `lt` or `cmp` as std's driftsort does past 16 elements - [A B-tree's searches call Ord as std's do](/quest/m3/ts-btree-search-order.md) - a B-tree's lookups and inserts call a key's own `Ord` in std's order and number -- [A &mut into a Box of a value JS copies](/quest/m3/ts-box-places.md) - a write through `&mut *b` of a `Box`, a `Box`, or a `Box` reaches the box's place - [A str's checked and inclusive parts](/quest/m3/ts-str-get.md) - `str::get` and indexing a `str` by `a..=b` or `..=b` translate - [The rest of a boxed slice's impls](/quest/m3/ts-boxed-slice-rest.md) - `clone_from`, `AsRef`, `AsMut`, `TryFrom` into a boxed array, and `Box` into bytes translate for boxed slices - [A crate's own Extend in a tuple](/quest/m3/ts-tuple-own-extend.md) - `collect` and `extend` into a tuple holding a crate's `Extend` type translate diff --git a/quest/m3/ts-box-places.md b/quest/m3/ts-box-places.md deleted file mode 100644 index 68b2d7dba..000000000 --- a/quest/m3/ts-box-places.md +++ /dev/null @@ -1,16 +0,0 @@ -# [S] A &mut into a Box of a value JS copies - -## Goal - -[rust2-ts](/ts/README.md) translates a `&mut` to what a `Box` holds, where JS copies it (a -number, a `String`, or a `str`), as a write to the local or field holding the box. Today -`*(&mut *b) += 1` of a `Box`, `push` on a `Box`, and `make_ascii_uppercase` -on a `Box` translate to `b.v` of a value with no `v`, which `tsc` rejects. Proven by -differential tests against native Rust. - -## Plan - -Found translating `&mut str`'s places. A `Box` is its `T`, so a `&mut` through it is -the box's own place, as `String::as_mut_str` borrows the `String`'s. - -Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index ab8317f7f..999c36f35 100644 --- a/ts/README.md +++ b/ts/README.md @@ -94,7 +94,7 @@ crate translation reaches is refused, and so are two versions of one crate it re | `ControlFlow` | `rt.Result`, `Ok` to continue; what `?` branches on is the value it was applied to, but for a `Poll`'s `Pending` and `Ready(None)`, which continue as `Ok` of themselves | | tuple, `[T; N]`, `&[T]`, `Box<[T]>`, `Vec` | an array; for bytes, `Uint8Array` for `[u8; N]`, `rt.ByteSlice` for `&[u8]`, `&[u8; N]`, and `Box<[u8]>`, and `rt.ByteVec` for `Vec` | | `Cow<[T]>` | `rt.Cow`: the `Vec` it owns, or an `rt.Borrowed` holding the slice it borrows; `rt.ByteCow` for bytes, an `rt.ByteVec` or an `rt.ByteSlice` | -| `&T`, `&mut T`, `Box`, `Reverse`, `NonZero` | the value; a `&mut` to a value JS copies, such as a number, an `Option`, a `String`, or a reference, or to an `Arc` or a `Waker`, is an `rt.Place` | +| `&T`, `&mut T`, `Box`, `Reverse`, `NonZero` | the value; a `&mut` to a value JS copies, such as a number, an `Option`, a `String`, or a reference, or to an `Arc` or a `Waker`, is an `rt.Place`, which for what a box holds is the place holding the box | | `*const T`, `*mut T`, `NonNull` | what a `&mut T` is: the object, an `rt.ByteSlice` of a `[u8; N]`'s bytes, which compares by the buffer and offset they are at, or an `rt.Place` to a value JS copies and to a library type such as a `Vec` or an `Arc`; `rt.NULL` for null and `rt.DANGLING` for dangling. A `*const ()` is an identity, such as a waker's data, and `rt.DANGLING_UNIT` when dangling; one to a place of `()` or from a reference to one is refused. A write of a whole object copies into it one object deep, as an assignment through a `&mut` does, so a pointer to a part kept as an object, such as a field of a tuple or struct type, is refused wherever the crate may put another object there while a pointer into that memory may still be read, which a write into a fresh allocation, or a variable before any pointer into it is taken, can't, whether by index or through std's iterators over its slots; a read copies what the crate writes into in place | | `MaybeUninit` | `T`: `undefined` until written, or an object whose parts kept as objects are there, holding `undefined` | | `union` | an object of slots named by offset, `at0` and `at8`, each holding the field part kept there; fields must overlap in the same type, or in a non-null pointer and an `Option` of it | diff --git a/ts/fixtures/lang/expected/boxes.Owner.ts b/ts/fixtures/lang/expected/boxes.Owner.ts new file mode 100644 index 000000000..c8d263a2f --- /dev/null +++ b/ts/fixtures/lang/expected/boxes.Owner.ts @@ -0,0 +1,12 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** Boxes of values JS copies, held in a struct a `&mut` reaches. */ +export interface Owner { + n: rt.u32; + s: string; + nested: rt.u32; +} + +//# sourceMappingURL=boxes.Owner.ts.map diff --git a/ts/fixtures/lang/expected/boxes.ts b/ts/fixtures/lang/expected/boxes.ts index 745dd00c2..bba5059ff 100644 --- a/ts/fixtures/lang/expected/boxes.ts +++ b/ts/fixtures/lang/expected/boxes.ts @@ -4,7 +4,9 @@ import * as rt from "./rt.ts"; import { copy$array_tuple2_u8_u16, copy$array_u16, copy$array_u8, copy$tuple2_u8_u16 } from "./lib.ts"; import * as boxes_Held from "./boxes.Held.ts"; import * as boxes_Logged from "./boxes.Logged.ts"; -import { unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$1j4op5y as option_unwrapOr$1j4op5y, mapOr$1e4a1e0 as option_mapOr$1e4a1e0 } from "./core/option.ts"; +import type * as Owner from "./boxes.Owner.ts"; +import { then$0ea5h05 } from "./core/bool.ts"; +import { unwrapOr$1iemzn8 as option_unwrapOr$1iemzn8, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$1j4op5y as option_unwrapOr$1j4op5y, unwrapOr$11c0we2 as option_unwrapOr$11c0we2, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, asDeref$0w8at8i as option_asDeref$0w8at8i, asDeref$0avuzwv as option_asDeref$0avuzwv } from "./core/option.ts"; import { put as fmt_put } from "./fmt.ts"; import { text } from "./strs.ts"; @@ -430,4 +432,208 @@ export function boxes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } } +/** Adds `by` to what `x` borrows. */ +export function bump(x: rt.Place, by: rt.u8): void { + x.v = rt.u32WrappingAdd(x.v, by as rt.u32); +} + +/** Writes through a `&mut` to what a `Box` holds, and to a part of it. */ +export function shout(s: rt.Place, by: rt.u8): void { + const half: rt.usize = rt.usizeDiv(rt.stringLen(s.v), 2); + if (rt.u8Rem(by, 2) === 0) { + s.v = rt.strToAsciiUppercase(s.v); + } else { + const _9: rt.Place = rt.strPart(s, 0, half); + _9.v = rt.strToAsciiLowercase(_9.v); + } +} + +/** A box taken by value and written through before it is given back. */ +export function took(b: rt.u32, by: rt.u8): rt.u32 { + bump(rt.place(() => b, (value) => b = value), by); + return b; +} + +/** What `&mut Owner` reaches of its boxes, each written by `by`. */ +export function reach(b: Owner.Owner, by: rt.u8): void { + const _3: rt.u8 = rt.u8Rem(by, 4); + if (_3 === 0) { + bump(rt.place(() => b.n, (value2) => b.n = value2), by); + } else if (_3 === 1) { + b.n = (b.n ^ by as rt.u32) >>> 0; + } else if (_3 === 2) { + bump(rt.place(() => b.nested, (value) => b.nested = value), by); + } else { + b.s = b.s + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char); + } +} + +/** + * Writes reaching what boxes hold, each step by a byte, kept in a local, reassigned, + * nested, in a field, a `Vec`, and an `Option`, captured, passed, and leaked: through + * `&mut *b`, `DerefMut`, `AsMut`, `BorrowMut`, `as_deref_mut`, and a write through the box + * itself. + */ +export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + let n: rt.u32 = 7; + const pair: Uint8Array = Uint8Array.of(1, 2); + let s: string = "b"; + let t: string = "aBc/D"; + let nested: rt.u32 = 3; + let maybe: rt.u32 | undefined = undefined as rt.u32 | undefined; + const held: Owner.Owner = { n: 5, s: "", nested: 9 }; + const v: rt.u32[] = [1, 2]; + let o: rt.u32 | undefined = 4; + const words: rt.u32[] = [6, 8]; + const someWords: rt.u32[] | undefined = [3, 5]; + let named: string | undefined = "xY/z"; + const leaked: rt.Place = { v: 11 }; + const iter: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterSlice(rt.byteSliceView(data))); + while (true) { + const _39: [rt.usize, rt.u8] | rt.Done = iter.next(); + if (_39 === rt.DONE) { + break; + } + const i: rt.usize = _39[0]; + const by: rt.u8 = _39[1]; + const _45: rt.u8 = rt.u8Rem(by, 26); + if (_45 === 0) { + n = rt.u32WrappingMul(n, 3); + } else if (_45 === 1) { + bump(rt.place(() => n, (value20) => n = value20), by); + } else if (_45 === 2) { + const _52: rt.Place = rt.place(() => n, (value18) => n = value18); + bump(rt.place(() => _52.v, (value19) => _52.v = value19), by); + } else if (_45 === 3) { + const _54: rt.Place = rt.place(() => n, (value16) => n = value16); + bump(rt.place(() => _54.v, (value17) => _54.v = value17), by); + } else if (_45 === 4) { + const _56: rt.Place = rt.place(() => n, (value14) => n = value14); + bump(rt.place(() => _56.v, (value15) => _56.v = value15), by); + } else if (_45 === 5) { + n = (n ^ by as rt.u32) >>> 0; + } else if (_45 === 6) { + n = rt.u32WrappingAdd(by as rt.u32, n); + } else if (_45 === 7) { + const r: rt.ByteSlice = rt.byteSliceFrom(pair); + const _63: rt.usize = rt.usizeRem(by as rt.usize, 2); + if (!(_63 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _63); + } + r.data[r.start + _63] = r.data[r.start + _63] ^ by; + } else if (_45 === 8) { + s = s + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char); + } else if (_45 === 9) { + s = s + "!?"; + } else if (_45 === 10) { + s = rt.stringInsertStr(s, 0, "<"); + } else if (_45 === 11) { + shout(rt.place(() => t, (value13) => t = value13), by); + } else if (_45 === 12) { + const _79: rt.Place = rt.place(() => t, (value11) => t = value11); + shout(rt.place(() => _79.v, (value12) => _79.v = value12), by); + } else if (_45 === 13) { + const _81: rt.Place = rt.place(() => t, (value10) => t = value10); + _81.v = rt.strToAsciiLowercase(_81.v); + } else if (_45 === 14) { + t = rt.strSlice(s, 0); + } else if (_45 === 15) { + bump(rt.place(() => nested, (value9) => nested = value9), by); + } else if (_45 === 16) { + nested = rt.u32WrappingAdd(nested, by as rt.u32); + } else if (_45 === 17) { + const _91: rt.u32 = by as rt.u32; + if (maybe === undefined) { + maybe = _91; + } + maybe = rt.u32Add(maybe as rt.u32, 1); + if (maybe !== undefined) { + bump(rt.place(() => maybe as rt.u32, (value8) => maybe = value8), by); + } + } else if (_45 === 18) { + reach(held, by); + } else if (_45 === 19) { + const at2 = rt.idx(v, rt.usizeRem(by as rt.usize, v.length)); + const borrowed = v; + const borrowed2 = at2; + bump(rt.place(() => borrowed[borrowed2], (value7) => borrowed[borrowed2] = value7), by); + const _107: rt.Place | undefined = rt.sliceLastMut(v); + if (_107 !== undefined) { + _107.v = (_107.v ^ 16) >>> 0; + } + } else if (_45 === 20) { + const iter2: rt.Iter> = rt.iterSliceMut(v); + while (true) { + const _117: rt.Place | rt.Done = iter2.next(); + if (_117 === rt.DONE) { + break; + } + bump(rt.place(() => _117.v, (value6) => _117.v = value6), by); + } + v.push(by as rt.u32); + } else if (_45 === 21) { + const _127: rt.Place = rt.place(() => o, (value3) => o = value3); + if (_127.v !== undefined) { + _127.v = rt.u32WrappingAdd(_127.v, by as rt.u32); + } + const _134: rt.Place = rt.place(() => o, (value4) => o = value4); + const _133: rt.Place | undefined = _134.v === undefined ? undefined : rt.place(() => _134.v as rt.u32, (value5) => _134.v = value5); + if (_133 !== undefined) { + bump(_133, by); + } + if (rt.usizeRem(i, 3) === 0) { + o = then$0ea5h05(o === undefined, (): rt.u32 => { + return by as rt.u32; + }); + } + } else if (_45 === 22) { + const _147: rt.u32 = by as rt.u32; + const _148: rt.usize = rt.usizeRem(by as rt.usize, 2); + rt.idx(words, _148); + words[_148] = rt.u32Add(words[_148], _147); + const _155: rt.u32[] | undefined = someWords; + if (_155 !== undefined) { + const _159: rt.u32 = by as rt.u32; + rt.idx(_155, 1); + _155[1] = (_155[1] ^ _159) >>> 0; + } + const _164: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value2) => named = value2); + if (_164 !== undefined) { + shout(_164, by); + } + } else if (_45 === 23) { + const f: (a0: rt.u8) => undefined = (by2: rt.u8): undefined => { + bump(rt.place(() => n, (value) => n = value), by2); + }; + f(by); + f(1); + } else if (_45 === 24) { + n = took(n, by); + } else { + bump(leaked, by); + } + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(n).reverse()), undefined, true); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(pair)); + fmt_put(out, s); + fmt_put(out, t); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(nested).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(maybe, 238)).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(held.n).reverse()), undefined, true); + fmt_put(out, held.s); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(held.nested).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterSlice(v), (b: rt.u32): Uint8Array => { + return rt.u32ToBeBytes(b).reverse(); + }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(option_asDeref$0avuzwv(o), 238)).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterSlice(words), (w: rt.u32): Uint8Array => { + return rt.u32ToBeBytes(w).reverse(); + }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); + rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterFlatten(rt.iterOption(someWords), (value: rt.u32[]) => rt.iterSlice(value)), (w2: rt.u32): Uint8Array => { + return rt.u32ToBeBytes(w2).reverse(); + }, (value: Uint8Array) => rt.iterSlice(value), false, 4), "next"); + fmt_put(out, option_unwrapOr$1iemzn8(option_asDeref$0w8at8i(named), "-")); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(leaked.v).reverse()), undefined, true); + } +} + //# sourceMappingURL=boxes.ts.map diff --git a/ts/fixtures/lang/expected/core/bool.ts b/ts/fixtures/lang/expected/core/bool.ts index c5f520aa5..0a0cd172e 100644 --- a/ts/fixtures/lang/expected/core/bool.ts +++ b/ts/fixtures/lang/expected/core/bool.ts @@ -209,6 +209,13 @@ export function then$1j955kq(self: boolean, _: () => defaults_Made.Made): defaul return defaults_Made.default$Default(); } +export function then$0ea5h05(self: boolean, f: () => rt.u32): rt.u32 | undefined { + if (!self) { + return undefined; + } + return f(); +} + export function then$0wlzj76(self: boolean, f: () => rt.Ordering): rt.Ordering | undefined { if (!self) { return undefined; diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index 2d2b2cd85..4fba97380 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -1541,6 +1541,12 @@ export function asDeref$0w8at8i(self: string | undefined): string | undefined { }); } +export function asDeref$0avuzwv(self: rt.u32 | undefined): rt.u32 | undefined { + return map$0xz4pvf(self, (a0: rt.u32): rt.u32 => { + return a0; + }); +} + export function and$06om98g(self: rt.u8 | undefined, optb: rt.u8 | undefined): rt.u8 | undefined { if (self === undefined) { return undefined; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 12f6e5b6f..cda860ade 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -6,7 +6,7 @@ import { bytes as ascii_bytes, chars as ascii_chars, slices as ascii_slices, par import { atomics } from "./atomics.ts"; import { borrows as borrows_borrows } from "./borrows.ts"; import { bounds as bounds_bounds } from "./bounds.ts"; -import { boxes } from "./boxes.ts"; +import { boxes, places as boxes_places } from "./boxes.ts"; import { captures } from "./captures.ts"; import { cells as cells_cells } from "./cells.ts"; import { chars as chars_chars } from "./chars.ts"; @@ -236,7 +236,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) optionItems(data85, out86); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["lists::lists", lists_lists as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["pointers::reattached", (_2186: rt.u8, data86: rt.ByteSlice, out87: rt.ByteVec): undefined => { reattached(data86, out87); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["ascii::parts", ascii_parts as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["ascii::parts", ascii_parts as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["boxes::places", boxes_places as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; } /** Run one case. */ diff --git a/ts/fixtures/lang/src/boxes.rs b/ts/fixtures/lang/src/boxes.rs index b3056e315..224de57b8 100644 --- a/ts/fixtures/lang/src/boxes.rs +++ b/ts/fixtures/lang/src/boxes.rs @@ -2,7 +2,8 @@ //! by `collect`, `Vec::into_boxed_slice`, `Default`, `Clone`, and coercing a boxed //! array, read and written through `Deref`, compared, hashed, and printed as their //! slice is, and turned back by `into_vec` and `into_iter`, of bytes and of other values, -//! empty or not, with what drops dropped in std's order. +//! empty or not, with what drops dropped in std's order. Then writes reaching what a box +//! of a value JS copies holds. use std::borrow::Cow; use std::cell::RefCell; @@ -345,3 +346,156 @@ pub fn boxes(kind: u8, data: &[u8], out: &mut Vec) { } } } + +/// Boxes of values JS copies, held in a struct a `&mut` reaches. +struct Owner { + n: Box, + s: Box, + nested: Box>, +} + +/// Adds `by` to what `x` borrows. +fn bump(x: &mut u32, by: u8) { + *x = x.wrapping_add(u32::from(by)); +} + +/// Writes through a `&mut` to what a `Box` holds, and to a part of it. +fn shout(s: &mut str, by: u8) { + let half = s.len() / 2; + match by % 2 { + 0 => s.make_ascii_uppercase(), + _ => s[..half].make_ascii_lowercase(), + } +} + +/// A box taken by value and written through before it is given back. +fn took(mut b: Box, by: u8) -> Box { + bump(&mut *b, by); + b +} + +/// What `&mut Owner` reaches of its boxes, each written by `by`. +fn reach(b: &mut Owner, by: u8) { + match by % 4 { + 0 => bump(&mut *b.n, by), + 1 => *b.n ^= u32::from(by), + 2 => bump(&mut **b.nested, by), + _ => b.s.push(char::from(b'a' + by % 26)), + } +} + +/// Writes reaching what boxes hold, each step by a byte, kept in a local, reassigned, +/// nested, in a field, a `Vec`, and an `Option`, captured, passed, and leaked: through +/// `&mut *b`, `DerefMut`, `AsMut`, `BorrowMut`, `as_deref_mut`, and a write through the box +/// itself. +pub fn places(_: u8, data: &[u8], out: &mut Vec) { + use std::borrow::BorrowMut; + use std::ops::DerefMut; + let mut n = Box::new(7u32); + let mut pair = Box::new([1u8, 2]); + let mut s = Box::new(String::from("b")); + let mut t: Box = Box::from("aBc/D"); + let mut nested = Box::new(Box::new(3u32)); + let mut maybe = Box::new(None::); + let mut held = Owner { + n: Box::new(5), + s: Box::new(String::new()), + nested: Box::new(Box::new(9)), + }; + let mut v = vec![Box::new(1u32), Box::new(2)]; + let mut o = Some(Box::new(4u32)); + let mut words: Box<[u32]> = Box::from([6, 8]); + let mut some_words: Option> = Some(Box::from([3, 5])); + let mut named: Option> = Some(Box::from("xY/z")); + let leaked = Box::leak(Box::new(11u32)); + for (i, &by) in data.iter().enumerate() { + match by % 26 { + 0 => { + let r = &mut *n; + *r = r.wrapping_mul(3); + } + 1 => bump(&mut *n, by), + 2 => bump(n.as_mut(), by), + 3 => bump(n.deref_mut(), by), + 4 => bump(n.borrow_mut(), by), + 5 => *n ^= u32::from(by), + 6 => n = Box::new(u32::from(by).wrapping_add(*n)), + 7 => { + let r = &mut *pair; + r[usize::from(by) % 2] ^= by; + } + 8 => s.push(char::from(b'a' + by % 26)), + 9 => (&mut *s).push_str("!?"), + 10 => s.as_mut().insert(0, '<'), + 11 => shout(&mut *t, by), + 12 => shout(t.as_mut(), by), + 13 => BorrowMut::::borrow_mut(&mut t).make_ascii_lowercase(), + 14 => t = Box::from(&s[..]), + 15 => bump(&mut **nested, by), + 16 => **nested = nested.wrapping_add(u32::from(by)), + 17 => { + *maybe.get_or_insert(u32::from(by)) += 1; + if let Some(x) = &mut *maybe { + bump(x, by); + } + } + 18 => reach(&mut held, by), + 19 => { + let at = usize::from(by) % v.len(); + bump(&mut *v[at], by); + if let Some(last) = v.last_mut() { + **last ^= 0x10; + } + } + 20 => { + for b in v.iter_mut() { + bump(b, by); + } + v.push(Box::new(u32::from(by))); + } + 21 => { + if let Some(b) = &mut o { + **b = b.wrapping_add(u32::from(by)); + } + if let Some(r) = o.as_deref_mut() { + bump(r, by); + } + if i % 3 == 0 { + o = o.is_none().then(|| Box::new(u32::from(by))); + } + } + 22 => { + let r = &mut *words; + r[usize::from(by) % 2] += u32::from(by); + if let Some(w) = some_words.as_deref_mut() { + w[1] ^= u32::from(by); + } + if let Some(t) = named.as_deref_mut() { + shout(t, by); + } + } + 23 => { + let mut f = |by| bump(&mut *n, by); + f(by); + f(1); + } + 24 => n = took(n, by), + _ => bump(leaked, by), + } + out.extend(n.to_le_bytes()); + out.extend_from_slice(&*pair); + put(out, &s); + put(out, &t); + out.extend(nested.to_le_bytes()); + out.extend(maybe.unwrap_or(0xee).to_le_bytes()); + out.extend(held.n.to_le_bytes()); + put(out, &held.s); + out.extend(held.nested.to_le_bytes()); + out.extend(v.iter().flat_map(|b| b.to_le_bytes())); + out.extend(o.as_deref().copied().unwrap_or(0xee).to_le_bytes()); + out.extend(words.iter().flat_map(|w| w.to_le_bytes())); + out.extend(some_words.iter().flatten().flat_map(|w| w.to_le_bytes())); + put(out, named.as_deref().unwrap_or("-")); + out.extend(leaked.to_le_bytes()); + } +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index b9aec49bf..ab81640a9 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -259,6 +259,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("lists::lists", lists::lists), ("pointers::reattached", |_, data, out| pointers::reattached(data, out)), ("ascii::parts", ascii::parts), + ("boxes::places", boxes::places), ] } diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 6475c7202..f5858c390 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -1516,6 +1516,8 @@ fn mapping<'tcx>( ("Option", "is_some") => args.pop()?.binary("!==", b.t.none(targ(gargs, 0))), ("Option", "is_none") => args.pop()?.binary("===", b.t.none(targ(gargs, 0))), ("Option", "as_ref" | "as_mut") => args.pop()?, + // A box is what it holds. + ("Option", "as_deref_mut") if targ(gargs, 0).is_box() => args.pop()?, // `Option<&T>` or `Option<&mut T>` of the `T` it points at, through `T`'s `Clone` // where that does more than copy, as std's `cloned` does. ("Option", "copied" | "cloned") => { diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 9efd00024..e99421d4f 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -734,7 +734,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { // The place of the payload, if any: `as_mut`'s, or what `iter_mut` yields. A box's is // what it holds, which `as_deref_mut` lends. ("Option", "as_mut" | "iter_mut" | "as_deref_mut") - if self.b.t.needs_place(targ(0)?) && (name != "as_deref_mut" || targ(0)?.is_box()) => + if match name.as_str() { + "as_deref_mut" => targ(0)?.boxed_ty().is_some_and(|t| self.b.t.needs_place(t)), + _ => self.b.t.needs_place(targ(0)?), + } => { let (target, payload) = self.payload_place(&args[0].node, targ(0)?, span, out)?; let Some(payload) = payload else { From 54eae7efc8cc2e8a2b04a40828eebbd12b22b1b5 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:02:40 -0700 Subject: [PATCH 08/11] style(ts): format Co-Authored-By: Claude Opus 5.5 --- ts/src/lower/mir/call.rs | 4 +++- ts/src/lower/mir/place.rs | 16 +++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index e99421d4f..6cea5a2b9 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -658,7 +658,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } // A box is what it holds, so the `&mut` borrows the place holding the box. ("DerefMut", "deref_mut") | ("AsMut", "as_mut") | ("BorrowMut", "borrow_mut") - if targ(0).and_then(|t| t.boxed_ty()).is_some_and(|t| self.b.t.needs_place(t)) => + if targ(0) + .and_then(|t| t.boxed_ty()) + .is_some_and(|t| self.b.t.needs_place(t)) => { self.same_place(args, dest, span, out) } diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index de3a91df1..a20d212fc 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -927,12 +927,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return place; } let (base, rest) = match (self.def_rvalue(place.local), place.projection.as_slice()) { - (Some(mir::Rvalue::Ref(_, _, p)), [ProjectionElem::Deref, rest @ ..]) if self.alias_of_place(place.local) => { + (Some(mir::Rvalue::Ref(_, _, p)), [ProjectionElem::Deref, rest @ ..]) + if self.alias_of_place(place.local) => + { (*p, rest) } - (Some(mir::Rvalue::Cast(mir::CastKind::BoxDerefTransmute, op, _)), [ProjectionElem::Deref, rest @ ..]) - if let Some(p) = op.place() - && let [inner @ .., ProjectionElem::Field(..)] = p.projection.as_slice() => + ( + Some(mir::Rvalue::Cast(mir::CastKind::BoxDerefTransmute, op, _)), + [ProjectionElem::Deref, rest @ ..], + ) if let Some(p) = op.place() + && let [inner @ .., ProjectionElem::Field(..)] = p.projection.as_slice() => { let boxed = Place { local: p.local, @@ -1083,7 +1087,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { }; let base_ty = base.ty(&self.mir.local_decls, self.tcx).ty; if self.b.t.place_pointee(base_ty).is_none() - || base.as_local().is_some_and(|l| self.alias_of_place(l) || self.box_pointer(l)) + || base + .as_local() + .is_some_and(|l| self.alias_of_place(l) || self.box_pointer(l)) { return None; } From 3109174ca6d2394cbdf9fd7d4b5a56e1139e2afc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:22:48 -0700 Subject: [PATCH 09/11] fix(ts): a write into a Result's box makes the Result again Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/lang/expected/boxes.ts | 174 +++++++++++++---------- ts/fixtures/lang/expected/core/result.ts | 34 +++++ ts/fixtures/lang/src/boxes.rs | 18 ++- ts/src/lower/mir/place.rs | 16 ++- 4 files changed, 160 insertions(+), 82 deletions(-) diff --git a/ts/fixtures/lang/expected/boxes.ts b/ts/fixtures/lang/expected/boxes.ts index bba5059ff..34d9333ff 100644 --- a/ts/fixtures/lang/expected/boxes.ts +++ b/ts/fixtures/lang/expected/boxes.ts @@ -7,6 +7,7 @@ import * as boxes_Logged from "./boxes.Logged.ts"; import type * as Owner from "./boxes.Owner.ts"; import { then$0ea5h05 } from "./core/bool.ts"; import { unwrapOr$1iemzn8 as option_unwrapOr$1iemzn8, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$1j4op5y as option_unwrapOr$1j4op5y, unwrapOr$11c0we2 as option_unwrapOr$11c0we2, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, asDeref$0w8at8i as option_asDeref$0w8at8i, asDeref$0avuzwv as option_asDeref$0avuzwv } from "./core/option.ts"; +import { asDeref$04i8i5u as result_asDeref$04i8i5u, unwrapOr$0e4foht as result_unwrapOr$0e4foht, copied$0bbq7yi } from "./core/result.ts"; import { put as fmt_put } from "./fmt.ts"; import { text } from "./strs.ts"; @@ -470,7 +471,7 @@ export function reach(b: Owner.Owner, by: rt.u8): void { /** * Writes reaching what boxes hold, each step by a byte, kept in a local, reassigned, - * nested, in a field, a `Vec`, and an `Option`, captured, passed, and leaked: through + * nested, in a field, a `Vec`, an `Option`, and a `Result`, captured, passed, and leaked: through * `&mut *b`, `DerefMut`, `AsMut`, `BorrowMut`, `as_deref_mut`, and a write through the box * itself. */ @@ -484,130 +485,142 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const held: Owner.Owner = { n: 5, s: "", nested: 9 }; const v: rt.u32[] = [1, 2]; let o: rt.u32 | undefined = 4; + let res: rt.Result = rt.Ok(2); + let said: rt.Result = rt.Ok("r"); const words: rt.u32[] = [6, 8]; const someWords: rt.u32[] | undefined = [3, 5]; let named: string | undefined = "xY/z"; const leaked: rt.Place = { v: 11 }; const iter: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterSlice(rt.byteSliceView(data))); while (true) { - const _39: [rt.usize, rt.u8] | rt.Done = iter.next(); - if (_39 === rt.DONE) { + const _44: [rt.usize, rt.u8] | rt.Done = iter.next(); + if (_44 === rt.DONE) { break; } - const i: rt.usize = _39[0]; - const by: rt.u8 = _39[1]; - const _45: rt.u8 = rt.u8Rem(by, 26); - if (_45 === 0) { + const i: rt.usize = _44[0]; + const by: rt.u8 = _44[1]; + const _50: rt.u8 = rt.u8Rem(by, 26); + if (_50 === 0) { n = rt.u32WrappingMul(n, 3); - } else if (_45 === 1) { - bump(rt.place(() => n, (value20) => n = value20), by); - } else if (_45 === 2) { - const _52: rt.Place = rt.place(() => n, (value18) => n = value18); - bump(rt.place(() => _52.v, (value19) => _52.v = value19), by); - } else if (_45 === 3) { - const _54: rt.Place = rt.place(() => n, (value16) => n = value16); - bump(rt.place(() => _54.v, (value17) => _54.v = value17), by); - } else if (_45 === 4) { - const _56: rt.Place = rt.place(() => n, (value14) => n = value14); - bump(rt.place(() => _56.v, (value15) => _56.v = value15), by); - } else if (_45 === 5) { + } else if (_50 === 1) { + bump(rt.place(() => n, (value21) => n = value21), by); + } else if (_50 === 2) { + const _57: rt.Place = rt.place(() => n, (value19) => n = value19); + bump(rt.place(() => _57.v, (value20) => _57.v = value20), by); + } else if (_50 === 3) { + const _59: rt.Place = rt.place(() => n, (value17) => n = value17); + bump(rt.place(() => _59.v, (value18) => _59.v = value18), by); + } else if (_50 === 4) { + const _61: rt.Place = rt.place(() => n, (value15) => n = value15); + bump(rt.place(() => _61.v, (value16) => _61.v = value16), by); + } else if (_50 === 5) { n = (n ^ by as rt.u32) >>> 0; - } else if (_45 === 6) { + } else if (_50 === 6) { n = rt.u32WrappingAdd(by as rt.u32, n); - } else if (_45 === 7) { + } else if (_50 === 7) { const r: rt.ByteSlice = rt.byteSliceFrom(pair); - const _63: rt.usize = rt.usizeRem(by as rt.usize, 2); - if (!(_63 < 2)) { - rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _63); + const _68: rt.usize = rt.usizeRem(by as rt.usize, 2); + if (!(_68 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _68); } - r.data[r.start + _63] = r.data[r.start + _63] ^ by; - } else if (_45 === 8) { + r.data[r.start + _68] = r.data[r.start + _68] ^ by; + } else if (_50 === 8) { s = s + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char); - } else if (_45 === 9) { + } else if (_50 === 9) { s = s + "!?"; - } else if (_45 === 10) { + } else if (_50 === 10) { s = rt.stringInsertStr(s, 0, "<"); - } else if (_45 === 11) { - shout(rt.place(() => t, (value13) => t = value13), by); - } else if (_45 === 12) { - const _79: rt.Place = rt.place(() => t, (value11) => t = value11); - shout(rt.place(() => _79.v, (value12) => _79.v = value12), by); - } else if (_45 === 13) { - const _81: rt.Place = rt.place(() => t, (value10) => t = value10); - _81.v = rt.strToAsciiLowercase(_81.v); - } else if (_45 === 14) { + } else if (_50 === 11) { + shout(rt.place(() => t, (value14) => t = value14), by); + } else if (_50 === 12) { + const _84: rt.Place = rt.place(() => t, (value12) => t = value12); + shout(rt.place(() => _84.v, (value13) => _84.v = value13), by); + } else if (_50 === 13) { + const _86: rt.Place = rt.place(() => t, (value11) => t = value11); + _86.v = rt.strToAsciiLowercase(_86.v); + } else if (_50 === 14) { t = rt.strSlice(s, 0); - } else if (_45 === 15) { - bump(rt.place(() => nested, (value9) => nested = value9), by); - } else if (_45 === 16) { + } else if (_50 === 15) { + bump(rt.place(() => nested, (value10) => nested = value10), by); + } else if (_50 === 16) { nested = rt.u32WrappingAdd(nested, by as rt.u32); - } else if (_45 === 17) { - const _91: rt.u32 = by as rt.u32; + } else if (_50 === 17) { + const _96: rt.u32 = by as rt.u32; if (maybe === undefined) { - maybe = _91; + maybe = _96; } maybe = rt.u32Add(maybe as rt.u32, 1); if (maybe !== undefined) { - bump(rt.place(() => maybe as rt.u32, (value8) => maybe = value8), by); + bump(rt.place(() => maybe as rt.u32, (value9) => maybe = value9), by); } - } else if (_45 === 18) { + } else if (_50 === 18) { reach(held, by); - } else if (_45 === 19) { + } else if (_50 === 19) { const at2 = rt.idx(v, rt.usizeRem(by as rt.usize, v.length)); const borrowed = v; const borrowed2 = at2; - bump(rt.place(() => borrowed[borrowed2], (value7) => borrowed[borrowed2] = value7), by); - const _107: rt.Place | undefined = rt.sliceLastMut(v); - if (_107 !== undefined) { - _107.v = (_107.v ^ 16) >>> 0; + bump(rt.place(() => borrowed[borrowed2], (value8) => borrowed[borrowed2] = value8), by); + const _112: rt.Place | undefined = rt.sliceLastMut(v); + if (_112 !== undefined) { + _112.v = (_112.v ^ 16) >>> 0; } - } else if (_45 === 20) { + } else if (_50 === 20) { const iter2: rt.Iter> = rt.iterSliceMut(v); while (true) { - const _117: rt.Place | rt.Done = iter2.next(); - if (_117 === rt.DONE) { + const _122: rt.Place | rt.Done = iter2.next(); + if (_122 === rt.DONE) { break; } - bump(rt.place(() => _117.v, (value6) => _117.v = value6), by); + bump(rt.place(() => _122.v, (value7) => _122.v = value7), by); } v.push(by as rt.u32); - } else if (_45 === 21) { - const _127: rt.Place = rt.place(() => o, (value3) => o = value3); - if (_127.v !== undefined) { - _127.v = rt.u32WrappingAdd(_127.v, by as rt.u32); + } else if (_50 === 21) { + const _132: rt.Place = rt.place(() => o, (value3) => o = value3); + if (_132.v !== undefined) { + _132.v = rt.u32WrappingAdd(_132.v, by as rt.u32); } - const _134: rt.Place = rt.place(() => o, (value4) => o = value4); - const _133: rt.Place | undefined = _134.v === undefined ? undefined : rt.place(() => _134.v as rt.u32, (value5) => _134.v = value5); - if (_133 !== undefined) { - bump(_133, by); + const _139: rt.Place = rt.place(() => o, (value4) => o = value4); + const _138: rt.Place | undefined = _139.v === undefined ? undefined : rt.place(() => _139.v as rt.u32, (value5) => _139.v = value5); + if (_138 !== undefined) { + bump(_138, by); } if (rt.usizeRem(i, 3) === 0) { o = then$0ea5h05(o === undefined, (): rt.u32 => { return by as rt.u32; }); } - } else if (_45 === 22) { - const _147: rt.u32 = by as rt.u32; - const _148: rt.usize = rt.usizeRem(by as rt.usize, 2); - rt.idx(words, _148); - words[_148] = rt.u32Add(words[_148], _147); - const _155: rt.u32[] | undefined = someWords; - if (_155 !== undefined) { - const _159: rt.u32 = by as rt.u32; - rt.idx(_155, 1); - _155[1] = (_155[1] ^ _159) >>> 0; + if (res.ok) { + res = rt.Ok(rt.u32WrappingMul(res.value, by as rt.u32)); } - const _164: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value2) => named = value2); - if (_164 !== undefined) { - shout(_164, by); + const _157: rt.Place> = rt.place(() => said, (value6) => said = value6); + if (_157.v.ok) { + _157.v = rt.Ok(_157.v.value + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char)); } - } else if (_45 === 23) { + if (rt.usizeRem(i, 5) === 4) { + said = rt.Err(by); + } + } else if (_50 === 22) { + const _172: rt.u32 = by as rt.u32; + const _173: rt.usize = rt.usizeRem(by as rt.usize, 2); + rt.idx(words, _173); + words[_173] = rt.u32Add(words[_173], _172); + const _180: rt.u32[] | undefined = someWords; + if (_180 !== undefined) { + const _184: rt.u32 = by as rt.u32; + rt.idx(_180, 1); + _180[1] = (_180[1] ^ _184) >>> 0; + } + const _189: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value2) => named = value2); + if (_189 !== undefined) { + shout(_189, by); + } + } else if (_50 === 23) { const f: (a0: rt.u8) => undefined = (by2: rt.u8): undefined => { bump(rt.place(() => n, (value) => n = value), by2); }; f(by); f(1); - } else if (_45 === 24) { + } else if (_50 === 24) { n = took(n, by); } else { bump(leaked, by); @@ -625,6 +638,13 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { return rt.u32ToBeBytes(b).reverse(); }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(option_asDeref$0avuzwv(o), 238)).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(copied$0bbq7yi(result_asDeref$04i8i5u(res)), 238)).reverse()), undefined, true); + const _252: rt.Result = said; + if (_252.ok) { + fmt_put(out, _252.value); + } else { + rt.byteVecPush(out, _252.error); + } rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterSlice(words), (w: rt.u32): Uint8Array => { return rt.u32ToBeBytes(w).reverse(); }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); diff --git a/ts/fixtures/lang/expected/core/result.ts b/ts/fixtures/lang/expected/core/result.ts index e3449b6b5..cb9bfa907 100644 --- a/ts/fixtures/lang/expected/core/result.ts +++ b/ts/fixtures/lang/expected/core/result.ts @@ -486,6 +486,13 @@ export function err$05f656d(self: rt.Result): rt.u16 | undefined return self.error; } +export function asRef$10maq8w(self: rt.Result): rt.Result { + if (self.ok) { + return rt.Ok(self.value); + } + return rt.Err(self.error); +} + export function asRef$1glrxiq(self: rt.Result): rt.Result { if (self.ok) { return rt.Ok(self.value); @@ -521,6 +528,13 @@ export function map$0fm1w6u(self: rt.Result, op: (a0 return self as rt.Result, rt.ParseBoolError>; } +export function map$0m0doqe(self: rt.Result, _: (a0: rt.u32) => rt.u32): rt.Result { + if (self.ok) { + return rt.Ok(self.value); + } + return self; +} + export function map$0zzqmaz(self: rt.Result, rt.Arc>, op: (a0: rt.Arc<[rt.u8, rt.u8]>) => [rt.usize, rt.u8]): rt.Result<[rt.usize, rt.u8], rt.Arc> { if (self.ok) { return rt.Ok(op(self.value)); @@ -628,6 +642,12 @@ export function inspectErr$06tv5sa(self: rt.Result, f: (a0: rt.u1 return self; } +export function asDeref$04i8i5u(self: rt.Result): rt.Result { + return map$0m0doqe(asRef$10maq8w(self), (a0: rt.u32): rt.u32 => { + return a0; + }); +} + export function unwrapOrDefault$1exw7nd(self: rt.Result): rt.u8 { if (self.ok) { return self.value; @@ -726,6 +746,13 @@ export function unwrapOr$0u9zzk3(self: rt.Result, de return default_; } +export function unwrapOr$0e4foht(self: rt.Result, default_: rt.u32): rt.u32 { + if (self.ok) { + return self.value; + } + return default_; +} + export function unwrapOr$1dnnsw8(self: rt.Result, default_: rt.u32): rt.u32 { if (self.ok) { return self.value; @@ -782,6 +809,13 @@ export function unwrapOrElse$009ibtw(self: rt.Result, op: (a0: rt. return op(self.error); } +export function copied$0bbq7yi(self: rt.Result): rt.Result { + if (self.ok) { + return rt.Ok(self.value); + } + return self; +} + export function copied$0ma6p21(self: rt.Result): rt.Result { if (self.ok) { return rt.Ok(self.value); diff --git a/ts/fixtures/lang/src/boxes.rs b/ts/fixtures/lang/src/boxes.rs index 224de57b8..a4c2b318a 100644 --- a/ts/fixtures/lang/src/boxes.rs +++ b/ts/fixtures/lang/src/boxes.rs @@ -385,7 +385,7 @@ fn reach(b: &mut Owner, by: u8) { } /// Writes reaching what boxes hold, each step by a byte, kept in a local, reassigned, -/// nested, in a field, a `Vec`, and an `Option`, captured, passed, and leaked: through +/// nested, in a field, a `Vec`, an `Option`, and a `Result`, captured, passed, and leaked: through /// `&mut *b`, `DerefMut`, `AsMut`, `BorrowMut`, `as_deref_mut`, and a write through the box /// itself. pub fn places(_: u8, data: &[u8], out: &mut Vec) { @@ -404,6 +404,8 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { }; let mut v = vec![Box::new(1u32), Box::new(2)]; let mut o = Some(Box::new(4u32)); + let mut res: Result, u8> = Ok(Box::new(2)); + let mut said: Result, u8> = Ok(Box::new(String::from("r"))); let mut words: Box<[u32]> = Box::from([6, 8]); let mut some_words: Option> = Some(Box::from([3, 5])); let mut named: Option> = Some(Box::from("xY/z")); @@ -463,6 +465,15 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { if i % 3 == 0 { o = o.is_none().then(|| Box::new(u32::from(by))); } + if let Ok(b) = &mut res { + **b = b.wrapping_mul(u32::from(by)); + } + if let Ok(s) = &mut said { + s.push(char::from(b'a' + by % 26)); + } + if i % 5 == 4 { + said = Err(by); + } } 22 => { let r = &mut *words; @@ -493,6 +504,11 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { out.extend(held.nested.to_le_bytes()); out.extend(v.iter().flat_map(|b| b.to_le_bytes())); out.extend(o.as_deref().copied().unwrap_or(0xee).to_le_bytes()); + out.extend(res.as_deref().copied().unwrap_or(0xee).to_le_bytes()); + match &said { + Ok(s) => put(out, s), + Err(e) => out.push(*e), + } out.extend(words.iter().flat_map(|w| w.to_le_bytes())); out.extend(some_words.iter().flatten().flat_map(|w| w.to_le_bytes())); put(out, named.as_deref().unwrap_or("-")); diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index a20d212fc..eed0458bd 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -817,11 +817,19 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let tcx = self.tcx; let (mut at, mut value, mut rebuilt) = (place, value, false); loop { - if let [ProjectionElem::Deref, rest @ ..] = at.projection.as_slice() - && self.alias_of_place(at.local) - && let Some(mir::Rvalue::Ref(_, _, borrowed)) = self.def_rvalue(at.local) + let through = self.through_aliases(at); + if through != at { + at = through; + continue; + } + // A box is what it holds. + if let [rest @ .., ProjectionElem::Deref] = at.projection.as_slice() + && Place::ty_from(at.local, rest, &self.mir.local_decls, tcx).ty.is_box() { - at = borrowed.project_deeper(rest, tcx); + at = Place { + local: at.local, + projection: tcx.mk_place_elems(rest), + }; continue; } if let [ProjectionElem::Deref, rest @ ..] = at.projection.as_slice() From 857631e263d91c021eb873d8b180a47d2c6e2a40 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:36:13 -0700 Subject: [PATCH 10/11] fix(ts): a Some of a box of an enum keeps its whole type, as the enum's does TypeScript narrowed `Some(Box::new(Some(1)))` to `u32`, so a later `=== rt.None` test failed tsc: `narrows` said a box does not narrow, though it is what it holds in JS. Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/lang/expected/boxes.ts | 206 +++++++++++++---------- ts/fixtures/lang/expected/core/option.ts | 20 +++ ts/fixtures/lang/expected/core/result.ts | 27 +++ ts/fixtures/lang/src/boxes.rs | 26 +++ ts/fixtures/task/expected/drops.ts | 2 +- ts/src/lower/mod.rs | 2 + 6 files changed, 197 insertions(+), 86 deletions(-) diff --git a/ts/fixtures/lang/expected/boxes.ts b/ts/fixtures/lang/expected/boxes.ts index 34d9333ff..1452f7436 100644 --- a/ts/fixtures/lang/expected/boxes.ts +++ b/ts/fixtures/lang/expected/boxes.ts @@ -6,8 +6,8 @@ import * as boxes_Held from "./boxes.Held.ts"; import * as boxes_Logged from "./boxes.Logged.ts"; import type * as Owner from "./boxes.Owner.ts"; import { then$0ea5h05 } from "./core/bool.ts"; -import { unwrapOr$1iemzn8 as option_unwrapOr$1iemzn8, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$1j4op5y as option_unwrapOr$1j4op5y, unwrapOr$11c0we2 as option_unwrapOr$11c0we2, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, asDeref$0w8at8i as option_asDeref$0w8at8i, asDeref$0avuzwv as option_asDeref$0avuzwv } from "./core/option.ts"; -import { asDeref$04i8i5u as result_asDeref$04i8i5u, unwrapOr$0e4foht as result_unwrapOr$0e4foht, copied$0bbq7yi } from "./core/result.ts"; +import { unwrapOr$1iemzn8 as option_unwrapOr$1iemzn8, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$1j4op5y as option_unwrapOr$1j4op5y, unwrapOr$11c0we2 as option_unwrapOr$11c0we2, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, asDeref$0w8at8i as option_asDeref$0w8at8i, asDeref$0w2m0zn as option_asDeref$0w2m0zn, asDeref$0avuzwv as option_asDeref$0avuzwv, flatten$08boupk as option_flatten$08boupk } from "./core/option.ts"; +import { map$0nfi04k as result_map$0nfi04k, asDeref$1fldd5d as result_asDeref$1fldd5d, asDeref$04i8i5u as result_asDeref$04i8i5u, unwrapOr$0e4foht as result_unwrapOr$0e4foht, copied$0bbq7yi } from "./core/result.ts"; import { put as fmt_put } from "./fmt.ts"; import { text } from "./strs.ts"; @@ -491,98 +491,101 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const someWords: rt.u32[] | undefined = [3, 5]; let named: string | undefined = "xY/z"; const leaked: rt.Place = { v: 11 }; + let deep = 1 as rt.u32 | undefined | rt.None; + const tup: rt.Result<[rt.u32, rt.u32], rt.u8> = rt.Ok([1, 2]); + let boxedOpt: rt.u32 | undefined = 3; const iter: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterSlice(rt.byteSliceView(data))); while (true) { - const _44: [rt.usize, rt.u8] | rt.Done = iter.next(); - if (_44 === rt.DONE) { + const _52: [rt.usize, rt.u8] | rt.Done = iter.next(); + if (_52 === rt.DONE) { break; } - const i: rt.usize = _44[0]; - const by: rt.u8 = _44[1]; - const _50: rt.u8 = rt.u8Rem(by, 26); - if (_50 === 0) { + const i: rt.usize = _52[0]; + const by: rt.u8 = _52[1]; + const _58: rt.u8 = rt.u8Rem(by, 26); + if (_58 === 0) { n = rt.u32WrappingMul(n, 3); - } else if (_50 === 1) { - bump(rt.place(() => n, (value21) => n = value21), by); - } else if (_50 === 2) { - const _57: rt.Place = rt.place(() => n, (value19) => n = value19); - bump(rt.place(() => _57.v, (value20) => _57.v = value20), by); - } else if (_50 === 3) { - const _59: rt.Place = rt.place(() => n, (value17) => n = value17); - bump(rt.place(() => _59.v, (value18) => _59.v = value18), by); - } else if (_50 === 4) { - const _61: rt.Place = rt.place(() => n, (value15) => n = value15); - bump(rt.place(() => _61.v, (value16) => _61.v = value16), by); - } else if (_50 === 5) { + } else if (_58 === 1) { + bump(rt.place(() => n, (value25) => n = value25), by); + } else if (_58 === 2) { + const _65: rt.Place = rt.place(() => n, (value23) => n = value23); + bump(rt.place(() => _65.v, (value24) => _65.v = value24), by); + } else if (_58 === 3) { + const _67: rt.Place = rt.place(() => n, (value21) => n = value21); + bump(rt.place(() => _67.v, (value22) => _67.v = value22), by); + } else if (_58 === 4) { + const _69: rt.Place = rt.place(() => n, (value19) => n = value19); + bump(rt.place(() => _69.v, (value20) => _69.v = value20), by); + } else if (_58 === 5) { n = (n ^ by as rt.u32) >>> 0; - } else if (_50 === 6) { + } else if (_58 === 6) { n = rt.u32WrappingAdd(by as rt.u32, n); - } else if (_50 === 7) { + } else if (_58 === 7) { const r: rt.ByteSlice = rt.byteSliceFrom(pair); - const _68: rt.usize = rt.usizeRem(by as rt.usize, 2); - if (!(_68 < 2)) { - rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _68); + const _76: rt.usize = rt.usizeRem(by as rt.usize, 2); + if (!(_76 < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _76); } - r.data[r.start + _68] = r.data[r.start + _68] ^ by; - } else if (_50 === 8) { + r.data[r.start + _76] = r.data[r.start + _76] ^ by; + } else if (_58 === 8) { s = s + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char); - } else if (_50 === 9) { + } else if (_58 === 9) { s = s + "!?"; - } else if (_50 === 10) { + } else if (_58 === 10) { s = rt.stringInsertStr(s, 0, "<"); - } else if (_50 === 11) { - shout(rt.place(() => t, (value14) => t = value14), by); - } else if (_50 === 12) { - const _84: rt.Place = rt.place(() => t, (value12) => t = value12); - shout(rt.place(() => _84.v, (value13) => _84.v = value13), by); - } else if (_50 === 13) { - const _86: rt.Place = rt.place(() => t, (value11) => t = value11); - _86.v = rt.strToAsciiLowercase(_86.v); - } else if (_50 === 14) { + } else if (_58 === 11) { + shout(rt.place(() => t, (value18) => t = value18), by); + } else if (_58 === 12) { + const _92: rt.Place = rt.place(() => t, (value16) => t = value16); + shout(rt.place(() => _92.v, (value17) => _92.v = value17), by); + } else if (_58 === 13) { + const _94: rt.Place = rt.place(() => t, (value15) => t = value15); + _94.v = rt.strToAsciiLowercase(_94.v); + } else if (_58 === 14) { t = rt.strSlice(s, 0); - } else if (_50 === 15) { - bump(rt.place(() => nested, (value10) => nested = value10), by); - } else if (_50 === 16) { + } else if (_58 === 15) { + bump(rt.place(() => nested, (value14) => nested = value14), by); + } else if (_58 === 16) { nested = rt.u32WrappingAdd(nested, by as rt.u32); - } else if (_50 === 17) { - const _96: rt.u32 = by as rt.u32; + } else if (_58 === 17) { + const _104: rt.u32 = by as rt.u32; if (maybe === undefined) { - maybe = _96; + maybe = _104; } maybe = rt.u32Add(maybe as rt.u32, 1); if (maybe !== undefined) { - bump(rt.place(() => maybe as rt.u32, (value9) => maybe = value9), by); + bump(rt.place(() => maybe as rt.u32, (value13) => maybe = value13), by); } - } else if (_50 === 18) { + } else if (_58 === 18) { reach(held, by); - } else if (_50 === 19) { + } else if (_58 === 19) { const at2 = rt.idx(v, rt.usizeRem(by as rt.usize, v.length)); const borrowed = v; const borrowed2 = at2; - bump(rt.place(() => borrowed[borrowed2], (value8) => borrowed[borrowed2] = value8), by); - const _112: rt.Place | undefined = rt.sliceLastMut(v); - if (_112 !== undefined) { - _112.v = (_112.v ^ 16) >>> 0; + bump(rt.place(() => borrowed[borrowed2], (value12) => borrowed[borrowed2] = value12), by); + const _120: rt.Place | undefined = rt.sliceLastMut(v); + if (_120 !== undefined) { + _120.v = (_120.v ^ 16) >>> 0; } - } else if (_50 === 20) { + } else if (_58 === 20) { const iter2: rt.Iter> = rt.iterSliceMut(v); while (true) { - const _122: rt.Place | rt.Done = iter2.next(); - if (_122 === rt.DONE) { + const _130: rt.Place | rt.Done = iter2.next(); + if (_130 === rt.DONE) { break; } - bump(rt.place(() => _122.v, (value7) => _122.v = value7), by); + bump(rt.place(() => _130.v, (value11) => _130.v = value11), by); } v.push(by as rt.u32); - } else if (_50 === 21) { - const _132: rt.Place = rt.place(() => o, (value3) => o = value3); - if (_132.v !== undefined) { - _132.v = rt.u32WrappingAdd(_132.v, by as rt.u32); + } else if (_58 === 21) { + const _140: rt.Place = rt.place(() => o, (value7) => o = value7); + if (_140.v !== undefined) { + _140.v = rt.u32WrappingAdd(_140.v, by as rt.u32); } - const _139: rt.Place = rt.place(() => o, (value4) => o = value4); - const _138: rt.Place | undefined = _139.v === undefined ? undefined : rt.place(() => _139.v as rt.u32, (value5) => _139.v = value5); - if (_138 !== undefined) { - bump(_138, by); + const _147: rt.Place = rt.place(() => o, (value8) => o = value8); + const _146: rt.Place | undefined = _147.v === undefined ? undefined : rt.place(() => _147.v as rt.u32, (value9) => _147.v = value9); + if (_146 !== undefined) { + bump(_146, by); } if (rt.usizeRem(i, 3) === 0) { o = then$0ea5h05(o === undefined, (): rt.u32 => { @@ -592,35 +595,63 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { if (res.ok) { res = rt.Ok(rt.u32WrappingMul(res.value, by as rt.u32)); } - const _157: rt.Place> = rt.place(() => said, (value6) => said = value6); - if (_157.v.ok) { - _157.v = rt.Ok(_157.v.value + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char)); + const _165: rt.Place> = rt.place(() => said, (value10) => said = value10); + if (_165.v.ok) { + _165.v = rt.Ok(_165.v.value + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char)); } if (rt.usizeRem(i, 5) === 4) { said = rt.Err(by); } - } else if (_50 === 22) { - const _172: rt.u32 = by as rt.u32; - const _173: rt.usize = rt.usizeRem(by as rt.usize, 2); - rt.idx(words, _173); - words[_173] = rt.u32Add(words[_173], _172); - const _180: rt.u32[] | undefined = someWords; - if (_180 !== undefined) { - const _184: rt.u32 = by as rt.u32; - rt.idx(_180, 1); - _180[1] = (_180[1] ^ _184) >>> 0; + } else if (_58 === 22) { + const _180: rt.u32 = by as rt.u32; + const _181: rt.usize = rt.usizeRem(by as rt.usize, 2); + rt.idx(words, _181); + words[_181] = rt.u32Add(words[_181], _180); + const _188: rt.u32[] | undefined = someWords; + if (_188 !== undefined) { + const _192: rt.u32 = by as rt.u32; + rt.idx(_188, 1); + _188[1] = (_188[1] ^ _192) >>> 0; } - const _189: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value2) => named = value2); - if (_189 !== undefined) { - shout(_189, by); + const _197: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value2) => named = value2); + if (_197 !== undefined) { + shout(_197, by); } - } else if (_50 === 23) { + const _202: rt.Place | undefined = deep === rt.None ? undefined : rt.place(() => deep as rt.u32 | undefined, (value3) => deep = value3); + if (_202 !== undefined) { + if (_202.v !== undefined) { + _202.v = rt.u32Add(_202.v, by as rt.u32); + } + } + const _209: rt.Place | undefined = deep === rt.None ? undefined : rt.place(() => deep as rt.u32 | undefined, (value4) => deep = value4); + if (_209 !== undefined) { + if (!(rt.u8Rem(by, 4) === 0)) { + if (_209.v === undefined) { + _209.v = 9; + } + } else { + _209.v = undefined; + } + } + if (tup.ok) { + tup.value[0] = rt.u32Add(tup.value[0], by as rt.u32); + const _354: [rt.u32, rt.u32] = tup.value; + bump(rt.place(() => _354[1], (value5) => _354[1] = value5), by); + } + const _227: rt.Place | undefined = boxedOpt === undefined ? undefined : rt.place(() => boxedOpt as rt.u32, (value6) => boxedOpt = value6); + if (_227 !== undefined) { + bump(_227, by); + } + if (boxedOpt !== undefined) { + boxedOpt = rt.u32Add(boxedOpt, 1); + } + } else if (_58 === 23) { const f: (a0: rt.u8) => undefined = (by2: rt.u8): undefined => { bump(rt.place(() => n, (value) => n = value), by2); }; f(by); f(1); - } else if (_50 === 24) { + } else if (_58 === 24) { n = took(n, by); } else { bump(leaked, by); @@ -639,11 +670,11 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(option_asDeref$0avuzwv(o), 238)).reverse()), undefined, true); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(copied$0bbq7yi(result_asDeref$04i8i5u(res)), 238)).reverse()), undefined, true); - const _252: rt.Result = said; - if (_252.ok) { - fmt_put(out, _252.value); + const _295: rt.Result = said; + if (_295.ok) { + fmt_put(out, _295.value); } else { - rt.byteVecPush(out, _252.error); + rt.byteVecPush(out, _295.error); } rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterSlice(words), (w: rt.u32): Uint8Array => { return rt.u32ToBeBytes(w).reverse(); @@ -653,6 +684,11 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { }, (value: Uint8Array) => rt.iterSlice(value), false, 4), "next"); fmt_put(out, option_unwrapOr$1iemzn8(option_asDeref$0w8at8i(named), "-")); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(leaked.v).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(option_flatten$08boupk(option_asDeref$0w2m0zn(deep)), 238)).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(result_map$0nfi04k(result_asDeref$1fldd5d(tup), (t2: [rt.u32, rt.u32]): rt.u32 => { + return (t2[0] ^ t2[1]) >>> 0; + }), 238)).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(boxedOpt, 238)).reverse()), undefined, true); } } diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index e273e2814..2310d858b 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -500,6 +500,13 @@ export function map$11y9s7r(self: slices_Pair.Pair[] | undefined, f: (a0: slices return f(self); } +export function map$1k1fy8u(self: rt.u32 | undefined | rt.None, _: (a0: rt.u32 | undefined) => rt.u32 | undefined): rt.u32 | undefined | rt.None { + if (self === rt.None) { + return rt.None; + } + return self; +} + export function map$0ltgf8p(self: ByRef.ByRef | undefined, f: (a0: ByRef.ByRef) => rt.u8): rt.u8 | undefined { if (self === undefined) { return undefined; @@ -1541,6 +1548,12 @@ export function asDeref$0w8at8i(self: string | undefined): string | undefined { }); } +export function asDeref$0w2m0zn(self: rt.u32 | undefined | rt.None): rt.u32 | undefined | rt.None { + return map$1k1fy8u(self, (a0: rt.u32 | undefined): rt.u32 | undefined => { + return a0; + }); +} + export function asDeref$0avuzwv(self: rt.u32 | undefined): rt.u32 | undefined { return map$0xz4pvf(self, (a0: rt.u32): rt.u32 => { return a0; @@ -1806,6 +1819,13 @@ export function clone$1omlcob(self: slices_Noisy.Noisy | undefined): slices_Nois return slices_Noisy.clone$Clone(self); } +export function flatten$08boupk(self: rt.u32 | undefined | rt.None): rt.u32 | undefined { + if (self === rt.None) { + return undefined; + } + return self; +} + export function flatten$1nwzx42(self: rt.u8 | undefined | rt.None): rt.u8 | undefined { if (self === rt.None) { return undefined; diff --git a/ts/fixtures/lang/expected/core/result.ts b/ts/fixtures/lang/expected/core/result.ts index cb9bfa907..3b2ba5936 100644 --- a/ts/fixtures/lang/expected/core/result.ts +++ b/ts/fixtures/lang/expected/core/result.ts @@ -486,6 +486,13 @@ export function err$05f656d(self: rt.Result): rt.u16 | undefined return self.error; } +export function asRef$0iljode(self: rt.Result<[rt.u32, rt.u32], rt.u8>): rt.Result<[rt.u32, rt.u32], rt.u8> { + if (self.ok) { + return rt.Ok(self.value); + } + return rt.Err(self.error); +} + export function asRef$10maq8w(self: rt.Result): rt.Result { if (self.ok) { return rt.Ok(self.value); @@ -528,6 +535,13 @@ export function map$0fm1w6u(self: rt.Result, op: (a0 return self as rt.Result, rt.ParseBoolError>; } +export function map$17yn9bi(self: rt.Result<[rt.u32, rt.u32], rt.u8>, _: (a0: [rt.u32, rt.u32]) => [rt.u32, rt.u32]): rt.Result<[rt.u32, rt.u32], rt.u8> { + if (self.ok) { + return rt.Ok(self.value); + } + return self; +} + export function map$0m0doqe(self: rt.Result, _: (a0: rt.u32) => rt.u32): rt.Result { if (self.ok) { return rt.Ok(self.value); @@ -535,6 +549,13 @@ export function map$0m0doqe(self: rt.Result, _: (a0: rt.u32) => r return self; } +export function map$0nfi04k(self: rt.Result<[rt.u32, rt.u32], rt.u8>, op: (a0: [rt.u32, rt.u32]) => rt.u32): rt.Result { + if (self.ok) { + return rt.Ok(op(self.value)); + } + return self as rt.Result; +} + export function map$0zzqmaz(self: rt.Result, rt.Arc>, op: (a0: rt.Arc<[rt.u8, rt.u8]>) => [rt.usize, rt.u8]): rt.Result<[rt.usize, rt.u8], rt.Arc> { if (self.ok) { return rt.Ok(op(self.value)); @@ -642,6 +663,12 @@ export function inspectErr$06tv5sa(self: rt.Result, f: (a0: rt.u1 return self; } +export function asDeref$1fldd5d(self: rt.Result<[rt.u32, rt.u32], rt.u8>): rt.Result<[rt.u32, rt.u32], rt.u8> { + return map$17yn9bi(asRef$0iljode(self), (a0: [rt.u32, rt.u32]): [rt.u32, rt.u32] => { + return a0; + }); +} + export function asDeref$04i8i5u(self: rt.Result): rt.Result { return map$0m0doqe(asRef$10maq8w(self), (a0: rt.u32): rt.u32 => { return a0; diff --git a/ts/fixtures/lang/src/boxes.rs b/ts/fixtures/lang/src/boxes.rs index a4c2b318a..09b05ca2f 100644 --- a/ts/fixtures/lang/src/boxes.rs +++ b/ts/fixtures/lang/src/boxes.rs @@ -410,6 +410,9 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { let mut some_words: Option> = Some(Box::from([3, 5])); let mut named: Option> = Some(Box::from("xY/z")); let leaked = Box::leak(Box::new(11u32)); + let mut deep: Option>> = Some(Box::new(Some(1))); + let mut tup: Result, u8> = Ok(Box::new((1, 2))); + let mut boxed_opt: Box> = Box::new(Some(3)); for (i, &by) in data.iter().enumerate() { match by % 26 { 0 => { @@ -484,6 +487,26 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { if let Some(t) = named.as_deref_mut() { shout(t, by); } + if let Some(Some(x)) = deep.as_deref_mut() { + *x += u32::from(by); + } + if let Some(d) = deep.as_deref_mut() { + if by % 4 == 0 { + *d = None; + } else if d.is_none() { + *d = Some(9); + } + } + if let Ok(b) = &mut tup { + b.0 += u32::from(by); + bump(&mut b.1, by); + } + if let Some(x) = boxed_opt.as_mut().as_mut() { + bump(x, by); + } + if let Some(x) = &mut *boxed_opt { + *x += 1; + } } 23 => { let mut f = |by| bump(&mut *n, by); @@ -513,5 +536,8 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { out.extend(some_words.iter().flatten().flat_map(|w| w.to_le_bytes())); put(out, named.as_deref().unwrap_or("-")); out.extend(leaked.to_le_bytes()); + out.extend(deep.as_deref().copied().flatten().unwrap_or(0xee).to_le_bytes()); + out.extend(tup.as_deref().map(|t| t.0 ^ t.1).unwrap_or(0xee).to_le_bytes()); + out.extend(boxed_opt.unwrap_or(0xee).to_le_bytes()); } } diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 9241586ea..d1645d00a 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -99,7 +99,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { v2.push(_70); const mutex: rt.Mutex = new rt.Mutex(v2); const boxed: Held.Held = { tag: "Two", _0: guard(6), _1: guard(7) }; - const maybe: Held.Held | undefined = { tag: "One", _0: guard(8) }; + const maybe = (({ tag: "One", _0: guard(8) } as Held.Held)) as Held.Held | undefined; const _94: rt.usize = held.length; const _97: boolean = maybe !== undefined; const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_94, f), (f: rt.Formatter) => rt.fmtBool(_97, f)]; diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 8ece3f813..8c62a7bd2 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -1116,6 +1116,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { /// variable to the member it was assigned. pub fn narrows(&self, ty: Ty<'tcx>) -> bool { match ty.kind() { + // A box is what it holds. + ty::Adt(adt, args) if adt.is_box() => self.narrows(args.type_at(0)), ty::Adt(adt, _) => match library::Std::of(self.tcx, adt.did()) { Some( library::Std::Option From 8e946f4de77459c5e1e01f96fc1e9d3575cb59bc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:44:03 -0700 Subject: [PATCH 11/11] fix(ts): judge a borrow through a box's pointer by the place holding the box Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/lang/expected/boxes.ts | 88 +++++++++++++++++++----------- ts/fixtures/lang/src/boxes.rs | 19 ++++++- ts/src/lower/mir/mod.rs | 36 +++++++++++- 3 files changed, 108 insertions(+), 35 deletions(-) diff --git a/ts/fixtures/lang/expected/boxes.ts b/ts/fixtures/lang/expected/boxes.ts index 1452f7436..48d67251c 100644 --- a/ts/fixtures/lang/expected/boxes.ts +++ b/ts/fixtures/lang/expected/boxes.ts @@ -455,6 +455,25 @@ export function took(b: rt.u32, by: rt.u8): rt.u32 { return b; } +/** + * A write through a pointer into what `a` holds, made before the reference holding `a` + * is aimed at `b`, still reaches `a`. + */ +export function reaimed(a: rt.Place, b: rt.Place, by: rt.u8): void { + let p!: rt.Place; + let r: rt.Place = a; + if (rt.u8Rem(by, 2) === 0) { + const borrowed = r; + p = rt.place(() => borrowed.v, (value2) => borrowed.v = value2); + } else { + const _9: rt.Place = r; + p = rt.place(() => _9.v, (value) => _9.v = value); + } + r = b; + p.v = (p.v ^ by as rt.u32) >>> 0; + r.v = rt.u32WrappingAdd(r.v, 1); +} + /** What `&mut Owner` reaches of its boxes, each written by `by`. */ export function reach(b: Owner.Owner, by: rt.u8): void { const _3: rt.u8 = rt.u8Rem(by, 4); @@ -504,29 +523,30 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const by: rt.u8 = _52[1]; const _58: rt.u8 = rt.u8Rem(by, 26); if (_58 === 0) { - n = rt.u32WrappingMul(n, 3); + const r: rt.Place = rt.place(() => n, (value28) => n = value28); + r.v = rt.u32WrappingMul(r.v, 3); } else if (_58 === 1) { - bump(rt.place(() => n, (value25) => n = value25), by); + bump(rt.place(() => n, (value27) => n = value27), by); } else if (_58 === 2) { - const _65: rt.Place = rt.place(() => n, (value23) => n = value23); - bump(rt.place(() => _65.v, (value24) => _65.v = value24), by); + const _65: rt.Place = rt.place(() => n, (value25) => n = value25); + bump(rt.place(() => _65.v, (value26) => _65.v = value26), by); } else if (_58 === 3) { - const _67: rt.Place = rt.place(() => n, (value21) => n = value21); - bump(rt.place(() => _67.v, (value22) => _67.v = value22), by); + const _67: rt.Place = rt.place(() => n, (value23) => n = value23); + bump(rt.place(() => _67.v, (value24) => _67.v = value24), by); } else if (_58 === 4) { - const _69: rt.Place = rt.place(() => n, (value19) => n = value19); - bump(rt.place(() => _69.v, (value20) => _69.v = value20), by); + const _69: rt.Place = rt.place(() => n, (value21) => n = value21); + bump(rt.place(() => _69.v, (value22) => _69.v = value22), by); } else if (_58 === 5) { n = (n ^ by as rt.u32) >>> 0; } else if (_58 === 6) { n = rt.u32WrappingAdd(by as rt.u32, n); } else if (_58 === 7) { - const r: rt.ByteSlice = rt.byteSliceFrom(pair); + const r2: rt.ByteSlice = rt.byteSliceFrom(pair); const _76: rt.usize = rt.usizeRem(by as rt.usize, 2); if (!(_76 < 2)) { rt.panic("index out of bounds: the len is " + 2 + " but the index is " + _76); } - r.data[r.start + _76] = r.data[r.start + _76] ^ by; + r2.data[r2.start + _76] = r2.data[r2.start + _76] ^ by; } else if (_58 === 8) { s = s + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char); } else if (_58 === 9) { @@ -534,17 +554,17 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } else if (_58 === 10) { s = rt.stringInsertStr(s, 0, "<"); } else if (_58 === 11) { - shout(rt.place(() => t, (value18) => t = value18), by); + shout(rt.place(() => t, (value20) => t = value20), by); } else if (_58 === 12) { - const _92: rt.Place = rt.place(() => t, (value16) => t = value16); - shout(rt.place(() => _92.v, (value17) => _92.v = value17), by); + const _92: rt.Place = rt.place(() => t, (value18) => t = value18); + shout(rt.place(() => _92.v, (value19) => _92.v = value19), by); } else if (_58 === 13) { - const _94: rt.Place = rt.place(() => t, (value15) => t = value15); + const _94: rt.Place = rt.place(() => t, (value17) => t = value17); _94.v = rt.strToAsciiLowercase(_94.v); } else if (_58 === 14) { t = rt.strSlice(s, 0); } else if (_58 === 15) { - bump(rt.place(() => nested, (value14) => nested = value14), by); + bump(rt.place(() => nested, (value16) => nested = value16), by); } else if (_58 === 16) { nested = rt.u32WrappingAdd(nested, by as rt.u32); } else if (_58 === 17) { @@ -554,7 +574,7 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } maybe = rt.u32Add(maybe as rt.u32, 1); if (maybe !== undefined) { - bump(rt.place(() => maybe as rt.u32, (value13) => maybe = value13), by); + bump(rt.place(() => maybe as rt.u32, (value15) => maybe = value15), by); } } else if (_58 === 18) { reach(held, by); @@ -562,7 +582,7 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const at2 = rt.idx(v, rt.usizeRem(by as rt.usize, v.length)); const borrowed = v; const borrowed2 = at2; - bump(rt.place(() => borrowed[borrowed2], (value12) => borrowed[borrowed2] = value12), by); + bump(rt.place(() => borrowed[borrowed2], (value14) => borrowed[borrowed2] = value14), by); const _120: rt.Place | undefined = rt.sliceLastMut(v); if (_120 !== undefined) { _120.v = (_120.v ^ 16) >>> 0; @@ -574,16 +594,16 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { if (_130 === rt.DONE) { break; } - bump(rt.place(() => _130.v, (value11) => _130.v = value11), by); + bump(rt.place(() => _130.v, (value13) => _130.v = value13), by); } v.push(by as rt.u32); } else if (_58 === 21) { - const _140: rt.Place = rt.place(() => o, (value7) => o = value7); + const _140: rt.Place = rt.place(() => o, (value9) => o = value9); if (_140.v !== undefined) { _140.v = rt.u32WrappingAdd(_140.v, by as rt.u32); } - const _147: rt.Place = rt.place(() => o, (value8) => o = value8); - const _146: rt.Place | undefined = _147.v === undefined ? undefined : rt.place(() => _147.v as rt.u32, (value9) => _147.v = value9); + const _147: rt.Place = rt.place(() => o, (value10) => o = value10); + const _146: rt.Place | undefined = _147.v === undefined ? undefined : rt.place(() => _147.v as rt.u32, (value11) => _147.v = value11); if (_146 !== undefined) { bump(_146, by); } @@ -595,7 +615,7 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { if (res.ok) { res = rt.Ok(rt.u32WrappingMul(res.value, by as rt.u32)); } - const _165: rt.Place> = rt.place(() => said, (value10) => said = value10); + const _165: rt.Place> = rt.place(() => said, (value12) => said = value12); if (_165.v.ok) { _165.v = rt.Ok(_165.v.value + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(by, 26)) as rt.char)); } @@ -613,17 +633,17 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { rt.idx(_188, 1); _188[1] = (_188[1] ^ _192) >>> 0; } - const _197: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value2) => named = value2); + const _197: rt.Place | undefined = named === undefined ? undefined : rt.place(() => named as string, (value4) => named = value4); if (_197 !== undefined) { shout(_197, by); } - const _202: rt.Place | undefined = deep === rt.None ? undefined : rt.place(() => deep as rt.u32 | undefined, (value3) => deep = value3); + const _202: rt.Place | undefined = deep === rt.None ? undefined : rt.place(() => deep as rt.u32 | undefined, (value5) => deep = value5); if (_202 !== undefined) { if (_202.v !== undefined) { _202.v = rt.u32Add(_202.v, by as rt.u32); } } - const _209: rt.Place | undefined = deep === rt.None ? undefined : rt.place(() => deep as rt.u32 | undefined, (value4) => deep = value4); + const _209: rt.Place | undefined = deep === rt.None ? undefined : rt.place(() => deep as rt.u32 | undefined, (value6) => deep = value6); if (_209 !== undefined) { if (!(rt.u8Rem(by, 4) === 0)) { if (_209.v === undefined) { @@ -635,10 +655,10 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } if (tup.ok) { tup.value[0] = rt.u32Add(tup.value[0], by as rt.u32); - const _354: [rt.u32, rt.u32] = tup.value; - bump(rt.place(() => _354[1], (value5) => _354[1] = value5), by); + const _357: [rt.u32, rt.u32] = tup.value; + bump(rt.place(() => _357[1], (value7) => _357[1] = value7), by); } - const _227: rt.Place | undefined = boxedOpt === undefined ? undefined : rt.place(() => boxedOpt as rt.u32, (value6) => boxedOpt = value6); + const _227: rt.Place | undefined = boxedOpt === undefined ? undefined : rt.place(() => boxedOpt as rt.u32, (value8) => boxedOpt = value8); if (_227 !== undefined) { bump(_227, by); } @@ -646,13 +666,15 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { boxedOpt = rt.u32Add(boxedOpt, 1); } } else if (_58 === 23) { + const _238: rt.Place = rt.place(() => n, (value3) => n = value3); const f: (a0: rt.u8) => undefined = (by2: rt.u8): undefined => { - bump(rt.place(() => n, (value) => n = value), by2); + bump(_238, by2); }; f(by); f(1); } else if (_58 === 24) { n = took(n, by); + reaimed(rt.place(() => n, (value) => n = value), rt.place(() => held.n, (value2) => held.n = value2), by); } else { bump(leaked, by); } @@ -670,11 +692,11 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(option_asDeref$0avuzwv(o), 238)).reverse()), undefined, true); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(copied$0bbq7yi(result_asDeref$04i8i5u(res)), 238)).reverse()), undefined, true); - const _295: rt.Result = said; - if (_295.ok) { - fmt_put(out, _295.value); + const _298: rt.Result = said; + if (_298.ok) { + fmt_put(out, _298.value); } else { - rt.byteVecPush(out, _295.error); + rt.byteVecPush(out, _298.error); } rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterSlice(words), (w: rt.u32): Uint8Array => { return rt.u32ToBeBytes(w).reverse(); diff --git a/ts/fixtures/lang/src/boxes.rs b/ts/fixtures/lang/src/boxes.rs index 09b05ca2f..dfae1e516 100644 --- a/ts/fixtures/lang/src/boxes.rs +++ b/ts/fixtures/lang/src/boxes.rs @@ -374,6 +374,20 @@ fn took(mut b: Box, by: u8) -> Box { b } +/// A write through a pointer into what `a` holds, made before the reference holding `a` +/// is aimed at `b`, still reaches `a`. +fn reaimed(a: &mut Box, b: &mut Box, by: u8) { + use std::ops::DerefMut; + let mut r = a; + let p = match by % 2 { + 0 => &mut **r, + _ => r.deref_mut(), + }; + r = b; + *p ^= u32::from(by); + **r = r.wrapping_add(1); +} + /// What `&mut Owner` reaches of its boxes, each written by `by`. fn reach(b: &mut Owner, by: u8) { match by % 4 { @@ -513,7 +527,10 @@ pub fn places(_: u8, data: &[u8], out: &mut Vec) { f(by); f(1); } - 24 => n = took(n, by), + 24 => { + n = took(n, by); + reaimed(&mut n, &mut held.n, by); + } _ => bump(leaked, by), } out.extend(n.to_le_bytes()); diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 906240d9f..4ad1127b0 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -936,6 +936,39 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ) } + /// `place` with each box's pointer or copy of a box it starts from replaced by the place + /// holding the box, which those aliases read in their place. + fn through_boxes(&self, mut place: Place<'tcx>) -> Place<'tcx> { + let tcx = self.tcx; + loop { + let (base, rest) = match (self.def_rvalue(place.local), place.projection.as_slice()) { + ( + Some(Rvalue::Cast(mir::CastKind::BoxDerefTransmute, op, _)), + [mir::ProjectionElem::Deref, rest @ ..], + ) if let Some(p) = op.place() + && let Some(n) = (0..=p.projection.len()).rev().find(|&n| { + Place::ty_from(p.local, &p.projection[..n], &self.mir.local_decls, tcx) + .ty + .is_box() + }) => + { + let boxed = Place { + local: p.local, + projection: tcx.mk_place_elems(&p.projection[..n]), + }; + (boxed, rest) + } + (Some(Rvalue::Use(Operand::Copy(p), _) | Rvalue::CopyForDeref(p)), rest) + if self.mir.local_decls[place.local].ty.is_box() => + { + (*p, rest) + } + _ => return place, + }; + place = base.project_deeper(rest, tcx); + } + } + /// Whether `local` is a parameter. fn is_arg(&self, local: Local) -> bool { (1..=self.mir.arg_count).contains(&local.as_usize()) @@ -986,7 +1019,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { false } (ty::Ref(..), Rvalue::Ref(_, _, place)) => { - self.stable(*place) + let place = self.through_boxes(*place); + self.stable(place) && place .projection .iter()