diff --git a/quest/m3/README.md b/quest/m3/README.md index d12d7f92e..552ba2609 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -34,7 +34,7 @@ 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 +- [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 - [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 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/ts/README.md b/ts/README.md index b0e0c131c..a5fda3cc2 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..48d67251c 100644 --- a/ts/fixtures/lang/expected/boxes.ts +++ b/ts/fixtures/lang/expected/boxes.ts @@ -4,7 +4,10 @@ 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$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"; @@ -430,4 +433,285 @@ 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; +} + +/** + * 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); + 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`, 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. + */ +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; + 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 }; + 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 _52: [rt.usize, rt.u8] | rt.Done = iter.next(); + if (_52 === rt.DONE) { + break; + } + const i: rt.usize = _52[0]; + const by: rt.u8 = _52[1]; + const _58: rt.u8 = rt.u8Rem(by, 26); + if (_58 === 0) { + 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, (value27) => n = value27), by); + } else if (_58 === 2) { + 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, (value23) => n = value23); + bump(rt.place(() => _67.v, (value24) => _67.v = value24), by); + } else if (_58 === 4) { + 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 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); + } + 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) { + s = s + "!?"; + } else if (_58 === 10) { + s = rt.stringInsertStr(s, 0, "<"); + } else if (_58 === 11) { + shout(rt.place(() => t, (value20) => t = value20), by); + } else if (_58 === 12) { + 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, (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, (value16) => nested = value16), by); + } else if (_58 === 16) { + nested = rt.u32WrappingAdd(nested, by as rt.u32); + } else if (_58 === 17) { + const _104: rt.u32 = by as rt.u32; + if (maybe === undefined) { + maybe = _104; + } + maybe = rt.u32Add(maybe as rt.u32, 1); + if (maybe !== undefined) { + bump(rt.place(() => maybe as rt.u32, (value15) => maybe = value15), by); + } + } else if (_58 === 18) { + reach(held, by); + } 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], (value14) => borrowed[borrowed2] = value14), by); + const _120: rt.Place | undefined = rt.sliceLastMut(v); + if (_120 !== undefined) { + _120.v = (_120.v ^ 16) >>> 0; + } + } else if (_58 === 20) { + const iter2: rt.Iter> = rt.iterSliceMut(v); + while (true) { + const _130: rt.Place | rt.Done = iter2.next(); + if (_130 === rt.DONE) { + break; + } + 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, (value9) => o = value9); + if (_140.v !== undefined) { + _140.v = rt.u32WrappingAdd(_140.v, by as rt.u32); + } + 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); + } + if (rt.usizeRem(i, 3) === 0) { + o = then$0ea5h05(o === undefined, (): rt.u32 => { + return by as rt.u32; + }); + } + if (res.ok) { + res = rt.Ok(rt.u32WrappingMul(res.value, by as rt.u32)); + } + 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)); + } + if (rt.usizeRem(i, 5) === 4) { + said = rt.Err(by); + } + } 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 _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, (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, (value6) => deep = value6); + 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 _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, (value8) => boxedOpt = value8); + if (_227 !== undefined) { + bump(_227, by); + } + if (boxedOpt !== undefined) { + 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(_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); + } + 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.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(copied$0bbq7yi(result_asDeref$04i8i5u(res)), 238)).reverse()), undefined, true); + const _298: rt.Result = said; + if (_298.ok) { + fmt_put(out, _298.value); + } else { + rt.byteVecPush(out, _298.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); + 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); + 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); + } +} + //# sourceMappingURL=boxes.ts.map diff --git a/ts/fixtures/lang/expected/core/bool.ts b/ts/fixtures/lang/expected/core/bool.ts index 05a78782b..923325e2d 100644 --- a/ts/fixtures/lang/expected/core/bool.ts +++ b/ts/fixtures/lang/expected/core/bool.ts @@ -216,6 +216,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 6cf5dfb77..d39042e77 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -501,6 +501,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; @@ -1570,6 +1577,18 @@ 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; + }); +} + export function and$06om98g(self: rt.u8 | undefined, optb: rt.u8 | undefined): rt.u8 | undefined { if (self === undefined) { return undefined; @@ -1829,6 +1848,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 7616af035..dc466cac4 100644 --- a/ts/fixtures/lang/expected/core/result.ts +++ b/ts/fixtures/lang/expected/core/result.ts @@ -487,6 +487,20 @@ 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); + } + return rt.Err(self.error); +} + export function asRef$1glrxiq(self: rt.Result): rt.Result { if (self.ok) { return rt.Ok(self.value); @@ -522,6 +536,27 @@ 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); + } + 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)); @@ -636,6 +671,18 @@ 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; + }); +} + export function unwrapOrDefault$1exw7nd(self: rt.Result): rt.u8 { if (self.ok) { return self.value; @@ -741,6 +788,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; @@ -797,6 +851,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/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 91eae0993..ad4b9f138 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -7,7 +7,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"; @@ -250,7 +250,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) partWritten(data87, out88); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["pointers::aimed", (_2188: rt.u8, data88: rt.ByteSlice, out89: rt.ByteVec): undefined => { aimed(data88, out89); - }] 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], ["arrays::flattened", arrays_flattened as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["args::args", args as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["returns::returns", returns 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], ["arrays::flattened", arrays_flattened as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["args::args", args as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["returns::returns", returns 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..dfae1e516 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,215 @@ 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 +} + +/// 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 { + 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`, 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) { + 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 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")); + 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 => { + 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))); + } + 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; + 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); + } + 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); + f(by); + f(1); + } + 24 => { + n = took(n, by); + reaimed(&mut n, &mut held.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(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("-")); + 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/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 2c6a262da..667375b25 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -264,6 +264,7 @@ fn cases() -> Vec<(&'static str, Case)> { }), ("pointers::aimed", |_, data, out| pointers::aimed(data, out)), ("ascii::parts", ascii::parts), + ("boxes::places", boxes::places), ("arrays::flattened", arrays::flattened), ("args::args", args::args), ("returns::returns", returns::returns), 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/fixtures/task/expected/drops/objects.ts b/ts/fixtures/task/expected/drops/objects.ts index e4a0269d0..b605107bd 100644 --- a/ts/fixtures/task/expected/drops/objects.ts +++ b/ts/fixtures/task/expected/drops/objects.ts @@ -207,8 +207,8 @@ export function anys(log: Log.Log, id: rt.u32): void { const _72: Held.Held = { tag: "Empty" }; rt.drop(slot); slot = new Any.of$drops_Held(_72); - const _160: Any.Any = slot; - const arg = _160 instanceof Any.of$drops_Held || _160 instanceof Any.ofPlace$drops_Held; + const _81: Any.Any = slot; + const arg = _81 instanceof Any.of$drops_Held || _81 instanceof Any.ofPlace$drops_Held; const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg, f)]; Log.note(log, rt.fmtFormat(["slot ", args6[0]])); lib_drop$Result_boxed_Box_model_Guard_boxed_Box_dyn_Any(held); @@ -231,8 +231,8 @@ export function anys(log: Log.Log, id: rt.u32): void { lib_drop$Option_sync_Arc_tuple2_model_Guard_model_Guard(typed); Log.note(log, "dropped"); b[Symbol.dispose](); - const _161: Any.Any = slot; - const part5 = ((_161 instanceof Any.of$drops_Held ? _161.v : _161 instanceof Any.ofPlace$drops_Held ? _161.v.v : undefined)) !== undefined; + const _149: Any.Any = slot; + const part5 = ((_149 instanceof Any.of$drops_Held ? _149.v : _149 instanceof Any.ofPlace$drops_Held ? _149.v.v : undefined)) !== undefined; const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(part5, f)]; Log.note(log, rt.fmtFormat(["slot ", args12[0]])); rt.drop(slot); diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index c0faaf2de..ffef575b6 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -1539,6 +1539,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 ce510440b..2e0cb27cf 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -660,6 +660,14 @@ 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); @@ -729,8 +737,14 @@ 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 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 { return done(target, true); @@ -739,8 +753,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 1af37b33c..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()) @@ -962,6 +995,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. @@ -973,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() diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 61fc5fe4e..9a32c203c 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -820,11 +820,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() @@ -865,8 +873,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, }, @@ -912,18 +921,62 @@ 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) @@ -1047,7 +1100,11 @@ 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)) diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index cdc1de073..69d59194a 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -1138,6 +1138,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