diff --git a/quest/m2/README.md b/quest/m2/README.md index df3547796..aed8acf65 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -33,7 +33,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values -- [Copy what a container stores](/quest/m2/ts-store-alias.md) - `push` and other stores of a `Copy` aggregate copy it instead of sharing it - [Share a held-back read across a call](/quest/m2/ts-shared-read.md) - `leading-ones` decode recovers what #83's copy fix cost - [Output tsc accepts for writes through Result and Poll compares](/quest/m2/ts-tsc-shapes.md) - two shapes whose output fails `tsc` type-check - [Translate moq-net's model to TypeScript](/quest/m2/ts-model.md) - the driver grows from moq-net's codec to its model, for moq to compare against WASM diff --git a/quest/m2/ts-store-alias.md b/quest/m2/ts-store-alias.md deleted file mode 100644 index 990f2807a..000000000 --- a/quest/m2/ts-store-alias.md +++ /dev/null @@ -1,23 +0,0 @@ -# [S] Copy what a container stores - -## Goal - -Storing a by-value `Copy` aggregate in a container copies it, as Rust does: -`v.push(pair); v.push(pair); v[0].0 ^= 1` leaves `v[1]` and `pair` unchanged in -translated TypeScript. Differential tests against native Rust cover `Vec::push`, -`insert`, `VecDeque::push_back`, map inserts, and `Box::new`. - -## Plan - -Found by [#86](https://github.com/kixelated/rust2/pull/86) on 2026-10-26, and it -still reproduces after [#83](https://github.com/kixelated/rust2/pull/83)'s typed -copies: 1280 differences against native Rust in its probe. It is a silent miscompile. - -- The cause is the share analysis in `ts/src/lower/mir/mod.rs`: it sees a later change - made in place through a local, not through a container element, so it shares the - argument instead of copying it. -- Fix it there, once for every std call that stores a by-value argument, not in each - mapping. -- Measure the codec bench before and after. - -Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index 67d8eee9f..1041e387e 100644 --- a/ts/README.md +++ b/ts/README.md @@ -338,8 +338,9 @@ built natively for wasm32 and run beside its translation on the same inputs by Bun bundles a caller of `Decoder.u8` and `Decoder.new` through `import * as Decoder`, which must keep only those and what they call. - `lang` covers every integer width's arithmetic and casts, `char`s next to each - encoding's edges and the surrogates, control flow, patterns, `Copy` aggregates, - formatting, methods on generic types, iterators, with closures that log what each + encoding's edges and the surrogates, control flow, patterns, `Copy` aggregates, those + a container stores included, formatting, methods on generic types, iterators, with + closures that log what each adaptor reads, and std's collections, over keys whose own `Hash`, `Eq`, and `Ord` disagree with JS's, and `vec![x; n]` of types whose `Clone` counts its clones. Its differential test runs through `caller.ts`, a hand-written caller that also prints a `printable` error nothing translated prints, diff --git a/ts/fixtures/codec/expected/coding/decode.Decoder.ts b/ts/fixtures/codec/expected/coding/decode.Decoder.ts index 5e25955be..0d99db5f1 100644 --- a/ts/fixtures/codec/expected/coding/decode.Decoder.ts +++ b/ts/fixtures/codec/expected/coding/decode.Decoder.ts @@ -31,7 +31,7 @@ export interface Decoder { /** Read `buf`, with varints in the given form. */ function new_(buf: Uint8Array, form: Form.Form): Decoder { - return { buf, form, len: buf.length, need: 0, control: undefined, uncounted: 0 }; + return { buf, form: copy$Form(form), len: buf.length, need: 0, control: undefined, uncounted: 0 }; } /** diff --git a/ts/fixtures/codec/expected/coding/encode.Encoder.ts b/ts/fixtures/codec/expected/coding/encode.Encoder.ts index 553371c0f..8e431f7cc 100644 --- a/ts/fixtures/codec/expected/coding/encode.Encoder.ts +++ b/ts/fixtures/codec/expected/coding/encode.Encoder.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; +import { copy$Form } from "../lib.ts"; import * as EncodeError from "../coding/encode.EncodeError.ts"; import type * as Prefix from "../coding/encode.Prefix.ts"; import type * as PrefixKind from "../coding/encode.PrefixKind.ts"; @@ -22,7 +23,7 @@ export interface Encoder { /** Append to `buf`, with varints in the given form. */ function new_(buf: rt.ByteVec, form: Form.Form): Encoder { - return { buf, form, control: undefined }; + return { buf, form: copy$Form(form), control: undefined }; } /** Write raw bytes. */ diff --git a/ts/fixtures/codec/expected/coding/version.Versions.ts b/ts/fixtures/codec/expected/coding/version.Versions.ts index 518b5aa6e..0cc38ef26 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -16,7 +16,8 @@ export function decodeSlice$Decode_Form(buf: Uint8Array, version: Form.Form): rt const _6: rt.Result = decode$Decode_Form(r, version); if (_6.ok) { const val: Versions = _6.value; - const _0: rt.Result<[Versions, rt.usize], DecodeError.DecodeError> = rt.Ok([val, rt.usizeSub(buf.length, Decoder.remaining(r))]); + const value: Versions = val; + const _0: rt.Result<[Versions, rt.usize], DecodeError.DecodeError> = rt.Ok([value, rt.usizeSub(buf.length, Decoder.remaining(r))]); return _0; } return _6; @@ -41,7 +42,7 @@ export function decode$Decode_Form(r: Decoder.Decoder, version: Form.Form): rt.R } const _15: rt.Result = Version.decode$Decode_Form(r, version); if (_15.ok) { - vs.push(_15.value); + vs.push(copy$Version(_15.value)); } else { return _15; } diff --git a/ts/fixtures/lang/expected/collections.Holder.ts b/ts/fixtures/lang/expected/collections.Holder.ts new file mode 100644 index 000000000..3e2ef4752 --- /dev/null +++ b/ts/fixtures/lang/expected/collections.Holder.ts @@ -0,0 +1,10 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A struct that is not `Copy` holding a `Copy` aggregate by value. */ +export interface Holder { + pair: [rt.u8, rt.u8]; +} + +//# sourceMappingURL=collections.Holder.ts.map diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index d6c9624aa..8ad49a973 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -1,11 +1,12 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Bumped, copy$Clash, copy$Rank, copy$Tally, copy$u8_Tally, copy$u8_u16, copy$u8_u8 } from "./lib.ts"; +import { copy$Bumped, copy$Clash, copy$Pair, copy$Rank, copy$Tally, copy$u8_Tally, copy$u8_str, copy$u8_u16, copy$u8_u16s, copy$u8_u8, copy$u8_u8s } from "./lib.ts"; import * as Clash from "./collections.Clash.ts"; import * as Cloned from "./collections.Cloned.ts"; import * as Dir from "./collections.Dir.ts"; import * as Fussy from "./collections.Fussy.ts"; +import type * as Holder from "./collections.Holder.ts"; import * as Nibble from "./collections.Nibble.ts"; import * as Pair from "./collections.Pair.ts"; import * as Rank from "./collections.Rank.ts"; @@ -162,14 +163,14 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const b3: rt.u8 = _167[1]; rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(map3, { _0: a }, b3), 204)); const pair: Pair.Pair = { a: rt.u8Rem(a, 4), b: rt.u16Rem(b3 as rt.u16, 3) }; - const t: Tally.Tally = rt.entryOrInsertWith(rt.entry(pairs, pair), Tally.default$Default); + const t: Tally.Tally = rt.entryOrInsertWith(rt.entry(pairs, copy$Pair(pair)), Tally.default$Default); t.n = rt.u16Add(t.n, 1); const r: Rank.Rank = rank(a, b3); const _192: Tally.Tally | undefined = rt.hashGet(ranks, r); if (_192 !== undefined) { _192.n = rt.u16Add(_192.n, 1); } else { - rt.hashInsert(ranks, r, { n: i3 & 0xffff }); + rt.hashInsert(ranks, copy$Rank(r), { n: i3 & 0xffff }); } const _203: rt.u8 = rt.u8Rem(a, 3); const _207: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); @@ -179,7 +180,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const t2: [rt.u8, string] = [_203, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_207]]; rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashRemove(tuples, t2), 187)); if (rt.u8Rem(a, 2) === 0) { - rt.hashInsert(tuples, t2, a); + rt.hashInsert(tuples, copy$u8_str(t2), a); } } const _225: rt.Iter<[rt.u8, rt.u8]> = rt.iterMap(rt.hashIter(map3), (_214: [Nibble.Nibble, rt.u8]): [rt.u8, rt.u8] => { @@ -198,7 +199,8 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } const key: Pair.Pair = { a: 9, b: 9 }; const local: Tally.Tally = { n: 7 }; - rt.hashInsert(pairs, key, copy$Tally(local)); + const _241: Tally.Tally = copy$Tally(local); + rt.hashInsert(pairs, copy$Pair(key), _241); local.n = 8; const before: Tally.Tally = copy$Tally(rt.hashIndex(pairs, key)); const _246: Tally.Tally | undefined = rt.hashGet(pairs, key); @@ -232,7 +234,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _292: [rt.u8, rt.u8] = [_293, data[i4]]; const a2: rt.u8 = _293; const b4: rt.u8 = _292[1]; - const _305: Rank.Rank = rank(b4, a2); + const _305: Rank.Rank = copy$Rank(rank(b4, a2)); const t4: Tally.Tally = rt.entryOrInsertWith(rt.entryAndModify(rt.entry(ranks, _305), (t9: Tally.Tally): void => { t9.n = t9.n ^ 3; }), (): Tally.Tally => { @@ -240,7 +242,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { }); t4.n = rt.u16WrappingAdd(t4.n, t4.n); rt.idx(data, i4); - const _313: Rank.Rank = rank(data[i4], 0); + const _313: Rank.Rank = copy$Rank(rank(data[i4], 0)); const e: rt.Entry = rt.entry(ranks, _313); rt.byteVecPush(out, rankByte(rt.entryKey(e))); rt.byteVecPush(out, rt.entryOrInsertWith(e, (k9: Rank.Rank): Tally.Tally => { @@ -418,7 +420,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return t6.n & 0xff; })); } else { - rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(clashes, k6, { n: i5 & 0xffff }), 204, (t5: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(clashes, copy$Clash(k6), { n: i5 & 0xffff }), 204, (t5: Tally.Tally): rt.u8 => { return t5.n & 0xff; })); } @@ -450,7 +452,7 @@ export function countedHasher(h: rt.Hasher, counted: Tally.Tally): rt.Hasher { /** Inserts a key, and gives back the map. */ export function stamp(map: rt.HashMap): rt.HashMap { - rt.hashInsert(map, rt.hashLen(map) & 0xff, Tally.default$Default()); + rt.hashInsert(map, rt.hashLen(map) & 0xff, copy$Tally(Tally.default$Default())); return map; } @@ -724,7 +726,7 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void const _170: [rt.u8, rt.u8] = [_171, data[i2]]; const a: rt.u8 = _171; const b: rt.u8 = _170[1]; - const _182: Rank.Rank = rank(a, b); + const _182: Rank.Rank = copy$Rank(rank(a, b)); const t: Tally.Tally = rt.entryOrInsertWith(rt.entry(ranks, _182), Tally.default$Default); t.n = rt.u16WrappingAdd(t.n, b as rt.u16); const _188: [rt.u8, rt.u8] = [rt.u8Rem(a, 4), rt.u8Rem(b, 4)]; @@ -745,7 +747,7 @@ export function btreeMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void } const b2: rt.u8 = _205; const r: Rank.Rank = rank(b2, rt.u8Div(b2, 3)); - const _212: rt.Entry = rt.entry(ranks, r); + const _212: rt.Entry = rt.entry(ranks, copy$Rank(r)); if (!rt.entryOccupied(_212)) { const e: rt.Entry = _212; rt.byteVecPush(out, rankByte(rt.entryKey(e))); @@ -1031,7 +1033,7 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { name = "?"; } rt.byteVecExtendFromSlice(out, rt.byteVecView(rt.byteVecFrom(Uint8Array.of(a, b, 66)))); - const pairs: [rt.u8, rt.u16][] = [[a, b as rt.u16] as [rt.u8, rt.u16]].map(copy$u8_u16); + const pairs: [rt.u8, rt.u16][] = copy$u8_u16s([[a, b as rt.u16] as [rt.u8, rt.u16]]).map(copy$u8_u16); pairs.push([b, a as rt.u16] as [rt.u8, rt.u16]); const at = rt.idx(pairs, 0); pairs[at][0] = pairs[at][0] ^ 255; @@ -1052,7 +1054,7 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rt.vecFromElem(rt.u16Mul(a as rt.u16, 257), n, undefined)), (w: rt.u16): rt.u8 => { return rt.u16Shr(w, 4) & 0xff; })); - const tuples: [rt.u8, rt.u8][] = rt.vecFromElem(copy$u8_u8([a, b] as [rt.u8, rt.u8]), n, copy$u8_u8); + const tuples: [rt.u8, rt.u8][] = rt.vecFromElem([a, b] as [rt.u8, rt.u8], n, copy$u8_u8); if (n > 0) { const at3 = rt.idx(tuples, 0); tuples[at3][0] = 238; @@ -1069,12 +1071,12 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.iterAll(_113, (c2: Cloned.Cloned): boolean => { return rt.stringLen(c2.name) === data.length; }) ? 1 : 0); - rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rt.vecFromElem(copy$Bumped({ _0: b }), n, Bumped.clone$Clone)), (o: Bumped.Bumped): rt.u8 => { + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rt.vecFromElem({ _0: b }, n, Bumped.clone$Clone)), (o: Bumped.Bumped): rt.u8 => { return o._0; })); const pair: [rt.u8, rt.u8] = [a, b]; const held: Bumped.Bumped = { _0: a }; - const listed: [rt.u8, rt.u8][] = [pair, pair].map(copy$u8_u8); + const listed: [rt.u8, rt.u8][] = copy$u8_u8s([pair, pair]).map(copy$u8_u8); const at4 = rt.idx(listed, 0); listed[at4][0] = listed[at4][0] ^ 255; const repeated: [rt.u8, rt.u8][] = rt.vecFromElem(copy$u8_u8(pair), n, copy$u8_u8); @@ -1101,4 +1103,133 @@ export function vecs(data: Uint8Array, out: rt.ByteVec): void { })); } +/** Stores `p` by value in `v`. */ +export function keep(v: [rt.u8, rt.u8][], p: [rt.u8, rt.u8]): void { + v.push(copy$u8_u8(p)); +} + +/** Gives back what it was given. */ +export function same(p: [rt.u8, rt.u8]): [rt.u8, rt.u8] { + return p; +} + +/** Changes what it was given in place, which is its own. */ +export function bump(h: Holder.Holder): rt.u8 { + h.pair[0] = h.pair[0] ^ 1; + return h.pair[0]; +} + +/** Holds `pair`, for its caller to change. */ +export function hold(pair: [rt.u8, rt.u8]): Holder.Holder { + return { pair: copy$u8_u8(pair) }; +} + +/** + * A `Copy` aggregate a std call stores by value is the container's own copy: changing + * one stored element leaves the value it came from and the other elements as they were. + */ +export function stores(data: Uint8Array, out: rt.ByteVec): void { + const a: rt.u8 = rt.optionUnwrapOr(rt.sliceFirst(data), 0); + const b: rt.u8 = rt.optionUnwrapOr(rt.sliceGet(data, 1), 0); + const pair: [rt.u8, rt.u8] = same([a, b] as [rt.u8, rt.u8]); + const changed: [rt.u8, rt.u8] = [b, a]; + changed[0] = changed[0] ^ 16; + const v: [rt.u8, rt.u8][] = []; + v.push(copy$u8_u8(pair)); + v.push(copy$u8_u8(pair)); + const at = rt.idx(v, 0); + v[at][0] = v[at][0] ^ 1; + v.push(copy$u8_u8(changed)); + changed[1] = changed[1] ^ 32; + const at2 = rt.idx(v, 2); + v[at2][0] = v[at2][0] ^ 4; + keep(v, pair); + const at3 = rt.idx(v, 3); + v[at3][1] = v[at3][1] ^ 8; + const _30: [rt.u8, rt.u8] = copy$u8_u8(same(pair)); + v.push(_30); + const at4 = rt.idx(v, 4); + v[at4][0] = v[at4][0] ^ 64; + const _36: [rt.u8, rt.u8] = copy$u8_u8(changed); + rt.iterExtend(v, rt.iterSlice([copy$u8_u8(pair), _36])); + const at5 = rt.idx(v, 5); + v[at5][1] = v[at5][1] ^ 128; + const at6 = rt.idx(v, 6); + v[at6][0] = v[at6][0] ^ 128; + const at7 = rt.idx(v, 0); + const old2 = v[at7]; + v[at7] = copy$u8_u8(pair); + const old: [rt.u8, rt.u8] = old2; + const at8 = rt.idx(v, 0); + v[at8][1] = v[at8][1] ^ 16; + rt.iterExtendBytes(out, rt.iterFlatMap(rt.iterSlice(v), (p: [rt.u8, rt.u8]): Uint8Array => { + return Uint8Array.of(p[0], p[1]); + }, (value: Uint8Array) => rt.iterSlice(value))); + rt.byteVecExtendFromSlice(out, Uint8Array.of(changed[0], changed[1], old[0], old[1])); + const tally: Tally.Tally = { n: a as rt.u16 }; + const q: rt.VecDeque = rt.dequeNew() as rt.VecDeque; + rt.dequePushBack(q, copy$Tally(tally)); + rt.dequePushFront(q, copy$Tally(tally)); + rt.dequeInsert(q, 1, copy$Tally(tally)); + const _68: Tally.Tally | undefined = rt.dequeEnd(q); + if (_68 !== undefined) { + _68.n = _68.n ^ 1; + } + const _72: Tally.Tally | undefined = rt.dequeEnd(q, true); + if (_72 !== undefined) { + _72.n = _72.n ^ 2; + } + rt.iterExtendBytes(out, rt.iterMap(rt.dequeIter(q), (t: Tally.Tally): rt.u8 => { + return t.n & 0xff; + })); + rt.byteVecPush(out, tally.n & 0xff); + const hash: rt.HashMap = rt.hashNew() as rt.HashMap; + rt.hashInsert(hash, 0, copy$u8_u8(pair)); + rt.hashInsert(hash, 1, copy$u8_u8(pair)); + const _88: rt.Place<[rt.u8, rt.u8]> | undefined = rt.hashGetMut(hash, 0); + if (_88 !== undefined) { + _88.v[0] = _88.v[0] ^ 1; + } + const place = rt.entryOrInsertMut(rt.entry(hash, 2), copy$u8_u8(pair)); + place.v[1] = place.v[1] ^ 2; + rt.iterExtendBytes(out, rt.iterFlatMap(new rt.Range(0, 3), (k: rt.u8): Uint8Array => { + return rt.optionMapOr(rt.hashGet(hash, k), rt.bytes(2).fill(255), (p2: [rt.u8, rt.u8]): Uint8Array => { + return Uint8Array.of(p2[0], p2[1]); + }); + }, (value: Uint8Array) => rt.iterSlice(value))); + const tree: rt.BTreeMap = rt.btreeNew(rt.cmp) as rt.BTreeMap; + rt.btreeInsert(tree, 0, copy$u8_u8(pair)); + rt.btreeInsert(tree, 1, copy$u8_u8(pair)); + const _106: rt.Place<[rt.u8, rt.u8]> | undefined = rt.btreeGetMut(tree, 1); + if (_106 !== undefined) { + _106.v[1] = _106.v[1] ^ 1; + } + rt.iterExtendBytes(out, rt.iterFlatMap(rt.btreeValues(tree), (p3: [rt.u8, rt.u8]): Uint8Array => { + return Uint8Array.of(p3[0], p3[1]); + }, (value: Uint8Array) => rt.iterSlice(value))); + const boxed: [rt.u8, rt.u8] = copy$u8_u8(pair); + boxed[0] = boxed[0] ^ 1; + const holders: Holder.Holder[] = [{ pair: copy$u8_u8(pair) }]; + holders.push({ pair: copy$u8_u8(pair) }); + const at9 = rt.idx(holders, 1); + holders[at9].pair[1] = holders[at9].pair[1] ^ 2; + const _128: rt.u8 = boxed[0]; + const _129: rt.u8 = boxed[1]; + const at10 = rt.idx(holders, 0); + const _130: rt.u8 = holders[at10].pair[1]; + const at11 = rt.idx(holders, 1); + rt.byteVecExtendFromSlice(out, Uint8Array.of(_128, _129, _130, holders[at11].pair[1])); + rt.byteVecPush(out, bump({ pair: copy$u8_u8(pair) })); + const held: Holder.Holder = hold(pair); + held.pair[1] = held.pair[1] ^ 4; + const _142: Holder.Holder = hold(pair); + holders.push(_142); + const at12 = rt.idx(holders, 2); + holders[at12].pair[0] = holders[at12].pair[0] ^ 8; + const _149: rt.u8 = held.pair[1]; + const at13 = rt.idx(holders, 2); + rt.byteVecExtendFromSlice(out, Uint8Array.of(_149, holders[at13].pair[0])); + rt.byteVecExtendFromSlice(out, Uint8Array.of(pair[0], pair[1])); +} + //# sourceMappingURL=collections.ts.map diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 5955d67a1..a70e49ea8 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Pair } from "./lib.ts"; +import { copy$Pair$2 } from "./lib.ts"; import * as Bare from "./fmt.Bare.ts"; import * as Braced from "./fmt.Braced.ts"; import * as Fails from "./fmt.Fails.ts"; @@ -212,7 +212,7 @@ export function nested(data: Uint8Array): Nested.Nested { _22 = { tag: "Rect", corner: { x: 0, y: 0 }, width: at(3) as rt.u16, height: 9 } as Shape.Shape; } const _35: rt.ByteVec = rt.sliceToByteVec(rt.sliceRange(data, 0, rt.min(data.length, 4))); - const _40: Pair.Pair[] = [{ _0: at(4), _1: -1 }, { _0: 2, _1: { hi: -0x80000000, lo: 0 } as rt.i64 }].map(copy$Pair); + const _40: Pair.Pair[] = [{ _0: at(4), _1: -1 }, { _0: 2, _1: { hi: -0x80000000, lo: 0 } as rt.i64 }].map(copy$Pair$2); if (!(rt.u8Rem(at(5), 2) === 0)) { _49 = undefined; } else { @@ -309,8 +309,8 @@ export function written(data: Uint8Array, out: rt.ByteVec): void { const arg3 = { id: 0, list: [] }; const args6: rt.Fmt[] = [_66, (f: rt.Formatter) => Manual.fmt$Debug(arg3, f)]; put(out, rt.fmtFormat([args6[0], " ", rt.fmtSpec({ alternate: true }, args6[0]), " ", args6[1]])); - [{ _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair) }, { _0: [] }] as [Seq.Seq, Seq.Seq]; - const arg4 = { _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair) }; + [{ _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair$2) }, { _0: [] }] as [Seq.Seq, Seq.Seq]; + const arg4 = { _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair$2) }; const _92: rt.Fmt = (f: rt.Formatter) => Seq.fmt$Debug(arg4, f); const arg5 = { _0: [] }; const args8: rt.Fmt[] = [_92, (f: rt.Formatter) => Seq.fmt$Debug(arg5, f)]; diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index a37d3b059..4c480c11d 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Wrap_Point, copy$Wrap_i16, copy$Wrap_u8 } from "./lib.ts"; +import { copy$Either_u8_Points, copy$Wrap_Point, copy$Wrap_i16, copy$Wrap_u8 } from "./lib.ts"; import { put } from "./fmt.ts"; import type * as Pair from "./fmt.Pair.ts"; import * as Either from "./generics.Either.ts"; @@ -45,7 +45,7 @@ export function methods(data: Uint8Array, out: rt.ByteVec): void { const arg2 = Wrap.eq$PartialEq_Pair(mapped, _119); const args6: rt.Fmt[] = [_126, (f: rt.Formatter) => rt.fmtBool(arg2, f)]; put(out, rt.fmtFormat([args6[0], " ", args6[1]])); - const iter: rt.Iter> = rt.iterSlice([{ tag: "Left", _0: at(7) } as Either.Either, { tag: "Right", value: Point.new(1, -1) } as Either.Either, { tag: "Neither" } as Either.Either]); + const iter: rt.Iter> = rt.iterSlice(copy$Either_u8_Points([{ tag: "Left", _0: at(7) } as Either.Either, { tag: "Right", value: Point.new(1, -1) } as Either.Either, { tag: "Neither" } as Either.Either])); while (true) { const _140: Either.Either | rt.Done = iter.next(); if (_140 === rt.DONE) { diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 3013a5c5f..fe4115a13 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 { chars } from "./chars.ts"; -import { hashMaps, sets, btreeMaps, deques, vecs } from "./collections.ts"; +import { hashMaps, sets, btreeMaps, deques, vecs, stores } from "./collections.ts"; import { ints, strings, derived, written, panics } from "./fmt.ts"; import { methods } from "./generics.ts"; import { u8Op, u16Op, u32Op, u64Op, u128Op, usizeOp, i8Op, i16Op, i32Op, i64Op, i128Op, isizeOp, i8Neg, i16Neg, i32Neg, i64Neg, i128Neg, isizeNeg, cast, convert } from "./ints.ts"; @@ -20,7 +20,7 @@ export function run(input: Uint8Array): rt.ByteVec { const _10: [rt.u8, rt.u8] = [input[0], input[1]]; const op: rt.u8 = _10[0]; const kind: rt.u8 = _10[1]; - const _14: rt.u8 = rt.u8Rem(op, 43); + const _14: rt.u8 = rt.u8Rem(op, 44); if (_14 === 0) { u8Op(kind, input.subarray(2, input.length - 0), out); } else if (_14 === 1) { @@ -123,8 +123,10 @@ export function run(input: Uint8Array): rt.ByteVec { chars(kind, input.subarray(2, input.length - 0), out); } else if (_14 === 41) { strs(kind, input.subarray(2, input.length - 0), out); - } else { + } else if (_14 === 42) { vecs(input.subarray(2, input.length - 0), out); + } else { + stores(input.subarray(2, input.length - 0), out); } return out; } diff --git a/ts/fixtures/lang/expected/keys.ts b/ts/fixtures/lang/expected/keys.ts index 22af19ef7..9b901b0d4 100644 --- a/ts/fixtures/lang/expected/keys.ts +++ b/ts/fixtures/lang/expected/keys.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Hop, copy$Horizon } from "./lib.ts"; +import { copy$Hop, copy$Horizon, copy$u8_Horizon } from "./lib.ts"; import * as Hop from "./keys.Hop.ts"; import * as Horizon from "./keys.Horizon.ts"; import * as Liar from "./keys.Liar.ts"; @@ -376,10 +376,10 @@ export function options(data: Uint8Array, out: rt.ByteVec): void { const _261: rt.u8 = rt.u8Rem(c, 3); const _264: boolean = rt.u8Rem(d, 2) === 0; const key: [rt.u8, Horizon.Horizon] = [_261, { exclude: a, local: _264 }]; - const _269: rt.u8 | undefined = rt.hashInsert(hashed, key, i & 0xff); + const _269: rt.u8 | undefined = rt.hashInsert(hashed, copy$u8_Horizon(key), i & 0xff); unwind = 133; rt.byteVecPush(out, rt.optionUnwrapOr(_269, 204)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(sorted, key, i & 0xff), 204)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(sorted, copy$u8_Horizon(key), i & 0xff), 204)); const _281: [Way.Way | undefined, boolean] = [way(c), c < 128]; const _284: rt.u8 = i & 0xff; rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(ways, _281, _284), 204)); diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index 626711d8d..bc5f8c02c 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -2,16 +2,17 @@ import * as rt from "./rt.ts"; import type * as Clash from "./collections.Clash.ts"; +import type * as Pair from "./collections.Pair.ts"; import type * as Rank from "./collections.Rank.ts"; import type * as Tally from "./collections.Tally.ts"; -import type * as Pair from "./fmt.Pair.ts"; +import type * as fmt_Pair from "./fmt.Pair.ts"; +import type * as Either from "./generics.Either.ts"; import * as Wrap from "./generics.Wrap.ts"; import type * as Bumped from "./iters.Bumped.ts"; import type * as Hop from "./keys.Hop.ts"; import type * as Horizon from "./keys.Horizon.ts"; import type * as Held from "./shapes.Held.ts"; import type * as Lens from "./shapes.Lens.ts"; -import type * as Meters from "./shapes.Meters.ts"; import type * as Point from "./shapes.Point.ts"; import type * as Shape from "./shapes.Shape.ts"; @@ -31,6 +32,20 @@ export function copy$ControlFlow_unit_u8s(v: rt.Result): return v.ok ? rt.Ok(copy$u8s(v.value)) : rt.Err(v.error); } +export function copy$Either_u8_Point(v: Either.Either): Either.Either { + if (v.tag === "Left") { + return { tag: "Left", _0: v._0 }; + } + if (v.tag === "Right") { + return { tag: "Right", value: copy$Point(v.value) }; + } + return v; +} + +export function copy$Either_u8_Points(v: Either.Either[]): Either.Either[] { + return v.map(copy$Either_u8_Point); +} + export function copy$Held(v: Held.Held): Held.Held { return { at: copy$Point(v.at) }; } @@ -47,10 +62,6 @@ export function copy$Lens(v: Lens.Lens): Lens.Lens { return { slot: v.slot, n: v.n }; } -export function copy$Meters(v: Meters.Meters): Meters.Meters { - return { _0: v._0 }; -} - export function copy$Mutex_u8_u8(v: [rt.Mutex, rt.u8]): [rt.Mutex, rt.u8] { return [v[0], v[1]]; } @@ -72,6 +83,10 @@ export function copy$Option_Wrap_i16(v: Wrap.Wrap | undefined): Wrap.Wra } export function copy$Pair(v: Pair.Pair): Pair.Pair { + return { a: v.a, b: v.b }; +} + +export function copy$Pair$2(v: fmt_Pair.Pair): fmt_Pair.Pair { return { _0: v._0, _1: v._1 }; } @@ -131,18 +146,34 @@ export function copy$Wrap_u8(v: Wrap.Wrap): Wrap.Wrap { return new Wrap.Wrap({ value: v.value, count: v.count }); } +export function copy$u8_Horizon(v: [rt.u8, Horizon.Horizon]): [rt.u8, Horizon.Horizon] { + return [v[0], copy$Horizon(v[1])]; +} + export function copy$u8_Tally(v: [rt.u8, Tally.Tally]): [rt.u8, Tally.Tally] { return [v[0], copy$Tally(v[1])]; } +export function copy$u8_str(v: [rt.u8, string]): [rt.u8, string] { + return [v[0], v[1]]; +} + export function copy$u8_u16(v: [rt.u8, rt.u16]): [rt.u8, rt.u16] { return [v[0], v[1]]; } +export function copy$u8_u16s(v: [rt.u8, rt.u16][]): [rt.u8, rt.u16][] { + return v.map(copy$u8_u16); +} + export function copy$u8_u8(v: [rt.u8, rt.u8]): [rt.u8, rt.u8] { return [v[0], v[1]]; } +export function copy$u8_u8s(v: [rt.u8, rt.u8][]): [rt.u8, rt.u8][] { + return v.map(copy$u8_u8); +} + export function copy$u8s(v: Uint8Array): Uint8Array { return v.slice(); } diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index bb1f37171..6514cebdf 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$ControlFlow_Arc_u8_u8s, copy$ControlFlow_unit_u8s, copy$Held, copy$Lens, copy$Meters, copy$Mutex_u8_u8, copy$Mutex_u8s, copy$Option_Mutex_u8_u8, copy$Point, copy$Point_u8, copy$Points, copy$Poll_u8s, copy$Result_Mutex_u8_u8_u8, copy$Shape, copy$u8_u8, copy$u8s } from "./lib.ts"; +import { copy$ControlFlow_Arc_u8_u8s, copy$ControlFlow_unit_u8s, copy$Held, copy$Lens, copy$Mutex_u8_u8, copy$Mutex_u8s, copy$Option_Mutex_u8_u8, copy$Point, copy$Point_u8, copy$Points, copy$Poll_u8s, copy$Result_Mutex_u8_u8_u8, copy$Shape, copy$u8_u8, copy$u8s } from "./lib.ts"; import * as Pair from "./fmt.Pair.ts"; import type * as Dir from "./shapes.Dir.ts"; import type * as Held from "./shapes.Held.ts"; @@ -105,7 +105,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { grid[1].x = 9; const row: Point.Point[] = copy$Points(grid); const _20: Point.Point = copy$Point(q); - grid[2] = copy$Point(_20); + grid[2] = _20; const _25: rt.i32 = p.x; const _26: rt.i32 = p.y; const _27: rt.i32 = q.x; @@ -131,9 +131,9 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { const swapped = a; a = b; b = swapped; - const _66: Point.Point = Point.new(5, 6); + const _66: Point.Point = copy$Point(Point.new(5, 6)); const old2 = a; - a = copy$Point(_66); + a = _66; const old: Point.Point = old2; const _71: rt.u8 = a.x & 0xff; const _73: rt.u8 = b.x & 0xff; @@ -166,7 +166,7 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { const marked: boolean = mark(out, 1) === 0; mark(out, 2); rt.byteVecPush(out, marked ? 1 : 0); - let opt: Meters.Meters | undefined = copy$Meters({ _0: 9 }); + let opt: Meters.Meters | undefined = { _0: 9 }; const taken2 = opt; opt = undefined; const taken: Meters.Meters | undefined = taken2; @@ -191,7 +191,8 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { shape_.width = 6; } } - const iter2: rt.Iter = rt.iterSlice([before, copy$Shape(shape_)]); + const _202: Shape.Shape = copy$Shape(shape_); + const iter2: rt.Iter = rt.iterSlice([copy$Shape(before), _202]); while (true) { const _204: Shape.Shape | rt.Done = iter2.next(); if (_204 === rt.DONE) { @@ -215,14 +216,15 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { if (rt.usizeRem(data.length, 2) === 0) { poll = rt.Pending; } else { - poll = copy$u8s(Uint8Array.of(data.length & 0xff)); + poll = Uint8Array.of(data.length & 0xff); } const polled_: rt.Poll = copy$Poll_u8s(poll); if (poll !== rt.Pending) { const bytes: Uint8Array = poll; bytes[0] = 9; } - const iter3: rt.Iter> = rt.iterSlice([polled_, copy$Poll_u8s(poll)]); + const _239: rt.Poll = copy$Poll_u8s(poll); + const iter3: rt.Iter> = rt.iterSlice([copy$Poll_u8s(polled_), _239]); while (true) { const _241: rt.Poll | rt.Done = iter3.next(); if (_241 === rt.DONE) { @@ -281,8 +283,10 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { copy3[1] = _45; } unwind = 0; - const iter: rt.Iter<[rt.Mutex, rt.u8] | undefined> = rt.iterSlice([held, copy$Option_Mutex_u8_u8(copy3)]); + const _49: [rt.Mutex, rt.u8] | undefined = copy$Option_Mutex_u8_u8(copy3); + const iter: rt.Iter<[rt.Mutex, rt.u8] | undefined> = rt.iterSlice([copy$Option_Mutex_u8_u8(held), _49]); while (true) { + unwind = 0; const _51: [rt.Mutex, rt.u8] | undefined | rt.Done = iter.next(); if (_51 === rt.DONE) { break; @@ -303,7 +307,7 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { copy4.value[1] = _69; } unwind = 0; - const iter2: rt.Iter, rt.u8], rt.u8>> = rt.iterSlice([res, copy$Result_Mutex_u8_u8_u8(copy4)]); + const iter2: rt.Iter, rt.u8], rt.u8>> = rt.iterSlice([copy$Result_Mutex_u8_u8_u8(res), copy$Result_Mutex_u8_u8_u8(copy4)]); while (true) { const _76: rt.Result<[rt.Mutex, rt.u8], rt.u8> | rt.Done = iter2.next(); if (_76 === rt.DONE) { @@ -335,7 +339,7 @@ export function shares(data: Uint8Array, out: rt.ByteVec): void { bump(_104.slot); } const lenses: Lens.Lens[] = []; - lenses.push(lens); + lenses.push(copy$Lens(lens)); const _114: rt.Iter = rt.iterSlice([lens]); rt.iterExtend(lenses, rt.iterMap(_114, copy$Lens)); const iter4: rt.Iter = rt.iterMap(rt.iterSlice(lenses), copy$Lens); @@ -1621,7 +1625,8 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { const _83: rt.u8 = rt.u8WrappingAdd(copied.value[0], 1); copied.value[0] = _83; } - const iter2: rt.Iter> = rt.iterSlice([original, copy$ControlFlow_unit_u8s(copied)]); + const _91: rt.Result = copy$ControlFlow_unit_u8s(copied); + const iter2: rt.Iter> = rt.iterSlice([copy$ControlFlow_unit_u8s(original), _91]); while (true) { const _93: rt.Result | rt.Done = iter2.next(); if (_93 === rt.DONE) { diff --git a/ts/fixtures/lang/src/collections.rs b/ts/fixtures/lang/src/collections.rs index e96042b47..f083b1e58 100644 --- a/ts/fixtures/lang/src/collections.rs +++ b/ts/fixtures/lang/src/collections.rs @@ -740,3 +740,107 @@ pub fn vecs(data: &[u8], out: &mut Vec) { out.extend(repeated.iter().chain(&again).map(|t| t.1)); out.extend(bumps.iter().chain(&kept).map(|o| o.0)); } + +/// A struct that is not `Copy` holding a `Copy` aggregate by value. +struct Holder { + pair: (u8, u8), +} + +/// Stores `p` by value in `v`. +fn keep(v: &mut Vec<(u8, u8)>, p: (u8, u8)) { + v.push(p); +} + +/// Gives back what it was given. +fn same(p: (u8, u8)) -> (u8, u8) { + p +} + +/// Changes what it was given in place, which is its own. +fn bump(mut h: Holder) -> u8 { + h.pair.0 ^= 1; + h.pair.0 +} + +/// Holds `pair`, for its caller to change. +fn hold(pair: (u8, u8)) -> Holder { + Holder { pair } +} + +/// A `Copy` aggregate a std call stores by value is the container's own copy: changing +/// one stored element leaves the value it came from and the other elements as they were. +pub fn stores(data: &[u8], out: &mut Vec) { + let a = data.first().copied().unwrap_or(0); + let b = data.get(1).copied().unwrap_or(0); + // Made by a call, so its fields are read from it, not from `a` and `b`. + let pair = same((a, b)); + let mut changed = (b, a); + changed.0 ^= 0x10; + + let mut v = Vec::new(); + v.push(pair); + v.push(pair); + v[0].0 ^= 1; + // A local changed in place, before and after it is stored. + v.push(changed); + changed.1 ^= 0x20; + v[2].0 ^= 4; + // Through a parameter, and through a call's result. + keep(&mut v, pair); + v[3].1 ^= 8; + v.push(same(pair)); + v[4].0 ^= 0x40; + // Each element of an array std takes apart. + v.extend([pair, changed]); + v[5].1 ^= 0x80; + v[6].0 ^= 0x80; + let old = std::mem::replace(&mut v[0], pair); + v[0].1 ^= 0x10; + out.extend(v.iter().flat_map(|p| [p.0, p.1])); + out.extend_from_slice(&[changed.0, changed.1, old.0, old.1]); + + let tally = Tally { n: a as u16 }; + let mut q = VecDeque::new(); + q.push_back(tally); + q.push_front(tally); + q.insert(1, tally); + if let Some(t) = q.front_mut() { + t.n ^= 1; + } + if let Some(t) = q.back_mut() { + t.n ^= 2; + } + out.extend(q.iter().map(|t| t.n as u8)); + out.push(tally.n as u8); + + let mut hash = HashMap::new(); + hash.insert(0u8, pair); + hash.insert(1, pair); + if let Some(p) = hash.get_mut(&0) { + p.0 ^= 1; + } + hash.entry(2).or_insert(pair).1 ^= 2; + out.extend((0..3).flat_map(|k| hash.get(&k).map_or([0xff; 2], |p| [p.0, p.1]))); + let mut tree = BTreeMap::new(); + tree.insert(0u8, pair); + tree.insert(1, pair); + if let Some(p) = tree.get_mut(&1) { + p.1 ^= 1; + } + out.extend(tree.values().flat_map(|p| [p.0, p.1])); + + let mut boxed = Box::new(pair); + boxed.0 ^= 1; + let mut holders = vec![Holder { pair }]; + let holder = Holder { pair }; + holders.push(holder); + holders[1].pair.1 ^= 2; + out.extend_from_slice(&[boxed.0, boxed.1, holders[0].pair.1, holders[1].pair.1]); + out.push(bump(Holder { pair })); + let mut held = hold(pair); + held.pair.1 ^= 4; + holders.push(hold(pair)); + holders[2].pair.0 ^= 8; + out.extend_from_slice(&[held.pair.1, holders[2].pair.0]); + out.extend_from_slice(&[pair.0, pair.1]); +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 7ad220513..5430d8c80 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -19,7 +19,7 @@ pub fn run(input: &[u8]) -> Vec { return out; }; let (op, kind) = (*op, *kind); - match op % 43 { + match op % 44 { 0 => ints::u8_op(kind, data, &mut out), 1 => ints::u16_op(kind, data, &mut out), 2 => ints::u32_op(kind, data, &mut out), @@ -72,7 +72,8 @@ pub fn run(input: &[u8]) -> Vec { 39 => keys::keys(kind, data, &mut out), 40 => chars::chars(kind, data, &mut out), 41 => strs::strs(kind, data, &mut out), - _ => collections::vecs(data, &mut out), + 42 => collections::vecs(data, &mut out), + _ => collections::stores(data, &mut out), } out } diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 1445589da..9ed7b8a1e 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -672,16 +672,14 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec } } ("Box", "new") => args.pop()?, - // `vec![x; n]`: `n - 1` clones of `x`, then `x` itself. + // `vec![x; n]`: `n - 1` clones of `x`, then `x` itself, which the caller gives as its + // own, as it does whatever std keeps. ("vec", "from_elem") => { let elem = targ(gargs, 0); let mut values = args; match is_u8(elem) { true => Expr::rt("byteVecOf", values), false => { - // The last element is `x` itself: a copy of a `Copy` aggregate, without its `Clone`. - let value = owned(b, values.remove(0), elem, span); - values.insert(0, value); values.push(super::collections::clone_fn(b, elem, span)); Expr::rt("vecFromElem", values) } diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index f23c9c420..f507a5f54 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -25,6 +25,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ) { let tcx = self.tcx; let fn_ty = func.ty(&self.mir.local_decls, tcx); + let result = dest.ty(&self.mir.local_decls, tcx).ty; let mut pre = Vec::new(); let (value, effect) = match *fn_ty.kind() { // `next` into a local that holds the protocol's item or `rt.DONE`, unconverted. @@ -70,11 +71,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.emit(pre, None, false, out); return; } - None => (self.call_def(def_id, gargs.skip_binder(), args, span, &mut pre), true), + None => ( + self.call_def(def_id, gargs.skip_binder(), args, result, span, &mut pre), + true, + ), }, ty::FnPtr(..) => { let f = self.operand(func, span, &mut pre); - let values = self.operands(args, span, &mut pre); + let values = self.operands(false, args, result, span, &mut pre); (f.call(values), true) } _ => (self.err(span, format!("a call through `{fn_ty}`")), true), @@ -128,13 +132,31 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } - /// Arguments, uncopied: a callee that changes a parameter in place copies it first. - fn operands(&mut self, args: &[Spanned>], span: Span, out: &mut Vec) -> Vec { + /// Arguments, uncopied, since a callee that changes a parameter in place copies it + /// first, but for a `Copy` aggregate std `keeps`, copied unless moved out of a local's + /// own value, which the analysis then made the local's own. + fn operands( + &mut self, + translated: bool, + args: &[Spanned>], + result: Ty<'tcx>, + span: Span, + out: &mut Vec, + ) -> Vec { let saved = std::mem::replace(&mut self.into_frozen, true); - let values = args - .iter() - .map(|arg| self.operand_frozen(&arg.node, span, out)) - .collect(); + let mut values = Vec::with_capacity(args.len()); + for arg in args { + let value = self.operand_frozen(&arg.node, span, out); + values.push(match &arg.node { + Operand::Copy(p) | Operand::Move(p) + if self.moved_from(&arg.node).is_none() + && self.keeps(translated, args, p.ty(&self.mir.local_decls, self.tcx).ty, result) => + { + self.b.t.copied(value, p.ty(&self.mir.local_decls, self.tcx).ty, span) + } + _ => value, + }); + } self.into_frozen = saved; values } @@ -153,6 +175,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { def_id: rustc_hir::def_id::DefId, gargs: GenericArgsRef<'tcx>, args: &[Spanned>], + result: Ty<'tcx>, span: Span, out: &mut Vec, ) -> Expr { @@ -183,16 +206,13 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return f.call(values); } // A function of the crate gets what JS passes, so a `&mut` to a number can't reach it. - let local = match Instance::try_resolve(tcx, self.b.t.typing_env_pub(), def_id, gargs) { - Ok(Some(instance)) => matches!(instance.def, ty::InstanceKind::Item(did) if did.is_local()), - _ => false, - }; + let local = self.b.t.translated(def_id, gargs); if local { for arg in args { self.check_escape(&arg.node, span); } } - let values = self.operands(args, span, out); + let values = self.operands(local, args, result, span, out); self.b.call_def(def_id, gargs, values, span, out) } @@ -302,7 +322,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { && self.defs[local] == 1 && matches!(self.slots[local], Slot::Var(_)) => { - let place = self.call_def(def_id, gargs, args, span, out); + let result = dest.ty(&self.mir.local_decls, tcx).ty; + let place = self.call_def(def_id, gargs, args, result, span, out); if !place.is_path() { return done(place, true); } diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 8eca465ac..54f227f18 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -24,7 +24,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_index::IndexVec; use rustc_middle::mir::{self, BasicBlock, Local, Operand, Place, Rvalue, StatementKind, TerminatorKind}; use rustc_middle::ty::{self, EarlyBinder, Instance, Ty, TyCtxt}; -use rustc_span::Span; +use rustc_span::{Span, Spanned}; use self::cfg::Exit; use super::Translator; @@ -140,7 +140,10 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { defs: IndexVec, /// Locals something borrows, which a call or closure can change behind a read. borrowed: IndexVec, - /// Locals changed in place: assigned through a projection, or borrowed mutably. + /// Locals changed in place: assigned through a projection, borrowed mutably, or moved, + /// holding a `Copy` aggregate, into what can change it later: a field, a local changed + /// in place, or a call that `keeps` it. The return place is one when its caller has no + /// copy to make. Each holds its own JS objects, which a move hands over uncopied. mutated: IndexVec, /// The names of borrowed locals. shared: FxHashSet, @@ -294,6 +297,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.find_ignored_sites(); self.find_noops(); let mut bounds = Vec::new(); + // Locals whose value moves whole into another's, `(to, from)`. + let mut moves = Vec::new(); for (bb, data) in mir.basic_blocks.iter_enumerated() { if data.statements.iter().all(|s| { matches!( @@ -316,6 +321,19 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } self.def(*place); self.rvalue_uses(rvalue); + let ops = match rvalue { + Rvalue::Use(op, _) => std::slice::from_ref(op), + Rvalue::Aggregate(_, ops) => &ops.raw[..], + _ => &[], + }; + let moved: Vec = ops.iter().filter_map(|op| self.moved_from(op)).collect(); + for from in moved { + match place.as_local() { + Some(to) => moves.push((to, from)), + // Into a field or through a reference, which changes in place. + None => self.mutated[from] = true, + } + } if let Rvalue::BinaryOp(op, _) = rvalue && op.overflowing_to_wrapping().is_some() && let Some(local) = place.as_local() @@ -333,7 +351,13 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let term = data.terminator(); match &term.kind { TerminatorKind::SwitchInt { discr, .. } => self.operand_use(discr), - TerminatorKind::Return => self.uses[mir::RETURN_PLACE] += 1, + TerminatorKind::Return => { + self.uses[mir::RETURN_PLACE] += 1; + // The caller can change what it holds, and has no copy to make. + if self.moves_copied(mir.local_decls[mir::RETURN_PLACE].ty) { + self.mutated[mir::RETURN_PLACE] = true; + } + } // A drop JS can't see reads nothing. TerminatorKind::Drop { place, .. } => { if self.b.t.drops(place.ty(&mir.local_decls, self.tcx).ty) { @@ -348,20 +372,26 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } => { self.operand_use(func); let result = destination.ty(&mir.local_decls, self.tcx).ty; + let translated = self.translated(func); for arg in args.iter() { self.operand_use(&arg.node); - if let Operand::Copy(p) | Operand::Move(p) = &arg.node - && let Some(local) = p.as_local() - { + let (Operand::Copy(p) | Operand::Move(p)) = &arg.node else { + continue; + }; + let part = p.ty(&mir.local_decls, self.tcx).ty; + let kept = self.keeps(translated, args, part, result); + if kept && let Some(from) = self.moved_from(&arg.node) { + self.mutated[from] = true; + } + if let Some(local) = p.as_local() { // A callee given nothing that can change what the argument is can't // change its source while it runs. - let part = mir.local_decls[local].ty; let alone = !std::iter::once(func) .chain(args.iter().map(|a| &a.node)) .any(|op| self.changes(op.ty(&mir.local_decls, self.tcx), part)); self.arg_use[local] = true; self.arg_alone[local] = alone; - self.arg_kept[local] = self.holds(result, part); + self.arg_kept[local] = kept || self.holds(result, part); } } self.def(*destination); @@ -380,6 +410,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { _ => {} } } + // What moves into a local changed in place must be its source's own too. + let mut changed = true; + while std::mem::take(&mut changed) { + for &(to, from) in &moves { + if self.mutated[to] && !self.mutated[from] { + self.mutated[from] = true; + changed = true; + } + } + } // A bounds check of a slice's length is `rt.idx` of the slice; others test their // condition, and show their operands. for (cond, len, index) in bounds { @@ -2342,6 +2382,126 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { }) } + /// Whether a call given `args`, of std's code unless `translated`, may change what it + /// takes by value of type `part` in place after its source gave it: a value with no + /// copy holding a `Copy` aggregate, whatever the callee, or a `Copy` aggregate std + /// keeps, or keeps a part of, in its result or where another argument reaches, as + /// `Vec::push` keeps it in the vector. The crate's own code copies a `Copy` aggregate + /// it keeps itself. + pub(super) fn keeps( + &self, + translated: bool, + args: &[Spanned>], + part: Ty<'tcx>, + result: Ty<'tcx>, + ) -> bool { + if self.moves_copied(part) { + return true; + } + !translated + && self.copied_parts(part).into_iter().any(|t| { + self.holds_behind(result, t) + || args + .iter() + .any(|a| self.stores(a.node.ty(&self.mir.local_decls, self.tcx), t)) + }) + } + + /// Whether a value of `ty` reaches somewhere that could take a `part` in: a raw + /// pointer, or a mutable reference to or interior mutability around what could hold one. + fn stores(&self, ty: Ty<'tcx>, part: Ty<'tcx>) -> bool { + use rustc_middle::ty::TypeVisitableExt; + let env = self.b.t.typing_env_pub(); + self.reaches(ty, |t| match t.kind() { + ty::RawPtr(..) => true, + ty::Ref(_, inner, rustc_ast::Mutability::Mut) => self.holds(*inner, part), + _ => !t.has_escaping_bound_vars() && !t.is_freeze(self.tcx, env) && self.holds(t, part), + }) + } + + /// The local whose own value `op` moves out, which nothing reads after, if it holds a + /// `Copy` aggregate: by `move`, or by `copy` of a type that isn't `Copy`, as optimized + /// MIR moves too. + pub(super) fn moved_from(&self, op: &Operand<'tcx>) -> Option { + let (Operand::Copy(p) | Operand::Move(p)) = op else { + return None; + }; + let ty = p.ty(&self.mir.local_decls, self.tcx).ty; + let moves = matches!(op, Operand::Move(_)) || !self.b.t.is_copy(ty); + (moves && own(*p) && self.holds_copied(ty)).then_some(p.local) + } + + /// Whether a value of `ty` has no copy to make but holds a `Copy` aggregate by value, + /// so wherever it moves can change what it holds, which must then be its own. + fn moves_copied(&self, ty: Ty<'tcx>) -> bool { + !self.b.t.is_copy(ty) && self.holds_copied(ty) + } + + /// Whether a value of `ty` is or holds by value a `Copy` aggregate. + fn holds_copied(&self, ty: Ty<'tcx>) -> bool { + !self.copied_parts(ty).is_empty() + } + + /// The `Copy` aggregates, JS objects Rust code copies, that a value of `ty` is or holds + /// by value, not behind a reference, in any of which std could take it apart. + fn copied_parts(&self, ty: Ty<'tcx>) -> Vec> { + let mut parts = Vec::new(); + let mut seen = FxHashSet::default(); + let mut stack = vec![ty]; + while let Some(ty) = stack.pop() { + if !seen.insert(ty) { + continue; + } + if self.b.t.needs_copy(ty) { + parts.push(ty); + } + match ty.kind() { + ty::Tuple(tys) => stack.extend(tys.iter()), + ty::Array(elem, _) | ty::Slice(elem) => stack.push(*elem), + ty::Adt(adt, args) if adt.did().is_local() => { + stack.extend(adt.all_fields().map(|field| self.b.t.field_ty(field.did, args))) + } + ty::Adt(_, args) => stack.extend(args.types()), + ty::Closure(_, args) => stack.extend(args.as_closure().upvar_tys()), + _ => {} + } + } + parts + } + + /// Whether `func` is a function the crate translates, rather than std's. + pub(super) fn translated(&self, func: &Operand<'tcx>) -> bool { + match *func.ty(&self.mir.local_decls, self.tcx).kind() { + ty::FnDef(def_id, args) => self.b.t.translated(def_id, args.skip_binder()), + _ => false, + } + } + + /// Whether a value of `ty` could hold a `part` where changing it in place changes no + /// local holding the value: behind a box, a reference, or a collection. One it holds + /// in a field or a variant changes in place only as its local does, which copies it. + fn holds_behind(&self, ty: Ty<'tcx>, part: Ty<'tcx>) -> bool { + if ty == part { + return false; + } + use crate::lower::library::Std; + match ty.kind() { + ty::Tuple(tys) => tys.iter().any(|t| self.holds_behind(t, part)), + ty::Array(elem, _) => self.holds_behind(*elem, part), + ty::Adt(adt, args) + if adt.did().is_local() + || matches!( + self.b.t.std_of(ty), + Some(Std::Option | Std::Result | Std::ControlFlow | Std::Poll) + ) => + { + adt.all_fields() + .any(|field| self.holds_behind(self.b.t.field_ty(field.did, args), part)) + } + _ => self.holds(ty, part), + } + } + /// Whether a value of `ty` could hold a `part`: holds its type, or hides what it holds. fn holds(&self, ty: Ty<'tcx>, part: Ty<'tcx>) -> bool { // An array and a slice of its element share storage through an unsizing coercion. @@ -2383,7 +2543,7 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { /// Whether `place` is part of its local's own value, rather than reached through a /// reference or pointer. -fn own(place: Place<'_>) -> bool { +pub(super) fn own(place: Place<'_>) -> bool { place .projection .iter() diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 15b9d998e..b8716bf6c 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -302,10 +302,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { false => self.b.t.copied(value, ty, span), } } + // Moved out of a local's own value changed in place, which is its own. Operand::Move(place) => { let ty = place.ty(&self.mir.local_decls, self.tcx).ty; let value = self.place_expr(*place, span, out); - match self.into_frozen { + match self.into_frozen || super::own(*place) && self.mutated[place.local] { true => value, false => self.b.t.copied(value, ty, span), } diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index eec276eb4..7f3020dc8 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -648,6 +648,15 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { self.tcx.type_is_copy_modulo_regions(self.typing_env(), ty) } + /// Whether a call of `def_id` with `args` runs a function of the crate, which it + /// translates, rather than std's. + pub fn translated(&self, def_id: DefId, args: GenericArgsRef<'tcx>) -> bool { + match Instance::try_resolve(self.tcx, self.typing_env(), def_id, args) { + Ok(Some(instance)) => matches!(instance.def, InstanceKind::Item(did) if did.is_local()), + _ => false, + } + } + /// A local struct or enum, translating its definition the first time. pub fn adt(&mut self, adt: AdtDef<'tcx>, span: Span) -> Adt { if let Some(info) = self.adts.get(&adt.did()) { diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 5c64cb0ff..9418dc2e3 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -263,7 +263,8 @@ fn shake(out: &Path) { "u32Sub", "usizeSaturatingAdd", "usizeSub", - // The translation's, and the caller. + // The translation's, and the caller. The decoder keeps its own copy of the form. + "copy$Form", "new_", "run", "short",