From 83b183c3fd1caaaec85f613de57da89bb51b909f Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:56:48 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/m3/ts-shared-slices.md Quest-Claim: 5ef1a67841ae733a From 6f093b7945803b8f558a8cb3f0354a5e1696b7fb Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:10:00 -0800 Subject: [PATCH 2/3] feat(ts): translate Rc and Arc of a slice and of str Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 3 +- quest/m3/ts-arc-pointers.md | 16 + quest/m3/ts-shared-slices.md | 17 - quest/m3/ts-slice-conversions.md | 15 + ts/Cargo.lock | 4 + ts/README.md | 2 +- ts/fixtures/lang/shares/Cargo.toml | 14 + .../lang/shares/expected/core/option.ts | 41 + ts/fixtures/lang/shares/expected/harness.ts | 64 ++ ts/fixtures/lang/shares/expected/lib.ts | 37 + .../lang/shares/expected/shares.Held.ts | 23 + .../lang/shares/expected/shares.Logged.ts | 37 + .../lang/shares/expected/shares.Shared.ts | 92 +++ ts/fixtures/lang/shares/expected/shares.ts | 728 ++++++++++++++++++ ts/fixtures/lang/shares/src/lib.rs | 27 + ts/fixtures/lang/shares/src/shares.rs | 566 ++++++++++++++ ts/fixtures/lang/shares/ts.toml | 2 + ts/runtime/rt/task.ts | 15 +- ts/src/lower/iter.rs | 7 + ts/src/lower/library.rs | 12 +- ts/src/lower/task.rs | 35 +- ts/tests/fixtures.rs | 1 + 22 files changed, 1726 insertions(+), 32 deletions(-) create mode 100644 quest/m3/ts-arc-pointers.md delete mode 100644 quest/m3/ts-shared-slices.md create mode 100644 quest/m3/ts-slice-conversions.md create mode 100644 ts/fixtures/lang/shares/Cargo.toml create mode 100644 ts/fixtures/lang/shares/expected/core/option.ts create mode 100644 ts/fixtures/lang/shares/expected/harness.ts create mode 100644 ts/fixtures/lang/shares/expected/lib.ts create mode 100644 ts/fixtures/lang/shares/expected/shares.Held.ts create mode 100644 ts/fixtures/lang/shares/expected/shares.Logged.ts create mode 100644 ts/fixtures/lang/shares/expected/shares.Shared.ts create mode 100644 ts/fixtures/lang/shares/expected/shares.ts create mode 100644 ts/fixtures/lang/shares/src/lib.rs create mode 100644 ts/fixtures/lang/shares/src/shares.rs create mode 100644 ts/fixtures/lang/shares/ts.toml diff --git a/quest/m3/README.md b/quest/m3/README.md index 3dbf54e10..e87800ecd 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -31,7 +31,8 @@ generic std gap is planned here even when moq never calls it. - [A crate's own find and for_each](/quest/m3/ts-iter-own-calls.md) - a crate's iterator that overrides `find`, `rfind`, `find_map`, or `for_each` translates, each called where std's adaptors and consumers call it - [A vector's exact capacity as it shrinks](/quest/m3/ts-vec-exact-capacity.md) - a deque made from a `Vec` splits its slices where std's does - [A B-tree's searches call Ord as std's do](/quest/m3/ts-btree-search-order.md) - a B-tree's lookups and inserts call a key's own `Ord` in std's order and number -- [Rc and Arc of a slice](/quest/m3/ts-shared-slices.md) - `Rc<[T]>` and `Arc<[T]>` from a `Vec`, a slice, or an iterator translate +- [A Vec from a slice, and a slice's chunks as arrays](/quest/m3/ts-slice-conversions.md) - `Vec::from(&[T])` and `as_chunks` translate +- [An Arc's pointer](/quest/m3/ts-arc-pointers.md) - `Arc::as_ptr` and `Rc::as_ptr` translate, comparable by `ptr::addr_eq` - [The rest of a vector's methods](/quest/m3/ts-vec-rest.md) - `append`, `resize`, `split_off`, `try_reserve`, and `Vec::from(VecDeque)` translate - [A reversed zip's per-pair cost](/quest/m3/ts-zip-rev-overhead.md) - a reversed by-index zip costs per pair what a forward one does, or the gap is explained - [Whole writes into a lazy cell or thread-local key](/quest/m3/ts-lazy-writes.md) - a whole write through a `&mut` to a `LazyCell`, `LazyLock`, or `LocalKey` keeps its state diff --git a/quest/m3/ts-arc-pointers.md b/quest/m3/ts-arc-pointers.md new file mode 100644 index 000000000..1bf38514d --- /dev/null +++ b/quest/m3/ts-arc-pointers.md @@ -0,0 +1,16 @@ +# [S] An Arc's pointer + +## Goal + +[rust2-ts](/ts/README.md) translates `Arc::as_ptr` and `Rc::as_ptr`, of a sized value and +of a slice, and `ptr::addr_eq` of the pointers they give, proven by a differential test +against native Rust that `make_mut` keeps the allocation only when no other owner shares it. + +## Plan + +Found writing the `lang/shares` fixture for `Rc<[T]>`: `Rc::as_ptr` and `ptr::addr_eq` are +refused as unsupported calls. An `rt.Arc` is its allocation, so its pointer may be the +`rt.Arc` itself or a place of its value; the choice must keep what `ptr::eq` and +`addr_eq` already compare. No consumer calls them yet; they are planned here as part of std. + +Public API: the translator's output. diff --git a/quest/m3/ts-shared-slices.md b/quest/m3/ts-shared-slices.md deleted file mode 100644 index 32c0eae72..000000000 --- a/quest/m3/ts-shared-slices.md +++ /dev/null @@ -1,17 +0,0 @@ -# [S] Rc and Arc of a slice - -## Goal - -[rust2-ts](/ts/README.md) translates an `Rc<[T]>` and an `Arc<[T]>` made from a `Vec`, a -slice, or an iterator, read as the slice, cloned, and dropped, proven by a differential -test against native Rust at `u8`, at another element, and at one that drops. - -## Plan - -Found writing [a generic type's byte fields](https://github.com/moq-dev/rust2/pull/375)' -fixture: `Rc::from(vec)` and `Rc::from(slice)` are refused as unsupported calls to -`From`. A shared slice is what a generic type's `[T]` already is, so the form of a -`u8` instance is the open question: an `rt.ByteSlice` as a `Box<[u8]>` is, or one that -counts its owners as `rt.Arc` does. - -Public API: the translator's output. diff --git a/quest/m3/ts-slice-conversions.md b/quest/m3/ts-slice-conversions.md new file mode 100644 index 000000000..415202b92 --- /dev/null +++ b/quest/m3/ts-slice-conversions.md @@ -0,0 +1,15 @@ +# [S] A Vec from a slice, and a slice's chunks as arrays + +## Goal + +[rust2-ts](/ts/README.md) translates `Vec::from` of a `&[T]` and a `&mut [T]`, and +`slice::as_chunks`, `as_rchunks`, and `as_chunks_mut`, proven by differential tests +against native Rust at `u8`, at another element, and at one that drops. + +## Plan + +Found writing the `lang/shares` fixture for `Rc<[T]>`: `Vec::::from(&[u8])` and +`<[u8]>::as_chunks::<2>` are refused as unsupported calls, while `to_vec` and +`chunks_exact` translate. No consumer calls them yet; they are planned here as part of std. + +Public API: the translator's output. diff --git a/ts/Cargo.lock b/ts/Cargo.lock index febd036d4..55c314d64 100644 --- a/ts/Cargo.lock +++ b/ts/Cargo.lock @@ -395,6 +395,10 @@ version = "0.0.0" name = "lang-shapes-fixture" version = "0.0.0" +[[package]] +name = "lang-shares-fixture" +version = "0.0.0" + [[package]] name = "lang-singles-fixture" version = "0.0.0" diff --git a/ts/README.md b/ts/README.md index e65276415..3b173bd95 100644 --- a/ts/README.md +++ b/ts/README.md @@ -131,7 +131,7 @@ crate translation reaches is refused, and so are two versions of one crate it re | `static` | a module's value, named for the static, that every use shares, read from the memory rustc evaluated; one that reads another static or a class is an `rt.LazyCell` of it, made on first use, since that may not be made yet when its module is. A `static mut`, and a pointer in one into memory the translation can't name, fail translation | | a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields | | a type's function | a function of the type's module, taking `self` first: `Decoder.slice(dec, 4)` after `import * as Decoder` | -| `Arc`, `Rc`, `Weak`, `Mutex` | `rt.Arc` for either, with its strong and weak counts, and `new_cyclic`'s `Weak` upgrading only once its value is made, `get_mut` lending its value only while no other `Arc` or `Weak` shares it, `make_mut` cloning it into a new `rt.Arc` while another `Arc` shares it, or moving it there while only `Weak`s do, which then dangle, and `into_inner` giving it only from the last strong `Arc`, after which its `Weak`s no longer upgrade; `rt.Weak`, counted in its `rt.Arc` until it drops, and of no `Arc` once made by `Weak::new`; `rt.Mutex`, its own guard, which a lock gives as `Ok` and the guard's drop unlocks: locking it again while held panics and `try_lock` gives `WouldBlock`, as wasm32's do, and a guard's `map` and `filter_map` make `rt.MutexMap`s, each where the part it lends is, which hold the mutex locked until they drop, and a panic aborts, so nothing poisons it and `thread::panicking` is `false`; a `Mutex`'s, a `RefCell`'s, and an `RwLock`'s `into_inner` gives its value and `get_mut` lends it, or an `rt.Place` of it where JS copies it | +| `Arc`, `Rc`, `Weak`, `Mutex` | `rt.Arc` for either, of what a `Box` is for a slice or `str`, with its strong and weak counts, an `Arc<[u8]>` of an `Arc`'s bytes sharing its count, and `new_cyclic`'s `Weak` upgrading only once its value is made, `get_mut` lending its value only while no other `Arc` or `Weak` shares it, `make_mut` cloning it into a new `rt.Arc` while another `Arc` shares it, or moving it there while only `Weak`s do, which then dangle, and `into_inner` giving it only from the last strong `Arc`, after which its `Weak`s no longer upgrade; `rt.Weak`, counted in its `rt.Arc` until it drops, and of no `Arc` once made by `Weak::new`; `rt.Mutex`, its own guard, which a lock gives as `Ok` and the guard's drop unlocks: locking it again while held panics and `try_lock` gives `WouldBlock`, as wasm32's do, and a guard's `map` and `filter_map` make `rt.MutexMap`s, each where the part it lends is, which hold the mutex locked until they drop, and a panic aborts, so nothing poisons it and `thread::panicking` is `false`; a `Mutex`'s, a `RefCell`'s, and an `RwLock`'s `into_inner` gives its value and `get_mut` lends it, or an `rt.Place` of it where JS copies it | | `PoisonError`, `TryLockError` | the `T` it holds; `rt.TryLockError`, tagged as `Bound` is | | `Cell`, `UnsafeCell`, `RefCell`, `RwLock` | `rt.Cell`, the place holding its value in `v`, for either of the first two: `UnsafeCell::get`'s pointer is the cell where it is an `rt.Place`, and otherwise the object in `v`, refused where the crate may put another cell or object in its place; `rt.RefCell` for either of the others, its own guard, counting its borrows: borrowing it while that conflicts panics as `RefCell`'s does, and locking it so aborts as wasm32's `RwLock` does; `try_borrow` and `try_borrow_mut` fail with `rt.BorrowError` and `rt.BorrowMutError` instead, a clone borrows the cell, `Ref::clone` counts another borrow of it, and a guard's `map`, `filter_map`, `try_map`, and `map_split`, an `RwLock` guard's included, make `rt.RefMap`s, each where a part it lends is, which a write through a mapped `RefMut` reaches in place, sharing the cell's borrow until the last drops; `RwLockWriteGuard::downgrade` keeps the lock as one read, and `Ref::leak` and `RefMut::leak` keep the borrow until `RefCell::undo_leak` ends it; refused for a part of a sized type JS can't write in place, such as a binding's | | `thread_local!`, `LocalKey` | an `rt.LocalKey`, a module's value, which makes its value on first use from the `const` or the expression and never drops it, as wasm32's do; `with` calls its function on that value, `try_with` never fails, the `Cell` and `RefCell` helpers lower from std, and a `RefCell` key's `set` and `with_borrow_mut` borrow it as `borrow_mut` does | diff --git a/ts/fixtures/lang/shares/Cargo.toml b/ts/fixtures/lang/shares/Cargo.toml new file mode 100644 index 000000000..fb85dca71 --- /dev/null +++ b/ts/fixtures/lang/shares/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "lang-shares-fixture" +description = "A part of the language rust2-ts translates, exercised against native Rust" +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"] + +[lints] +workspace = true diff --git a/ts/fixtures/lang/shares/expected/core/option.ts b/ts/fixtures/lang/shares/expected/core/option.ts new file mode 100644 index 000000000..00a352b0a --- /dev/null +++ b/ts/fixtures/lang/shares/expected/core/option.ts @@ -0,0 +1,41 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as Logged from "../shares.Logged.ts"; + +export function isSomeAnd$0vr0nda(self: rt.Arc | undefined, f: (a0: rt.Arc) => boolean): boolean { + if (self === undefined) { + return false; + } + return f(self); +} + +export function unwrapOr$0r2bmpr(self: rt.u8 | undefined, default_: rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return self; +} + +export function mapOr$1e4a1e0(self: rt.Ordering | undefined, default_: rt.u8, f: (a0: rt.Ordering) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$03siheh(self: rt.Arc | undefined, default_: rt.u8, f: (a0: rt.Arc) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$148vfk5(self: Logged.Logged | undefined, default_: rt.u8, f: (a0: Logged.Logged) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +//# sourceMappingURL=option.ts.map diff --git a/ts/fixtures/lang/shares/expected/harness.ts b/ts/fixtures/lang/shares/expected/harness.ts new file mode 100644 index 000000000..7c19e53ff --- /dev/null +++ b/ts/fixtures/lang/shares/expected/harness.ts @@ -0,0 +1,64 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { cases } from "./lib.ts"; + +/** Run one case. */ +export function run(input: rt.ByteSlice): rt.ByteVec { + const out: rt.ByteVec = new rt.ByteVec(); + if (!(input.length >= 3)) { + return out; + } + const cases_: [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined][] = cases(); + cases_[rt.idx(cases_, rt.usizeRem(((input.data[input.start] << 8) | input.data[input.start + 1]) as rt.usize, cases_.length))][1](input.data[input.start + 2], new rt.ByteSlice(input.data, input.start + 3, input.length - 3), out); + return out; +} + +/** + * The first two bytes, as one big-endian number, that pick the case named `name`, which + * `lang.ts` targets by. + */ +export function op(name: string): rt.u16 { + const _11: rt.usize | undefined = rt.iterPosition(rt.iterSlice(cases()), (_2: [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]): boolean => { + return _2[0] === name; + }); + if (_11 !== undefined) { + const _20: rt.Result = rt.u16TryFrom(_11); + if (_20.ok) { + if ((_20.value >> 8) !== 255) { + return _20.value; + } + } + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, name)]; + rt.panicFmt(["case ", args4[0], " is past what two bytes pick"]); + } else { + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, name)]; + rt.panicFmt(["no case ", args2[0]]); + } +} + +/** Write `s` and the byte no UTF-8 holds, which ends it. */ +export function put(out: rt.ByteVec, s: string): void { + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(s)); + rt.byteVecPush(out, 255); +} + +/** A char of the alphabet for each byte, by its low bits. */ +export function text(data: rt.ByteSlice): string { + let s: string = ""; + const iterS: Uint8Array = rt.byteSliceView(data); + let iterI: number = 0; + while (true) { + const _5: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_5 === rt.DONE) { + return s; + } + const _13: rt.usize = rt.u8Rem(_5, 16) as rt.usize; + if (!(_13 < 16)) { + rt.panic("index out of bounds: the len is " + 16 + " but the index is " + _13); + } + s = s + String.fromCodePoint([47, 92, 97, 48, 57, 127, 128, 233, 2047, 2048, 55295, 57344, 65535, 65536, 128512, 1114111][_13]); + } +} + +//# sourceMappingURL=harness.ts.map diff --git a/ts/fixtures/lang/shares/expected/lib.ts b/ts/fixtures/lang/shares/expected/lib.ts new file mode 100644 index 000000000..1f61f7bc4 --- /dev/null +++ b/ts/fixtures/lang/shares/expected/lib.ts @@ -0,0 +1,37 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { bytes, wides, copies, drops, strs, generics, keys } from "./shares.ts"; +import type * as Logged from "./shares.Logged.ts"; + +export function copy$array_u8(v: Uint8Array): Uint8Array { + return v.slice(); +} + +export function copy$tuple2_u8_u16(v: [rt.u8, rt.u16]): [rt.u8, rt.u16] { + return [v[0], v[1]]; +} + +export function drop$Option_Rc_slice_shares_Logged(_1: rt.Arc | undefined): void { + if (_1 !== undefined) { + rt.arcDrop(_1, drop$slice_shares_Logged); + } +} + +export function drop$Rc_slice_shares_Logged(value: rt.Arc): void { + rt.arcDrop(value, drop$slice_shares_Logged); +} + +export function drop$slice_shares_Logged(value: Logged.Logged[]): void { + rt.dropAll(value); +} + +/** + * Each case's name and what it runs. The first two bytes, big-endian, pick one modulo + * their count, so a case added at the end moves no other. + */ +export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined][] { + return [["shares::bytes", bytes as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["shares::wides", wides as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["shares::copies", copies as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["shares::drops", drops as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["shares::strs", strs as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["shares::generics", generics as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["shares::keys", keys as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; +} + +//# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/lang/shares/expected/shares.Held.ts b/ts/fixtures/lang/shares/expected/shares.Held.ts new file mode 100644 index 000000000..69e187fcd --- /dev/null +++ b/ts/fixtures/lang/shares/expected/shares.Held.ts @@ -0,0 +1,23 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { drop$slice_shares_Logged } from "./lib.ts"; +import type * as Logged from "./shares.Logged.ts"; + +/** A shared slice in a field, beside one that drops after it. */ +export class Held { + items: rt.Arc; + last: Logged.Logged; + + constructor(items: rt.Arc, last: Logged.Logged) { + this.items = items; + this.last = last; + } + + [Symbol.dispose](): void { + rt.arcDrop(this.items, drop$slice_shares_Logged); + this.last[Symbol.dispose](); + } +} + +//# sourceMappingURL=shares.Held.ts.map diff --git a/ts/fixtures/lang/shares/expected/shares.Logged.ts b/ts/fixtures/lang/shares/expected/shares.Logged.ts new file mode 100644 index 000000000..a66030ef8 --- /dev/null +++ b/ts/fixtures/lang/shares/expected/shares.Logged.ts @@ -0,0 +1,37 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** + * Logs its id as it drops, and as it is cloned, the id with the high bit set: its clone's + * id is one more. + */ +export class Logged { + id: rt.u8; + log: rt.Arc>; + + constructor(id: rt.u8, log: rt.Arc>) { + this.id = id; + this.log = log; + } + + [Symbol.dispose](): void { + drop$ops_Drop(this); + this.log[Symbol.dispose](); + } +} + +export function clone$Clone(self: Logged): Logged { + const _5: rt.RefCell = rt.refCellBorrowMut(self.log.value); + rt.byteVecPush(_5.value, 128 | self.id); + rt.refMutRelease(_5); + return new Logged(rt.u8WrappingAdd(self.id, 1), rt.arcClone(self.log)); +} + +export function drop$ops_Drop(self: Logged): void { + const _5: rt.RefCell = rt.refCellBorrowMut(self.log.value); + rt.byteVecPush(_5.value, self.id); + rt.refMutRelease(_5); +} + +//# sourceMappingURL=shares.Logged.ts.map diff --git a/ts/fixtures/lang/shares/expected/shares.Shared.ts b/ts/fixtures/lang/shares/expected/shares.Shared.ts new file mode 100644 index 000000000..48cc9e226 --- /dev/null +++ b/ts/fixtures/lang/shares/expected/shares.Shared.ts @@ -0,0 +1,92 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { drop$Rc_slice_shares_Logged } from "./lib.ts"; +import * as Logged from "./shares.Logged.ts"; + +/** + * A shared slice of its parameter, made from a `Vec` and an iterator, cloned, and written, + * as each instance holds it. + */ +export class Shared { + items: rt.Arc>; + + constructor(items: rt.Arc>) { + this.items = items; + } + + [Symbol.dispose](): void { + rt.arcDrop(this.items as rt.Arc, (value: T[]) => rt.dropAll(value)); + } +} + +export function new$shares_Logged(items: Logged.Logged[]): Shared { + return new Shared(new rt.Arc(items)); +} + +export function new$u8(items: rt.ByteVec): Shared { + return new Shared(new rt.Arc(rt.byteVecSlice(items))); +} + +export function collected$u16_iter_Map_slice_Iter_u8_shares_generics_closure0(items: rt.Iter): Shared { + return new Shared(new rt.Arc(rt.iterToArray(items, undefined, 2, true))); +} + +export function first$shares_Logged(self: Shared): Logged.Logged | undefined { + return rt.sliceFirst((self.items as rt.Arc).value); +} + +export function first$u8(self: Shared): rt.u8 | undefined { + return rt.byteSliceFirst((self.items as rt.Arc).value); +} + +/** Its items, made its own, with `item` in place of its last. */ +export function setLast$shares_Logged(self: Shared, item: Logged.Logged): void { + let _9: boolean = false; + _9 = true; + const _3: Logged.Logged | undefined = rt.sliceLast(rt.arcMakeMut(rt.place(() => self.items as rt.Arc, (value) => (self.items as rt.Arc) = value), (a0: Logged.Logged[]): Logged.Logged[] => { + return a0.map(Logged.clone$Clone); + }, drop$Rc_slice_shares_Logged)); + if (_3 !== undefined) { + _9 = false; + _3[Symbol.dispose](); + Object.assign(_3, item); + } + if (_9) { + item[Symbol.dispose](); + } +} + +/** Its items, made its own, with `item` in place of its last. */ +export function setLast$u16(self: Shared, item: rt.u16): void { + const _3: rt.Place | undefined = rt.sliceLastMut(rt.arcMakeMut(rt.place(() => self.items as rt.Arc, (value) => (self.items as rt.Arc) = value), (a0: rt.u16[]): rt.u16[] => { + return a0.slice(); + }, rt.drop)); + if (_3 !== undefined) { + _3.v = item; + } +} + +/** Its items, made its own, with `item` in place of its last. */ +export function setLast$u8(self: Shared, item: rt.u8): void { + const _3: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(rt.arcMakeMut(rt.place(() => self.items as rt.Arc, (value) => (self.items as rt.Arc) = value), (a0: rt.ByteSlice): rt.ByteSlice => { + return rt.byteSliceFrom(rt.byteSliceToArray(a0)); + }, rt.drop))); + if (_3 !== undefined) { + _3.v = item; + } +} + +export function clone$Clone_shares_Logged(self: Shared): Shared { + return new Shared(rt.arcClone(self.items as rt.Arc)); +} + +export function clone$Clone_u16(self: Shared): Shared { + return new Shared(rt.arcClone(self.items as rt.Arc)); +} + +export function clone$Clone_u8(self: Shared): Shared { + return new Shared(rt.arcClone(self.items as rt.Arc)); +} + +//# sourceMappingURL=shares.Shared.ts.map diff --git a/ts/fixtures/lang/shares/expected/shares.ts b/ts/fixtures/lang/shares/expected/shares.ts new file mode 100644 index 000000000..17db8801c --- /dev/null +++ b/ts/fixtures/lang/shares/expected/shares.ts @@ -0,0 +1,728 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$array_u8, copy$tuple2_u8_u16, drop$Option_Rc_slice_shares_Logged, drop$Rc_slice_shares_Logged, drop$slice_shares_Logged } from "./lib.ts"; +import { isSomeAnd$0vr0nda, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, mapOr$03siheh as option_mapOr$03siheh, mapOr$148vfk5 as option_mapOr$148vfk5 } from "./core/option.ts"; +import { put, text } from "./harness.ts"; +import * as Held from "./shares.Held.ts"; +import * as Logged from "./shares.Logged.ts"; +import * as Shared from "./shares.Shared.ts"; + +/** Puts what was logged since the last flush, after a marker. */ +export function flush(log: rt.RefCell, out: rt.ByteVec): void { + rt.byteVecPush(out, 253); + const _8: rt.RefCell = rt.refCellBorrowMut(log); + rt.iterExtendBytes(out, rt.byteVecDrain(_8.value, undefined), "fold", true); + rt.refMutRelease(_8); +} + +export function hash$Rc_slice_u16(value: rt.Arc): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashArc(rt.hashInts(2))(value, h); + return rt.hashFinish(h); +} + +export function hash$Rc_slice_u8(value: rt.Arc): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashArc(rt.hashBytes)(value, h); + return rt.hashFinish(h); +} + +export function hash$Rc_str(value: rt.Arc): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashArc(rt.hashStr)(value, h); + return rt.hashFinish(h); +} + +export function hash$slice_u16(value: rt.u16[]): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashInts(2)(value, h); + return rt.hashFinish(h); +} + +export function hash$slice_u8(value: rt.ByteSlice): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashBytes(value, h); + return rt.hashFinish(h); +} + +export function hash$str(value: string): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashStr(value, h); + return rt.hashFinish(h); +} + +export function hash$sync_Arc_slice_u8(value: rt.Arc): rt.u64 { + const h: rt.Hasher = rt.hasher(); + rt.hashArc(rt.hashBytes)(value, h); + return rt.hashFinish(h); +} + +/** Puts `b`'s length and bytes. */ +export function putBytes(b: rt.ByteSlice, out: rt.ByteVec): void { + rt.byteVecPush(out, b.length & 0xff); + rt.byteVecExtendFromSlice(out, b); +} + +/** Puts `b`'s length and each `u16`'s bytes. */ +export function putWides(b: rt.u16[], out: rt.ByteVec): void { + rt.byteVecPush(out, b.length & 0xff); + for (const _8 of b) { + rt.iterExtendBytes(out, rt.iterSlice(rt.u16ToBeBytes(_8).reverse()), undefined, true); + } +} + +/** Puts the ids of `b`. */ +export function ids(b: Logged.Logged[], out: rt.ByteVec): void { + rt.byteVecPush(out, b.length & 0xff); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(b), (l: Logged.Logged): rt.u8 => { + return l.id; + }), undefined, true); +} + +/** Puts each pair's bytes. */ +export function pairs(b: [rt.u8, rt.u16][], out: rt.ByteVec): void { + rt.byteVecPush(out, b.length & 0xff); + for (const _8 of b) { + rt.byteVecPush(out, _8[0]); + rt.iterExtendBytes(out, rt.iterSlice(rt.u16ToBeBytes(_8[1]).reverse()), undefined, true); + } +} + +/** Puts an `Rc`'s strong and weak counts. */ +export function counts$slice_u16(rc: rt.Arc, out: rt.ByteVec): void { + rt.byteVecPush(out, rc.strong & 0xff); + rt.byteVecPush(out, rc.weak & 0xff); +} + +/** Puts an `Rc`'s strong and weak counts. */ +export function counts$slice_u8(rc: rt.Arc, out: rt.ByteVec): void { + rt.byteVecPush(out, rc.strong & 0xff); + rt.byteVecPush(out, rc.weak & 0xff); +} + +/** Puts an `Rc`'s strong and weak counts. */ +export function counts$str(rc: rt.Arc, out: rt.ByteVec): void { + rt.byteVecPush(out, rc.strong & 0xff); + rt.byteVecPush(out, rc.weak & 0xff); +} + +/** Puts an `Arc`'s strong and weak counts. */ +export function arcCounts$slice_u8(arc: rt.Arc, out: rt.ByteVec): void { + rt.byteVecPush(out, arc.strong & 0xff); + rt.byteVecPush(out, arc.weak & 0xff); +} + +/** Writes through a `&mut` to bytes another function was handed. */ +export function scramble(b: rt.ByteSlice): void { + rt.byteSliceView(b).reverse(); + const iter: rt.Iter> = rt.iterSliceMut(rt.byteSliceView(b)); + while (true) { + const _6: rt.Place | rt.Done = iter.next(); + if (_6 === rt.DONE) { + break; + } + _6.v = rt.u8WrappingAdd(_6.v, 1); + } + const _12: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(b)); + if (_12 !== undefined) { + _12.v = _12.v ^ 255; + } +} + +/** Bytes, each way, read, counted, and written apart from what they came from. */ +export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const data2: rt.ByteSlice = rt.byteSliceRange(data, 0, rt.usizeRem(kind >> 3 as rt.usize, rt.usizeAdd(data.length, 1))); + const _15: rt.u8 = rt.u8Rem(kind, 4); + if (_15 === 0) { + const source: rt.ByteVec = rt.byteSliceToByteVec(data2); + const fromRef: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(rt.byteSliceRange(rt.byteVecSlice(source), 0)))); + const fromMut: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(rt.byteSliceRange(rt.byteVecSlice(source), 0)))); + scramble(rt.byteVecSlice(source)); + putBytes(fromRef.value, out); + putBytes(fromMut.value, out); + putBytes(rt.byteVecSlice(source), out); + const spare: rt.ByteVec = rt.byteVecWithCapacity(64); + rt.byteVecExtendFromSlice(spare, data2); + const fromVec: rt.Arc = new rt.Arc(rt.byteVecSlice(spare)); + putBytes(fromVec.value, out); + const into: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.byteSliceToByteVec(data2))); + putBytes(into.value, out); + const fromBox: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + putBytes(fromBox.value, out); + const fromArray: rt.Arc = new rt.Arc(rt.byteSliceFrom(copy$array_u8(Uint8Array.of(option_unwrapOr$0r2bmpr(rt.byteSliceFirst(data2), 1), 2, 3)))); + putBytes(fromArray.value, out); + const collected: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.iterToByteVec(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_2: rt.u8): rt.u8 => { + return _2 ^ 85; + }), undefined, true))); + putBytes(collected.value, out); + const arcCollected: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.iterToByteVec(rt.iterRev(rt.iterSlice(rt.byteSliceView(data2))), undefined, true))); + putBytes(arcCollected.value, out); + const empty: rt.Arc = new rt.Arc(rt.byteSliceFrom(new Uint8Array(0))); + putBytes(empty.value, out); + const arcEmpty: rt.Arc = new rt.Arc(rt.byteSliceFrom(new Uint8Array(0))); + putBytes(arcEmpty.value, out); + const borrowed: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.byteCowIntoOwned(data2))); + putBytes(borrowed.value, out); + const owned: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.byteCowIntoOwned(rt.byteSliceToByteVec(data2)))); + putBytes(owned.value, out); + const s: rt.Arc = new rt.Arc(text(data2)); + const twin: rt.Arc = rt.arcClone(s); + const ofStr: rt.Arc = rt.arcStrBytes(s); + counts$slice_u8(ofStr, out); + const ofTwin: rt.Arc = rt.arcStrBytes(twin); + rt.byteVecPush(out, ofStr === ofTwin ? 1 : 0); + counts$slice_u8(ofTwin, out); + ofTwin[Symbol.dispose](); + counts$slice_u8(ofStr, out); + putBytes(ofStr.value, out); + const arcOfStr: rt.Arc = rt.arcStrBytes(new rt.Arc(text(data2))); + putBytes(arcOfStr.value, out); + const v: rt.ByteVec = rt.byteSliceToByteVec(fromVec.value); + rt.byteVecPush(v, 238); + rt.byteVecExtendFromSlice(v, collected.value); + putBytes(rt.byteVecSlice(v), out); + putBytes(rt.byteVecSlice(rt.byteSliceToByteVec(into.value)), out); + putBytes(rt.byteSliceFrom(rt.byteSliceToArray(fromBox.value)), out); + arcOfStr[Symbol.dispose](); + ofStr[Symbol.dispose](); + owned[Symbol.dispose](); + borrowed[Symbol.dispose](); + arcEmpty[Symbol.dispose](); + empty[Symbol.dispose](); + arcCollected[Symbol.dispose](); + collected[Symbol.dispose](); + fromArray[Symbol.dispose](); + fromBox[Symbol.dispose](); + into[Symbol.dispose](); + fromVec[Symbol.dispose](); + fromMut[Symbol.dispose](); + fromRef[Symbol.dispose](); + } else if (_15 === 1) { + const a: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + const b2: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(rt.byteSliceRange(data2, 0, rt.usizeDiv(data2.length, 2))))); + rt.byteVecPush(out, rt.eqArc(rt.eqBytes, true)(a, b2) ? 1 : 0); + rt.byteVecPush(out, !rt.eqArc(rt.eqBytes, true)(a, b2) ? 1 : 0); + rt.byteVecPush(out, rt.cmpArc(rt.cmpBytes)(a, b2) === -1 ? 1 : 0); + rt.byteVecPush(out, rt.cmpArc(rt.cmpBytes)(a, b2) & 0xff); + rt.byteVecPush(out, option_mapOr$1e4a1e0(rt.cmpArc(rt.cmpBytes)(b2, a), 9, (o: rt.Ordering): rt.u8 => { + return o & 0xff; + })); + rt.byteVecPush(out, rt.byteSliceEq(a.value, data2) ? 1 : 0); + rt.byteVecPush(out, rt.u64Eq(hash$Rc_slice_u8(a), hash$slice_u8(data2)) ? 1 : 0); + rt.iterExtendBytes(out, rt.iterSlice(rt.u64ToBeBytes(hash$Rc_slice_u8(b2)).reverse()), undefined, true); + rt.byteVecPush(out, a.value.length & 0xff); + rt.byteVecPush(out, a.value.length === 0 ? 1 : 0); + rt.byteVecPush(out, rt.iterFold(rt.iterSlice(rt.byteSliceView(a.value)), 0, (a05: rt.u8, a1: rt.u8): rt.u8 => { + return rt.u8WrappingAdd(a05, a1); + })); + rt.byteVecPush(out, option_unwrapOr$0r2bmpr(rt.byteSliceFirst(a.value), 170)); + rt.byteVecPush(out, option_unwrapOr$0r2bmpr(rt.byteSliceGet(a.value, 1), 187)); + const arc: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + rt.byteVecPush(out, rt.byteSliceEq(arc.value, a.value) ? 1 : 0); + rt.byteVecPush(out, rt.u64Eq(hash$sync_Arc_slice_u8(arc), hash$Rc_slice_u8(a)) ? 1 : 0); + const _244: rt.Arc = new rt.Arc(rt.byteSliceFrom(new Uint8Array(0))); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(a.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(b2.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arc.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_244.value), f, rt.u8Debug)]; + const _240: string = rt.fmtFormat([args2[0], "|", args2[1], "|", args2[2], "|", args2[3]]); + _244[Symbol.dispose](); + put(out, _240); + arc[Symbol.dispose](); + b2[Symbol.dispose](); + a[Symbol.dispose](); + } else if (_15 === 2) { + const a2: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + counts$slice_u8(a2, out); + const b3: rt.Arc = rt.arcClone(a2); + counts$slice_u8(a2, out); + rt.byteVecPush(out, a2 === b3 ? 1 : 0); + const c: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + rt.byteVecPush(out, a2 === c ? 1 : 0); + rt.byteVecPush(out, rt.eqArc(rt.eqBytes, true)(a2, c) ? 1 : 0); + const weak: rt.Weak = new rt.Weak(a2); + counts$slice_u8(b3, out); + a2[Symbol.dispose](); + counts$slice_u8(b3, out); + rt.byteVecPush(out, isSomeAnd$0vr0nda(rt.weakUpgrade(weak), (up: rt.Arc): boolean => { + const _05: boolean = up === b3; + up[Symbol.dispose](); + return _05; + }) ? 1 : 0); + rt.byteVecPush(out, weak.arc.strong & 0xff); + b3[Symbol.dispose](); + const _301: rt.Arc | undefined = rt.weakUpgrade(weak); + rt.byteVecPush(out, _301 === undefined ? 1 : 0); + rt.drop(_301); + rt.byteVecPush(out, weak.arc.strong & 0xff); + const arc2: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.byteSliceToByteVec(data2))); + const twin2: rt.Arc = rt.arcClone(arc2); + arcCounts$slice_u8(arc2, out); + rt.byteVecPush(out, arc2 === twin2 ? 1 : 0); + const arcWeak: rt.Weak = new rt.Weak(twin2); + arcCounts$slice_u8(arc2, out); + twin2[Symbol.dispose](); + arcCounts$slice_u8(arc2, out); + arcWeak[Symbol.dispose](); + arcCounts$slice_u8(arc2, out); + putBytes(arc2.value, out); + arc2[Symbol.dispose](); + weak[Symbol.dispose](); + c[Symbol.dispose](); + } else { + let a3: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + const _332: rt.ByteSlice | undefined = rt.arcGetMut(a3); + if (_332 !== undefined) { + scramble(_332); + } + putBytes(a3.value, out); + const b4: rt.Arc = rt.arcClone(a3); + rt.byteVecPush(out, rt.arcGetMut(a3) === undefined ? 1 : 0); + scramble(rt.arcMakeMut(rt.place(() => a3, (value) => a3 = value), (a0: rt.ByteSlice): rt.ByteSlice => { + return rt.byteSliceFrom(rt.byteSliceToArray(a0)); + }, rt.drop)); + rt.byteVecPush(out, a3 === b4 ? 1 : 0); + counts$slice_u8(a3, out); + counts$slice_u8(b4, out); + putBytes(a3.value, out); + putBytes(b4.value, out); + rt.arcClone(a3)[Symbol.dispose](); + rt.byteSliceFill(rt.arcMakeMut(rt.place(() => a3, (value2) => a3 = value2), (a02: rt.ByteSlice): rt.ByteSlice => { + return rt.byteSliceFrom(rt.byteSliceToArray(a02)); + }, rt.drop), 17); + counts$slice_u8(a3, out); + putBytes(a3.value, out); + const weak2: rt.Weak = new rt.Weak(a3); + const _379: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(rt.arcMakeMut(rt.place(() => a3, (value3) => a3 = value3), (a03: rt.ByteSlice): rt.ByteSlice => { + return rt.byteSliceFrom(rt.byteSliceToArray(a03)); + }, rt.drop))); + if (_379 !== undefined) { + _379.v = 34; + } + const _388: rt.Arc | undefined = rt.weakUpgrade(weak2); + rt.byteVecPush(out, _388 === undefined ? 1 : 0); + rt.drop(_388); + putBytes(a3.value, out); + let arc3: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + const shared: rt.Arc = rt.arcClone(arc3); + rt.byteSliceView(rt.arcMakeMut(rt.place(() => arc3, (value4) => arc3 = value4), (a04: rt.ByteSlice): rt.ByteSlice => { + return rt.byteSliceFrom(rt.byteSliceToArray(a04)); + }, rt.drop)).reverse(); + const _399: rt.ByteSlice | undefined = rt.arcGetMut(arc3); + if (_399 !== undefined) { + rt.iterForEach(rt.iterSliceMut(rt.byteSliceView(_399)), (x: rt.Place): undefined => { + x.v = x.v ^ 15; + }); + } + putBytes(arc3.value, out); + putBytes(shared.value, out); + arcCounts$slice_u8(shared, out); + shared[Symbol.dispose](); + arc3[Symbol.dispose](); + weak2[Symbol.dispose](); + b4[Symbol.dispose](); + a3[Symbol.dispose](); + } +} + +/** `u16`s, each way, written, compared, and counted. */ +export function wides(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const wide: rt.u16[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(rt.byteSliceRange(data, 0, rt.usizeRem(kind >> 3 as rt.usize, rt.usizeAdd(data.length, 1))))), (_2: rt.u8): rt.u16 => { + return rt.u16Mul(_2 as rt.u16, 257); + }), undefined, 2, true); + const fromRef: rt.Arc = new rt.Arc(rt.sliceRange(wide, 0).slice()); + const fromVec: rt.Arc = new rt.Arc(rt.vecExact(wide.slice(), 2)); + const fromBox: rt.Arc = new rt.Arc(rt.vecExact(wide.slice(), 2)); + const fromArray: rt.Arc = new rt.Arc([1, 2, 768]); + const collected: rt.Arc = new rt.Arc(rt.iterToArray(rt.iterMap(rt.iterSlice(wide), (_23: rt.u16): rt.u16 => { + return rt.intRotateLeft(_23, 3, 16, false); + }), undefined, 2, true)); + const empty: rt.Arc = new rt.Arc([]); + const iter: rt.Iter> = rt.iterSlice([fromRef, fromBox, fromArray, collected]); + while (true) { + const _43: rt.Arc | rt.Done = iter.next(); + if (_43 === rt.DONE) { + break; + } + putWides(_43.value, out); + } + putWides(fromVec.value, out); + putWides(empty.value, out); + rt.byteVecPush(out, rt.eqArc(rt.eqSlice(rt.same), true)(fromRef, fromBox) ? 1 : 0); + rt.byteVecPush(out, rt.cmpArc(rt.cmpSlice(rt.cmp))(collected, fromRef) & 0xff); + rt.byteVecPush(out, rt.u64Eq(hash$Rc_slice_u16(collected), hash$slice_u16(rt.sliceRange(collected.value, 0))) ? 1 : 0); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(collected.value, f, rt.u16Debug), (f: rt.Formatter) => rt.fmtList(fromVec.value, f, rt.u16Debug)]; + put(out, rt.fmtFormat([args2[0], "|", args2[1]])); + let shared: rt.Arc = rt.arcClone(fromRef); + counts$slice_u16(fromRef, out); + if (rt.u8Rem(kind, 2) === 0) { + rt.sliceSortUnstable(rt.arcMakeMut(rt.place(() => shared, (value2) => shared = value2), (a02: rt.u16[]): rt.u16[] => { + return a02.slice(); + }, rt.drop), rt.cmpLt((a: rt.u16, b: rt.u16): rt.Ordering => { + return rt.cmp(b, a); + }), 2, true, true); + } else { + const _98: rt.Place | undefined = rt.sliceLastMut(rt.arcMakeMut(rt.place(() => shared, (value) => shared = value), (a0: rt.u16[]): rt.u16[] => { + return a0.slice(); + }, rt.drop)); + if (_98 !== undefined) { + _98.v = 48879; + } + } + counts$slice_u16(fromRef, out); + rt.byteVecPush(out, shared === fromRef ? 1 : 0); + putWides(shared.value, out); + putWides(fromRef.value, out); + const alone: rt.Arc = collected; + const _117: rt.u16[] | undefined = rt.arcGetMut(alone); + if (_117 !== undefined) { + rt.iterForEach(rt.iterSliceMut(_117), (x3: rt.Place): undefined => { + x3.v = x3.v ^ 3855; + }); + } + putWides(alone.value, out); + alone[Symbol.dispose](); + shared[Symbol.dispose](); + empty[Symbol.dispose](); + fromArray[Symbol.dispose](); + fromBox[Symbol.dispose](); + fromVec[Symbol.dispose](); + fromRef[Symbol.dispose](); +} + +/** + * Values JS copies, held in a shared slice apart from what they came from, and from each + * clone `make_mut` makes. + */ +export function copies(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const data2: rt.ByteSlice = rt.byteSliceRange(data, 0, rt.usizeRem(kind >> 3 as rt.usize, rt.usizeAdd(data.length, 1))); + const source: [rt.u8, rt.u16][] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_2: rt.u8): [rt.u8, rt.u16] => { + const b: rt.u8 = _2; + return [b, (((b as rt.u16)) << 4) & 0xffff] as [rt.u8, rt.u16]; + }), undefined, 4, true); + const fromRef: rt.Arc<[rt.u8, rt.u16][]> = new rt.Arc(rt.sliceRange(source, 0).map(copy$tuple2_u8_u16)); + const fromVec: rt.Arc<[rt.u8, rt.u16][]> = new rt.Arc(rt.vecExact(source.map(copy$tuple2_u8_u16), 4)); + const p: [rt.u8, rt.u16] = [option_unwrapOr$0r2bmpr(rt.byteSliceFirst(data2), 5), 6]; + const twins: rt.Arc<[rt.u8, rt.u16][]> = new rt.Arc([copy$tuple2_u8_u16(p), copy$tuple2_u8_u16(p)]); + const iter: rt.Iter<[rt.u8, rt.u16]> = rt.iterSlice(source); + while (true) { + const _35: [rt.u8, rt.u16] | rt.Done = iter.next(); + if (_35 === rt.DONE) { + break; + } + _35[0] = _35[0] ^ 255; + } + const _39: [rt.u8, rt.u16][] = rt.optionExpect(rt.arcGetMut(twins), "alone"); + rt.idx(_39, 0); + _39[0][0] = _39[0][0] ^ 1; + pairs(source, out); + pairs(fromRef.value, out); + pairs(fromVec.value, out); + pairs(twins.value, out); + rt.byteVecPush(out, p[0]); + let shared: rt.Arc<[rt.u8, rt.u16][]> = rt.arcClone(fromRef); + const _63: [rt.u8, rt.u16] | undefined = rt.sliceFirst(rt.arcMakeMut(rt.place(() => shared, (value) => shared = value), (a0: [rt.u8, rt.u16][]): [rt.u8, rt.u16][] => { + return a0.map(copy$tuple2_u8_u16); + }, rt.drop)); + if (_63 !== undefined) { + _63[1] = 1; + } + pairs(shared.value, out); + pairs(fromRef.value, out); + const quads: rt.Arc = new rt.Arc(rt.iterToArray(rt.iterMap(rt.byteSliceChunksExact(data2, 2), (c: rt.ByteSlice): Uint8Array => { + rt.idx(c, 0); + const _3: rt.u8 = c.data[c.start]; + rt.idx(c, 1); + return Uint8Array.of(_3, c.data[c.start + 1]); + }), undefined, 2, true)); + let copy: rt.Arc = rt.arcClone(quads); + const _79: rt.ByteSlice | undefined = rt.optionMap(rt.sliceFirst(rt.arcMakeMut(rt.place(() => copy, (value2) => copy = value2), (a02: Uint8Array[]): Uint8Array[] => { + return a02.map(copy$array_u8); + }, rt.drop)), rt.byteSliceFrom); + if (_79 !== undefined) { + _79.data[_79.start] = 119; + } + const iter2: rt.Iter = rt.iterChain(rt.iterLend(rt.iterSlice(quads.value), rt.byteSliceFrom), rt.iterLend(rt.iterSlice(copy.value), rt.byteSliceFrom)); + while (true) { + const _95: rt.ByteSlice | rt.Done = iter2.next(); + if (_95 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _95); + } + rt.byteVecPush(out, rt.eqArc(rt.eqSlice(rt.eqBytes), true)(quads, copy) ? 1 : 0); + copy[Symbol.dispose](); + quads[Symbol.dispose](); + shared[Symbol.dispose](); + twins[Symbol.dispose](); + fromVec[Symbol.dispose](); + fromRef[Symbol.dispose](); +} + +/** + * Items that log their clones and drops: each shared slice drops its items in order as its + * last owner drops, and not before, however it was made. + */ +export function drops(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + let kept!: rt.Arc | undefined; + const data2: rt.ByteSlice = rt.byteSliceRange(data, 0, rt.usizeRem(kind >> 3 as rt.usize, rt.usizeAdd(data.length, 1))); + const log: rt.Arc> = new rt.Arc(new rt.RefCell(new rt.ByteVec())); + const logged: (a0: rt.u8) => Logged.Logged = (id: rt.u8): Logged.Logged => { + return new Logged.Logged(id, rt.arcClone(log)); + }; + const shared: rt.Arc = new rt.Arc(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_2: rt.u8): Logged.Logged => { + return logged(_2 & 126); + }), undefined, 8, true)); + ids(shared.value, out); + flush(log.value, out); + const twin: rt.Arc = rt.arcClone(shared); + const weak: rt.Weak = new rt.Weak(twin); + flush(log.value, out); + rt.arcDrop(shared, drop$slice_shares_Logged); + flush(log.value, out); + const fromRef: rt.Arc = new rt.Arc(rt.sliceRange(twin.value, 0).map(Logged.clone$Clone)); + flush(log.value, out); + rt.arcDrop(twin, drop$slice_shares_Logged); + flush(log.value, out); + const _58: rt.Arc | undefined = rt.weakUpgrade(weak); + rt.byteVecPush(out, _58 === undefined ? 1 : 0); + drop$Option_Rc_slice_shares_Logged(_58); + weak[Symbol.dispose](); + flush(log.value, out); + const collected: rt.Arc = new rt.Arc(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_24: rt.u8): Logged.Logged => { + return logged(_24 | 1); + }), undefined, 8, true)); + ids(collected.value, out); + const fromBox: rt.Arc = new rt.Arc([logged(16), logged(18)]); + const fromArray: rt.Arc = new rt.Arc([logged(20)]); + const cow: rt.Arc = new rt.Arc(rt.cowIntoOwned(new rt.Borrowed(rt.sliceRange(fromRef.value, 0)), Logged.clone$Clone)); + flush(log.value, out); + rt.arcDrop(fromArray, drop$slice_shares_Logged); + rt.arcDrop(collected, drop$slice_shares_Logged); + flush(log.value, out); + let mine: rt.Arc = rt.arcClone(fromBox); + const _101: Logged.Logged = logged(22); + const _104: Logged.Logged[] = rt.arcMakeMut(rt.place(() => mine, (value) => mine = value), (a0: Logged.Logged[]): Logged.Logged[] => { + return a0.map(Logged.clone$Clone); + }, drop$Rc_slice_shares_Logged); + rt.idx(_104, 0); + _104[0][Symbol.dispose](); + _104[0] = _101; + flush(log.value, out); + ids(mine.value, out); + ids(fromBox.value, out); + rt.arcDrop(fromBox, drop$slice_shares_Logged); + flush(log.value, out); + const _123: Logged.Logged[] | undefined = rt.arcGetMut(mine); + if (_123 !== undefined) { + const _127: Logged.Logged = logged(24); + rt.idx(_123, 1); + _123[1][Symbol.dispose](); + _123[1] = _127; + } + flush(log.value, out); + const held: Held.Held = new Held.Held(mine, logged(32)); + rt.byteVecPush(out, held.items.value.length & 0xff); + rt.byteVecPush(out, held.last.id); + if (rt.u8Rem(kind, 2) === 0) { + kept = rt.arcClone(held.items); + } else { + kept = undefined; + } + held[Symbol.dispose](); + flush(log.value, out); + drop$Option_Rc_slice_shares_Logged(kept); + flush(log.value, out); + const empty: rt.Arc = new rt.Arc([]); + const _167: rt.Arc = rt.arcClone(empty); + ids(_167.value, out); + rt.arcDrop(_167, drop$slice_shares_Logged); + rt.arcDrop(cow, drop$slice_shares_Logged); + rt.arcDrop(fromRef, drop$slice_shares_Logged); + flush(log.value, out); + rt.arcDrop(empty, drop$slice_shares_Logged); + log[Symbol.dispose](); +} + +/** `Rc` and `Arc`, each way, read, counted, and written. */ +export function strs(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const s: string = text(data); + const fromRef: rt.Arc = new rt.Arc(s); + const fromString: rt.Arc = new rt.Arc(s); + const fromBox: rt.Arc = new rt.Arc(s); + let source: string = s; + const fromMut: rt.Arc = new rt.Arc(source); + source = rt.strToAsciiUppercase(source); + const borrowed: rt.Arc = new rt.Arc(s); + const owned: rt.Arc = new rt.Arc(s); + const into: rt.Arc = new rt.Arc(s); + const empty: rt.Arc = new rt.Arc(""); + const arcEmpty: rt.Arc = new rt.Arc(""); + put(out, fromRef.value); + put(out, fromString.value); + put(out, fromBox.value); + put(out, fromMut.value); + put(out, source); + put(out, borrowed.value); + put(out, owned.value); + put(out, into.value); + put(out, empty.value); + put(out, arcEmpty.value); + rt.byteVecPush(out, rt.eqArc(rt.same, true)(fromRef, into) ? 1 : 0); + rt.byteVecPush(out, rt.cmpArc(rt.cmpStr)(fromRef, empty) & 0xff); + rt.byteVecPush(out, rt.u64Eq(hash$Rc_str(fromRef), hash$str(s)) ? 1 : 0); + rt.byteVecPush(out, rt.stringLen(fromRef.value) & 0xff); + rt.byteVecPush(out, rt.iterCount(rt.strChars(fromRef.value)) & 0xff); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, fromRef.value), (f: rt.Formatter) => rt.fmtStr(fromString.value, f), (f: rt.Formatter) => rt.fmtStr(empty.value, f)]; + put(out, rt.fmtFormat([args2[0], "|", args2[1], "|", args2[2]])); + const twin: rt.Arc = rt.arcClone(fromRef); + counts$str(twin, out); + rt.byteVecPush(out, twin === fromRef ? 1 : 0); + rt.byteVecPush(out, into === fromRef ? 1 : 0); + const mine: rt.Arc = into; + if (rt.u8Rem(kind, 2) === 0) { + const _130: rt.Place | undefined = rt.arcGetMutPlace(mine); + if (_130 !== undefined) { + _130.v = rt.strToAsciiUppercase(_130.v); + } + } else { + let _137: rt.Arc = rt.arcClone(twin); + const _135: rt.Place = rt.arcMakeMutPlace(rt.place(() => _137, (value2) => _137 = value2), undefined, rt.drop); + _135.v = rt.strToAsciiLowercase(_135.v); + _137[Symbol.dispose](); + } + let shared: rt.Arc = twin; + const _141: rt.Place = rt.arcMakeMutPlace(rt.place(() => shared, (value3) => shared = value3), undefined, rt.drop); + _141.v = rt.strToAsciiUppercase(_141.v); + counts$str(shared, out); + counts$str(fromRef, out); + put(out, mine.value); + put(out, shared.value); + put(out, fromRef.value); + let arc: rt.Arc = rt.arcClone(fromString); + const _159: rt.Place = rt.arcMakeMutPlace(rt.place(() => arc, (value4) => arc = value4), undefined, rt.drop); + _159.v = rt.strToAsciiUppercase(_159.v); + put(out, arc.value); + put(out, fromString.value); + put(out, arc.value); + put(out, rt.fmtToString((f: rt.Formatter) => rt.fmtPad(f, fromBox.value))); + arc[Symbol.dispose](); + shared[Symbol.dispose](); + mine[Symbol.dispose](); + arcEmpty[Symbol.dispose](); + empty[Symbol.dispose](); + owned[Symbol.dispose](); + borrowed[Symbol.dispose](); + fromMut[Symbol.dispose](); + fromBox[Symbol.dispose](); + fromString[Symbol.dispose](); + fromRef[Symbol.dispose](); +} + +/** A generic type's shared slice, of bytes, of `u16`s, and of items that log. */ +export function generics(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const data2: rt.ByteSlice = rt.byteSliceRange(data, 0, rt.usizeRem(kind >> 3 as rt.usize, rt.usizeAdd(data.length, 1))); + const bytes: Shared.Shared = Shared.new$u8(rt.byteSliceToByteVec(data2)); + const copy: Shared.Shared = Shared.clone$Clone_u8(bytes); + Shared.setLast$u8(bytes, 238); + putBytes((bytes.items as rt.Arc).value, out); + putBytes((copy.items as rt.Arc).value, out); + rt.byteVecPush(out, option_unwrapOr$0r2bmpr(Shared.first$u8(bytes), 170)); + counts$slice_u8(copy.items as rt.Arc, out); + const wide: Shared.Shared = Shared.collected$u16_iter_Map_slice_Iter_u8_shares_generics_closure0(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_2: rt.u8): rt.u16 => { + return (((_2 as rt.u16)) << 8) & 0xffff; + })); + const twin: Shared.Shared = Shared.clone$Clone_u16(wide); + counts$slice_u16(wide.items as rt.Arc, out); + Shared.setLast$u16(wide, 48879); + putWides((wide.items as rt.Arc).value, out); + putWides((twin.items as rt.Arc).value, out); + const log: rt.Arc> = new rt.Arc(new rt.RefCell(new rt.ByteVec())); + const logged: (a0: rt.u8) => Logged.Logged = (id: rt.u8): Logged.Logged => { + return new Logged.Logged(id, rt.arcClone(log)); + }; + const items: Shared.Shared = Shared.new$shares_Logged(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_23: rt.u8): Logged.Logged => { + return logged(_23 & 126); + }), undefined, 8, true)); + const kept: Shared.Shared = Shared.clone$Clone_shares_Logged(items); + flush(log.value, out); + const _67: Logged.Logged = logged(64); + Shared.setLast$shares_Logged(items, _67); + flush(log.value, out); + ids((items.items as rt.Arc).value, out); + rt.byteVecPush(out, option_mapOr$148vfk5(Shared.first$shares_Logged(items), 170, (l: Logged.Logged): rt.u8 => { + return l.id; + })); + kept[Symbol.dispose](); + flush(log.value, out); + items[Symbol.dispose](); + flush(log.value, out); + log[Symbol.dispose](); + twin[Symbol.dispose](); + wide[Symbol.dispose](); + copy[Symbol.dispose](); + bytes[Symbol.dispose](); +} + +/** + * Shared slices and text as keys a borrow of their slice or text looks up, and through + * `AsRef`, `Borrow`, and `FromIterator::from_iter`. + */ +export function keys(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const data2: rt.ByteSlice = rt.byteSliceRange(data, 0, rt.usizeRem(kind >> 3 as rt.usize, rt.usizeAdd(data.length, 1))); + const words: string[] = rt.iterToArray(rt.iterMap(rt.byteSliceChunks(data2, 2), text), undefined, 12, true); + const _19: rt.Iter> = rt.iterMap(rt.iterSlice(words), (w: string): rt.Arc => { + return new rt.Arc(w); + }); + const interned: rt.HashSet> = rt.hashExtendKeys(rt.hashNew(rt.hashing(rt.hashArc(rt.hashStr), rt.eqArc(rt.same, true))) as rt.HashSet>, _19, rt.drop, undefined, 117440512); + rt.byteVecPush(out, rt.hashLen(interned) & 0xff); + for (const _30 of words) { + rt.byteVecPush(out, rt.hashContains(interned, new rt.Arc(_30)) ? 1 : 0); + rt.byteVecPush(out, option_mapOr$03siheh(rt.hashKey(interned, new rt.Arc(_30)), 0, (k: rt.Arc): rt.u8 => { + return k.strong & 0xff; + })); + } + rt.byteVecPush(out, rt.hashContains(interned, new rt.Arc("\u0000")) ? 1 : 0); + const counted: rt.HashMap, rt.u8> = rt.hashNew(rt.hashing(rt.hashArc(rt.hashBytes), rt.eqArc(rt.eqBytes, true))) as rt.HashMap, rt.u8>; + const iter2: rt.Iter = rt.byteSliceChunks(data2, 3); + while (true) { + const _53: rt.ByteSlice | rt.Done = iter2.next(); + if (_53 === rt.DONE) { + break; + } + const _60: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(_53))); + const _57: rt.Place = rt.entryOrInsertWithMut(rt.entry(counted, _60, rt.drop), (): rt.u8 => { + return 0; + }); + _57.v = rt.u8Add(_57.v, 1); + } + const iter3: rt.Iter = rt.byteSliceChunks(data2, 3); + while (true) { + const _65: rt.ByteSlice | rt.Done = iter3.next(); + if (_65 === rt.DONE) { + break; + } + rt.byteVecPush(out, option_unwrapOr$0r2bmpr(rt.hashGet(counted, new rt.Arc(_65)), 0)); + } + const fromIter: rt.Arc = new rt.Arc(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data2)), (_2: rt.u8): rt.u16 => { + return rt.u16Add(_2 as rt.u16, 1); + }), undefined, 2, true)); + putWides(fromIter.value, out); + putWides(fromIter.value, out); + const text_: rt.Arc = new rt.Arc(rt.strsJoin(words, "")); + put(out, text_.value); + put(out, text_.value); + let slot: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); + const other: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(rt.byteSliceRange(data2, 0, rt.usizeDiv(data2.length, 2))))); + const old = slot; + slot = rt.arcClone(other); + old[Symbol.dispose](); + rt.byteVecPush(out, slot === other ? 1 : 0); + counts$slice_u8(other, out); + other[Symbol.dispose](); + slot[Symbol.dispose](); + text_[Symbol.dispose](); + fromIter[Symbol.dispose](); + rt.hashDrop(counted, rt.drop); + rt.hashDrop(interned, rt.drop); +} + +//# sourceMappingURL=shares.ts.map diff --git a/ts/fixtures/lang/shares/src/lib.rs b/ts/fixtures/lang/shares/src/lib.rs new file mode 100644 index 000000000..8ef56b34d --- /dev/null +++ b/ts/fixtures/lang/shares/src/lib.rs @@ -0,0 +1,27 @@ +//! A part of the language the driver translates, exercised against native Rust: what +//! each of its modules says. + +#[path = "../../harness.rs"] +pub mod harness; +mod shares; +#[cfg(target_arch = "wasm32")] +#[path = "../../../wasm.rs"] +mod wasm; +#[cfg(target_arch = "wasm32")] +use harness::run as entry; + +use harness::Case; + +/// Each case's name and what it runs. The first two bytes, big-endian, pick one modulo +/// their count, so a case added at the end moves no other. +fn cases() -> Vec<(&'static str, Case)> { + vec![ + ("shares::bytes", shares::bytes), + ("shares::wides", shares::wides), + ("shares::copies", shares::copies), + ("shares::drops", shares::drops), + ("shares::strs", shares::strs), + ("shares::generics", shares::generics), + ("shares::keys", shares::keys), + ] +} diff --git a/ts/fixtures/lang/shares/src/shares.rs b/ts/fixtures/lang/shares/src/shares.rs new file mode 100644 index 000000000..d5a149473 --- /dev/null +++ b/ts/fixtures/lang/shares/src/shares.rs @@ -0,0 +1,566 @@ +//! `Rc<[T]>`, `Arc<[T]>`, `Rc`, and `Arc`: made by `From` of a `Vec`, a slice, +//! a `&mut` slice, a `Box`, an array, and a `Cow`, by `collect` and `Default`, read +//! through `Deref`, compared, hashed, and printed as their slice is, cloned and counted, +//! written through `get_mut` and `make_mut`, and downgraded, of bytes, of `u16`s, of +//! values JS copies, and of values that log their clones and drops, empty or not, with +//! what drops dropped when its last owner does; held by a generic type at each of those, +//! and looked up as map keys by a borrow of their slice or text. + +use std::borrow::{Borrow, Cow}; +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::rc::{Rc, Weak}; +use std::sync::Arc; + +use crate::harness::{put, text}; + +/// Logs its id as it drops, and as it is cloned, the id with the high bit set: its clone's +/// id is one more. +struct Logged { + id: u8, + log: Rc>>, +} + +impl Clone for Logged { + fn clone(&self) -> Self { + self.log.borrow_mut().push(0x80 | self.id); + Self { + id: self.id.wrapping_add(1), + log: self.log.clone(), + } + } +} + +impl Drop for Logged { + fn drop(&mut self) { + self.log.borrow_mut().push(self.id); + } +} + +/// A shared slice in a field, beside one that drops after it. +struct Held { + items: Rc<[Logged]>, + last: Logged, +} + +/// A shared slice of its parameter, made from a `Vec` and an iterator, cloned, and written, +/// as each instance holds it. +struct Shared { + items: Rc<[T]>, +} + +impl Shared { + fn new(items: Vec) -> Self { + Self { items: items.into() } + } + + fn collected(items: impl Iterator) -> Self { + Self { items: items.collect() } + } + + fn first(&self) -> Option<&T> { + self.items.first() + } + + /// Its items, made its own, with `item` in place of its last. + fn set_last(&mut self, item: T) { + if let Some(last) = Rc::make_mut(&mut self.items).last_mut() { + *last = item; + } + } +} + +impl Clone for Shared { + fn clone(&self) -> Self { + Self { + items: Rc::clone(&self.items), + } + } +} + +/// Puts what was logged since the last flush, after a marker. +fn flush(log: &RefCell>, out: &mut Vec) { + out.push(0xfd); + out.extend(log.borrow_mut().drain(..)); +} + +fn hash(value: &T) -> u64 { + let mut h = DefaultHasher::new(); + value.hash(&mut h); + h.finish() +} + +/// Puts `b`'s length and bytes. +fn put_bytes(b: &[u8], out: &mut Vec) { + out.push(b.len() as u8); + out.extend_from_slice(b); +} + +/// Puts `b`'s length and each `u16`'s bytes. +fn put_wides(b: &[u16], out: &mut Vec) { + out.push(b.len() as u8); + for x in b { + out.extend(x.to_le_bytes()); + } +} + +/// Puts the ids of `b`. +fn ids(b: &[Logged], out: &mut Vec) { + out.push(b.len() as u8); + out.extend(b.iter().map(|l| l.id)); +} + +/// Puts each pair's bytes. +fn pairs(b: &[(u8, u16)], out: &mut Vec) { + out.push(b.len() as u8); + for (a, w) in b { + out.push(*a); + out.extend(w.to_le_bytes()); + } +} + +/// Puts an `Rc`'s strong and weak counts. +fn counts(rc: &Rc, out: &mut Vec) { + out.push(Rc::strong_count(rc) as u8); + out.push(Rc::weak_count(rc) as u8); +} + +/// Puts an `Arc`'s strong and weak counts. +fn arc_counts(arc: &Arc, out: &mut Vec) { + out.push(Arc::strong_count(arc) as u8); + out.push(Arc::weak_count(arc) as u8); +} + +/// Writes through a `&mut` to bytes another function was handed. +fn scramble(b: &mut [u8]) { + b.reverse(); + for x in b.iter_mut() { + *x = x.wrapping_add(1); + } + if let Some(first) = b.first_mut() { + *first ^= 0xff; + } +} + +/// Bytes, each way, read, counted, and written apart from what they came from. +pub fn bytes(kind: u8, data: &[u8], out: &mut Vec) { + // As many bytes as `kind`'s high bits pick, none included. + let data = &data[..usize::from(kind >> 3) % (data.len() + 1)]; + match kind % 4 { + // Made each way, apart from what each came from. + 0 => { + let mut source = data.to_vec(); + let from_ref: Rc<[u8]> = Rc::from(&source[..]); + let from_mut: Arc<[u8]> = Arc::from(&mut source[..]); + scramble(&mut source); + put_bytes(&from_ref, out); + put_bytes(&from_mut, out); + put_bytes(&source, out); + let mut spare = Vec::with_capacity(64); + spare.extend_from_slice(data); + let from_vec = Rc::<[u8]>::from(spare); + put_bytes(&from_vec, out); + let into: Arc<[u8]> = data.to_vec().into(); + put_bytes(&into, out); + let from_box: Rc<[u8]> = Rc::from(Box::<[u8]>::from(data)); + put_bytes(&from_box, out); + let array = [data.first().copied().unwrap_or(1), 2, 3]; + let from_array: Arc<[u8]> = Arc::from(array); + put_bytes(&from_array, out); + let collected: Rc<[u8]> = data.iter().map(|&x| x ^ 0x55).collect(); + put_bytes(&collected, out); + let arc_collected: Arc<[u8]> = data.iter().rev().copied().collect(); + put_bytes(&arc_collected, out); + let empty: Rc<[u8]> = Default::default(); + put_bytes(&empty, out); + let arc_empty = Arc::<[u8]>::default(); + put_bytes(&arc_empty, out); + let borrowed: Rc<[u8]> = Rc::from(Cow::Borrowed(data)); + put_bytes(&borrowed, out); + let owned: Arc<[u8]> = Arc::from(Cow::<[u8]>::Owned(data.to_vec())); + put_bytes(&owned, out); + // Of text's bytes, which share its count, as std shares its allocation. + let s = Rc::::from(text(data)); + let twin = s.clone(); + let of_str: Rc<[u8]> = Rc::from(s); + counts(&of_str, out); + let of_twin: Rc<[u8]> = Rc::from(twin); + out.push(u8::from(Rc::ptr_eq(&of_str, &of_twin))); + counts(&of_twin, out); + drop(of_twin); + counts(&of_str, out); + put_bytes(&of_str, out); + let arc_of_str: Arc<[u8]> = Arc::from(Arc::::from(text(data))); + put_bytes(&arc_of_str, out); + // Back to what owns its bytes, which grows as any does. + let mut v = from_vec.to_vec(); + v.push(0xee); + v.extend_from_slice(&collected); + put_bytes(&v, out); + let v = into.to_vec(); + put_bytes(&v, out); + let b: Box<[u8]> = Box::from(&*from_box); + put_bytes(&b, out); + } + // Compared, ordered, hashed, and printed as their slice is. + 1 => { + let a: Rc<[u8]> = data.into(); + let half = &data[..data.len() / 2]; + let b: Rc<[u8]> = half.into(); + out.push(u8::from(a == b)); + out.push(u8::from(a != b)); + out.push(u8::from(a < b)); + out.push(a.cmp(&b) as u8); + out.push(b.partial_cmp(&a).map_or(9, |o| o as u8)); + out.push(u8::from(*a == *data)); + out.push(u8::from(hash(&a) == hash(data))); + out.extend(hash(&b).to_le_bytes()); + out.push(a.len() as u8); + out.push(u8::from(a.is_empty())); + out.push(a.iter().copied().fold(0, u8::wrapping_add)); + out.push(a.first().copied().unwrap_or(0xaa)); + out.push(a.get(1).copied().unwrap_or(0xbb)); + let arc: Arc<[u8]> = Arc::from(data); + out.push(u8::from(*arc == *a)); + out.push(u8::from(hash(&arc) == hash(&a))); + put(out, &format!("{a:?}|{b:?}|{arc:?}|{:?}", Rc::<[u8]>::default())); + } + // Cloned and counted: one allocation every clone shares, and every `Weak`. + 2 => { + let a: Rc<[u8]> = Rc::from(data); + counts(&a, out); + let b = a.clone(); + counts(&a, out); + out.push(u8::from(Rc::ptr_eq(&a, &b))); + let c: Rc<[u8]> = Rc::from(data); + out.push(u8::from(Rc::ptr_eq(&a, &c))); + out.push(u8::from(a == c)); + let weak: Weak<[u8]> = Rc::downgrade(&a); + counts(&b, out); + drop(a); + counts(&b, out); + out.push(u8::from(weak.upgrade().is_some_and(|up| Rc::ptr_eq(&up, &b)))); + out.push(weak.strong_count() as u8); + drop(b); + out.push(u8::from(weak.upgrade().is_none())); + out.push(weak.strong_count() as u8); + let arc: Arc<[u8]> = Arc::from(data.to_vec()); + let twin = Arc::clone(&arc); + arc_counts(&arc, out); + out.push(u8::from(Arc::ptr_eq(&arc, &twin))); + let arc_weak = Arc::downgrade(&twin); + arc_counts(&arc, out); + drop(twin); + arc_counts(&arc, out); + drop(arc_weak); + arc_counts(&arc, out); + put_bytes(&arc, out); + } + // Written through `get_mut`, only when no other owner shares it, and `make_mut`, which + // copies them first when one does. + _ => { + let mut a: Rc<[u8]> = Rc::from(data); + if let Some(m) = Rc::get_mut(&mut a) { + scramble(m); + } + put_bytes(&a, out); + let b = a.clone(); + out.push(u8::from(Rc::get_mut(&mut a).is_none())); + scramble(Rc::make_mut(&mut a)); + out.push(u8::from(Rc::ptr_eq(&a, &b))); + counts(&a, out); + counts(&b, out); + put_bytes(&a, out); + put_bytes(&b, out); + // Alone again, `make_mut` writes in place. + let before = a.clone(); + drop(before); + Rc::make_mut(&mut a).fill(0x11); + counts(&a, out); + put_bytes(&a, out); + // A `Weak` alone leaves it to `make_mut` to move it out, which the `Weak` no + // longer sees. + let weak = Rc::downgrade(&a); + if let Some(first) = Rc::make_mut(&mut a).first_mut() { + *first = 0x22; + } + out.push(u8::from(weak.upgrade().is_none())); + put_bytes(&a, out); + let mut arc: Arc<[u8]> = Arc::from(data); + let shared = Arc::clone(&arc); + Arc::make_mut(&mut arc).reverse(); + if let Some(m) = Arc::get_mut(&mut arc) { + m.iter_mut().for_each(|x| *x ^= 0x0f); + } + put_bytes(&arc, out); + put_bytes(&shared, out); + arc_counts(&shared, out); + } + } +} + +/// `u16`s, each way, written, compared, and counted. +pub fn wides(kind: u8, data: &[u8], out: &mut Vec) { + let data = &data[..usize::from(kind >> 3) % (data.len() + 1)]; + let wide: Vec = data.iter().map(|&x| u16::from(x) * 257).collect(); + let from_ref: Rc<[u16]> = Rc::from(&wide[..]); + let from_vec: Arc<[u16]> = Arc::from(wide.clone()); + let from_box: Rc<[u16]> = wide.clone().into_boxed_slice().into(); + let from_array = Rc::<[u16]>::from([1, 2, 0x300]); + let collected: Rc<[u16]> = wide.iter().map(|&x| x.rotate_left(3)).collect(); + let empty: Arc<[u16]> = Arc::default(); + for w in [&from_ref, &from_box, &from_array, &collected] { + put_wides(w, out); + } + put_wides(&from_vec, out); + put_wides(&empty, out); + out.push(u8::from(from_ref == from_box)); + out.push(collected.cmp(&from_ref) as u8); + out.push(u8::from(hash(&collected) == hash(&collected[..]))); + put(out, &format!("{collected:?}|{from_vec:?}")); + let mut shared = from_ref.clone(); + counts(&from_ref, out); + match kind % 2 { + 0 => Rc::make_mut(&mut shared).sort_unstable_by(|a, b| b.cmp(a)), + _ => { + if let Some(last) = Rc::make_mut(&mut shared).last_mut() { + *last = 0xbeef; + } + } + } + counts(&from_ref, out); + out.push(u8::from(Rc::ptr_eq(&shared, &from_ref))); + put_wides(&shared, out); + put_wides(&from_ref, out); + let mut alone = collected; + if let Some(m) = Rc::get_mut(&mut alone) { + m.iter_mut().for_each(|x| *x ^= 0x0f0f); + } + put_wides(&alone, out); +} + +/// Values JS copies, held in a shared slice apart from what they came from, and from each +/// clone `make_mut` makes. +pub fn copies(kind: u8, data: &[u8], out: &mut Vec) { + let data = &data[..usize::from(kind >> 3) % (data.len() + 1)]; + let mut source: Vec<(u8, u16)> = data.iter().map(|&b| (b, u16::from(b) << 4)).collect(); + let from_ref: Rc<[(u8, u16)]> = Rc::from(&source[..]); + let from_vec: Arc<[(u8, u16)]> = Arc::from(source.clone()); + let p = (data.first().copied().unwrap_or(5), 6u16); + let mut twins = Rc::<[(u8, u16)]>::from([p, p]); + for s in source.iter_mut() { + s.0 ^= 0xff; + } + Rc::get_mut(&mut twins).expect("alone")[0].0 ^= 1; + pairs(&source, out); + pairs(&from_ref, out); + pairs(&from_vec, out); + pairs(&twins, out); + out.push(p.0); + let mut shared = from_ref.clone(); + if let Some(first) = Rc::make_mut(&mut shared).first_mut() { + first.1 = 1; + } + pairs(&shared, out); + pairs(&from_ref, out); + let quads: Rc<[[u8; 2]]> = data.chunks_exact(2).map(|c| [c[0], c[1]]).collect(); + let mut copy = quads.clone(); + if let Some(q) = Rc::make_mut(&mut copy).first_mut() { + q[0] = 0x77; + } + for q in quads.iter().chain(copy.iter()) { + out.extend_from_slice(q); + } + out.push(u8::from(quads == copy)); +} + +/// Items that log their clones and drops: each shared slice drops its items in order as its +/// last owner drops, and not before, however it was made. +pub fn drops(kind: u8, data: &[u8], out: &mut Vec) { + let data = &data[..usize::from(kind >> 3) % (data.len() + 1)]; + let log = Rc::new(RefCell::new(Vec::new())); + let logged = |id: u8| Logged { id, log: log.clone() }; + let items: Vec = data.iter().map(|&b| logged(b & 0x7e)).collect(); + let shared: Rc<[Logged]> = Rc::from(items); + ids(&shared, out); + flush(&log, out); + let twin = shared.clone(); + let weak = Rc::downgrade(&twin); + flush(&log, out); + drop(shared); + flush(&log, out); + let from_ref: Rc<[Logged]> = Rc::from(&twin[..]); + flush(&log, out); + drop(twin); + flush(&log, out); + out.push(u8::from(weak.upgrade().is_none())); + drop(weak); + flush(&log, out); + let collected: Arc<[Logged]> = data.iter().map(|&b| logged(b | 1)).collect(); + ids(&collected, out); + let from_box: Rc<[Logged]> = Rc::from(Box::<[Logged]>::from([logged(0x10), logged(0x12)])); + let from_array: Arc<[Logged]> = Arc::from([logged(0x14)]); + let cow: Rc<[Logged]> = Rc::from(Cow::Borrowed(&from_ref[..])); + flush(&log, out); + drop(from_array); + drop(collected); + flush(&log, out); + // A clone `make_mut` makes clones every item, and the item it overwrites drops. + let mut mine = from_box.clone(); + Rc::make_mut(&mut mine)[0] = logged(0x16); + flush(&log, out); + ids(&mine, out); + ids(&from_box, out); + drop(from_box); + flush(&log, out); + if let Some(m) = Rc::get_mut(&mut mine) { + m[1] = logged(0x18); + } + flush(&log, out); + let held = Held { + items: mine, + last: logged(0x20), + }; + out.push(held.items.len() as u8); + out.push(held.last.id); + let kept = match kind % 2 { + 0 => Some(held.items.clone()), + _ => None, + }; + drop(held); + flush(&log, out); + drop(kept); + flush(&log, out); + let empty: Rc<[Logged]> = Rc::default(); + ids(&empty.clone(), out); + drop(cow); + drop(from_ref); + flush(&log, out); +} + +/// `Rc` and `Arc`, each way, read, counted, and written. +pub fn strs(kind: u8, data: &[u8], out: &mut Vec) { + let s = text(data); + let from_ref: Rc = Rc::from(s.as_str()); + let from_string: Arc = Arc::from(s.clone()); + let from_box: Rc = Rc::from(s.clone().into_boxed_str()); + let mut source = s.clone(); + let from_mut: Arc = Arc::from(source.as_mut_str()); + source.make_ascii_uppercase(); + let borrowed: Rc = Rc::from(Cow::Borrowed(s.as_str())); + let owned: Arc = Arc::from(Cow::::Owned(s.clone())); + let into: Rc = s.clone().into(); + let empty: Rc = Rc::default(); + let arc_empty: Arc = Arc::default(); + put(out, &from_ref); + put(out, &from_string); + put(out, &from_box); + put(out, &from_mut); + put(out, &source); + put(out, &borrowed); + put(out, &owned); + put(out, &into); + put(out, &empty); + put(out, &arc_empty); + out.push(u8::from(from_ref == into)); + out.push(from_ref.cmp(&empty) as u8); + out.push(u8::from(hash(&from_ref) == hash(s.as_str()))); + out.push(from_ref.len() as u8); + out.push(from_ref.chars().count() as u8); + put(out, &format!("{from_ref}|{from_string:?}|{empty:?}")); + let twin = from_ref.clone(); + counts(&twin, out); + out.push(u8::from(Rc::ptr_eq(&twin, &from_ref))); + out.push(u8::from(Rc::ptr_eq(&into, &from_ref))); + let mut mine = into; + match kind % 2 { + 0 => { + if let Some(m) = Rc::get_mut(&mut mine) { + m.make_ascii_uppercase(); + } + } + _ => Rc::make_mut(&mut twin.clone()).make_ascii_lowercase(), + } + let mut shared = twin; + Rc::make_mut(&mut shared).make_ascii_uppercase(); + counts(&shared, out); + counts(&from_ref, out); + put(out, &mine); + put(out, &shared); + put(out, &from_ref); + let mut arc = from_string.clone(); + Arc::make_mut(&mut arc).make_ascii_uppercase(); + put(out, &arc); + put(out, &from_string); + let back = String::from(&*arc); + put(out, &back); + let to: String = from_box.to_string(); + put(out, &to); +} + +/// A generic type's shared slice, of bytes, of `u16`s, and of items that log. +pub fn generics(kind: u8, data: &[u8], out: &mut Vec) { + let data = &data[..usize::from(kind >> 3) % (data.len() + 1)]; + let mut bytes = Shared::new(data.to_vec()); + let copy = bytes.clone(); + bytes.set_last(0xee); + put_bytes(&bytes.items, out); + put_bytes(©.items, out); + out.push(bytes.first().copied().unwrap_or(0xaa)); + counts(©.items, out); + let mut wide = Shared::collected(data.iter().map(|&b| u16::from(b) << 8)); + let twin = wide.clone(); + counts(&wide.items, out); + wide.set_last(0xbeef); + put_wides(&wide.items, out); + put_wides(&twin.items, out); + let log = Rc::new(RefCell::new(Vec::new())); + let logged = |id: u8| Logged { id, log: log.clone() }; + let mut items = Shared::new(data.iter().map(|&b| logged(b & 0x7e)).collect()); + let kept = items.clone(); + flush(&log, out); + items.set_last(logged(0x40)); + flush(&log, out); + ids(&items.items, out); + out.push(items.first().map_or(0xaa, |l| l.id)); + drop(kept); + flush(&log, out); + drop(items); + flush(&log, out); +} + +/// Shared slices and text as keys a borrow of their slice or text looks up, and through +/// `AsRef`, `Borrow`, and `FromIterator::from_iter`. +pub fn keys(kind: u8, data: &[u8], out: &mut Vec) { + let data = &data[..usize::from(kind >> 3) % (data.len() + 1)]; + let words: Vec = data.chunks(2).map(text).collect(); + let interned: HashSet> = words.iter().map(|w| Rc::from(w.as_str())).collect(); + out.push(interned.len() as u8); + for w in &words { + out.push(u8::from(interned.contains(w.as_str()))); + out.push(interned.get(w.as_str()).map_or(0, |k| Rc::strong_count(k) as u8)); + } + out.push(u8::from(interned.contains("\u{0}"))); + let mut counted: HashMap, u8> = HashMap::new(); + for c in data.chunks(3) { + *counted.entry(Arc::from(c)).or_default() += 1; + } + for c in data.chunks(3) { + out.push(counted.get(c).copied().unwrap_or(0)); + } + let from_iter = Rc::<[u16]>::from_iter(data.iter().map(|&b| u16::from(b) + 1)); + put_wides(from_iter.as_ref(), out); + let borrowed: &[u16] = from_iter.borrow(); + put_wides(borrowed, out); + let text: Arc = Arc::from(words.concat()); + let s: &str = text.as_ref(); + put(out, s); + let b: &str = text.borrow(); + put(out, b); + let mut slot: Rc<[u8]> = Rc::from(data); + let other: Rc<[u8]> = Rc::from(&data[..data.len() / 2]); + slot.clone_from(&other); + out.push(u8::from(Rc::ptr_eq(&slot, &other))); + counts(&other, out); +} diff --git a/ts/fixtures/lang/shares/ts.toml b/ts/fixtures/lang/shares/ts.toml new file mode 100644 index 000000000..0ed2e6de7 --- /dev/null +++ b/ts/fixtures/lang/shares/ts.toml @@ -0,0 +1,2 @@ +package = "lang-shares-fixture" +roots = ["harness::run", "harness::op"] diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 4404a32ca..82c28cc06 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -4,7 +4,7 @@ // A value whose drop JS can observe has `[Symbol.dispose]`, which runs its `Drop` impl // and drops its fields. `None` is `undefined`, which drops as nothing. -import { Abort, type Debug, type DebugStruct, debugStructField, debugStructFinish, debugStructFinishNonExhaustive, debugTupleField, debugTupleFinish, Err, type FmtResult, type Formatter, fmtBool, fmtDebugStruct, fmtDebugTuple, fmtPad, fmtStr, type None, OK, Ok, Panic, panic, type Place, place, ptrWrite, type Result, vecAssign } from "../rt.ts"; +import { Abort, type ByteSlice, type Debug, type DebugStruct, debugStructField, debugStructFinish, debugStructFinishNonExhaustive, debugTupleField, debugTupleFinish, Err, type FmtResult, type Formatter, fmtBool, fmtDebugStruct, fmtDebugTuple, fmtPad, fmtStr, type None, OK, Ok, Panic, panic, type Place, place, ptrWrite, type Result, stringAsBytes, vecAssign } from "../rt.ts"; // Drops @@ -188,6 +188,19 @@ export function arcDowncast( return Ok(typed); } +/** The `Arc<[u8]>` each `From` of an `Arc` gives, which is one allocation. */ +const strBytes = new WeakMap, Arc>(); + +/** `Arc<[u8]>::from` an `Arc`: its bytes, sharing its count as std shares the allocation. */ +export function arcStrBytes(arc: Arc): Arc { + let bytes = strBytes.get(arc); + if (bytes === undefined) { + bytes = new ArcDyn(arc, stringAsBytes(arc.value)); + strBytes.set(arc, bytes); + } + return bytes; +} + /** * Drop `arc`, whose value has no `[Symbol.dispose]` that drops it: the last one drops it * by `f`, or not at all without one, as a borrow. diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index 912424284..e7242facd 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -1704,6 +1704,13 @@ fn collect<'tcx>( return None; }; let std = Std::of(tcx, adt.did())?; + // An `Arc<[T]>` holds the `Box<[T]>` std's collects. + if std == Std::Arc + && let Some(boxed) = super::task::shared_box(tcx, args.type_at(0)) + { + let boxed = collect(b, boxed, item, iter, from, trusted, span)?; + return Some(Expr::New(Box::new(Expr::Rt("Arc".into())), vec![boxed])); + } // A `Cow<[T]>` owns the `Vec` std's collects, and a `Box<[T]>` becomes it. let boxed = library::box_slice(tcx, ty); let elem = match std { diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 22e045f64..dd008802d 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -3398,14 +3398,18 @@ pub fn default_value<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span, vec![default_value(b, args.type_at(0), span, out)?], ), Std::OnceCell | Std::OnceLock => super::task::once_new(b, ty), - // An empty slice or text, its own. - Std::Box if !args.type_at(0).is_sized(tcx, b.t.typing_env_pub()) => { - return default_value( + // An empty slice or text, its own, or an `Arc`'s. + std @ (Std::Box | Std::Arc) if !args.type_at(0).is_sized(tcx, b.t.typing_env_pub()) => { + let empty = default_value( b, Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, args.type_at(0)), span, out, - ); + )?; + match std { + Std::Arc => Expr::New(Box::new(Expr::Rt("Arc".into())), vec![empty]), + _ => empty, + } } Std::Box | Std::Wrapping | Std::Saturating => part(b, args.type_at(0), out), Std::Arc => Expr::New(Box::new(Expr::Rt("Arc".into())), vec![part(b, args.type_at(0), out)]), diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 551a7f823..0100a02aa 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -149,14 +149,19 @@ pub fn call<'tcx>( Expr::rt("arcGetMut", args) } // A `&mut` to the value, which is where it is for one JS copies. `make_mut` takes the - // `Arc`'s place, which it may point at a new `Arc`. - ("Arc" | "Rc", "get_mut" | "make_mut") if call.args.type_at(0).is_sized(tcx, b.t.typing_env_pub()) => { + // `Arc`'s place, which it may point at a new `Arc` of a clone, cloned as a box of a + // slice or text is. + ("Arc" | "Rc", "get_mut" | "make_mut") + if call.args.type_at(0).is_sized(tcx, b.t.typing_env_pub()) + || shared_box(tcx, call.args.type_at(0)).is_some() => + { let value = call.args.type_at(0); let place = if b.t.needs_place(value) { "Place" } else { "" }; match name { "get_mut" => Expr::rt(format!("arcGetMut{place}"), args), _ => { - let clone = super::collections::clone_fn(b, value, call.span); + let cloned = shared_box(tcx, value).unwrap_or(value); + let clone = super::collections::clone_fn(b, cloned, call.span); let arc = b.t.sig(call.def_id, call.args).inputs()[0].peel_refs(); let Some(droppers) = b.t.droppers([arc], call.span) else { return Ok(Some(Expr::undefined())); @@ -166,15 +171,24 @@ pub fn call<'tcx>( } } } - // An `Arc` of a string, which JS shares as it is. + // An `Arc<[u8]>` of an `Arc`'s bytes, which shares its count, as std's shares its + // allocation. + ("From", "from") + if let [_, from] = call.args.as_slice() + && self_std == Some(Std::Arc) + && std_of(from.expect_ty()) == Some(Std::Arc) => + { + Expr::rt("arcStrBytes", args) + } + // An `Arc` of a slice or text, of the box `From` makes of the same value. ("From", "from") if let [arc, from] = call.args.as_slice() - && let ty::Adt(_, arc) = arc.expect_ty().kind() && self_std == Some(Std::Arc) - && arc.type_at(0).is_str() - && library::string(tcx, from.expect_ty().peel_refs()) => + && let ty::Adt(_, arc) = arc.expect_ty().kind() + && let Some(boxed) = shared_box(tcx, arc.type_at(0)) => { - Expr::New(Box::new(Expr::Rt("Arc".into())), args) + let value = b.convert(first(args), from.expect_ty(), boxed, call.span, out); + Expr::New(Box::new(Expr::Rt("Arc".into())), vec![value]) } // A waker over the crate's `Wake` impl. ("From", "from") @@ -581,6 +595,11 @@ fn once<'tcx>( Ok(Some(e)) } +/// A `Box`, if `pointee` is a slice or text, whose value an `rt.Arc` of it holds. +pub fn shared_box<'tcx>(tcx: ty::TyCtxt<'tcx>, pointee: Ty<'tcx>) -> Option> { + matches!(pointee.kind(), ty::Slice(_) | ty::Str).then(|| Ty::new_box(tcx, pointee)) +} + /// The type a cell or lock of type `ty` holds. fn held(ty: Option>) -> Ty<'_> { match ty.map(|ty| ty.kind()) { diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index bd3d3922a..c7eaf8359 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -433,6 +433,7 @@ mod lang { searches, separated, shapes, + shares, singles, slices, sorts, From 6d165a2a2a46c006177a6f8f07d3fab757b05046 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:46:46 -0800 Subject: [PATCH 3/3] fix(ts): convert only an Arc to an Arc<[u8]>, and refresh its bytes after a write Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/lang/shares/expected/shares.ts | 58 ++++++++++++++-------- ts/fixtures/lang/shares/src/shares.rs | 13 +++++ ts/runtime/rt/task.ts | 18 ++++--- ts/src/lower/task.rs | 11 ++-- 4 files changed, 70 insertions(+), 30 deletions(-) diff --git a/ts/fixtures/lang/shares/expected/shares.ts b/ts/fixtures/lang/shares/expected/shares.ts index 17db8801c..5a6b27815 100644 --- a/ts/fixtures/lang/shares/expected/shares.ts +++ b/ts/fixtures/lang/shares/expected/shares.ts @@ -176,6 +176,21 @@ export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { ofTwin[Symbol.dispose](); counts$slice_u8(ofStr, out); putBytes(ofStr.value, out); + const s2: rt.Arc = new rt.Arc(text(data2)); + rt.arcStrBytes(rt.arcClone(s2))[Symbol.dispose](); + const _121: rt.Place | undefined = rt.arcGetMutPlace(s2); + if (_121 !== undefined) { + _121.v = rt.strToAsciiUppercase(_121.v); + } + const same: rt.Arc = rt.arcClone(s2); + rt.byteVecPush(out, same === s2 ? 1 : 0); + const _137: rt.Arc = rt.arcStrBytes(s2); + putBytes(_137.value, out); + _137[Symbol.dispose](); + const n: rt.Arc = new rt.Arc((data2.length & 0xff) as rt.u32); + const same2: rt.Arc = rt.arcClone(n); + rt.byteVecPush(out, same2 === n ? 1 : 0); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(same2.value).reverse()), undefined, true); const arcOfStr: rt.Arc = rt.arcStrBytes(new rt.Arc(text(data2))); putBytes(arcOfStr.value, out); const v: rt.ByteVec = rt.byteSliceToByteVec(fromVec.value); @@ -185,6 +200,9 @@ export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { putBytes(rt.byteVecSlice(rt.byteSliceToByteVec(into.value)), out); putBytes(rt.byteSliceFrom(rt.byteSliceToArray(fromBox.value)), out); arcOfStr[Symbol.dispose](); + same2[Symbol.dispose](); + n[Symbol.dispose](); + same[Symbol.dispose](); ofStr[Symbol.dispose](); owned[Symbol.dispose](); borrowed[Symbol.dispose](); @@ -221,11 +239,11 @@ export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const arc: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); rt.byteVecPush(out, rt.byteSliceEq(arc.value, a.value) ? 1 : 0); rt.byteVecPush(out, rt.u64Eq(hash$sync_Arc_slice_u8(arc), hash$Rc_slice_u8(a)) ? 1 : 0); - const _244: rt.Arc = new rt.Arc(rt.byteSliceFrom(new Uint8Array(0))); - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(a.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(b2.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arc.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_244.value), f, rt.u8Debug)]; - const _240: string = rt.fmtFormat([args2[0], "|", args2[1], "|", args2[2], "|", args2[3]]); - _244[Symbol.dispose](); - put(out, _240); + const _285: rt.Arc = new rt.Arc(rt.byteSliceFrom(new Uint8Array(0))); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(a.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(b2.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(arc.value), f, rt.u8Debug), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(_285.value), f, rt.u8Debug)]; + const _281: string = rt.fmtFormat([args2[0], "|", args2[1], "|", args2[2], "|", args2[3]]); + _285[Symbol.dispose](); + put(out, _281); arc[Symbol.dispose](); b2[Symbol.dispose](); a[Symbol.dispose](); @@ -249,9 +267,9 @@ export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { }) ? 1 : 0); rt.byteVecPush(out, weak.arc.strong & 0xff); b3[Symbol.dispose](); - const _301: rt.Arc | undefined = rt.weakUpgrade(weak); - rt.byteVecPush(out, _301 === undefined ? 1 : 0); - rt.drop(_301); + const _342: rt.Arc | undefined = rt.weakUpgrade(weak); + rt.byteVecPush(out, _342 === undefined ? 1 : 0); + rt.drop(_342); rt.byteVecPush(out, weak.arc.strong & 0xff); const arc2: rt.Arc = new rt.Arc(rt.byteVecSlice(rt.byteSliceToByteVec(data2))); const twin2: rt.Arc = rt.arcClone(arc2); @@ -269,9 +287,9 @@ export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { c[Symbol.dispose](); } else { let a3: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); - const _332: rt.ByteSlice | undefined = rt.arcGetMut(a3); - if (_332 !== undefined) { - scramble(_332); + const _373: rt.ByteSlice | undefined = rt.arcGetMut(a3); + if (_373 !== undefined) { + scramble(_373); } putBytes(a3.value, out); const b4: rt.Arc = rt.arcClone(a3); @@ -291,24 +309,24 @@ export function bytes(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { counts$slice_u8(a3, out); putBytes(a3.value, out); const weak2: rt.Weak = new rt.Weak(a3); - const _379: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(rt.arcMakeMut(rt.place(() => a3, (value3) => a3 = value3), (a03: rt.ByteSlice): rt.ByteSlice => { + const _420: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(rt.arcMakeMut(rt.place(() => a3, (value3) => a3 = value3), (a03: rt.ByteSlice): rt.ByteSlice => { return rt.byteSliceFrom(rt.byteSliceToArray(a03)); }, rt.drop))); - if (_379 !== undefined) { - _379.v = 34; + if (_420 !== undefined) { + _420.v = 34; } - const _388: rt.Arc | undefined = rt.weakUpgrade(weak2); - rt.byteVecPush(out, _388 === undefined ? 1 : 0); - rt.drop(_388); + const _429: rt.Arc | undefined = rt.weakUpgrade(weak2); + rt.byteVecPush(out, _429 === undefined ? 1 : 0); + rt.drop(_429); putBytes(a3.value, out); let arc3: rt.Arc = new rt.Arc(rt.byteSliceFrom(rt.byteSliceToArray(data2))); const shared: rt.Arc = rt.arcClone(arc3); rt.byteSliceView(rt.arcMakeMut(rt.place(() => arc3, (value4) => arc3 = value4), (a04: rt.ByteSlice): rt.ByteSlice => { return rt.byteSliceFrom(rt.byteSliceToArray(a04)); }, rt.drop)).reverse(); - const _399: rt.ByteSlice | undefined = rt.arcGetMut(arc3); - if (_399 !== undefined) { - rt.iterForEach(rt.iterSliceMut(rt.byteSliceView(_399)), (x: rt.Place): undefined => { + const _440: rt.ByteSlice | undefined = rt.arcGetMut(arc3); + if (_440 !== undefined) { + rt.iterForEach(rt.iterSliceMut(rt.byteSliceView(_440)), (x: rt.Place): undefined => { x.v = x.v ^ 15; }); } diff --git a/ts/fixtures/lang/shares/src/shares.rs b/ts/fixtures/lang/shares/src/shares.rs index d5a149473..15e81a51e 100644 --- a/ts/fixtures/lang/shares/src/shares.rs +++ b/ts/fixtures/lang/shares/src/shares.rs @@ -191,6 +191,19 @@ pub fn bytes(kind: u8, data: &[u8], out: &mut Vec) { drop(of_twin); counts(&of_str, out); put_bytes(&of_str, out); + // Text written once no bytes share it, and pointers converted to themselves. + let mut s = Rc::::from(text(data)); + drop(Rc::<[u8]>::from(s.clone())); + if let Some(m) = Rc::get_mut(&mut s) { + m.make_ascii_uppercase(); + } + let same = Rc::::from(s.clone()); + out.push(u8::from(Rc::ptr_eq(&same, &s))); + put_bytes(&Rc::<[u8]>::from(s), out); + let n = Arc::new(u32::from(data.len() as u8)); + let same = Arc::::from(n.clone()); + out.push(u8::from(Arc::ptr_eq(&same, &n))); + out.extend(same.to_le_bytes()); let arc_of_str: Arc<[u8]> = Arc::from(Arc::::from(text(data))); put_bytes(&arc_of_str, out); // Back to what owns its bytes, which grows as any does. diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 82c28cc06..6809c9ecc 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -188,17 +188,21 @@ export function arcDowncast( return Ok(typed); } -/** The `Arc<[u8]>` each `From` of an `Arc` gives, which is one allocation. */ -const strBytes = new WeakMap, Arc>(); +/** + * The `Arc<[u8]>` each `From` of an `Arc` gives, which is one allocation, and the text + * it was made of. Other text there was written through a unique `Arc`, so no `Arc<[u8]>` + * of the old text is left. + */ +const strBytes = new WeakMap, { text: string; bytes: Arc }>(); /** `Arc<[u8]>::from` an `Arc`: its bytes, sharing its count as std shares the allocation. */ export function arcStrBytes(arc: Arc): Arc { - let bytes = strBytes.get(arc); - if (bytes === undefined) { - bytes = new ArcDyn(arc, stringAsBytes(arc.value)); - strBytes.set(arc, bytes); + let made = strBytes.get(arc); + if (made?.text !== arc.value) { + made = { text: arc.value, bytes: new ArcDyn(arc, stringAsBytes(arc.value)) }; + strBytes.set(arc, made); } - return bytes; + return made.bytes; } /** diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 0100a02aa..dab929267 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -174,16 +174,21 @@ pub fn call<'tcx>( // An `Arc<[u8]>` of an `Arc`'s bytes, which shares its count, as std's shares its // allocation. ("From", "from") - if let [_, from] = call.args.as_slice() + if let [to, from] = call.args.as_slice() + && let (ty::Adt(_, to), ty::Adt(_, from)) = (to.expect_ty().kind(), from.expect_ty().kind()) && self_std == Some(Std::Arc) - && std_of(from.expect_ty()) == Some(Std::Arc) => + && std_of(call.args.type_at(1)) == Some(Std::Arc) + && matches!(to.type_at(0).kind(), ty::Slice(e) if matches!(e.kind(), ty::Uint(ty::UintTy::U8))) + && from.type_at(0).is_str() => { Expr::rt("arcStrBytes", args) } - // An `Arc` of a slice or text, of the box `From` makes of the same value. + // An `Arc` of a slice or text, of the box `From` makes of the same value, but for the + // `Arc` itself. ("From", "from") if let [arc, from] = call.args.as_slice() && self_std == Some(Std::Arc) + && std_of(from.expect_ty()) != Some(Std::Arc) && let ty::Adt(_, arc) = arc.expect_ty().kind() && let Some(boxed) = shared_box(tcx, arc.type_at(0)) => {