diff --git a/quest/m2/README.md b/quest/m2/README.md index 4e453b0bf..8941cc455 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -30,7 +30,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 -- [Share what the crate never changes in place](/quest/m2/ts-shared-read.md) - copies of `Copy` aggregates no one writes into in place go away, recovering #83's decode cost - [Matches TypeScript has already narrowed](/quest/m2/ts-narrow-test.md) - an inner match on a value an outer match decided passes `tsc` - [Small std gaps](/quest/m2/ts-std-gaps.md) - `bool::then`, `iter::successors`, `usize::from(bool)`, and `None.ok_or` narrowing - [Copy-on-write strings](/quest/m2/ts-cow-str.md) - `Cow` translates, finishing `ietf/namespace.rs` diff --git a/quest/m2/ts-shared-read.md b/quest/m2/ts-shared-read.md deleted file mode 100644 index 034b5c7d5..000000000 --- a/quest/m2/ts-shared-read.md +++ /dev/null @@ -1,31 +0,0 @@ -# [S] Share what the crate never changes in place - -## Goal - -rust2-ts shares a `Copy` aggregate, where it copies one today, when nothing in the crate -writes into a value of that type in place. `Decoder::varint`'s `leading-ones` decode -on `just ts bench` is back to its speed before -[#83](https://github.com/kixelated/rust2/pull/83) in Chrome, and every differential -test still passes. - -## Plan - -Decided with the maintainer on 2026-10-27, replacing the narrower fix for -`self.form`'s copy that this quest held before: -[#83](https://github.com/kixelated/rust2/pull/83) and -[#99](https://github.com/kixelated/rust2/pull/99) copy a `Copy` aggregate before a call -can share it (`self.form` before `read`, `copy$Form` in `Decoder::new` and -`Encoder::new`, and map keys). A copy is only observable if something writes into a -shared value in place: a field or element assignment through it, or a `&mut` to its -inside. A type the crate never writes that way can be shared freely. - -- Find, per crate, each `Copy` aggregate type that some place writes into in place, and - let `copy_fn`'s callers skip the copy for every other type. -- Keep the analysis whole-crate and fail closed: a write the analysis can't see, such as - through a generic, counts as a write. -- Prove it with #83's argument-aliasing cases and #99's store cases, plus a new case - where the only in-place write is in another module or behind a generic. -- Report the copies removed in moq-net's output, and the Chrome codec bench before and - after. - -Public API: the translator's output. diff --git a/ts/Cargo.lock b/ts/Cargo.lock index 942691474..b4f565afc 100644 --- a/ts/Cargo.lock +++ b/ts/Cargo.lock @@ -209,6 +209,10 @@ dependencies = [ "serde_core", ] +[[package]] +name = "share-fixture" +version = "0.0.0" + [[package]] name = "syn" version = "2.0.119" diff --git a/ts/README.md b/ts/README.md index 50ac4f8e9..e9a7380eb 100644 --- a/ts/README.md +++ b/ts/README.md @@ -151,7 +151,12 @@ and exports it as its own: `function new_` is `Decoder.new`. A `Copy` struct, en or array, or an `Option`, `Result`, or `Poll` holding one, is copied where Rust copies it, since JS would share the object: by a function of `lib.ts` made for its type, such as `copy$Point`, which copies what it holds by value and shares what it holds by -reference. +reference. Only a type the crate writes into in place is copied, or one holding such a +type by value: a value of any other type never changes once made, so it is shared. A +write counts through a field, an element, a reference, or a box, and a mutable reference +a std function's parameters take, where the crate calls it or takes it as a value, or +one kept other than in a local, counts as a write into what it points at. A write over a type parameter counts for every type its bounds allow. A caller must +not change in place what it passes to or gets from the translation either. A collection keeps Rust's key semantics. A hash map or set keeps a key that is a JS number, string, or boolean in a JS `Map`, which compares those as Rust's `Eq` does, and @@ -353,7 +358,8 @@ built natively for wasm32 and run beside its translation on the same inputs by 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, those - a container stores included, formatting, methods on generic types, iterators, with + a container stores included and those written into only in another module, behind a + type parameter, or through a box, 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 @@ -363,6 +369,10 @@ built natively for wasm32 and run beside its translation on the same inputs by with products of those values at 128 bits, 128-bit quotients by divisors below 2^32, and their halves joined back. `brands.ts`, another caller, mixes integer types where `tsc` must refuse them. +- `share` holds a `Copy` aggregate whose only write in the crate makes it copied, where + `lang`'s other writes into the same type would hide a write the analysis misses: a + byte array overwritten whole through a type parameter, or, under its features, by std + called directly or through a pointer a generic function calls. - `task` trims moq's kio to a channel of `Arc`ed state, waiters, and wakers, under async functions, beside values that drop inside std's types. Its caller is hand-written TS (`tests/task.ts`): a FIFO executor that runs a script of spawns, sends, polls, and drops, and logs every poll, wake, and drop, as the diff --git a/ts/fixtures/codec/expected/coding/decode.Decoder.ts b/ts/fixtures/codec/expected/coding/decode.Decoder.ts index 53e1ddba5..61c6c7814 100644 --- a/ts/fixtures/codec/expected/coding/decode.Decoder.ts +++ b/ts/fixtures/codec/expected/coding/decode.Decoder.ts @@ -1,7 +1,6 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { copy$Form } from "../lib.ts"; import * as DecodeError from "../coding/decode.DecodeError.ts"; import { read } from "../coding/varint.ts"; import type * as Form from "../coding/varint.Form.ts"; @@ -31,7 +30,7 @@ export interface Decoder { /** Read `buf`, with varints in the given form. */ function new_(buf: rt.ByteSlice, form: Form.Form): Decoder { - return { buf, form: copy$Form(form), len: buf.length, need: 0, control: undefined, uncounted: 0 }; + return { buf, form, len: buf.length, need: 0, control: undefined, uncounted: 0 }; } /** @@ -81,7 +80,7 @@ export function rest(self: Decoder): rt.ByteSlice { export function sub(self: Decoder, len: rt.usize): rt.Result { const _4: rt.Result = slice(self, len); if (_4.ok) { - return rt.Ok(new_(_4.value, copy$Form(self.form))); + return rt.Ok(new_(_4.value, self.form)); } return _4; } @@ -127,7 +126,7 @@ export function bool(self: Decoder): rt.Result /** Read a varint. */ export function varint(self: Decoder): rt.Result { let _0!: rt.Result; - const _2: rt.Result<[rt.u64, rt.ByteSlice], DecodeError.DecodeError> = read(self.buf, copy$Form(self.form)); + const _2: rt.Result<[rt.u64, rt.ByteSlice], DecodeError.DecodeError> = read(self.buf, self.form); if (_2.ok) { const value: rt.u64 = _2.value[0]; self.buf = _2.value[1]; diff --git a/ts/fixtures/codec/expected/coding/encode.Encoder.ts b/ts/fixtures/codec/expected/coding/encode.Encoder.ts index 5b746659e..151cf0758 100644 --- a/ts/fixtures/codec/expected/coding/encode.Encoder.ts +++ b/ts/fixtures/codec/expected/coding/encode.Encoder.ts @@ -1,7 +1,6 @@ // 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 +21,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: copy$Form(form), control: undefined }; + return { buf, 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 6c9179f2b..76b0eabd9 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -1,7 +1,6 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { copy$Version } from "../lib.ts"; import type * as DecodeError from "../coding/decode.DecodeError.ts"; import * as Decoder from "../coding/decode.Decoder.ts"; import type * as EncodeError from "../coding/encode.EncodeError.ts"; @@ -35,7 +34,7 @@ export function decode$Decode_Form(r: Decoder.Decoder, version: Form.Form): rt.R while (iter.next() !== rt.DONE) { const _15: rt.Result = Version.decode$Decode_Form(r, version); if (_15.ok) { - vs.push(copy$Version(_15.value)); + vs.push(_15.value); } else { return _15; } @@ -76,7 +75,7 @@ export function encode$Encode_Version(self: Versions, w: Encoder.Encoder, versio } export function from$From_Versions(vs: Version.Version[]): Versions { - return { _0: vs.map(copy$Version) }; + return { _0: vs.slice() }; } //# sourceMappingURL=version.Versions.ts.map diff --git a/ts/fixtures/codec/expected/lib.ts b/ts/fixtures/codec/expected/lib.ts index 4a5725376..6c0482431 100644 --- a/ts/fixtures/codec/expected/lib.ts +++ b/ts/fixtures/codec/expected/lib.ts @@ -1,22 +1,9 @@ // Generated by rust2-ts. Do not edit. import type * as Timestamp from "./bench.Timestamp.ts"; -import type * as Form from "./coding/varint.Form.ts"; -import type * as Version from "./coding/version.Version.ts"; - -export function copy$Form(v: Form.Form): Form.Form { - if (v.tag === "LeadingOnes") { - return { tag: "LeadingOnes", seven: v.seven }; - } - return v; -} export function copy$Timestamp(v: Timestamp.Timestamp): Timestamp.Timestamp { return { value: v.value, scale: v.scale }; } -export function copy$Version(v: Version.Version): Version.Version { - return { _0: v._0 }; -} - //# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/lang/expected/chunks.ts b/ts/fixtures/lang/expected/chunks.ts index a435031e0..b97338907 100644 --- a/ts/fixtures/lang/expected/chunks.ts +++ b/ts/fixtures/lang/expected/chunks.ts @@ -1,11 +1,10 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Option_u8s_u8s } from "./lib.ts"; import type * as Header from "./chunks.Header.ts"; export function header(data: rt.ByteSlice): Header.Header | undefined { - const _4: [rt.ByteSlice, rt.ByteSlice] | undefined = copy$Option_u8s_u8s(rt.byteSliceSplitFirstChunk(data, 2)); + const _4: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitFirstChunk(data, 2); if (_4 !== undefined) { const val: [rt.ByteSlice, rt.ByteSlice] = _4; return { tag: val[0], rest: val[1] }; diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index e84410d41..b49254326 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.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 { copy$Bumped, 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"; @@ -160,14 +160,14 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, 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, copy$Pair(pair)), Tally.default$Default); + const t: Tally.Tally = rt.entryOrInsertWith(rt.entry(pairs, 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, copy$Rank(r), { n: i3 & 0xffff }); + rt.hashInsert(ranks, 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); @@ -196,8 +196,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void } const key: Pair.Pair = { a: 9, b: 9 }; const local: Tally.Tally = { n: 7 }; - const _241: Tally.Tally = copy$Tally(local); - rt.hashInsert(pairs, copy$Pair(key), _241); + rt.hashInsert(pairs, key, copy$Tally(local)); local.n = 8; const before: Tally.Tally = copy$Tally(rt.hashIndex(pairs, key)); const _246: Tally.Tally | undefined = rt.hashGet(pairs, key); @@ -231,7 +230,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const _292: [rt.u8, rt.u8] = [_293, data.data[data.start + i4]]; const a2: rt.u8 = _293; const b4: rt.u8 = _292[1]; - const _305: Rank.Rank = copy$Rank(rank(b4, a2)); + const _305: Rank.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 => { @@ -239,14 +238,14 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void }); t4.n = rt.u16WrappingAdd(t4.n, t4.n); rt.idx(data, i4); - const _313: Rank.Rank = copy$Rank(rank(data.data[data.start + i4], 0)); + const _313: Rank.Rank = rank(data.data[data.start + 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 => { return { n: rankByte(k9) as rt.u16 }; }).n & 0xff); } - const copy: rt.HashMap = rt.hashClone(ranks, copy$Rank, copy$Tally); + const copy: rt.HashMap = rt.hashClone(ranks, undefined, copy$Tally); const _327: Tally.Tally | undefined = rt.hashGet(copy, { tag: "Low" } as Rank.Rank); if (_327 !== undefined) { _327.n = 119; @@ -332,7 +331,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void return true; }); const _473: rt.Iter<[Rank.Rank, rt.u16]> = rt.iterMap(rt.hashIter(ranks), (_224: [Rank.Rank, Tally.Tally]): [Rank.Rank, rt.u16] => { - return [copy$Rank(_224[0]), _224[1].n] as [Rank.Rank, rt.u16]; + return [_224[0], _224[1].n] as [Rank.Rank, rt.u16]; }); const iter14: rt.Iter<[Rank.Rank, rt.u16]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(Rank.cmp$Ord) as rt.BTreeMap, _473, true)); while (true) { @@ -397,7 +396,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void return t6.n & 0xff; })); } else { - rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(clashes, copy$Clash(k6), { n: i5 & 0xffff }), 204, (t5: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(clashes, k6, { n: i5 & 0xffff }), 204, (t5: Tally.Tally): rt.u8 => { return t5.n & 0xff; })); } @@ -412,7 +411,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void return k8._0; }); rt.iterExtendBytes(out, rt.btreeKeys(rt.btreeExtendKeys(rt.btreeNew(rt.cmp) as rt.BTreeSet, _583, true))); - const copy3: rt.HashMap = rt.hashClone(clashes, copy$Clash, copy$Tally); + const copy3: rt.HashMap = rt.hashClone(clashes, undefined, copy$Tally); rt.byteVecPush(out, rt.hashLen(copy3) & 0xff); rt.byteVecPush(out, rt.hashContains(copy3, { _0: 1 }) ? 1 : 0); } @@ -676,7 +675,7 @@ export function btreeMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi const _170: [rt.u8, rt.u8] = [_171, data.data[data.start + i2]]; const a: rt.u8 = _171; const b: rt.u8 = _170[1]; - const _182: Rank.Rank = copy$Rank(rank(a, b)); + const _182: Rank.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)]; @@ -690,7 +689,7 @@ export function btreeMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi } for (const b2 of rt.byteSliceView(data)) { const r: Rank.Rank = rank(b2, rt.u8Div(b2, 3)); - const _212: rt.Entry = rt.entry(ranks, copy$Rank(r)); + const _212: rt.Entry = rt.entry(ranks, r); if (!rt.entryOccupied(_212)) { const e: rt.Entry = _212; rt.byteVecPush(out, rankByte(rt.entryKey(e))); diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 24fd886dc..70e244bd6 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -1,7 +1,6 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.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"; @@ -198,7 +197,7 @@ export function nested(data: rt.ByteSlice): 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.byteSliceToByteVec(rt.byteSliceRange(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$2); + const _40: Pair.Pair[] = [{ _0: at(4), _1: -1 }, { _0: 2, _1: { hi: -0x80000000, lo: 0 } as rt.i64 }].slice(); if (!(rt.u8Rem(at(5), 2) === 0)) { _49 = undefined; } else { @@ -303,7 +302,7 @@ export function written(data: rt.ByteSlice, out: rt.ByteVec): void { const empty: Manual.Manual = { id: 0, list: [] }; const args6: rt.Fmt[] = [(f: rt.Formatter) => Manual.fmt$Debug(manual, f), (f: rt.Formatter) => Manual.fmt$Debug(empty, f)]; put(out, rt.fmtFormat([args6[0], " ", rt.fmtSpec({ alternate: true }, args6[0]), " ", args6[1]])); - const seq: Seq.Seq = { _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair$2) }; + const seq: Seq.Seq = { _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].slice() }; const none: Seq.Seq = { _0: [] }; const args8: rt.Fmt[] = [(f: rt.Formatter) => Seq.fmt$Debug(seq, f), (f: rt.Formatter) => Seq.fmt$Debug(none, f)]; put(out, rt.fmtFormat([args8[0], " ", rt.fmtSpec({ alternate: true }, args8[0]), " ", args8[1], " ", rt.fmtSpec({ alternate: true }, args8[1])])); diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index f9f476bbb..5ca04ef80 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -1,15 +1,17 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Either_u8_Points, copy$Wrap_Point, copy$Wrap_i16, copy$Wrap_u8 } from "./lib.ts"; +import { copy$Either_u8_Points, copy$Gauge, 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"; import * as Tagged from "./generics.Tagged.ts"; import * as Wrap from "./generics.Wrap.ts"; +import * as Gauge from "./shapes.Gauge.ts"; import type * as Meters from "./shapes.Meters.ts"; import * as Point from "./shapes.Point.ts"; import type * as Shape from "./shapes.Shape.ts"; +import type * as Track from "./shapes.Track.ts"; /** Each method once per instance: `Wrap` of a struct, an enum, a number, and itself. */ export function methods(data: rt.ByteSlice, out: rt.ByteVec): void { @@ -73,4 +75,28 @@ export function methods(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, rt.optionUnwrapOr(Either.left$u8_u16(tagged.key), 0)); } +/** + * Moves `track`'s mark on: the crate's only write into a `Mark`, in another module than + * the copy of one that must not see it. + */ +export function advance(track: Track.Track): void { + const _2: rt.u8 = rt.u8WrappingAdd(track.mark.at, 1); + track.mark.at = _2; +} + +/** + * Resets each of `xs`, writing into each one in place, which only an instance knows the + * type of. + */ +export function reset$Gauge(xs: Gauge.Gauge[]): void { + const iter: rt.Iter = rt.iterSlice(xs); + while (true) { + const _5: Gauge.Gauge | rt.Done = iter.next(); + if (_5 === rt.DONE) { + break; + } + Object.assign(_5, copy$Gauge(Gauge.default$Default())); + } +} + //# sourceMappingURL=generics.ts.map diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index eeff54b6c..47e98794d 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -1,18 +1,17 @@ // Generated by rust2-ts. Do not edit. 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 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 Gauge from "./shapes.Gauge.ts"; import type * as Held from "./shapes.Held.ts"; import type * as Lens from "./shapes.Lens.ts"; +import type * as Level from "./shapes.Level.ts"; +import type * as Mark from "./shapes.Mark.ts"; import type * as Point from "./shapes.Point.ts"; import type * as Shape from "./shapes.Shape.ts"; @@ -20,10 +19,6 @@ export function copy$Bumped(v: Bumped.Bumped): Bumped.Bumped { return { _0: v._0 }; } -export function copy$Clash(v: Clash.Clash): Clash.Clash { - return { _0: v._0 }; -} - export function copy$ControlFlow_Arc_u8_u8s(v: rt.Result>): rt.Result> { return v.ok ? rt.Ok(copy$u8s(v.value)) : rt.Err(v.error); } @@ -46,6 +41,10 @@ export function copy$Either_u8_Points(v: Either.Either[]): E return v.map(copy$Either_u8_Point); } +export function copy$Gauge(v: Gauge.Gauge): Gauge.Gauge { + return { level: v.level }; +} + export function copy$Held(v: Held.Held): Held.Held { return { at: copy$Point(v.at) }; } @@ -62,6 +61,14 @@ export function copy$Lens(v: Lens.Lens): Lens.Lens { return { slot: v.slot, n: v.n }; } +export function copy$Level(v: Level.Level): Level.Level { + return { _0: v._0 }; +} + +export function copy$Mark(v: Mark.Mark): Mark.Mark { + return { at: v.at }; +} + export function copy$Mutex_u8_u8(v: [rt.Mutex, rt.u8]): [rt.Mutex, rt.u8] { return [v[0], v[1]]; } @@ -82,18 +89,6 @@ export function copy$Option_Wrap_i16(v: Wrap.Wrap | undefined): Wrap.Wra return v === undefined ? v : copy$Wrap_i16(v); } -export function copy$Option_u8s_u8s(v: [rt.ByteSlice, rt.ByteSlice] | undefined): [rt.ByteSlice, rt.ByteSlice] | undefined { - return v === undefined ? v : copy$u8s_u8s(v); -} - -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 }; -} - export function copy$Point(v: Point.Point): Point.Point { return { x: v.x, y: v.y }; } @@ -110,16 +105,6 @@ export function copy$Poll_u8s(v: rt.Poll): rt.Poll { return v === rt.Pending ? v : copy$u8s(v); } -export function copy$Rank(v: Rank.Rank): Rank.Rank { - if (v.tag === "Mid") { - return { tag: "Mid", _0: v._0 }; - } - if (v.tag === "High") { - return { tag: "High", x: v.x, y: v.y }; - } - return v; -} - export function copy$Result_Mutex_u8_u8_u8(v: rt.Result<[rt.Mutex, rt.u8], rt.u8>): rt.Result<[rt.Mutex, rt.u8], rt.u8> { return v.ok ? rt.Ok(copy$Mutex_u8_u8(v.value)) : rt.Err(v.error); } @@ -182,8 +167,4 @@ export function copy$u8s(v: Uint8Array): Uint8Array { return v.slice(); } -export function copy$u8s_u8s(v: [rt.ByteSlice, rt.ByteSlice]): [rt.ByteSlice, rt.ByteSlice] { - return [v[0], v[1]]; -} - //# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Gauge.ts b/ts/fixtures/lang/expected/shapes.Gauge.ts new file mode 100644 index 000000000..a5517f656 --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Gauge.ts @@ -0,0 +1,14 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +export function default$Default(): Gauge { + return { level: 0 }; +} + +/** A `Copy` struct written into only behind a type parameter, by `generics::reset`. */ +export interface Gauge { + level: rt.u8; +} + +//# sourceMappingURL=shapes.Gauge.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Level.ts b/ts/fixtures/lang/expected/shapes.Level.ts new file mode 100644 index 000000000..46839714e --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Level.ts @@ -0,0 +1,10 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A `Copy` struct written into only through a box. */ +export interface Level { + _0: rt.u8; +} + +//# sourceMappingURL=shapes.Level.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Mark.ts b/ts/fixtures/lang/expected/shapes.Mark.ts new file mode 100644 index 000000000..3b0d6eedb --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Mark.ts @@ -0,0 +1,10 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A `Copy` struct this module never writes into: only `generics::advance` does. */ +export interface Mark { + at: rt.u8; +} + +//# sourceMappingURL=shapes.Mark.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Track.ts b/ts/fixtures/lang/expected/shapes.Track.ts new file mode 100644 index 000000000..3e762783b --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Track.ts @@ -0,0 +1,15 @@ +// Generated by rust2-ts. Do not edit. + +import { copy$Mark } from "./lib.ts"; +import type * as Mark from "./shapes.Mark.ts"; + +/** What holds a `Mark`. */ +export interface Track { + mark: Mark.Mark; +} + +export function mark(self: Track): Mark.Mark { + return copy$Mark(self.mark); +} + +//# sourceMappingURL=shapes.Track.ts.map diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 027e34551..84a5fd77f 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1,11 +1,15 @@ // 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$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$Gauge, copy$Held, copy$Lens, copy$Level, 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 { advance, reset$Gauge } from "./generics.ts"; import type * as Dir from "./shapes.Dir.ts"; +import type * as Gauge from "./shapes.Gauge.ts"; import type * as Held from "./shapes.Held.ts"; import type * as Lens from "./shapes.Lens.ts"; +import type * as Level from "./shapes.Level.ts"; +import type * as Mark from "./shapes.Mark.ts"; import * as Meters from "./shapes.Meters.ts"; import * as Moved from "./shapes.Moved.ts"; import type * as Mover from "./shapes.Mover.ts"; @@ -13,6 +17,7 @@ import * as Point from "./shapes.Point.ts"; import * as Shape from "./shapes.Shape.ts"; import type * as Signed from "./shapes.Signed.ts"; import type * as Slot from "./shapes.Slot.ts"; +import * as Track from "./shapes.Track.ts"; import * as Void from "./shapes.Void.ts"; import type * as Wide from "./shapes.Wide.ts"; @@ -218,6 +223,38 @@ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, _246); } shares(data, out); + unwritten(data, out); +} + +/** + * `Copy` aggregates written into only in another module, behind a type parameter, or + * through a box. Each copy keeps its value. + */ +export function unwritten(data: rt.ByteSlice, out: rt.ByteVec): void { + const n: rt.u8 = data.length & 0xff; + const track: Track.Track = { mark: { at: n } }; + const seen: Mark.Mark = Track.mark(track); + advance(track); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(seen.at, track.mark.at))); + const first: Gauge.Gauge = { level: n | 1 }; + const item = copy$Gauge(first); + const gauges: Gauge.Gauge[] = Array.from({ length: 2 }, (): Gauge.Gauge => { + return copy$Gauge(item); + }); + reset$Gauge(gauges); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(first.level, gauges[0].level, gauges[1].level))); + const start: Level.Level = { _0: n }; + const boxed: Level.Level = copy$Level(start); + Object.assign(boxed, { _0: ~n & 0xff }); + const _40: Level.Level = copy$Level(boxed); + const iter: rt.Iter = rt.iterSlice([copy$Level(start), _40]); + while (true) { + const _42: Level.Level | rt.Done = iter.next(); + if (_42 === rt.DONE) { + break; + } + rt.byteVecPush(out, _42._0); + } } /** Adds one to what `slot` holds. */ diff --git a/ts/fixtures/lang/src/generics.rs b/ts/fixtures/lang/src/generics.rs index 77ee85840..1663056b5 100644 --- a/ts/fixtures/lang/src/generics.rs +++ b/ts/fixtures/lang/src/generics.rs @@ -1,7 +1,7 @@ //! Methods on generic structs and enums, each instance its own method. use crate::fmt::{Pair, put}; -use crate::shapes::{Area, Meters, Point, Shape}; +use crate::shapes::{Area, Meters, Point, Shape, Track}; /// A generic struct, with methods on every instance, on some, and on one. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -173,3 +173,17 @@ pub fn methods(data: &[u8], out: &mut Vec) { out.extend_from_slice(&tagged.inner.value.to_be_bytes()); out.push(tagged.key.left().unwrap_or(0)); } + +/// Moves `track`'s mark on: the crate's only write into a `Mark`, in another module than +/// the copy of one that must not see it. +pub fn advance(track: &mut Track) { + track.mark.at = track.mark.at.wrapping_add(1); +} + +/// Resets each of `xs`, writing into each one in place, which only an instance knows the +/// type of. +pub fn reset(xs: &mut [X]) { + for x in xs.iter_mut() { + *x = X::default(); + } +} diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 81312971c..5bcd6e573 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -269,6 +269,56 @@ pub fn copies(data: &[u8], out: &mut Vec) { }); } shares(data, out); + unwritten(data, out); +} + +/// A `Copy` struct this module never writes into: only `generics::advance` does. +#[derive(Clone, Copy)] +pub struct Mark { + pub at: u8, +} + +/// What holds a `Mark`. +pub struct Track { + pub mark: Mark, +} + +impl Track { + fn mark(&self) -> Mark { + self.mark + } +} + +/// A `Copy` struct written into only behind a type parameter, by `generics::reset`. +#[derive(Clone, Copy, Default)] +struct Gauge { + level: u8, +} + +/// A `Copy` struct written into only through a box. +#[derive(Clone, Copy)] +struct Level(u8); + +/// `Copy` aggregates written into only in another module, behind a type parameter, or +/// through a box. Each copy keeps its value. +fn unwritten(data: &[u8], out: &mut Vec) { + let n = data.len() as u8; + let mut track = Track { mark: Mark { at: n } }; + let seen = track.mark(); + crate::generics::advance(&mut track); + out.extend_from_slice(&[seen.at, track.mark.at]); + + let first = Gauge { level: n | 1 }; + let mut gauges = [first; 2]; + crate::generics::reset(&mut gauges); + out.extend_from_slice(&[first.level, gauges[0].level, gauges[1].level]); + + let start = Level(n); + let mut boxed = Box::new(start); + *boxed = Level(!n); + for level in [start, *boxed] { + out.push(level.0); + } } /// A `Copy` struct holding a shared reference to a value that changes through it. diff --git a/ts/fixtures/share/Cargo.toml b/ts/fixtures/share/Cargo.toml new file mode 100644 index 000000000..ad8578d6a --- /dev/null +++ b/ts/fixtures/share/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "share-fixture" +description = "Copy aggregates rust2-ts copies for a single write, which lang's other writes would hide" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish = false + +[lib] +# The cdylib is the native side of the differential test, built for wasm32. +crate-type = ["lib", "cdylib"] + +[features] +# Each makes `harness::overwrite` another kind of write, for the fixture's only one. +call = [] +pointer = [] + +[lints] +workspace = true diff --git a/ts/fixtures/share/expected/harness.ts b/ts/fixtures/share/expected/harness.ts new file mode 100644 index 000000000..89b33cef4 --- /dev/null +++ b/ts/fixtures/share/expected/harness.ts @@ -0,0 +1,30 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$u8s } from "./lib.ts"; + +/** + * Copy two bytes of the input into an array, overwrite the copy, and output both: a + * shared array would change the original too. + */ +export function run(input: rt.ByteSlice): rt.ByteVec { + const out: rt.ByteVec = new rt.ByteVec(); + if (!(input.length >= 2)) { + return out; + } + const bytes: Uint8Array = Uint8Array.of(input.data[input.start], input.data[input.start + 1]); + const copy: Uint8Array = copy$u8s(bytes); + overwrite$u8s(rt.byteSliceFrom(copy), Uint8Array.of(rt.u8WrappingAdd(input.data[input.start + 1], 1), ~input.data[input.start] & 0xff)); + rt.byteVecPush(out, bytes[0]); + rt.byteVecPush(out, bytes[1]); + rt.byteVecPush(out, copy[0]); + rt.byteVecPush(out, copy[1]); + return out; +} + +/** The crate's only write into a byte array: whole, through a type parameter. */ +export function overwrite$u8s(dst: rt.ByteSlice, value: Uint8Array): void { + dst.data.set(copy$u8s(value), dst.start); +} + +//# sourceMappingURL=harness.ts.map diff --git a/ts/fixtures/share/expected/lib.ts b/ts/fixtures/share/expected/lib.ts new file mode 100644 index 000000000..3a3c04fa8 --- /dev/null +++ b/ts/fixtures/share/expected/lib.ts @@ -0,0 +1,7 @@ +// Generated by rust2-ts. Do not edit. + +export function copy$u8s(v: Uint8Array): Uint8Array { + return v.slice(); +} + +//# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/share/src/harness.rs b/ts/fixtures/share/src/harness.rs new file mode 100644 index 000000000..93ba2e156 --- /dev/null +++ b/ts/fixtures/share/src/harness.rs @@ -0,0 +1,42 @@ +//! The entry point both sides of the differential test run. + +/// Copy two bytes of the input into an array, overwrite the copy, and output both: a +/// shared array would change the original too. +pub fn run(input: &[u8]) -> Vec { + let mut out = Vec::new(); + let [a, b, ..] = input else { + return out; + }; + let bytes = [*a, *b]; + let mut copy = bytes; + overwrite(&mut copy, [b.wrapping_add(1), !*a]); + out.push(bytes[0]); + out.push(bytes[1]); + out.push(copy[0]); + out.push(copy[1]); + out +} + +/// The crate's only write into a byte array: whole, through a type parameter. +#[cfg(not(any(feature = "call", feature = "pointer")))] +fn overwrite(dst: &mut T, value: T) { + *dst = value; +} + +/// The crate's only write into a byte array: std's, called directly. +#[cfg(feature = "call")] +fn overwrite(dst: &mut [u8; 2], value: [u8; 2]) { + dst.copy_from_slice(&value); +} + +/// The crate's only write into a byte array: std's, through a pointer a generic function +/// calls, which no call to std shows. +#[cfg(feature = "pointer")] +fn overwrite(dst: &mut [u8; 2], value: [u8; 2]) { + invoke(<[u8]>::copy_from_slice, dst, &value); +} + +#[cfg(feature = "pointer")] +fn invoke(f: fn(A, B), a: A, b: B) { + f(a, b) +} diff --git a/ts/fixtures/share/src/lib.rs b/ts/fixtures/share/src/lib.rs new file mode 100644 index 000000000..1c80e9bb3 --- /dev/null +++ b/ts/fixtures/share/src/lib.rs @@ -0,0 +1,12 @@ +//! `Copy` aggregates whose only write in the crate makes them copied, where any other +//! write into the same type, as `lang` has, would hide a write the analysis misses. Each +//! feature makes that write another kind. +//! +//! `harness::run` is the entry point both sides of the differential test run. + +pub mod harness; +#[cfg(target_arch = "wasm32")] +#[path = "../../wasm.rs"] +mod wasm; +#[cfg(target_arch = "wasm32")] +use harness::run as entry; diff --git a/ts/fixtures/share/ts.toml b/ts/fixtures/share/ts.toml new file mode 100644 index 000000000..49fe970c7 --- /dev/null +++ b/ts/fixtures/share/ts.toml @@ -0,0 +1,2 @@ +package = "share-fixture" +roots = ["harness::run"] diff --git a/ts/src/lower/copy.rs b/ts/src/lower/copy.rs index 2c162269f..e7743ff72 100644 --- a/ts/src/lower/copy.rs +++ b/ts/src/lower/copy.rs @@ -1,11 +1,20 @@ //! Copies of `Copy` aggregates, by their type. //! //! JS shares an object where Rust copies its value, so a `Copy` value that is a JS object -//! Rust code can change in place is copied where Rust copies it. A function made for its -//! type copies what it holds by value and shares what it holds by reference, as Rust does. +//! the crate's code writes into in place is copied where Rust copies it. A function made +//! for its type copies what it holds by value and shares what it holds by reference, as +//! Rust does. A value of a type nothing writes into never changes once made, so sharing +//! it is a copy no one can tell apart. -use rustc_middle::ty::{self, EarlyBinder, Ty, TypeVisitableExt}; -use rustc_span::Span; +use std::cell::RefCell; + +use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; +use rustc_hir::def_id::DefId; +use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; +use rustc_middle::mir::{self, Location, Place, ProjectionElem, Rvalue}; +use rustc_middle::ty::fast_reject::DeepRejectCtxt; +use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt, TypeVisitableExt}; +use rustc_span::{DUMMY_SP, Span}; use super::library::{Flow, Std}; use super::{AdtRepr, Translator, field_name, short_name}; @@ -14,25 +23,29 @@ use crate::ts::{self, Expr, Key, Param, Stmt, StmtKind}; impl<'a, 'tcx> Translator<'a, 'tcx> { /// Whether a `ty` is copied where Rust copies it: a `Copy` value that is, or holds by - /// value, a JS object Rust code can change in place. + /// value, a JS object the crate's code writes into in place. pub fn needs_copy(&self, ty: Ty<'tcx>) -> bool { - self.is_copy(ty) && self.mutable_aggregate(ty) + self.is_copy(ty) && self.changes(ty) } - fn mutable_aggregate(&self, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::Tuple(tys) => !tys.is_empty(), - ty::Array(..) => true, + /// Whether a value of `ty` is, or holds by value, a JS object the crate writes into. + fn changes(&self, ty: Ty<'tcx>) -> bool { + let (object, parts): (bool, Vec>) = match ty.kind() { + ty::Tuple(tys) if !tys.is_empty() => (true, tys.to_vec()), + ty::Array(elem, _) => (true, vec![*elem]), ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { - // The runtime's methods hand out the payload itself. - Some(Std::Option | Std::Result | Std::ControlFlow | Std::Poll) => { - args.types().any(|t| self.mutable_aggregate(t)) + // Their payload, or no object at all; a write into an `rt.Result`'s payload + // replaces the result. + Some(Std::Option | Std::Poll | Std::Result | Std::ControlFlow) => (false, args.types().collect()), + Some(_) => return false, + None if adt.did().is_local() && adt.all_fields().next().is_some() => { + (true, adt.all_fields().map(|f| self.field_ty(f.did, args)).collect()) } - Some(_) => false, - None => adt.did().is_local() && adt.all_fields().next().is_some(), + None => return false, }, - _ => false, - } + _ => return false, + }; + object && self.writes.written(self.tcx, ty) || parts.into_iter().any(|t| self.changes(t)) } /// `value`, copied if a `ty` is. @@ -192,3 +205,268 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { .unwrap_or_else(|_| field.instantiate(self.tcx, args).skip_norm_wip()) } } + +/// The types the crate's code writes into in place: through a projection, as `p.x = 1` +/// writes into `p`; through a reference or a box, as `*r = v` does into what `r` points +/// at; or by anything code it doesn't read can do with a mutable reference or pointer to +/// one, which counts as a write: one a parameter of a std function the crate names takes, +/// or one kept anywhere but in a local, whose uses tell. Bodies are read as written, over +/// their own type parameters, so a write into a type parameter stands for every type its +/// bounds let it be. +pub struct Writes<'tcx> { + /// Each type written without type parameters, an array as a slice of its element, + /// since the two share storage in JS. + concrete: FxHashSet>, + /// Each type over the type parameters of the body writing it, and that body. + generic: FxIndexSet<(DefId, Ty<'tcx>)>, + /// What [`Writes::written`] found of each type it was asked about. + found: RefCell, bool>>, +} + +impl<'tcx> Writes<'tcx> { + /// The writes of every function, closure, and coroutine body in the crate. + pub fn of_crate(tcx: TyCtxt<'tcx>) -> Self { + let mut writes = Writes { + concrete: FxHashSet::default(), + generic: FxIndexSet::default(), + found: RefCell::default(), + }; + for &def_id in tcx.mir_keys(()) { + if !tcx.def_kind(def_id).is_fn_like() { + continue; + } + let def_id = def_id.to_def_id(); + let body = tcx.optimized_mir(def_id); + BodyWrites { + tcx, + body, + def_id, + writes: &mut writes, + } + .visit_body(body); + } + writes + } + + fn insert(&mut self, tcx: TyCtxt<'tcx>, def_id: DefId, ty: Ty<'tcx>) { + let ty = storage(tcx, ty); + match ty.has_param() { + true => _ = self.generic.insert((def_id, ty)), + false => _ = self.concrete.insert(ty), + } + } + + /// Whether the crate writes into a value of `ty` in place. Over type parameters, as a + /// census lowers some functions, it may. + fn written(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { + let ty = tcx.erase_and_anonymize_regions(ty); + let stored = storage(tcx, ty); + if ty.has_param() || self.concrete.contains(&stored) { + return true; + } + if let Some(&found) = self.found.borrow().get(&ty) { + return found; + } + // A parameter can be the array itself, as in `*dst = value` with `dst: &mut T`, and + // its slice pattern can be any array of that element. + let found = self.generic.iter().any(|&(def_id, written)| { + instantiates(tcx, def_id, written, ty) || stored != ty && instantiates(tcx, def_id, written, stored) + }); + self.found.borrow_mut().insert(ty, found); + found + } +} + +/// `ty` as [`Writes`] keys it: without regions, and an array as a slice of its element. +fn storage<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { + let ty = tcx.erase_and_anonymize_regions(ty); + match ty.kind() { + ty::Array(elem, _) => Ty::new_slice(tcx, *elem), + _ => ty, + } +} + +/// Whether `written`, a type over the type parameters of `def_id`, is `ty` for some +/// arguments that satisfy its bounds. A projection on them, which only those arguments +/// decide, is any type that satisfies its associated type's bounds. +fn instantiates<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, written: Ty<'tcx>, ty: Ty<'tcx>) -> bool { + use rustc_infer::infer::TyCtxtInferExt; + use rustc_infer::traits::{Obligation, ObligationCause}; + use rustc_middle::ty::{BottomUpFolder, TypeFoldable, Upcast}; + use rustc_trait_selection::traits::ObligationCtxt; + if !DeepRejectCtxt::relate_rigid_infer(tcx).types_may_unify(ty, written) { + return false; + } + let (infcx, env) = tcx + .infer_ctxt() + .build_with_typing_env(ty::TypingEnv::fully_monomorphized()); + let ocx = ObligationCtxt::new(&infcx); + let cause = ObligationCause::dummy(); + let register = |clause: ty::Clause<'tcx>| ocx.register_obligation(Obligation::new(tcx, cause.clone(), env, clause)); + let args = infcx.fresh_args_for_item(DUMMY_SP, def_id); + let written = EarlyBinder::bind(tcx, written) + .instantiate(tcx, args) + .skip_normalization(); + let mut projections = Vec::new(); + let written = written.fold_with(&mut BottomUpFolder { + tcx, + ty_op: |t: Ty<'tcx>| match *t.kind() { + ty::Alias( + _, + alias @ ty::AliasTy { + kind: ty::Projection { .. }, + .. + }, + ) => { + let var = infcx.next_ty_var(DUMMY_SP); + projections.push((alias, var)); + var + } + _ => t, + }, + lt_op: |r| r, + ct_op: |c| c, + }); + for (alias, var) in projections { + let ty::Projection { def_id: item } = alias.kind else { + unreachable!("only projections are replaced") + }; + for clause in tcx.item_bounds(item).iter_instantiated(tcx, alias.args) { + let clause = clause.skip_normalization().fold_with(&mut BottomUpFolder { + tcx, + ty_op: |t: Ty<'tcx>| match *t.kind() { + ty::Alias(_, a) if a == alias => var, + _ => t, + }, + lt_op: |r| r, + ct_op: |c| c, + }); + register(ocx.normalize(&cause, env, ty::Unnormalized::new(clause))); + } + let projection = ty::ProjectionClause { + projection_term: alias.into(), + term: var.into(), + }; + register(projection.upcast(tcx)); + } + let written = ocx.normalize(&cause, env, ty::Unnormalized::new(written)); + if ocx.eq(&cause, env, written, ty).is_err() { + return false; + } + for (clause, _) in tcx.clauses_of(def_id).instantiate(tcx, args) { + register(ocx.normalize(&cause, env, clause)); + } + !ocx.try_evaluate_obligations().has_errors() +} + +/// The writes of one body. +struct BodyWrites<'w, 'm, 'tcx> { + tcx: TyCtxt<'tcx>, + body: &'m mir::Body<'tcx>, + def_id: DefId, + writes: &'w mut Writes<'tcx>, +} + +impl<'tcx> BodyWrites<'_, '_, 'tcx> { + fn insert(&mut self, ty: Ty<'tcx>) { + self.writes.insert(self.tcx, self.def_id, ty); + } + + /// What each mutable reference or pointer a value of `ty` holds points at, where code + /// given the value can reach it. What a closure or a coroutine holds only its own body + /// reads, a function holds nothing, and what a trait object holds counted where it + /// became one. + fn pointees(&mut self, ty: Ty<'tcx>) { + let mut stack = vec![ty]; + while let Some(ty) = stack.pop() { + match *ty.kind() { + ty::Ref(_, inner, mutability) | ty::RawPtr(inner, mutability) => { + if mutability.is_mut() { + self.insert(inner); + } + stack.push(inner); + } + ty::Adt(_, args) => stack.extend(args.types()), + ty::Tuple(tys) => stack.extend(tys), + ty::Array(elem, _) | ty::Slice(elem) => stack.push(elem), + _ => {} + } + } + } + + /// Whether the function item `def_id` with `args` is the crate's own, whose body is + /// read, rather than std's or a trait method only an instance resolves. + fn crate_fn(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> bool { + let env = ty::TypingEnv::post_analysis(self.tcx, self.def_id); + matches!( + ty::Instance::try_resolve(self.tcx, env, def_id, args), + Ok(Some(instance)) if matches!(instance.def, ty::InstanceKind::Item(did) if did.is_local()) + ) + } +} + +impl<'tcx> Visitor<'tcx> for BodyWrites<'_, '_, 'tcx> { + fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) { + if place.as_local().is_none() { + self.pointees(place.ty(self.body, self.tcx).ty); + } + if let Rvalue::Cast(mir::CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _), op, to) = rvalue + && to.walk().any(|arg| arg.as_type().is_some_and(|t| t.is_trait())) + { + self.pointees(op.ty(self.body, self.tcx)); + } + self.super_assign(place, rvalue, location); + } + + fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) { + match &terminator.kind { + mir::TerminatorKind::Call { destination, .. } if destination.as_local().is_none() => { + self.pointees(destination.ty(self.body, self.tcx).ty) + } + mir::TerminatorKind::Yield { value, .. } => self.pointees(value.ty(self.body, self.tcx)), + _ => {} + } + self.super_terminator(terminator, location); + } + + /// A function not of the crate, called here or taken as a value that a pointer or a + /// type parameter calls where no call shows: what its parameters take escapes to it. + /// This holds while the runtime writes in place only through such a parameter, as + /// `copy_from_slice` does, never in a std trait impl that a type parameter reaches. + fn visit_operand(&mut self, operand: &mir::Operand<'tcx>, location: Location) { + if let mir::Operand::Constant(constant) = operand + && let ty::FnDef(def_id, args) = *constant.ty().kind() + && !self.crate_fn(def_id, args.skip_binder()) + { + let sig = self + .tcx + .fn_sig(def_id) + .instantiate(self.tcx, args.skip_binder()) + .skip_norm_wip(); + for &input in sig.skip_binder().inputs() { + self.pointees(input); + } + } + self.super_operand(operand, location); + } + + fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _: Location) { + let PlaceContext::MutatingUse(kind) = context else { + return; + }; + // A write to a part of a value writes into the value, unless the part is behind a + // reference, whose referent it writes into instead. + for (base, elem) in place.iter_projections() { + if !matches!(elem, ProjectionElem::Deref) { + self.insert(base.ty(self.body, self.tcx).ty); + } + } + // A write to a whole local gives it another value, but one through a reference or a + // box writes into the value there. + if matches!(place.projection.last(), Some(ProjectionElem::Deref)) + || matches!(kind, MutatingUseContext::SetDiscriminant) + { + self.insert(place.ty(self.body, self.tcx).ty); + } + } +} diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 01e2e0b0d..e4aefac26 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -148,6 +148,8 @@ pub struct Translator<'a, 'tcx> { pub drop_shims: rustc_data_structures::fx::FxHashMap, SymId>, /// The function copying each `Copy` aggregate type. copy_shims: rustc_data_structures::fx::FxHashMap, SymId>, + /// The types the crate writes into in place, which alone are copied. + writes: copy::Writes<'tcx>, /// The class of each coroutine instance. pub coroutines: rustc_data_structures::fx::FxHashMap, mir::coroutine::Info<'tcx>>, /// Whether [`Self::ty`] is typing a variable: see [`Self::held_ty`]. @@ -215,6 +217,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { coroutines: Default::default(), drop_shims: Default::default(), copy_shims: Default::default(), + writes: copy::Writes::of_crate(tcx), held: false, }) } diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 98b30fd84..d30e57711 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -149,9 +149,9 @@ fn typecheck(out: &Path) { } /// Run the harness natively, as wasm32, and translated, on the same inputs: the -/// translated side through `entry`, a module in `out`. `extra` are `differential.ts`'s -/// arguments after the case count. -fn differential(package: &str, out: &Path, entry: &str, cases: u32, extra: &[&str]) { +/// translated side through `entry`, a module in `out`. `features` are the package's, and +/// `extra` are `differential.ts`'s arguments after the case count. +fn differential(package: &str, features: &[&str], out: &Path, entry: &str, cases: u32, extra: &[&str]) { let target_dir = scratch().join("wasm"); let status = cargo() .args([ @@ -164,6 +164,7 @@ fn differential(package: &str, out: &Path, entry: &str, cases: u32, extra: &[&st "--target-dir", ]) .arg(&target_dir) + .args(features.iter().flat_map(|f| ["--features", f])) .arg("--manifest-path") .arg(manifest_dir().join("Cargo.toml")) .status() @@ -197,7 +198,7 @@ fn codec() { snapshot("codec", &out); std::fs::write(out.join("shake.ts"), SHAKE).unwrap(); typecheck(&out); - differential("codec-fixture", &out, "harness.ts", 20_000, &[]); + differential("codec-fixture", &[], &out, "harness.ts", 20_000, &[]); shake(&out); } @@ -265,8 +266,7 @@ fn shake(out: &Path) { "u32Sub", "usizeSaturatingAdd", "usizeSub", - // The translation's, and the caller. The decoder keeps its own copy of the form. - "copy$Form", + // The translation's, and the caller. "new_", "run", "short", @@ -372,7 +372,35 @@ fn lang_differential(out: &Path) { std::fs::copy(manifest_dir().join("fixtures/lang").join(file), out.join(file)).unwrap(); } typecheck(out); - differential("lang-fixture", out, "caller.ts", 50_000, &["wide"]); + differential("lang-fixture", &[], out, "caller.ts", 50_000, &["wide"]); +} + +/// A copy that only one write in the crate keeps, of each kind: one per feature. +#[test] +fn share() { + let out = translated("share"); + snapshot("share", &out); + typecheck(&out); + differential("share-fixture", &[], &out, "harness.ts", 1_000, &[]); + let config = fixture("share").join("ts.toml"); + for feature in ["call", "pointer"] { + let out = scratch().join("share").join(feature); + let args: [&std::ffi::OsStr; 5] = [ + "--out".as_ref(), + out.as_ref(), + "--".as_ref(), + "--features".as_ref(), + feature.as_ref(), + ]; + let output = driver("share", &config, &args, "build"); + assert!( + output.status.success(), + "translating share with {feature} failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + typecheck(&out); + differential("share-fixture", &[feature], &out, "harness.ts", 1_000, &[]); + } } /// Futures and drops: the harness is hand-written TS around the translation, whose FIFO @@ -404,7 +432,7 @@ export const unwind = harness(fixture, true); ); std::fs::write(out.join("caller.ts"), text).unwrap(); typecheck(out); - differential("task-fixture", out, "caller.ts", 20_000, &[]); + differential("task-fixture", &[], out, "caller.ts", 20_000, &[]); unwinding(out, "caller.ts", 5_000); }