diff --git a/quest/m2/README.md b/quest/m2/README.md index fed4211af..14ab2f892 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -32,7 +32,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 by type](/quest/m2/ts-copy.md) - copying a `Copy` aggregate shares its references instead of deep-copying them - [Translate char and vec![x]](/quest/m2/ts-char-vec.md) - `char` values and `vec![x]` translate, unblocking moq-net's refused sites - [Firefox in the TS benchmark](/quest/m2/ts-bench-firefox.md) - SpiderMonkey joins Chrome, Bun, and Node in `just ts bench` - [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-copy.md b/quest/m2/ts-copy.md deleted file mode 100644 index ca8fff2ee..000000000 --- a/quest/m2/ts-copy.md +++ /dev/null @@ -1,23 +0,0 @@ -# [S] Copy by type - -## Goal - -Copying a `Copy` aggregate in translated TypeScript copies its values and shares its -references, as Rust does. Today `rt.copy` deep-copies the aggregate, references -included: copying `(&Cell, u8)` clones the cell, so a write through the copy's -reference changes the clone instead of the original. Differential tests against -native Rust cover tuples, arrays, `Option`, `Result`, and structs holding shared -references to interior-mutable values. - -## Plan - -Decided with the maintainer on 2026-10-26, from a review finding on -[#78](https://github.com/kixelated/rust2/pull/78). The bug predates #78 and is a -silent miscompile, so either fix it or refuse the shapes it can't copy, with a span. - -- Copy by the static type: the lowering knows which fields are references, so it - can emit a shallow copy for those and a value copy for the rest, instead of - one generic `rt.copy`. -- Measure the codec bench before and after; a typed copy should be no slower. - -Public API: the translator's output. diff --git a/quest/m2/ts-shared.md b/quest/m2/ts-shared.md index 31f8f2282..4045e3622 100644 --- a/quest/m2/ts-shared.md +++ b/quest/m2/ts-shared.md @@ -25,9 +25,6 @@ is its own guard. Left: `Rc`, `weak_count` (a dropped `Weak` counts nothing yet) panics. A re-entrant `Mutex` lock on one thread is unspecified in Rust; pick a loud failure (panic) and document it. - Measure the counter overhead on the [TS benchmark](/ts/README.md#bench). -- `rt.copy` copies a `Copy` aggregate deeply, through the shared references in it, - so copying `(&Arc, u8)` copies the `Arc` and its count, or a `Cell` and its - value. Copy only what the type owns. Public API: the translator's output for shared and interior-mutable types. diff --git a/ts/README.md b/ts/README.md index 046a4e8ea..77230df98 100644 --- a/ts/README.md +++ b/ts/README.md @@ -133,9 +133,11 @@ arguments. Types are translated once, generically, so a function of a generic ty instance's, declaring the instance it takes as `self`: `fmt$Debug_Pair(self: Wrap, f: rt.Formatter)`. A type's module exports the type by its own name, which a caller writes `Decoder.Decoder`, and a function whose name -and exports it as its own: `function new_` is `Decoder.new`. A `Copy` struct, tuple, or -array, or an `Option` or `Result` holding one, is copied where Rust copies it, since JS -would share the object. +and exports it as its own: `function new_` is `Decoder.new`. A `Copy` struct, enum, tuple, +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. 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 diff --git a/ts/fixtures/codec/expected/coding/decode.Decoder.ts b/ts/fixtures/codec/expected/coding/decode.Decoder.ts index d56652df5..5e25955be 100644 --- a/ts/fixtures/codec/expected/coding/decode.Decoder.ts +++ b/ts/fixtures/codec/expected/coding/decode.Decoder.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 DecodeError from "../coding/decode.DecodeError.ts"; import { read } from "../coding/varint.ts"; import type * as Form from "../coding/varint.Form.ts"; @@ -81,7 +82,7 @@ export function rest(self: Decoder): Uint8Array { 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, self.form)); + return rt.Ok(new_(_4.value, copy$Form(self.form))); } return _4; } @@ -128,7 +129,7 @@ export function bool(self: Decoder): rt.Result export function varint(self: Decoder): rt.Result { let _0!: rt.Result; const _13: Uint8Array = self.buf; - const _3: Form.Form = self.form; + const _3: Form.Form = copy$Form(self.form); const _2: rt.Result<[rt.u64, Uint8Array], DecodeError.DecodeError> = read(_13, _3); if (_2.ok) { const value: rt.u64 = _2.value[0]; diff --git a/ts/fixtures/codec/expected/coding/version.Versions.ts b/ts/fixtures/codec/expected/coding/version.Versions.ts index 5fb89482a..518b5aa6e 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -1,6 +1,7 @@ // 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"; @@ -93,7 +94,7 @@ export function encode$Encode_Version(self: Versions, w: Encoder.Encoder, versio } export function from$From_Versions(vs: Version.Version[]): Versions { - return { _0: rt.sliceToVec(vs) }; + return { _0: vs.map(copy$Version) }; } //# sourceMappingURL=version.Versions.ts.map diff --git a/ts/fixtures/codec/expected/lib.ts b/ts/fixtures/codec/expected/lib.ts new file mode 100644 index 000000000..28e4aec41 --- /dev/null +++ b/ts/fixtures/codec/expected/lib.ts @@ -0,0 +1,17 @@ +// Generated by rust2-ts. Do not edit. + +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$Version(v: Version.Version): Version.Version { + return { _0: v._0 }; +} + +//# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index fc03f783b..29c5762fc 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$Clash, copy$Rank, copy$Tally, copy$u8_Tally } from "./lib.ts"; import * as Clash from "./collections.Clash.ts"; import * as Dir from "./collections.Dir.ts"; import * as Fussy from "./collections.Fussy.ts"; @@ -195,9 +196,9 @@ 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, rt.copy(local)); + rt.hashInsert(pairs, key, copy$Tally(local)); local.n = 8; - const before: Tally.Tally = rt.copy(rt.hashIndex(pairs, key)); + const before: Tally.Tally = copy$Tally(rt.hashIndex(pairs, key)); const _246: Tally.Tally | undefined = rt.hashGet(pairs, key); if (_246 !== undefined) { _246.n = rt.u16Add(_246.n, 2); @@ -244,7 +245,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return { n: rankByte(k9) as rt.u16 }; }).n & 0xff); } - const copy: rt.HashMap = rt.hashClone(ranks, undefined, rt.copy); + const copy: rt.HashMap = rt.hashClone(ranks, copy$Rank, copy$Tally); const _327: Tally.Tally | undefined = rt.hashGet(copy, { tag: "Low" } as Rank.Rank); if (_327 !== undefined) { _327.n = 119; @@ -265,7 +266,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { return [rt.u8Rem(b8, 8), { n: b8 as rt.u16 }] as [rt.u8, Tally.Tally]; }); const bytes: rt.HashMap = rt.hashExtend(rt.hashNew() as rt.HashMap, _348); - const copy2: rt.HashMap = rt.hashClone(bytes, undefined, rt.copy); + const copy2: rt.HashMap = rt.hashClone(bytes, undefined, copy$Tally); const iter9: rt.Iter = rt.hashValues(copy2); while (true) { const _356: Tally.Tally | rt.Done = iter9.next(); @@ -302,7 +303,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { stamp(stamped); rt.byteVecPush(out, rt.hashLen(stamped) & 0xff); const extended: rt.HashMap = rt.hashNew() as rt.HashMap; - rt.hashExtend(extended, rt.iterMap(rt.hashIter(bytes), rt.copy)); + rt.hashExtend(extended, rt.iterMap(rt.hashIter(bytes), copy$u8_Tally)); const iter12: rt.Iter = rt.hashValues(extended); while (true) { const _409: Tally.Tally | rt.Done = iter12.next(); @@ -326,7 +327,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, rt.u64Eq(_430({ _0: first }), _430({ _0: first ^ 240 })) ? 1 : 0); const _448: [rt.Hasher, Tally.Tally] = [rt.hasher(), { n: first as rt.u16 }]; const h: rt.Hasher = _448[0]; - const counted: Tally.Tally = rt.copy(_448[1]); + const counted: Tally.Tally = copy$Tally(_448[1]); const _453: rt.Hasher = countedHasher(h, counted); const _456: rt.u16 = counted.n; rt.hashInt(_456, _453); @@ -340,7 +341,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, 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 [_224[0], _224[1].n] as [Rank.Rank, rt.u16]; + return [copy$Rank(_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) { @@ -430,7 +431,7 @@ export function hashMaps(kind: rt.u8, data: Uint8Array, 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, rt.copy, rt.copy); + const copy3: rt.HashMap = rt.hashClone(clashes, copy$Clash, copy$Tally); rt.byteVecPush(out, rt.hashLen(copy3) & 0xff); rt.byteVecPush(out, rt.hashContains(copy3, { _0: 1 }) ? 1 : 0); } @@ -963,7 +964,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { return { n: _2 as rt.u16 }; }); const tallies: rt.VecDeque = rt.dequeExtend(rt.dequeNew() as rt.VecDeque, _101); - const copy: rt.VecDeque = rt.dequeClone(tallies, rt.copy); + const copy: rt.VecDeque = rt.dequeClone(tallies, copy$Tally); const _105: Tally.Tally | undefined = rt.dequeEnd(copy); if (_105 !== undefined) { _105.n = _105.n ^ 255; @@ -975,7 +976,7 @@ export function deques(data: Uint8Array, out: rt.ByteVec): void { return t2.n & 0xff; })); const _119: rt.Iter = rt.dequeIter(tallies); - rt.dequeExtend(copy, rt.iterMap(_119, rt.copy)); + rt.dequeExtend(copy, rt.iterMap(_119, copy$Tally)); const _121: Tally.Tally | undefined = rt.dequeEnd(copy, true); if (_121 !== undefined) { _121.n = _121.n ^ 255; diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 79a9f4cd9..859e0761b 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$Pair } from "./lib.ts"; import * as Bare from "./fmt.Bare.ts"; import * as Braced from "./fmt.Braced.ts"; import * as Fails from "./fmt.Fails.ts"; @@ -211,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[] = rt.sliceToVec([{ _0: at(4), _1: -1 }, { _0: 2, _1: rt.i64Of(-9223372036854775808n) }]); + const _40: Pair.Pair[] = [{ _0: at(4), _1: -1 }, { _0: 2, _1: rt.i64Of(-9223372036854775808n) }].map(copy$Pair); if (!(rt.u8Rem(at(5), 2) === 0)) { _49 = undefined; } else { @@ -304,14 +305,14 @@ export function written(data: Uint8Array, out: rt.ByteVec): void { const arg = ([{ _0: "pad" }] as [Padded.Padded])[0]; const args4: rt.Fmt[] = [(f: rt.Formatter) => Padded.fmt$Display(arg, f)]; put(out, rt.fmtFormat([args4[0], "|", rt.fmtSpec({ align: ">", width: 6 }, args4[0]), "|", rt.fmtSpec({ fill: "_", align: "^", width: 9 }, args4[0]), "|", rt.fmtSpec({ width: 30 }, args4[0]), "|"])); - [{ id: at(1), list: rt.sliceToVec([1, at(2) as rt.u16]) }, { id: 0, list: [] }] as [Manual.Manual, Manual.Manual]; - const arg2 = { id: at(1), list: rt.sliceToVec([1, at(2) as rt.u16]) }; + [{ id: at(1), list: [1, at(2) as rt.u16].slice() }, { id: 0, list: [] }] as [Manual.Manual, Manual.Manual]; + const arg2 = { id: at(1), list: [1, at(2) as rt.u16].slice() }; const _66: rt.Fmt = (f: rt.Formatter) => Manual.fmt$Debug(arg2, f); 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: rt.sliceToVec([{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }]) }, { _0: [] }] as [Seq.Seq, Seq.Seq]; - const arg4 = { _0: rt.sliceToVec([{ _0: at(3), _1: 0 }, { _0: 1, _1: -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) }; 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.Either.ts b/ts/fixtures/lang/expected/generics.Either.ts index 55812552c..a1e338ba8 100644 --- a/ts/fixtures/lang/expected/generics.Either.ts +++ b/ts/fixtures/lang/expected/generics.Either.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$Point } from "./lib.ts"; import * as Point from "./shapes.Point.ts"; export function fmt$Debug_Point_u8(self: Either, f: rt.Formatter): rt.Result { @@ -53,7 +54,7 @@ export type Either = { tag: "Left"; _0: L } | { tag: "Right"; value: R } | export function left$Point_u8(self: Either): Point.Point | undefined { if (self.tag === "Left") { - return rt.copy(self._0); + return copy$Point(self._0); } return undefined; } diff --git a/ts/fixtures/lang/expected/generics.Tagged.ts b/ts/fixtures/lang/expected/generics.Tagged.ts index 32edc8610..e99537c33 100644 --- a/ts/fixtures/lang/expected/generics.Tagged.ts +++ b/ts/fixtures/lang/expected/generics.Tagged.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$Option_Wrap_i16 } from "./lib.ts"; import * as Either from "./generics.Either.ts"; import * as Wrap from "./generics.Wrap.ts"; @@ -29,7 +30,7 @@ export class Tagged { } export function first$Either_u8_u16_i16(self: Tagged, rt.i16>): Wrap.Wrap | undefined { - return rt.copy(rt.sliceFirst(self.all)); + return copy$Option_Wrap_i16(rt.sliceFirst(self.all)); } //# sourceMappingURL=generics.Tagged.ts.map diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index 8d75c4e92..a37d3b059 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -1,6 +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 { put } from "./fmt.ts"; import type * as Pair from "./fmt.Pair.ts"; import * as Either from "./generics.Either.ts"; @@ -15,9 +16,9 @@ export function methods(data: Uint8Array, out: rt.ByteVec): void { const at: (a0: rt.usize) => rt.u8 = (i: rt.usize): rt.u8 => { return rt.optionUnwrapOr(rt.sliceGet(data, i), 0); }; - const point: Wrap.Wrap = rt.copy(Wrap.new$Point({ x: at(0) as rt.i32, y: -2 })); + const point: Wrap.Wrap = copy$Wrap_Point(Wrap.new$Point({ x: at(0) as rt.i32, y: -2 })); Wrap.bump$Point(point); - const byte: Wrap.Wrap = rt.copy(Wrap.new$u8(at(1))); + const byte: Wrap.Wrap = copy$Wrap_u8(Wrap.new$u8(at(1))); Wrap.bump$u8(byte); Wrap.bump$u8(byte); const nested: Wrap.Wrap> = Wrap.new$Wrap_Pair(Wrap.new$Pair({ _0: at(2), _1: -3 })); @@ -71,7 +72,7 @@ export function methods(data: Uint8Array, out: rt.ByteVec): void { const _193: rt.u8 = rt.optionUnwrapOr(Wrap.get$Option_u8(none), some.count); const args10: rt.Fmt[] = [(f: rt.Formatter) => Wrap.fmt$Debug_Vec_u16(list, f), (f: rt.Formatter) => Wrap.fmt$Debug_Option_u8(none, f), (f: rt.Formatter) => Wrap.fmt$Debug_Option_u8(some, f), (f: rt.Formatter) => Wrap.fmt$Debug_Result_u8_Shape(err, f), (f: rt.Formatter) => rt.u8Display(_193, f)]; put(out, rt.fmtFormat([args10[0], " ", args10[1], " ", args10[2], " ", args10[3], " ", args10[4]])); - const tagged: Tagged.Tagged, rt.i16> = new Tagged.Tagged({ key: { tag: "Right", value: 500 } as Either.Either, inner: Wrap.new$i16(rt.i16Sub(at(8) as rt.i16, 100)), all: rt.sliceToVec([Wrap.new$i16(-1), Wrap.new$i16(at(9) as rt.i16)]) }); + const tagged: Tagged.Tagged, rt.i16> = new Tagged.Tagged({ key: { tag: "Right", value: 500 } as Either.Either, inner: Wrap.new$i16(rt.i16Sub(at(8) as rt.i16, 100)), all: [Wrap.new$i16(-1), Wrap.new$i16(at(9) as rt.i16)].map(copy$Wrap_i16) }); [Tagged.first$Either_u8_u16_i16(tagged), tagged] as [Wrap.Wrap | undefined, Tagged.Tagged, rt.i16>]; const _241: rt.Fmt = (f: rt.Formatter) => Tagged.fmt$Debug_Either_u8_u16_i16(tagged, f); const arg5 = Tagged.first$Either_u8_u16_i16(tagged); diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 6fe0d81a7..37199d91e 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$Bumped, copy$u8s } from "./lib.ts"; import * as Bumped from "./iters.Bumped.ts"; import * as Countdown from "./iters.Countdown.ts"; import * as Doubled from "./iters.Doubled.ts"; @@ -124,7 +125,7 @@ export function adaptors(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const b3: rt.u8 = _2; return Uint8Array.of(b3, ~b3 & 0xff); })); - const copies: Uint8Array[] = rt.iterToArray(rt.iterMap(rt.iterSlice(pairs), rt.copy)); + const copies: Uint8Array[] = rt.iterToArray(rt.iterMap(rt.iterSlice(pairs), copy$u8s)); if (!((copies.length === 0))) { const at = rt.idx(copies, 0); copies[at][0] = 85; @@ -665,7 +666,7 @@ export function values(data: Uint8Array, out: rt.ByteVec): void { rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(bumps), Bumped.clone$Clone), (b5: Bumped.Bumped): rt.u8 => { return b5._0; })); - rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(bumps), rt.copy), (b6: Bumped.Bumped): rt.u8 => { + rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(bumps), copy$Bumped), (b6: Bumped.Bumped): rt.u8 => { return b6._0; })); rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(rt.iterToArray(rt.iterMap(rt.iterSlice(data), (_23: rt.u8): Wrapper.Wrapper => { diff --git a/ts/fixtures/lang/expected/keys.ts b/ts/fixtures/lang/expected/keys.ts index 1dd178e3a..7856735d7 100644 --- a/ts/fixtures/lang/expected/keys.ts +++ b/ts/fixtures/lang/expected/keys.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$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"; @@ -289,7 +290,7 @@ export function options(data: Uint8Array, out: rt.ByteVec): void { }))); rt.byteVecPush(out, (_310[0][1].exclude !== undefined ? 1 : 0) | (((_310[0][1].local ? 1 : 0) << 1) & 0xff)); rt.byteVecPush(out, _310[1]); - rt.byteVecPush(out, rt.hashIndex(hashed, [_310[0][0], rt.copy(_310[0][1])] as [rt.u8, Horizon.Horizon])); + rt.byteVecPush(out, rt.hashIndex(hashed, [_310[0][0], copy$Horizon(_310[0][1])] as [rt.u8, Horizon.Horizon])); } } catch (e) { b4: { diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts new file mode 100644 index 000000000..64b392a6f --- /dev/null +++ b/ts/fixtures/lang/expected/lib.ts @@ -0,0 +1,146 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as Clash from "./collections.Clash.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 * 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"; + +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); +} + +export function copy$ControlFlow_unit_u8s(v: rt.Result): rt.Result { + return v.ok ? rt.Ok(copy$u8s(v.value)) : rt.Err(v.error); +} + +export function copy$Held(v: Held.Held): Held.Held { + return { at: copy$Point(v.at) }; +} + +export function copy$Hop(v: Hop.Hop): Hop.Hop { + return { _0: v._0 }; +} + +export function copy$Horizon(v: Horizon.Horizon): Horizon.Horizon { + return { exclude: copy$Option_Hop(v.exclude), local: v.local }; +} + +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]]; +} + +export function copy$Mutex_u8s(v: rt.Mutex[]): rt.Mutex[] { + return v.slice(); +} + +export function copy$Option_Hop(v: Hop.Hop | undefined): Hop.Hop | undefined { + return v === undefined ? v : copy$Hop(v); +} + +export function copy$Option_Mutex_u8_u8(v: [rt.Mutex, rt.u8] | undefined): [rt.Mutex, rt.u8] | undefined { + return v === undefined ? v : copy$Mutex_u8_u8(v); +} + +export function copy$Option_Wrap_i16(v: Wrap.Wrap | undefined): Wrap.Wrap | undefined { + return v === undefined ? v : copy$Wrap_i16(v); +} + +export function copy$Pair(v: Pair.Pair): 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 }; +} + +export function copy$Point_u8(v: [Point.Point, rt.u8]): [Point.Point, rt.u8] { + return [copy$Point(v[0]), v[1]]; +} + +export function copy$Points(v: Point.Point[]): Point.Point[] { + return v.map(copy$Point); +} + +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); +} + +export function copy$Shape(v: Shape.Shape): Shape.Shape { + if (v.tag === "Line") { + return { tag: "Line", _0: copy$Point(v._0), _1: copy$Point(v._1) }; + } + if (v.tag === "Rect") { + return { tag: "Rect", corner: copy$Point(v.corner), width: v.width, height: v.height }; + } + return v; +} + +export function copy$Tally(v: Tally.Tally): Tally.Tally { + return { n: v.n }; +} + +export function copy$Wrap_Point(v: Wrap.Wrap): Wrap.Wrap { + return new Wrap.Wrap({ value: copy$Point(v.value), count: v.count }); +} + +export function copy$Wrap_i16(v: Wrap.Wrap): Wrap.Wrap { + return new Wrap.Wrap({ value: v.value, count: v.count }); +} + +export function copy$Wrap_u8(v: Wrap.Wrap): Wrap.Wrap { + return new Wrap.Wrap({ value: v.value, count: v.count }); +} + +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_u8(v: [rt.u8, rt.u8]): [rt.u8, rt.u8] { + return [v[0], v[1]]; +} + +export function copy$u8s(v: Uint8Array): Uint8Array { + return v.slice(); +} + +//# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Held.ts b/ts/fixtures/lang/expected/shapes.Held.ts new file mode 100644 index 000000000..a5321ef89 --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Held.ts @@ -0,0 +1,10 @@ +// Generated by rust2-ts. Do not edit. + +import type * as Point from "./shapes.Point.ts"; + +/** A `Copy` struct holding another by value. */ +export interface Held { + at: Point.Point; +} + +//# sourceMappingURL=shapes.Held.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Lens.ts b/ts/fixtures/lang/expected/shapes.Lens.ts new file mode 100644 index 000000000..c86f9609a --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Lens.ts @@ -0,0 +1,11 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A `Copy` struct holding a shared reference to a value that changes through it. */ +export interface Lens { + slot: rt.Mutex; + n: rt.u8; +} + +//# sourceMappingURL=shapes.Lens.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Mover.ts b/ts/fixtures/lang/expected/shapes.Mover.ts new file mode 100644 index 000000000..851592240 --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Mover.ts @@ -0,0 +1,10 @@ +// Generated by rust2-ts. Do not edit. + +import type * as Held from "./shapes.Held.ts"; + +/** A mutable borrow of a `Held`, held by value. */ +export interface Mover { + held: Held.Held; +} + +//# sourceMappingURL=shapes.Mover.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Point.ts b/ts/fixtures/lang/expected/shapes.Point.ts index 8f90f1feb..e8ec4a997 100644 --- a/ts/fixtures/lang/expected/shapes.Point.ts +++ b/ts/fixtures/lang/expected/shapes.Point.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { copy$Point } from "./lib.ts"; export function fmt$Debug(self: Point, f: rt.Formatter): rt.Result { const _3: string = "Point"; @@ -30,9 +31,9 @@ function new_(x: rt.i32, y: rt.i32): Point { /** Changes `self`, which a caller's copy must not see. */ export function shift(self: Point, by: rt.i32): Point { - self = rt.copy(self); + self = copy$Point(self); self.x = rt.i32Add(self.x, by); - return rt.copy(self); + return copy$Point(self); } export function bump(self: Point): void { diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 80dd21579..c6c44016d 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1,10 +1,14 @@ // 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 * as Pair from "./fmt.Pair.ts"; import type * as Dir from "./shapes.Dir.ts"; +import type * as Held from "./shapes.Held.ts"; +import type * as Lens from "./shapes.Lens.ts"; import * as Meters from "./shapes.Meters.ts"; import * as Moved from "./shapes.Moved.ts"; +import type * as Mover from "./shapes.Mover.ts"; import * as Point from "./shapes.Point.ts"; import * as Shape from "./shapes.Shape.ts"; import type * as Signed from "./shapes.Signed.ts"; @@ -81,24 +85,27 @@ export function shape(data: Uint8Array): Shape.Shape { /** `Copy` aggregates: a copy changes apart from its original. */ export function copies(data: Uint8Array, out: rt.ByteVec): void { + let _211!: Uint8Array; + let poll!: rt.Poll; + let _246!: rt.u8; const p: Point.Point = Point.new(rt.optionUnwrapOr(rt.sliceFirst(data), 0) as rt.i32, 7); - const q: Point.Point = rt.copy(p); + const q: Point.Point = copy$Point(p); const _9: rt.i32 = rt.i32Add(q.x, 100); q.x = _9; Point.bump(q); const r: Point.Point = Point.shift(p, 5); - const pair: [Point.Point, rt.u8] = [rt.copy(p), 3]; - const saved: [Point.Point, rt.u8] = rt.copy(pair); + const pair: [Point.Point, rt.u8] = [copy$Point(p), 3]; + const saved: [Point.Point, rt.u8] = copy$Point_u8(pair); pair[0].y = -1; pair[1] = rt.u8Add(pair[1], 1); - const item = rt.copy(p); + const item = copy$Point(p); const grid: Point.Point[] = Array.from({ length: 3 }, (): Point.Point => { - return rt.copy(item); + return copy$Point(item); }); grid[1].x = 9; - const row: Point.Point[] = rt.copy(grid); - const _20: Point.Point = rt.copy(q); - grid[2] = rt.copy(_20); + const row: Point.Point[] = copy$Points(grid); + const _20: Point.Point = copy$Point(q); + grid[2] = copy$Point(_20); const _25: rt.i32 = p.x; const _26: rt.i32 = p.y; const _27: rt.i32 = q.x; @@ -119,25 +126,25 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, saved[1]); rt.byteVecPush(out, pair[1]); rt.byteVecPush(out, Point.eq$PartialEq(p, saved[0]) ? 1 : 0); - let a: Point.Point = rt.copy(Point.new(1, 2)); - let b: Point.Point = rt.copy(Point.new(3, 4)); + let a: Point.Point = copy$Point(Point.new(1, 2)); + let b: Point.Point = copy$Point(Point.new(3, 4)); const swapped = a; a = b; b = swapped; const _66: Point.Point = Point.new(5, 6); const old2 = a; - a = rt.copy(_66); + a = copy$Point(_66); const old: Point.Point = old2; const _71: rt.u8 = a.x & 0xff; const _73: rt.u8 = b.x & 0xff; rt.byteVecExtendFromSlice(out, Uint8Array.of(_71, _73, old.x & 0xff)); const boxed: Moved.Moved = { _0: data.length & 0xff, _1: 0 }; const _81: rt.u16 = rt.u16Add(boxed._1, 1); - const _198: Moved.Moved = boxed; - _198._1 = _81; + const _257: Moved.Moved = boxed; + _257._1 = _81; const _83: rt.u16 = rt.u16Add(boxed._1, 2); - const _195: Moved.Moved = boxed; - _195._1 = _83; + const _254: Moved.Moved = boxed; + _254._1 = _83; rt.byteVecExtendFromSlice(out, Uint8Array.of(boxed._0)); rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(boxed._1)); let n: rt.u32 = data.length as rt.u32; @@ -149,9 +156,9 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { word[0] = 9; rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(rt.u32Add(converted, word[0] as rt.u32))); const cell: Uint8Array = Uint8Array.of(data.length & 0xff); - rt.byteVecPush(out, writeThenRead(rt.copy(cell), cell)); + rt.byteVecPush(out, writeThenRead(copy$u8s(cell), cell)); const source: Uint8Array = Uint8Array.of(data.length & 0xff); - const returned: Uint8Array = same(rt.copy(source)); + const returned: Uint8Array = same(copy$u8s(source)); source[0] = 9; const _145: rt.u8 = returned[0]; rt.byteVecExtendFromSlice(out, Uint8Array.of(_145, source[0])); @@ -159,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 = rt.copy({ _0: 9 }); + let opt: Meters.Meters | undefined = copy$Meters({ _0: 9 }); const taken2 = opt; opt = undefined; const taken: Meters.Meters | undefined = taken2; @@ -168,12 +175,274 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { return m._0; }))); const res: rt.Result = rt.Ok(p); - const first: Point.Point = rt.copy(rt.resultUnwrap(res, rt.u8Display)); + const first: Point.Point = copy$Point(rt.resultUnwrap(res, rt.u8Display)); first.x = 2; - const fail: rt.Result = rt.Err(rt.copy(q)); - const err: Point.Point = rt.copy(rt.resultUnwrapErr(fail, rt.u8Display)); + const fail: rt.Result = rt.Err(copy$Point(q)); + const err: Point.Point = copy$Point(rt.resultUnwrapErr(fail, rt.u8Display)); err.y = 3; rt.byteVecExtendFromSlice(out, Uint8Array.of(first.x & 0xff, rt.resultUnwrap(res, rt.u8Display).x & 0xff, err.y & 0xff, rt.resultUnwrapErr(fail, rt.u8Display).y & 0xff)); + const shape_: Shape.Shape = copy$Shape(shape(data)); + const before: Shape.Shape = copy$Shape(shape_); + if (shape_.tag !== "Dot") { + if (shape_.tag === "Line") { + shape_._0.x = 77; + } else { + shape_.corner.y = 5; + shape_.width = 6; + } + } + const iter2: rt.Iter = rt.iterSlice([before, copy$Shape(shape_)]); + while (true) { + const _204: Shape.Shape | rt.Done = iter2.next(); + if (_204 === rt.DONE) { + break; + } + const shape2: Shape.Shape = _204; + if (shape2.tag === "Dot") { + _211 = rt.bytes(3); + } else if (shape2.tag === "Line") { + const from: Point.Point = shape2._0; + _211 = Uint8Array.of(1, from.x & 0xff, from.y & 0xff); + } else { + const corner: Point.Point = shape2.corner; + const width: rt.u16 = shape2.width; + const _220: rt.u8 = corner.x & 0xff; + const _222: rt.u8 = corner.y & 0xff; + _211 = Uint8Array.of(_220, _222, width & 0xff); + } + rt.byteVecExtendFromSlice(out, _211); + } + if (rt.usizeRem(data.length, 2) === 0) { + poll = rt.Pending; + } else { + poll = copy$u8s(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)]); + while (true) { + const _241: rt.Poll | rt.Done = iter3.next(); + if (_241 === rt.DONE) { + break; + } + const poll2: rt.Poll = _241; + if (poll2 !== rt.Pending) { + const bytes2: Uint8Array = poll2; + _246 = bytes2[0]; + } else { + _246 = 255; + } + rt.byteVecPush(out, _246); + } + shares(data, out); +} + +/** Adds one to what `slot` holds. */ +export function bump(slot: rt.Mutex): void { + const held: rt.Mutex = slot; + const _4: rt.u8 = rt.u8WrappingAdd(held.value, 1); + held.value = _4; +} + +/** + * `Copy` aggregates holding shared references: a copy has its own values, and shares + * what its references point at with the original's. + */ +export function shares(data: Uint8Array, out: rt.ByteVec): void { + let res!: rt.Result<[rt.Mutex, rt.u8], rt.u8>; + let n!: rt.u8; + let arc!: rt.Arc; + let flow!: rt.Result>; + let unwind: number = 0; + try { + const a: rt.u8 = rt.optionUnwrapOr(rt.sliceFirst(data), 0); + const slot: rt.Mutex = new rt.Mutex(a); + const other: rt.Mutex = new rt.Mutex(0); + const pair: [rt.Mutex, rt.u8] = [slot, a]; + const copy: [rt.Mutex, rt.u8] = copy$Mutex_u8_u8(pair); + copy[1] = rt.u8WrappingAdd(copy[1], 1); + bump(copy[0]); + bump(slot); + rt.byteVecExtendFromSlice(out, Uint8Array.of(a, copy[1])); + const refs: rt.Mutex[] = [slot, other]; + const copy2: rt.Mutex[] = copy$Mutex_u8s(refs); + bump(copy2[0]); + copy2[1] = slot; + bump(copy2[1]); + bump(refs[1]); + const held: [rt.Mutex, rt.u8] | undefined = [slot, a]; + const copy3: [rt.Mutex, rt.u8] | undefined = copy$Option_Mutex_u8_u8(held); + if (copy3 !== undefined) { + bump(copy3[0]); + const _45: rt.u8 = rt.u8WrappingAdd(copy3[1], 2); + copy3[1] = _45; + } + unwind = 0; + const iter: rt.Iter<[rt.Mutex, rt.u8] | undefined> = rt.iterSlice([held, copy$Option_Mutex_u8_u8(copy3)]); + while (true) { + const _51: [rt.Mutex, rt.u8] | undefined | rt.Done = iter.next(); + if (_51 === rt.DONE) { + break; + } + rt.byteVecPush(out, rt.optionMapOr(_51, 0, (_2: [rt.Mutex, rt.u8]): rt.u8 => { + return _2[1]; + })); + } + if (!(rt.u8Rem(a, 2) === 0)) { + res = rt.Err(a); + } else { + res = rt.Ok([slot, a] as [rt.Mutex, rt.u8]); + } + const copy4: rt.Result<[rt.Mutex, rt.u8], rt.u8> = copy$Result_Mutex_u8_u8_u8(res); + if (copy4.ok) { + bump(copy4.value[0]); + const _69: rt.u8 = rt.u8WrappingAdd(copy4.value[1], 3); + copy4.value[1] = _69; + } + unwind = 0; + const iter2: rt.Iter, rt.u8], rt.u8>> = rt.iterSlice([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) { + break; + } + const r: rt.Result<[rt.Mutex, rt.u8], rt.u8> = _76; + if (r.ok) { + n = r.value[1]; + } else { + n = r.error; + } + rt.byteVecPush(out, n); + } + const lens: Lens.Lens = { slot, n: a }; + const copy5: Lens.Lens = copy$Lens(lens); + copy5.n = rt.u8WrappingAdd(copy5.n, 4); + bump(copy5.slot); + rt.byteVecExtendFromSlice(out, Uint8Array.of(a, copy5.n)); + rt.byteVecPush(out, lensBumped(lens)); + const iterS: Lens.Lens[] = Array.from({ length: 2 }, (): Lens.Lens => { + return copy$Lens(lens); + }).map(copy$Lens); + let iterI: number = 0; + while (true) { + const _104: Lens.Lens | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_104 === rt.DONE) { + break; + } + bump(_104.slot); + } + const lenses: Lens.Lens[] = []; + lenses.push(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); + while (true) { + const _124: Lens.Lens | rt.Done = iter4.next(); + if (_124 === rt.DONE) { + break; + } + bump(_124.slot); + } + arc = new rt.Arc(a); + unwind = 102; + if (rt.u8Rem(a, 3) === 0) { + flow = rt.Ok(Uint8Array.of(a)); + } else { + flow = rt.Err(arc); + } + rt.byteVecPush(out, sameArc(flow, arc)); + const _143: rt.Mutex = slot; + unwind = 101; + rt.byteVecPush(out, _143.value); + unwind = 102; + const _150: rt.Mutex = other; + unwind = 100; + rt.byteVecPush(out, _150.value); + unwind = 102; + const source: Held.Held = { at: copy$Point(Point.new(a as rt.i32, 0)) }; + const kept: Held.Held = hold(copy$Point(source.at)); + source.at.x = 9; + const read: rt.i32 = movedThenRead(copy$Point(source.at), source); + const by: rt.i32 = movedBy(copy$Point(source.at), { held: source }); + const part: rt.i32 = partMovedThenRead(copy$Held(source), source.at); + const _172: rt.u8 = kept.at.x & 0xff; + rt.byteVecExtendFromSlice(out, Uint8Array.of(_172, read & 0xff, by & 0xff, part & 0xff, source.at.x & 0xff)); + unwind = 102; + const bytes: Uint8Array = Uint8Array.of(a, 1); + rt.byteVecPush(out, unsizedCopy(bytes)); + rt.byteVecPush(out, bytes[0]); + unwind = 0; + rt.drop(arc); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(arc); + throw e; + } +} + +/** `at`, held. */ +export function hold(at: Point.Point): Held.Held { + return { at }; +} + +/** `copy.x`, read after `held` moves right by one, which a copy of its point doesn't see. */ +export function movedThenRead(copy: Point.Point, held: Held.Held): rt.i32 { + const _3: rt.i32 = rt.i32Add(held.at.x, 1); + held.at.x = _3; + return copy.x; +} + +/** + * `copy.at.x`, read after `at` moves right by one, which a copy of what holds it doesn't + * see. + */ +export function partMovedThenRead(copy: Held.Held, at: Point.Point): rt.i32 { + at.x = rt.i32Add(at.x, 1); + return copy.at.x; +} + +/** `copy[0]`, read after `live`, its source unsized, changes. */ +export function sliceChangedThenRead(copy: Uint8Array, live: Uint8Array): rt.u8 { + rt.sliceCopyFromSlice(live, Uint8Array.of(9, 9)); + return copy[0]; +} + +/** `src[0]` as it was, read after a call changes it through a slice. */ +export function unsizedCopy(src: Uint8Array): rt.u8 { + return sliceChangedThenRead(copy$u8s(src), src); +} + +/** `copy.x`, read after `by` moves what it holds right by one. */ +export function movedBy(copy: Point.Point, by: Mover.Mover): rt.i32 { + const _3: rt.i32 = rt.i32Add(by.held.at.y, 1); + by.held.at.y = _3; + const _4: rt.i32 = rt.i32Add(by.held.at.x, 1); + by.held.at.x = _4; + return copy.x; +} + +/** A `Lens` changed in place, which changes its slot too. */ +export function lensBumped(lens: Lens.Lens): rt.u8 { + lens = copy$Lens(lens); + lens.n = rt.u8WrappingAdd(lens.n, 5); + bump(lens.slot); + return lens.n; +} + +/** Whether `flow` breaks with `arc` itself, after changing its own bytes in place. */ +export function sameArc(flow: rt.Result>, arc: rt.Arc): rt.u8 { + flow = copy$ControlFlow_Arc_u8_u8s(flow); + if (flow.ok) { + const _5: rt.u8 = rt.u8WrappingAdd(flow.value[0], 1); + flow.value[0] = _5; + return flow.value[0]; + } + return flow.error === arc ? 1 : 0; } /** `a`'s byte, after writing `b`'s. */ @@ -184,8 +453,8 @@ export function writeThenRead(a: Uint8Array, b: Uint8Array): rt.u8 { /** A copy of `a` read after `a` changes in place, which it doesn't see. */ export function copyThenWrite(a: [rt.u8, rt.u8]): rt.u8 { - a = rt.copy(a); - const b: [rt.u8, rt.u8] = rt.copy(a); + a = copy$u8_u8(a); + const b: [rt.u8, rt.u8] = copy$u8_u8(a); a[0] = 9; return rt.u8WrappingAdd(b[0], a[0]); } @@ -1289,12 +1558,12 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, 253); } const original: rt.Result = rt.Ok(Uint8Array.of(a, 1)); - const copied: rt.Result = rt.copy(original); + const copied: rt.Result = copy$ControlFlow_unit_u8s(original); if (copied.ok) { const _83: rt.u8 = rt.u8WrappingAdd(copied.value[0], 1); copied.value[0] = _83; } - const iter2: rt.Iter> = rt.iterSlice([original, rt.copy(copied)]); + const iter2: rt.Iter> = rt.iterSlice([original, copy$ControlFlow_unit_u8s(copied)]); while (true) { const _93: rt.Result | rt.Done = iter2.next(); if (_93 === rt.DONE) { diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index d3054c0b5..2914e447a 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -2,7 +2,7 @@ use std::convert::Infallible; use std::ops::ControlFlow; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::task::Poll; use crate::fmt::Pair; @@ -235,6 +235,210 @@ pub fn copies(data: &[u8], out: &mut Vec) { err.y as u8, fail.unwrap_err().y as u8, ]); + + // An enum's and a `Poll`'s payload changes in place apart from a copy's. + let mut shape = shape(data); + let before = shape; + match &mut shape { + Shape::Dot => {} + Shape::Line(from, _) => from.x = 77, + Shape::Rect { corner, width, .. } => { + corner.y = 5; + *width = 6; + } + } + for shape in [before, shape] { + out.extend_from_slice(&match shape { + Shape::Dot => [0; 3], + Shape::Line(from, _) => [1, from.x as u8, from.y as u8], + Shape::Rect { corner, width, .. } => [corner.x as u8, corner.y as u8, width as u8], + }); + } + let mut poll = match data.len() % 2 { + 0 => Poll::Pending, + _ => Poll::Ready([data.len() as u8]), + }; + let polled = poll; + if let Poll::Ready(ref mut bytes) = poll { + bytes[0] = 9; + } + for poll in [polled, poll] { + out.push(match poll { + Poll::Ready(bytes) => bytes[0], + Poll::Pending => 0xff, + }); + } + shares(data, out); +} + +/// A `Copy` struct holding a shared reference to a value that changes through it. +#[derive(Clone, Copy)] +struct Lens<'a> { + slot: &'a Mutex, + n: u8, +} + +/// Adds one to what `slot` holds. +fn bump(slot: &Mutex) { + let mut held = slot.lock().unwrap(); + *held = held.wrapping_add(1); +} + +/// `Copy` aggregates holding shared references: a copy has its own values, and shares +/// what its references point at with the original's. +fn shares(data: &[u8], out: &mut Vec) { + let a = data.first().copied().unwrap_or(0); + let slot = Mutex::new(a); + let other = Mutex::new(0); + + let pair = (&slot, a); + let mut copy = pair; + copy.1 = copy.1.wrapping_add(1); + bump(copy.0); + bump(pair.0); + out.extend_from_slice(&[pair.1, copy.1]); + + let refs = [&slot, &other]; + let mut copy = refs; + bump(copy[0]); + copy[1] = &slot; + bump(copy[1]); + bump(refs[1]); + + let held = Some((&slot, a)); + let mut copy = held; + if let Some((held, ref mut n)) = copy { + bump(held); + *n = n.wrapping_add(2); + } + for held in [held, copy] { + out.push(held.map_or(0, |(_, n)| n)); + } + + let res: Result<(&Mutex, u8), u8> = if a % 2 == 0 { Ok((&slot, a)) } else { Err(a) }; + let mut copy = res; + if let Ok((held, n)) = &mut copy { + bump(held); + *n = n.wrapping_add(3); + } + for r in [res, copy] { + out.push(match r { + Ok((_, n)) | Err(n) => n, + }); + } + + let lens = Lens { slot: &slot, n: a }; + let mut copy = lens; + copy.n = copy.n.wrapping_add(4); + bump(copy.slot); + out.extend_from_slice(&[lens.n, copy.n]); + out.push(lens_bumped(lens)); + + // Copied out of a slice and a collection, each still points at the original. + for lens in [lens; 2].to_vec() { + bump(lens.slot); + } + let mut lenses = Vec::new(); + lenses.push(lens); + lenses.extend([lens].iter()); + for lens in lenses.iter().copied() { + bump(lens.slot); + } + + let arc = Arc::new(a); + let flow: ControlFlow<&Arc, [u8; 1]> = match a % 3 { + 0 => ControlFlow::Continue([a]), + _ => ControlFlow::Break(&arc), + }; + out.push(same_arc(flow, &arc)); + + out.push(*slot.lock().unwrap()); + out.push(*other.lock().unwrap()); + + // An argument copied into what a call returns, or read after the call changes its + // source through another argument, keeps its value. + let mut source = Held { + at: Point::new(a as i32, 0), + }; + let kept = hold(source.at); + source.at.x = 9; + let read = moved_then_read(source.at, &mut source); + let by = moved_by(source.at, Mover { held: &mut source }); + let part = part_moved_then_read(source, &mut source.at); + out.extend_from_slice(&[kept.at.x as u8, read as u8, by as u8, part as u8, source.at.x as u8]); + let mut bytes = [a, 1]; + out.push(unsized_copy(&mut bytes)); + out.push(bytes[0]); +} + +/// A `Copy` struct holding another by value. +#[derive(Clone, Copy)] +struct Held { + at: Point, +} + +/// `at`, held. +#[inline(never)] +fn hold(at: Point) -> Held { + Held { at } +} + +/// `copy.x`, read after `held` moves right by one, which a copy of its point doesn't see. +#[inline(never)] +fn moved_then_read(copy: Point, held: &mut Held) -> i32 { + held.at.x += 1; + copy.x +} + +/// `copy.at.x`, read after `at` moves right by one, which a copy of what holds it doesn't +/// see. +#[inline(never)] +fn part_moved_then_read(copy: Held, at: &mut Point) -> i32 { + at.x += 1; + copy.at.x +} + +/// `copy[0]`, read after `live`, its source unsized, changes. +#[inline(never)] +fn slice_changed_then_read(copy: [u8; 2], live: &mut [u8]) -> u8 { + live.copy_from_slice(&[9, 9]); + copy[0] +} + +/// `src[0]` as it was, read after a call changes it through a slice. +fn unsized_copy(src: &mut [u8; 2]) -> u8 { + slice_changed_then_read(*src, src) +} + +/// A mutable borrow of a `Held`, held by value. +struct Mover<'a> { + held: &'a mut Held, +} + +/// `copy.x`, read after `by` moves what it holds right by one. +#[inline(never)] +fn moved_by(copy: Point, by: Mover) -> i32 { + by.held.at.y += 1; + by.held.at.x += 1; + copy.x +} + +/// A `Lens` changed in place, which changes its slot too. +fn lens_bumped(mut lens: Lens) -> u8 { + lens.n = lens.n.wrapping_add(5); + bump(lens.slot); + lens.n +} + +/// Whether `flow` breaks with `arc` itself, after changing its own bytes in place. +fn same_arc(mut flow: ControlFlow<&Arc, [u8; 1]>, arc: &Arc) -> u8 { + match flow { + ControlFlow::Continue(ref mut bytes) => { + bytes[0] = bytes[0].wrapping_add(1); + bytes[0] + } + ControlFlow::Break(p) => Arc::ptr_eq(p, arc) as u8, + } } /// `a`'s byte, after writing `b`'s. diff --git a/ts/fixtures/task/expected/lib.ts b/ts/fixtures/task/expected/lib.ts index 4c452cc8a..c0655c243 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -2,6 +2,11 @@ import * as rt from "./rt.ts"; import type * as Guard from "./model.Guard.ts"; +import type * as Tally from "./model.Tally.ts"; + +export function copy$Tally(v: Tally.Tally): Tally.Tally { + return { n: v.n }; +} export function drop$ControlFlow_Guard_u32(_1: rt.Result): void { if (!_1.ok) { diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 32a4f139c..7d889f54b 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { drop$ControlFlow_Guard_u32, drop$Result_u32_Guard } from "./lib.ts"; +import { copy$Tally, drop$ControlFlow_Guard_u32, drop$Result_u32_Guard } from "./lib.ts"; import { recvFuture } from "./kio.ts"; import type * as Consumer from "./kio.Consumer.ts"; import * as Log from "./log.Log.ts"; @@ -495,7 +495,7 @@ export class blocksFuture { unwind = 137; this.#tally = { n: this.#guard$2.id }; this.#saved$9 = true; - seen = new blocksFuture$3(rt.copy(this.#tally)); + seen = new blocksFuture$3(copy$Tally(this.#tally)); const _89: rt.u32 = rt.u32Add(this.#tally.n, 1000); this.#tally.n = _89; this.#saved$3 = this.#guard$2; diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index cdad6ed11..94763b370 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -230,11 +230,6 @@ export function sliceToByteVec(s: Uint8Array): ByteVec { return byteVecFrom(s); } -/** `to_vec` of `Copy` elements. */ -export function sliceToVec(s: readonly T[]): T[] { - return s.map(copy); -} - const SLAB = 8192; let slab = /* @__PURE__ */ new ArrayBuffer(SLAB); let slabUsed = 0; @@ -390,21 +385,6 @@ export function stringLen(s: string): number { return encoder.encode(s).length; } -// Values - -/** - * A copy of a `Copy` value. Objects stand for structs, tuples, and arrays, and Rust - * copies those where JS would share them. - */ -export function copy(value: T): T { - if (typeof value !== "object" || value === null) return value; - if (value instanceof Uint8Array) return value.slice() as T; - if (Array.isArray(value)) return value.map(copy) as T; - const out = Object.create(Object.getPrototypeOf(value)); - for (const key of Object.keys(value)) out[key] = copy((value as Record)[key]); - return out; -} - // Formatting, as `core::fmt` does it: the same output byte for byte. /** `core::fmt::Error`. */ diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 67c7a8fe2..80b0d6956 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -73,38 +73,6 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.call_def(from_fn.def_id, args, vec![value], span, out) } - pub fn needs_copy(&self, ty: Ty<'tcx>) -> bool { - if !self.t.is_copy(ty) { - return false; - } - self.mutable_aggregate(ty) - } - - /// Whether values of `ty` are JS objects that Rust code can change in place. - fn mutable_aggregate(&self, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::Tuple(tys) => !tys.is_empty(), - ty::Array(..) => true, - ty::Adt(adt, args) => match library::Std::of(self.t.tcx, adt.did()) { - // The runtime's methods hand out the payload itself. - Some(library::Std::Option | library::Std::Result | library::Std::ControlFlow) => { - args.types().any(|t| self.mutable_aggregate(t)) - } - Some(_) => false, - None => adt.is_struct() && !adt.non_enum_variant().fields.is_empty(), - }, - _ => false, - } - } - - /// `value`, copied if `ty` is a `Copy` aggregate. - pub fn copied(&mut self, value: Expr, ty: Ty<'tcx>) -> Expr { - match self.needs_copy(ty) { - true => Expr::rt("copy", vec![value]), - false => value, - } - } - /// A call of `def_id` with `gargs`, from wherever it resolves. pub fn call_def( &mut self, diff --git a/ts/src/lower/collections.rs b/ts/src/lower/collections.rs index 9d3c19b47..0cae4bbae 100644 --- a/ts/src/lower/collections.rs +++ b/ts/src/lower/collections.rs @@ -628,9 +628,12 @@ fn extend_source<'tcx>( _ => elems[0], }; let borrowed = owner == "Extend" && library::targ(call.args, 1) != stored; - Some(match borrowed && elems.iter().any(|&t| b.needs_copy(t)) { - true => Expr::rt("iterMap", vec![items, Expr::Rt("copy".into())]), - false => items, + if !borrowed || !elems.iter().any(|&t| b.t.needs_copy(t)) { + return Some(items); + } + Some(match b.t.copy_fn(stored, call.span) { + Some(copy) => Expr::rt("iterMap", vec![items, copy]), + None => items, }) } @@ -888,8 +891,10 @@ fn hash_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, hasher: Ty<'tcx>, spa /// `Clone::clone` of `ty`, as a function, or `undefined` where it is the value itself. fn clone_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Expr { let tcx = b.t.tcx; - if b.needs_copy(ty) && library::clone_copies(b.t, ty) { - return Expr::Rt("copy".into()); + if library::clone_copies(b.t, ty) + && let Some(copy) = b.t.copy_fn(ty, span) + { + return copy; } if (b.t.is_copy(ty) && library::clone_copies(b.t, ty)) || b.t.std_of(ty) == Some(Std::String) { return Expr::undefined(); diff --git a/ts/src/lower/copy.rs b/ts/src/lower/copy.rs new file mode 100644 index 000000000..2c162269f --- /dev/null +++ b/ts/src/lower/copy.rs @@ -0,0 +1,194 @@ +//! 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. + +use rustc_middle::ty::{self, EarlyBinder, Ty, TypeVisitableExt}; +use rustc_span::Span; + +use super::library::{Flow, Std}; +use super::{AdtRepr, Translator, field_name, short_name}; +use crate::program::{SymKind, Symbol}; +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. + pub fn needs_copy(&self, ty: Ty<'tcx>) -> bool { + self.is_copy(ty) && self.mutable_aggregate(ty) + } + + fn mutable_aggregate(&self, ty: Ty<'tcx>) -> bool { + match ty.kind() { + ty::Tuple(tys) => !tys.is_empty(), + ty::Array(..) => true, + 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)) + } + Some(_) => false, + None => adt.did().is_local() && adt.all_fields().next().is_some(), + }, + _ => false, + } + } + + /// `value`, copied if a `ty` is. + pub fn copied(&mut self, value: Expr, ty: Ty<'tcx>, span: Span) -> Expr { + match self.copy_fn(ty, span) { + Some(copy) => copy.call(vec![value]), + None => value, + } + } + + /// The function copying a `ty`, made the first time, or `None` if a `ty` is shared. + pub fn copy_fn(&mut self, ty: Ty<'tcx>, span: Span) -> Option { + if !self.needs_copy(ty) { + return None; + } + // An array's copy is the same at every length. + let ty = match ty.kind() { + ty::Array(elem, _) => Ty::new_array(self.tcx, *elem, 0), + _ => ty, + }; + if let Some(&sym) = self.copy_shims.get(&ty) { + return Some(Expr::Sym(sym)); + } + // Only an instance can say what a parameter holds; a census writes nothing. + if self.polymorphic() && ty.has_param() { + return None; + } + let sym = self.program.sym(Symbol { + module: Vec::new(), + base: "copy".into(), + suffix: short_name(self.tcx, ty), + owner: None, + kind: SymKind::Function, + order: 0, + instance: ty::print::with_no_trimmed_paths!(ty.to_string()), + name: String::new(), + alias: None, + }); + self.copy_shims.insert(ty, sym); + let body = self.copy_body(ty, span); + let ts_ty = self.ty(ty, span); + self.program.items.push(ts::Item::Function(ts::Function { + sym, + params: vec![Param { + name: "v".into(), + ty: Some(ts_ty.clone()), + }], + ret: ts_ty, + body, + loc: None, + doc: None, + })); + Some(Expr::Sym(sym)) + } + + /// The body of the function copying `v`, a `ty`. + fn copy_body(&mut self, ty: Ty<'tcx>, span: Span) -> Vec { + let v = || Expr::ident("v"); + let ret = |e: Expr| vec![StmtKind::Return(Some(e.typed())).at(None)]; + let tcx = self.tcx; + match ty.kind() { + ty::Tuple(tys) => { + let parts = tys + .iter() + .enumerate() + .map(|(i, t)| self.copied(v().index(Expr::lit(i.to_string())), t, span)) + .collect(); + ret(Expr::Array(parts)) + } + ty::Array(elem, _) => ret(match self.copy_fn(*elem, span) { + Some(copy) => v().member("map").call(vec![copy]), + None => v().member("slice").call(Vec::new()), + }), + ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { + Some(Std::Option) => ret(self.copy_unless(Expr::undefined(), args.type_at(0), span)), + Some(Std::Poll) => ret(self.copy_unless(Expr::Rt("Pending".into()), args.type_at(0), span)), + Some(Std::Result) => ret(self.copy_result(args.type_at(0), args.type_at(1), span)), + Some(Std::ControlFlow) => { + let (residual, value) = (args.type_at(0), args.type_at(1)); + ret(match (Flow::of(tcx, args), residual.kind()) { + (Flow::Result, ty::Adt(_, residual)) => self.copy_result(value, residual.type_at(1), span), + (Flow::Option, _) => self.copy_unless(Expr::undefined(), value, span), + _ => self.copy_result(value, residual, span), + }) + } + _ => { + let info = self.adt(*adt, span); + match info.repr { + AdtRepr::Struct { ctor, fields } => { + let variant = adt.non_enum_variant(); + let values = (variant.fields.iter().zip(&fields)) + .map(|(field, &id)| { + let field_ty = self.field_ty(field.did, args); + self.copied(v().field(id), field_ty, span) + }) + .collect(); + ret(self.construct(info.sym, &ctor, &fields, values)) + } + AdtRepr::Union => { + let ts_ty = self.ty(ty, span); + let mut body = Vec::new(); + for variant in adt.variants().iter().filter(|v| !v.fields.is_empty()) { + let tag = variant.name.to_string(); + let mut props = vec![(Key::Name("tag".into()), Expr::Str(tag.clone()))]; + for (i, field) in variant.fields.iter().enumerate() { + let name = field_name(field.name.as_str(), i); + let field_ty = self.field_ty(field.did, args); + props + .push((Key::Name(name.clone()), self.copied(v().member(name), field_ty, span))); + } + body.push( + StmtKind::If { + cond: v().member("tag").binary("===", Expr::Str(tag)), + then: ret(Expr::As(Box::new(Expr::Object(props)), ts_ty.clone())), + els: Vec::new(), + } + .at(None), + ); + } + // A variant without fields has nothing to change in place. + body.extend(ret(v())); + body + } + AdtRepr::Tags => unreachable!("an enum without fields is shared"), + } + } + }, + _ => unreachable!("`{ty}` is shared"), + } + } + + /// A copy of `v`, an `rt.Result` of `ok` or `err`. + fn copy_result(&mut self, ok: Ty<'tcx>, err: Ty<'tcx>, span: Span) -> Expr { + let v = || Expr::ident("v"); + Expr::Cond( + Box::new(v().member("ok")), + Box::new(Expr::rt("Ok", vec![self.copied(v().member("value"), ok, span)])), + Box::new(Expr::rt("Err", vec![self.copied(v().member("error"), err, span)])), + ) + } + + /// A copy of `v`, which is `none` or a `some`. + fn copy_unless(&mut self, none: Expr, some: Ty<'tcx>, span: Span) -> Expr { + let v = || Expr::ident("v"); + Expr::Cond( + Box::new(v().binary("===", none)), + Box::new(v()), + Box::new(self.copied(v(), some, span)), + ) + } + + /// The type of field `did` of an ADT with `args`. + pub fn field_ty(&self, did: rustc_hir::def_id::DefId, args: ty::GenericArgsRef<'tcx>) -> Ty<'tcx> { + let field = EarlyBinder::bind(self.tcx, self.tcx.type_of(did).instantiate_identity().skip_norm_wip()); + self.tcx + .try_instantiate_and_normalize_erasing_regions(args, self.typing_env_pub(), field) + .unwrap_or_else(|_| field.instantiate(self.tcx, args).skip_norm_wip()) + } +} diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index 0f9cea803..d81a5e56e 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -231,8 +231,10 @@ pub fn call<'tcx>( let [v, items] = <[Expr; 2]>::try_from(args).ok()?; let mut items = into_iter(b, source, items, span)?; // `Extend<&T>` copies each element. - if item != vec_args.type_at(0) && b.needs_copy(vec_args.type_at(0)) { - items = Expr::rt("iterMap", vec![items, Expr::Rt("copy".into())]); + if item != vec_args.type_at(0) + && let Some(copy) = b.t.copy_fn(vec_args.type_at(0), span) + { + items = Expr::rt("iterMap", vec![items, copy]); } let extend = match vec_args.type_at(0).kind() { ty::Uint(ty::UintTy::U8) => "iterExtendBytes", @@ -342,7 +344,7 @@ pub fn call<'tcx>( let clone = b.fn_value(clone, tcx.mk_args(&[(*inner).into()]), span); method("map", vec![clone]) } - _ if b.needs_copy(*inner) => method("map", vec![Expr::Rt("copy".into())]), + _ if b.t.needs_copy(*inner) => method("map", b.t.copy_fn(*inner, span).into_iter().collect()), // A JS string is a value already. _ if b.t.is_copy(*inner) || matches!(inner.kind(), ty::Adt(adt, _) if Std::of(tcx, adt.did()) == Some(Std::String)) => diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 1239230e6..6dc1a0f14 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -509,7 +509,7 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec ty::Adt(adt, _) if int_range(ty) => { Expr::rt_of(range_of(Std::of(tcx, adt.did())?)?, "clone").call(vec![value]) } - _ if b.t.is_copy(ty) && clone_copies(b.t, ty) => b.copied(value, ty), + _ if b.t.is_copy(ty) && clone_copies(b.t, ty) => b.t.copied(value, ty, span), _ => return None, } } @@ -526,9 +526,10 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec ("Option", "is_none") => args.pop()?.binary("===", Expr::undefined()), ("Option", "as_ref" | "as_mut") => args.pop()?, ("Option", "copied" | "cloned") => { - let inner = targ(gargs, 0); + let sig = tcx.fn_sig(call.def_id).instantiate(tcx, call.args).skip_norm_wip(); + let option = tcx.instantiate_bound_regions_with_erased(sig).output(); let value = args.pop()?; - b.copied(value, inner) + b.t.copied(value, option, span) } // Results. @@ -595,7 +596,13 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec let values = args; match is_u8(elem) { true => Expr::rt("sliceToByteVec", values), - false if b.t.is_copy(elem) => Expr::rt("sliceToVec", values), + false if b.t.is_copy(elem) => { + let slice = values.into_iter().next()?; + match b.t.copy_fn(elem, span) { + Some(copy) => slice.member("map").call(vec![copy]), + None => slice.member("slice").call(Vec::new()), + } + } false => return None, } } @@ -624,7 +631,7 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec Expr::ident(name) } }; - let item = b.copied(value, elem); + let item = b.t.copied(value, elem, span); let item_ty = b.t.ty(elem, span); Expr::ident("Array").member("from").call(vec![ Expr::Object(vec![(crate::ts::Key::Name("length".into()), n)]), diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 6c35d7b46..dd1bec09a 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -112,7 +112,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let value = match dest.as_local() { Some(local) if self.mutated[local] => { let ty = self.mir.local_decls[local].ty; - self.b.copied(value, ty) + self.b.t.copied(value, ty, span) } _ => value, }; diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index e92c70d25..2bb83feae 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -339,20 +339,21 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { .. } => { self.operand_use(func); - // A callee given nothing that changes memory can't change an argument's - // source while it runs. - let alone = !std::iter::once(func) - .chain(args.iter().map(|a| &a.node)) - .any(|op| self.reaches_mutable(op.ty(&mir.local_decls, self.tcx))); let result = destination.ty(&mir.local_decls, self.tcx).ty; 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() { + // 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] = holds(result, mir.local_decls[local].ty); + self.arg_kept[local] = self.holds(result, part); } } self.def(*destination); @@ -1125,13 +1126,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { for local in self.mir.args_iter() { let ty = self.mir.local_decls[local].ty; if self.mutated[local] - && self.b.needs_copy(ty) && let Slot::Var(name) = &self.slots[local] + && let Some(copy) = self.b.t.copy_fn(ty, self.local_span(local)) { let name = name.clone(); - entry.push( - StmtKind::Expr(Expr::ident(&name).assign(Expr::rt("copy", vec![Expr::ident(&name)]))).at(None), - ); + entry.push(StmtKind::Expr(Expr::ident(&name).assign(copy.call(vec![Expr::ident(&name)]))).at(None)); } } // A closure that captures nothing holds nothing, so MIR never assigns it: JS needs @@ -1538,12 +1537,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } fn flush_one(&mut self, p: Pending, out: &mut Vec) { - if let Some(local) = self.local_named(&p.name) { + let local = self.local_named(&p.name); + if let Some(local) = local { self.assigned[local] = true; } - let value = match p.copy { - true => Expr::rt("copy", vec![p.value]), - false => p.value, + let value = match (p.copy, local) { + (true, Some(local)) => self + .b + .t + .copied(p.value, self.mir.local_decls[local].ty, self.local_span(local)), + _ => p.value, }; out.push(match p.decl { true => StmtKind::decl(false, p.name, None, Some(value)).at(None), @@ -1883,7 +1886,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { && matches!(rvalue, Rvalue::Use(Operand::Copy(p), _) if !self.frozen(*p) && (own(*p) && !self.borrowed[p.local] || self.arg_alone[l]) - && self.b.needs_copy(p.ty(&self.mir.local_decls, self.tcx).ty)) + && self.b.t.needs_copy(p.ty(&self.mir.local_decls, self.tcx).ty)) }); if shares { self.into_frozen = true; @@ -2295,32 +2298,58 @@ impl Fx<'_, '_, '_, '_> { } impl<'tcx> Fx<'_, '_, '_, 'tcx> { - /// Whether a value of `ty` can change memory: it holds a mutable reference, a raw - /// pointer, or something with interior mutability. - fn reaches_mutable(&self, ty: Ty<'tcx>) -> bool { + /// Whether a value of `ty` can change a `part` in place: it holds a raw pointer, or a + /// mutable reference to or interior mutability around something that could hold a + /// `part` or be part of one. + fn changes(&self, ty: Ty<'tcx>, part: Ty<'tcx>) -> bool { use rustc_middle::ty::TypeVisitableExt; let env = self.b.t.typing_env_pub(); - ty.walk().any(|arg| { - arg.as_type().is_some_and(|t| { - matches!(t.kind(), ty::Ref(_, _, rustc_ast::Mutability::Mut) | ty::RawPtr(..)) - // Inside a binder, as a function pointer's signature, only its kind tells. - || !t.has_escaping_bound_vars() && !t.is_freeze(self.tcx, env) - }) + let overlaps = |t: Ty<'tcx>| self.holds(t, part) || self.holds(part, t); + self.reaches(ty, |t| match t.kind() { + ty::RawPtr(..) => true, + ty::Ref(_, inner, rustc_ast::Mutability::Mut) => overlaps(*inner), + // Inside a binder, as a function pointer's signature, only its kind tells. + _ => !t.has_escaping_bound_vars() && !t.is_freeze(self.tcx, env) && overlaps(t), }) } -} -/// Whether a value of `ty` could hold a `part`: contains its type, or hides what it holds. -fn holds<'tcx>(ty: Ty<'tcx>, part: Ty<'tcx>) -> bool { - ty.walk().any(|arg| { - arg.as_type().is_some_and(|t| { - t == 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. + let storage = |t: Ty<'tcx>| match t.kind() { + ty::Array(elem, _) => Ty::new_slice(self.tcx, *elem), + _ => t, + }; + let part = storage(part); + self.reaches(ty, |t| { + storage(t) == part || matches!( t.kind(), ty::Dynamic(..) | ty::Alias(..) | ty::Param(_) | ty::Closure(..) | ty::Coroutine(..) ) }) - }) + } + + /// Whether `f` holds for any type a value of `ty` holds: its type arguments, which are + /// what std's types hold, and the fields of the crate's own types. + fn reaches(&self, ty: Ty<'tcx>, mut f: impl FnMut(Ty<'tcx>) -> bool) -> bool { + let mut seen = FxHashSet::default(); + let mut stack = vec![ty]; + while let Some(ty) = stack.pop() { + for t in ty.walk().filter_map(|arg| arg.as_type()) { + if f(t) { + return true; + } + if let ty::Adt(adt, args) = t.kind() + && adt.did().is_local() + && seen.insert(t) + { + stack.extend(adt.all_fields().map(|field| self.b.t.field_ty(field.did, args))); + } + } + } + false + } } /// Whether `place` is part of its local's own value, rather than reached through a diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 52c13e00f..7abc34335 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -259,7 +259,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let value = self.place_expr(*place, span, out); match self.force_share || self.into_frozen && self.frozen(*place) { true => value, - false => self.b.copied(value, ty), + false => self.b.t.copied(value, ty, span), } } Operand::Move(place) => { @@ -267,7 +267,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let value = self.place_expr(*place, span, out); match self.into_frozen { true => value, - false => self.b.copied(value, ty), + false => self.b.t.copied(value, ty, span), } } Operand::Constant(c) => self.constant(c, span), diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index f7bd91f16..45bacbd4d 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -158,7 +158,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } _ => { let v = self.path(v, "item", out); - let item = self.b.copied(v, elem_ty); + let item = self.b.t.copied(v, elem_ty, span); let item_ty = self.b.t.ty(elem_ty, span); Expr::ident("Array").member("from").call(vec![ Expr::Object(vec![(Key::Name("length".into()), Expr::lit(n.to_string()))]), diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index fa473928c..3f27f5f95 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -8,6 +8,7 @@ mod body; mod collections; mod consts; +mod copy; mod drop; mod fmt; mod iter; @@ -145,6 +146,8 @@ pub struct Translator<'a, 'tcx> { glued: rustc_data_structures::fx::FxHashSet, /// The drop glue made from each type's drop shim. 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 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`]. @@ -211,6 +214,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { glued: Default::default(), coroutines: Default::default(), drop_shims: Default::default(), + copy_shims: Default::default(), held: false, }) }