From 6cb85eb931af237cf093fdfacc1234a04ad64a86 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:18:46 -0800 Subject: [PATCH 1/4] chore(quest): claim quest/m3/ts-guard-maps.md Quest-Claim: 1d3f1f04f27d5fe2 From b3a0903d52d7b0b3d68e29012a90e63f2e2da9bc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:10:23 -0800 Subject: [PATCH 2/4] feat(ts): translate the rest of a guard's maps RefMut::map, Ref and RefMut's filter_map and map_split, and the map and filter_map of an RwLock's guards, mapped or not. A mapped guard is an rt.RefMap of where its part is: a write through a mapped RefMut reaches the cell, through the part's rt.Place where JS copies it, or into the object in place. Split guards share the cell's borrow until the last drops. A mapped guard of a sized part JS can't write in place is refused. Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 1 - quest/m3/ts-guard-maps.md | 16 -- ts/README.md | 2 +- ts/fixtures/lang/caller.ts | 20 +- ts/fixtures/lang/expected/atomics.ts | 2 +- ts/fixtures/lang/expected/borrows.Parts.ts | 30 ++ ts/fixtures/lang/expected/borrows.ts | 309 ++++++++++++++++++++- ts/fixtures/lang/expected/core/bool.ts | 17 +- ts/fixtures/lang/expected/core/option.ts | 8 + ts/fixtures/lang/expected/core/result.ts | 8 + ts/fixtures/lang/expected/harness.ts | 12 +- ts/fixtures/lang/expected/iters.ts | 2 +- ts/fixtures/lang/expected/lib.ts | 54 ++++ ts/fixtures/lang/expected/locks.ts | 151 +++++++++- ts/fixtures/lang/expected/shapes.ts | 4 +- ts/fixtures/lang/src/borrows.rs | 194 ++++++++++++- ts/fixtures/lang/src/harness.rs | 2 + ts/fixtures/lang/src/lib.rs | 1 + ts/fixtures/lang/src/locks.rs | 82 +++++- ts/fixtures/reject/census.md | 14 +- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 8 + ts/fixtures/reject/ts.toml | 1 + ts/runtime/rt/task.ts | 82 +++++- ts/src/lower/library.rs | 9 +- ts/src/lower/mir/call.rs | 5 +- ts/src/lower/mir/place.rs | 63 +---- ts/src/lower/mod.rs | 42 ++- ts/src/lower/task.rs | 72 ++++- 29 files changed, 1095 insertions(+), 117 deletions(-) delete mode 100644 quest/m3/ts-guard-maps.md create mode 100644 ts/fixtures/lang/expected/borrows.Parts.ts diff --git a/quest/m3/README.md b/quest/m3/README.md index 1deab792a..f2192bead 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -31,7 +31,6 @@ generic std gap is planned here even when moq never calls it. - [A deque's two slices](/quest/m3/ts-deque-slices.md) - `VecDeque::as_slices` and `{:?}` of a deque's `Iter`, `IterMut`, and `Drain` translate, split where std's are - [std's sorts call their tests in std's order](/quest/m3/ts-sort-order.md) - `slice::sort` and a B-tree's `collect` call `lt` or `cmp` as std's driftsort does past 16 elements - [A B-tree's searches call Ord as std's do](/quest/m3/ts-btree-search-order.md) - a B-tree's lookups and inserts call a key's own `Ord` in std's order and number -- [The rest of a guard's maps](/quest/m3/ts-guard-maps.md) - `RefMut::map`, the guards' `filter_map` and `map_split`, and an `RwLock` guard's `map` translate - [A str's checked and inclusive parts](/quest/m3/ts-str-get.md) - `str::get` and indexing a `str` by `a..=b` or `..=b` translate - [The rest of a boxed slice's impls](/quest/m3/ts-boxed-slice-rest.md) - `clone_from`, `AsRef`, `AsMut`, `TryFrom` into a boxed array, and `Box` into bytes translate for boxed slices - [A reversed zip's per-pair cost](/quest/m3/ts-zip-rev-overhead.md) - a reversed by-index zip costs per pair what a forward one does, or the gap is explained diff --git a/quest/m3/ts-guard-maps.md b/quest/m3/ts-guard-maps.md deleted file mode 100644 index 0d5d42d68..000000000 --- a/quest/m3/ts-guard-maps.md +++ /dev/null @@ -1,16 +0,0 @@ -# [S] The rest of a guard's maps - -## Goal - -[rust2-ts](/ts/README.md) translates `RefMut::map`, `Ref::filter_map`, `Ref::map_split`, -`RefMut::filter_map`, `RefMut::map_split`, and the `map` of an `RwLock`'s guards, each -releasing its cell's borrow as the last guard drops, as std's do. Today they are refused. -Proven by differential tests against native Rust. - -## Plan - -`Ref::map` makes an `rt.RefMap`, which holds the part it lends and counts its borrow in -the cell. A mapped `RefMut` lends a `&mut`, which is an `rt.Place` where JS copies the -part, so writes through it must reach that place rather than a copy in the guard. - -Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index b6904a224..07c582504 100644 --- a/ts/README.md +++ b/ts/README.md @@ -123,7 +123,7 @@ crate translation reaches is refused, and so are two versions of one crate it re | 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 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 `Ref::map` makes an `rt.RefMap`, the part it lends, which releases the cell's borrow as it drops | +| `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`, 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; 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 | | `OnceCell`, `OnceLock` | `rt.OnceCell` and `rt.OnceLock`, holding the `Option` in `v`, which is the place `get_mut` lends where JS copies the value; a `OnceLock` initialized from within its own initialization panics, as wasm32's does, and `get_or_try_init`'s error leaves either empty | | `Once`, `OnceState` | `rt.Once`, an `rt.OnceLock` that holds `true` once `call_once` or `call_once_force` ran its function, and panics as wasm32's does if run again from within it; `rt.OnceState`, that `Once`, which a panic never poisons, as it aborts | diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index 7e32158ab..7e4e51105 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -403,6 +403,24 @@ const guards = [ [0xf6], ].map((bytes) => Uint8Array.of(op("borrows::guards"), 0, ...bytes)); +/** + * `borrows::maps` scripts: each operation through mapped, filtered, and split guards, with + * parts written whole and split parts dropped in either order, and each borrow again + * while one holds the cell, which panics. + */ +const maps = [ + [0x00, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x15, 0x07, 0xf1, 0xf2, 0x0b, 0x06, 0x13, 0x0c], + [0x02, 0x22, 0x0d, 0xc6], + [0x0a, 0xd6], + [0xe6], + [0x02, 0xf6], +].map((bytes) => Uint8Array.of(op("borrows::maps"), 0, ...bytes)); + +/** `locks::mapped` scripts: writes and reads through mapped and filtered guards. */ +const mappedLocks = [[0x04, 0x01, 0x02, 0x86, 0x05, 0x0a, 0x03, 0x02, 0x80, 0x01, 0x03]].map((bytes) => + Uint8Array.of(op("locks::mapped"), 0, ...bytes), +); + /** `locks::rwlocks` scripts: `get_mut` and `into_inner` among writes and reads. */ const rwlocks = [[6, 7, 0, 6, 2, 14, 15, 1]].map((bytes) => Uint8Array.of(op("locks::rwlocks"), 0, ...bytes)); @@ -753,4 +771,4 @@ const asciiCases = [ ...Array.from({ length: 8 * 3 * 3 }, (_, i) => Uint8Array.of(op("ascii::parts"), 0x10 | (i % 8), Math.floor(i / 8) % 3, Math.floor(i / 24))), ]; -export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...singlesCases, ...singlesFormats, ...singlesParsed, ...dyns, ...cells, ...shared, ...locks, ...guards, ...rwlocks, ...onces, ...bounds, ...unsafeCells, ...edits, ...subslices, ...consumers, ...closures, ...elements, ...ranges, ...reducers, ...sliceEdits, ...drains, ...iters, ...hinted, ...peekedOthers, ...hints, ...reserves, ...setOps, ...zeros, ...writes, ...floatsMulAdds, ...singlesMulAdds, ...unlikeEqs, ...ownNes, ...rangeFroms, ...compares, ...unlikeCompares, ...rangeMethods, ...wraps(), ...refOrders, ...saturates(), ...methods(), ...separated, ...asciiCases]; +export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...singlesCases, ...singlesFormats, ...singlesParsed, ...dyns, ...cells, ...shared, ...locks, ...guards, ...maps, ...mappedLocks, ...rwlocks, ...onces, ...bounds, ...unsafeCells, ...edits, ...subslices, ...consumers, ...closures, ...elements, ...ranges, ...reducers, ...sliceEdits, ...drains, ...iters, ...hinted, ...peekedOthers, ...hints, ...reserves, ...setOps, ...zeros, ...writes, ...floatsMulAdds, ...singlesMulAdds, ...unlikeEqs, ...ownNes, ...rangeFroms, ...compares, ...unlikeCompares, ...rangeMethods, ...wraps(), ...refOrders, ...saturates(), ...methods(), ...separated, ...asciiCases]; diff --git a/ts/fixtures/lang/expected/atomics.ts b/ts/fixtures/lang/expected/atomics.ts index 7e1e180da..6afe2cb9b 100644 --- a/ts/fixtures/lang/expected/atomics.ts +++ b/ts/fixtures/lang/expected/atomics.ts @@ -2,7 +2,7 @@ import * as rt from "./rt.ts"; import * as Stats from "./atomics.Stats.ts"; -import { thenSome$0kwiij6, thenSome$0n2gkz4, thenSome$0tjggir, thenSome$1s4itlz, thenSome$0jkru5t, thenSome$0b23a33, thenSome$1af3oea, thenSome$1ugl8af, thenSome$0d5am30, thenSome$07z8k4h } from "./core/bool.ts"; +import { thenSome$0kwiij6, thenSome$0n2gkz4, thenSome$0tjggir, thenSome$1s4itlz, thenSome$0jkru5t, thenSome$0d5am30, thenSome$0b23a33, thenSome$1af3oea, thenSome$1ugl8af, thenSome$07z8k4h } from "./core/bool.ts"; import { isSomeAnd$09tpccf } from "./core/option.ts"; import { unwrapOr$1pnwyus as result_unwrapOr$1pnwyus, unwrapOr$0xokg9f as result_unwrapOr$0xokg9f, unwrapOr$1imvcmw as result_unwrapOr$1imvcmw, unwrapOr$06fxvgg as result_unwrapOr$06fxvgg, unwrapOr$0gr9tn5 as result_unwrapOr$0gr9tn5, unwrapOr$0hnup9g as result_unwrapOr$0hnup9g, unwrapOr$1dnnsw8 as result_unwrapOr$1dnnsw8, unwrapOr$1k2j44a as result_unwrapOr$1k2j44a, unwrapOr$0jmm2jy as result_unwrapOr$0jmm2jy, unwrapOr$1czbd6g as result_unwrapOr$1czbd6g } from "./core/result.ts"; diff --git a/ts/fixtures/lang/expected/borrows.Parts.ts b/ts/fixtures/lang/expected/borrows.Parts.ts new file mode 100644 index 000000000..a574e923e --- /dev/null +++ b/ts/fixtures/lang/expected/borrows.Parts.ts @@ -0,0 +1,30 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as borrows_Tagged from "./borrows.Tagged.ts"; + +/** + * What mapped guards lend parts of: a number and a `String`, which JS copies, and a `Vec` + * and a value that logs as it drops, which it doesn't. + */ +export class Parts { + n: rt.u32; + text: string; + bytes: rt.ByteVec; + tagged: borrows_Tagged.Tagged; + maybe: rt.u16 | undefined; + + constructor(n: rt.u32, text: string, bytes: rt.ByteVec, tagged: borrows_Tagged.Tagged, maybe: rt.u16 | undefined) { + this.n = n; + this.text = text; + this.bytes = bytes; + this.tagged = tagged; + this.maybe = maybe; + } + + [Symbol.dispose](): void { + this.tagged[Symbol.dispose](); + } +} + +//# sourceMappingURL=borrows.Parts.ts.map diff --git a/ts/fixtures/lang/expected/borrows.ts b/ts/fixtures/lang/expected/borrows.ts index a6f76cb49..d69301b56 100644 --- a/ts/fixtures/lang/expected/borrows.ts +++ b/ts/fixtures/lang/expected/borrows.ts @@ -1,12 +1,13 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Option_tuple2_u64_u64, copy$tuple2_u64_u64, drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Tagged_cell_BorrowMutError, drop$Result_cell_Ref_Vec_u8_cell_BorrowError, drop$tuple2_Option_cell_Ref_borrows_Tagged_Option_cell_RefMut_borrows_Tagged, drop$tuple2_Result_cell_Ref_Vec_u8_cell_BorrowError_cell_Ref_Vec_u8, drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8 } from "./lib.ts"; +import { copy$Option_tuple2_u64_u64, copy$tuple2_u64_u64, drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Parts_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Tagged_cell_BorrowMutError, drop$Result_cell_RefMut_u32_cell_BorrowMutError, drop$Result_cell_Ref_Vec_u8_cell_BorrowError, drop$Result_cell_Ref_borrows_Parts_cell_BorrowError, drop$Result_cell_Ref_u32_cell_BorrowError, drop$Result_cell_Ref_u32_cell_Ref_borrows_Parts, drop$tuple2_Option_cell_Ref_borrows_Tagged_Option_cell_RefMut_borrows_Tagged, drop$tuple2_Result_cell_Ref_Vec_u8_cell_BorrowError_cell_Ref_Vec_u8, drop$tuple2_cell_RefMut_slice_u8_cell_RefMut_slice_u8, drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8 } from "./lib.ts"; import * as borrows_Noisy from "./borrows.Noisy.ts"; +import * as borrows_Parts from "./borrows.Parts.ts"; import * as borrows_Polling from "./borrows.Polling.ts"; import * as borrows_Tagged from "./borrows.Tagged.ts"; import { then$1jgls7y } from "./core/bool.ts"; -import { unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, mapOr$0qqbaqw as option_mapOr$0qqbaqw, mapOr$0ucbp7g as option_mapOr$0ucbp7g } from "./core/option.ts"; +import { unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, mapOr$0qqbaqw as option_mapOr$0qqbaqw, mapOr$1dvn0au as option_mapOr$1dvn0au, mapOr$099335t as option_mapOr$099335t, mapOr$0ucbp7g as option_mapOr$0ucbp7g } from "./core/option.ts"; import { map$0n1xnuw as result_map$0n1xnuw, unwrapOr$0k9nfhn as result_unwrapOr$0k9nfhn } from "./core/result.ts"; /** @@ -295,6 +296,310 @@ export function guards(data: rt.ByteSlice, out: rt.ByteVec): void { log[Symbol.dispose](); } +/** + * Each byte an operation on `RefCell`s through guards mapped, filtered, and split to their + * parts, its value the operand; each puts what it read through them, what the cell holds + * after they drop, whether it is still borrowed, and what dropped. + */ +export function maps(data: rt.ByteSlice, out: rt.ByteVec): void { + const log: rt.Arc> = new rt.Arc(new rt.Mutex(new rt.ByteVec())); + const tag: (a0: rt.u8) => borrows_Tagged.Tagged = (id: rt.u8): borrows_Tagged.Tagged => { + return new borrows_Tagged.Tagged(id, 0, rt.arcClone(log)); + }; + const parts: rt.RefCell = new rt.RefCell(new borrows_Parts.Parts(0, "", new rt.ByteVec(), tag(1), undefined)); + const number: rt.RefCell = new rt.RefCell(0); + const slot: rt.RefCell = new rt.RefCell(undefined as borrows_Tagged.Tagged | undefined); + for (const op of rt.byteSliceView(data)) { + const _26: rt.u8 = rt.u8Rem(op, 8); + if (_26 === 0) { + const _29: rt.RefCell = rt.refCellBorrowMut(parts); + const n: rt.RefCell = rt.refMutMap(_29, ((p14: borrows_Parts.Parts): rt.Place => { + return rt.place(() => p14.n, (value7) => p14.n = value7); + })(_29.value)); + n.value = rt.u32Add(n.value, op as rt.u32); + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + const _39: rt.RefCell = n; + const again: rt.RefCell = rt.refMutMap(_39, ((n6: rt.Place): rt.Place => { + return n6; + })(rt.valuePlace(_39))); + again.value = rt.u32Add(again.value, 1); + rt.refMutRelease(again); + const _49: rt.u8 = borrowed$borrows_Parts(parts); + const _55: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_49, _55.value.n & 0xff))); + rt.refRelease(_55); + const _58: rt.RefCell = rt.refCellBorrowMut(number); + const whole: rt.RefCell = rt.refMutMap(_58, ((n7: rt.Place): rt.Place => { + return n7; + })(rt.valuePlace(_58))); + const _65: rt.u32 = rt.u32Add(rt.u32WrappingMul(whole.value, 3), op as rt.u32); + whole.value = _65; + rt.refMutRelease(whole); + const _75: rt.RefCell = rt.refCellBorrow(number); + rt.byteVecPush(out, _75.value & 0xff); + rt.refRelease(_75); + } else if (_26 === 1) { + const _78: rt.RefCell = rt.refCellBorrowMut(parts); + const text: rt.RefCell = rt.refMutMap(_78, ((p13: borrows_Parts.Parts): rt.Place => { + return rt.place(() => p13.text, (value6) => p13.text = value6); + })(_78.value)); + text.value = text.value + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(op, 26)) as rt.char); + if ((op >> 4) === 15) { + text.value = "z"; + } + rt.byteVecPush(out, rt.stringLen(text.value) & 0xff); + rt.refMutRelease(text); + const _107: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(_107.value.text)); + rt.refRelease(_107); + } else if (_26 === 2) { + const _110: rt.RefCell = rt.refCellBorrowMut(parts); + const bytes: rt.RefCell = rt.refMutMap(_110, rt.partPlace(((p11: borrows_Parts.Parts): rt.ByteVec => { + return p11.bytes; + })(_110.value))); + rt.byteVecPush(bytes.value, op); + if ((op >> 4) === 15) { + const _119: rt.ByteVec = rt.byteVecFrom(Uint8Array.of(op, op)); + bytes.value = _119; + } + rt.refMutRelease(bytes); + const _130: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_130.value.bytes)); + rt.refRelease(_130); + const _133: rt.RefCell = rt.refCellBorrowMut(parts); + const tagged: rt.RefCell = rt.refMutMap(_133, rt.partPlace(((p12: borrows_Parts.Parts): borrows_Tagged.Tagged => { + return p12.tagged; + })(_133.value))); + tagged.value.n = rt.u32Add(tagged.value.n, 1); + const _138: borrows_Tagged.Tagged = new borrows_Tagged.Tagged(op, tagged.value.n, rt.arcClone(log)); + tagged.value[Symbol.dispose](); + tagged.value = _138; + flush(log.value, out); + rt.refMutRelease(tagged); + const _158: rt.RefCell = rt.refCellBorrow(parts); + const _155: rt.u8 = _158.value.tagged.id; + const _164: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_155, _164.value.tagged.n & 0xff))); + rt.refRelease(_164); + rt.refRelease(_158); + } else if (_26 === 3) { + const _167: rt.RefCell = rt.refCellBorrowMut(parts); + const _166: rt.Result, rt.RefCell> = rt.refMutFilterMap(_167, ((p9: borrows_Parts.Parts): rt.Place | undefined => { + return p9.maybe === undefined ? undefined : rt.place(() => p9.maybe as rt.u16, (value5) => p9.maybe = value5); + })(_167.value)); + if (_166.ok) { + const m: rt.RefCell = _166.value; + m.value = rt.u16Add(m.value, 1); + rt.byteVecPush(out, m.value & 0xff); + rt.refMutRelease(m); + } else { + const whole2: rt.RefCell = _166.error; + whole2.value.maybe = op as rt.u16; + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + rt.refMutRelease(whole2); + } + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + const _191: rt.Result, rt.RefCell> = rt.refFilterMap(rt.refCellBorrow(parts), (p10: borrows_Parts.Parts): rt.u8 | undefined => { + return rt.byteSliceLast(rt.byteVecSlice(p10.bytes)); + }); + if (_191.ok) { + const last: rt.RefCell = _191.value; + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(last.value, borrowed$borrows_Parts(parts)))); + rt.refRelease(last); + } else { + const whole3: rt.RefCell = _191.error; + rt.byteVecPush(out, 240 | (whole3.value.bytes.length & 0xff)); + rt.refRelease(whole3); + } + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + const _215: rt.RefCell = rt.refCellBorrowMut(slot); + const part = ((s2: rt.Place): borrows_Tagged.Tagged | undefined => { + return s2.v; + })(rt.valuePlace(_215)); + const _214: rt.Result, rt.RefCell> = rt.refMutFilterMap(_215, part === undefined ? undefined : rt.partPlace(part)); + if (_214.ok) { + const t: rt.RefCell = _214.value; + const _219: borrows_Tagged.Tagged = tag(op); + t.value[Symbol.dispose](); + t.value = _219; + rt.refMutRelease(t); + } else { + const s: rt.RefCell = _214.error; + const _225: borrows_Tagged.Tagged | undefined = tag(op); + rt.drop(s.value); + s.value = _225; + rt.refMutRelease(s); + } + flush(log.value, out); + const _239: rt.RefCell = rt.refCellBorrow(slot); + rt.byteVecPush(out, option_mapOr$1dvn0au(_239.value, 253, (t2: borrows_Tagged.Tagged): rt.u8 => { + return t2.id; + })); + rt.refRelease(_239); + } else if (_26 === 4) { + const _243: [rt.RefCell, rt.RefCell] = rt.refMapSplit(rt.refCellBorrow(parts), (p8: borrows_Parts.Parts): [rt.u32, rt.ByteVec] => { + return [p8.n, p8.bytes] as [rt.u32, rt.ByteVec]; + }); + const n2: rt.RefCell = _243[0]; + const bytes2: rt.RefCell = _243[1]; + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(n2.value & 0xff, bytes2.value.length & 0xff, borrowed$borrows_Parts(parts)))); + rt.refRelease(n2); + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + rt.refRelease(bytes2); + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + } else if (_26 === 5) { + const _271: rt.RefCell = rt.refCellBorrowMut(parts); + const parts3 = ((p6: borrows_Parts.Parts): [rt.Place, rt.Place] => { + return [rt.place(() => p6.n, (value3) => p6.n = value3), rt.place(() => p6.text, (value4) => p6.text = value4)] as [rt.Place, rt.Place]; + })(_271.value); + const _270: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_271, parts3[0], parts3[1]); + const n3: rt.RefCell = _270[0]; + const text2: rt.RefCell = _270[1]; + n3.value = rt.u32Add(n3.value, 1); + text2.value = text2.value + "s"; + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + if (!((op & 16) === 0)) { + rt.refMutRelease(text2); + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + rt.refMutRelease(n3); + } else { + rt.refMutRelease(n3); + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + rt.refMutRelease(text2); + } + const _302: rt.u8 = borrowed$borrows_Parts(parts); + const _308: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_302, _308.value.n & 0xff))); + rt.refRelease(_308); + const _313: rt.RefCell = rt.refCellBorrowMut(parts); + const parts4 = ((p7: borrows_Parts.Parts): [rt.ByteSlice, rt.ByteSlice] => { + const half: rt.usize = rt.usizeDiv(p7.bytes.length, 2); + return rt.byteSliceSplitAt(rt.byteVecSlice(p7.bytes), half); + })(_313.value); + const _312: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_313, rt.partPlace(parts4[0]), rt.partPlace(parts4[1])); + const low: rt.RefCell = _312[0]; + const high: rt.RefCell = _312[1]; + const _315: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(low.value)); + if (_315 !== undefined) { + _315.v = rt.u8WrappingAdd(_315.v, op); + } + const _322: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(high.value)); + if (_322 !== undefined) { + _322.v = _322.v ^ 255; + } + drop$tuple2_cell_RefMut_slice_u8_cell_RefMut_slice_u8([low, high] as [rt.RefCell, rt.RefCell]); + const _336: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_336.value.bytes)); + rt.refRelease(_336); + } else if (_26 === 6) { + const _338: rt.u8 = op >> 4; + if (_338 === 12) { + const _342: rt.RefCell = rt.refCellBorrowMut(parts); + const _n: rt.RefCell = rt.refMutMap(_342, ((p5: borrows_Parts.Parts): rt.Place => { + return rt.place(() => p5.n, (value2) => p5.n = value2); + })(_342.value)); + rt.refRelease(rt.refCellBorrow(parts)); + rt.refMutRelease(_n); + } else if (_338 === 13) { + const _349: rt.RefCell = rt.refCellBorrowMut(parts); + const parts2 = ((p4: borrows_Parts.Parts): [rt.Place, rt.ByteVec] => { + return [rt.place(() => p4.n, (value) => p4.n = value), p4.bytes] as [rt.Place, rt.ByteVec]; + })(_349.value); + const _348: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_349, parts2[0], rt.partPlace(parts2[1])); + const a: rt.RefCell = _348[0]; + const _b: rt.RefCell = _348[1]; + rt.refMutRelease(a); + rt.refMutRelease(rt.refCellBorrowMut(parts)); + rt.refMutRelease(_b); + } else if (_338 === 14) { + const _f: rt.Result, rt.RefCell> = rt.refFilterMap(rt.refCellBorrow(parts), (p3: borrows_Parts.Parts): rt.u32 | undefined => { + return p3.n; + }); + rt.refMutRelease(rt.refCellBorrowMut(parts)); + drop$Result_cell_Ref_u32_cell_Ref_borrows_Parts(_f); + } else if (_338 === 15) { + const _361: [rt.RefCell, rt.RefCell] = rt.refMapSplit(rt.refCellBorrow(parts), (p2: borrows_Parts.Parts): [rt.u32, string] => { + return [p2.n, p2.text] as [rt.u32, string]; + }); + const _a: rt.RefCell = _361[0]; + rt.refRelease(_361[1]); + rt.refMutRelease(rt.refCellBorrowMut(parts)); + rt.refRelease(_a); + } else { + rt.byteVecPush(out, borrowed$borrows_Parts(parts)); + } + } else { + const text3: rt.RefCell = rt.refMap(rt.refCellBorrow(parts), (p: borrows_Parts.Parts): string => { + return p.text; + }); + const _373: rt.RefCell = rt.refCellBorrowMut(number); + const n4: rt.RefCell = rt.refMutMap(_373, ((n5: rt.Place): rt.Place => { + return n5; + })(rt.valuePlace(_373))); + const _384: string = text3.value; + const _387: rt.u32 = rt.u32Add(n4.value, 1); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _384), (f: rt.Formatter) => rt.u32Display(_387, f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1]]))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(borrowed$borrows_Parts(parts), borrowed$u32(number)))); + rt.refMutRelease(n4); + rt.refRelease(text3); + } + flush(log.value, out); + } + const last2: borrows_Parts.Parts = parts.value; + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(last2.n & 0xff, last2.tagged.id, option_mapOr$099335t(last2.maybe, 253, (m2: rt.u16): rt.u8 => { + return m2 & 0xff; + })))); + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(last2.text)); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(last2.bytes)); + last2[Symbol.dispose](); + slot[Symbol.dispose](); + flush(log.value, out); + log[Symbol.dispose](); +} + +/** Whether `cell` is borrowed exclusively, as 2, shared, as 1, or not at all. */ +export function borrowed$borrows_Parts(cell: rt.RefCell): rt.u8 { + let _0!: rt.u8; + const _5: rt.Result, rt.BorrowError> = rt.refCellTryBorrow(cell); + const _3: boolean = !_5.ok; + const _8: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(cell); + const _2: [boolean, boolean] = [_3, !_8.ok]; + if (!_3) { + if (!_2[1]) { + _0 = 0; + } else { + _0 = 1; + } + } else { + _0 = 2; + } + drop$Result_cell_RefMut_borrows_Parts_cell_BorrowMutError(_8); + drop$Result_cell_Ref_borrows_Parts_cell_BorrowError(_5); + return _0; +} + +/** Whether `cell` is borrowed exclusively, as 2, shared, as 1, or not at all. */ +export function borrowed$u32(cell: rt.RefCell): rt.u8 { + let _0!: rt.u8; + const _5: rt.Result, rt.BorrowError> = rt.refCellTryBorrow(cell); + const _3: boolean = !_5.ok; + const _8: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(cell); + const _2: [boolean, boolean] = [_3, !_8.ok]; + if (!_3) { + if (!_2[1]) { + _0 = 0; + } else { + _0 = 1; + } + } else { + _0 = 2; + } + drop$Result_cell_RefMut_u32_cell_BorrowMutError(_8); + drop$Result_cell_Ref_u32_cell_BorrowError(_5); + return _0; +} + /** A clone of `t`, which for a reference is that reference. */ export function twin$ref_cell_RefCell_u32(t: rt.RefCell): rt.RefCell { return t; diff --git a/ts/fixtures/lang/expected/core/bool.ts b/ts/fixtures/lang/expected/core/bool.ts index 18a25a453..7660e9693 100644 --- a/ts/fixtures/lang/expected/core/bool.ts +++ b/ts/fixtures/lang/expected/core/bool.ts @@ -70,35 +70,42 @@ export function thenSome$0xksuo2(self: boolean, t: rt.Place): rt.Place): rt.Place | undefined { if (!self) { return undefined; } return t; } -export function thenSome$0b23a33(self: boolean, t: rt.u16): rt.u16 | undefined { +export function thenSome$0d5am30(self: boolean, t: rt.u8): rt.u8 | undefined { if (!self) { return undefined; } return t; } -export function thenSome$1af3oea(self: boolean, t: rt.u32): rt.u32 | undefined { +export function thenSome$1jqdi5p(self: boolean, t: rt.Duration): rt.Duration | undefined { if (!self) { return undefined; } return t; } -export function thenSome$1ugl8af(self: boolean, t: rt.u64): rt.u64 | undefined { +export function thenSome$0b23a33(self: boolean, t: rt.u16): rt.u16 | undefined { if (!self) { return undefined; } return t; } -export function thenSome$0d5am30(self: boolean, t: rt.u8): rt.u8 | undefined { +export function thenSome$1af3oea(self: boolean, t: rt.u32): rt.u32 | undefined { + if (!self) { + return undefined; + } + return t; +} + +export function thenSome$1ugl8af(self: boolean, t: rt.u64): rt.u64 | undefined { if (!self) { return undefined; } diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index d39042e77..d2f8ead8b 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -3,6 +3,7 @@ import * as rt from "../rt.ts"; import { opaque as args_opaque, len as args_len } from "../args.ts"; import type * as borrows_Noisy from "../borrows.Noisy.ts"; +import type * as borrows_Tagged from "../borrows.Tagged.ts"; import type * as bounds_Item from "../bounds.Item.ts"; import * as clones_Logged from "../clones.Logged.ts"; import type * as ByRef from "../collections.ByRef.ts"; @@ -1111,6 +1112,13 @@ export function mapOr$0qqbaqw(self: borrows_Noisy.Noisy | undefined, default_: r return f(self); } +export function mapOr$1dvn0au(self: borrows_Tagged.Tagged | undefined, default_: rt.u8, f: (a0: borrows_Tagged.Tagged) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + export function mapOr$1yabfom(self: clones_Logged.Logged | undefined, default_: rt.u8, _: (a0: clones_Logged.Logged) => rt.u8): rt.u8 { if (self === undefined) { return default_; diff --git a/ts/fixtures/lang/expected/core/result.ts b/ts/fixtures/lang/expected/core/result.ts index 806dbe900..f1a094e74 100644 --- a/ts/fixtures/lang/expected/core/result.ts +++ b/ts/fixtures/lang/expected/core/result.ts @@ -13,6 +13,7 @@ import { eq$1horntk as float_parse_eq$1horntk } from "../core/num/float_parse.ts import { eq$1v93ipo as str_error_eq$1v93ipo, eq$1f3e51k as str_error_eq$1f3e51k } from "../core/str/error.ts"; import { cmp$175ka5q as poll_cmp$175ka5q } from "../core/task/poll.ts"; import { eq$0dhyfbb as time_eq$0dhyfbb } from "../core/time.ts"; +import type * as locks_Tally from "../locks.Tally.ts"; import * as Part from "../orders.Part.ts"; import type * as returns_Error from "../returns.Error.ts"; @@ -626,6 +627,13 @@ export function map$0zzqmaz(self: rt.Result, rt.Arc, rt.RefCell>, op: (a0: rt.RefCell) => rt.Result, rt.RefCell>): rt.Result, rt.RefCell>, rt.RefCell> { + if (self.ok) { + return rt.Ok(op(self.value)); + } + return self as rt.Result, rt.RefCell>, rt.RefCell>; +} + export function map$0r57egs(self: rt.Result, op: (a0: rt.u8) => rt.u8 | undefined): rt.Result { if (self.ok) { return rt.Ok(op(self.value)); diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 6c77b4360..aa1601b96 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -2,10 +2,10 @@ import * as rt from "./rt.ts"; import { args } from "./args.ts"; -import { fromFns, maps, lent as arrays_lent, asSlices, given, flattened as arrays_flattened } from "./arrays.ts"; +import { fromFns, maps as arrays_maps, lent as arrays_lent, asSlices, given, flattened as arrays_flattened } from "./arrays.ts"; import { bytes as ascii_bytes, chars as ascii_chars, slices as ascii_slices, parts as ascii_parts } from "./ascii.ts"; import { atomics } from "./atomics.ts"; -import { borrows as borrows_borrows, guards } from "./borrows.ts"; +import { borrows as borrows_borrows, guards, maps as borrows_maps } from "./borrows.ts"; import { bounds as bounds_bounds } from "./bounds.ts"; import { boxes, places as boxes_places } from "./boxes.ts"; import { captures } from "./captures.ts"; @@ -37,7 +37,7 @@ import { keys as keys_keys, overrides, bytes as keys_bytes, lentKeys, lentValues import { lengths } from "./lengths.ts"; import { lists as lists_lists } from "./lists.ts"; import { locals } from "./locals.ts"; -import { locks, relock, rwlocks } from "./locks.ts"; +import { locks, relock, rwlocks, mapped } from "./locks.ts"; import { u8s as methods_u8s, u16s as methods_u16s, u32s as methods_u32s, u64s as methods_u64s, u128s as methods_u128s, usizes as methods_usizes, i8s as methods_i8s, i16s as methods_i16s, i32s as methods_i32s, i64s as methods_i64s, i128s as methods_i128s, isizes as methods_isizes } from "./methods.ts"; import { nested as nested_nested } from "./nested.ts"; import { objects } from "./objects.ts"; @@ -209,7 +209,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["keys::lent_keys", lentKeys as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["keys::lent_values", lentValues as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::singles", singles as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::formats", singles_formats as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::parses", singles_parses as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::peeked_others", (_2168: rt.u8, data68: rt.ByteSlice, out69: rt.ByteVec): undefined => { peekedOthers(data68, out69); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["hints::hints", hints as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["hints::reserves", reserves as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::set_ops", setOps as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["folds::folds", folds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::zeros", zeros as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["arrays::maps", (_2169: rt.u8, data69: rt.ByteSlice, out70: rt.ByteVec): undefined => { - maps(data69, out70); + arrays_maps(data69, out70); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["arrays::lent", (_2170: rt.u8, data70: rt.ByteSlice, out71: rt.ByteVec): undefined => { arrays_lent(data70, out71); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["floats::mul_adds", floats_mulAdds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::mul_adds", singles_mulAdds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fmt::collections", (_2171: rt.u8, data71: rt.ByteSlice, out72: rt.ByteVec): undefined => { @@ -252,6 +252,10 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) aimed(data88, out89); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["ascii::parts", ascii_parts as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["boxes::places", boxes_places as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["arrays::flattened", arrays_flattened as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["args::args", args as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["returns::returns", returns as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["borrows::guards", (_2189: rt.u8, data89: rt.ByteSlice, out90: rt.ByteVec): undefined => { guards(data89, out90); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["borrows::maps", (_2190: rt.u8, data90: rt.ByteSlice, out91: rt.ByteVec): undefined => { + borrows_maps(data90, out91); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["locks::mapped", (_2191: rt.u8, data91: rt.ByteSlice, out92: rt.ByteVec): undefined => { + mapped(data91, out92); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; } diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 8aafa5244..8afbe7f0d 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -2,7 +2,7 @@ import * as rt from "./rt.ts"; import { copy$iters_Bumped, copy$tuple2_u8_u8 } from "./lib.ts"; -import { thenSome$0b23a33, thenSome$0d5am30 } from "./core/bool.ts"; +import { thenSome$0d5am30, thenSome$0b23a33 } from "./core/bool.ts"; import { unwrapOr$0k15iai as option_unwrapOr$0k15iai, unwrapOr$00uis1j as option_unwrapOr$00uis1j, unwrapOr$1tvry1i as option_unwrapOr$1tvry1i, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$14m5xjm as option_unwrapOr$14m5xjm, unwrapOrDefault$165pyh5 as option_unwrapOrDefault$165pyh5, unwrapOrDefault$0wx44sw as option_unwrapOrDefault$0wx44sw, map$1uo1d4o as option_map$1uo1d4o, map$1httady as option_map$1httady, map$0p22lts as option_map$0p22lts, map$0of9gds as option_map$0of9gds, map$1c7zybz as option_map$1c7zybz, map$0cs071d as option_map$0cs071d, mapOr$0lcrgk1 as option_mapOr$0lcrgk1, mapOr$1kiffmd as option_mapOr$1kiffmd, mapOr$1a3irjf as option_mapOr$1a3irjf, mapOr$0sl5app as option_mapOr$0sl5app, mapOr$0atjiti as option_mapOr$0atjiti, mapOr$0okqj9y as option_mapOr$0okqj9y, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, mapOr$1lznlgz as option_mapOr$1lznlgz, mapOr$0tmtgfi as option_mapOr$0tmtgfi, mapOr$0ev76sb as option_mapOr$0ev76sb, mapOr$1surhce as option_mapOr$1surhce, mapOr$1t0muvr as option_mapOr$1t0muvr, mapOr$02k4ito as option_mapOr$02k4ito, mapOr$0a96v80 as option_mapOr$0a96v80, mapOr$0mmpeqx as option_mapOr$0mmpeqx, mapOr$1vjqo89 as option_mapOr$1vjqo89, mapOr$1h04da8 as option_mapOr$1h04da8, mapOr$0f73bb7 as option_mapOr$0f73bb7, mapOr$06gg5x7 as option_mapOr$06gg5x7, mapOr$1dmz9kd as option_mapOr$1dmz9kd, mapOr$1sxa8ki as option_mapOr$1sxa8ki, asDeref$0w8at8i as option_asDeref$0w8at8i, filter$0v80fk8 } from "./core/option.ts"; import { unwrapOr$01jdcm7 as result_unwrapOr$01jdcm7 } from "./core/result.ts"; import * as Badge from "./iters.Badge.ts"; diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index 601bc539c..d9545bb47 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import type * as borrows_Parts from "./borrows.Parts.ts"; import type * as borrows_Tagged from "./borrows.Tagged.ts"; import type * as clones_Logged from "./clones.Logged.ts"; import type * as collections_Picky from "./collections.Picky.ts"; @@ -790,24 +791,72 @@ export function drop$Option_cell_Ref_borrows_Tagged(_1: rt.RefCell, rt.RefCell>, rt.RefCell>): void { + if (_1.ok) { + drop$Result_sync_MappedRwLockWriteGuard_u64_sync_MappedRwLockWriteGuard_u64(_1.value); + } else { + rt.refMutRelease(_1.error); + } +} + export function drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError(_1: rt.Result, rt.BorrowMutError>): void { if (_1.ok) { rt.refMutRelease(_1.value); } } +export function drop$Result_cell_RefMut_borrows_Parts_cell_BorrowMutError(_1: rt.Result, rt.BorrowMutError>): void { + if (_1.ok) { + rt.refMutRelease(_1.value); + } +} + export function drop$Result_cell_RefMut_borrows_Tagged_cell_BorrowMutError(_1: rt.Result, rt.BorrowMutError>): void { if (_1.ok) { rt.refMutRelease(_1.value); } } +export function drop$Result_cell_RefMut_u32_cell_BorrowMutError(_1: rt.Result, rt.BorrowMutError>): void { + if (_1.ok) { + rt.refMutRelease(_1.value); + } +} + export function drop$Result_cell_Ref_Vec_u8_cell_BorrowError(_1: rt.Result, rt.BorrowError>): void { if (_1.ok) { rt.refRelease(_1.value); } } +export function drop$Result_cell_Ref_borrows_Parts_cell_BorrowError(_1: rt.Result, rt.BorrowError>): void { + if (_1.ok) { + rt.refRelease(_1.value); + } +} + +export function drop$Result_cell_Ref_u32_cell_BorrowError(_1: rt.Result, rt.BorrowError>): void { + if (_1.ok) { + rt.refRelease(_1.value); + } +} + +export function drop$Result_cell_Ref_u32_cell_Ref_borrows_Parts(_1: rt.Result, rt.RefCell>): void { + if (_1.ok) { + rt.refRelease(_1.value); + } else { + rt.refRelease(_1.error); + } +} + +export function drop$Result_sync_MappedRwLockWriteGuard_u64_sync_MappedRwLockWriteGuard_u64(_1: rt.Result, rt.RefCell>): void { + if (_1.ok) { + rt.refMutRelease(_1.value); + } else { + rt.refMutRelease(_1.error); + } +} + export function drop$Result_sync_MutexGuard_locks_Tally_sync_TryLockError_sync_MutexGuard_locks_Tally(_1: rt.Result, rt.TryLockError>>): void { if (_1.ok) { rt.mutexUnlock(_1.value); @@ -938,6 +987,11 @@ export function drop$tuple2_Vec_tuples_Logged_tuples_Tally(_1: [tuples_Logged.Lo rt.dropAll(_1[0]); } +export function drop$tuple2_cell_RefMut_slice_u8_cell_RefMut_slice_u8(_1: [rt.RefCell, rt.RefCell]): void { + rt.refMutRelease(_1[0]); + rt.refMutRelease(_1[1]); +} + export function drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8(_1: [rt.RefCell, rt.RefCell]): void { rt.refRelease(_1[0]); rt.refRelease(_1[1]); diff --git a/ts/fixtures/lang/expected/locks.ts b/ts/fixtures/lang/expected/locks.ts index 4d2bf8ef5..dbc41c15c 100644 --- a/ts/fixtures/lang/expected/locks.ts +++ b/ts/fixtures/lang/expected/locks.ts @@ -1,8 +1,10 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { drop$Result_sync_MutexGuard_locks_Tally_sync_TryLockError_sync_MutexGuard_locks_Tally, drop$Result_sync_MutexGuard_u32_sync_TryLockError_sync_MutexGuard_u32, drop$Result_sync_RwLockReadGuard_locks_Tally_sync_TryLockError_sync_RwLockReadGuard_locks_Tally, drop$Result_sync_RwLockWriteGuard_locks_Tally_sync_TryLockError_sync_RwLockWriteGuard_locks_Tally } from "./lib.ts"; +import { drop$Result_Result_sync_MappedRwLockWriteGuard_u64_sync_MappedRwLockWriteGuard_u64_sync_RwLockWriteGuard_locks_Tally, drop$Result_sync_MutexGuard_locks_Tally_sync_TryLockError_sync_MutexGuard_locks_Tally, drop$Result_sync_MutexGuard_u32_sync_TryLockError_sync_MutexGuard_u32, drop$Result_sync_RwLockReadGuard_locks_Tally_sync_TryLockError_sync_RwLockReadGuard_locks_Tally, drop$Result_sync_RwLockWriteGuard_locks_Tally_sync_TryLockError_sync_RwLockWriteGuard_locks_Tally } from "./lib.ts"; +import { thenSome$0sf2w1i, thenSome$0d5am30 } from "./core/bool.ts"; import { isSomeAnd$09tpccf, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr } from "./core/option.ts"; +import { map$1g6jln5 as result_map$1g6jln5 } from "./core/result.ts"; import * as locks_Lock from "./locks.Lock.ts"; import * as locks_Tally from "./locks.Tally.ts"; @@ -208,4 +210,151 @@ export function rwlocks(data: rt.ByteSlice, out: rt.ByteVec): void { lock[Symbol.dispose](); } +/** + * Each byte an operation on a read-write lock through guards mapped and filtered to its + * parts, its value the operand; each puts what it read through them, what the lock holds + * after they drop, and whether it is still locked. Locking it again while one is held + * aborts on wasm32, with no panic message to compare. + */ +export function mapped(data: rt.ByteSlice, out: rt.ByteVec): void { + const lock: rt.RefCell = new rt.RefCell(locks_Tally.default$Default()); + const locked: (a0: rt.ByteVec) => undefined = (out2: rt.ByteVec): undefined => { + let read!: boolean; + let write!: boolean; + const _43: rt.Result, rt.TryLockError>> = rt.rwLockTryRead(lock); + if (!_43.ok) { + read = true; + } else { + read = false; + } + drop$Result_sync_RwLockReadGuard_locks_Tally_sync_TryLockError_sync_RwLockReadGuard_locks_Tally(_43); + const _8: rt.Result, rt.TryLockError>> = rt.rwLockTryWrite(lock); + if (!_8.ok) { + write = true; + } else { + write = false; + } + drop$Result_sync_RwLockWriteGuard_locks_Tally_sync_TryLockError_sync_RwLockWriteGuard_locks_Tally(_8); + rt.byteVecPush(out2, ((((read ? 1 : 0)) << 1) & 0xff) | ((write ? 1 : 0))); + }; + for (const op of rt.byteSliceView(data)) { + const _13: rt.u8 = rt.u8Rem(op, 4); + if (_13 === 0) { + const _16: rt.RefCell = rt.rwLockWrite(lock); + const n: rt.RefCell = rt.refMutMap(_16, ((t7: locks_Tally.Tally): rt.Place => { + return rt.place(() => t7.n, (value3) => t7.n = value3); + })(_16.value)); + n.value = rt.u64Add(n.value, op as rt.u64); + locked(out); + const _27: rt.RefCell = n; + const again: rt.RefCell = rt.refMutMap(_27, ((n9: rt.Place): rt.Place => { + return n9; + })(rt.valuePlace(_27))); + const _28: rt.u64 = rt.u64WrappingMul(again.value, 3); + again.value = _28; + rt.refMutRelease(again); + locked(out); + const _44: rt.RefCell = rt.rwLockRead(lock); + rt.byteVecPush(out, rt.u64Low(_44.value.n) & 0xff); + rt.refRelease(_44); + } else if (_13 === 1) { + const seen: rt.RefCell = rt.refMap(rt.rwLockRead(lock), (t6: locks_Tally.Tally): rt.ByteVec => { + return t6.seen; + }); + rt.byteVecPush(out, seen.value.length & 0xff); + const last: rt.RefCell = rt.refMap(seen, (s: rt.ByteVec): rt.u8 => { + return option_unwrapOr$0r2bmpr(rt.byteSliceLast(rt.byteVecSlice(s)), 253); + }); + rt.byteVecPush(out, last.value); + locked(out); + rt.refRelease(last); + locked(out); + } else if (_13 === 2) { + const _70: rt.RefCell = rt.rwLockWrite(lock); + const _69: rt.Result, rt.RefCell> = rt.refMutFilterMap(_70, ((t3: locks_Tally.Tally): rt.Place | undefined => { + return rt.sliceLastMut(rt.byteSliceView(rt.byteVecSlice(t3.seen))); + })(_70.value)); + if (_69.ok) { + const last2: rt.RefCell = _69.value; + const _75: rt.u8 = rt.u8WrappingAdd(last2.value, op); + last2.value = _75; + rt.refMutRelease(last2); + } else { + const whole: rt.RefCell = _69.error; + rt.byteVecPush(whole.value.seen, op); + rt.refMutRelease(whole); + } + locked(out); + const _89: rt.Result, rt.RefCell> = rt.refFilterMap(rt.rwLockRead(lock), (t4: locks_Tally.Tally): rt.u8 | undefined => { + return rt.byteSliceFirst(rt.byteVecSlice(t4.seen)); + }); + if (_89.ok) { + const _95: rt.Result, rt.RefCell> = rt.refFilterMap(_89.value, (b2: rt.u8): rt.u8 | undefined => { + return thenSome$0d5am30(b2 > 128, b2); + }); + if (_95.ok) { + const b: rt.RefCell = _95.value; + rt.byteVecPush(out, b.value); + rt.refRelease(b); + } else { + const first2: rt.RefCell = _95.error; + rt.byteVecPush(out, ~first2.value & 0xff); + rt.refRelease(first2); + } + } else { + const whole2: rt.RefCell = _89.error; + rt.byteVecPush(out, 240 | (whole2.value.seen.length & 0xff)); + rt.refRelease(whole2); + } + locked(out); + const _117: rt.RefCell = rt.rwLockWrite(lock); + const _121: rt.Result, rt.RefCell>, rt.RefCell> = result_map$1g6jln5(rt.refMutFilterMap(_117, ((t5: locks_Tally.Tally): rt.Place | undefined => { + return rt.place(() => t5.n, (value2) => t5.n = value2); + })(_117.value)), (n7: rt.RefCell): rt.Result, rt.RefCell> => { + return rt.refMutFilterMap(n7, ((n8: rt.Place): rt.Place | undefined => { + return thenSome$0sf2w1i(rt.u64And(n8.v, 1) === 0, n8); + })(rt.valuePlace(n7))); + }); + if (_121.ok) { + if (_121.value.ok) { + const n3: rt.RefCell = _121.value.value; + n3.value = rt.u64Add(n3.value, 1); + rt.refMutRelease(n3); + } else { + const n4: rt.RefCell = _121.value.error; + n4.value = rt.u64Add(n4.value, 2); + rt.refMutRelease(n4); + } + } else { + rt.byteVecPush(out, 254); + } + if (!_121.ok) { + drop$Result_Result_sync_MappedRwLockWriteGuard_u64_sync_MappedRwLockWriteGuard_u64_sync_RwLockWriteGuard_locks_Tally(_121); + } + const _137: rt.RefCell = rt.rwLockRead(lock); + rt.byteVecPush(out, rt.u64Low(_137.value.n) & 0xff); + rt.refRelease(_137); + const _145: rt.RefCell = rt.rwLockRead(lock); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_145.value.seen)); + rt.refRelease(_145); + } else { + const _149: rt.RefCell = rt.rwLockWrite(lock); + const n5: rt.RefCell = rt.refMutMap(_149, ((t: locks_Tally.Tally): rt.Place => { + return rt.place(() => t.n, (value) => t.n = value); + })(_149.value)); + locked(out); + rt.refMutRelease(n5); + const n6: rt.RefCell = rt.refMap(rt.rwLockRead(lock), (t2: locks_Tally.Tally): rt.u64 => { + return t2.n; + }); + locked(out); + rt.byteVecPush(out, rt.u64Low(n6.value) & 0xff); + rt.refRelease(n6); + } + } + const last3: locks_Tally.Tally = lock.value; + rt.byteVecPush(out, rt.u64Low(last3.n) & 0xff); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(last3.seen)); +} + //# sourceMappingURL=locks.ts.map diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 25348fb65..ddc80a53d 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -19,7 +19,7 @@ import * as Meters from "./shapes.Meters.ts"; import * as Moved from "./shapes.Moved.ts"; import type * as Mover from "./shapes.Mover.ts"; import type * as Partial from "./shapes.Partial.ts"; -import type * as Parts from "./shapes.Parts.ts"; +import type * as shapes_Parts from "./shapes.Parts.ts"; import * as Point from "./shapes.Point.ts"; import * as shapes_Shape from "./shapes.Shape.ts"; import type * as Signed from "./shapes.Signed.ts"; @@ -2177,7 +2177,7 @@ export function uninhabited(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, calls); const pair: [rt.Result, Partial.Partial] = [counted(rt.place(() => calls, (value9) => calls = value9), a), { tag: "Real", _0: b } as Partial.Partial]; rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of((pair[0] as { ok: true; value: rt.u8 }).value, (pair[1] as { tag: "Real"; _0: rt.u8 })._0))); - const held: Parts.Parts = { left: rt.Ok(a), right: thenSome$0ztng9q(rt.u8Rem(b, 2) === 0, rt.Ok((((b as rt.u16)) << 4) & 0xffff)) }; + const held: shapes_Parts.Parts = { left: rt.Ok(a), right: thenSome$0ztng9q(rt.u8Rem(b, 2) === 0, rt.Ok((((b as rt.u16)) << 4) & 0xffff)) }; const l: rt.u8 = (held.left as { ok: true; value: rt.u8 }).value; const right: rt.Result | undefined = held.right; if (right === undefined) { diff --git a/ts/fixtures/lang/src/borrows.rs b/ts/fixtures/lang/src/borrows.rs index e81f94ad6..13f0aa398 100644 --- a/ts/fixtures/lang/src/borrows.rs +++ b/ts/fixtures/lang/src/borrows.rs @@ -2,9 +2,10 @@ //! tuples, and values that drop; borrowed shared and exclusive, held in bindings and //! dropped; and borrowed again while held, which panics as wasm32's does. `RefCell`s //! cloned, written through `get_mut`, taken apart, tried, and borrowed through mapped and -//! cloned guards, each released as it drops. +//! cloned guards, each released as it drops; and guards mapped, filtered, and split to +//! parts JS copies and parts it doesn't, written through, released as the last drops. -use std::cell::{Cell, Ref, RefCell}; +use std::cell::{Cell, Ref, RefCell, RefMut}; use std::sync::{Arc, Mutex}; /// Logs its id when it drops. @@ -270,6 +271,195 @@ pub fn guards(data: &[u8], out: &mut Vec) { flush(&log, out); } +/// What mapped guards lend parts of: a number and a `String`, which JS copies, and a `Vec` +/// and a value that logs as it drops, which it doesn't. +struct Parts { + n: u32, + text: String, + bytes: Vec, + tagged: Tagged, + maybe: Option, +} + +/// Each byte an operation on `RefCell`s through guards mapped, filtered, and split to their +/// parts, its value the operand; each puts what it read through them, what the cell holds +/// after they drop, whether it is still borrowed, and what dropped. +pub fn maps(data: &[u8], out: &mut Vec) { + let log = Arc::new(Mutex::new(Vec::new())); + let tag = |id| Tagged { + id, + n: 0, + log: log.clone(), + }; + let parts = RefCell::new(Parts { + n: 0, + text: String::new(), + bytes: Vec::new(), + tagged: tag(1), + maybe: None, + }); + let number = RefCell::new(0u32); + let slot: RefCell> = RefCell::new(None); + for &op in data { + match op % 8 { + // A number written through a guard mapped to it, and through that guard's own map. + 0 => { + let mut n = RefMut::map(parts.borrow_mut(), |p| &mut p.n); + *n += u32::from(op); + out.push(borrowed(&parts)); + let mut again = RefMut::map(n, |n| n); + *again += 1; + drop(again); + out.extend_from_slice(&[borrowed(&parts), parts.borrow().n as u8]); + let mut whole = RefMut::map(number.borrow_mut(), |n| n); + *whole = whole.wrapping_mul(3) + u32::from(op); + drop(whole); + out.push(*number.borrow() as u8); + } + // A `String` pushed to and written whole. + 1 => { + let mut text = RefMut::map(parts.borrow_mut(), |p| &mut p.text); + text.push(char::from(b'a' + op % 26)); + if op >> 4 == 0xf { + *text = String::from("z"); + } + out.push(text.len() as u8); + drop(text); + out.extend_from_slice(parts.borrow().text.as_bytes()); + } + // A `Vec` and a value that drops written whole, which drops the old one there. + 2 => { + let mut bytes = RefMut::map(parts.borrow_mut(), |p| &mut p.bytes); + bytes.push(op); + if op >> 4 == 0xf { + *bytes = vec![op, op]; + } + drop(bytes); + out.extend_from_slice(&parts.borrow().bytes); + let mut tagged = RefMut::map(parts.borrow_mut(), |p| &mut p.tagged); + tagged.n += 1; + *tagged = Tagged { + id: op, + n: tagged.n, + log: log.clone(), + }; + flush(&log, out); + drop(tagged); + out.extend_from_slice(&[parts.borrow().tagged.id, parts.borrow().tagged.n as u8]); + } + // Filtered, which gives the guard back on `None`. + 3 => { + match RefMut::filter_map(parts.borrow_mut(), |p| p.maybe.as_mut()) { + Ok(mut m) => { + *m += 1; + out.push(*m as u8); + } + Err(mut whole) => { + whole.maybe = Some(u16::from(op)); + out.push(borrowed(&parts)); + } + } + out.push(borrowed(&parts)); + match Ref::filter_map(parts.borrow(), |p| p.bytes.last()) { + Ok(last) => out.extend_from_slice(&[*last, borrowed(&parts)]), + Err(whole) => out.push(0xf0 | whole.bytes.len() as u8), + } + out.push(borrowed(&parts)); + match RefMut::filter_map(slot.borrow_mut(), |s| s.as_mut()) { + Ok(mut t) => *t = tag(op), + Err(mut s) => *s = Some(tag(op)), + } + flush(&log, out); + out.push(slot.borrow().as_ref().map_or(0xfd, |t| t.id)); + } + // Split shared, released as the last part drops. + 4 => { + let (n, bytes) = Ref::map_split(parts.borrow(), |p| (&p.n, &p.bytes)); + out.extend_from_slice(&[*n as u8, bytes.len() as u8, borrowed(&parts)]); + drop(n); + out.push(borrowed(&parts)); + drop(bytes); + out.push(borrowed(&parts)); + } + // Split exclusive, released as the last part drops in either order. + 5 => { + let (mut n, mut text) = RefMut::map_split(parts.borrow_mut(), |p| (&mut p.n, &mut p.text)); + *n += 1; + text.push('s'); + out.push(borrowed(&parts)); + if op & 0x10 == 0 { + drop(n); + out.push(borrowed(&parts)); + drop(text); + } else { + drop(text); + out.push(borrowed(&parts)); + drop(n); + } + out.extend_from_slice(&[borrowed(&parts), parts.borrow().n as u8]); + let (mut low, mut high) = RefMut::map_split(parts.borrow_mut(), |p| { + let half = p.bytes.len() / 2; + p.bytes.split_at_mut(half) + }); + if let Some(b) = low.first_mut() { + *b = b.wrapping_add(op); + } + if let Some(b) = high.last_mut() { + *b ^= 0xff; + } + drop((low, high)); + out.extend_from_slice(&parts.borrow().bytes); + } + // Borrowed again while a mapped, filtered, or split guard holds it, which panics. + 6 => match op >> 4 { + 0xc => { + let _n = RefMut::map(parts.borrow_mut(), |p| &mut p.n); + let _r = parts.borrow(); + } + 0xd => { + let (a, _b) = RefMut::map_split(parts.borrow_mut(), |p| (&mut p.n, &mut p.bytes)); + drop(a); + let _w = parts.borrow_mut(); + } + 0xe => { + let _f = Ref::filter_map(parts.borrow(), |p| Some(&p.n)); + let _w = parts.borrow_mut(); + } + 0xf => { + let (_a, b) = Ref::map_split(parts.borrow(), |p| (&p.n, &p.text)); + drop(b); + let _w = parts.borrow_mut(); + } + _ => out.push(borrowed(&parts)), + }, + // Read through mapped guards as what they lend, shared and exclusive. + _ => { + let text = Ref::map(parts.borrow(), |p| p.text.as_str()); + let n = RefMut::map(number.borrow_mut(), |n| n); + out.extend_from_slice(format!("{} {}", &*text, *n + 1).as_bytes()); + out.extend_from_slice(&[borrowed(&parts), borrowed(&number)]); + } + } + flush(&log, out); + } + let last = parts.into_inner(); + out.extend_from_slice(&[last.n as u8, last.tagged.id, last.maybe.map_or(0xfd, |m| m as u8)]); + out.extend_from_slice(last.text.as_bytes()); + out.extend_from_slice(&last.bytes); + drop(last); + drop(slot); + flush(&log, out); +} + +/// Whether `cell` is borrowed exclusively, as 2, shared, as 1, or not at all. +fn borrowed(cell: &RefCell) -> u8 { + match (cell.try_borrow().is_err(), cell.try_borrow_mut().is_err()) { + (true, _) => 2, + (false, true) => 1, + (false, false) => 0, + } +} + /// A clone of `t`, which for a reference is that reference. fn twin(t: &T) -> T { t.clone() diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 9a6d553cb..106a9325b 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -269,6 +269,8 @@ fn cases() -> Vec<(&'static str, Case)> { ("args::args", args::args), ("returns::returns", returns::returns), ("borrows::guards", |_, data, out| borrows::guards(data, out)), + ("borrows::maps", |_, data, out| borrows::maps(data, out)), + ("locks::mapped", |_, data, out| locks::mapped(data, out)), ] } diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index cec049032..f9e737089 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -26,6 +26,7 @@ #![feature( iter_order_by, + mapped_lock_guards, once_cell_try, split_as_slice, wrapping_int_impl, diff --git a/ts/fixtures/lang/src/locks.rs b/ts/fixtures/lang/src/locks.rs index 618590207..7d7014575 100644 --- a/ts/fixtures/lang/src/locks.rs +++ b/ts/fixtures/lang/src/locks.rs @@ -2,10 +2,14 @@ //! `Default`, read and written through a guard, recovered from a `PoisonError` that never //! comes, read and written by `get_mut` without locking, taken apart, tried while held and free, and locked again //! while held, which panics as wasm32's does; and read-write locks, read and written, -//! tried while read and while written, written through `get_mut`, and taken apart. +//! tried while read and while written, written through `get_mut`, taken apart, and read +//! and written through guards mapped and filtered to parts of their values. use std::fmt; -use std::sync::{Arc, Mutex, PoisonError, RwLock, TryLockError}; +use std::sync::{ + Arc, MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, + TryLockError, +}; /// A value a mutex holds, which `Default` makes. #[derive(Default)] @@ -167,3 +171,77 @@ pub fn rwlocks(data: &[u8], out: &mut Vec) { out.push(number.into_inner().unwrap() as u8); out.extend_from_slice(&owned.into_inner().unwrap_or_else(PoisonError::into_inner)); } + +/// Each byte an operation on a read-write lock through guards mapped and filtered to its +/// parts, its value the operand; each puts what it read through them, what the lock holds +/// after they drop, and whether it is still locked. Locking it again while one is held +/// aborts on wasm32, with no panic message to compare. +pub fn mapped(data: &[u8], out: &mut Vec) { + let lock = RwLock::new(Tally::default()); + let locked = |out: &mut Vec| { + let read = matches!(lock.try_read(), Err(TryLockError::WouldBlock)); + let write = matches!(lock.try_write(), Err(TryLockError::WouldBlock)); + out.push(u8::from(read) << 1 | u8::from(write)); + }; + for &op in data { + match op % 4 { + // A number written through a write guard mapped to it, and through that one's map. + 0 => { + let mut n = RwLockWriteGuard::map(lock.write().unwrap(), |t| &mut t.n); + *n += u64::from(op); + locked(out); + let mut again = MappedRwLockWriteGuard::map(n, |n| n); + *again = again.wrapping_mul(3); + drop(again); + locked(out); + out.push(lock.read().unwrap().n as u8); + } + // Read through a read guard mapped to a part, and that one's map to a part of it. + 1 => { + let seen = RwLockReadGuard::map(lock.read().unwrap(), |t| &t.seen); + out.push(seen.len() as u8); + let last = MappedRwLockReadGuard::map(seen, |s| s.last().unwrap_or(&0xfd)); + out.push(*last); + locked(out); + drop(last); + locked(out); + } + // Filtered, which gives the guard back where there is no part. + 2 => { + match RwLockWriteGuard::filter_map(lock.write().unwrap(), |t| t.seen.last_mut()) { + Ok(mut last) => *last = last.wrapping_add(op), + Err(mut whole) => whole.seen.push(op), + } + locked(out); + match RwLockReadGuard::filter_map(lock.read().unwrap(), |t| t.seen.first()) { + Ok(first) => match MappedRwLockReadGuard::filter_map(first, |b| (*b > 0x80).then_some(b)) { + Ok(b) => out.push(*b), + Err(first) => out.push(!*first), + }, + Err(whole) => out.push(0xf0 | whole.seen.len() as u8), + } + locked(out); + let n = RwLockWriteGuard::filter_map(lock.write().unwrap(), |t| Some(&mut t.n)); + match n.map(|n| MappedRwLockWriteGuard::filter_map(n, |n| (*n & 1 == 0).then_some(n))) { + Ok(Ok(mut n)) => *n += 1, + Ok(Err(mut n)) => *n += 2, + Err(_) => out.push(0xfe), + } + out.push(lock.read().unwrap().n as u8); + out.extend_from_slice(&lock.read().unwrap().seen); + } + // Tried while a mapped write guard holds it, then while a mapped read guard does. + _ => { + let n = RwLockWriteGuard::map(lock.write().unwrap(), |t| &mut t.n); + locked(out); + drop(n); + let n = RwLockReadGuard::map(lock.read().unwrap(), |t| &t.n); + locked(out); + out.push(*n as u8); + } + } + } + let last = lock.into_inner().unwrap(); + out.push(last.n as u8); + out.extend_from_slice(&last.seen); +} diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 09fec4fb7..352006d9e 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 217 -- Function instances: 273 +- Refusals: 218 +- Function instances: 274 - Generic functions no instance reached, lowered over their type parameters: 13 ## By construct @@ -57,6 +57,7 @@ | 1 | a constant of type `_`, a pointer into memory translation can't name | fixtures/reject/src/lib.rs:780:3 | | 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | fixtures/reject/src/lib.rs:739:11 | | 1 | a future of `_`, which can be `rt.Pending`, as the future's own `Pending` is | fixtures/reject/src/lib.rs:84:34 | +| 1 | a mapped guard of `_`, which JS can't write in place | fixtures/reject/src/lib.rs:2172:10 | | 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:369:12 | | 1 | a mutable static, which any code may write | fixtures/reject/src/lib.rs:68:11 | | 1 | a pointer's address, which JS has no counterpart of | fixtures/reject/src/lib.rs:562:17 | @@ -98,12 +99,12 @@ The type or module each refused type or path belongs to. | 4 | `Iterator` | fixtures/reject/src/lib.rs:37:4 | | 4 | `std::pin::Pin` | fixtures/reject/src/lib.rs:98:2 | | 4 | `std::str` | fixtures/reject/src/lib.rs:441:4 | +| 4 | `{closure}` | fixtures/reject/src/lib.rs:326:13 | | 3 | `*const [u8; 4]` | fixtures/reject/src/lib.rs:1715:33 | | 3 | `Mid` | fixtures/reject/src/lib.rs:1357:34 | | 3 | `Outer` | fixtures/reject/src/lib.rs:1357:34 | | 3 | `std::ptr` | fixtures/reject/src/lib.rs:1712:3 | | 3 | `std::vec::Vec` | fixtures/reject/src/lib.rs:317:16 | -| 3 | `{closure}` | fixtures/reject/src/lib.rs:326:13 | | 2 | `(u16, u16)` | fixtures/reject/src/lib.rs:1178:31 | | 2 | `InArray` | fixtures/reject/src/lib.rs:1304:9 | | 2 | `InPayload` | fixtures/reject/src/lib.rs:1316:9 | @@ -302,6 +303,7 @@ The type or module each refused type or path belongs to. | 1 | a constant of type `_`, a pointer into memory translation can't name | `&u32` | fixtures/reject/src/lib.rs:780:3 | | 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | `Only` | fixtures/reject/src/lib.rs:739:11 | | 1 | a future of `_`, which can be `rt.Pending`, as the future's own `Pending` is | `std::task::Poll` | fixtures/reject/src/lib.rs:84:34 | +| 1 | a mapped guard of `_`, which JS can't write in place | `{closure}` | fixtures/reject/src/lib.rs:2172:10 | | 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | `std::vec::Vec` | fixtures/reject/src/lib.rs:579:10 | | 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | `(u16, u16)`, `Copied` | fixtures/reject/src/lib.rs:1178:31 | | 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | `(u16, u16)`, `Pushed` | fixtures/reject/src/lib.rs:1250:22 | @@ -861,6 +863,12 @@ The type or module each refused type or path belongs to. +
a mapped guard of `_`, which JS can't write in place (1) + +- fixtures/reject/src/lib.rs:2172:10: a mapped guard of `{closure@fixtures/reject/src/lib.rs:2171:38: 2171:50}`, which JS can't write in place + +
+
a mutable reference into a `Result`'s payload, passed on or kept (1) - fixtures/reject/src/lib.rs:369:12: a mutable reference into a `Result`'s payload, passed on or kept diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index c767bd53b..59f89707c 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -198,6 +198,7 @@ const generic types are not supported: `Block` at fixtures/reject/src/lib.rs:210 `std::collections::LinkedList::::retain` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:2119:4 `clone_from` of `std::collections::LinkedList`, whose items' `clone_from` is their own, which is not supported yet at fixtures/reject/src/lib.rs:2120:4 `std::default::Default::default` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:2121:2 +a mapped guard of `{closure@fixtures/reject/src/lib.rs:2171:38: 2171:50}`, which JS can't write in place at fixtures/reject/src/lib.rs:2172:10 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:132:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:152:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:180:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 96d109ecb..42ebc943a 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -2164,3 +2164,11 @@ pub fn optional_places_compared(n: &mut u32) -> bool { let p = std::ptr::NonNull::from(&mut *n); Some(p) == std::ptr::NonNull::new(&raw mut *n) } + +/// A `RefMut` mapped to a closure, which a write through the guard would put in place of +/// the cell's, though JS can't write one closure's captures into another. +pub fn mapped_closure(add: u8) -> u8 { + let cell = std::cell::RefCell::new((move |x: u8| x + add, 0u8)); + let f = std::cell::RefMut::map(cell.borrow_mut(), |pair| &mut pair.0); + f(1) +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index f40e30409..532e7378e 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -165,5 +165,6 @@ roots = [ "byte_pointer_rebound", "block_cloned", "lists", + "mapped_closure", ] printable = ["Meters"] diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 04883dce5..d93f2cfdd 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 { type Debug, debugTupleField, debugTupleFinish, Err, type FmtResult, type Formatter, fmtDebugTuple, fmtPad, type None, OK, Ok, Panic, panic, type Place, place, type Result } from "../rt.ts"; +import { type Debug, debugTupleField, debugTupleFinish, Err, type FmtResult, type Formatter, fmtDebugTuple, fmtPad, type None, OK, Ok, Panic, panic, type Place, place, ptrWrite, type Result, vecAssign } from "../rt.ts"; // Drops @@ -327,7 +327,8 @@ export function mutexUnlock(mutex: Mutex): void { /** * `RefCell` and `RwLock`, which one thread can't tell apart but by how a borrow * that conflicts fails, and their guards: a borrow is the cell itself, `borrows` counting - * the shared ones held, or -1 while an exclusive one is. + * the shared ones held, or the negated count of exclusive ones, which only a split makes + * more than one of. */ export class RefCell implements Disposable { value: T; @@ -393,19 +394,33 @@ export function rwLockTryWrite(lock: RefCell): Result, TryLockE } /** - * A `Ref` that `Ref::map` made: the part of a cell's value it lends, whose borrow that - * cell counts. + * A guard a map made: where the part of a cell's value it lends is, which it reads and + * writes as `value`, as a cell does its own, and whose borrow that cell counts. */ -export class RefMap extends RefCell { +export class RefMap implements RefCell { + /** A cell's count, which a guard's cell keeps instead. */ + borrows = 0; + readonly at: Place; readonly cell: RefCell; - constructor(value: T, cell: RefCell) { - super(value); + constructor(at: Place, cell: RefCell) { + this.at = at; this.cell = cell; } + + get value(): T { + return this.at.v; + } + + set value(value: T) { + this.at.v = value; + } + + /** A guard drops nothing of what it lends. */ + [Symbol.dispose](): void {} } -/** The cell whose borrow `r`, a `Ref`, holds. */ +/** The cell whose borrow `r`, a guard, holds. */ function refCellOf(r: RefCell): RefCell { return r instanceof RefMap ? r.cell : r; } @@ -417,7 +432,21 @@ export function refRelease(r: RefCell): void { /** `Ref::map`: a `Ref` of the part of `r`'s value `f` lends, which takes over `r`'s borrow. */ export function refMap(r: RefCell, f: (value: T) => U): RefCell { - return new RefMap(f(r.value), refCellOf(r)); + return new RefMap({ v: f(r.value) }, refCellOf(r)); +} + +/** `Ref::filter_map`: `refMap` of the part `f` lends, or `r` back if it lends none. */ +export function refFilterMap(r: RefCell, f: (value: T) => U | undefined): Result, RefCell> { + const part = f(r.value); + return part === undefined ? Err(r) : Ok(new RefMap({ v: part }, refCellOf(r))); +} + +/** `Ref::map_split`: `Ref`s of the two parts of `r`'s value `f` lends, which share `r`'s borrow. */ +export function refMapSplit(r: RefCell, f: (value: T) => [U, V]): [RefCell, RefCell] { + const [u, v] = f(r.value); + const cell = refCellOf(r); + cell.borrows++; + return [new RefMap({ v: u }, cell), new RefMap({ v: v }, cell)]; } /** `Ref::clone`: `r` again, a shared borrow of its own, which never conflicts. */ @@ -426,6 +455,37 @@ export function refClone(r: RefCell): RefCell { return r; } +/** + * Where `part`, an object a `&mut` lends, is: the object itself, which a whole value is + * written into in place, as a write through that `&mut` would. + */ +export function partPlace(part: T): Place { + return place( + () => part, + (value) => { + if (Array.isArray(part)) vecAssign(part, value as unknown[]); + else ptrWrite(part, value); + }, + ); +} + +/** `RefMut::map`: a `RefMut` of the part of `r`'s value at `at`, which takes over `r`'s borrow. */ +export function refMutMap(r: RefCell, at: Place): RefCell { + return new RefMap(at, refCellOf(r)); +} + +/** `RefMut::filter_map`: `refMutMap` of the part at `at`, or `r` back if there is none. */ +export function refMutFilterMap(r: RefCell, at: Place | undefined): Result, RefCell> { + return at === undefined ? Err(r) : Ok(new RefMap(at, refCellOf(r))); +} + +/** `RefMut::map_split`: `RefMut`s of the parts of `r`'s value at `a` and `b`, which share `r`'s borrow. */ +export function refMutMapSplit(r: RefCell, a: Place, b: Place): [RefCell, RefCell] { + const cell = refCellOf(r); + cell.borrows--; + return [new RefMap(a, cell), new RefMap(b, cell)]; +} + /** `RefCell::try_borrow`'s error: the cell is mutably borrowed. */ export class BorrowError {} @@ -481,8 +541,8 @@ export function refCellClone(cell: RefCell, clone?: (value: T) => T): RefC } /** A `RefMut`'s or an `RwLockWriteGuard`'s drop. */ -export function refMutRelease(cell: RefCell): void { - cell.borrows = 0; +export function refMutRelease(r: RefCell): void { + refCellOf(r).borrows++; } /** diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index a99df894a..5f05d3b53 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -316,6 +316,9 @@ impl Std { ["cell", "BorrowError"] => Some(Self::BorrowError), ["cell", "BorrowMutError"] => Some(Self::BorrowMutError), ["sync", "once_lock", "OnceLock"] => Some(Self::OnceLock), + // What a read-write lock's guards map to, which guard as they do. + ["sync", "poison", "rwlock", "MappedRwLockReadGuard"] => Some(Self::Ref), + ["sync", "poison", "rwlock", "MappedRwLockWriteGuard"] => Some(Self::RefMut), ["sync", "once", "Once"] => Some(Self::Once), ["sync", "once", "OnceState"] => Some(Self::OnceState), ["cell", "lazy", "LazyCell"] => Some(Self::LazyCell), @@ -902,7 +905,11 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { ("slice", "fill" | "fill_with" | "clone_from_slice") => &[0], // `get_or_init::` drops its function uncalled if the cell is set. ("OnceCell" | "OnceLock", "get_or_init" | "get_or_try_init") => &[1], - ("Ref", "map") => &[], + // A guard's map calls its function, filtered or not. + ( + "Ref" | "RefMut" | "RwLockReadGuard" | "RwLockWriteGuard" | "MappedRwLockReadGuard" | "MappedRwLockWriteGuard", + "map" | "filter_map" | "map_split", + ) => &[], ("Once", "call_once" | "call_once_force") => &[0], ("Arc" | "Rc", "new_cyclic") => &[1], // `pop_if::` drops its test uncalled if there is no element. diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 5e115617c..226e1c761 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -336,7 +336,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let t = &*self.b.t; // Mappings that lend an element JS copies as its place, as a map's `get_mut` does, the // item a `Peekable` peeked, the place a `&mut dyn Any` wraps, a `RefCell` key's value, - // or the value of an `Arc`, a lock, or a cell. + // the value of an `Arc`, a lock, or a cell, or what a write guard lends its map. let lends = match library::key(tcx, def_id) { Some((owner, name)) => match (owner.as_str(), name.as_str()) { ("slice", "get_mut" | "first_mut" | "last_mut" | "iter_mut" | "split_first_mut" | "split_last_mut") @@ -345,7 +345,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { | ("Peekable", "peek_mut") | ("LocalKey", "with_borrow_mut") | ("Arc" | "Rc", "get_mut" | "make_mut") - | ("Mutex" | "RwLock" | "RefCell" | "OnceCell" | "OnceLock", "get_mut") => true, + | ("Mutex" | "RwLock" | "RefCell" | "OnceCell" | "OnceLock", "get_mut") + | ("RefMut" | "RwLockWriteGuard" | "MappedRwLockWriteGuard", "map" | "filter_map" | "map_split") => true, ("IntoIterator", "into_iter") => gargs.types().next().is_some_and(|ty| { let ty = crate::lower::iter::unbox_ref(tcx, ty); ty.ref_mutability() == Some(ty::Mutability::Mut) diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 9a32c203c..2bb71ef34 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -726,14 +726,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { matches!(self.mir.local_decls[place.local].ty.kind(), ty::RawPtr(..)) && !self.box_pointer(place.local); let e = match raw { true => Expr::rt("ptrWrite", vec![target, value]), - false => match self.write_in(pointee) { + false => match self.b.t.write_in(pointee) { Some(ObjectKind::Bytes) => target.member("set").call(vec![value]), // A `Vec` is an `rt.ByteVec`, and any other a JS array, as a boxed slice // is, whose length a write changes, unlike a tuple's or an array's. - Some(ObjectKind::Vec) if !byte_vec(self.erased(pointee)) => { + Some(ObjectKind::Vec) if !byte_vec(self.b.t.erased(pointee)) => { Expr::rt("vecAssign", vec![target, value]) } - Some(ObjectKind::Array) if self.erased(pointee).is_slice() => { + Some(ObjectKind::Array) if self.b.t.erased(pointee).is_slice() => { Expr::rt("vecAssign", vec![target, value]) } Some(_) => Expr::ident("Object").member("assign").call(vec![target, value]), @@ -773,45 +773,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { pub(super) fn in_object(&self, place: Place<'tcx>) -> bool { let raw = matches!(self.mir.local_decls[place.local].ty.kind(), ty::RawPtr(..)); self.pointee_object(place) - .and_then(|pointee| self.write_in(pointee)) + .and_then(|pointee| self.b.t.write_in(pointee)) .is_some_and(|kind| kind != ObjectKind::Bytes && !raw) } - /// The kind of a `pointee`'s object, through the `Pin`s and `Box`es JS erases, where a - /// whole value of it can be written into the object in place: one only its owner - /// holds, unlike an `Arc`'s, which its clones share, and whose parts `Object.assign` - /// copies, unlike a binding's, an `rt.PollFn`'s or a future's private fields, or a - /// trait object's, whatever class it is. - pub(super) fn write_in(&self, pointee: Ty<'tcx>) -> Option { - let erased = self.erased(pointee); - let hidden = match erased.kind() { - ty::Adt(adt, _) => { - self.b.t.bound_drops(adt.did()).is_some() || Std::of(self.tcx, adt.did()) == Some(Std::PollFn) - } - ty::Dynamic(..) | ty::Closure(..) => true, - // A `Uint8Array`'s length never changes, as a boxed slice's may. - ty::Slice(elem) => matches!(elem.kind(), ty::Uint(ty::UintTy::U8)), - _ => false, - }; - self.b.t.object_kind(pointee)?; - match self.b.t.object_kind(erased)? { - _ if hidden || shared(self, pointee) => None, - ObjectKind::Closure => None, - kind => Some(kind), - } - } - - /// What JS keeps of a `ty`: what it holds through any number of `Pin`s and `Box`es. - fn erased(&self, ty: Ty<'tcx>) -> Ty<'tcx> { - let mut erased = ty; - while let ty::Adt(adt, args) = erased.kind() - && matches!(Std::of(self.tcx, adt.did()), Some(Std::Pin | Std::Box)) - { - erased = args.type_at(0); - } - erased - } - /// A store of `value` to `place` as a store of the whole value to what holds it, where /// `place`, or what a reference to it reads, is the payload of an `Option`, `Poll`, /// `Result`, or `ControlFlow`: JS shares their values as immutable, so a payload @@ -1865,26 +1830,6 @@ fn written_captures(mir: &mir::Body<'_>) -> FxHashSet { written.0 } -/// Whether the JS object of a `ty` is shared or private, so that copying fields into it -/// would change other handles, or nothing. -fn shared<'tcx>(fx: &Fx<'_, '_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { - let tcx = fx.tcx; - let mut erased = ty; - while let ty::Adt(adt, args) = erased.kind() - && matches!(Std::of(tcx, adt.did()), Some(Std::Pin | Std::Box)) - { - erased = args.type_at(0); - } - match erased.kind() { - ty::Adt(adt, _) => matches!( - Std::of(tcx, adt.did()), - Some(Std::Arc | Std::Waker | Std::Context | Std::MutexGuard | Std::Ref | Std::RefMut) - ), - ty::Ref(..) | ty::Coroutine(..) => true, - _ => false, - } -} - /// Whether `ty` is a `Vec`, an `rt.ByteVec`. fn byte_vec(ty: Ty<'_>) -> bool { matches!(ty.kind(), ty::Adt(_, args) if args.types().next().is_some_and(|t| matches!(t.kind(), ty::Uint(ty::UintTy::U8)))) diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index c84d658ca..600917db8 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -1242,13 +1242,53 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { if self.object_kind(ty).is_none() { return true; } + matches!(self.std_of(self.erased(ty)), Some(Std::Arc | Std::Waker)) + } + + /// What JS keeps of a `ty`: what it holds through any number of `Pin`s and `Box`es. + pub fn erased(&self, ty: Ty<'tcx>) -> Ty<'tcx> { + use library::Std; let mut erased = ty; while let ty::Adt(adt, args) = erased.kind() && matches!(Std::of(self.tcx, adt.did()), Some(Std::Pin | Std::Box)) { erased = args.type_at(0); } - matches!(self.std_of(erased), Some(Std::Arc | Std::Waker)) + erased + } + + /// The kind of a `pointee`'s object, through the `Pin`s and `Box`es JS erases, where a + /// whole value of it can be written into the object in place: one only its owner + /// holds, unlike an `Arc`'s, which its clones share, and whose parts `Object.assign` + /// copies, unlike a binding's, an `rt.PollFn`'s or a future's private fields, or a + /// trait object's, whatever class it is. + pub fn write_in(&self, pointee: Ty<'tcx>) -> Option { + use library::Std; + let erased = self.erased(pointee); + let hidden = match erased.kind() { + ty::Adt(adt, _) => { + self.bound_drops(adt.did()).is_some() || Std::of(self.tcx, adt.did()) == Some(Std::PollFn) + } + ty::Dynamic(..) | ty::Closure(..) => true, + // A `Uint8Array`'s length never changes, as a boxed slice's may. + ty::Slice(elem) => matches!(elem.kind(), ty::Uint(ty::UintTy::U8)), + _ => false, + }; + // Copying fields into an object others share would change their handles too. + let shared = match erased.kind() { + ty::Adt(adt, _) => matches!( + Std::of(self.tcx, adt.did()), + Some(Std::Arc | Std::Waker | Std::Context | Std::MutexGuard | Std::Ref | Std::RefMut) + ), + ty::Ref(..) | ty::Coroutine(..) => true, + _ => false, + }; + self.object_kind(pointee)?; + match self.object_kind(erased)? { + _ if hidden || shared => None, + ObjectKind::Closure => None, + kind => Some(kind), + } } /// What `ty` points at, if it is a `&mut` that is an `rt.Place`. diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index c46c9bf40..8d8051dfc 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -260,7 +260,12 @@ pub fn call<'tcx>( ("RefCell", "borrow_mut") => Expr::rt("refCellBorrowMut", args), ("RefCell", "try_borrow") => Expr::rt("refCellTryBorrow", args), ("RefCell", "try_borrow_mut") => Expr::rt("refCellTryBorrowMut", args), - ("Ref", "map") => Expr::rt("refMap", args), + ("Ref" | "RwLockReadGuard" | "MappedRwLockReadGuard", "map") => Expr::rt("refMap", args), + ("Ref" | "RwLockReadGuard" | "MappedRwLockReadGuard", "filter_map") => Expr::rt("refFilterMap", args), + ("Ref", "map_split") => Expr::rt("refMapSplit", args), + ("RefMut" | "RwLockWriteGuard" | "MappedRwLockWriteGuard", "map" | "filter_map" | "map_split") => { + ref_mut_map(b, call, name, args, out) + } ("Ref", "clone") => Expr::rt("refClone", args), ("RefCell", "replace") => Expr::rt("refCellReplace", args), ("RefCell", "take") => { @@ -571,6 +576,71 @@ fn held(ty: Option>) -> Ty<'_> { } } +/// `map`, `filter_map`, or `map_split` of a `RefMut` or a write guard: its function called +/// on what the guard lends, and a guard of where each part that lends is, which a write +/// through it reaches. +fn ref_mut_map<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + name: &str, + args: Vec, + out: &mut Vec, +) -> Expr { + let tcx = b.t.tcx; + let [guard, f] = two(args); + let guard = match guard.is_path() { + true => guard, + false => b.spill(guard, "guard", out), + }; + // The guarded value, then each part's type. + let mut tys = call.args.types(); + let held = tys.next().expect("a guarded type"); + let lent = match b.t.needs_place(held) { + true => Expr::rt("valuePlace", vec![guard.clone()]), + false => guard.clone().member("value"), + }; + let lent = f.call(vec![lent]); + // A `&mut` to a part JS copies is its place, and one to an object is that object, which + // a whole value is written into in place. + let at = |b: &mut Body<'_, '_, 'tcx>, part: Ty<'tcx>, value: Expr| { + if b.t.needs_place(part) { + value + } else if b.t.write_in(part).is_none() && part.is_sized(tcx, b.t.typing_env_pub()) { + b.err( + call.span, + format!("a mapped guard of `{part}`, which JS can't write in place"), + ) + } else { + Expr::rt("partPlace", vec![value]) + } + }; + let part = tys.next().expect("a part's type"); + match name { + "map" => { + let at = at(b, part, lent); + Expr::rt("refMutMap", vec![guard, at]) + } + "filter_map" if b.t.needs_place(part) => Expr::rt("refMutFilterMap", vec![guard, lent]), + "filter_map" => { + let lent = b.spill(lent, "part", out); + let some = at(b, part, lent.clone()); + let at = Expr::Cond( + Box::new(lent.binary("===", Expr::undefined())), + Box::new(Expr::undefined()), + Box::new(some), + ); + Expr::rt("refMutFilterMap", vec![guard, at]) + } + _ => { + let pair = b.spill(lent, "parts", out); + let other = tys.next().expect("the other part's type"); + let a = at(b, part, pair.clone().index(Expr::lit("0"))); + let other = at(b, other, pair.index(Expr::lit("1"))); + Expr::rt("refMutMapSplit", vec![guard, a, other]) + } + } +} + /// What `get_mut` of `holder`, a `Mutex`, a `RefCell`, or an `RwLock`, lends: its value, /// or where that is where JS copies it. fn lend_value<'tcx>(b: &Body<'_, '_, 'tcx>, call: &Call<'tcx>, holder: Expr) -> Expr { From ecfdcaa3da355583d25c7649f37d2369e1ecc5dd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:31:05 -0800 Subject: [PATCH 3/4] fix(ts): give a guard's `[u8; N]` part as the array, through one map lowering for both guards Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/lang/expected/borrows.Parts.ts | 8 +- ts/fixtures/lang/expected/borrows.ts | 404 ++++++++++++--------- ts/fixtures/lang/expected/lib.ts | 17 + ts/fixtures/lang/expected/locks.ts | 24 +- ts/fixtures/lang/src/borrows.rs | 22 +- ts/runtime/rt/task.ts | 20 +- ts/src/lower/task.rs | 49 ++- 7 files changed, 339 insertions(+), 205 deletions(-) diff --git a/ts/fixtures/lang/expected/borrows.Parts.ts b/ts/fixtures/lang/expected/borrows.Parts.ts index a574e923e..ddca0ed13 100644 --- a/ts/fixtures/lang/expected/borrows.Parts.ts +++ b/ts/fixtures/lang/expected/borrows.Parts.ts @@ -4,8 +4,8 @@ import * as rt from "./rt.ts"; import type * as borrows_Tagged from "./borrows.Tagged.ts"; /** - * What mapped guards lend parts of: a number and a `String`, which JS copies, and a `Vec` - * and a value that logs as it drops, which it doesn't. + * What mapped guards lend parts of: a number and a `String`, which JS copies, a `Vec` and + * a value that logs as it drops, which it doesn't, and bytes, which a reference views. */ export class Parts { n: rt.u32; @@ -13,13 +13,15 @@ export class Parts { bytes: rt.ByteVec; tagged: borrows_Tagged.Tagged; maybe: rt.u16 | undefined; + quad: Uint8Array; - constructor(n: rt.u32, text: string, bytes: rt.ByteVec, tagged: borrows_Tagged.Tagged, maybe: rt.u16 | undefined) { + constructor(n: rt.u32, text: string, bytes: rt.ByteVec, tagged: borrows_Tagged.Tagged, maybe: rt.u16 | undefined, quad: Uint8Array) { this.n = n; this.text = text; this.bytes = bytes; this.tagged = tagged; this.maybe = maybe; + this.quad = quad; } [Symbol.dispose](): void { diff --git a/ts/fixtures/lang/expected/borrows.ts b/ts/fixtures/lang/expected/borrows.ts index d69301b56..4b47d9301 100644 --- a/ts/fixtures/lang/expected/borrows.ts +++ b/ts/fixtures/lang/expected/borrows.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Option_tuple2_u64_u64, copy$tuple2_u64_u64, drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Parts_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Tagged_cell_BorrowMutError, drop$Result_cell_RefMut_u32_cell_BorrowMutError, drop$Result_cell_Ref_Vec_u8_cell_BorrowError, drop$Result_cell_Ref_borrows_Parts_cell_BorrowError, drop$Result_cell_Ref_u32_cell_BorrowError, drop$Result_cell_Ref_u32_cell_Ref_borrows_Parts, drop$tuple2_Option_cell_Ref_borrows_Tagged_Option_cell_RefMut_borrows_Tagged, drop$tuple2_Result_cell_Ref_Vec_u8_cell_BorrowError_cell_Ref_Vec_u8, drop$tuple2_cell_RefMut_slice_u8_cell_RefMut_slice_u8, drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8 } from "./lib.ts"; +import { copy$Option_tuple2_u64_u64, copy$tuple2_u64_u64, drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError, drop$Result_cell_RefMut_array4_u8_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Parts_cell_BorrowMutError, drop$Result_cell_RefMut_borrows_Tagged_cell_BorrowMutError, drop$Result_cell_RefMut_u32_cell_BorrowMutError, drop$Result_cell_Ref_Vec_u8_cell_BorrowError, drop$Result_cell_Ref_array4_u8_cell_BorrowError, drop$Result_cell_Ref_borrows_Parts_cell_BorrowError, drop$Result_cell_Ref_u32_cell_BorrowError, drop$Result_cell_Ref_u32_cell_Ref_borrows_Parts, drop$tuple2_Option_cell_Ref_borrows_Tagged_Option_cell_RefMut_borrows_Tagged, drop$tuple2_Result_cell_Ref_Vec_u8_cell_BorrowError_cell_Ref_Vec_u8, drop$tuple2_cell_RefMut_slice_u8_cell_RefMut_slice_u8, drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8, drop$tuple2_cell_Ref_str_cell_RefMut_u32 } from "./lib.ts"; import * as borrows_Noisy from "./borrows.Noisy.ts"; import * as borrows_Parts from "./borrows.Parts.ts"; import * as borrows_Polling from "./borrows.Polling.ts"; @@ -203,12 +203,14 @@ export function guards(data: rt.ByteSlice, out: rt.ByteVec): void { return _05; }), 253)); } else if (_22 === 4) { - const n: rt.RefCell = rt.refMap(rt.refCellBorrow(tagged), (t2: borrows_Tagged.Tagged): rt.u32 => { + const _166: rt.RefCell = rt.refCellBorrow(tagged); + const n: rt.RefCell = rt.refMap(_166, ((t2: borrows_Tagged.Tagged): rt.u32 => { return t2.n; - }); - const id: rt.RefCell = rt.refMap(rt.refCellBorrow(tagged), (t3: borrows_Tagged.Tagged): rt.u8 => { + })(_166.value)); + const _169: rt.RefCell = rt.refCellBorrow(tagged); + const id: rt.RefCell = rt.refMap(_169, ((t3: borrows_Tagged.Tagged): rt.u8 => { return t3.id; - }); + })(_169.value)); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(n.value & 0xff, id.value))); const _186: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(tagged); rt.byteVecPush(out, !_186.ok ? 1 : 0); @@ -221,14 +223,15 @@ export function guards(data: rt.ByteSlice, out: rt.ByteVec): void { const _200: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(tagged); rt.byteVecPush(out, !_200.ok ? 1 : 0); drop$Result_cell_RefMut_borrows_Tagged_cell_BorrowMutError(_200); - const half: rt.RefCell = rt.refMap(rt.refCellBorrow(bytes), (b2: rt.ByteVec): rt.ByteSlice => { + const _203: rt.RefCell = rt.refCellBorrow(bytes); + const half: rt.RefCell = rt.refMap(_203, ((b2: rt.ByteVec): rt.ByteSlice => { const part2 = rt.usizeDiv(b2.length, 2); return rt.byteSliceRange(rt.byteVecSlice(b2), part2); - }); + })(_203.value)); rt.byteVecPush(out, half.value.length & 0xff); - const last: rt.RefCell = rt.refMap(half, (s: rt.ByteSlice): rt.u8 => { + const last: rt.RefCell = rt.refMap(half, ((s: rt.ByteSlice): rt.u8 => { return option_unwrapOr$0r2bmpr(rt.byteSliceLast(s), 253); - }); + })(half.value)); rt.byteVecPush(out, last.value); const _219: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(bytes); rt.byteVecPush(out, !_219.ok ? 1 : 0); @@ -244,9 +247,10 @@ export function guards(data: rt.ByteSlice, out: rt.ByteVec): void { const _237: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(bytes); rt.byteVecPush(out, !_237.ok ? 1 : 0); drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError(_237); - const c: rt.RefCell = rt.refMap(rt.refClone(b), (v: rt.ByteVec): rt.u8 => { + const _240: rt.RefCell = rt.refClone(b); + const c: rt.RefCell = rt.refMap(_240, ((v: rt.ByteVec): rt.u8 => { return option_unwrapOr$0r2bmpr(rt.byteSliceFirst(rt.byteVecSlice(v)), 253); - }); + })(_240.value)); const d: rt.RefCell = rt.refClone(c); drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8([b, c] as [rt.RefCell, rt.RefCell]); rt.byteVecPush(out, d.value); @@ -260,9 +264,10 @@ export function guards(data: rt.ByteSlice, out: rt.ByteVec): void { } else if (_22 === 6) { const _263: rt.u8 = op >> 4; if (_263 === 14) { - const _n: rt.RefCell = rt.refMap(rt.refCellBorrow(tagged), (t: borrows_Tagged.Tagged): rt.u32 => { + const _267: rt.RefCell = rt.refCellBorrow(tagged); + const _n: rt.RefCell = rt.refMap(_267, ((t: borrows_Tagged.Tagged): rt.u32 => { return t.n; - }); + })(_267.value)); rt.refMutRelease(rt.refCellBorrowMut(tagged)); rt.refRelease(_n); } else if (_263 === 15) { @@ -306,155 +311,159 @@ export function maps(data: rt.ByteSlice, out: rt.ByteVec): void { const tag: (a0: rt.u8) => borrows_Tagged.Tagged = (id: rt.u8): borrows_Tagged.Tagged => { return new borrows_Tagged.Tagged(id, 0, rt.arcClone(log)); }; - const parts: rt.RefCell = new rt.RefCell(new borrows_Parts.Parts(0, "", new rt.ByteVec(), tag(1), undefined)); + const parts: rt.RefCell = new rt.RefCell(new borrows_Parts.Parts(0, "", new rt.ByteVec(), tag(1), undefined, rt.bytes(4))); const number: rt.RefCell = new rt.RefCell(0); + const bytes4: rt.RefCell = new rt.RefCell(Uint8Array.of(1, 2, 3, 4)); const slot: rt.RefCell = new rt.RefCell(undefined as borrows_Tagged.Tagged | undefined); for (const op of rt.byteSliceView(data)) { - const _26: rt.u8 = rt.u8Rem(op, 8); - if (_26 === 0) { - const _29: rt.RefCell = rt.refCellBorrowMut(parts); - const n: rt.RefCell = rt.refMutMap(_29, ((p14: borrows_Parts.Parts): rt.Place => { - return rt.place(() => p14.n, (value7) => p14.n = value7); - })(_29.value)); + const _29: rt.u8 = rt.u8Rem(op, 8); + if (_29 === 0) { + const _32: rt.RefCell = rt.refCellBorrowMut(parts); + const n: rt.RefCell = rt.refMutMap(_32, ((p16: borrows_Parts.Parts): rt.Place => { + return rt.place(() => p16.n, (value8) => p16.n = value8); + })(_32.value)); n.value = rt.u32Add(n.value, op as rt.u32); rt.byteVecPush(out, borrowed$borrows_Parts(parts)); - const _39: rt.RefCell = n; - const again: rt.RefCell = rt.refMutMap(_39, ((n6: rt.Place): rt.Place => { + const _42: rt.RefCell = n; + const again: rt.RefCell = rt.refMutMap(_42, ((n6: rt.Place): rt.Place => { return n6; - })(rt.valuePlace(_39))); + })(rt.valuePlace(_42))); again.value = rt.u32Add(again.value, 1); rt.refMutRelease(again); - const _49: rt.u8 = borrowed$borrows_Parts(parts); - const _55: rt.RefCell = rt.refCellBorrow(parts); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_49, _55.value.n & 0xff))); - rt.refRelease(_55); - const _58: rt.RefCell = rt.refCellBorrowMut(number); - const whole: rt.RefCell = rt.refMutMap(_58, ((n7: rt.Place): rt.Place => { + const _52: rt.u8 = borrowed$borrows_Parts(parts); + const _58: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_52, _58.value.n & 0xff))); + rt.refRelease(_58); + const _61: rt.RefCell = rt.refCellBorrowMut(number); + const whole: rt.RefCell = rt.refMutMap(_61, ((n7: rt.Place): rt.Place => { return n7; - })(rt.valuePlace(_58))); - const _65: rt.u32 = rt.u32Add(rt.u32WrappingMul(whole.value, 3), op as rt.u32); - whole.value = _65; + })(rt.valuePlace(_61))); + const _68: rt.u32 = rt.u32Add(rt.u32WrappingMul(whole.value, 3), op as rt.u32); + whole.value = _68; rt.refMutRelease(whole); - const _75: rt.RefCell = rt.refCellBorrow(number); - rt.byteVecPush(out, _75.value & 0xff); - rt.refRelease(_75); - } else if (_26 === 1) { - const _78: rt.RefCell = rt.refCellBorrowMut(parts); - const text: rt.RefCell = rt.refMutMap(_78, ((p13: borrows_Parts.Parts): rt.Place => { - return rt.place(() => p13.text, (value6) => p13.text = value6); - })(_78.value)); + const _78: rt.RefCell = rt.refCellBorrow(number); + rt.byteVecPush(out, _78.value & 0xff); + rt.refRelease(_78); + } else if (_29 === 1) { + const _81: rt.RefCell = rt.refCellBorrowMut(parts); + const text: rt.RefCell = rt.refMutMap(_81, ((p15: borrows_Parts.Parts): rt.Place => { + return rt.place(() => p15.text, (value7) => p15.text = value7); + })(_81.value)); text.value = text.value + String.fromCodePoint(rt.u8Add(97, rt.u8Rem(op, 26)) as rt.char); if ((op >> 4) === 15) { text.value = "z"; } rt.byteVecPush(out, rt.stringLen(text.value) & 0xff); rt.refMutRelease(text); - const _107: rt.RefCell = rt.refCellBorrow(parts); - rt.byteVecExtendFromSlice(out, rt.stringAsBytes(_107.value.text)); - rt.refRelease(_107); - } else if (_26 === 2) { - const _110: rt.RefCell = rt.refCellBorrowMut(parts); - const bytes: rt.RefCell = rt.refMutMap(_110, rt.partPlace(((p11: borrows_Parts.Parts): rt.ByteVec => { - return p11.bytes; - })(_110.value))); + const _110: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(_110.value.text)); + rt.refRelease(_110); + } else if (_29 === 2) { + const _113: rt.RefCell = rt.refCellBorrowMut(parts); + const bytes: rt.RefCell = rt.refMutMap(_113, rt.partPlace(((p13: borrows_Parts.Parts): rt.ByteVec => { + return p13.bytes; + })(_113.value))); rt.byteVecPush(bytes.value, op); if ((op >> 4) === 15) { - const _119: rt.ByteVec = rt.byteVecFrom(Uint8Array.of(op, op)); - bytes.value = _119; + const _122: rt.ByteVec = rt.byteVecFrom(Uint8Array.of(op, op)); + bytes.value = _122; } rt.refMutRelease(bytes); - const _130: rt.RefCell = rt.refCellBorrow(parts); - rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_130.value.bytes)); - rt.refRelease(_130); - const _133: rt.RefCell = rt.refCellBorrowMut(parts); - const tagged: rt.RefCell = rt.refMutMap(_133, rt.partPlace(((p12: borrows_Parts.Parts): borrows_Tagged.Tagged => { - return p12.tagged; - })(_133.value))); + const _133: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_133.value.bytes)); + rt.refRelease(_133); + const _136: rt.RefCell = rt.refCellBorrowMut(parts); + const tagged: rt.RefCell = rt.refMutMap(_136, rt.partPlace(((p14: borrows_Parts.Parts): borrows_Tagged.Tagged => { + return p14.tagged; + })(_136.value))); tagged.value.n = rt.u32Add(tagged.value.n, 1); - const _138: borrows_Tagged.Tagged = new borrows_Tagged.Tagged(op, tagged.value.n, rt.arcClone(log)); + const _142: rt.u32 = tagged.value.n; + const _145: rt.Arc> = rt.arcClone(log); + const _141: borrows_Tagged.Tagged = new borrows_Tagged.Tagged(op, _142, _145); tagged.value[Symbol.dispose](); - tagged.value = _138; + tagged.value = _141; flush(log.value, out); rt.refMutRelease(tagged); - const _158: rt.RefCell = rt.refCellBorrow(parts); - const _155: rt.u8 = _158.value.tagged.id; - const _164: rt.RefCell = rt.refCellBorrow(parts); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_155, _164.value.tagged.n & 0xff))); - rt.refRelease(_164); - rt.refRelease(_158); - } else if (_26 === 3) { - const _167: rt.RefCell = rt.refCellBorrowMut(parts); - const _166: rt.Result, rt.RefCell> = rt.refMutFilterMap(_167, ((p9: borrows_Parts.Parts): rt.Place | undefined => { - return p9.maybe === undefined ? undefined : rt.place(() => p9.maybe as rt.u16, (value5) => p9.maybe = value5); - })(_167.value)); - if (_166.ok) { - const m: rt.RefCell = _166.value; + const _161: rt.RefCell = rt.refCellBorrow(parts); + const _158: rt.u8 = _161.value.tagged.id; + const _167: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_158, _167.value.tagged.n & 0xff))); + rt.refRelease(_167); + rt.refRelease(_161); + } else if (_29 === 3) { + const _170: rt.RefCell = rt.refCellBorrowMut(parts); + const _169: rt.Result, rt.RefCell> = rt.refMutFilterMap(_170, ((p11: borrows_Parts.Parts): rt.Place | undefined => { + return p11.maybe === undefined ? undefined : rt.place(() => p11.maybe as rt.u16, (value6) => p11.maybe = value6); + })(_170.value)); + if (_169.ok) { + const m: rt.RefCell = _169.value; m.value = rt.u16Add(m.value, 1); rt.byteVecPush(out, m.value & 0xff); rt.refMutRelease(m); } else { - const whole2: rt.RefCell = _166.error; + const whole2: rt.RefCell = _169.error; whole2.value.maybe = op as rt.u16; rt.byteVecPush(out, borrowed$borrows_Parts(parts)); rt.refMutRelease(whole2); } rt.byteVecPush(out, borrowed$borrows_Parts(parts)); - const _191: rt.Result, rt.RefCell> = rt.refFilterMap(rt.refCellBorrow(parts), (p10: borrows_Parts.Parts): rt.u8 | undefined => { - return rt.byteSliceLast(rt.byteVecSlice(p10.bytes)); - }); - if (_191.ok) { - const last: rt.RefCell = _191.value; + const _195: rt.RefCell = rt.refCellBorrow(parts); + const _194: rt.Result, rt.RefCell> = rt.refFilterMap(_195, ((p12: borrows_Parts.Parts): rt.u8 | undefined => { + return rt.byteSliceLast(rt.byteVecSlice(p12.bytes)); + })(_195.value)); + if (_194.ok) { + const last: rt.RefCell = _194.value; rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(last.value, borrowed$borrows_Parts(parts)))); rt.refRelease(last); } else { - const whole3: rt.RefCell = _191.error; + const whole3: rt.RefCell = _194.error; rt.byteVecPush(out, 240 | (whole3.value.bytes.length & 0xff)); rt.refRelease(whole3); } rt.byteVecPush(out, borrowed$borrows_Parts(parts)); - const _215: rt.RefCell = rt.refCellBorrowMut(slot); + const _218: rt.RefCell = rt.refCellBorrowMut(slot); const part = ((s2: rt.Place): borrows_Tagged.Tagged | undefined => { return s2.v; - })(rt.valuePlace(_215)); - const _214: rt.Result, rt.RefCell> = rt.refMutFilterMap(_215, part === undefined ? undefined : rt.partPlace(part)); - if (_214.ok) { - const t: rt.RefCell = _214.value; - const _219: borrows_Tagged.Tagged = tag(op); + })(rt.valuePlace(_218)); + const _217: rt.Result, rt.RefCell> = rt.refMutFilterMap(_218, part === undefined ? undefined : rt.partPlace(part)); + if (_217.ok) { + const t: rt.RefCell = _217.value; + const _222: borrows_Tagged.Tagged = tag(op); t.value[Symbol.dispose](); - t.value = _219; + t.value = _222; rt.refMutRelease(t); } else { - const s: rt.RefCell = _214.error; - const _225: borrows_Tagged.Tagged | undefined = tag(op); + const s: rt.RefCell = _217.error; + const _228: borrows_Tagged.Tagged | undefined = tag(op); rt.drop(s.value); - s.value = _225; + s.value = _228; rt.refMutRelease(s); } flush(log.value, out); - const _239: rt.RefCell = rt.refCellBorrow(slot); - rt.byteVecPush(out, option_mapOr$1dvn0au(_239.value, 253, (t2: borrows_Tagged.Tagged): rt.u8 => { + const _242: rt.RefCell = rt.refCellBorrow(slot); + rt.byteVecPush(out, option_mapOr$1dvn0au(_242.value, 253, (t2: borrows_Tagged.Tagged): rt.u8 => { return t2.id; })); - rt.refRelease(_239); - } else if (_26 === 4) { - const _243: [rt.RefCell, rt.RefCell] = rt.refMapSplit(rt.refCellBorrow(parts), (p8: borrows_Parts.Parts): [rt.u32, rt.ByteVec] => { - return [p8.n, p8.bytes] as [rt.u32, rt.ByteVec]; - }); - const n2: rt.RefCell = _243[0]; - const bytes2: rt.RefCell = _243[1]; + rt.refRelease(_242); + } else if (_29 === 4) { + const _247: rt.RefCell = rt.refCellBorrow(parts); + const _246: [rt.RefCell, rt.RefCell] = rt.refMapSplit(_247, ((p10: borrows_Parts.Parts): [rt.u32, rt.ByteVec] => { + return [p10.n, p10.bytes] as [rt.u32, rt.ByteVec]; + })(_247.value)); + const n2: rt.RefCell = _246[0]; + const bytes2: rt.RefCell = _246[1]; rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(n2.value & 0xff, bytes2.value.length & 0xff, borrowed$borrows_Parts(parts)))); rt.refRelease(n2); rt.byteVecPush(out, borrowed$borrows_Parts(parts)); rt.refRelease(bytes2); rt.byteVecPush(out, borrowed$borrows_Parts(parts)); - } else if (_26 === 5) { - const _271: rt.RefCell = rt.refCellBorrowMut(parts); - const parts3 = ((p6: borrows_Parts.Parts): [rt.Place, rt.Place] => { - return [rt.place(() => p6.n, (value3) => p6.n = value3), rt.place(() => p6.text, (value4) => p6.text = value4)] as [rt.Place, rt.Place]; - })(_271.value); - const _270: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_271, parts3[0], parts3[1]); - const n3: rt.RefCell = _270[0]; - const text2: rt.RefCell = _270[1]; + } else if (_29 === 5) { + const _274: rt.RefCell = rt.refCellBorrowMut(parts); + const _273: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_274, ((p8: borrows_Parts.Parts): [rt.Place, rt.Place] => { + return [rt.place(() => p8.n, (value4) => p8.n = value4), rt.place(() => p8.text, (value5) => p8.text = value5)] as [rt.Place, rt.Place]; + })(_274.value)); + const n3: rt.RefCell = _273[0]; + const text2: rt.RefCell = _273[1]; n3.value = rt.u32Add(n3.value, 1); text2.value = text2.value + "s"; rt.byteVecPush(out, borrowed$borrows_Parts(parts)); @@ -467,82 +476,132 @@ export function maps(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, borrowed$borrows_Parts(parts)); rt.refMutRelease(text2); } - const _302: rt.u8 = borrowed$borrows_Parts(parts); - const _308: rt.RefCell = rt.refCellBorrow(parts); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_302, _308.value.n & 0xff))); - rt.refRelease(_308); - const _313: rt.RefCell = rt.refCellBorrowMut(parts); - const parts4 = ((p7: borrows_Parts.Parts): [rt.ByteSlice, rt.ByteSlice] => { - const half: rt.usize = rt.usizeDiv(p7.bytes.length, 2); - return rt.byteSliceSplitAt(rt.byteVecSlice(p7.bytes), half); - })(_313.value); - const _312: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_313, rt.partPlace(parts4[0]), rt.partPlace(parts4[1])); - const low: rt.RefCell = _312[0]; - const high: rt.RefCell = _312[1]; - const _315: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(low.value)); - if (_315 !== undefined) { - _315.v = rt.u8WrappingAdd(_315.v, op); + const _305: rt.u8 = borrowed$borrows_Parts(parts); + const _311: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_305, _311.value.n & 0xff))); + rt.refRelease(_311); + const _316: rt.RefCell = rt.refCellBorrowMut(parts); + const parts3 = ((p9: borrows_Parts.Parts): [rt.ByteSlice, rt.ByteSlice] => { + const half: rt.usize = rt.usizeDiv(p9.bytes.length, 2); + return rt.byteSliceSplitAt(rt.byteVecSlice(p9.bytes), half); + })(_316.value); + const _315: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_316, [rt.partPlace(parts3[0]), rt.partPlace(parts3[1])]); + const low: rt.RefCell = _315[0]; + const high: rt.RefCell = _315[1]; + const _318: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(low.value)); + if (_318 !== undefined) { + _318.v = rt.u8WrappingAdd(_318.v, op); } - const _322: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(high.value)); - if (_322 !== undefined) { - _322.v = _322.v ^ 255; + const _325: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(high.value)); + if (_325 !== undefined) { + _325.v = _325.v ^ 255; } drop$tuple2_cell_RefMut_slice_u8_cell_RefMut_slice_u8([low, high] as [rt.RefCell, rt.RefCell]); - const _336: rt.RefCell = rt.refCellBorrow(parts); - rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_336.value.bytes)); - rt.refRelease(_336); - } else if (_26 === 6) { - const _338: rt.u8 = op >> 4; - if (_338 === 12) { - const _342: rt.RefCell = rt.refCellBorrowMut(parts); - const _n: rt.RefCell = rt.refMutMap(_342, ((p5: borrows_Parts.Parts): rt.Place => { - return rt.place(() => p5.n, (value2) => p5.n = value2); - })(_342.value)); + const _339: rt.RefCell = rt.refCellBorrow(parts); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(_339.value.bytes)); + rt.refRelease(_339); + } else if (_29 === 6) { + const _341: rt.u8 = op >> 4; + if (_341 === 12) { + const _345: rt.RefCell = rt.refCellBorrowMut(parts); + const _n: rt.RefCell = rt.refMutMap(_345, ((p7: borrows_Parts.Parts): rt.Place => { + return rt.place(() => p7.n, (value3) => p7.n = value3); + })(_345.value)); rt.refRelease(rt.refCellBorrow(parts)); rt.refMutRelease(_n); - } else if (_338 === 13) { - const _349: rt.RefCell = rt.refCellBorrowMut(parts); - const parts2 = ((p4: borrows_Parts.Parts): [rt.Place, rt.ByteVec] => { - return [rt.place(() => p4.n, (value) => p4.n = value), p4.bytes] as [rt.Place, rt.ByteVec]; - })(_349.value); - const _348: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_349, parts2[0], rt.partPlace(parts2[1])); - const a: rt.RefCell = _348[0]; - const _b: rt.RefCell = _348[1]; + } else if (_341 === 13) { + const _352: rt.RefCell = rt.refCellBorrowMut(parts); + const parts2 = ((p6: borrows_Parts.Parts): [rt.Place, rt.ByteVec] => { + return [rt.place(() => p6.n, (value2) => p6.n = value2), p6.bytes] as [rt.Place, rt.ByteVec]; + })(_352.value); + const _351: [rt.RefCell, rt.RefCell] = rt.refMutMapSplit(_352, [parts2[0], rt.partPlace(parts2[1])]); + const a: rt.RefCell = _351[0]; + const _b: rt.RefCell = _351[1]; rt.refMutRelease(a); rt.refMutRelease(rt.refCellBorrowMut(parts)); rt.refMutRelease(_b); - } else if (_338 === 14) { - const _f: rt.Result, rt.RefCell> = rt.refFilterMap(rt.refCellBorrow(parts), (p3: borrows_Parts.Parts): rt.u32 | undefined => { - return p3.n; - }); + } else if (_341 === 14) { + const _358: rt.RefCell = rt.refCellBorrow(parts); + const _f: rt.Result, rt.RefCell> = rt.refFilterMap(_358, ((p5: borrows_Parts.Parts): rt.u32 | undefined => { + return p5.n; + })(_358.value)); rt.refMutRelease(rt.refCellBorrowMut(parts)); drop$Result_cell_Ref_u32_cell_Ref_borrows_Parts(_f); - } else if (_338 === 15) { - const _361: [rt.RefCell, rt.RefCell] = rt.refMapSplit(rt.refCellBorrow(parts), (p2: borrows_Parts.Parts): [rt.u32, string] => { - return [p2.n, p2.text] as [rt.u32, string]; - }); - const _a: rt.RefCell = _361[0]; - rt.refRelease(_361[1]); + } else if (_341 === 15) { + const _365: rt.RefCell = rt.refCellBorrow(parts); + const _364: [rt.RefCell, rt.RefCell] = rt.refMapSplit(_365, ((p4: borrows_Parts.Parts): [rt.u32, string] => { + return [p4.n, p4.text] as [rt.u32, string]; + })(_365.value)); + const _a: rt.RefCell = _364[0]; + rt.refRelease(_364[1]); rt.refMutRelease(rt.refCellBorrowMut(parts)); rt.refRelease(_a); } else { rt.byteVecPush(out, borrowed$borrows_Parts(parts)); } } else { - const text3: rt.RefCell = rt.refMap(rt.refCellBorrow(parts), (p: borrows_Parts.Parts): string => { + const _373: rt.RefCell = rt.refCellBorrow(parts); + const text3: rt.RefCell = rt.refMap(_373, ((p: borrows_Parts.Parts): string => { return p.text; - }); - const _373: rt.RefCell = rt.refCellBorrowMut(number); - const n4: rt.RefCell = rt.refMutMap(_373, ((n5: rt.Place): rt.Place => { + })(_373.value)); + const _376: rt.RefCell = rt.refCellBorrowMut(number); + const n4: rt.RefCell = rt.refMutMap(_376, ((n5: rt.Place): rt.Place => { return n5; - })(rt.valuePlace(_373))); - const _384: string = text3.value; - const _387: rt.u32 = rt.u32Add(n4.value, 1); - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _384), (f: rt.Formatter) => rt.u32Display(_387, f)]; + })(rt.valuePlace(_376))); + const _387: string = text3.value; + const _390: rt.u32 = rt.u32Add(n4.value, 1); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, _387), (f: rt.Formatter) => rt.u32Display(_390, f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1]]))); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(borrowed$borrows_Parts(parts), borrowed$u32(number)))); - rt.refMutRelease(n4); - rt.refRelease(text3); + drop$tuple2_cell_Ref_str_cell_RefMut_u32([text3, n4] as [rt.RefCell, rt.RefCell]); + const _411: rt.RefCell = rt.refCellBorrowMut(parts); + const quad: rt.RefCell = rt.refMutMap(_411, rt.partPlace(rt.byteSliceView(((p2: borrows_Parts.Parts): rt.ByteSlice => { + return rt.byteSliceFrom(p2.quad); + })(_411.value)))); + const _413: rt.ByteSlice = rt.byteSliceFrom(quad.value); + const _415: rt.usize = ((op >> 4) & 3) as rt.usize; + if (!(_415 < 4)) { + rt.panic("index out of bounds: the len is " + 4 + " but the index is " + _415); + } + _413.data[_413.start + _415] = _413.data[_413.start + _415] ^ op; + if ((op & 64) !== 0) { + const _423: rt.ByteSlice = rt.byteSliceFrom(quad.value); + _423.data.set(rt.bytes(4).fill(op), _423.start); + } + rt.refMutRelease(quad); + const _428: rt.RefCell = rt.refCellBorrow(parts); + const quad2: rt.RefCell = rt.refMap(_428, rt.byteSliceView(((p3: borrows_Parts.Parts): rt.ByteSlice => { + return rt.byteSliceFrom(p3.quad); + })(_428.value))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(quad2.value)); + rt.refRelease(quad2); + const _436: rt.RefCell = rt.refCellBorrowMut(bytes4); + const _438: (a0: rt.ByteSlice) => rt.Place = (b2: rt.ByteSlice): rt.Place => { + const _33: rt.usize = (op & 3) as rt.usize; + if (!(_33 < 4)) { + rt.panic("index out of bounds: the len is " + 4 + " but the index is " + _33); + } + return rt.place(() => b2.data[b2.start + _33], (value) => b2.data[b2.start + _33] = value); + }; + const byte: rt.RefCell = rt.refMutMap(_436, ((held) => _438(rt.byteSliceFrom(held)))(_436.value)); + const _440: rt.u8 = rt.u8WrappingAdd(byte.value, op); + byte.value = _440; + rt.refMutRelease(byte); + const _451: rt.RefCell = rt.refCellBorrow(bytes4); + const f = (b3: rt.ByteSlice): [rt.ByteSlice, rt.ByteSlice] => { + return rt.byteSliceSplitAt(b3, 2); + }; + const _450: [rt.RefCell, rt.RefCell] = rt.refMapSplit(_451, ((held2) => f(rt.byteSliceFrom(held2)))(_451.value)); + const low2: rt.RefCell = _450[0]; + const high2: rt.RefCell = _450[1]; + const _459: rt.ByteSlice = low2.value; + rt.idx(_459, 0); + const _458: rt.u8 = _459.data[_459.start]; + const _465: rt.ByteSlice = high2.value; + rt.idx(_465, 1); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_458 ^ _465.data[_465.start + 1], borrowed$array4_u8(bytes4)))); + rt.refRelease(high2); + rt.refRelease(low2); } flush(log.value, out); } @@ -558,6 +617,27 @@ export function maps(data: rt.ByteSlice, out: rt.ByteVec): void { log[Symbol.dispose](); } +/** Whether `cell` is borrowed exclusively, as 2, shared, as 1, or not at all. */ +export function borrowed$array4_u8(cell: rt.RefCell): rt.u8 { + let _0!: rt.u8; + const _5: rt.Result, rt.BorrowError> = rt.refCellTryBorrow(cell); + const _3: boolean = !_5.ok; + const _8: rt.Result, rt.BorrowMutError> = rt.refCellTryBorrowMut(cell); + const _2: [boolean, boolean] = [_3, !_8.ok]; + if (!_3) { + if (!_2[1]) { + _0 = 0; + } else { + _0 = 1; + } + } else { + _0 = 2; + } + drop$Result_cell_RefMut_array4_u8_cell_BorrowMutError(_8); + drop$Result_cell_Ref_array4_u8_cell_BorrowError(_5); + return _0; +} + /** Whether `cell` is borrowed exclusively, as 2, shared, as 1, or not at all. */ export function borrowed$borrows_Parts(cell: rt.RefCell): rt.u8 { let _0!: rt.u8; diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index d9545bb47..9b71b7a71 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -805,6 +805,12 @@ export function drop$Result_cell_RefMut_Vec_u8_cell_BorrowMutError(_1: rt.Result } } +export function drop$Result_cell_RefMut_array4_u8_cell_BorrowMutError(_1: rt.Result, rt.BorrowMutError>): void { + if (_1.ok) { + rt.refMutRelease(_1.value); + } +} + export function drop$Result_cell_RefMut_borrows_Parts_cell_BorrowMutError(_1: rt.Result, rt.BorrowMutError>): void { if (_1.ok) { rt.refMutRelease(_1.value); @@ -829,6 +835,12 @@ export function drop$Result_cell_Ref_Vec_u8_cell_BorrowError(_1: rt.Result, rt.BorrowError>): void { + if (_1.ok) { + rt.refRelease(_1.value); + } +} + export function drop$Result_cell_Ref_borrows_Parts_cell_BorrowError(_1: rt.Result, rt.BorrowError>): void { if (_1.ok) { rt.refRelease(_1.value); @@ -997,6 +1009,11 @@ export function drop$tuple2_cell_Ref_Vec_u8_cell_Ref_u8(_1: [rt.RefCell, rt.RefCell]): void { + rt.refRelease(_1[0]); + rt.refMutRelease(_1[1]); +} + export function drop$tuple2_sync_Arc_collections_Picky_u8(_1: [rt.Arc, rt.u8]): void { _1[0][Symbol.dispose](); } diff --git a/ts/fixtures/lang/expected/locks.ts b/ts/fixtures/lang/expected/locks.ts index dbc41c15c..b80893d2f 100644 --- a/ts/fixtures/lang/expected/locks.ts +++ b/ts/fixtures/lang/expected/locks.ts @@ -258,13 +258,14 @@ export function mapped(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, rt.u64Low(_44.value.n) & 0xff); rt.refRelease(_44); } else if (_13 === 1) { - const seen: rt.RefCell = rt.refMap(rt.rwLockRead(lock), (t6: locks_Tally.Tally): rt.ByteVec => { + const _48: rt.RefCell = rt.rwLockRead(lock); + const seen: rt.RefCell = rt.refMap(_48, ((t6: locks_Tally.Tally): rt.ByteVec => { return t6.seen; - }); + })(_48.value)); rt.byteVecPush(out, seen.value.length & 0xff); - const last: rt.RefCell = rt.refMap(seen, (s: rt.ByteVec): rt.u8 => { + const last: rt.RefCell = rt.refMap(seen, ((s: rt.ByteVec): rt.u8 => { return option_unwrapOr$0r2bmpr(rt.byteSliceLast(rt.byteVecSlice(s)), 253); - }); + })(seen.value)); rt.byteVecPush(out, last.value); locked(out); rt.refRelease(last); @@ -285,13 +286,15 @@ export function mapped(data: rt.ByteSlice, out: rt.ByteVec): void { rt.refMutRelease(whole); } locked(out); - const _89: rt.Result, rt.RefCell> = rt.refFilterMap(rt.rwLockRead(lock), (t4: locks_Tally.Tally): rt.u8 | undefined => { + const _90: rt.RefCell = rt.rwLockRead(lock); + const _89: rt.Result, rt.RefCell> = rt.refFilterMap(_90, ((t4: locks_Tally.Tally): rt.u8 | undefined => { return rt.byteSliceFirst(rt.byteVecSlice(t4.seen)); - }); + })(_90.value)); if (_89.ok) { - const _95: rt.Result, rt.RefCell> = rt.refFilterMap(_89.value, (b2: rt.u8): rt.u8 | undefined => { + const first: rt.RefCell = _89.value; + const _95: rt.Result, rt.RefCell> = rt.refFilterMap(first, ((b2: rt.u8): rt.u8 | undefined => { return thenSome$0d5am30(b2 > 128, b2); - }); + })(first.value)); if (_95.ok) { const b: rt.RefCell = _95.value; rt.byteVecPush(out, b.value); @@ -344,9 +347,10 @@ export function mapped(data: rt.ByteSlice, out: rt.ByteVec): void { })(_149.value)); locked(out); rt.refMutRelease(n5); - const n6: rt.RefCell = rt.refMap(rt.rwLockRead(lock), (t2: locks_Tally.Tally): rt.u64 => { + const _157: rt.RefCell = rt.rwLockRead(lock); + const n6: rt.RefCell = rt.refMap(_157, ((t2: locks_Tally.Tally): rt.u64 => { return t2.n; - }); + })(_157.value)); locked(out); rt.byteVecPush(out, rt.u64Low(n6.value) & 0xff); rt.refRelease(n6); diff --git a/ts/fixtures/lang/src/borrows.rs b/ts/fixtures/lang/src/borrows.rs index 13f0aa398..66ee4491f 100644 --- a/ts/fixtures/lang/src/borrows.rs +++ b/ts/fixtures/lang/src/borrows.rs @@ -271,14 +271,15 @@ pub fn guards(data: &[u8], out: &mut Vec) { flush(&log, out); } -/// What mapped guards lend parts of: a number and a `String`, which JS copies, and a `Vec` -/// and a value that logs as it drops, which it doesn't. +/// What mapped guards lend parts of: a number and a `String`, which JS copies, a `Vec` and +/// a value that logs as it drops, which it doesn't, and bytes, which a reference views. struct Parts { n: u32, text: String, bytes: Vec, tagged: Tagged, maybe: Option, + quad: [u8; 4], } /// Each byte an operation on `RefCell`s through guards mapped, filtered, and split to their @@ -297,8 +298,10 @@ pub fn maps(data: &[u8], out: &mut Vec) { bytes: Vec::new(), tagged: tag(1), maybe: None, + quad: [0; 4], }); let number = RefCell::new(0u32); + let bytes4 = RefCell::new([1u8, 2, 3, 4]); let slot: RefCell> = RefCell::new(None); for &op in data { match op % 8 { @@ -438,6 +441,21 @@ pub fn maps(data: &[u8], out: &mut Vec) { let n = RefMut::map(number.borrow_mut(), |n| n); out.extend_from_slice(format!("{} {}", &*text, *n + 1).as_bytes()); out.extend_from_slice(&[borrowed(&parts), borrowed(&number)]); + drop((text, n)); + let mut quad = RefMut::map(parts.borrow_mut(), |p| &mut p.quad); + quad[usize::from(op >> 4 & 3)] ^= op; + if op & 0x40 != 0 { + *quad = [op; 4]; + } + drop(quad); + let quad = Ref::map(parts.borrow(), |p| &p.quad); + out.extend_from_slice(&*quad); + drop(quad); + let mut byte = RefMut::map(bytes4.borrow_mut(), |b| &mut b[usize::from(op & 3)]); + *byte = byte.wrapping_add(op); + drop(byte); + let (low, high) = Ref::map_split(bytes4.borrow(), |b| b.split_at(2)); + out.extend_from_slice(&[low[0] ^ high[1], borrowed(&bytes4)]); } } flush(&log, out); diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index d93f2cfdd..0359945d1 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -430,23 +430,21 @@ export function refRelease(r: RefCell): void { refCellOf(r).borrows--; } -/** `Ref::map`: a `Ref` of the part of `r`'s value `f` lends, which takes over `r`'s borrow. */ -export function refMap(r: RefCell, f: (value: T) => U): RefCell { - return new RefMap({ v: f(r.value) }, refCellOf(r)); +/** `Ref::map`: a `Ref` of `part` of `r`'s value, which takes over `r`'s borrow. */ +export function refMap(r: RefCell, part: U): RefCell { + return new RefMap({ v: part }, refCellOf(r)); } -/** `Ref::filter_map`: `refMap` of the part `f` lends, or `r` back if it lends none. */ -export function refFilterMap(r: RefCell, f: (value: T) => U | undefined): Result, RefCell> { - const part = f(r.value); +/** `Ref::filter_map`: `refMap` of `part`, or `r` back if there is none. */ +export function refFilterMap(r: RefCell, part: U | undefined): Result, RefCell> { return part === undefined ? Err(r) : Ok(new RefMap({ v: part }, refCellOf(r))); } -/** `Ref::map_split`: `Ref`s of the two parts of `r`'s value `f` lends, which share `r`'s borrow. */ -export function refMapSplit(r: RefCell, f: (value: T) => [U, V]): [RefCell, RefCell] { - const [u, v] = f(r.value); +/** `Ref::map_split`: `Ref`s of the two `parts` of `r`'s value, which share `r`'s borrow. */ +export function refMapSplit(r: RefCell, [u, v]: [U, V]): [RefCell, RefCell] { const cell = refCellOf(r); cell.borrows++; - return [new RefMap({ v: u }, cell), new RefMap({ v: v }, cell)]; + return [new RefMap({ v: u }, cell), new RefMap({ v }, cell)]; } /** `Ref::clone`: `r` again, a shared borrow of its own, which never conflicts. */ @@ -480,7 +478,7 @@ export function refMutFilterMap(r: RefCell, at: Place | undefined): } /** `RefMut::map_split`: `RefMut`s of the parts of `r`'s value at `a` and `b`, which share `r`'s borrow. */ -export function refMutMapSplit(r: RefCell, a: Place, b: Place): [RefCell, RefCell] { +export function refMutMapSplit(r: RefCell, [a, b]: [Place, Place]): [RefCell, RefCell] { const cell = refCellOf(r); cell.borrows--; return [new RefMap(a, cell), new RefMap(b, cell)]; diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 8d8051dfc..edff1345e 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -260,11 +260,11 @@ pub fn call<'tcx>( ("RefCell", "borrow_mut") => Expr::rt("refCellBorrowMut", args), ("RefCell", "try_borrow") => Expr::rt("refCellTryBorrow", args), ("RefCell", "try_borrow_mut") => Expr::rt("refCellTryBorrowMut", args), - ("Ref" | "RwLockReadGuard" | "MappedRwLockReadGuard", "map") => Expr::rt("refMap", args), - ("Ref" | "RwLockReadGuard" | "MappedRwLockReadGuard", "filter_map") => Expr::rt("refFilterMap", args), - ("Ref", "map_split") => Expr::rt("refMapSplit", args), + ("Ref" | "RwLockReadGuard" | "MappedRwLockReadGuard", "map" | "filter_map" | "map_split") => { + guard_map(b, call, name, false, args, out) + } ("RefMut" | "RwLockWriteGuard" | "MappedRwLockWriteGuard", "map" | "filter_map" | "map_split") => { - ref_mut_map(b, call, name, args, out) + guard_map(b, call, name, true, args, out) } ("Ref", "clone") => Expr::rt("refClone", args), ("RefCell", "replace") => Expr::rt("refCellReplace", args), @@ -576,13 +576,14 @@ fn held(ty: Option>) -> Ty<'_> { } } -/// `map`, `filter_map`, or `map_split` of a `RefMut` or a write guard: its function called -/// on what the guard lends, and a guard of where each part that lends is, which a write -/// through it reaches. -fn ref_mut_map<'tcx>( +/// `map`, `filter_map`, or `map_split` of a guard, `exclusive` for a `RefMut` or a write +/// guard: its function called on what the guard lends, and a guard of each part that +/// lends, which for an exclusive one is where the part is, so a write through it reaches. +fn guard_map<'tcx>( b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, name: &str, + exclusive: bool, args: Vec, out: &mut Vec, ) -> Expr { @@ -595,15 +596,22 @@ fn ref_mut_map<'tcx>( // The guarded value, then each part's type. let mut tys = call.args.types(); let held = tys.next().expect("a guarded type"); - let lent = match b.t.needs_place(held) { + let lent = match exclusive && b.t.needs_place(held) { true => Expr::rt("valuePlace", vec![guard.clone()]), false => guard.clone().member("value"), }; let lent = f.call(vec![lent]); - // A `&mut` to a part JS copies is its place, and one to an object is that object, which - // a whole value is written into in place. + // What the guard holds of a part: a `[u8; N]` as the array its `rt.ByteSlice` views, and + // for an exclusive one, where the part is: the place of one JS copies, and an object + // itself, which a whole value is written into in place. + let converts = + |b: &Body<'_, '_, 'tcx>, part: Ty<'tcx>| super::byte_array(part) || exclusive && !b.t.needs_place(part); let at = |b: &mut Body<'_, '_, 'tcx>, part: Ty<'tcx>, value: Expr| { - if b.t.needs_place(part) { + let value = match super::byte_array(part) { + true => Expr::rt("byteSliceView", vec![value]), + false => value, + }; + if !converts(b, part) || !exclusive { value } else if b.t.write_in(part).is_none() && part.is_sized(tcx, b.t.typing_env_pub()) { b.err( @@ -615,12 +623,16 @@ fn ref_mut_map<'tcx>( } }; let part = tys.next().expect("a part's type"); + let f = |name: &str| match exclusive { + true => format!("refMut{name}"), + false => format!("ref{name}"), + }; match name { "map" => { let at = at(b, part, lent); - Expr::rt("refMutMap", vec![guard, at]) + Expr::rt(f("Map"), vec![guard, at]) } - "filter_map" if b.t.needs_place(part) => Expr::rt("refMutFilterMap", vec![guard, lent]), + "filter_map" if !converts(b, part) => Expr::rt(f("FilterMap"), vec![guard, lent]), "filter_map" => { let lent = b.spill(lent, "part", out); let some = at(b, part, lent.clone()); @@ -629,14 +641,17 @@ fn ref_mut_map<'tcx>( Box::new(Expr::undefined()), Box::new(some), ); - Expr::rt("refMutFilterMap", vec![guard, at]) + Expr::rt(f("FilterMap"), vec![guard, at]) } _ => { - let pair = b.spill(lent, "parts", out); let other = tys.next().expect("the other part's type"); + if !converts(b, part) && !converts(b, other) { + return Expr::rt(f("MapSplit"), vec![guard, lent]); + } + let pair = b.spill(lent, "parts", out); let a = at(b, part, pair.clone().index(Expr::lit("0"))); let other = at(b, other, pair.index(Expr::lit("1"))); - Expr::rt("refMutMapSplit", vec![guard, a, other]) + Expr::rt(f("MapSplit"), vec![guard, Expr::Array(vec![a, other])]) } } } From 2b4d8fac10e155f207b4a2eb63656eb28c26b931 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:48:14 -0800 Subject: [PATCH 4/4] chore(quest): plan the rest of a guard's methods and aborts in the differential Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 2 ++ quest/m3/ts-abort-differential.md | 14 ++++++++++++++ quest/m3/ts-guard-rest.md | 15 +++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 quest/m3/ts-abort-differential.md create mode 100644 quest/m3/ts-guard-rest.md diff --git a/quest/m3/README.md b/quest/m3/README.md index 425f9b824..0b838f067 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -32,4 +32,6 @@ generic std gap is planned here even when moq never calls it. - [std's sorts call their tests in std's order](/quest/m3/ts-sort-order.md) - `slice::sort` and a B-tree's `collect` call `lt` or `cmp` as std's driftsort does past 16 elements - [A B-tree's searches call Ord as std's do](/quest/m3/ts-btree-search-order.md) - a B-tree's lookups and inserts call a key's own `Ord` in std's order and number - [The rest of a boxed slice's impls](/quest/m3/ts-boxed-slice-rest.md) - `clone_from`, `AsRef`, `AsMut`, `TryFrom` into a boxed array, and `Box` into bytes translate for boxed slices +- [The rest of a guard's methods](/quest/m3/ts-guard-rest.md) - `Debug` of `RefCell` and `RwLock` guards, `MutexGuard::map`, and the guards' `try_map` translate +- [Aborts in the differential](/quest/m3/ts-abort-differential.md) - the lang differential compares wasm32's aborts, so an `RwLock` locked again while held is tested - [A reversed zip's per-pair cost](/quest/m3/ts-zip-rev-overhead.md) - a reversed by-index zip costs per pair what a forward one does, or the gap is explained diff --git a/quest/m3/ts-abort-differential.md b/quest/m3/ts-abort-differential.md new file mode 100644 index 000000000..6a8c7c0a2 --- /dev/null +++ b/quest/m3/ts-abort-differential.md @@ -0,0 +1,14 @@ +# [S] Aborts in the differential + +## Goal + +The lang differential compares a wasm32 abort with the translation's, so the runtime's +abort of an `RwLock` locked again while held, `rwlock locked for reading` or `for writing`, +is tested as `RefCell`'s panics are. Today wasm32's `rtabort!` traps with no panic +message, which no translation's `rt.Panic` matches, so the fixtures avoid it. + +## Plan + +Tell an abort from a panic on both sides: natively by the trap without a panic hook's +message, and in the runtime by a distinct error or message prefix such as std's +`fatal runtime error: ..., aborting`. Keep the comparison exact for panics. diff --git a/quest/m3/ts-guard-rest.md b/quest/m3/ts-guard-rest.md new file mode 100644 index 000000000..5bf292ed6 --- /dev/null +++ b/quest/m3/ts-guard-rest.md @@ -0,0 +1,15 @@ +# [S] The rest of a guard's methods + +## Goal + +[rust2-ts](/ts/README.md) translates what is still refused of std's guards: `Debug` of a +`Ref`, a `RefMut`, and an `RwLock`'s guards, mapped or not; `MutexGuard::map` and +`filter_map` and the `MappedMutexGuard` they make; and `Ref::try_map` and +`RefMut::try_map`. Each releases its lock or cell as std's does, proven by differential +tests against native Rust. + +## Plan + +The maps reuse what a `RefCell` guard's map makes: an `rt.RefMap` of where its part is, +so a write through a mapped exclusive guard reaches the value. A `MutexGuard` is its +mutex, so a mapped one needs the mutex to unlock beside the part it lends.